ctl.c revision 268690
1/*-
2 * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3 * Copyright (c) 2012 The FreeBSD Foundation
4 * All rights reserved.
5 *
6 * Portions of this software were developed by Edward Tomasz Napierala
7 * under sponsorship from the FreeBSD Foundation.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions, and the following disclaimer,
14 *    without modification.
15 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
16 *    substantially similar to the "NO WARRANTY" disclaimer below
17 *    ("Disclaimer") and any redistribution must be conditioned upon
18 *    including a substantially similar Disclaimer requirement for further
19 *    binary redistribution.
20 *
21 * NO WARRANTY
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
25 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
31 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGES.
33 *
34 * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/ctl.c#8 $
35 */
36/*
37 * CAM Target Layer, a SCSI device emulation subsystem.
38 *
39 * Author: Ken Merry <ken@FreeBSD.org>
40 */
41
42#define _CTL_C
43
44#include <sys/cdefs.h>
45__FBSDID("$FreeBSD: stable/10/sys/cam/ctl/ctl.c 268690 2014-07-15 17:12:37Z mav $");
46
47#include <sys/param.h>
48#include <sys/systm.h>
49#include <sys/kernel.h>
50#include <sys/types.h>
51#include <sys/kthread.h>
52#include <sys/bio.h>
53#include <sys/fcntl.h>
54#include <sys/lock.h>
55#include <sys/module.h>
56#include <sys/mutex.h>
57#include <sys/condvar.h>
58#include <sys/malloc.h>
59#include <sys/conf.h>
60#include <sys/ioccom.h>
61#include <sys/queue.h>
62#include <sys/sbuf.h>
63#include <sys/smp.h>
64#include <sys/endian.h>
65#include <sys/sysctl.h>
66
67#include <cam/cam.h>
68#include <cam/scsi/scsi_all.h>
69#include <cam/scsi/scsi_da.h>
70#include <cam/ctl/ctl_io.h>
71#include <cam/ctl/ctl.h>
72#include <cam/ctl/ctl_frontend.h>
73#include <cam/ctl/ctl_frontend_internal.h>
74#include <cam/ctl/ctl_util.h>
75#include <cam/ctl/ctl_backend.h>
76#include <cam/ctl/ctl_ioctl.h>
77#include <cam/ctl/ctl_ha.h>
78#include <cam/ctl/ctl_private.h>
79#include <cam/ctl/ctl_debug.h>
80#include <cam/ctl/ctl_scsi_all.h>
81#include <cam/ctl/ctl_error.h>
82
83struct ctl_softc *control_softc = NULL;
84
85/*
86 * Size and alignment macros needed for Copan-specific HA hardware.  These
87 * can go away when the HA code is re-written, and uses busdma for any
88 * hardware.
89 */
90#define	CTL_ALIGN_8B(target, source, type)				\
91	if (((uint32_t)source & 0x7) != 0)				\
92		target = (type)(source + (0x8 - ((uint32_t)source & 0x7)));\
93	else								\
94		target = (type)source;
95
96#define	CTL_SIZE_8B(target, size)					\
97	if ((size & 0x7) != 0)						\
98		target = size + (0x8 - (size & 0x7));			\
99	else								\
100		target = size;
101
102#define CTL_ALIGN_8B_MARGIN	16
103
104/*
105 * Template mode pages.
106 */
107
108/*
109 * Note that these are default values only.  The actual values will be
110 * filled in when the user does a mode sense.
111 */
112static struct copan_power_subpage power_page_default = {
113	/*page_code*/ PWR_PAGE_CODE | SMPH_SPF,
114	/*subpage*/ PWR_SUBPAGE_CODE,
115	/*page_length*/ {(sizeof(struct copan_power_subpage) - 4) & 0xff00,
116			 (sizeof(struct copan_power_subpage) - 4) & 0x00ff},
117	/*page_version*/ PWR_VERSION,
118	/* total_luns */ 26,
119	/* max_active_luns*/ PWR_DFLT_MAX_LUNS,
120	/*reserved*/ {0, 0, 0, 0, 0, 0, 0, 0, 0,
121		      0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
122		      0, 0, 0, 0, 0, 0}
123};
124
125static struct copan_power_subpage power_page_changeable = {
126	/*page_code*/ PWR_PAGE_CODE | SMPH_SPF,
127	/*subpage*/ PWR_SUBPAGE_CODE,
128	/*page_length*/ {(sizeof(struct copan_power_subpage) - 4) & 0xff00,
129			 (sizeof(struct copan_power_subpage) - 4) & 0x00ff},
130	/*page_version*/ 0,
131	/* total_luns */ 0,
132	/* max_active_luns*/ 0,
133	/*reserved*/ {0, 0, 0, 0, 0, 0, 0, 0, 0,
134		      0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
135		      0, 0, 0, 0, 0, 0}
136};
137
138static struct copan_aps_subpage aps_page_default = {
139	APS_PAGE_CODE | SMPH_SPF, //page_code
140	APS_SUBPAGE_CODE, //subpage
141	{(sizeof(struct copan_aps_subpage) - 4) & 0xff00,
142	 (sizeof(struct copan_aps_subpage) - 4) & 0x00ff}, //page_length
143	APS_VERSION, //page_version
144	0, //lock_active
145	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
146	0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
147	0, 0, 0, 0, 0} //reserved
148};
149
150static struct copan_aps_subpage aps_page_changeable = {
151	APS_PAGE_CODE | SMPH_SPF, //page_code
152	APS_SUBPAGE_CODE, //subpage
153	{(sizeof(struct copan_aps_subpage) - 4) & 0xff00,
154	 (sizeof(struct copan_aps_subpage) - 4) & 0x00ff}, //page_length
155	0, //page_version
156	0, //lock_active
157	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
158	0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
159	0, 0, 0, 0, 0} //reserved
160};
161
162static struct copan_debugconf_subpage debugconf_page_default = {
163	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
164	DBGCNF_SUBPAGE_CODE,		/* subpage */
165	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
166	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
167	DBGCNF_VERSION,			/* page_version */
168	{CTL_TIME_IO_DEFAULT_SECS>>8,
169	 CTL_TIME_IO_DEFAULT_SECS>>0},	/* ctl_time_io_secs */
170};
171
172static struct copan_debugconf_subpage debugconf_page_changeable = {
173	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
174	DBGCNF_SUBPAGE_CODE,		/* subpage */
175	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
176	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
177	0,				/* page_version */
178	{0xff,0xff},			/* ctl_time_io_secs */
179};
180
181static struct scsi_format_page format_page_default = {
182	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
183	/*page_length*/sizeof(struct scsi_format_page) - 2,
184	/*tracks_per_zone*/ {0, 0},
185	/*alt_sectors_per_zone*/ {0, 0},
186	/*alt_tracks_per_zone*/ {0, 0},
187	/*alt_tracks_per_lun*/ {0, 0},
188	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
189			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
190	/*bytes_per_sector*/ {0, 0},
191	/*interleave*/ {0, 0},
192	/*track_skew*/ {0, 0},
193	/*cylinder_skew*/ {0, 0},
194	/*flags*/ SFP_HSEC,
195	/*reserved*/ {0, 0, 0}
196};
197
198static struct scsi_format_page format_page_changeable = {
199	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
200	/*page_length*/sizeof(struct scsi_format_page) - 2,
201	/*tracks_per_zone*/ {0, 0},
202	/*alt_sectors_per_zone*/ {0, 0},
203	/*alt_tracks_per_zone*/ {0, 0},
204	/*alt_tracks_per_lun*/ {0, 0},
205	/*sectors_per_track*/ {0, 0},
206	/*bytes_per_sector*/ {0, 0},
207	/*interleave*/ {0, 0},
208	/*track_skew*/ {0, 0},
209	/*cylinder_skew*/ {0, 0},
210	/*flags*/ 0,
211	/*reserved*/ {0, 0, 0}
212};
213
214static struct scsi_rigid_disk_page rigid_disk_page_default = {
215	/*page_code*/SMS_RIGID_DISK_PAGE,
216	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
217	/*cylinders*/ {0, 0, 0},
218	/*heads*/ CTL_DEFAULT_HEADS,
219	/*start_write_precomp*/ {0, 0, 0},
220	/*start_reduced_current*/ {0, 0, 0},
221	/*step_rate*/ {0, 0},
222	/*landing_zone_cylinder*/ {0, 0, 0},
223	/*rpl*/ SRDP_RPL_DISABLED,
224	/*rotational_offset*/ 0,
225	/*reserved1*/ 0,
226	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
227			   CTL_DEFAULT_ROTATION_RATE & 0xff},
228	/*reserved2*/ {0, 0}
229};
230
231static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
232	/*page_code*/SMS_RIGID_DISK_PAGE,
233	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
234	/*cylinders*/ {0, 0, 0},
235	/*heads*/ 0,
236	/*start_write_precomp*/ {0, 0, 0},
237	/*start_reduced_current*/ {0, 0, 0},
238	/*step_rate*/ {0, 0},
239	/*landing_zone_cylinder*/ {0, 0, 0},
240	/*rpl*/ 0,
241	/*rotational_offset*/ 0,
242	/*reserved1*/ 0,
243	/*rotation_rate*/ {0, 0},
244	/*reserved2*/ {0, 0}
245};
246
247static struct scsi_caching_page caching_page_default = {
248	/*page_code*/SMS_CACHING_PAGE,
249	/*page_length*/sizeof(struct scsi_caching_page) - 2,
250	/*flags1*/ SCP_DISC | SCP_WCE,
251	/*ret_priority*/ 0,
252	/*disable_pf_transfer_len*/ {0xff, 0xff},
253	/*min_prefetch*/ {0, 0},
254	/*max_prefetch*/ {0xff, 0xff},
255	/*max_pf_ceiling*/ {0xff, 0xff},
256	/*flags2*/ 0,
257	/*cache_segments*/ 0,
258	/*cache_seg_size*/ {0, 0},
259	/*reserved*/ 0,
260	/*non_cache_seg_size*/ {0, 0, 0}
261};
262
263static struct scsi_caching_page caching_page_changeable = {
264	/*page_code*/SMS_CACHING_PAGE,
265	/*page_length*/sizeof(struct scsi_caching_page) - 2,
266	/*flags1*/ 0,
267	/*ret_priority*/ 0,
268	/*disable_pf_transfer_len*/ {0, 0},
269	/*min_prefetch*/ {0, 0},
270	/*max_prefetch*/ {0, 0},
271	/*max_pf_ceiling*/ {0, 0},
272	/*flags2*/ 0,
273	/*cache_segments*/ 0,
274	/*cache_seg_size*/ {0, 0},
275	/*reserved*/ 0,
276	/*non_cache_seg_size*/ {0, 0, 0}
277};
278
279static struct scsi_control_page control_page_default = {
280	/*page_code*/SMS_CONTROL_MODE_PAGE,
281	/*page_length*/sizeof(struct scsi_control_page) - 2,
282	/*rlec*/0,
283	/*queue_flags*/0,
284	/*eca_and_aen*/0,
285	/*reserved*/0,
286	/*aen_holdoff_period*/{0, 0}
287};
288
289static struct scsi_control_page control_page_changeable = {
290	/*page_code*/SMS_CONTROL_MODE_PAGE,
291	/*page_length*/sizeof(struct scsi_control_page) - 2,
292	/*rlec*/SCP_DSENSE,
293	/*queue_flags*/0,
294	/*eca_and_aen*/0,
295	/*reserved*/0,
296	/*aen_holdoff_period*/{0, 0}
297};
298
299
300/*
301 * XXX KDM move these into the softc.
302 */
303static int rcv_sync_msg;
304static int persis_offset;
305static uint8_t ctl_pause_rtr;
306static int     ctl_is_single = 1;
307static int     index_to_aps_page;
308
309SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
310static int worker_threads = -1;
311TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
312SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
313    &worker_threads, 1, "Number of worker threads");
314static int verbose = 0;
315TUNABLE_INT("kern.cam.ctl.verbose", &verbose);
316SYSCTL_INT(_kern_cam_ctl, OID_AUTO, verbose, CTLFLAG_RWTUN,
317    &verbose, 0, "Show SCSI errors returned to initiator");
318
319/*
320 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
321 * SCSI Ports (0x88), Block limits (0xB0) and
322 * Logical Block Provisioning (0xB2)
323 */
324#define SCSI_EVPD_NUM_SUPPORTED_PAGES	6
325
326static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
327				  int param);
328static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
329static int ctl_init(void);
330void ctl_shutdown(void);
331static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
332static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
333static void ctl_ioctl_online(void *arg);
334static void ctl_ioctl_offline(void *arg);
335static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
336static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
337static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
338static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
339static int ctl_ioctl_submit_wait(union ctl_io *io);
340static void ctl_ioctl_datamove(union ctl_io *io);
341static void ctl_ioctl_done(union ctl_io *io);
342static void ctl_ioctl_hard_startstop_callback(void *arg,
343					      struct cfi_metatask *metatask);
344static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
345static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
346			      struct ctl_ooa *ooa_hdr,
347			      struct ctl_ooa_entry *kern_entries);
348static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
349		     struct thread *td);
350uint32_t ctl_get_resindex(struct ctl_nexus *nexus);
351uint32_t ctl_port_idx(int port_num);
352static uint32_t ctl_map_lun(int port_num, uint32_t lun);
353static uint32_t ctl_map_lun_back(int port_num, uint32_t lun);
354#ifdef unused
355static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
356				   uint32_t targ_target, uint32_t targ_lun,
357				   int can_wait);
358static void ctl_kfree_io(union ctl_io *io);
359#endif /* unused */
360static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
361			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
362static int ctl_free_lun(struct ctl_lun *lun);
363static void ctl_create_lun(struct ctl_be_lun *be_lun);
364/**
365static void ctl_failover_change_pages(struct ctl_softc *softc,
366				      struct ctl_scsiio *ctsio, int master);
367**/
368
369static int ctl_do_mode_select(union ctl_io *io);
370static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
371			   uint64_t res_key, uint64_t sa_res_key,
372			   uint8_t type, uint32_t residx,
373			   struct ctl_scsiio *ctsio,
374			   struct scsi_per_res_out *cdb,
375			   struct scsi_per_res_out_parms* param);
376static void ctl_pro_preempt_other(struct ctl_lun *lun,
377				  union ctl_ha_msg *msg);
378static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
379static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
380static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
381static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
382static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
383					 int alloc_len);
384static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
385					 int alloc_len);
386static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
387static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
388static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
389static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len);
390static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
391static ctl_action ctl_check_for_blockage(union ctl_io *pending_io,
392					 union ctl_io *ooa_io);
393static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
394				union ctl_io *starting_io);
395static int ctl_check_blocked(struct ctl_lun *lun);
396static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
397				struct ctl_lun *lun,
398				const struct ctl_cmd_entry *entry,
399				struct ctl_scsiio *ctsio);
400//static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
401static void ctl_failover(void);
402static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
403			       struct ctl_scsiio *ctsio);
404static int ctl_scsiio(struct ctl_scsiio *ctsio);
405
406static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
407static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
408			    ctl_ua_type ua_type);
409static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
410			 ctl_ua_type ua_type);
411static int ctl_abort_task(union ctl_io *io);
412static int ctl_abort_task_set(union ctl_io *io);
413static int ctl_i_t_nexus_reset(union ctl_io *io);
414static void ctl_run_task(union ctl_io *io);
415#ifdef CTL_IO_DELAY
416static void ctl_datamove_timer_wakeup(void *arg);
417static void ctl_done_timer_wakeup(void *arg);
418#endif /* CTL_IO_DELAY */
419
420static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
421static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
422static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
423static void ctl_datamove_remote_write(union ctl_io *io);
424static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
425static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
426static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
427static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
428				    ctl_ha_dt_cb callback);
429static void ctl_datamove_remote_read(union ctl_io *io);
430static void ctl_datamove_remote(union ctl_io *io);
431static int ctl_process_done(union ctl_io *io);
432static void ctl_lun_thread(void *arg);
433static void ctl_work_thread(void *arg);
434static void ctl_enqueue_incoming(union ctl_io *io);
435static void ctl_enqueue_rtr(union ctl_io *io);
436static void ctl_enqueue_done(union ctl_io *io);
437static void ctl_enqueue_isc(union ctl_io *io);
438static const struct ctl_cmd_entry *
439    ctl_get_cmd_entry(struct ctl_scsiio *ctsio);
440static const struct ctl_cmd_entry *
441    ctl_validate_command(struct ctl_scsiio *ctsio);
442static int ctl_cmd_applicable(uint8_t lun_type,
443    const struct ctl_cmd_entry *entry);
444
445/*
446 * Load the serialization table.  This isn't very pretty, but is probably
447 * the easiest way to do it.
448 */
449#include "ctl_ser_table.c"
450
451/*
452 * We only need to define open, close and ioctl routines for this driver.
453 */
454static struct cdevsw ctl_cdevsw = {
455	.d_version =	D_VERSION,
456	.d_flags =	0,
457	.d_open =	ctl_open,
458	.d_close =	ctl_close,
459	.d_ioctl =	ctl_ioctl,
460	.d_name =	"ctl",
461};
462
463
464MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
465MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
466
467static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
468
469static moduledata_t ctl_moduledata = {
470	"ctl",
471	ctl_module_event_handler,
472	NULL
473};
474
475DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
476MODULE_VERSION(ctl, 1);
477
478static struct ctl_frontend ioctl_frontend =
479{
480	.name = "ioctl",
481};
482
483static void
484ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
485			    union ctl_ha_msg *msg_info)
486{
487	struct ctl_scsiio *ctsio;
488
489	if (msg_info->hdr.original_sc == NULL) {
490		printf("%s: original_sc == NULL!\n", __func__);
491		/* XXX KDM now what? */
492		return;
493	}
494
495	ctsio = &msg_info->hdr.original_sc->scsiio;
496	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
497	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
498	ctsio->io_hdr.status = msg_info->hdr.status;
499	ctsio->scsi_status = msg_info->scsi.scsi_status;
500	ctsio->sense_len = msg_info->scsi.sense_len;
501	ctsio->sense_residual = msg_info->scsi.sense_residual;
502	ctsio->residual = msg_info->scsi.residual;
503	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
504	       sizeof(ctsio->sense_data));
505	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
506	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
507	ctl_enqueue_isc((union ctl_io *)ctsio);
508}
509
510static void
511ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
512				union ctl_ha_msg *msg_info)
513{
514	struct ctl_scsiio *ctsio;
515
516	if (msg_info->hdr.serializing_sc == NULL) {
517		printf("%s: serializing_sc == NULL!\n", __func__);
518		/* XXX KDM now what? */
519		return;
520	}
521
522	ctsio = &msg_info->hdr.serializing_sc->scsiio;
523#if 0
524	/*
525	 * Attempt to catch the situation where an I/O has
526	 * been freed, and we're using it again.
527	 */
528	if (ctsio->io_hdr.io_type == 0xff) {
529		union ctl_io *tmp_io;
530		tmp_io = (union ctl_io *)ctsio;
531		printf("%s: %p use after free!\n", __func__,
532		       ctsio);
533		printf("%s: type %d msg %d cdb %x iptl: "
534		       "%d:%d:%d:%d tag 0x%04x "
535		       "flag %#x status %x\n",
536			__func__,
537			tmp_io->io_hdr.io_type,
538			tmp_io->io_hdr.msg_type,
539			tmp_io->scsiio.cdb[0],
540			tmp_io->io_hdr.nexus.initid.id,
541			tmp_io->io_hdr.nexus.targ_port,
542			tmp_io->io_hdr.nexus.targ_target.id,
543			tmp_io->io_hdr.nexus.targ_lun,
544			(tmp_io->io_hdr.io_type ==
545			CTL_IO_TASK) ?
546			tmp_io->taskio.tag_num :
547			tmp_io->scsiio.tag_num,
548		        tmp_io->io_hdr.flags,
549			tmp_io->io_hdr.status);
550	}
551#endif
552	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
553	ctl_enqueue_isc((union ctl_io *)ctsio);
554}
555
556/*
557 * ISC (Inter Shelf Communication) event handler.  Events from the HA
558 * subsystem come in here.
559 */
560static void
561ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
562{
563	struct ctl_softc *ctl_softc;
564	union ctl_io *io;
565	struct ctl_prio *presio;
566	ctl_ha_status isc_status;
567
568	ctl_softc = control_softc;
569	io = NULL;
570
571
572#if 0
573	printf("CTL: Isc Msg event %d\n", event);
574#endif
575	if (event == CTL_HA_EVT_MSG_RECV) {
576		union ctl_ha_msg msg_info;
577
578		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
579					     sizeof(msg_info), /*wait*/ 0);
580#if 0
581		printf("CTL: msg_type %d\n", msg_info.msg_type);
582#endif
583		if (isc_status != 0) {
584			printf("Error receiving message, status = %d\n",
585			       isc_status);
586			return;
587		}
588
589		switch (msg_info.hdr.msg_type) {
590		case CTL_MSG_SERIALIZE:
591#if 0
592			printf("Serialize\n");
593#endif
594			io = ctl_alloc_io((void *)ctl_softc->othersc_pool);
595			if (io == NULL) {
596				printf("ctl_isc_event_handler: can't allocate "
597				       "ctl_io!\n");
598				/* Bad Juju */
599				/* Need to set busy and send msg back */
600				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
601				msg_info.hdr.status = CTL_SCSI_ERROR;
602				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
603				msg_info.scsi.sense_len = 0;
604			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
605				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
606				}
607				goto bailout;
608			}
609			ctl_zero_io(io);
610			// populate ctsio from msg_info
611			io->io_hdr.io_type = CTL_IO_SCSI;
612			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
613			io->io_hdr.original_sc = msg_info.hdr.original_sc;
614#if 0
615			printf("pOrig %x\n", (int)msg_info.original_sc);
616#endif
617			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
618					    CTL_FLAG_IO_ACTIVE;
619			/*
620			 * If we're in serialization-only mode, we don't
621			 * want to go through full done processing.  Thus
622			 * the COPY flag.
623			 *
624			 * XXX KDM add another flag that is more specific.
625			 */
626			if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
627				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
628			io->io_hdr.nexus = msg_info.hdr.nexus;
629#if 0
630			printf("targ %d, port %d, iid %d, lun %d\n",
631			       io->io_hdr.nexus.targ_target.id,
632			       io->io_hdr.nexus.targ_port,
633			       io->io_hdr.nexus.initid.id,
634			       io->io_hdr.nexus.targ_lun);
635#endif
636			io->scsiio.tag_num = msg_info.scsi.tag_num;
637			io->scsiio.tag_type = msg_info.scsi.tag_type;
638			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
639			       CTL_MAX_CDBLEN);
640			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
641				const struct ctl_cmd_entry *entry;
642
643				entry = ctl_get_cmd_entry(&io->scsiio);
644				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
645				io->io_hdr.flags |=
646					entry->flags & CTL_FLAG_DATA_MASK;
647			}
648			ctl_enqueue_isc(io);
649			break;
650
651		/* Performed on the Originating SC, XFER mode only */
652		case CTL_MSG_DATAMOVE: {
653			struct ctl_sg_entry *sgl;
654			int i, j;
655
656			io = msg_info.hdr.original_sc;
657			if (io == NULL) {
658				printf("%s: original_sc == NULL!\n", __func__);
659				/* XXX KDM do something here */
660				break;
661			}
662			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
663			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
664			/*
665			 * Keep track of this, we need to send it back over
666			 * when the datamove is complete.
667			 */
668			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
669
670			if (msg_info.dt.sg_sequence == 0) {
671				/*
672				 * XXX KDM we use the preallocated S/G list
673				 * here, but we'll need to change this to
674				 * dynamic allocation if we need larger S/G
675				 * lists.
676				 */
677				if (msg_info.dt.kern_sg_entries >
678				    sizeof(io->io_hdr.remote_sglist) /
679				    sizeof(io->io_hdr.remote_sglist[0])) {
680					printf("%s: number of S/G entries "
681					    "needed %u > allocated num %zd\n",
682					    __func__,
683					    msg_info.dt.kern_sg_entries,
684					    sizeof(io->io_hdr.remote_sglist)/
685					    sizeof(io->io_hdr.remote_sglist[0]));
686
687					/*
688					 * XXX KDM send a message back to
689					 * the other side to shut down the
690					 * DMA.  The error will come back
691					 * through via the normal channel.
692					 */
693					break;
694				}
695				sgl = io->io_hdr.remote_sglist;
696				memset(sgl, 0,
697				       sizeof(io->io_hdr.remote_sglist));
698
699				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
700
701				io->scsiio.kern_sg_entries =
702					msg_info.dt.kern_sg_entries;
703				io->scsiio.rem_sg_entries =
704					msg_info.dt.kern_sg_entries;
705				io->scsiio.kern_data_len =
706					msg_info.dt.kern_data_len;
707				io->scsiio.kern_total_len =
708					msg_info.dt.kern_total_len;
709				io->scsiio.kern_data_resid =
710					msg_info.dt.kern_data_resid;
711				io->scsiio.kern_rel_offset =
712					msg_info.dt.kern_rel_offset;
713				/*
714				 * Clear out per-DMA flags.
715				 */
716				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
717				/*
718				 * Add per-DMA flags that are set for this
719				 * particular DMA request.
720				 */
721				io->io_hdr.flags |= msg_info.dt.flags &
722						    CTL_FLAG_RDMA_MASK;
723			} else
724				sgl = (struct ctl_sg_entry *)
725					io->scsiio.kern_data_ptr;
726
727			for (i = msg_info.dt.sent_sg_entries, j = 0;
728			     i < (msg_info.dt.sent_sg_entries +
729			     msg_info.dt.cur_sg_entries); i++, j++) {
730				sgl[i].addr = msg_info.dt.sg_list[j].addr;
731				sgl[i].len = msg_info.dt.sg_list[j].len;
732
733#if 0
734				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
735				       __func__,
736				       msg_info.dt.sg_list[j].addr,
737				       msg_info.dt.sg_list[j].len,
738				       sgl[i].addr, sgl[i].len, j, i);
739#endif
740			}
741#if 0
742			memcpy(&sgl[msg_info.dt.sent_sg_entries],
743			       msg_info.dt.sg_list,
744			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
745#endif
746
747			/*
748			 * If this is the last piece of the I/O, we've got
749			 * the full S/G list.  Queue processing in the thread.
750			 * Otherwise wait for the next piece.
751			 */
752			if (msg_info.dt.sg_last != 0)
753				ctl_enqueue_isc(io);
754			break;
755		}
756		/* Performed on the Serializing (primary) SC, XFER mode only */
757		case CTL_MSG_DATAMOVE_DONE: {
758			if (msg_info.hdr.serializing_sc == NULL) {
759				printf("%s: serializing_sc == NULL!\n",
760				       __func__);
761				/* XXX KDM now what? */
762				break;
763			}
764			/*
765			 * We grab the sense information here in case
766			 * there was a failure, so we can return status
767			 * back to the initiator.
768			 */
769			io = msg_info.hdr.serializing_sc;
770			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
771			io->io_hdr.status = msg_info.hdr.status;
772			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
773			io->scsiio.sense_len = msg_info.scsi.sense_len;
774			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
775			io->io_hdr.port_status = msg_info.scsi.fetd_status;
776			io->scsiio.residual = msg_info.scsi.residual;
777			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
778			       sizeof(io->scsiio.sense_data));
779			ctl_enqueue_isc(io);
780			break;
781		}
782
783		/* Preformed on Originating SC, SER_ONLY mode */
784		case CTL_MSG_R2R:
785			io = msg_info.hdr.original_sc;
786			if (io == NULL) {
787				printf("%s: Major Bummer\n", __func__);
788				return;
789			} else {
790#if 0
791				printf("pOrig %x\n",(int) ctsio);
792#endif
793			}
794			io->io_hdr.msg_type = CTL_MSG_R2R;
795			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
796			ctl_enqueue_isc(io);
797			break;
798
799		/*
800		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
801		 * mode.
802		 * Performed on the Originating (i.e. secondary) SC in XFER
803		 * mode
804		 */
805		case CTL_MSG_FINISH_IO:
806			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
807				ctl_isc_handler_finish_xfer(ctl_softc,
808							    &msg_info);
809			else
810				ctl_isc_handler_finish_ser_only(ctl_softc,
811								&msg_info);
812			break;
813
814		/* Preformed on Originating SC */
815		case CTL_MSG_BAD_JUJU:
816			io = msg_info.hdr.original_sc;
817			if (io == NULL) {
818				printf("%s: Bad JUJU!, original_sc is NULL!\n",
819				       __func__);
820				break;
821			}
822			ctl_copy_sense_data(&msg_info, io);
823			/*
824			 * IO should have already been cleaned up on other
825			 * SC so clear this flag so we won't send a message
826			 * back to finish the IO there.
827			 */
828			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
829			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
830
831			/* io = msg_info.hdr.serializing_sc; */
832			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
833			ctl_enqueue_isc(io);
834			break;
835
836		/* Handle resets sent from the other side */
837		case CTL_MSG_MANAGE_TASKS: {
838			struct ctl_taskio *taskio;
839			taskio = (struct ctl_taskio *)ctl_alloc_io(
840				(void *)ctl_softc->othersc_pool);
841			if (taskio == NULL) {
842				printf("ctl_isc_event_handler: can't allocate "
843				       "ctl_io!\n");
844				/* Bad Juju */
845				/* should I just call the proper reset func
846				   here??? */
847				goto bailout;
848			}
849			ctl_zero_io((union ctl_io *)taskio);
850			taskio->io_hdr.io_type = CTL_IO_TASK;
851			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
852			taskio->io_hdr.nexus = msg_info.hdr.nexus;
853			taskio->task_action = msg_info.task.task_action;
854			taskio->tag_num = msg_info.task.tag_num;
855			taskio->tag_type = msg_info.task.tag_type;
856#ifdef CTL_TIME_IO
857			taskio->io_hdr.start_time = time_uptime;
858			getbintime(&taskio->io_hdr.start_bt);
859#if 0
860			cs_prof_gettime(&taskio->io_hdr.start_ticks);
861#endif
862#endif /* CTL_TIME_IO */
863			ctl_run_task((union ctl_io *)taskio);
864			break;
865		}
866		/* Persistent Reserve action which needs attention */
867		case CTL_MSG_PERS_ACTION:
868			presio = (struct ctl_prio *)ctl_alloc_io(
869				(void *)ctl_softc->othersc_pool);
870			if (presio == NULL) {
871				printf("ctl_isc_event_handler: can't allocate "
872				       "ctl_io!\n");
873				/* Bad Juju */
874				/* Need to set busy and send msg back */
875				goto bailout;
876			}
877			ctl_zero_io((union ctl_io *)presio);
878			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
879			presio->pr_msg = msg_info.pr;
880			ctl_enqueue_isc((union ctl_io *)presio);
881			break;
882		case CTL_MSG_SYNC_FE:
883			rcv_sync_msg = 1;
884			break;
885		case CTL_MSG_APS_LOCK: {
886			// It's quicker to execute this then to
887			// queue it.
888			struct ctl_lun *lun;
889			struct ctl_page_index *page_index;
890			struct copan_aps_subpage *current_sp;
891			uint32_t targ_lun;
892
893			targ_lun = msg_info.hdr.nexus.targ_mapped_lun;
894			lun = ctl_softc->ctl_luns[targ_lun];
895			mtx_lock(&lun->lun_lock);
896			page_index = &lun->mode_pages.index[index_to_aps_page];
897			current_sp = (struct copan_aps_subpage *)
898				     (page_index->page_data +
899				     (page_index->page_len * CTL_PAGE_CURRENT));
900
901			current_sp->lock_active = msg_info.aps.lock_flag;
902			mtx_unlock(&lun->lun_lock);
903		        break;
904		}
905		default:
906		        printf("How did I get here?\n");
907		}
908	} else if (event == CTL_HA_EVT_MSG_SENT) {
909		if (param != CTL_HA_STATUS_SUCCESS) {
910			printf("Bad status from ctl_ha_msg_send status %d\n",
911			       param);
912		}
913		return;
914	} else if (event == CTL_HA_EVT_DISCONNECT) {
915		printf("CTL: Got a disconnect from Isc\n");
916		return;
917	} else {
918		printf("ctl_isc_event_handler: Unknown event %d\n", event);
919		return;
920	}
921
922bailout:
923	return;
924}
925
926static void
927ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
928{
929	struct scsi_sense_data *sense;
930
931	sense = &dest->scsiio.sense_data;
932	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
933	dest->scsiio.scsi_status = src->scsi.scsi_status;
934	dest->scsiio.sense_len = src->scsi.sense_len;
935	dest->io_hdr.status = src->hdr.status;
936}
937
938static int
939ctl_init(void)
940{
941	struct ctl_softc *softc;
942	struct ctl_io_pool *internal_pool, *emergency_pool, *other_pool;
943	struct ctl_port *port;
944        uint8_t sc_id =0;
945	int i, error, retval;
946	//int isc_retval;
947
948	retval = 0;
949	ctl_pause_rtr = 0;
950        rcv_sync_msg = 0;
951
952	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
953			       M_WAITOK | M_ZERO);
954	softc = control_softc;
955
956	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
957			      "cam/ctl");
958
959	softc->dev->si_drv1 = softc;
960
961	/*
962	 * By default, return a "bad LUN" peripheral qualifier for unknown
963	 * LUNs.  The user can override this default using the tunable or
964	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
965	 */
966	softc->inquiry_pq_no_lun = 1;
967	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
968			  &softc->inquiry_pq_no_lun);
969	sysctl_ctx_init(&softc->sysctl_ctx);
970	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
971		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
972		CTLFLAG_RD, 0, "CAM Target Layer");
973
974	if (softc->sysctl_tree == NULL) {
975		printf("%s: unable to allocate sysctl tree\n", __func__);
976		destroy_dev(softc->dev);
977		free(control_softc, M_DEVBUF);
978		control_softc = NULL;
979		return (ENOMEM);
980	}
981
982	SYSCTL_ADD_INT(&softc->sysctl_ctx,
983		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
984		       "inquiry_pq_no_lun", CTLFLAG_RW,
985		       &softc->inquiry_pq_no_lun, 0,
986		       "Report no lun possible for invalid LUNs");
987
988	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
989	mtx_init(&softc->pool_lock, "CTL pool mutex", NULL, MTX_DEF);
990	softc->open_count = 0;
991
992	/*
993	 * Default to actually sending a SYNCHRONIZE CACHE command down to
994	 * the drive.
995	 */
996	softc->flags = CTL_FLAG_REAL_SYNC;
997
998	/*
999	 * In Copan's HA scheme, the "master" and "slave" roles are
1000	 * figured out through the slot the controller is in.  Although it
1001	 * is an active/active system, someone has to be in charge.
1002 	 */
1003#ifdef NEEDTOPORT
1004        scmicro_rw(SCMICRO_GET_SHELF_ID, &sc_id);
1005#endif
1006
1007        if (sc_id == 0) {
1008		softc->flags |= CTL_FLAG_MASTER_SHELF;
1009		persis_offset = 0;
1010	} else
1011		persis_offset = CTL_MAX_INITIATORS;
1012
1013	/*
1014	 * XXX KDM need to figure out where we want to get our target ID
1015	 * and WWID.  Is it different on each port?
1016	 */
1017	softc->target.id = 0;
1018	softc->target.wwid[0] = 0x12345678;
1019	softc->target.wwid[1] = 0x87654321;
1020	STAILQ_INIT(&softc->lun_list);
1021	STAILQ_INIT(&softc->pending_lun_queue);
1022	STAILQ_INIT(&softc->fe_list);
1023	STAILQ_INIT(&softc->port_list);
1024	STAILQ_INIT(&softc->be_list);
1025	STAILQ_INIT(&softc->io_pools);
1026
1027	if (ctl_pool_create(softc, CTL_POOL_INTERNAL, CTL_POOL_ENTRIES_INTERNAL,
1028			    &internal_pool)!= 0){
1029		printf("ctl: can't allocate %d entry internal pool, "
1030		       "exiting\n", CTL_POOL_ENTRIES_INTERNAL);
1031		return (ENOMEM);
1032	}
1033
1034	if (ctl_pool_create(softc, CTL_POOL_EMERGENCY,
1035			    CTL_POOL_ENTRIES_EMERGENCY, &emergency_pool) != 0) {
1036		printf("ctl: can't allocate %d entry emergency pool, "
1037		       "exiting\n", CTL_POOL_ENTRIES_EMERGENCY);
1038		ctl_pool_free(internal_pool);
1039		return (ENOMEM);
1040	}
1041
1042	if (ctl_pool_create(softc, CTL_POOL_4OTHERSC, CTL_POOL_ENTRIES_OTHER_SC,
1043	                    &other_pool) != 0)
1044	{
1045		printf("ctl: can't allocate %d entry other SC pool, "
1046		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1047		ctl_pool_free(internal_pool);
1048		ctl_pool_free(emergency_pool);
1049		return (ENOMEM);
1050	}
1051
1052	softc->internal_pool = internal_pool;
1053	softc->emergency_pool = emergency_pool;
1054	softc->othersc_pool = other_pool;
1055
1056	if (worker_threads <= 0)
1057		worker_threads = max(1, mp_ncpus / 4);
1058	if (worker_threads > CTL_MAX_THREADS)
1059		worker_threads = CTL_MAX_THREADS;
1060
1061	for (i = 0; i < worker_threads; i++) {
1062		struct ctl_thread *thr = &softc->threads[i];
1063
1064		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1065		thr->ctl_softc = softc;
1066		STAILQ_INIT(&thr->incoming_queue);
1067		STAILQ_INIT(&thr->rtr_queue);
1068		STAILQ_INIT(&thr->done_queue);
1069		STAILQ_INIT(&thr->isc_queue);
1070
1071		error = kproc_kthread_add(ctl_work_thread, thr,
1072		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1073		if (error != 0) {
1074			printf("error creating CTL work thread!\n");
1075			ctl_pool_free(internal_pool);
1076			ctl_pool_free(emergency_pool);
1077			ctl_pool_free(other_pool);
1078			return (error);
1079		}
1080	}
1081	error = kproc_kthread_add(ctl_lun_thread, softc,
1082	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1083	if (error != 0) {
1084		printf("error creating CTL lun thread!\n");
1085		ctl_pool_free(internal_pool);
1086		ctl_pool_free(emergency_pool);
1087		ctl_pool_free(other_pool);
1088		return (error);
1089	}
1090	if (bootverbose)
1091		printf("ctl: CAM Target Layer loaded\n");
1092
1093	/*
1094	 * Initialize the initiator and portname mappings
1095	 */
1096	memset(softc->wwpn_iid, 0, sizeof(softc->wwpn_iid));
1097
1098	/*
1099	 * Initialize the ioctl front end.
1100	 */
1101	ctl_frontend_register(&ioctl_frontend);
1102	port = &softc->ioctl_info.port;
1103	port->frontend = &ioctl_frontend;
1104	sprintf(softc->ioctl_info.port_name, "ioctl");
1105	port->port_type = CTL_PORT_IOCTL;
1106	port->num_requested_ctl_io = 100;
1107	port->port_name = softc->ioctl_info.port_name;
1108	port->port_online = ctl_ioctl_online;
1109	port->port_offline = ctl_ioctl_offline;
1110	port->onoff_arg = &softc->ioctl_info;
1111	port->lun_enable = ctl_ioctl_lun_enable;
1112	port->lun_disable = ctl_ioctl_lun_disable;
1113	port->targ_lun_arg = &softc->ioctl_info;
1114	port->fe_datamove = ctl_ioctl_datamove;
1115	port->fe_done = ctl_ioctl_done;
1116	port->max_targets = 15;
1117	port->max_target_id = 15;
1118
1119	if (ctl_port_register(&softc->ioctl_info.port,
1120	                  (softc->flags & CTL_FLAG_MASTER_SHELF)) != 0) {
1121		printf("ctl: ioctl front end registration failed, will "
1122		       "continue anyway\n");
1123	}
1124
1125#ifdef CTL_IO_DELAY
1126	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1127		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1128		       sizeof(struct callout), CTL_TIMER_BYTES);
1129		return (EINVAL);
1130	}
1131#endif /* CTL_IO_DELAY */
1132
1133	return (0);
1134}
1135
1136void
1137ctl_shutdown(void)
1138{
1139	struct ctl_softc *softc;
1140	struct ctl_lun *lun, *next_lun;
1141	struct ctl_io_pool *pool;
1142
1143	softc = (struct ctl_softc *)control_softc;
1144
1145	if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1146		printf("ctl: ioctl front end deregistration failed\n");
1147
1148	mtx_lock(&softc->ctl_lock);
1149
1150	/*
1151	 * Free up each LUN.
1152	 */
1153	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1154		next_lun = STAILQ_NEXT(lun, links);
1155		ctl_free_lun(lun);
1156	}
1157
1158	mtx_unlock(&softc->ctl_lock);
1159
1160	ctl_frontend_deregister(&ioctl_frontend);
1161
1162	/*
1163	 * This will rip the rug out from under any FETDs or anyone else
1164	 * that has a pool allocated.  Since we increment our module
1165	 * refcount any time someone outside the main CTL module allocates
1166	 * a pool, we shouldn't have any problems here.  The user won't be
1167	 * able to unload the CTL module until client modules have
1168	 * successfully unloaded.
1169	 */
1170	while ((pool = STAILQ_FIRST(&softc->io_pools)) != NULL)
1171		ctl_pool_free(pool);
1172
1173#if 0
1174	ctl_shutdown_thread(softc->work_thread);
1175	mtx_destroy(&softc->queue_lock);
1176#endif
1177
1178	mtx_destroy(&softc->pool_lock);
1179	mtx_destroy(&softc->ctl_lock);
1180
1181	destroy_dev(softc->dev);
1182
1183	sysctl_ctx_free(&softc->sysctl_ctx);
1184
1185	free(control_softc, M_DEVBUF);
1186	control_softc = NULL;
1187
1188	if (bootverbose)
1189		printf("ctl: CAM Target Layer unloaded\n");
1190}
1191
1192static int
1193ctl_module_event_handler(module_t mod, int what, void *arg)
1194{
1195
1196	switch (what) {
1197	case MOD_LOAD:
1198		return (ctl_init());
1199	case MOD_UNLOAD:
1200		return (EBUSY);
1201	default:
1202		return (EOPNOTSUPP);
1203	}
1204}
1205
1206/*
1207 * XXX KDM should we do some access checks here?  Bump a reference count to
1208 * prevent a CTL module from being unloaded while someone has it open?
1209 */
1210static int
1211ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1212{
1213	return (0);
1214}
1215
1216static int
1217ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1218{
1219	return (0);
1220}
1221
1222int
1223ctl_port_enable(ctl_port_type port_type)
1224{
1225	struct ctl_softc *softc;
1226	struct ctl_port *port;
1227
1228	if (ctl_is_single == 0) {
1229		union ctl_ha_msg msg_info;
1230		int isc_retval;
1231
1232#if 0
1233		printf("%s: HA mode, synchronizing frontend enable\n",
1234		        __func__);
1235#endif
1236		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1237	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1238		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1239			printf("Sync msg send error retval %d\n", isc_retval);
1240		}
1241		if (!rcv_sync_msg) {
1242			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1243			        sizeof(msg_info), 1);
1244		}
1245#if 0
1246        	printf("CTL:Frontend Enable\n");
1247	} else {
1248		printf("%s: single mode, skipping frontend synchronization\n",
1249		        __func__);
1250#endif
1251	}
1252
1253	softc = control_softc;
1254
1255	STAILQ_FOREACH(port, &softc->port_list, links) {
1256		if (port_type & port->port_type)
1257		{
1258#if 0
1259			printf("port %d\n", port->targ_port);
1260#endif
1261			ctl_port_online(port);
1262		}
1263	}
1264
1265	return (0);
1266}
1267
1268int
1269ctl_port_disable(ctl_port_type port_type)
1270{
1271	struct ctl_softc *softc;
1272	struct ctl_port *port;
1273
1274	softc = control_softc;
1275
1276	STAILQ_FOREACH(port, &softc->port_list, links) {
1277		if (port_type & port->port_type)
1278			ctl_port_offline(port);
1279	}
1280
1281	return (0);
1282}
1283
1284/*
1285 * Returns 0 for success, 1 for failure.
1286 * Currently the only failure mode is if there aren't enough entries
1287 * allocated.  So, in case of a failure, look at num_entries_dropped,
1288 * reallocate and try again.
1289 */
1290int
1291ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1292	      int *num_entries_filled, int *num_entries_dropped,
1293	      ctl_port_type port_type, int no_virtual)
1294{
1295	struct ctl_softc *softc;
1296	struct ctl_port *port;
1297	int entries_dropped, entries_filled;
1298	int retval;
1299	int i;
1300
1301	softc = control_softc;
1302
1303	retval = 0;
1304	entries_filled = 0;
1305	entries_dropped = 0;
1306
1307	i = 0;
1308	mtx_lock(&softc->ctl_lock);
1309	STAILQ_FOREACH(port, &softc->port_list, links) {
1310		struct ctl_port_entry *entry;
1311
1312		if ((port->port_type & port_type) == 0)
1313			continue;
1314
1315		if ((no_virtual != 0)
1316		 && (port->virtual_port != 0))
1317			continue;
1318
1319		if (entries_filled >= num_entries_alloced) {
1320			entries_dropped++;
1321			continue;
1322		}
1323		entry = &entries[i];
1324
1325		entry->port_type = port->port_type;
1326		strlcpy(entry->port_name, port->port_name,
1327			sizeof(entry->port_name));
1328		entry->physical_port = port->physical_port;
1329		entry->virtual_port = port->virtual_port;
1330		entry->wwnn = port->wwnn;
1331		entry->wwpn = port->wwpn;
1332
1333		i++;
1334		entries_filled++;
1335	}
1336
1337	mtx_unlock(&softc->ctl_lock);
1338
1339	if (entries_dropped > 0)
1340		retval = 1;
1341
1342	*num_entries_dropped = entries_dropped;
1343	*num_entries_filled = entries_filled;
1344
1345	return (retval);
1346}
1347
1348static void
1349ctl_ioctl_online(void *arg)
1350{
1351	struct ctl_ioctl_info *ioctl_info;
1352
1353	ioctl_info = (struct ctl_ioctl_info *)arg;
1354
1355	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1356}
1357
1358static void
1359ctl_ioctl_offline(void *arg)
1360{
1361	struct ctl_ioctl_info *ioctl_info;
1362
1363	ioctl_info = (struct ctl_ioctl_info *)arg;
1364
1365	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1366}
1367
1368/*
1369 * Remove an initiator by port number and initiator ID.
1370 * Returns 0 for success, 1 for failure.
1371 */
1372int
1373ctl_remove_initiator(int32_t targ_port, uint32_t iid)
1374{
1375	struct ctl_softc *softc;
1376
1377	softc = control_softc;
1378
1379	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1380
1381	if ((targ_port < 0)
1382	 || (targ_port > CTL_MAX_PORTS)) {
1383		printf("%s: invalid port number %d\n", __func__, targ_port);
1384		return (1);
1385	}
1386	if (iid > CTL_MAX_INIT_PER_PORT) {
1387		printf("%s: initiator ID %u > maximun %u!\n",
1388		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1389		return (1);
1390	}
1391
1392	mtx_lock(&softc->ctl_lock);
1393
1394	softc->wwpn_iid[targ_port][iid].in_use = 0;
1395
1396	mtx_unlock(&softc->ctl_lock);
1397
1398	return (0);
1399}
1400
1401/*
1402 * Add an initiator to the initiator map.
1403 * Returns 0 for success, 1 for failure.
1404 */
1405int
1406ctl_add_initiator(uint64_t wwpn, int32_t targ_port, uint32_t iid)
1407{
1408	struct ctl_softc *softc;
1409	int retval;
1410
1411	softc = control_softc;
1412
1413	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1414
1415	retval = 0;
1416
1417	if ((targ_port < 0)
1418	 || (targ_port > CTL_MAX_PORTS)) {
1419		printf("%s: invalid port number %d\n", __func__, targ_port);
1420		return (1);
1421	}
1422	if (iid > CTL_MAX_INIT_PER_PORT) {
1423		printf("%s: WWPN %#jx initiator ID %u > maximun %u!\n",
1424		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1425		return (1);
1426	}
1427
1428	mtx_lock(&softc->ctl_lock);
1429
1430	if (softc->wwpn_iid[targ_port][iid].in_use != 0) {
1431		/*
1432		 * We don't treat this as an error.
1433		 */
1434		if (softc->wwpn_iid[targ_port][iid].wwpn == wwpn) {
1435			printf("%s: port %d iid %u WWPN %#jx arrived again?\n",
1436			       __func__, targ_port, iid, (uintmax_t)wwpn);
1437			goto bailout;
1438		}
1439
1440		/*
1441		 * This is an error, but what do we do about it?  The
1442		 * driver is telling us we have a new WWPN for this
1443		 * initiator ID, so we pretty much need to use it.
1444		 */
1445		printf("%s: port %d iid %u WWPN %#jx arrived, WWPN %#jx is "
1446		       "still at that address\n", __func__, targ_port, iid,
1447		       (uintmax_t)wwpn,
1448		       (uintmax_t)softc->wwpn_iid[targ_port][iid].wwpn);
1449
1450		/*
1451		 * XXX KDM clear have_ca and ua_pending on each LUN for
1452		 * this initiator.
1453		 */
1454	}
1455	softc->wwpn_iid[targ_port][iid].in_use = 1;
1456	softc->wwpn_iid[targ_port][iid].iid = iid;
1457	softc->wwpn_iid[targ_port][iid].wwpn = wwpn;
1458	softc->wwpn_iid[targ_port][iid].port = targ_port;
1459
1460bailout:
1461
1462	mtx_unlock(&softc->ctl_lock);
1463
1464	return (retval);
1465}
1466
1467static int
1468ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1469{
1470	return (0);
1471}
1472
1473static int
1474ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1475{
1476	return (0);
1477}
1478
1479/*
1480 * Data movement routine for the CTL ioctl frontend port.
1481 */
1482static int
1483ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1484{
1485	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1486	struct ctl_sg_entry ext_entry, kern_entry;
1487	int ext_sglen, ext_sg_entries, kern_sg_entries;
1488	int ext_sg_start, ext_offset;
1489	int len_to_copy, len_copied;
1490	int kern_watermark, ext_watermark;
1491	int ext_sglist_malloced;
1492	int i, j;
1493
1494	ext_sglist_malloced = 0;
1495	ext_sg_start = 0;
1496	ext_offset = 0;
1497
1498	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1499
1500	/*
1501	 * If this flag is set, fake the data transfer.
1502	 */
1503	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1504		ctsio->ext_data_filled = ctsio->ext_data_len;
1505		goto bailout;
1506	}
1507
1508	/*
1509	 * To simplify things here, if we have a single buffer, stick it in
1510	 * a S/G entry and just make it a single entry S/G list.
1511	 */
1512	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1513		int len_seen;
1514
1515		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1516
1517		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1518							   M_WAITOK);
1519		ext_sglist_malloced = 1;
1520		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1521				   ext_sglen) != 0) {
1522			ctl_set_internal_failure(ctsio,
1523						 /*sks_valid*/ 0,
1524						 /*retry_count*/ 0);
1525			goto bailout;
1526		}
1527		ext_sg_entries = ctsio->ext_sg_entries;
1528		len_seen = 0;
1529		for (i = 0; i < ext_sg_entries; i++) {
1530			if ((len_seen + ext_sglist[i].len) >=
1531			     ctsio->ext_data_filled) {
1532				ext_sg_start = i;
1533				ext_offset = ctsio->ext_data_filled - len_seen;
1534				break;
1535			}
1536			len_seen += ext_sglist[i].len;
1537		}
1538	} else {
1539		ext_sglist = &ext_entry;
1540		ext_sglist->addr = ctsio->ext_data_ptr;
1541		ext_sglist->len = ctsio->ext_data_len;
1542		ext_sg_entries = 1;
1543		ext_sg_start = 0;
1544		ext_offset = ctsio->ext_data_filled;
1545	}
1546
1547	if (ctsio->kern_sg_entries > 0) {
1548		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1549		kern_sg_entries = ctsio->kern_sg_entries;
1550	} else {
1551		kern_sglist = &kern_entry;
1552		kern_sglist->addr = ctsio->kern_data_ptr;
1553		kern_sglist->len = ctsio->kern_data_len;
1554		kern_sg_entries = 1;
1555	}
1556
1557
1558	kern_watermark = 0;
1559	ext_watermark = ext_offset;
1560	len_copied = 0;
1561	for (i = ext_sg_start, j = 0;
1562	     i < ext_sg_entries && j < kern_sg_entries;) {
1563		uint8_t *ext_ptr, *kern_ptr;
1564
1565		len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1566				      kern_sglist[j].len - kern_watermark);
1567
1568		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1569		ext_ptr = ext_ptr + ext_watermark;
1570		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1571			/*
1572			 * XXX KDM fix this!
1573			 */
1574			panic("need to implement bus address support");
1575#if 0
1576			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1577#endif
1578		} else
1579			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1580		kern_ptr = kern_ptr + kern_watermark;
1581
1582		kern_watermark += len_to_copy;
1583		ext_watermark += len_to_copy;
1584
1585		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1586		     CTL_FLAG_DATA_IN) {
1587			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1588					 "bytes to user\n", len_to_copy));
1589			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1590					 "to %p\n", kern_ptr, ext_ptr));
1591			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1592				ctl_set_internal_failure(ctsio,
1593							 /*sks_valid*/ 0,
1594							 /*retry_count*/ 0);
1595				goto bailout;
1596			}
1597		} else {
1598			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1599					 "bytes from user\n", len_to_copy));
1600			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1601					 "to %p\n", ext_ptr, kern_ptr));
1602			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1603				ctl_set_internal_failure(ctsio,
1604							 /*sks_valid*/ 0,
1605							 /*retry_count*/0);
1606				goto bailout;
1607			}
1608		}
1609
1610		len_copied += len_to_copy;
1611
1612		if (ext_sglist[i].len == ext_watermark) {
1613			i++;
1614			ext_watermark = 0;
1615		}
1616
1617		if (kern_sglist[j].len == kern_watermark) {
1618			j++;
1619			kern_watermark = 0;
1620		}
1621	}
1622
1623	ctsio->ext_data_filled += len_copied;
1624
1625	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1626			 "kern_sg_entries: %d\n", ext_sg_entries,
1627			 kern_sg_entries));
1628	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1629			 "kern_data_len = %d\n", ctsio->ext_data_len,
1630			 ctsio->kern_data_len));
1631
1632
1633	/* XXX KDM set residual?? */
1634bailout:
1635
1636	if (ext_sglist_malloced != 0)
1637		free(ext_sglist, M_CTL);
1638
1639	return (CTL_RETVAL_COMPLETE);
1640}
1641
1642/*
1643 * Serialize a command that went down the "wrong" side, and so was sent to
1644 * this controller for execution.  The logic is a little different than the
1645 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1646 * sent back to the other side, but in the success case, we execute the
1647 * command on this side (XFER mode) or tell the other side to execute it
1648 * (SER_ONLY mode).
1649 */
1650static int
1651ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1652{
1653	struct ctl_softc *ctl_softc;
1654	union ctl_ha_msg msg_info;
1655	struct ctl_lun *lun;
1656	int retval = 0;
1657	uint32_t targ_lun;
1658
1659	ctl_softc = control_softc;
1660
1661	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1662	lun = ctl_softc->ctl_luns[targ_lun];
1663	if (lun==NULL)
1664	{
1665		/*
1666		 * Why isn't LUN defined? The other side wouldn't
1667		 * send a cmd if the LUN is undefined.
1668		 */
1669		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1670
1671		/* "Logical unit not supported" */
1672		ctl_set_sense_data(&msg_info.scsi.sense_data,
1673				   lun,
1674				   /*sense_format*/SSD_TYPE_NONE,
1675				   /*current_error*/ 1,
1676				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1677				   /*asc*/ 0x25,
1678				   /*ascq*/ 0x00,
1679				   SSD_ELEM_NONE);
1680
1681		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1682		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1683		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1684		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1685		msg_info.hdr.serializing_sc = NULL;
1686		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1687	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1688				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1689		}
1690		return(1);
1691
1692	}
1693
1694	mtx_lock(&lun->lun_lock);
1695    	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1696
1697	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1698		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1699		 ooa_links))) {
1700	case CTL_ACTION_BLOCK:
1701		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1702		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1703				  blocked_links);
1704		break;
1705	case CTL_ACTION_PASS:
1706	case CTL_ACTION_SKIP:
1707		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1708			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1709			ctl_enqueue_rtr((union ctl_io *)ctsio);
1710		} else {
1711
1712			/* send msg back to other side */
1713			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1714			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1715			msg_info.hdr.msg_type = CTL_MSG_R2R;
1716#if 0
1717			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1718#endif
1719		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1720			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1721			}
1722		}
1723		break;
1724	case CTL_ACTION_OVERLAP:
1725		/* OVERLAPPED COMMANDS ATTEMPTED */
1726		ctl_set_sense_data(&msg_info.scsi.sense_data,
1727				   lun,
1728				   /*sense_format*/SSD_TYPE_NONE,
1729				   /*current_error*/ 1,
1730				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1731				   /*asc*/ 0x4E,
1732				   /*ascq*/ 0x00,
1733				   SSD_ELEM_NONE);
1734
1735		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1736		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1737		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1738		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1739		msg_info.hdr.serializing_sc = NULL;
1740		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1741#if 0
1742		printf("BAD JUJU:Major Bummer Overlap\n");
1743#endif
1744		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1745		retval = 1;
1746		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1747		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1748		}
1749		break;
1750	case CTL_ACTION_OVERLAP_TAG:
1751		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1752		ctl_set_sense_data(&msg_info.scsi.sense_data,
1753				   lun,
1754				   /*sense_format*/SSD_TYPE_NONE,
1755				   /*current_error*/ 1,
1756				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1757				   /*asc*/ 0x4D,
1758				   /*ascq*/ ctsio->tag_num & 0xff,
1759				   SSD_ELEM_NONE);
1760
1761		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1762		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1763		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1764		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1765		msg_info.hdr.serializing_sc = NULL;
1766		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1767#if 0
1768		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1769#endif
1770		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1771		retval = 1;
1772		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1773		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1774		}
1775		break;
1776	case CTL_ACTION_ERROR:
1777	default:
1778		/* "Internal target failure" */
1779		ctl_set_sense_data(&msg_info.scsi.sense_data,
1780				   lun,
1781				   /*sense_format*/SSD_TYPE_NONE,
1782				   /*current_error*/ 1,
1783				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1784				   /*asc*/ 0x44,
1785				   /*ascq*/ 0x00,
1786				   SSD_ELEM_NONE);
1787
1788		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1789		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1790		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1791		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1792		msg_info.hdr.serializing_sc = NULL;
1793		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1794#if 0
1795		printf("BAD JUJU:Major Bummer HW Error\n");
1796#endif
1797		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1798		retval = 1;
1799		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1800		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1801		}
1802		break;
1803	}
1804	mtx_unlock(&lun->lun_lock);
1805	return (retval);
1806}
1807
1808static int
1809ctl_ioctl_submit_wait(union ctl_io *io)
1810{
1811	struct ctl_fe_ioctl_params params;
1812	ctl_fe_ioctl_state last_state;
1813	int done, retval;
1814
1815	retval = 0;
1816
1817	bzero(&params, sizeof(params));
1818
1819	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1820	cv_init(&params.sem, "ctlioccv");
1821	params.state = CTL_IOCTL_INPROG;
1822	last_state = params.state;
1823
1824	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1825
1826	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1827
1828	/* This shouldn't happen */
1829	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1830		return (retval);
1831
1832	done = 0;
1833
1834	do {
1835		mtx_lock(&params.ioctl_mtx);
1836		/*
1837		 * Check the state here, and don't sleep if the state has
1838		 * already changed (i.e. wakeup has already occured, but we
1839		 * weren't waiting yet).
1840		 */
1841		if (params.state == last_state) {
1842			/* XXX KDM cv_wait_sig instead? */
1843			cv_wait(&params.sem, &params.ioctl_mtx);
1844		}
1845		last_state = params.state;
1846
1847		switch (params.state) {
1848		case CTL_IOCTL_INPROG:
1849			/* Why did we wake up? */
1850			/* XXX KDM error here? */
1851			mtx_unlock(&params.ioctl_mtx);
1852			break;
1853		case CTL_IOCTL_DATAMOVE:
1854			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1855
1856			/*
1857			 * change last_state back to INPROG to avoid
1858			 * deadlock on subsequent data moves.
1859			 */
1860			params.state = last_state = CTL_IOCTL_INPROG;
1861
1862			mtx_unlock(&params.ioctl_mtx);
1863			ctl_ioctl_do_datamove(&io->scsiio);
1864			/*
1865			 * Note that in some cases, most notably writes,
1866			 * this will queue the I/O and call us back later.
1867			 * In other cases, generally reads, this routine
1868			 * will immediately call back and wake us up,
1869			 * probably using our own context.
1870			 */
1871			io->scsiio.be_move_done(io);
1872			break;
1873		case CTL_IOCTL_DONE:
1874			mtx_unlock(&params.ioctl_mtx);
1875			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
1876			done = 1;
1877			break;
1878		default:
1879			mtx_unlock(&params.ioctl_mtx);
1880			/* XXX KDM error here? */
1881			break;
1882		}
1883	} while (done == 0);
1884
1885	mtx_destroy(&params.ioctl_mtx);
1886	cv_destroy(&params.sem);
1887
1888	return (CTL_RETVAL_COMPLETE);
1889}
1890
1891static void
1892ctl_ioctl_datamove(union ctl_io *io)
1893{
1894	struct ctl_fe_ioctl_params *params;
1895
1896	params = (struct ctl_fe_ioctl_params *)
1897		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1898
1899	mtx_lock(&params->ioctl_mtx);
1900	params->state = CTL_IOCTL_DATAMOVE;
1901	cv_broadcast(&params->sem);
1902	mtx_unlock(&params->ioctl_mtx);
1903}
1904
1905static void
1906ctl_ioctl_done(union ctl_io *io)
1907{
1908	struct ctl_fe_ioctl_params *params;
1909
1910	params = (struct ctl_fe_ioctl_params *)
1911		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1912
1913	mtx_lock(&params->ioctl_mtx);
1914	params->state = CTL_IOCTL_DONE;
1915	cv_broadcast(&params->sem);
1916	mtx_unlock(&params->ioctl_mtx);
1917}
1918
1919static void
1920ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
1921{
1922	struct ctl_fe_ioctl_startstop_info *sd_info;
1923
1924	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
1925
1926	sd_info->hs_info.status = metatask->status;
1927	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
1928	sd_info->hs_info.luns_complete =
1929		metatask->taskinfo.startstop.luns_complete;
1930	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
1931
1932	cv_broadcast(&sd_info->sem);
1933}
1934
1935static void
1936ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
1937{
1938	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
1939
1940	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
1941
1942	mtx_lock(fe_bbr_info->lock);
1943	fe_bbr_info->bbr_info->status = metatask->status;
1944	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
1945	fe_bbr_info->wakeup_done = 1;
1946	mtx_unlock(fe_bbr_info->lock);
1947
1948	cv_broadcast(&fe_bbr_info->sem);
1949}
1950
1951/*
1952 * Returns 0 for success, errno for failure.
1953 */
1954static int
1955ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
1956		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
1957{
1958	union ctl_io *io;
1959	int retval;
1960
1961	retval = 0;
1962
1963	mtx_lock(&lun->lun_lock);
1964	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
1965	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
1966	     ooa_links)) {
1967		struct ctl_ooa_entry *entry;
1968
1969		/*
1970		 * If we've got more than we can fit, just count the
1971		 * remaining entries.
1972		 */
1973		if (*cur_fill_num >= ooa_hdr->alloc_num)
1974			continue;
1975
1976		entry = &kern_entries[*cur_fill_num];
1977
1978		entry->tag_num = io->scsiio.tag_num;
1979		entry->lun_num = lun->lun;
1980#ifdef CTL_TIME_IO
1981		entry->start_bt = io->io_hdr.start_bt;
1982#endif
1983		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
1984		entry->cdb_len = io->scsiio.cdb_len;
1985		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
1986			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
1987
1988		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
1989			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
1990
1991		if (io->io_hdr.flags & CTL_FLAG_ABORT)
1992			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
1993
1994		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
1995			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
1996
1997		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
1998			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
1999	}
2000	mtx_unlock(&lun->lun_lock);
2001
2002	return (retval);
2003}
2004
2005static void *
2006ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2007		 size_t error_str_len)
2008{
2009	void *kptr;
2010
2011	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2012
2013	if (copyin(user_addr, kptr, len) != 0) {
2014		snprintf(error_str, error_str_len, "Error copying %d bytes "
2015			 "from user address %p to kernel address %p", len,
2016			 user_addr, kptr);
2017		free(kptr, M_CTL);
2018		return (NULL);
2019	}
2020
2021	return (kptr);
2022}
2023
2024static void
2025ctl_free_args(int num_args, struct ctl_be_arg *args)
2026{
2027	int i;
2028
2029	if (args == NULL)
2030		return;
2031
2032	for (i = 0; i < num_args; i++) {
2033		free(args[i].kname, M_CTL);
2034		free(args[i].kvalue, M_CTL);
2035	}
2036
2037	free(args, M_CTL);
2038}
2039
2040static struct ctl_be_arg *
2041ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2042		char *error_str, size_t error_str_len)
2043{
2044	struct ctl_be_arg *args;
2045	int i;
2046
2047	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2048				error_str, error_str_len);
2049
2050	if (args == NULL)
2051		goto bailout;
2052
2053	for (i = 0; i < num_args; i++) {
2054		args[i].kname = NULL;
2055		args[i].kvalue = NULL;
2056	}
2057
2058	for (i = 0; i < num_args; i++) {
2059		uint8_t *tmpptr;
2060
2061		args[i].kname = ctl_copyin_alloc(args[i].name,
2062			args[i].namelen, error_str, error_str_len);
2063		if (args[i].kname == NULL)
2064			goto bailout;
2065
2066		if (args[i].kname[args[i].namelen - 1] != '\0') {
2067			snprintf(error_str, error_str_len, "Argument %d "
2068				 "name is not NUL-terminated", i);
2069			goto bailout;
2070		}
2071
2072		if (args[i].flags & CTL_BEARG_RD) {
2073			tmpptr = ctl_copyin_alloc(args[i].value,
2074				args[i].vallen, error_str, error_str_len);
2075			if (tmpptr == NULL)
2076				goto bailout;
2077			if ((args[i].flags & CTL_BEARG_ASCII)
2078			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2079				snprintf(error_str, error_str_len, "Argument "
2080				    "%d value is not NUL-terminated", i);
2081				goto bailout;
2082			}
2083			args[i].kvalue = tmpptr;
2084		} else {
2085			args[i].kvalue = malloc(args[i].vallen,
2086			    M_CTL, M_WAITOK | M_ZERO);
2087		}
2088	}
2089
2090	return (args);
2091bailout:
2092
2093	ctl_free_args(num_args, args);
2094
2095	return (NULL);
2096}
2097
2098static void
2099ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2100{
2101	int i;
2102
2103	for (i = 0; i < num_args; i++) {
2104		if (args[i].flags & CTL_BEARG_WR)
2105			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2106	}
2107}
2108
2109/*
2110 * Escape characters that are illegal or not recommended in XML.
2111 */
2112int
2113ctl_sbuf_printf_esc(struct sbuf *sb, char *str)
2114{
2115	int retval;
2116
2117	retval = 0;
2118
2119	for (; *str; str++) {
2120		switch (*str) {
2121		case '&':
2122			retval = sbuf_printf(sb, "&amp;");
2123			break;
2124		case '>':
2125			retval = sbuf_printf(sb, "&gt;");
2126			break;
2127		case '<':
2128			retval = sbuf_printf(sb, "&lt;");
2129			break;
2130		default:
2131			retval = sbuf_putc(sb, *str);
2132			break;
2133		}
2134
2135		if (retval != 0)
2136			break;
2137
2138	}
2139
2140	return (retval);
2141}
2142
2143static int
2144ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2145	  struct thread *td)
2146{
2147	struct ctl_softc *softc;
2148	int retval;
2149
2150	softc = control_softc;
2151
2152	retval = 0;
2153
2154	switch (cmd) {
2155	case CTL_IO: {
2156		union ctl_io *io;
2157		void *pool_tmp;
2158
2159		/*
2160		 * If we haven't been "enabled", don't allow any SCSI I/O
2161		 * to this FETD.
2162		 */
2163		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2164			retval = EPERM;
2165			break;
2166		}
2167
2168		io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2169		if (io == NULL) {
2170			printf("ctl_ioctl: can't allocate ctl_io!\n");
2171			retval = ENOSPC;
2172			break;
2173		}
2174
2175		/*
2176		 * Need to save the pool reference so it doesn't get
2177		 * spammed by the user's ctl_io.
2178		 */
2179		pool_tmp = io->io_hdr.pool;
2180
2181		memcpy(io, (void *)addr, sizeof(*io));
2182
2183		io->io_hdr.pool = pool_tmp;
2184		/*
2185		 * No status yet, so make sure the status is set properly.
2186		 */
2187		io->io_hdr.status = CTL_STATUS_NONE;
2188
2189		/*
2190		 * The user sets the initiator ID, target and LUN IDs.
2191		 */
2192		io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2193		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2194		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2195		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2196			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2197
2198		retval = ctl_ioctl_submit_wait(io);
2199
2200		if (retval != 0) {
2201			ctl_free_io(io);
2202			break;
2203		}
2204
2205		memcpy((void *)addr, io, sizeof(*io));
2206
2207		/* return this to our pool */
2208		ctl_free_io(io);
2209
2210		break;
2211	}
2212	case CTL_ENABLE_PORT:
2213	case CTL_DISABLE_PORT:
2214	case CTL_SET_PORT_WWNS: {
2215		struct ctl_port *port;
2216		struct ctl_port_entry *entry;
2217
2218		entry = (struct ctl_port_entry *)addr;
2219
2220		mtx_lock(&softc->ctl_lock);
2221		STAILQ_FOREACH(port, &softc->port_list, links) {
2222			int action, done;
2223
2224			action = 0;
2225			done = 0;
2226
2227			if ((entry->port_type == CTL_PORT_NONE)
2228			 && (entry->targ_port == port->targ_port)) {
2229				/*
2230				 * If the user only wants to enable or
2231				 * disable or set WWNs on a specific port,
2232				 * do the operation and we're done.
2233				 */
2234				action = 1;
2235				done = 1;
2236			} else if (entry->port_type & port->port_type) {
2237				/*
2238				 * Compare the user's type mask with the
2239				 * particular frontend type to see if we
2240				 * have a match.
2241				 */
2242				action = 1;
2243				done = 0;
2244
2245				/*
2246				 * Make sure the user isn't trying to set
2247				 * WWNs on multiple ports at the same time.
2248				 */
2249				if (cmd == CTL_SET_PORT_WWNS) {
2250					printf("%s: Can't set WWNs on "
2251					       "multiple ports\n", __func__);
2252					retval = EINVAL;
2253					break;
2254				}
2255			}
2256			if (action != 0) {
2257				/*
2258				 * XXX KDM we have to drop the lock here,
2259				 * because the online/offline operations
2260				 * can potentially block.  We need to
2261				 * reference count the frontends so they
2262				 * can't go away,
2263				 */
2264				mtx_unlock(&softc->ctl_lock);
2265
2266				if (cmd == CTL_ENABLE_PORT) {
2267					struct ctl_lun *lun;
2268
2269					STAILQ_FOREACH(lun, &softc->lun_list,
2270						       links) {
2271						port->lun_enable(port->targ_lun_arg,
2272						    lun->target,
2273						    lun->lun);
2274					}
2275
2276					ctl_port_online(port);
2277				} else if (cmd == CTL_DISABLE_PORT) {
2278					struct ctl_lun *lun;
2279
2280					ctl_port_offline(port);
2281
2282					STAILQ_FOREACH(lun, &softc->lun_list,
2283						       links) {
2284						port->lun_disable(
2285						    port->targ_lun_arg,
2286						    lun->target,
2287						    lun->lun);
2288					}
2289				}
2290
2291				mtx_lock(&softc->ctl_lock);
2292
2293				if (cmd == CTL_SET_PORT_WWNS)
2294					ctl_port_set_wwns(port,
2295					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2296					    1 : 0, entry->wwnn,
2297					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2298					    1 : 0, entry->wwpn);
2299			}
2300			if (done != 0)
2301				break;
2302		}
2303		mtx_unlock(&softc->ctl_lock);
2304		break;
2305	}
2306	case CTL_GET_PORT_LIST: {
2307		struct ctl_port *port;
2308		struct ctl_port_list *list;
2309		int i;
2310
2311		list = (struct ctl_port_list *)addr;
2312
2313		if (list->alloc_len != (list->alloc_num *
2314		    sizeof(struct ctl_port_entry))) {
2315			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2316			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2317			       "%zu\n", __func__, list->alloc_len,
2318			       list->alloc_num, sizeof(struct ctl_port_entry));
2319			retval = EINVAL;
2320			break;
2321		}
2322		list->fill_len = 0;
2323		list->fill_num = 0;
2324		list->dropped_num = 0;
2325		i = 0;
2326		mtx_lock(&softc->ctl_lock);
2327		STAILQ_FOREACH(port, &softc->port_list, links) {
2328			struct ctl_port_entry entry, *list_entry;
2329
2330			if (list->fill_num >= list->alloc_num) {
2331				list->dropped_num++;
2332				continue;
2333			}
2334
2335			entry.port_type = port->port_type;
2336			strlcpy(entry.port_name, port->port_name,
2337				sizeof(entry.port_name));
2338			entry.targ_port = port->targ_port;
2339			entry.physical_port = port->physical_port;
2340			entry.virtual_port = port->virtual_port;
2341			entry.wwnn = port->wwnn;
2342			entry.wwpn = port->wwpn;
2343			if (port->status & CTL_PORT_STATUS_ONLINE)
2344				entry.online = 1;
2345			else
2346				entry.online = 0;
2347
2348			list_entry = &list->entries[i];
2349
2350			retval = copyout(&entry, list_entry, sizeof(entry));
2351			if (retval != 0) {
2352				printf("%s: CTL_GET_PORT_LIST: copyout "
2353				       "returned %d\n", __func__, retval);
2354				break;
2355			}
2356			i++;
2357			list->fill_num++;
2358			list->fill_len += sizeof(entry);
2359		}
2360		mtx_unlock(&softc->ctl_lock);
2361
2362		/*
2363		 * If this is non-zero, we had a copyout fault, so there's
2364		 * probably no point in attempting to set the status inside
2365		 * the structure.
2366		 */
2367		if (retval != 0)
2368			break;
2369
2370		if (list->dropped_num > 0)
2371			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2372		else
2373			list->status = CTL_PORT_LIST_OK;
2374		break;
2375	}
2376	case CTL_DUMP_OOA: {
2377		struct ctl_lun *lun;
2378		union ctl_io *io;
2379		char printbuf[128];
2380		struct sbuf sb;
2381
2382		mtx_lock(&softc->ctl_lock);
2383		printf("Dumping OOA queues:\n");
2384		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2385			mtx_lock(&lun->lun_lock);
2386			for (io = (union ctl_io *)TAILQ_FIRST(
2387			     &lun->ooa_queue); io != NULL;
2388			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2389			     ooa_links)) {
2390				sbuf_new(&sb, printbuf, sizeof(printbuf),
2391					 SBUF_FIXEDLEN);
2392				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2393					    (intmax_t)lun->lun,
2394					    io->scsiio.tag_num,
2395					    (io->io_hdr.flags &
2396					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2397					    (io->io_hdr.flags &
2398					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2399					    (io->io_hdr.flags &
2400					    CTL_FLAG_ABORT) ? " ABORT" : "",
2401			                    (io->io_hdr.flags &
2402		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2403				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2404				sbuf_finish(&sb);
2405				printf("%s\n", sbuf_data(&sb));
2406			}
2407			mtx_unlock(&lun->lun_lock);
2408		}
2409		printf("OOA queues dump done\n");
2410		mtx_unlock(&softc->ctl_lock);
2411		break;
2412	}
2413	case CTL_GET_OOA: {
2414		struct ctl_lun *lun;
2415		struct ctl_ooa *ooa_hdr;
2416		struct ctl_ooa_entry *entries;
2417		uint32_t cur_fill_num;
2418
2419		ooa_hdr = (struct ctl_ooa *)addr;
2420
2421		if ((ooa_hdr->alloc_len == 0)
2422		 || (ooa_hdr->alloc_num == 0)) {
2423			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2424			       "must be non-zero\n", __func__,
2425			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2426			retval = EINVAL;
2427			break;
2428		}
2429
2430		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2431		    sizeof(struct ctl_ooa_entry))) {
2432			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2433			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2434			       __func__, ooa_hdr->alloc_len,
2435			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2436			retval = EINVAL;
2437			break;
2438		}
2439
2440		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2441		if (entries == NULL) {
2442			printf("%s: could not allocate %d bytes for OOA "
2443			       "dump\n", __func__, ooa_hdr->alloc_len);
2444			retval = ENOMEM;
2445			break;
2446		}
2447
2448		mtx_lock(&softc->ctl_lock);
2449		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2450		 && ((ooa_hdr->lun_num > CTL_MAX_LUNS)
2451		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2452			mtx_unlock(&softc->ctl_lock);
2453			free(entries, M_CTL);
2454			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2455			       __func__, (uintmax_t)ooa_hdr->lun_num);
2456			retval = EINVAL;
2457			break;
2458		}
2459
2460		cur_fill_num = 0;
2461
2462		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2463			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2464				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2465					ooa_hdr, entries);
2466				if (retval != 0)
2467					break;
2468			}
2469			if (retval != 0) {
2470				mtx_unlock(&softc->ctl_lock);
2471				free(entries, M_CTL);
2472				break;
2473			}
2474		} else {
2475			lun = softc->ctl_luns[ooa_hdr->lun_num];
2476
2477			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2478						    entries);
2479		}
2480		mtx_unlock(&softc->ctl_lock);
2481
2482		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2483		ooa_hdr->fill_len = ooa_hdr->fill_num *
2484			sizeof(struct ctl_ooa_entry);
2485		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2486		if (retval != 0) {
2487			printf("%s: error copying out %d bytes for OOA dump\n",
2488			       __func__, ooa_hdr->fill_len);
2489		}
2490
2491		getbintime(&ooa_hdr->cur_bt);
2492
2493		if (cur_fill_num > ooa_hdr->alloc_num) {
2494			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2495			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2496		} else {
2497			ooa_hdr->dropped_num = 0;
2498			ooa_hdr->status = CTL_OOA_OK;
2499		}
2500
2501		free(entries, M_CTL);
2502		break;
2503	}
2504	case CTL_CHECK_OOA: {
2505		union ctl_io *io;
2506		struct ctl_lun *lun;
2507		struct ctl_ooa_info *ooa_info;
2508
2509
2510		ooa_info = (struct ctl_ooa_info *)addr;
2511
2512		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2513			ooa_info->status = CTL_OOA_INVALID_LUN;
2514			break;
2515		}
2516		mtx_lock(&softc->ctl_lock);
2517		lun = softc->ctl_luns[ooa_info->lun_id];
2518		if (lun == NULL) {
2519			mtx_unlock(&softc->ctl_lock);
2520			ooa_info->status = CTL_OOA_INVALID_LUN;
2521			break;
2522		}
2523		mtx_lock(&lun->lun_lock);
2524		mtx_unlock(&softc->ctl_lock);
2525		ooa_info->num_entries = 0;
2526		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2527		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2528		     &io->io_hdr, ooa_links)) {
2529			ooa_info->num_entries++;
2530		}
2531		mtx_unlock(&lun->lun_lock);
2532
2533		ooa_info->status = CTL_OOA_SUCCESS;
2534
2535		break;
2536	}
2537	case CTL_HARD_START:
2538	case CTL_HARD_STOP: {
2539		struct ctl_fe_ioctl_startstop_info ss_info;
2540		struct cfi_metatask *metatask;
2541		struct mtx hs_mtx;
2542
2543		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2544
2545		cv_init(&ss_info.sem, "hard start/stop cv" );
2546
2547		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2548		if (metatask == NULL) {
2549			retval = ENOMEM;
2550			mtx_destroy(&hs_mtx);
2551			break;
2552		}
2553
2554		if (cmd == CTL_HARD_START)
2555			metatask->tasktype = CFI_TASK_STARTUP;
2556		else
2557			metatask->tasktype = CFI_TASK_SHUTDOWN;
2558
2559		metatask->callback = ctl_ioctl_hard_startstop_callback;
2560		metatask->callback_arg = &ss_info;
2561
2562		cfi_action(metatask);
2563
2564		/* Wait for the callback */
2565		mtx_lock(&hs_mtx);
2566		cv_wait_sig(&ss_info.sem, &hs_mtx);
2567		mtx_unlock(&hs_mtx);
2568
2569		/*
2570		 * All information has been copied from the metatask by the
2571		 * time cv_broadcast() is called, so we free the metatask here.
2572		 */
2573		cfi_free_metatask(metatask);
2574
2575		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2576
2577		mtx_destroy(&hs_mtx);
2578		break;
2579	}
2580	case CTL_BBRREAD: {
2581		struct ctl_bbrread_info *bbr_info;
2582		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2583		struct mtx bbr_mtx;
2584		struct cfi_metatask *metatask;
2585
2586		bbr_info = (struct ctl_bbrread_info *)addr;
2587
2588		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2589
2590		bzero(&bbr_mtx, sizeof(bbr_mtx));
2591		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2592
2593		fe_bbr_info.bbr_info = bbr_info;
2594		fe_bbr_info.lock = &bbr_mtx;
2595
2596		cv_init(&fe_bbr_info.sem, "BBR read cv");
2597		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2598
2599		if (metatask == NULL) {
2600			mtx_destroy(&bbr_mtx);
2601			cv_destroy(&fe_bbr_info.sem);
2602			retval = ENOMEM;
2603			break;
2604		}
2605		metatask->tasktype = CFI_TASK_BBRREAD;
2606		metatask->callback = ctl_ioctl_bbrread_callback;
2607		metatask->callback_arg = &fe_bbr_info;
2608		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2609		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2610		metatask->taskinfo.bbrread.len = bbr_info->len;
2611
2612		cfi_action(metatask);
2613
2614		mtx_lock(&bbr_mtx);
2615		while (fe_bbr_info.wakeup_done == 0)
2616			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2617		mtx_unlock(&bbr_mtx);
2618
2619		bbr_info->status = metatask->status;
2620		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2621		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2622		memcpy(&bbr_info->sense_data,
2623		       &metatask->taskinfo.bbrread.sense_data,
2624		       ctl_min(sizeof(bbr_info->sense_data),
2625			       sizeof(metatask->taskinfo.bbrread.sense_data)));
2626
2627		cfi_free_metatask(metatask);
2628
2629		mtx_destroy(&bbr_mtx);
2630		cv_destroy(&fe_bbr_info.sem);
2631
2632		break;
2633	}
2634	case CTL_DELAY_IO: {
2635		struct ctl_io_delay_info *delay_info;
2636#ifdef CTL_IO_DELAY
2637		struct ctl_lun *lun;
2638#endif /* CTL_IO_DELAY */
2639
2640		delay_info = (struct ctl_io_delay_info *)addr;
2641
2642#ifdef CTL_IO_DELAY
2643		mtx_lock(&softc->ctl_lock);
2644
2645		if ((delay_info->lun_id > CTL_MAX_LUNS)
2646		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2647			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2648		} else {
2649			lun = softc->ctl_luns[delay_info->lun_id];
2650			mtx_lock(&lun->lun_lock);
2651
2652			delay_info->status = CTL_DELAY_STATUS_OK;
2653
2654			switch (delay_info->delay_type) {
2655			case CTL_DELAY_TYPE_CONT:
2656				break;
2657			case CTL_DELAY_TYPE_ONESHOT:
2658				break;
2659			default:
2660				delay_info->status =
2661					CTL_DELAY_STATUS_INVALID_TYPE;
2662				break;
2663			}
2664
2665			switch (delay_info->delay_loc) {
2666			case CTL_DELAY_LOC_DATAMOVE:
2667				lun->delay_info.datamove_type =
2668					delay_info->delay_type;
2669				lun->delay_info.datamove_delay =
2670					delay_info->delay_secs;
2671				break;
2672			case CTL_DELAY_LOC_DONE:
2673				lun->delay_info.done_type =
2674					delay_info->delay_type;
2675				lun->delay_info.done_delay =
2676					delay_info->delay_secs;
2677				break;
2678			default:
2679				delay_info->status =
2680					CTL_DELAY_STATUS_INVALID_LOC;
2681				break;
2682			}
2683			mtx_unlock(&lun->lun_lock);
2684		}
2685
2686		mtx_unlock(&softc->ctl_lock);
2687#else
2688		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2689#endif /* CTL_IO_DELAY */
2690		break;
2691	}
2692	case CTL_REALSYNC_SET: {
2693		int *syncstate;
2694
2695		syncstate = (int *)addr;
2696
2697		mtx_lock(&softc->ctl_lock);
2698		switch (*syncstate) {
2699		case 0:
2700			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2701			break;
2702		case 1:
2703			softc->flags |= CTL_FLAG_REAL_SYNC;
2704			break;
2705		default:
2706			retval = EINVAL;
2707			break;
2708		}
2709		mtx_unlock(&softc->ctl_lock);
2710		break;
2711	}
2712	case CTL_REALSYNC_GET: {
2713		int *syncstate;
2714
2715		syncstate = (int*)addr;
2716
2717		mtx_lock(&softc->ctl_lock);
2718		if (softc->flags & CTL_FLAG_REAL_SYNC)
2719			*syncstate = 1;
2720		else
2721			*syncstate = 0;
2722		mtx_unlock(&softc->ctl_lock);
2723
2724		break;
2725	}
2726	case CTL_SETSYNC:
2727	case CTL_GETSYNC: {
2728		struct ctl_sync_info *sync_info;
2729		struct ctl_lun *lun;
2730
2731		sync_info = (struct ctl_sync_info *)addr;
2732
2733		mtx_lock(&softc->ctl_lock);
2734		lun = softc->ctl_luns[sync_info->lun_id];
2735		if (lun == NULL) {
2736			mtx_unlock(&softc->ctl_lock);
2737			sync_info->status = CTL_GS_SYNC_NO_LUN;
2738		}
2739		/*
2740		 * Get or set the sync interval.  We're not bounds checking
2741		 * in the set case, hopefully the user won't do something
2742		 * silly.
2743		 */
2744		mtx_lock(&lun->lun_lock);
2745		mtx_unlock(&softc->ctl_lock);
2746		if (cmd == CTL_GETSYNC)
2747			sync_info->sync_interval = lun->sync_interval;
2748		else
2749			lun->sync_interval = sync_info->sync_interval;
2750		mtx_unlock(&lun->lun_lock);
2751
2752		sync_info->status = CTL_GS_SYNC_OK;
2753
2754		break;
2755	}
2756	case CTL_GETSTATS: {
2757		struct ctl_stats *stats;
2758		struct ctl_lun *lun;
2759		int i;
2760
2761		stats = (struct ctl_stats *)addr;
2762
2763		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2764		     stats->alloc_len) {
2765			stats->status = CTL_SS_NEED_MORE_SPACE;
2766			stats->num_luns = softc->num_luns;
2767			break;
2768		}
2769		/*
2770		 * XXX KDM no locking here.  If the LUN list changes,
2771		 * things can blow up.
2772		 */
2773		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2774		     i++, lun = STAILQ_NEXT(lun, links)) {
2775			retval = copyout(&lun->stats, &stats->lun_stats[i],
2776					 sizeof(lun->stats));
2777			if (retval != 0)
2778				break;
2779		}
2780		stats->num_luns = softc->num_luns;
2781		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2782				 softc->num_luns;
2783		stats->status = CTL_SS_OK;
2784#ifdef CTL_TIME_IO
2785		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2786#else
2787		stats->flags = CTL_STATS_FLAG_NONE;
2788#endif
2789		getnanouptime(&stats->timestamp);
2790		break;
2791	}
2792	case CTL_ERROR_INJECT: {
2793		struct ctl_error_desc *err_desc, *new_err_desc;
2794		struct ctl_lun *lun;
2795
2796		err_desc = (struct ctl_error_desc *)addr;
2797
2798		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2799				      M_WAITOK | M_ZERO);
2800		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2801
2802		mtx_lock(&softc->ctl_lock);
2803		lun = softc->ctl_luns[err_desc->lun_id];
2804		if (lun == NULL) {
2805			mtx_unlock(&softc->ctl_lock);
2806			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2807			       __func__, (uintmax_t)err_desc->lun_id);
2808			retval = EINVAL;
2809			break;
2810		}
2811		mtx_lock(&lun->lun_lock);
2812		mtx_unlock(&softc->ctl_lock);
2813
2814		/*
2815		 * We could do some checking here to verify the validity
2816		 * of the request, but given the complexity of error
2817		 * injection requests, the checking logic would be fairly
2818		 * complex.
2819		 *
2820		 * For now, if the request is invalid, it just won't get
2821		 * executed and might get deleted.
2822		 */
2823		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2824
2825		/*
2826		 * XXX KDM check to make sure the serial number is unique,
2827		 * in case we somehow manage to wrap.  That shouldn't
2828		 * happen for a very long time, but it's the right thing to
2829		 * do.
2830		 */
2831		new_err_desc->serial = lun->error_serial;
2832		err_desc->serial = lun->error_serial;
2833		lun->error_serial++;
2834
2835		mtx_unlock(&lun->lun_lock);
2836		break;
2837	}
2838	case CTL_ERROR_INJECT_DELETE: {
2839		struct ctl_error_desc *delete_desc, *desc, *desc2;
2840		struct ctl_lun *lun;
2841		int delete_done;
2842
2843		delete_desc = (struct ctl_error_desc *)addr;
2844		delete_done = 0;
2845
2846		mtx_lock(&softc->ctl_lock);
2847		lun = softc->ctl_luns[delete_desc->lun_id];
2848		if (lun == NULL) {
2849			mtx_unlock(&softc->ctl_lock);
2850			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2851			       __func__, (uintmax_t)delete_desc->lun_id);
2852			retval = EINVAL;
2853			break;
2854		}
2855		mtx_lock(&lun->lun_lock);
2856		mtx_unlock(&softc->ctl_lock);
2857		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2858			if (desc->serial != delete_desc->serial)
2859				continue;
2860
2861			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2862				      links);
2863			free(desc, M_CTL);
2864			delete_done = 1;
2865		}
2866		mtx_unlock(&lun->lun_lock);
2867		if (delete_done == 0) {
2868			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2869			       "error serial %ju on LUN %u\n", __func__,
2870			       delete_desc->serial, delete_desc->lun_id);
2871			retval = EINVAL;
2872			break;
2873		}
2874		break;
2875	}
2876	case CTL_DUMP_STRUCTS: {
2877		int i, j, k;
2878		struct ctl_port *port;
2879		struct ctl_frontend *fe;
2880
2881		printf("CTL IID to WWPN map start:\n");
2882		for (i = 0; i < CTL_MAX_PORTS; i++) {
2883			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2884				if (softc->wwpn_iid[i][j].in_use == 0)
2885					continue;
2886
2887				printf("port %d iid %u WWPN %#jx\n",
2888				       softc->wwpn_iid[i][j].port,
2889				       softc->wwpn_iid[i][j].iid,
2890				       (uintmax_t)softc->wwpn_iid[i][j].wwpn);
2891			}
2892		}
2893		printf("CTL IID to WWPN map end\n");
2894		printf("CTL Persistent Reservation information start:\n");
2895		for (i = 0; i < CTL_MAX_LUNS; i++) {
2896			struct ctl_lun *lun;
2897
2898			lun = softc->ctl_luns[i];
2899
2900			if ((lun == NULL)
2901			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
2902				continue;
2903
2904			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
2905				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2906					if (lun->per_res[j+k].registered == 0)
2907						continue;
2908					printf("LUN %d port %d iid %d key "
2909					       "%#jx\n", i, j, k,
2910					       (uintmax_t)scsi_8btou64(
2911					       lun->per_res[j+k].res_key.key));
2912				}
2913			}
2914		}
2915		printf("CTL Persistent Reservation information end\n");
2916		printf("CTL Ports:\n");
2917		/*
2918		 * XXX KDM calling this without a lock.  We'd likely want
2919		 * to drop the lock before calling the frontend's dump
2920		 * routine anyway.
2921		 */
2922		STAILQ_FOREACH(port, &softc->port_list, links) {
2923			printf("Port %s Frontend %s Type %u pport %d vport %d WWNN "
2924			       "%#jx WWPN %#jx\n", port->port_name,
2925			       port->frontend->name, port->port_type,
2926			       port->physical_port, port->virtual_port,
2927			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2928		}
2929		printf("CTL Port information end\n");
2930		printf("CTL Frontends:\n");
2931		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2932			printf("Frontend %s\n", fe->name);
2933			if (fe->fe_dump != NULL)
2934				fe->fe_dump();
2935		}
2936		printf("CTL Frontend information end\n");
2937		break;
2938	}
2939	case CTL_LUN_REQ: {
2940		struct ctl_lun_req *lun_req;
2941		struct ctl_backend_driver *backend;
2942
2943		lun_req = (struct ctl_lun_req *)addr;
2944
2945		backend = ctl_backend_find(lun_req->backend);
2946		if (backend == NULL) {
2947			lun_req->status = CTL_LUN_ERROR;
2948			snprintf(lun_req->error_str,
2949				 sizeof(lun_req->error_str),
2950				 "Backend \"%s\" not found.",
2951				 lun_req->backend);
2952			break;
2953		}
2954		if (lun_req->num_be_args > 0) {
2955			lun_req->kern_be_args = ctl_copyin_args(
2956				lun_req->num_be_args,
2957				lun_req->be_args,
2958				lun_req->error_str,
2959				sizeof(lun_req->error_str));
2960			if (lun_req->kern_be_args == NULL) {
2961				lun_req->status = CTL_LUN_ERROR;
2962				break;
2963			}
2964		}
2965
2966		retval = backend->ioctl(dev, cmd, addr, flag, td);
2967
2968		if (lun_req->num_be_args > 0) {
2969			ctl_copyout_args(lun_req->num_be_args,
2970				      lun_req->kern_be_args);
2971			ctl_free_args(lun_req->num_be_args,
2972				      lun_req->kern_be_args);
2973		}
2974		break;
2975	}
2976	case CTL_LUN_LIST: {
2977		struct sbuf *sb;
2978		struct ctl_lun *lun;
2979		struct ctl_lun_list *list;
2980		struct ctl_option *opt;
2981
2982		list = (struct ctl_lun_list *)addr;
2983
2984		/*
2985		 * Allocate a fixed length sbuf here, based on the length
2986		 * of the user's buffer.  We could allocate an auto-extending
2987		 * buffer, and then tell the user how much larger our
2988		 * amount of data is than his buffer, but that presents
2989		 * some problems:
2990		 *
2991		 * 1.  The sbuf(9) routines use a blocking malloc, and so
2992		 *     we can't hold a lock while calling them with an
2993		 *     auto-extending buffer.
2994 		 *
2995		 * 2.  There is not currently a LUN reference counting
2996		 *     mechanism, outside of outstanding transactions on
2997		 *     the LUN's OOA queue.  So a LUN could go away on us
2998		 *     while we're getting the LUN number, backend-specific
2999		 *     information, etc.  Thus, given the way things
3000		 *     currently work, we need to hold the CTL lock while
3001		 *     grabbing LUN information.
3002		 *
3003		 * So, from the user's standpoint, the best thing to do is
3004		 * allocate what he thinks is a reasonable buffer length,
3005		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3006		 * double the buffer length and try again.  (And repeat
3007		 * that until he succeeds.)
3008		 */
3009		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3010		if (sb == NULL) {
3011			list->status = CTL_LUN_LIST_ERROR;
3012			snprintf(list->error_str, sizeof(list->error_str),
3013				 "Unable to allocate %d bytes for LUN list",
3014				 list->alloc_len);
3015			break;
3016		}
3017
3018		sbuf_printf(sb, "<ctllunlist>\n");
3019
3020		mtx_lock(&softc->ctl_lock);
3021		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3022			mtx_lock(&lun->lun_lock);
3023			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3024					     (uintmax_t)lun->lun);
3025
3026			/*
3027			 * Bail out as soon as we see that we've overfilled
3028			 * the buffer.
3029			 */
3030			if (retval != 0)
3031				break;
3032
3033			retval = sbuf_printf(sb, "\t<backend_type>%s"
3034					     "</backend_type>\n",
3035					     (lun->backend == NULL) ?  "none" :
3036					     lun->backend->name);
3037
3038			if (retval != 0)
3039				break;
3040
3041			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3042					     lun->be_lun->lun_type);
3043
3044			if (retval != 0)
3045				break;
3046
3047			if (lun->backend == NULL) {
3048				retval = sbuf_printf(sb, "</lun>\n");
3049				if (retval != 0)
3050					break;
3051				continue;
3052			}
3053
3054			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3055					     (lun->be_lun->maxlba > 0) ?
3056					     lun->be_lun->maxlba + 1 : 0);
3057
3058			if (retval != 0)
3059				break;
3060
3061			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3062					     lun->be_lun->blocksize);
3063
3064			if (retval != 0)
3065				break;
3066
3067			retval = sbuf_printf(sb, "\t<serial_number>");
3068
3069			if (retval != 0)
3070				break;
3071
3072			retval = ctl_sbuf_printf_esc(sb,
3073						     lun->be_lun->serial_num);
3074
3075			if (retval != 0)
3076				break;
3077
3078			retval = sbuf_printf(sb, "</serial_number>\n");
3079
3080			if (retval != 0)
3081				break;
3082
3083			retval = sbuf_printf(sb, "\t<device_id>");
3084
3085			if (retval != 0)
3086				break;
3087
3088			retval = ctl_sbuf_printf_esc(sb,lun->be_lun->device_id);
3089
3090			if (retval != 0)
3091				break;
3092
3093			retval = sbuf_printf(sb, "</device_id>\n");
3094
3095			if (retval != 0)
3096				break;
3097
3098			if (lun->backend->lun_info != NULL) {
3099				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3100				if (retval != 0)
3101					break;
3102			}
3103			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3104				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3105				    opt->name, opt->value, opt->name);
3106				if (retval != 0)
3107					break;
3108			}
3109
3110			retval = sbuf_printf(sb, "</lun>\n");
3111
3112			if (retval != 0)
3113				break;
3114			mtx_unlock(&lun->lun_lock);
3115		}
3116		if (lun != NULL)
3117			mtx_unlock(&lun->lun_lock);
3118		mtx_unlock(&softc->ctl_lock);
3119
3120		if ((retval != 0)
3121		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3122			retval = 0;
3123			sbuf_delete(sb);
3124			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3125			snprintf(list->error_str, sizeof(list->error_str),
3126				 "Out of space, %d bytes is too small",
3127				 list->alloc_len);
3128			break;
3129		}
3130
3131		sbuf_finish(sb);
3132
3133		retval = copyout(sbuf_data(sb), list->lun_xml,
3134				 sbuf_len(sb) + 1);
3135
3136		list->fill_len = sbuf_len(sb) + 1;
3137		list->status = CTL_LUN_LIST_OK;
3138		sbuf_delete(sb);
3139		break;
3140	}
3141	case CTL_ISCSI: {
3142		struct ctl_iscsi *ci;
3143		struct ctl_frontend *fe;
3144
3145		ci = (struct ctl_iscsi *)addr;
3146
3147		fe = ctl_frontend_find("iscsi");
3148		if (fe == NULL) {
3149			ci->status = CTL_ISCSI_ERROR;
3150			snprintf(ci->error_str, sizeof(ci->error_str),
3151			    "Frontend \"iscsi\" not found.");
3152			break;
3153		}
3154
3155		retval = fe->ioctl(dev, cmd, addr, flag, td);
3156		break;
3157	}
3158	case CTL_PORT_REQ: {
3159		struct ctl_req *req;
3160		struct ctl_frontend *fe;
3161
3162		req = (struct ctl_req *)addr;
3163
3164		fe = ctl_frontend_find(req->driver);
3165		if (fe == NULL) {
3166			req->status = CTL_LUN_ERROR;
3167			snprintf(req->error_str, sizeof(req->error_str),
3168			    "Frontend \"%s\" not found.", req->driver);
3169			break;
3170		}
3171		if (req->num_args > 0) {
3172			req->kern_args = ctl_copyin_args(req->num_args,
3173			    req->args, req->error_str, sizeof(req->error_str));
3174			if (req->kern_args == NULL) {
3175				req->status = CTL_LUN_ERROR;
3176				break;
3177			}
3178		}
3179
3180		retval = fe->ioctl(dev, cmd, addr, flag, td);
3181
3182		if (req->num_args > 0) {
3183			ctl_copyout_args(req->num_args, req->kern_args);
3184			ctl_free_args(req->num_args, req->kern_args);
3185		}
3186		break;
3187	}
3188	case CTL_PORT_LIST: {
3189		struct sbuf *sb;
3190		struct ctl_port *port;
3191		struct ctl_lun_list *list;
3192		struct ctl_option *opt;
3193
3194		list = (struct ctl_lun_list *)addr;
3195
3196		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3197		if (sb == NULL) {
3198			list->status = CTL_LUN_LIST_ERROR;
3199			snprintf(list->error_str, sizeof(list->error_str),
3200				 "Unable to allocate %d bytes for LUN list",
3201				 list->alloc_len);
3202			break;
3203		}
3204
3205		sbuf_printf(sb, "<ctlportlist>\n");
3206
3207		mtx_lock(&softc->ctl_lock);
3208		STAILQ_FOREACH(port, &softc->port_list, links) {
3209			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3210					     (uintmax_t)port->targ_port);
3211
3212			/*
3213			 * Bail out as soon as we see that we've overfilled
3214			 * the buffer.
3215			 */
3216			if (retval != 0)
3217				break;
3218
3219			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3220			    "</frontend_type>\n", port->frontend->name);
3221			if (retval != 0)
3222				break;
3223
3224			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3225					     port->port_type);
3226			if (retval != 0)
3227				break;
3228
3229			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3230			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3231			if (retval != 0)
3232				break;
3233
3234			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3235			    port->port_name);
3236			if (retval != 0)
3237				break;
3238
3239			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3240			    port->physical_port);
3241			if (retval != 0)
3242				break;
3243
3244			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3245			    port->virtual_port);
3246			if (retval != 0)
3247				break;
3248
3249			retval = sbuf_printf(sb, "\t<wwnn>%#jx</wwnn>\n",
3250			    (uintmax_t)port->wwnn);
3251			if (retval != 0)
3252				break;
3253
3254			retval = sbuf_printf(sb, "\t<wwpn>%#jx</wwpn>\n",
3255			    (uintmax_t)port->wwpn);
3256			if (retval != 0)
3257				break;
3258
3259			if (port->port_info != NULL) {
3260				retval = port->port_info(port->onoff_arg, sb);
3261				if (retval != 0)
3262					break;
3263			}
3264			STAILQ_FOREACH(opt, &port->options, links) {
3265				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3266				    opt->name, opt->value, opt->name);
3267				if (retval != 0)
3268					break;
3269			}
3270
3271			retval = sbuf_printf(sb, "</targ_port>\n");
3272			if (retval != 0)
3273				break;
3274		}
3275		mtx_unlock(&softc->ctl_lock);
3276
3277		if ((retval != 0)
3278		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3279			retval = 0;
3280			sbuf_delete(sb);
3281			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3282			snprintf(list->error_str, sizeof(list->error_str),
3283				 "Out of space, %d bytes is too small",
3284				 list->alloc_len);
3285			break;
3286		}
3287
3288		sbuf_finish(sb);
3289
3290		retval = copyout(sbuf_data(sb), list->lun_xml,
3291				 sbuf_len(sb) + 1);
3292
3293		list->fill_len = sbuf_len(sb) + 1;
3294		list->status = CTL_LUN_LIST_OK;
3295		sbuf_delete(sb);
3296		break;
3297	}
3298	default: {
3299		/* XXX KDM should we fix this? */
3300#if 0
3301		struct ctl_backend_driver *backend;
3302		unsigned int type;
3303		int found;
3304
3305		found = 0;
3306
3307		/*
3308		 * We encode the backend type as the ioctl type for backend
3309		 * ioctls.  So parse it out here, and then search for a
3310		 * backend of this type.
3311		 */
3312		type = _IOC_TYPE(cmd);
3313
3314		STAILQ_FOREACH(backend, &softc->be_list, links) {
3315			if (backend->type == type) {
3316				found = 1;
3317				break;
3318			}
3319		}
3320		if (found == 0) {
3321			printf("ctl: unknown ioctl command %#lx or backend "
3322			       "%d\n", cmd, type);
3323			retval = EINVAL;
3324			break;
3325		}
3326		retval = backend->ioctl(dev, cmd, addr, flag, td);
3327#endif
3328		retval = ENOTTY;
3329		break;
3330	}
3331	}
3332	return (retval);
3333}
3334
3335uint32_t
3336ctl_get_initindex(struct ctl_nexus *nexus)
3337{
3338	if (nexus->targ_port < CTL_MAX_PORTS)
3339		return (nexus->initid.id +
3340			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3341	else
3342		return (nexus->initid.id +
3343		       ((nexus->targ_port - CTL_MAX_PORTS) *
3344			CTL_MAX_INIT_PER_PORT));
3345}
3346
3347uint32_t
3348ctl_get_resindex(struct ctl_nexus *nexus)
3349{
3350	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3351}
3352
3353uint32_t
3354ctl_port_idx(int port_num)
3355{
3356	if (port_num < CTL_MAX_PORTS)
3357		return(port_num);
3358	else
3359		return(port_num - CTL_MAX_PORTS);
3360}
3361
3362static uint32_t
3363ctl_map_lun(int port_num, uint32_t lun_id)
3364{
3365	struct ctl_port *port;
3366
3367	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3368	if (port == NULL)
3369		return (UINT32_MAX);
3370	if (port->lun_map == NULL)
3371		return (lun_id);
3372	return (port->lun_map(port->targ_lun_arg, lun_id));
3373}
3374
3375static uint32_t
3376ctl_map_lun_back(int port_num, uint32_t lun_id)
3377{
3378	struct ctl_port *port;
3379	uint32_t i;
3380
3381	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3382	if (port->lun_map == NULL)
3383		return (lun_id);
3384	for (i = 0; i < CTL_MAX_LUNS; i++) {
3385		if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3386			return (i);
3387	}
3388	return (UINT32_MAX);
3389}
3390
3391/*
3392 * Note:  This only works for bitmask sizes that are at least 32 bits, and
3393 * that are a power of 2.
3394 */
3395int
3396ctl_ffz(uint32_t *mask, uint32_t size)
3397{
3398	uint32_t num_chunks, num_pieces;
3399	int i, j;
3400
3401	num_chunks = (size >> 5);
3402	if (num_chunks == 0)
3403		num_chunks++;
3404	num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3405
3406	for (i = 0; i < num_chunks; i++) {
3407		for (j = 0; j < num_pieces; j++) {
3408			if ((mask[i] & (1 << j)) == 0)
3409				return ((i << 5) + j);
3410		}
3411	}
3412
3413	return (-1);
3414}
3415
3416int
3417ctl_set_mask(uint32_t *mask, uint32_t bit)
3418{
3419	uint32_t chunk, piece;
3420
3421	chunk = bit >> 5;
3422	piece = bit % (sizeof(uint32_t) * 8);
3423
3424	if ((mask[chunk] & (1 << piece)) != 0)
3425		return (-1);
3426	else
3427		mask[chunk] |= (1 << piece);
3428
3429	return (0);
3430}
3431
3432int
3433ctl_clear_mask(uint32_t *mask, uint32_t bit)
3434{
3435	uint32_t chunk, piece;
3436
3437	chunk = bit >> 5;
3438	piece = bit % (sizeof(uint32_t) * 8);
3439
3440	if ((mask[chunk] & (1 << piece)) == 0)
3441		return (-1);
3442	else
3443		mask[chunk] &= ~(1 << piece);
3444
3445	return (0);
3446}
3447
3448int
3449ctl_is_set(uint32_t *mask, uint32_t bit)
3450{
3451	uint32_t chunk, piece;
3452
3453	chunk = bit >> 5;
3454	piece = bit % (sizeof(uint32_t) * 8);
3455
3456	if ((mask[chunk] & (1 << piece)) == 0)
3457		return (0);
3458	else
3459		return (1);
3460}
3461
3462#ifdef unused
3463/*
3464 * The bus, target and lun are optional, they can be filled in later.
3465 * can_wait is used to determine whether we can wait on the malloc or not.
3466 */
3467union ctl_io*
3468ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3469	      uint32_t targ_lun, int can_wait)
3470{
3471	union ctl_io *io;
3472
3473	if (can_wait)
3474		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3475	else
3476		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3477
3478	if (io != NULL) {
3479		io->io_hdr.io_type = io_type;
3480		io->io_hdr.targ_port = targ_port;
3481		/*
3482		 * XXX KDM this needs to change/go away.  We need to move
3483		 * to a preallocated pool of ctl_scsiio structures.
3484		 */
3485		io->io_hdr.nexus.targ_target.id = targ_target;
3486		io->io_hdr.nexus.targ_lun = targ_lun;
3487	}
3488
3489	return (io);
3490}
3491
3492void
3493ctl_kfree_io(union ctl_io *io)
3494{
3495	free(io, M_CTL);
3496}
3497#endif /* unused */
3498
3499/*
3500 * ctl_softc, pool_type, total_ctl_io are passed in.
3501 * npool is passed out.
3502 */
3503int
3504ctl_pool_create(struct ctl_softc *ctl_softc, ctl_pool_type pool_type,
3505		uint32_t total_ctl_io, struct ctl_io_pool **npool)
3506{
3507	uint32_t i;
3508	union ctl_io *cur_io, *next_io;
3509	struct ctl_io_pool *pool;
3510	int retval;
3511
3512	retval = 0;
3513
3514	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3515					    M_NOWAIT | M_ZERO);
3516	if (pool == NULL) {
3517		retval = ENOMEM;
3518		goto bailout;
3519	}
3520
3521	pool->type = pool_type;
3522	pool->ctl_softc = ctl_softc;
3523
3524	mtx_lock(&ctl_softc->pool_lock);
3525	pool->id = ctl_softc->cur_pool_id++;
3526	mtx_unlock(&ctl_softc->pool_lock);
3527
3528	pool->flags = CTL_POOL_FLAG_NONE;
3529	pool->refcount = 1;		/* Reference for validity. */
3530	STAILQ_INIT(&pool->free_queue);
3531
3532	/*
3533	 * XXX KDM other options here:
3534	 * - allocate a page at a time
3535	 * - allocate one big chunk of memory.
3536	 * Page allocation might work well, but would take a little more
3537	 * tracking.
3538	 */
3539	for (i = 0; i < total_ctl_io; i++) {
3540		cur_io = (union ctl_io *)malloc(sizeof(*cur_io), M_CTLIO,
3541						M_NOWAIT);
3542		if (cur_io == NULL) {
3543			retval = ENOMEM;
3544			break;
3545		}
3546		cur_io->io_hdr.pool = pool;
3547		STAILQ_INSERT_TAIL(&pool->free_queue, &cur_io->io_hdr, links);
3548		pool->total_ctl_io++;
3549		pool->free_ctl_io++;
3550	}
3551
3552	if (retval != 0) {
3553		for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3554		     cur_io != NULL; cur_io = next_io) {
3555			next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3556							      links);
3557			STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr,
3558				      ctl_io_hdr, links);
3559			free(cur_io, M_CTLIO);
3560		}
3561
3562		free(pool, M_CTL);
3563		goto bailout;
3564	}
3565	mtx_lock(&ctl_softc->pool_lock);
3566	ctl_softc->num_pools++;
3567	STAILQ_INSERT_TAIL(&ctl_softc->io_pools, pool, links);
3568	/*
3569	 * Increment our usage count if this is an external consumer, so we
3570	 * can't get unloaded until the external consumer (most likely a
3571	 * FETD) unloads and frees his pool.
3572	 *
3573	 * XXX KDM will this increment the caller's module use count, or
3574	 * mine?
3575	 */
3576#if 0
3577	if ((pool_type != CTL_POOL_EMERGENCY)
3578	 && (pool_type != CTL_POOL_INTERNAL)
3579	 && (pool_type != CTL_POOL_4OTHERSC))
3580		MOD_INC_USE_COUNT;
3581#endif
3582
3583	mtx_unlock(&ctl_softc->pool_lock);
3584
3585	*npool = pool;
3586
3587bailout:
3588
3589	return (retval);
3590}
3591
3592static int
3593ctl_pool_acquire(struct ctl_io_pool *pool)
3594{
3595
3596	mtx_assert(&pool->ctl_softc->pool_lock, MA_OWNED);
3597
3598	if (pool->flags & CTL_POOL_FLAG_INVALID)
3599		return (EINVAL);
3600
3601	pool->refcount++;
3602
3603	return (0);
3604}
3605
3606static void
3607ctl_pool_release(struct ctl_io_pool *pool)
3608{
3609	struct ctl_softc *ctl_softc = pool->ctl_softc;
3610	union ctl_io *io;
3611
3612	mtx_assert(&ctl_softc->pool_lock, MA_OWNED);
3613
3614	if (--pool->refcount != 0)
3615		return;
3616
3617	while ((io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue)) != NULL) {
3618		STAILQ_REMOVE(&pool->free_queue, &io->io_hdr, ctl_io_hdr,
3619			      links);
3620		free(io, M_CTLIO);
3621	}
3622
3623	STAILQ_REMOVE(&ctl_softc->io_pools, pool, ctl_io_pool, links);
3624	ctl_softc->num_pools--;
3625
3626	/*
3627	 * XXX KDM will this decrement the caller's usage count or mine?
3628	 */
3629#if 0
3630	if ((pool->type != CTL_POOL_EMERGENCY)
3631	 && (pool->type != CTL_POOL_INTERNAL)
3632	 && (pool->type != CTL_POOL_4OTHERSC))
3633		MOD_DEC_USE_COUNT;
3634#endif
3635
3636	free(pool, M_CTL);
3637}
3638
3639void
3640ctl_pool_free(struct ctl_io_pool *pool)
3641{
3642	struct ctl_softc *ctl_softc;
3643
3644	if (pool == NULL)
3645		return;
3646
3647	ctl_softc = pool->ctl_softc;
3648	mtx_lock(&ctl_softc->pool_lock);
3649	pool->flags |= CTL_POOL_FLAG_INVALID;
3650	ctl_pool_release(pool);
3651	mtx_unlock(&ctl_softc->pool_lock);
3652}
3653
3654/*
3655 * This routine does not block (except for spinlocks of course).
3656 * It tries to allocate a ctl_io union from the caller's pool as quickly as
3657 * possible.
3658 */
3659union ctl_io *
3660ctl_alloc_io(void *pool_ref)
3661{
3662	union ctl_io *io;
3663	struct ctl_softc *ctl_softc;
3664	struct ctl_io_pool *pool, *npool;
3665	struct ctl_io_pool *emergency_pool;
3666
3667	pool = (struct ctl_io_pool *)pool_ref;
3668
3669	if (pool == NULL) {
3670		printf("%s: pool is NULL\n", __func__);
3671		return (NULL);
3672	}
3673
3674	emergency_pool = NULL;
3675
3676	ctl_softc = pool->ctl_softc;
3677
3678	mtx_lock(&ctl_softc->pool_lock);
3679	/*
3680	 * First, try to get the io structure from the user's pool.
3681	 */
3682	if (ctl_pool_acquire(pool) == 0) {
3683		io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3684		if (io != NULL) {
3685			STAILQ_REMOVE_HEAD(&pool->free_queue, links);
3686			pool->total_allocated++;
3687			pool->free_ctl_io--;
3688			mtx_unlock(&ctl_softc->pool_lock);
3689			return (io);
3690		} else
3691			ctl_pool_release(pool);
3692	}
3693	/*
3694	 * If he doesn't have any io structures left, search for an
3695	 * emergency pool and grab one from there.
3696	 */
3697	STAILQ_FOREACH(npool, &ctl_softc->io_pools, links) {
3698		if (npool->type != CTL_POOL_EMERGENCY)
3699			continue;
3700
3701		if (ctl_pool_acquire(npool) != 0)
3702			continue;
3703
3704		emergency_pool = npool;
3705
3706		io = (union ctl_io *)STAILQ_FIRST(&npool->free_queue);
3707		if (io != NULL) {
3708			STAILQ_REMOVE_HEAD(&npool->free_queue, links);
3709			npool->total_allocated++;
3710			npool->free_ctl_io--;
3711			mtx_unlock(&ctl_softc->pool_lock);
3712			return (io);
3713		} else
3714			ctl_pool_release(npool);
3715	}
3716
3717	/* Drop the spinlock before we malloc */
3718	mtx_unlock(&ctl_softc->pool_lock);
3719
3720	/*
3721	 * The emergency pool (if it exists) didn't have one, so try an
3722	 * atomic (i.e. nonblocking) malloc and see if we get lucky.
3723	 */
3724	io = (union ctl_io *)malloc(sizeof(*io), M_CTLIO, M_NOWAIT);
3725	if (io != NULL) {
3726		/*
3727		 * If the emergency pool exists but is empty, add this
3728		 * ctl_io to its list when it gets freed.
3729		 */
3730		if (emergency_pool != NULL) {
3731			mtx_lock(&ctl_softc->pool_lock);
3732			if (ctl_pool_acquire(emergency_pool) == 0) {
3733				io->io_hdr.pool = emergency_pool;
3734				emergency_pool->total_ctl_io++;
3735				/*
3736				 * Need to bump this, otherwise
3737				 * total_allocated and total_freed won't
3738				 * match when we no longer have anything
3739				 * outstanding.
3740				 */
3741				emergency_pool->total_allocated++;
3742			}
3743			mtx_unlock(&ctl_softc->pool_lock);
3744		} else
3745			io->io_hdr.pool = NULL;
3746	}
3747
3748	return (io);
3749}
3750
3751void
3752ctl_free_io(union ctl_io *io)
3753{
3754	if (io == NULL)
3755		return;
3756
3757	/*
3758	 * If this ctl_io has a pool, return it to that pool.
3759	 */
3760	if (io->io_hdr.pool != NULL) {
3761		struct ctl_io_pool *pool;
3762
3763		pool = (struct ctl_io_pool *)io->io_hdr.pool;
3764		mtx_lock(&pool->ctl_softc->pool_lock);
3765		io->io_hdr.io_type = 0xff;
3766		STAILQ_INSERT_TAIL(&pool->free_queue, &io->io_hdr, links);
3767		pool->total_freed++;
3768		pool->free_ctl_io++;
3769		ctl_pool_release(pool);
3770		mtx_unlock(&pool->ctl_softc->pool_lock);
3771	} else {
3772		/*
3773		 * Otherwise, just free it.  We probably malloced it and
3774		 * the emergency pool wasn't available.
3775		 */
3776		free(io, M_CTLIO);
3777	}
3778
3779}
3780
3781void
3782ctl_zero_io(union ctl_io *io)
3783{
3784	void *pool_ref;
3785
3786	if (io == NULL)
3787		return;
3788
3789	/*
3790	 * May need to preserve linked list pointers at some point too.
3791	 */
3792	pool_ref = io->io_hdr.pool;
3793
3794	memset(io, 0, sizeof(*io));
3795
3796	io->io_hdr.pool = pool_ref;
3797}
3798
3799/*
3800 * This routine is currently used for internal copies of ctl_ios that need
3801 * to persist for some reason after we've already returned status to the
3802 * FETD.  (Thus the flag set.)
3803 *
3804 * XXX XXX
3805 * Note that this makes a blind copy of all fields in the ctl_io, except
3806 * for the pool reference.  This includes any memory that has been
3807 * allocated!  That memory will no longer be valid after done has been
3808 * called, so this would be VERY DANGEROUS for command that actually does
3809 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3810 * start and stop commands, which don't transfer any data, so this is not a
3811 * problem.  If it is used for anything else, the caller would also need to
3812 * allocate data buffer space and this routine would need to be modified to
3813 * copy the data buffer(s) as well.
3814 */
3815void
3816ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3817{
3818	void *pool_ref;
3819
3820	if ((src == NULL)
3821	 || (dest == NULL))
3822		return;
3823
3824	/*
3825	 * May need to preserve linked list pointers at some point too.
3826	 */
3827	pool_ref = dest->io_hdr.pool;
3828
3829	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3830
3831	dest->io_hdr.pool = pool_ref;
3832	/*
3833	 * We need to know that this is an internal copy, and doesn't need
3834	 * to get passed back to the FETD that allocated it.
3835	 */
3836	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3837}
3838
3839#ifdef NEEDTOPORT
3840static void
3841ctl_update_power_subpage(struct copan_power_subpage *page)
3842{
3843	int num_luns, num_partitions, config_type;
3844	struct ctl_softc *softc;
3845	cs_BOOL_t aor_present, shelf_50pct_power;
3846	cs_raidset_personality_t rs_type;
3847	int max_active_luns;
3848
3849	softc = control_softc;
3850
3851	/* subtract out the processor LUN */
3852	num_luns = softc->num_luns - 1;
3853	/*
3854	 * Default to 7 LUNs active, which was the only number we allowed
3855	 * in the past.
3856	 */
3857	max_active_luns = 7;
3858
3859	num_partitions = config_GetRsPartitionInfo();
3860	config_type = config_GetConfigType();
3861	shelf_50pct_power = config_GetShelfPowerMode();
3862	aor_present = config_IsAorRsPresent();
3863
3864	rs_type = ddb_GetRsRaidType(1);
3865	if ((rs_type != CS_RAIDSET_PERSONALITY_RAID5)
3866	 && (rs_type != CS_RAIDSET_PERSONALITY_RAID1)) {
3867		EPRINT(0, "Unsupported RS type %d!", rs_type);
3868	}
3869
3870
3871	page->total_luns = num_luns;
3872
3873	switch (config_type) {
3874	case 40:
3875		/*
3876		 * In a 40 drive configuration, it doesn't matter what DC
3877		 * cards we have, whether we have AOR enabled or not,
3878		 * partitioning or not, or what type of RAIDset we have.
3879		 * In that scenario, we can power up every LUN we present
3880		 * to the user.
3881		 */
3882		max_active_luns = num_luns;
3883
3884		break;
3885	case 64:
3886		if (shelf_50pct_power == CS_FALSE) {
3887			/* 25% power */
3888			if (aor_present == CS_TRUE) {
3889				if (rs_type ==
3890				     CS_RAIDSET_PERSONALITY_RAID5) {
3891					max_active_luns = 7;
3892				} else if (rs_type ==
3893					 CS_RAIDSET_PERSONALITY_RAID1){
3894					max_active_luns = 14;
3895				} else {
3896					/* XXX KDM now what?? */
3897				}
3898			} else {
3899				if (rs_type ==
3900				     CS_RAIDSET_PERSONALITY_RAID5) {
3901					max_active_luns = 8;
3902				} else if (rs_type ==
3903					 CS_RAIDSET_PERSONALITY_RAID1){
3904					max_active_luns = 16;
3905				} else {
3906					/* XXX KDM now what?? */
3907				}
3908			}
3909		} else {
3910			/* 50% power */
3911			/*
3912			 * With 50% power in a 64 drive configuration, we
3913			 * can power all LUNs we present.
3914			 */
3915			max_active_luns = num_luns;
3916		}
3917		break;
3918	case 112:
3919		if (shelf_50pct_power == CS_FALSE) {
3920			/* 25% power */
3921			if (aor_present == CS_TRUE) {
3922				if (rs_type ==
3923				     CS_RAIDSET_PERSONALITY_RAID5) {
3924					max_active_luns = 7;
3925				} else if (rs_type ==
3926					 CS_RAIDSET_PERSONALITY_RAID1){
3927					max_active_luns = 14;
3928				} else {
3929					/* XXX KDM now what?? */
3930				}
3931			} else {
3932				if (rs_type ==
3933				     CS_RAIDSET_PERSONALITY_RAID5) {
3934					max_active_luns = 8;
3935				} else if (rs_type ==
3936					 CS_RAIDSET_PERSONALITY_RAID1){
3937					max_active_luns = 16;
3938				} else {
3939					/* XXX KDM now what?? */
3940				}
3941			}
3942		} else {
3943			/* 50% power */
3944			if (aor_present == CS_TRUE) {
3945				if (rs_type ==
3946				     CS_RAIDSET_PERSONALITY_RAID5) {
3947					max_active_luns = 14;
3948				} else if (rs_type ==
3949					 CS_RAIDSET_PERSONALITY_RAID1){
3950					/*
3951					 * We're assuming here that disk
3952					 * caching is enabled, and so we're
3953					 * able to power up half of each
3954					 * LUN, and cache all writes.
3955					 */
3956					max_active_luns = num_luns;
3957				} else {
3958					/* XXX KDM now what?? */
3959				}
3960			} else {
3961				if (rs_type ==
3962				     CS_RAIDSET_PERSONALITY_RAID5) {
3963					max_active_luns = 15;
3964				} else if (rs_type ==
3965					 CS_RAIDSET_PERSONALITY_RAID1){
3966					max_active_luns = 30;
3967				} else {
3968					/* XXX KDM now what?? */
3969				}
3970			}
3971		}
3972		break;
3973	default:
3974		/*
3975		 * In this case, we have an unknown configuration, so we
3976		 * just use the default from above.
3977		 */
3978		break;
3979	}
3980
3981	page->max_active_luns = max_active_luns;
3982#if 0
3983	printk("%s: total_luns = %d, max_active_luns = %d\n", __func__,
3984	       page->total_luns, page->max_active_luns);
3985#endif
3986}
3987#endif /* NEEDTOPORT */
3988
3989/*
3990 * This routine could be used in the future to load default and/or saved
3991 * mode page parameters for a particuar lun.
3992 */
3993static int
3994ctl_init_page_index(struct ctl_lun *lun)
3995{
3996	int i;
3997	struct ctl_page_index *page_index;
3998	struct ctl_softc *softc;
3999
4000	memcpy(&lun->mode_pages.index, page_index_template,
4001	       sizeof(page_index_template));
4002
4003	softc = lun->ctl_softc;
4004
4005	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4006
4007		page_index = &lun->mode_pages.index[i];
4008		/*
4009		 * If this is a disk-only mode page, there's no point in
4010		 * setting it up.  For some pages, we have to have some
4011		 * basic information about the disk in order to calculate the
4012		 * mode page data.
4013		 */
4014		if ((lun->be_lun->lun_type != T_DIRECT)
4015		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4016			continue;
4017
4018		switch (page_index->page_code & SMPH_PC_MASK) {
4019		case SMS_FORMAT_DEVICE_PAGE: {
4020			struct scsi_format_page *format_page;
4021
4022			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4023				panic("subpage is incorrect!");
4024
4025			/*
4026			 * Sectors per track are set above.  Bytes per
4027			 * sector need to be set here on a per-LUN basis.
4028			 */
4029			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4030			       &format_page_default,
4031			       sizeof(format_page_default));
4032			memcpy(&lun->mode_pages.format_page[
4033			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4034			       sizeof(format_page_changeable));
4035			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4036			       &format_page_default,
4037			       sizeof(format_page_default));
4038			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4039			       &format_page_default,
4040			       sizeof(format_page_default));
4041
4042			format_page = &lun->mode_pages.format_page[
4043				CTL_PAGE_CURRENT];
4044			scsi_ulto2b(lun->be_lun->blocksize,
4045				    format_page->bytes_per_sector);
4046
4047			format_page = &lun->mode_pages.format_page[
4048				CTL_PAGE_DEFAULT];
4049			scsi_ulto2b(lun->be_lun->blocksize,
4050				    format_page->bytes_per_sector);
4051
4052			format_page = &lun->mode_pages.format_page[
4053				CTL_PAGE_SAVED];
4054			scsi_ulto2b(lun->be_lun->blocksize,
4055				    format_page->bytes_per_sector);
4056
4057			page_index->page_data =
4058				(uint8_t *)lun->mode_pages.format_page;
4059			break;
4060		}
4061		case SMS_RIGID_DISK_PAGE: {
4062			struct scsi_rigid_disk_page *rigid_disk_page;
4063			uint32_t sectors_per_cylinder;
4064			uint64_t cylinders;
4065#ifndef	__XSCALE__
4066			int shift;
4067#endif /* !__XSCALE__ */
4068
4069			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4070				panic("invalid subpage value %d",
4071				      page_index->subpage);
4072
4073			/*
4074			 * Rotation rate and sectors per track are set
4075			 * above.  We calculate the cylinders here based on
4076			 * capacity.  Due to the number of heads and
4077			 * sectors per track we're using, smaller arrays
4078			 * may turn out to have 0 cylinders.  Linux and
4079			 * FreeBSD don't pay attention to these mode pages
4080			 * to figure out capacity, but Solaris does.  It
4081			 * seems to deal with 0 cylinders just fine, and
4082			 * works out a fake geometry based on the capacity.
4083			 */
4084			memcpy(&lun->mode_pages.rigid_disk_page[
4085			       CTL_PAGE_CURRENT], &rigid_disk_page_default,
4086			       sizeof(rigid_disk_page_default));
4087			memcpy(&lun->mode_pages.rigid_disk_page[
4088			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4089			       sizeof(rigid_disk_page_changeable));
4090			memcpy(&lun->mode_pages.rigid_disk_page[
4091			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4092			       sizeof(rigid_disk_page_default));
4093			memcpy(&lun->mode_pages.rigid_disk_page[
4094			       CTL_PAGE_SAVED], &rigid_disk_page_default,
4095			       sizeof(rigid_disk_page_default));
4096
4097			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4098				CTL_DEFAULT_HEADS;
4099
4100			/*
4101			 * The divide method here will be more accurate,
4102			 * probably, but results in floating point being
4103			 * used in the kernel on i386 (__udivdi3()).  On the
4104			 * XScale, though, __udivdi3() is implemented in
4105			 * software.
4106			 *
4107			 * The shift method for cylinder calculation is
4108			 * accurate if sectors_per_cylinder is a power of
4109			 * 2.  Otherwise it might be slightly off -- you
4110			 * might have a bit of a truncation problem.
4111			 */
4112#ifdef	__XSCALE__
4113			cylinders = (lun->be_lun->maxlba + 1) /
4114				sectors_per_cylinder;
4115#else
4116			for (shift = 31; shift > 0; shift--) {
4117				if (sectors_per_cylinder & (1 << shift))
4118					break;
4119			}
4120			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4121#endif
4122
4123			/*
4124			 * We've basically got 3 bytes, or 24 bits for the
4125			 * cylinder size in the mode page.  If we're over,
4126			 * just round down to 2^24.
4127			 */
4128			if (cylinders > 0xffffff)
4129				cylinders = 0xffffff;
4130
4131			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4132				CTL_PAGE_CURRENT];
4133			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4134
4135			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4136				CTL_PAGE_DEFAULT];
4137			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4138
4139			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4140				CTL_PAGE_SAVED];
4141			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4142
4143			page_index->page_data =
4144				(uint8_t *)lun->mode_pages.rigid_disk_page;
4145			break;
4146		}
4147		case SMS_CACHING_PAGE: {
4148
4149			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4150				panic("invalid subpage value %d",
4151				      page_index->subpage);
4152			/*
4153			 * Defaults should be okay here, no calculations
4154			 * needed.
4155			 */
4156			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4157			       &caching_page_default,
4158			       sizeof(caching_page_default));
4159			memcpy(&lun->mode_pages.caching_page[
4160			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4161			       sizeof(caching_page_changeable));
4162			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4163			       &caching_page_default,
4164			       sizeof(caching_page_default));
4165			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4166			       &caching_page_default,
4167			       sizeof(caching_page_default));
4168			page_index->page_data =
4169				(uint8_t *)lun->mode_pages.caching_page;
4170			break;
4171		}
4172		case SMS_CONTROL_MODE_PAGE: {
4173
4174			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4175				panic("invalid subpage value %d",
4176				      page_index->subpage);
4177
4178			/*
4179			 * Defaults should be okay here, no calculations
4180			 * needed.
4181			 */
4182			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4183			       &control_page_default,
4184			       sizeof(control_page_default));
4185			memcpy(&lun->mode_pages.control_page[
4186			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4187			       sizeof(control_page_changeable));
4188			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4189			       &control_page_default,
4190			       sizeof(control_page_default));
4191			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4192			       &control_page_default,
4193			       sizeof(control_page_default));
4194			page_index->page_data =
4195				(uint8_t *)lun->mode_pages.control_page;
4196			break;
4197
4198		}
4199		case SMS_VENDOR_SPECIFIC_PAGE:{
4200			switch (page_index->subpage) {
4201			case PWR_SUBPAGE_CODE: {
4202				struct copan_power_subpage *current_page,
4203							   *saved_page;
4204
4205				memcpy(&lun->mode_pages.power_subpage[
4206				       CTL_PAGE_CURRENT],
4207				       &power_page_default,
4208				       sizeof(power_page_default));
4209				memcpy(&lun->mode_pages.power_subpage[
4210				       CTL_PAGE_CHANGEABLE],
4211				       &power_page_changeable,
4212				       sizeof(power_page_changeable));
4213				memcpy(&lun->mode_pages.power_subpage[
4214				       CTL_PAGE_DEFAULT],
4215				       &power_page_default,
4216				       sizeof(power_page_default));
4217				memcpy(&lun->mode_pages.power_subpage[
4218				       CTL_PAGE_SAVED],
4219				       &power_page_default,
4220				       sizeof(power_page_default));
4221				page_index->page_data =
4222				    (uint8_t *)lun->mode_pages.power_subpage;
4223
4224				current_page = (struct copan_power_subpage *)
4225					(page_index->page_data +
4226					 (page_index->page_len *
4227					  CTL_PAGE_CURRENT));
4228			        saved_page = (struct copan_power_subpage *)
4229				        (page_index->page_data +
4230					 (page_index->page_len *
4231					  CTL_PAGE_SAVED));
4232				break;
4233			}
4234			case APS_SUBPAGE_CODE: {
4235				struct copan_aps_subpage *current_page,
4236							 *saved_page;
4237
4238				// This gets set multiple times but
4239				// it should always be the same. It's
4240				// only done during init so who cares.
4241				index_to_aps_page = i;
4242
4243				memcpy(&lun->mode_pages.aps_subpage[
4244				       CTL_PAGE_CURRENT],
4245				       &aps_page_default,
4246				       sizeof(aps_page_default));
4247				memcpy(&lun->mode_pages.aps_subpage[
4248				       CTL_PAGE_CHANGEABLE],
4249				       &aps_page_changeable,
4250				       sizeof(aps_page_changeable));
4251				memcpy(&lun->mode_pages.aps_subpage[
4252				       CTL_PAGE_DEFAULT],
4253				       &aps_page_default,
4254				       sizeof(aps_page_default));
4255				memcpy(&lun->mode_pages.aps_subpage[
4256				       CTL_PAGE_SAVED],
4257				       &aps_page_default,
4258				       sizeof(aps_page_default));
4259				page_index->page_data =
4260					(uint8_t *)lun->mode_pages.aps_subpage;
4261
4262				current_page = (struct copan_aps_subpage *)
4263					(page_index->page_data +
4264					 (page_index->page_len *
4265					  CTL_PAGE_CURRENT));
4266				saved_page = (struct copan_aps_subpage *)
4267					(page_index->page_data +
4268					 (page_index->page_len *
4269					  CTL_PAGE_SAVED));
4270				break;
4271			}
4272			case DBGCNF_SUBPAGE_CODE: {
4273				struct copan_debugconf_subpage *current_page,
4274							       *saved_page;
4275
4276				memcpy(&lun->mode_pages.debugconf_subpage[
4277				       CTL_PAGE_CURRENT],
4278				       &debugconf_page_default,
4279				       sizeof(debugconf_page_default));
4280				memcpy(&lun->mode_pages.debugconf_subpage[
4281				       CTL_PAGE_CHANGEABLE],
4282				       &debugconf_page_changeable,
4283				       sizeof(debugconf_page_changeable));
4284				memcpy(&lun->mode_pages.debugconf_subpage[
4285				       CTL_PAGE_DEFAULT],
4286				       &debugconf_page_default,
4287				       sizeof(debugconf_page_default));
4288				memcpy(&lun->mode_pages.debugconf_subpage[
4289				       CTL_PAGE_SAVED],
4290				       &debugconf_page_default,
4291				       sizeof(debugconf_page_default));
4292				page_index->page_data =
4293					(uint8_t *)lun->mode_pages.debugconf_subpage;
4294
4295				current_page = (struct copan_debugconf_subpage *)
4296					(page_index->page_data +
4297					 (page_index->page_len *
4298					  CTL_PAGE_CURRENT));
4299				saved_page = (struct copan_debugconf_subpage *)
4300					(page_index->page_data +
4301					 (page_index->page_len *
4302					  CTL_PAGE_SAVED));
4303				break;
4304			}
4305			default:
4306				panic("invalid subpage value %d",
4307				      page_index->subpage);
4308				break;
4309			}
4310   			break;
4311		}
4312		default:
4313			panic("invalid page value %d",
4314			      page_index->page_code & SMPH_PC_MASK);
4315			break;
4316    	}
4317	}
4318
4319	return (CTL_RETVAL_COMPLETE);
4320}
4321
4322/*
4323 * LUN allocation.
4324 *
4325 * Requirements:
4326 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4327 *   wants us to allocate the LUN and he can block.
4328 * - ctl_softc is always set
4329 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4330 *
4331 * Returns 0 for success, non-zero (errno) for failure.
4332 */
4333static int
4334ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4335	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4336{
4337	struct ctl_lun *nlun, *lun;
4338	struct ctl_port *port;
4339	struct scsi_vpd_id_descriptor *desc;
4340	struct scsi_vpd_id_t10 *t10id;
4341	const char *scsiname, *vendor;
4342	int lun_number, i, lun_malloced;
4343	int devidlen, idlen1, idlen2 = 0, len;
4344
4345	if (be_lun == NULL)
4346		return (EINVAL);
4347
4348	/*
4349	 * We currently only support Direct Access or Processor LUN types.
4350	 */
4351	switch (be_lun->lun_type) {
4352	case T_DIRECT:
4353		break;
4354	case T_PROCESSOR:
4355		break;
4356	case T_SEQUENTIAL:
4357	case T_CHANGER:
4358	default:
4359		be_lun->lun_config_status(be_lun->be_lun,
4360					  CTL_LUN_CONFIG_FAILURE);
4361		break;
4362	}
4363	if (ctl_lun == NULL) {
4364		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4365		lun_malloced = 1;
4366	} else {
4367		lun_malloced = 0;
4368		lun = ctl_lun;
4369	}
4370
4371	memset(lun, 0, sizeof(*lun));
4372	if (lun_malloced)
4373		lun->flags = CTL_LUN_MALLOCED;
4374
4375	/* Generate LUN ID. */
4376	devidlen = max(CTL_DEVID_MIN_LEN,
4377	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4378	idlen1 = sizeof(*t10id) + devidlen;
4379	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4380	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4381	if (scsiname != NULL) {
4382		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4383		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4384	}
4385	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4386	    M_CTL, M_WAITOK | M_ZERO);
4387	lun->lun_devid->len = len;
4388	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4389	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4390	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4391	desc->length = idlen1;
4392	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4393	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4394	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4395		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4396	} else {
4397		strncpy(t10id->vendor, vendor,
4398		    min(sizeof(t10id->vendor), strlen(vendor)));
4399	}
4400	strncpy((char *)t10id->vendor_spec_id,
4401	    (char *)be_lun->device_id, devidlen);
4402	if (scsiname != NULL) {
4403		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4404		    desc->length);
4405		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4406		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4407		    SVPD_ID_TYPE_SCSI_NAME;
4408		desc->length = idlen2;
4409		strlcpy(desc->identifier, scsiname, idlen2);
4410	}
4411
4412	mtx_lock(&ctl_softc->ctl_lock);
4413	/*
4414	 * See if the caller requested a particular LUN number.  If so, see
4415	 * if it is available.  Otherwise, allocate the first available LUN.
4416	 */
4417	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4418		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4419		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4420			mtx_unlock(&ctl_softc->ctl_lock);
4421			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4422				printf("ctl: requested LUN ID %d is higher "
4423				       "than CTL_MAX_LUNS - 1 (%d)\n",
4424				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4425			} else {
4426				/*
4427				 * XXX KDM return an error, or just assign
4428				 * another LUN ID in this case??
4429				 */
4430				printf("ctl: requested LUN ID %d is already "
4431				       "in use\n", be_lun->req_lun_id);
4432			}
4433			if (lun->flags & CTL_LUN_MALLOCED)
4434				free(lun, M_CTL);
4435			be_lun->lun_config_status(be_lun->be_lun,
4436						  CTL_LUN_CONFIG_FAILURE);
4437			return (ENOSPC);
4438		}
4439		lun_number = be_lun->req_lun_id;
4440	} else {
4441		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4442		if (lun_number == -1) {
4443			mtx_unlock(&ctl_softc->ctl_lock);
4444			printf("ctl: can't allocate LUN on target %ju, out of "
4445			       "LUNs\n", (uintmax_t)target_id.id);
4446			if (lun->flags & CTL_LUN_MALLOCED)
4447				free(lun, M_CTL);
4448			be_lun->lun_config_status(be_lun->be_lun,
4449						  CTL_LUN_CONFIG_FAILURE);
4450			return (ENOSPC);
4451		}
4452	}
4453	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4454
4455	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4456	lun->target = target_id;
4457	lun->lun = lun_number;
4458	lun->be_lun = be_lun;
4459	/*
4460	 * The processor LUN is always enabled.  Disk LUNs come on line
4461	 * disabled, and must be enabled by the backend.
4462	 */
4463	lun->flags |= CTL_LUN_DISABLED;
4464	lun->backend = be_lun->be;
4465	be_lun->ctl_lun = lun;
4466	be_lun->lun_id = lun_number;
4467	atomic_add_int(&be_lun->be->num_luns, 1);
4468	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4469		lun->flags |= CTL_LUN_STOPPED;
4470
4471	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4472		lun->flags |= CTL_LUN_INOPERABLE;
4473
4474	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4475		lun->flags |= CTL_LUN_PRIMARY_SC;
4476
4477	lun->ctl_softc = ctl_softc;
4478	TAILQ_INIT(&lun->ooa_queue);
4479	TAILQ_INIT(&lun->blocked_queue);
4480	STAILQ_INIT(&lun->error_list);
4481
4482	/*
4483	 * Initialize the mode page index.
4484	 */
4485	ctl_init_page_index(lun);
4486
4487	/*
4488	 * Set the poweron UA for all initiators on this LUN only.
4489	 */
4490	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4491		lun->pending_sense[i].ua_pending = CTL_UA_POWERON;
4492
4493	/*
4494	 * Now, before we insert this lun on the lun list, set the lun
4495	 * inventory changed UA for all other luns.
4496	 */
4497	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4498		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4499			nlun->pending_sense[i].ua_pending |= CTL_UA_LUN_CHANGE;
4500		}
4501	}
4502
4503	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4504
4505	ctl_softc->ctl_luns[lun_number] = lun;
4506
4507	ctl_softc->num_luns++;
4508
4509	/* Setup statistics gathering */
4510	lun->stats.device_type = be_lun->lun_type;
4511	lun->stats.lun_number = lun_number;
4512	if (lun->stats.device_type == T_DIRECT)
4513		lun->stats.blocksize = be_lun->blocksize;
4514	else
4515		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4516	for (i = 0;i < CTL_MAX_PORTS;i++)
4517		lun->stats.ports[i].targ_port = i;
4518
4519	mtx_unlock(&ctl_softc->ctl_lock);
4520
4521	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4522
4523	/*
4524	 * Run through each registered FETD and bring it online if it isn't
4525	 * already.  Enable the target ID if it hasn't been enabled, and
4526	 * enable this particular LUN.
4527	 */
4528	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4529		int retval;
4530
4531		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4532		if (retval != 0) {
4533			printf("ctl_alloc_lun: FETD %s port %d returned error "
4534			       "%d for lun_enable on target %ju lun %d\n",
4535			       port->port_name, port->targ_port, retval,
4536			       (uintmax_t)target_id.id, lun_number);
4537		} else
4538			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4539	}
4540	return (0);
4541}
4542
4543/*
4544 * Delete a LUN.
4545 * Assumptions:
4546 * - LUN has already been marked invalid and any pending I/O has been taken
4547 *   care of.
4548 */
4549static int
4550ctl_free_lun(struct ctl_lun *lun)
4551{
4552	struct ctl_softc *softc;
4553#if 0
4554	struct ctl_port *port;
4555#endif
4556	struct ctl_lun *nlun;
4557	int i;
4558
4559	softc = lun->ctl_softc;
4560
4561	mtx_assert(&softc->ctl_lock, MA_OWNED);
4562
4563	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4564
4565	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4566
4567	softc->ctl_luns[lun->lun] = NULL;
4568
4569	if (!TAILQ_EMPTY(&lun->ooa_queue))
4570		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4571
4572	softc->num_luns--;
4573
4574	/*
4575	 * XXX KDM this scheme only works for a single target/multiple LUN
4576	 * setup.  It needs to be revamped for a multiple target scheme.
4577	 *
4578	 * XXX KDM this results in port->lun_disable() getting called twice,
4579	 * once when ctl_disable_lun() is called, and a second time here.
4580	 * We really need to re-think the LUN disable semantics.  There
4581	 * should probably be several steps/levels to LUN removal:
4582	 *  - disable
4583	 *  - invalidate
4584	 *  - free
4585 	 *
4586	 * Right now we only have a disable method when communicating to
4587	 * the front end ports, at least for individual LUNs.
4588	 */
4589#if 0
4590	STAILQ_FOREACH(port, &softc->port_list, links) {
4591		int retval;
4592
4593		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4594					 lun->lun);
4595		if (retval != 0) {
4596			printf("ctl_free_lun: FETD %s port %d returned error "
4597			       "%d for lun_disable on target %ju lun %jd\n",
4598			       port->port_name, port->targ_port, retval,
4599			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4600		}
4601
4602		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4603			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4604
4605			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4606			if (retval != 0) {
4607				printf("ctl_free_lun: FETD %s port %d "
4608				       "returned error %d for targ_disable on "
4609				       "target %ju\n", port->port_name,
4610				       port->targ_port, retval,
4611				       (uintmax_t)lun->target.id);
4612			} else
4613				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4614
4615			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4616				continue;
4617
4618#if 0
4619			port->port_offline(port->onoff_arg);
4620			port->status &= ~CTL_PORT_STATUS_ONLINE;
4621#endif
4622		}
4623	}
4624#endif
4625
4626	/*
4627	 * Tell the backend to free resources, if this LUN has a backend.
4628	 */
4629	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4630	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4631
4632	mtx_destroy(&lun->lun_lock);
4633	free(lun->lun_devid, M_CTL);
4634	if (lun->flags & CTL_LUN_MALLOCED)
4635		free(lun, M_CTL);
4636
4637	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4638		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4639			nlun->pending_sense[i].ua_pending |= CTL_UA_LUN_CHANGE;
4640		}
4641	}
4642
4643	return (0);
4644}
4645
4646static void
4647ctl_create_lun(struct ctl_be_lun *be_lun)
4648{
4649	struct ctl_softc *ctl_softc;
4650
4651	ctl_softc = control_softc;
4652
4653	/*
4654	 * ctl_alloc_lun() should handle all potential failure cases.
4655	 */
4656	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4657}
4658
4659int
4660ctl_add_lun(struct ctl_be_lun *be_lun)
4661{
4662	struct ctl_softc *ctl_softc = control_softc;
4663
4664	mtx_lock(&ctl_softc->ctl_lock);
4665	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4666	mtx_unlock(&ctl_softc->ctl_lock);
4667	wakeup(&ctl_softc->pending_lun_queue);
4668
4669	return (0);
4670}
4671
4672int
4673ctl_enable_lun(struct ctl_be_lun *be_lun)
4674{
4675	struct ctl_softc *ctl_softc;
4676	struct ctl_port *port, *nport;
4677	struct ctl_lun *lun;
4678	int retval;
4679
4680	ctl_softc = control_softc;
4681
4682	lun = (struct ctl_lun *)be_lun->ctl_lun;
4683
4684	mtx_lock(&ctl_softc->ctl_lock);
4685	mtx_lock(&lun->lun_lock);
4686	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4687		/*
4688		 * eh?  Why did we get called if the LUN is already
4689		 * enabled?
4690		 */
4691		mtx_unlock(&lun->lun_lock);
4692		mtx_unlock(&ctl_softc->ctl_lock);
4693		return (0);
4694	}
4695	lun->flags &= ~CTL_LUN_DISABLED;
4696	mtx_unlock(&lun->lun_lock);
4697
4698	for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4699		nport = STAILQ_NEXT(port, links);
4700
4701		/*
4702		 * Drop the lock while we call the FETD's enable routine.
4703		 * This can lead to a callback into CTL (at least in the
4704		 * case of the internal initiator frontend.
4705		 */
4706		mtx_unlock(&ctl_softc->ctl_lock);
4707		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4708		mtx_lock(&ctl_softc->ctl_lock);
4709		if (retval != 0) {
4710			printf("%s: FETD %s port %d returned error "
4711			       "%d for lun_enable on target %ju lun %jd\n",
4712			       __func__, port->port_name, port->targ_port, retval,
4713			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4714		}
4715#if 0
4716		 else {
4717            /* NOTE:  TODO:  why does lun enable affect port status? */
4718			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4719		}
4720#endif
4721	}
4722
4723	mtx_unlock(&ctl_softc->ctl_lock);
4724
4725	return (0);
4726}
4727
4728int
4729ctl_disable_lun(struct ctl_be_lun *be_lun)
4730{
4731	struct ctl_softc *ctl_softc;
4732	struct ctl_port *port;
4733	struct ctl_lun *lun;
4734	int retval;
4735
4736	ctl_softc = control_softc;
4737
4738	lun = (struct ctl_lun *)be_lun->ctl_lun;
4739
4740	mtx_lock(&ctl_softc->ctl_lock);
4741	mtx_lock(&lun->lun_lock);
4742	if (lun->flags & CTL_LUN_DISABLED) {
4743		mtx_unlock(&lun->lun_lock);
4744		mtx_unlock(&ctl_softc->ctl_lock);
4745		return (0);
4746	}
4747	lun->flags |= CTL_LUN_DISABLED;
4748	mtx_unlock(&lun->lun_lock);
4749
4750	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4751		mtx_unlock(&ctl_softc->ctl_lock);
4752		/*
4753		 * Drop the lock before we call the frontend's disable
4754		 * routine, to avoid lock order reversals.
4755		 *
4756		 * XXX KDM what happens if the frontend list changes while
4757		 * we're traversing it?  It's unlikely, but should be handled.
4758		 */
4759		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4760					 lun->lun);
4761		mtx_lock(&ctl_softc->ctl_lock);
4762		if (retval != 0) {
4763			printf("ctl_alloc_lun: FETD %s port %d returned error "
4764			       "%d for lun_disable on target %ju lun %jd\n",
4765			       port->port_name, port->targ_port, retval,
4766			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4767		}
4768	}
4769
4770	mtx_unlock(&ctl_softc->ctl_lock);
4771
4772	return (0);
4773}
4774
4775int
4776ctl_start_lun(struct ctl_be_lun *be_lun)
4777{
4778	struct ctl_softc *ctl_softc;
4779	struct ctl_lun *lun;
4780
4781	ctl_softc = control_softc;
4782
4783	lun = (struct ctl_lun *)be_lun->ctl_lun;
4784
4785	mtx_lock(&lun->lun_lock);
4786	lun->flags &= ~CTL_LUN_STOPPED;
4787	mtx_unlock(&lun->lun_lock);
4788
4789	return (0);
4790}
4791
4792int
4793ctl_stop_lun(struct ctl_be_lun *be_lun)
4794{
4795	struct ctl_softc *ctl_softc;
4796	struct ctl_lun *lun;
4797
4798	ctl_softc = control_softc;
4799
4800	lun = (struct ctl_lun *)be_lun->ctl_lun;
4801
4802	mtx_lock(&lun->lun_lock);
4803	lun->flags |= CTL_LUN_STOPPED;
4804	mtx_unlock(&lun->lun_lock);
4805
4806	return (0);
4807}
4808
4809int
4810ctl_lun_offline(struct ctl_be_lun *be_lun)
4811{
4812	struct ctl_softc *ctl_softc;
4813	struct ctl_lun *lun;
4814
4815	ctl_softc = control_softc;
4816
4817	lun = (struct ctl_lun *)be_lun->ctl_lun;
4818
4819	mtx_lock(&lun->lun_lock);
4820	lun->flags |= CTL_LUN_OFFLINE;
4821	mtx_unlock(&lun->lun_lock);
4822
4823	return (0);
4824}
4825
4826int
4827ctl_lun_online(struct ctl_be_lun *be_lun)
4828{
4829	struct ctl_softc *ctl_softc;
4830	struct ctl_lun *lun;
4831
4832	ctl_softc = control_softc;
4833
4834	lun = (struct ctl_lun *)be_lun->ctl_lun;
4835
4836	mtx_lock(&lun->lun_lock);
4837	lun->flags &= ~CTL_LUN_OFFLINE;
4838	mtx_unlock(&lun->lun_lock);
4839
4840	return (0);
4841}
4842
4843int
4844ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4845{
4846	struct ctl_softc *ctl_softc;
4847	struct ctl_lun *lun;
4848
4849	ctl_softc = control_softc;
4850
4851	lun = (struct ctl_lun *)be_lun->ctl_lun;
4852
4853	mtx_lock(&lun->lun_lock);
4854
4855	/*
4856	 * The LUN needs to be disabled before it can be marked invalid.
4857	 */
4858	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4859		mtx_unlock(&lun->lun_lock);
4860		return (-1);
4861	}
4862	/*
4863	 * Mark the LUN invalid.
4864	 */
4865	lun->flags |= CTL_LUN_INVALID;
4866
4867	/*
4868	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4869	 * If we have something in the OOA queue, we'll free it when the
4870	 * last I/O completes.
4871	 */
4872	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4873		mtx_unlock(&lun->lun_lock);
4874		mtx_lock(&ctl_softc->ctl_lock);
4875		ctl_free_lun(lun);
4876		mtx_unlock(&ctl_softc->ctl_lock);
4877	} else
4878		mtx_unlock(&lun->lun_lock);
4879
4880	return (0);
4881}
4882
4883int
4884ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4885{
4886	struct ctl_softc *ctl_softc;
4887	struct ctl_lun *lun;
4888
4889	ctl_softc = control_softc;
4890	lun = (struct ctl_lun *)be_lun->ctl_lun;
4891
4892	mtx_lock(&lun->lun_lock);
4893	lun->flags |= CTL_LUN_INOPERABLE;
4894	mtx_unlock(&lun->lun_lock);
4895
4896	return (0);
4897}
4898
4899int
4900ctl_lun_operable(struct ctl_be_lun *be_lun)
4901{
4902	struct ctl_softc *ctl_softc;
4903	struct ctl_lun *lun;
4904
4905	ctl_softc = control_softc;
4906	lun = (struct ctl_lun *)be_lun->ctl_lun;
4907
4908	mtx_lock(&lun->lun_lock);
4909	lun->flags &= ~CTL_LUN_INOPERABLE;
4910	mtx_unlock(&lun->lun_lock);
4911
4912	return (0);
4913}
4914
4915int
4916ctl_lun_power_lock(struct ctl_be_lun *be_lun, struct ctl_nexus *nexus,
4917		   int lock)
4918{
4919	struct ctl_softc *softc;
4920	struct ctl_lun *lun;
4921	struct copan_aps_subpage *current_sp;
4922	struct ctl_page_index *page_index;
4923	int i;
4924
4925	softc = control_softc;
4926
4927	mtx_lock(&softc->ctl_lock);
4928
4929	lun = (struct ctl_lun *)be_lun->ctl_lun;
4930	mtx_lock(&lun->lun_lock);
4931
4932	page_index = NULL;
4933	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4934		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
4935		     APS_PAGE_CODE)
4936			continue;
4937
4938		if (lun->mode_pages.index[i].subpage != APS_SUBPAGE_CODE)
4939			continue;
4940		page_index = &lun->mode_pages.index[i];
4941	}
4942
4943	if (page_index == NULL) {
4944		mtx_unlock(&lun->lun_lock);
4945		mtx_unlock(&softc->ctl_lock);
4946		printf("%s: APS subpage not found for lun %ju!\n", __func__,
4947		       (uintmax_t)lun->lun);
4948		return (1);
4949	}
4950#if 0
4951	if ((softc->aps_locked_lun != 0)
4952	 && (softc->aps_locked_lun != lun->lun)) {
4953		printf("%s: attempt to lock LUN %llu when %llu is already "
4954		       "locked\n");
4955		mtx_unlock(&lun->lun_lock);
4956		mtx_unlock(&softc->ctl_lock);
4957		return (1);
4958	}
4959#endif
4960
4961	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
4962		(page_index->page_len * CTL_PAGE_CURRENT));
4963
4964	if (lock != 0) {
4965		current_sp->lock_active = APS_LOCK_ACTIVE;
4966		softc->aps_locked_lun = lun->lun;
4967	} else {
4968		current_sp->lock_active = 0;
4969		softc->aps_locked_lun = 0;
4970	}
4971
4972
4973	/*
4974	 * If we're in HA mode, try to send the lock message to the other
4975	 * side.
4976	 */
4977	if (ctl_is_single == 0) {
4978		int isc_retval;
4979		union ctl_ha_msg lock_msg;
4980
4981		lock_msg.hdr.nexus = *nexus;
4982		lock_msg.hdr.msg_type = CTL_MSG_APS_LOCK;
4983		if (lock != 0)
4984			lock_msg.aps.lock_flag = 1;
4985		else
4986			lock_msg.aps.lock_flag = 0;
4987		isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &lock_msg,
4988					 sizeof(lock_msg), 0);
4989		if (isc_retval > CTL_HA_STATUS_SUCCESS) {
4990			printf("%s: APS (lock=%d) error returned from "
4991			       "ctl_ha_msg_send: %d\n", __func__, lock, isc_retval);
4992			mtx_unlock(&lun->lun_lock);
4993			mtx_unlock(&softc->ctl_lock);
4994			return (1);
4995		}
4996	}
4997
4998	mtx_unlock(&lun->lun_lock);
4999	mtx_unlock(&softc->ctl_lock);
5000
5001	return (0);
5002}
5003
5004void
5005ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5006{
5007	struct ctl_lun *lun;
5008	struct ctl_softc *softc;
5009	int i;
5010
5011	softc = control_softc;
5012
5013	lun = (struct ctl_lun *)be_lun->ctl_lun;
5014
5015	mtx_lock(&lun->lun_lock);
5016
5017	for (i = 0; i < CTL_MAX_INITIATORS; i++)
5018		lun->pending_sense[i].ua_pending |= CTL_UA_CAPACITY_CHANGED;
5019
5020	mtx_unlock(&lun->lun_lock);
5021}
5022
5023/*
5024 * Backend "memory move is complete" callback for requests that never
5025 * make it down to say RAIDCore's configuration code.
5026 */
5027int
5028ctl_config_move_done(union ctl_io *io)
5029{
5030	int retval;
5031
5032	retval = CTL_RETVAL_COMPLETE;
5033
5034
5035	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5036	/*
5037	 * XXX KDM this shouldn't happen, but what if it does?
5038	 */
5039	if (io->io_hdr.io_type != CTL_IO_SCSI)
5040		panic("I/O type isn't CTL_IO_SCSI!");
5041
5042	if ((io->io_hdr.port_status == 0)
5043	 && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5044	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
5045		io->io_hdr.status = CTL_SUCCESS;
5046	else if ((io->io_hdr.port_status != 0)
5047	      && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5048	      && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
5049		/*
5050		 * For hardware error sense keys, the sense key
5051		 * specific value is defined to be a retry count,
5052		 * but we use it to pass back an internal FETD
5053		 * error code.  XXX KDM  Hopefully the FETD is only
5054		 * using 16 bits for an error code, since that's
5055		 * all the space we have in the sks field.
5056		 */
5057		ctl_set_internal_failure(&io->scsiio,
5058					 /*sks_valid*/ 1,
5059					 /*retry_count*/
5060					 io->io_hdr.port_status);
5061		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5062			free(io->scsiio.kern_data_ptr, M_CTL);
5063		ctl_done(io);
5064		goto bailout;
5065	}
5066
5067	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
5068	 || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
5069	 || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5070		/*
5071		 * XXX KDM just assuming a single pointer here, and not a
5072		 * S/G list.  If we start using S/G lists for config data,
5073		 * we'll need to know how to clean them up here as well.
5074		 */
5075		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5076			free(io->scsiio.kern_data_ptr, M_CTL);
5077		/* Hopefully the user has already set the status... */
5078		ctl_done(io);
5079	} else {
5080		/*
5081		 * XXX KDM now we need to continue data movement.  Some
5082		 * options:
5083		 * - call ctl_scsiio() again?  We don't do this for data
5084		 *   writes, because for those at least we know ahead of
5085		 *   time where the write will go and how long it is.  For
5086		 *   config writes, though, that information is largely
5087		 *   contained within the write itself, thus we need to
5088		 *   parse out the data again.
5089		 *
5090		 * - Call some other function once the data is in?
5091		 */
5092
5093		/*
5094		 * XXX KDM call ctl_scsiio() again for now, and check flag
5095		 * bits to see whether we're allocated or not.
5096		 */
5097		retval = ctl_scsiio(&io->scsiio);
5098	}
5099bailout:
5100	return (retval);
5101}
5102
5103/*
5104 * This gets called by a backend driver when it is done with a
5105 * data_submit method.
5106 */
5107void
5108ctl_data_submit_done(union ctl_io *io)
5109{
5110	/*
5111	 * If the IO_CONT flag is set, we need to call the supplied
5112	 * function to continue processing the I/O, instead of completing
5113	 * the I/O just yet.
5114	 *
5115	 * If there is an error, though, we don't want to keep processing.
5116	 * Instead, just send status back to the initiator.
5117	 */
5118	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5119	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5120	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5121	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5122		io->scsiio.io_cont(io);
5123		return;
5124	}
5125	ctl_done(io);
5126}
5127
5128/*
5129 * This gets called by a backend driver when it is done with a
5130 * configuration write.
5131 */
5132void
5133ctl_config_write_done(union ctl_io *io)
5134{
5135	/*
5136	 * If the IO_CONT flag is set, we need to call the supplied
5137	 * function to continue processing the I/O, instead of completing
5138	 * the I/O just yet.
5139	 *
5140	 * If there is an error, though, we don't want to keep processing.
5141	 * Instead, just send status back to the initiator.
5142	 */
5143	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT)
5144	 && (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)
5145	  || ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))) {
5146		io->scsiio.io_cont(io);
5147		return;
5148	}
5149	/*
5150	 * Since a configuration write can be done for commands that actually
5151	 * have data allocated, like write buffer, and commands that have
5152	 * no data, like start/stop unit, we need to check here.
5153	 */
5154	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
5155		free(io->scsiio.kern_data_ptr, M_CTL);
5156	ctl_done(io);
5157}
5158
5159/*
5160 * SCSI release command.
5161 */
5162int
5163ctl_scsi_release(struct ctl_scsiio *ctsio)
5164{
5165	int length, longid, thirdparty_id, resv_id;
5166	struct ctl_softc *ctl_softc;
5167	struct ctl_lun *lun;
5168
5169	length = 0;
5170	resv_id = 0;
5171
5172	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5173
5174	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5175	ctl_softc = control_softc;
5176
5177	switch (ctsio->cdb[0]) {
5178	case RELEASE_10: {
5179		struct scsi_release_10 *cdb;
5180
5181		cdb = (struct scsi_release_10 *)ctsio->cdb;
5182
5183		if (cdb->byte2 & SR10_LONGID)
5184			longid = 1;
5185		else
5186			thirdparty_id = cdb->thirdparty_id;
5187
5188		resv_id = cdb->resv_id;
5189		length = scsi_2btoul(cdb->length);
5190		break;
5191	}
5192	}
5193
5194
5195	/*
5196	 * XXX KDM right now, we only support LUN reservation.  We don't
5197	 * support 3rd party reservations, or extent reservations, which
5198	 * might actually need the parameter list.  If we've gotten this
5199	 * far, we've got a LUN reservation.  Anything else got kicked out
5200	 * above.  So, according to SPC, ignore the length.
5201	 */
5202	length = 0;
5203
5204	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5205	 && (length > 0)) {
5206		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5207		ctsio->kern_data_len = length;
5208		ctsio->kern_total_len = length;
5209		ctsio->kern_data_resid = 0;
5210		ctsio->kern_rel_offset = 0;
5211		ctsio->kern_sg_entries = 0;
5212		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5213		ctsio->be_move_done = ctl_config_move_done;
5214		ctl_datamove((union ctl_io *)ctsio);
5215
5216		return (CTL_RETVAL_COMPLETE);
5217	}
5218
5219	if (length > 0)
5220		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5221
5222	mtx_lock(&lun->lun_lock);
5223
5224	/*
5225	 * According to SPC, it is not an error for an intiator to attempt
5226	 * to release a reservation on a LUN that isn't reserved, or that
5227	 * is reserved by another initiator.  The reservation can only be
5228	 * released, though, by the initiator who made it or by one of
5229	 * several reset type events.
5230	 */
5231	if (lun->flags & CTL_LUN_RESERVED) {
5232		if ((ctsio->io_hdr.nexus.initid.id == lun->rsv_nexus.initid.id)
5233		 && (ctsio->io_hdr.nexus.targ_port == lun->rsv_nexus.targ_port)
5234		 && (ctsio->io_hdr.nexus.targ_target.id ==
5235		     lun->rsv_nexus.targ_target.id)) {
5236			lun->flags &= ~CTL_LUN_RESERVED;
5237		}
5238	}
5239
5240	mtx_unlock(&lun->lun_lock);
5241
5242	ctsio->scsi_status = SCSI_STATUS_OK;
5243	ctsio->io_hdr.status = CTL_SUCCESS;
5244
5245	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5246		free(ctsio->kern_data_ptr, M_CTL);
5247		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5248	}
5249
5250	ctl_done((union ctl_io *)ctsio);
5251	return (CTL_RETVAL_COMPLETE);
5252}
5253
5254int
5255ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5256{
5257	int extent, thirdparty, longid;
5258	int resv_id, length;
5259	uint64_t thirdparty_id;
5260	struct ctl_softc *ctl_softc;
5261	struct ctl_lun *lun;
5262
5263	extent = 0;
5264	thirdparty = 0;
5265	longid = 0;
5266	resv_id = 0;
5267	length = 0;
5268	thirdparty_id = 0;
5269
5270	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5271
5272	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5273	ctl_softc = control_softc;
5274
5275	switch (ctsio->cdb[0]) {
5276	case RESERVE_10: {
5277		struct scsi_reserve_10 *cdb;
5278
5279		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5280
5281		if (cdb->byte2 & SR10_LONGID)
5282			longid = 1;
5283		else
5284			thirdparty_id = cdb->thirdparty_id;
5285
5286		resv_id = cdb->resv_id;
5287		length = scsi_2btoul(cdb->length);
5288		break;
5289	}
5290	}
5291
5292	/*
5293	 * XXX KDM right now, we only support LUN reservation.  We don't
5294	 * support 3rd party reservations, or extent reservations, which
5295	 * might actually need the parameter list.  If we've gotten this
5296	 * far, we've got a LUN reservation.  Anything else got kicked out
5297	 * above.  So, according to SPC, ignore the length.
5298	 */
5299	length = 0;
5300
5301	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5302	 && (length > 0)) {
5303		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5304		ctsio->kern_data_len = length;
5305		ctsio->kern_total_len = length;
5306		ctsio->kern_data_resid = 0;
5307		ctsio->kern_rel_offset = 0;
5308		ctsio->kern_sg_entries = 0;
5309		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5310		ctsio->be_move_done = ctl_config_move_done;
5311		ctl_datamove((union ctl_io *)ctsio);
5312
5313		return (CTL_RETVAL_COMPLETE);
5314	}
5315
5316	if (length > 0)
5317		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5318
5319	mtx_lock(&lun->lun_lock);
5320	if (lun->flags & CTL_LUN_RESERVED) {
5321		if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
5322		 || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
5323		 || (ctsio->io_hdr.nexus.targ_target.id !=
5324		     lun->rsv_nexus.targ_target.id)) {
5325			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
5326			ctsio->io_hdr.status = CTL_SCSI_ERROR;
5327			goto bailout;
5328		}
5329	}
5330
5331	lun->flags |= CTL_LUN_RESERVED;
5332	lun->rsv_nexus = ctsio->io_hdr.nexus;
5333
5334	ctsio->scsi_status = SCSI_STATUS_OK;
5335	ctsio->io_hdr.status = CTL_SUCCESS;
5336
5337bailout:
5338	mtx_unlock(&lun->lun_lock);
5339
5340	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5341		free(ctsio->kern_data_ptr, M_CTL);
5342		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5343	}
5344
5345	ctl_done((union ctl_io *)ctsio);
5346	return (CTL_RETVAL_COMPLETE);
5347}
5348
5349int
5350ctl_start_stop(struct ctl_scsiio *ctsio)
5351{
5352	struct scsi_start_stop_unit *cdb;
5353	struct ctl_lun *lun;
5354	struct ctl_softc *ctl_softc;
5355	int retval;
5356
5357	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5358
5359	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5360	ctl_softc = control_softc;
5361	retval = 0;
5362
5363	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5364
5365	/*
5366	 * XXX KDM
5367	 * We don't support the immediate bit on a stop unit.  In order to
5368	 * do that, we would need to code up a way to know that a stop is
5369	 * pending, and hold off any new commands until it completes, one
5370	 * way or another.  Then we could accept or reject those commands
5371	 * depending on its status.  We would almost need to do the reverse
5372	 * of what we do below for an immediate start -- return the copy of
5373	 * the ctl_io to the FETD with status to send to the host (and to
5374	 * free the copy!) and then free the original I/O once the stop
5375	 * actually completes.  That way, the OOA queue mechanism can work
5376	 * to block commands that shouldn't proceed.  Another alternative
5377	 * would be to put the copy in the queue in place of the original,
5378	 * and return the original back to the caller.  That could be
5379	 * slightly safer..
5380	 */
5381	if ((cdb->byte2 & SSS_IMMED)
5382	 && ((cdb->how & SSS_START) == 0)) {
5383		ctl_set_invalid_field(ctsio,
5384				      /*sks_valid*/ 1,
5385				      /*command*/ 1,
5386				      /*field*/ 1,
5387				      /*bit_valid*/ 1,
5388				      /*bit*/ 0);
5389		ctl_done((union ctl_io *)ctsio);
5390		return (CTL_RETVAL_COMPLETE);
5391	}
5392
5393	if ((lun->flags & CTL_LUN_PR_RESERVED)
5394	 && ((cdb->how & SSS_START)==0)) {
5395		uint32_t residx;
5396
5397		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5398		if (!lun->per_res[residx].registered
5399		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5400
5401			ctl_set_reservation_conflict(ctsio);
5402			ctl_done((union ctl_io *)ctsio);
5403			return (CTL_RETVAL_COMPLETE);
5404		}
5405	}
5406
5407	/*
5408	 * If there is no backend on this device, we can't start or stop
5409	 * it.  In theory we shouldn't get any start/stop commands in the
5410	 * first place at this level if the LUN doesn't have a backend.
5411	 * That should get stopped by the command decode code.
5412	 */
5413	if (lun->backend == NULL) {
5414		ctl_set_invalid_opcode(ctsio);
5415		ctl_done((union ctl_io *)ctsio);
5416		return (CTL_RETVAL_COMPLETE);
5417	}
5418
5419	/*
5420	 * XXX KDM Copan-specific offline behavior.
5421	 * Figure out a reasonable way to port this?
5422	 */
5423#ifdef NEEDTOPORT
5424	mtx_lock(&lun->lun_lock);
5425
5426	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5427	 && (lun->flags & CTL_LUN_OFFLINE)) {
5428		/*
5429		 * If the LUN is offline, and the on/offline bit isn't set,
5430		 * reject the start or stop.  Otherwise, let it through.
5431		 */
5432		mtx_unlock(&lun->lun_lock);
5433		ctl_set_lun_not_ready(ctsio);
5434		ctl_done((union ctl_io *)ctsio);
5435	} else {
5436		mtx_unlock(&lun->lun_lock);
5437#endif /* NEEDTOPORT */
5438		/*
5439		 * This could be a start or a stop when we're online,
5440		 * or a stop/offline or start/online.  A start or stop when
5441		 * we're offline is covered in the case above.
5442		 */
5443		/*
5444		 * In the non-immediate case, we send the request to
5445		 * the backend and return status to the user when
5446		 * it is done.
5447		 *
5448		 * In the immediate case, we allocate a new ctl_io
5449		 * to hold a copy of the request, and send that to
5450		 * the backend.  We then set good status on the
5451		 * user's request and return it immediately.
5452		 */
5453		if (cdb->byte2 & SSS_IMMED) {
5454			union ctl_io *new_io;
5455
5456			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5457			if (new_io == NULL) {
5458				ctl_set_busy(ctsio);
5459				ctl_done((union ctl_io *)ctsio);
5460			} else {
5461				ctl_copy_io((union ctl_io *)ctsio,
5462					    new_io);
5463				retval = lun->backend->config_write(new_io);
5464				ctl_set_success(ctsio);
5465				ctl_done((union ctl_io *)ctsio);
5466			}
5467		} else {
5468			retval = lun->backend->config_write(
5469				(union ctl_io *)ctsio);
5470		}
5471#ifdef NEEDTOPORT
5472	}
5473#endif
5474	return (retval);
5475}
5476
5477/*
5478 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5479 * we don't really do anything with the LBA and length fields if the user
5480 * passes them in.  Instead we'll just flush out the cache for the entire
5481 * LUN.
5482 */
5483int
5484ctl_sync_cache(struct ctl_scsiio *ctsio)
5485{
5486	struct ctl_lun *lun;
5487	struct ctl_softc *ctl_softc;
5488	uint64_t starting_lba;
5489	uint32_t block_count;
5490	int retval;
5491
5492	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5493
5494	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5495	ctl_softc = control_softc;
5496	retval = 0;
5497
5498	switch (ctsio->cdb[0]) {
5499	case SYNCHRONIZE_CACHE: {
5500		struct scsi_sync_cache *cdb;
5501		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5502
5503		starting_lba = scsi_4btoul(cdb->begin_lba);
5504		block_count = scsi_2btoul(cdb->lb_count);
5505		break;
5506	}
5507	case SYNCHRONIZE_CACHE_16: {
5508		struct scsi_sync_cache_16 *cdb;
5509		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5510
5511		starting_lba = scsi_8btou64(cdb->begin_lba);
5512		block_count = scsi_4btoul(cdb->lb_count);
5513		break;
5514	}
5515	default:
5516		ctl_set_invalid_opcode(ctsio);
5517		ctl_done((union ctl_io *)ctsio);
5518		goto bailout;
5519		break; /* NOTREACHED */
5520	}
5521
5522	/*
5523	 * We check the LBA and length, but don't do anything with them.
5524	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5525	 * get flushed.  This check will just help satisfy anyone who wants
5526	 * to see an error for an out of range LBA.
5527	 */
5528	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5529		ctl_set_lba_out_of_range(ctsio);
5530		ctl_done((union ctl_io *)ctsio);
5531		goto bailout;
5532	}
5533
5534	/*
5535	 * If this LUN has no backend, we can't flush the cache anyway.
5536	 */
5537	if (lun->backend == NULL) {
5538		ctl_set_invalid_opcode(ctsio);
5539		ctl_done((union ctl_io *)ctsio);
5540		goto bailout;
5541	}
5542
5543	/*
5544	 * Check to see whether we're configured to send the SYNCHRONIZE
5545	 * CACHE command directly to the back end.
5546	 */
5547	mtx_lock(&lun->lun_lock);
5548	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5549	 && (++(lun->sync_count) >= lun->sync_interval)) {
5550		lun->sync_count = 0;
5551		mtx_unlock(&lun->lun_lock);
5552		retval = lun->backend->config_write((union ctl_io *)ctsio);
5553	} else {
5554		mtx_unlock(&lun->lun_lock);
5555		ctl_set_success(ctsio);
5556		ctl_done((union ctl_io *)ctsio);
5557	}
5558
5559bailout:
5560
5561	return (retval);
5562}
5563
5564int
5565ctl_format(struct ctl_scsiio *ctsio)
5566{
5567	struct scsi_format *cdb;
5568	struct ctl_lun *lun;
5569	struct ctl_softc *ctl_softc;
5570	int length, defect_list_len;
5571
5572	CTL_DEBUG_PRINT(("ctl_format\n"));
5573
5574	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5575	ctl_softc = control_softc;
5576
5577	cdb = (struct scsi_format *)ctsio->cdb;
5578
5579	length = 0;
5580	if (cdb->byte2 & SF_FMTDATA) {
5581		if (cdb->byte2 & SF_LONGLIST)
5582			length = sizeof(struct scsi_format_header_long);
5583		else
5584			length = sizeof(struct scsi_format_header_short);
5585	}
5586
5587	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5588	 && (length > 0)) {
5589		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5590		ctsio->kern_data_len = length;
5591		ctsio->kern_total_len = length;
5592		ctsio->kern_data_resid = 0;
5593		ctsio->kern_rel_offset = 0;
5594		ctsio->kern_sg_entries = 0;
5595		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5596		ctsio->be_move_done = ctl_config_move_done;
5597		ctl_datamove((union ctl_io *)ctsio);
5598
5599		return (CTL_RETVAL_COMPLETE);
5600	}
5601
5602	defect_list_len = 0;
5603
5604	if (cdb->byte2 & SF_FMTDATA) {
5605		if (cdb->byte2 & SF_LONGLIST) {
5606			struct scsi_format_header_long *header;
5607
5608			header = (struct scsi_format_header_long *)
5609				ctsio->kern_data_ptr;
5610
5611			defect_list_len = scsi_4btoul(header->defect_list_len);
5612			if (defect_list_len != 0) {
5613				ctl_set_invalid_field(ctsio,
5614						      /*sks_valid*/ 1,
5615						      /*command*/ 0,
5616						      /*field*/ 2,
5617						      /*bit_valid*/ 0,
5618						      /*bit*/ 0);
5619				goto bailout;
5620			}
5621		} else {
5622			struct scsi_format_header_short *header;
5623
5624			header = (struct scsi_format_header_short *)
5625				ctsio->kern_data_ptr;
5626
5627			defect_list_len = scsi_2btoul(header->defect_list_len);
5628			if (defect_list_len != 0) {
5629				ctl_set_invalid_field(ctsio,
5630						      /*sks_valid*/ 1,
5631						      /*command*/ 0,
5632						      /*field*/ 2,
5633						      /*bit_valid*/ 0,
5634						      /*bit*/ 0);
5635				goto bailout;
5636			}
5637		}
5638	}
5639
5640	/*
5641	 * The format command will clear out the "Medium format corrupted"
5642	 * status if set by the configuration code.  That status is really
5643	 * just a way to notify the host that we have lost the media, and
5644	 * get them to issue a command that will basically make them think
5645	 * they're blowing away the media.
5646	 */
5647	mtx_lock(&lun->lun_lock);
5648	lun->flags &= ~CTL_LUN_INOPERABLE;
5649	mtx_unlock(&lun->lun_lock);
5650
5651	ctsio->scsi_status = SCSI_STATUS_OK;
5652	ctsio->io_hdr.status = CTL_SUCCESS;
5653bailout:
5654
5655	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5656		free(ctsio->kern_data_ptr, M_CTL);
5657		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5658	}
5659
5660	ctl_done((union ctl_io *)ctsio);
5661	return (CTL_RETVAL_COMPLETE);
5662}
5663
5664int
5665ctl_read_buffer(struct ctl_scsiio *ctsio)
5666{
5667	struct scsi_read_buffer *cdb;
5668	struct ctl_lun *lun;
5669	int buffer_offset, len;
5670	static uint8_t descr[4];
5671	static uint8_t echo_descr[4] = { 0 };
5672
5673	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5674
5675	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5676	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5677
5678	if (lun->flags & CTL_LUN_PR_RESERVED) {
5679		uint32_t residx;
5680
5681		/*
5682		 * XXX KDM need a lock here.
5683		 */
5684		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5685		if ((lun->res_type == SPR_TYPE_EX_AC
5686		  && residx != lun->pr_res_idx)
5687		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
5688		   || lun->res_type == SPR_TYPE_EX_AC_AR)
5689		  && !lun->per_res[residx].registered)) {
5690			ctl_set_reservation_conflict(ctsio);
5691			ctl_done((union ctl_io *)ctsio);
5692			return (CTL_RETVAL_COMPLETE);
5693	        }
5694	}
5695
5696	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5697	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5698	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5699		ctl_set_invalid_field(ctsio,
5700				      /*sks_valid*/ 1,
5701				      /*command*/ 1,
5702				      /*field*/ 1,
5703				      /*bit_valid*/ 1,
5704				      /*bit*/ 4);
5705		ctl_done((union ctl_io *)ctsio);
5706		return (CTL_RETVAL_COMPLETE);
5707	}
5708
5709	len = scsi_3btoul(cdb->length);
5710	buffer_offset = scsi_3btoul(cdb->offset);
5711
5712	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5713		ctl_set_invalid_field(ctsio,
5714				      /*sks_valid*/ 1,
5715				      /*command*/ 1,
5716				      /*field*/ 6,
5717				      /*bit_valid*/ 0,
5718				      /*bit*/ 0);
5719		ctl_done((union ctl_io *)ctsio);
5720		return (CTL_RETVAL_COMPLETE);
5721	}
5722
5723	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5724		descr[0] = 0;
5725		scsi_ulto3b(sizeof(lun->write_buffer), &descr[1]);
5726		ctsio->kern_data_ptr = descr;
5727		len = min(len, sizeof(descr));
5728	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5729		ctsio->kern_data_ptr = echo_descr;
5730		len = min(len, sizeof(echo_descr));
5731	} else
5732		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5733	ctsio->kern_data_len = len;
5734	ctsio->kern_total_len = len;
5735	ctsio->kern_data_resid = 0;
5736	ctsio->kern_rel_offset = 0;
5737	ctsio->kern_sg_entries = 0;
5738	ctsio->be_move_done = ctl_config_move_done;
5739	ctl_datamove((union ctl_io *)ctsio);
5740
5741	return (CTL_RETVAL_COMPLETE);
5742}
5743
5744int
5745ctl_write_buffer(struct ctl_scsiio *ctsio)
5746{
5747	struct scsi_write_buffer *cdb;
5748	struct ctl_lun *lun;
5749	int buffer_offset, len;
5750
5751	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5752
5753	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5754	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5755
5756	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5757		ctl_set_invalid_field(ctsio,
5758				      /*sks_valid*/ 1,
5759				      /*command*/ 1,
5760				      /*field*/ 1,
5761				      /*bit_valid*/ 1,
5762				      /*bit*/ 4);
5763		ctl_done((union ctl_io *)ctsio);
5764		return (CTL_RETVAL_COMPLETE);
5765	}
5766
5767	len = scsi_3btoul(cdb->length);
5768	buffer_offset = scsi_3btoul(cdb->offset);
5769
5770	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5771		ctl_set_invalid_field(ctsio,
5772				      /*sks_valid*/ 1,
5773				      /*command*/ 1,
5774				      /*field*/ 6,
5775				      /*bit_valid*/ 0,
5776				      /*bit*/ 0);
5777		ctl_done((union ctl_io *)ctsio);
5778		return (CTL_RETVAL_COMPLETE);
5779	}
5780
5781	/*
5782	 * If we've got a kernel request that hasn't been malloced yet,
5783	 * malloc it and tell the caller the data buffer is here.
5784	 */
5785	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5786		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5787		ctsio->kern_data_len = len;
5788		ctsio->kern_total_len = len;
5789		ctsio->kern_data_resid = 0;
5790		ctsio->kern_rel_offset = 0;
5791		ctsio->kern_sg_entries = 0;
5792		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5793		ctsio->be_move_done = ctl_config_move_done;
5794		ctl_datamove((union ctl_io *)ctsio);
5795
5796		return (CTL_RETVAL_COMPLETE);
5797	}
5798
5799	ctl_done((union ctl_io *)ctsio);
5800
5801	return (CTL_RETVAL_COMPLETE);
5802}
5803
5804int
5805ctl_write_same(struct ctl_scsiio *ctsio)
5806{
5807	struct ctl_lun *lun;
5808	struct ctl_lba_len_flags *lbalen;
5809	uint64_t lba;
5810	uint32_t num_blocks;
5811	int len, retval;
5812	uint8_t byte2;
5813
5814	retval = CTL_RETVAL_COMPLETE;
5815
5816	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5817
5818	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5819
5820	switch (ctsio->cdb[0]) {
5821	case WRITE_SAME_10: {
5822		struct scsi_write_same_10 *cdb;
5823
5824		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5825
5826		lba = scsi_4btoul(cdb->addr);
5827		num_blocks = scsi_2btoul(cdb->length);
5828		byte2 = cdb->byte2;
5829		break;
5830	}
5831	case WRITE_SAME_16: {
5832		struct scsi_write_same_16 *cdb;
5833
5834		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5835
5836		lba = scsi_8btou64(cdb->addr);
5837		num_blocks = scsi_4btoul(cdb->length);
5838		byte2 = cdb->byte2;
5839		break;
5840	}
5841	default:
5842		/*
5843		 * We got a command we don't support.  This shouldn't
5844		 * happen, commands should be filtered out above us.
5845		 */
5846		ctl_set_invalid_opcode(ctsio);
5847		ctl_done((union ctl_io *)ctsio);
5848
5849		return (CTL_RETVAL_COMPLETE);
5850		break; /* NOTREACHED */
5851	}
5852
5853	/*
5854	 * The first check is to make sure we're in bounds, the second
5855	 * check is to catch wrap-around problems.  If the lba + num blocks
5856	 * is less than the lba, then we've wrapped around and the block
5857	 * range is invalid anyway.
5858	 */
5859	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5860	 || ((lba + num_blocks) < lba)) {
5861		ctl_set_lba_out_of_range(ctsio);
5862		ctl_done((union ctl_io *)ctsio);
5863		return (CTL_RETVAL_COMPLETE);
5864	}
5865
5866	/* Zero number of blocks means "to the last logical block" */
5867	if (num_blocks == 0) {
5868		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5869			ctl_set_invalid_field(ctsio,
5870					      /*sks_valid*/ 0,
5871					      /*command*/ 1,
5872					      /*field*/ 0,
5873					      /*bit_valid*/ 0,
5874					      /*bit*/ 0);
5875			ctl_done((union ctl_io *)ctsio);
5876			return (CTL_RETVAL_COMPLETE);
5877		}
5878		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5879	}
5880
5881	len = lun->be_lun->blocksize;
5882
5883	/*
5884	 * If we've got a kernel request that hasn't been malloced yet,
5885	 * malloc it and tell the caller the data buffer is here.
5886	 */
5887	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5888		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5889		ctsio->kern_data_len = len;
5890		ctsio->kern_total_len = len;
5891		ctsio->kern_data_resid = 0;
5892		ctsio->kern_rel_offset = 0;
5893		ctsio->kern_sg_entries = 0;
5894		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5895		ctsio->be_move_done = ctl_config_move_done;
5896		ctl_datamove((union ctl_io *)ctsio);
5897
5898		return (CTL_RETVAL_COMPLETE);
5899	}
5900
5901	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5902	lbalen->lba = lba;
5903	lbalen->len = num_blocks;
5904	lbalen->flags = byte2;
5905	retval = lun->backend->config_write((union ctl_io *)ctsio);
5906
5907	return (retval);
5908}
5909
5910int
5911ctl_unmap(struct ctl_scsiio *ctsio)
5912{
5913	struct ctl_lun *lun;
5914	struct scsi_unmap *cdb;
5915	struct ctl_ptr_len_flags *ptrlen;
5916	struct scsi_unmap_header *hdr;
5917	struct scsi_unmap_desc *buf, *end;
5918	uint64_t lba;
5919	uint32_t num_blocks;
5920	int len, retval;
5921	uint8_t byte2;
5922
5923	retval = CTL_RETVAL_COMPLETE;
5924
5925	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5926
5927	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5928	cdb = (struct scsi_unmap *)ctsio->cdb;
5929
5930	len = scsi_2btoul(cdb->length);
5931	byte2 = cdb->byte2;
5932
5933	/*
5934	 * If we've got a kernel request that hasn't been malloced yet,
5935	 * malloc it and tell the caller the data buffer is here.
5936	 */
5937	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5938		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5939		ctsio->kern_data_len = len;
5940		ctsio->kern_total_len = len;
5941		ctsio->kern_data_resid = 0;
5942		ctsio->kern_rel_offset = 0;
5943		ctsio->kern_sg_entries = 0;
5944		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5945		ctsio->be_move_done = ctl_config_move_done;
5946		ctl_datamove((union ctl_io *)ctsio);
5947
5948		return (CTL_RETVAL_COMPLETE);
5949	}
5950
5951	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5952	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5953	if (len < sizeof (*hdr) ||
5954	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5955	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5956	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5957		ctl_set_invalid_field(ctsio,
5958				      /*sks_valid*/ 0,
5959				      /*command*/ 0,
5960				      /*field*/ 0,
5961				      /*bit_valid*/ 0,
5962				      /*bit*/ 0);
5963		ctl_done((union ctl_io *)ctsio);
5964		return (CTL_RETVAL_COMPLETE);
5965	}
5966	len = scsi_2btoul(hdr->desc_length);
5967	buf = (struct scsi_unmap_desc *)(hdr + 1);
5968	end = buf + len / sizeof(*buf);
5969
5970	ptrlen = (struct ctl_ptr_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5971	ptrlen->ptr = (void *)buf;
5972	ptrlen->len = len;
5973	ptrlen->flags = byte2;
5974
5975	for (; buf < end; buf++) {
5976		lba = scsi_8btou64(buf->lba);
5977		num_blocks = scsi_4btoul(buf->length);
5978		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5979		 || ((lba + num_blocks) < lba)) {
5980			ctl_set_lba_out_of_range(ctsio);
5981			ctl_done((union ctl_io *)ctsio);
5982			return (CTL_RETVAL_COMPLETE);
5983		}
5984	}
5985
5986	retval = lun->backend->config_write((union ctl_io *)ctsio);
5987
5988	return (retval);
5989}
5990
5991/*
5992 * Note that this function currently doesn't actually do anything inside
5993 * CTL to enforce things if the DQue bit is turned on.
5994 *
5995 * Also note that this function can't be used in the default case, because
5996 * the DQue bit isn't set in the changeable mask for the control mode page
5997 * anyway.  This is just here as an example for how to implement a page
5998 * handler, and a placeholder in case we want to allow the user to turn
5999 * tagged queueing on and off.
6000 *
6001 * The D_SENSE bit handling is functional, however, and will turn
6002 * descriptor sense on and off for a given LUN.
6003 */
6004int
6005ctl_control_page_handler(struct ctl_scsiio *ctsio,
6006			 struct ctl_page_index *page_index, uint8_t *page_ptr)
6007{
6008	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6009	struct ctl_lun *lun;
6010	struct ctl_softc *softc;
6011	int set_ua;
6012	uint32_t initidx;
6013
6014	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6015	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6016	set_ua = 0;
6017
6018	user_cp = (struct scsi_control_page *)page_ptr;
6019	current_cp = (struct scsi_control_page *)
6020		(page_index->page_data + (page_index->page_len *
6021		CTL_PAGE_CURRENT));
6022	saved_cp = (struct scsi_control_page *)
6023		(page_index->page_data + (page_index->page_len *
6024		CTL_PAGE_SAVED));
6025
6026	softc = control_softc;
6027
6028	mtx_lock(&lun->lun_lock);
6029	if (((current_cp->rlec & SCP_DSENSE) == 0)
6030	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6031		/*
6032		 * Descriptor sense is currently turned off and the user
6033		 * wants to turn it on.
6034		 */
6035		current_cp->rlec |= SCP_DSENSE;
6036		saved_cp->rlec |= SCP_DSENSE;
6037		lun->flags |= CTL_LUN_SENSE_DESC;
6038		set_ua = 1;
6039	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6040		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6041		/*
6042		 * Descriptor sense is currently turned on, and the user
6043		 * wants to turn it off.
6044		 */
6045		current_cp->rlec &= ~SCP_DSENSE;
6046		saved_cp->rlec &= ~SCP_DSENSE;
6047		lun->flags &= ~CTL_LUN_SENSE_DESC;
6048		set_ua = 1;
6049	}
6050	if (current_cp->queue_flags & SCP_QUEUE_DQUE) {
6051		if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
6052#ifdef NEEDTOPORT
6053			csevent_log(CSC_CTL | CSC_SHELF_SW |
6054				    CTL_UNTAG_TO_UNTAG,
6055				    csevent_LogType_Trace,
6056				    csevent_Severity_Information,
6057				    csevent_AlertLevel_Green,
6058				    csevent_FRU_Firmware,
6059				    csevent_FRU_Unknown,
6060				    "Received untagged to untagged transition");
6061#endif /* NEEDTOPORT */
6062		} else {
6063#ifdef NEEDTOPORT
6064			csevent_log(CSC_CTL | CSC_SHELF_SW |
6065				    CTL_UNTAG_TO_TAG,
6066				    csevent_LogType_ConfigChange,
6067				    csevent_Severity_Information,
6068				    csevent_AlertLevel_Green,
6069				    csevent_FRU_Firmware,
6070				    csevent_FRU_Unknown,
6071				    "Received untagged to tagged "
6072				    "queueing transition");
6073#endif /* NEEDTOPORT */
6074
6075			current_cp->queue_flags &= ~SCP_QUEUE_DQUE;
6076			saved_cp->queue_flags &= ~SCP_QUEUE_DQUE;
6077			set_ua = 1;
6078		}
6079	} else {
6080		if (user_cp->queue_flags & SCP_QUEUE_DQUE) {
6081#ifdef NEEDTOPORT
6082			csevent_log(CSC_CTL | CSC_SHELF_SW |
6083				    CTL_TAG_TO_UNTAG,
6084				    csevent_LogType_ConfigChange,
6085				    csevent_Severity_Warning,
6086				    csevent_AlertLevel_Yellow,
6087				    csevent_FRU_Firmware,
6088				    csevent_FRU_Unknown,
6089				    "Received tagged queueing to untagged "
6090				    "transition");
6091#endif /* NEEDTOPORT */
6092
6093			current_cp->queue_flags |= SCP_QUEUE_DQUE;
6094			saved_cp->queue_flags |= SCP_QUEUE_DQUE;
6095			set_ua = 1;
6096		} else {
6097#ifdef NEEDTOPORT
6098			csevent_log(CSC_CTL | CSC_SHELF_SW |
6099				    CTL_TAG_TO_TAG,
6100				    csevent_LogType_Trace,
6101				    csevent_Severity_Information,
6102				    csevent_AlertLevel_Green,
6103				    csevent_FRU_Firmware,
6104				    csevent_FRU_Unknown,
6105				    "Received tagged queueing to tagged "
6106				    "queueing transition");
6107#endif /* NEEDTOPORT */
6108		}
6109	}
6110	if (set_ua != 0) {
6111		int i;
6112		/*
6113		 * Let other initiators know that the mode
6114		 * parameters for this LUN have changed.
6115		 */
6116		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6117			if (i == initidx)
6118				continue;
6119
6120			lun->pending_sense[i].ua_pending |=
6121				CTL_UA_MODE_CHANGE;
6122		}
6123	}
6124	mtx_unlock(&lun->lun_lock);
6125
6126	return (0);
6127}
6128
6129int
6130ctl_power_sp_handler(struct ctl_scsiio *ctsio,
6131		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6132{
6133	return (0);
6134}
6135
6136int
6137ctl_power_sp_sense_handler(struct ctl_scsiio *ctsio,
6138			   struct ctl_page_index *page_index, int pc)
6139{
6140	struct copan_power_subpage *page;
6141
6142	page = (struct copan_power_subpage *)page_index->page_data +
6143		(page_index->page_len * pc);
6144
6145	switch (pc) {
6146	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6147		/*
6148		 * We don't update the changable bits for this page.
6149		 */
6150		break;
6151	case SMS_PAGE_CTRL_CURRENT >> 6:
6152	case SMS_PAGE_CTRL_DEFAULT >> 6:
6153	case SMS_PAGE_CTRL_SAVED >> 6:
6154#ifdef NEEDTOPORT
6155		ctl_update_power_subpage(page);
6156#endif
6157		break;
6158	default:
6159#ifdef NEEDTOPORT
6160		EPRINT(0, "Invalid PC %d!!", pc);
6161#endif
6162		break;
6163	}
6164	return (0);
6165}
6166
6167
6168int
6169ctl_aps_sp_handler(struct ctl_scsiio *ctsio,
6170		   struct ctl_page_index *page_index, uint8_t *page_ptr)
6171{
6172	struct copan_aps_subpage *user_sp;
6173	struct copan_aps_subpage *current_sp;
6174	union ctl_modepage_info *modepage_info;
6175	struct ctl_softc *softc;
6176	struct ctl_lun *lun;
6177	int retval;
6178
6179	retval = CTL_RETVAL_COMPLETE;
6180	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
6181		     (page_index->page_len * CTL_PAGE_CURRENT));
6182	softc = control_softc;
6183	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6184
6185	user_sp = (struct copan_aps_subpage *)page_ptr;
6186
6187	modepage_info = (union ctl_modepage_info *)
6188		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6189
6190	modepage_info->header.page_code = page_index->page_code & SMPH_PC_MASK;
6191	modepage_info->header.subpage = page_index->subpage;
6192	modepage_info->aps.lock_active = user_sp->lock_active;
6193
6194	mtx_lock(&softc->ctl_lock);
6195
6196	/*
6197	 * If there is a request to lock the LUN and another LUN is locked
6198	 * this is an error. If the requested LUN is already locked ignore
6199	 * the request. If no LUN is locked attempt to lock it.
6200	 * if there is a request to unlock the LUN and the LUN is currently
6201	 * locked attempt to unlock it. Otherwise ignore the request. i.e.
6202	 * if another LUN is locked or no LUN is locked.
6203	 */
6204	if (user_sp->lock_active & APS_LOCK_ACTIVE) {
6205		if (softc->aps_locked_lun == lun->lun) {
6206			/*
6207			 * This LUN is already locked, so we're done.
6208			 */
6209			retval = CTL_RETVAL_COMPLETE;
6210		} else if (softc->aps_locked_lun == 0) {
6211			/*
6212			 * No one has the lock, pass the request to the
6213			 * backend.
6214			 */
6215			retval = lun->backend->config_write(
6216				(union ctl_io *)ctsio);
6217		} else {
6218			/*
6219			 * Someone else has the lock, throw out the request.
6220			 */
6221			ctl_set_already_locked(ctsio);
6222			free(ctsio->kern_data_ptr, M_CTL);
6223			ctl_done((union ctl_io *)ctsio);
6224
6225			/*
6226			 * Set the return value so that ctl_do_mode_select()
6227			 * won't try to complete the command.  We already
6228			 * completed it here.
6229			 */
6230			retval = CTL_RETVAL_ERROR;
6231		}
6232	} else if (softc->aps_locked_lun == lun->lun) {
6233		/*
6234		 * This LUN is locked, so pass the unlock request to the
6235		 * backend.
6236		 */
6237		retval = lun->backend->config_write((union ctl_io *)ctsio);
6238	}
6239	mtx_unlock(&softc->ctl_lock);
6240
6241	return (retval);
6242}
6243
6244int
6245ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6246				struct ctl_page_index *page_index,
6247				uint8_t *page_ptr)
6248{
6249	uint8_t *c;
6250	int i;
6251
6252	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6253	ctl_time_io_secs =
6254		(c[0] << 8) |
6255		(c[1] << 0) |
6256		0;
6257	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6258	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6259	printf("page data:");
6260	for (i=0; i<8; i++)
6261		printf(" %.2x",page_ptr[i]);
6262	printf("\n");
6263	return (0);
6264}
6265
6266int
6267ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6268			       struct ctl_page_index *page_index,
6269			       int pc)
6270{
6271	struct copan_debugconf_subpage *page;
6272
6273	page = (struct copan_debugconf_subpage *)page_index->page_data +
6274		(page_index->page_len * pc);
6275
6276	switch (pc) {
6277	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6278	case SMS_PAGE_CTRL_DEFAULT >> 6:
6279	case SMS_PAGE_CTRL_SAVED >> 6:
6280		/*
6281		 * We don't update the changable or default bits for this page.
6282		 */
6283		break;
6284	case SMS_PAGE_CTRL_CURRENT >> 6:
6285		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6286		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6287		break;
6288	default:
6289#ifdef NEEDTOPORT
6290		EPRINT(0, "Invalid PC %d!!", pc);
6291#endif /* NEEDTOPORT */
6292		break;
6293	}
6294	return (0);
6295}
6296
6297
6298static int
6299ctl_do_mode_select(union ctl_io *io)
6300{
6301	struct scsi_mode_page_header *page_header;
6302	struct ctl_page_index *page_index;
6303	struct ctl_scsiio *ctsio;
6304	int control_dev, page_len;
6305	int page_len_offset, page_len_size;
6306	union ctl_modepage_info *modepage_info;
6307	struct ctl_lun *lun;
6308	int *len_left, *len_used;
6309	int retval, i;
6310
6311	ctsio = &io->scsiio;
6312	page_index = NULL;
6313	page_len = 0;
6314	retval = CTL_RETVAL_COMPLETE;
6315
6316	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6317
6318	if (lun->be_lun->lun_type != T_DIRECT)
6319		control_dev = 1;
6320	else
6321		control_dev = 0;
6322
6323	modepage_info = (union ctl_modepage_info *)
6324		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6325	len_left = &modepage_info->header.len_left;
6326	len_used = &modepage_info->header.len_used;
6327
6328do_next_page:
6329
6330	page_header = (struct scsi_mode_page_header *)
6331		(ctsio->kern_data_ptr + *len_used);
6332
6333	if (*len_left == 0) {
6334		free(ctsio->kern_data_ptr, M_CTL);
6335		ctl_set_success(ctsio);
6336		ctl_done((union ctl_io *)ctsio);
6337		return (CTL_RETVAL_COMPLETE);
6338	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6339
6340		free(ctsio->kern_data_ptr, M_CTL);
6341		ctl_set_param_len_error(ctsio);
6342		ctl_done((union ctl_io *)ctsio);
6343		return (CTL_RETVAL_COMPLETE);
6344
6345	} else if ((page_header->page_code & SMPH_SPF)
6346		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6347
6348		free(ctsio->kern_data_ptr, M_CTL);
6349		ctl_set_param_len_error(ctsio);
6350		ctl_done((union ctl_io *)ctsio);
6351		return (CTL_RETVAL_COMPLETE);
6352	}
6353
6354
6355	/*
6356	 * XXX KDM should we do something with the block descriptor?
6357	 */
6358	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6359
6360		if ((control_dev != 0)
6361		 && (lun->mode_pages.index[i].page_flags &
6362		     CTL_PAGE_FLAG_DISK_ONLY))
6363			continue;
6364
6365		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6366		    (page_header->page_code & SMPH_PC_MASK))
6367			continue;
6368
6369		/*
6370		 * If neither page has a subpage code, then we've got a
6371		 * match.
6372		 */
6373		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6374		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6375			page_index = &lun->mode_pages.index[i];
6376			page_len = page_header->page_length;
6377			break;
6378		}
6379
6380		/*
6381		 * If both pages have subpages, then the subpage numbers
6382		 * have to match.
6383		 */
6384		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6385		  && (page_header->page_code & SMPH_SPF)) {
6386			struct scsi_mode_page_header_sp *sph;
6387
6388			sph = (struct scsi_mode_page_header_sp *)page_header;
6389
6390			if (lun->mode_pages.index[i].subpage ==
6391			    sph->subpage) {
6392				page_index = &lun->mode_pages.index[i];
6393				page_len = scsi_2btoul(sph->page_length);
6394				break;
6395			}
6396		}
6397	}
6398
6399	/*
6400	 * If we couldn't find the page, or if we don't have a mode select
6401	 * handler for it, send back an error to the user.
6402	 */
6403	if ((page_index == NULL)
6404	 || (page_index->select_handler == NULL)) {
6405		ctl_set_invalid_field(ctsio,
6406				      /*sks_valid*/ 1,
6407				      /*command*/ 0,
6408				      /*field*/ *len_used,
6409				      /*bit_valid*/ 0,
6410				      /*bit*/ 0);
6411		free(ctsio->kern_data_ptr, M_CTL);
6412		ctl_done((union ctl_io *)ctsio);
6413		return (CTL_RETVAL_COMPLETE);
6414	}
6415
6416	if (page_index->page_code & SMPH_SPF) {
6417		page_len_offset = 2;
6418		page_len_size = 2;
6419	} else {
6420		page_len_size = 1;
6421		page_len_offset = 1;
6422	}
6423
6424	/*
6425	 * If the length the initiator gives us isn't the one we specify in
6426	 * the mode page header, or if they didn't specify enough data in
6427	 * the CDB to avoid truncating this page, kick out the request.
6428	 */
6429	if ((page_len != (page_index->page_len - page_len_offset -
6430			  page_len_size))
6431	 || (*len_left < page_index->page_len)) {
6432
6433
6434		ctl_set_invalid_field(ctsio,
6435				      /*sks_valid*/ 1,
6436				      /*command*/ 0,
6437				      /*field*/ *len_used + page_len_offset,
6438				      /*bit_valid*/ 0,
6439				      /*bit*/ 0);
6440		free(ctsio->kern_data_ptr, M_CTL);
6441		ctl_done((union ctl_io *)ctsio);
6442		return (CTL_RETVAL_COMPLETE);
6443	}
6444
6445	/*
6446	 * Run through the mode page, checking to make sure that the bits
6447	 * the user changed are actually legal for him to change.
6448	 */
6449	for (i = 0; i < page_index->page_len; i++) {
6450		uint8_t *user_byte, *change_mask, *current_byte;
6451		int bad_bit;
6452		int j;
6453
6454		user_byte = (uint8_t *)page_header + i;
6455		change_mask = page_index->page_data +
6456			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6457		current_byte = page_index->page_data +
6458			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6459
6460		/*
6461		 * Check to see whether the user set any bits in this byte
6462		 * that he is not allowed to set.
6463		 */
6464		if ((*user_byte & ~(*change_mask)) ==
6465		    (*current_byte & ~(*change_mask)))
6466			continue;
6467
6468		/*
6469		 * Go through bit by bit to determine which one is illegal.
6470		 */
6471		bad_bit = 0;
6472		for (j = 7; j >= 0; j--) {
6473			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6474			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6475				bad_bit = i;
6476				break;
6477			}
6478		}
6479		ctl_set_invalid_field(ctsio,
6480				      /*sks_valid*/ 1,
6481				      /*command*/ 0,
6482				      /*field*/ *len_used + i,
6483				      /*bit_valid*/ 1,
6484				      /*bit*/ bad_bit);
6485		free(ctsio->kern_data_ptr, M_CTL);
6486		ctl_done((union ctl_io *)ctsio);
6487		return (CTL_RETVAL_COMPLETE);
6488	}
6489
6490	/*
6491	 * Decrement these before we call the page handler, since we may
6492	 * end up getting called back one way or another before the handler
6493	 * returns to this context.
6494	 */
6495	*len_left -= page_index->page_len;
6496	*len_used += page_index->page_len;
6497
6498	retval = page_index->select_handler(ctsio, page_index,
6499					    (uint8_t *)page_header);
6500
6501	/*
6502	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6503	 * wait until this queued command completes to finish processing
6504	 * the mode page.  If it returns anything other than
6505	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6506	 * already set the sense information, freed the data pointer, and
6507	 * completed the io for us.
6508	 */
6509	if (retval != CTL_RETVAL_COMPLETE)
6510		goto bailout_no_done;
6511
6512	/*
6513	 * If the initiator sent us more than one page, parse the next one.
6514	 */
6515	if (*len_left > 0)
6516		goto do_next_page;
6517
6518	ctl_set_success(ctsio);
6519	free(ctsio->kern_data_ptr, M_CTL);
6520	ctl_done((union ctl_io *)ctsio);
6521
6522bailout_no_done:
6523
6524	return (CTL_RETVAL_COMPLETE);
6525
6526}
6527
6528int
6529ctl_mode_select(struct ctl_scsiio *ctsio)
6530{
6531	int param_len, pf, sp;
6532	int header_size, bd_len;
6533	int len_left, len_used;
6534	struct ctl_page_index *page_index;
6535	struct ctl_lun *lun;
6536	int control_dev, page_len;
6537	union ctl_modepage_info *modepage_info;
6538	int retval;
6539
6540	pf = 0;
6541	sp = 0;
6542	page_len = 0;
6543	len_used = 0;
6544	len_left = 0;
6545	retval = 0;
6546	bd_len = 0;
6547	page_index = NULL;
6548
6549	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6550
6551	if (lun->be_lun->lun_type != T_DIRECT)
6552		control_dev = 1;
6553	else
6554		control_dev = 0;
6555
6556	switch (ctsio->cdb[0]) {
6557	case MODE_SELECT_6: {
6558		struct scsi_mode_select_6 *cdb;
6559
6560		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6561
6562		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6563		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6564
6565		param_len = cdb->length;
6566		header_size = sizeof(struct scsi_mode_header_6);
6567		break;
6568	}
6569	case MODE_SELECT_10: {
6570		struct scsi_mode_select_10 *cdb;
6571
6572		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6573
6574		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6575		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6576
6577		param_len = scsi_2btoul(cdb->length);
6578		header_size = sizeof(struct scsi_mode_header_10);
6579		break;
6580	}
6581	default:
6582		ctl_set_invalid_opcode(ctsio);
6583		ctl_done((union ctl_io *)ctsio);
6584		return (CTL_RETVAL_COMPLETE);
6585		break; /* NOTREACHED */
6586	}
6587
6588	/*
6589	 * From SPC-3:
6590	 * "A parameter list length of zero indicates that the Data-Out Buffer
6591	 * shall be empty. This condition shall not be considered as an error."
6592	 */
6593	if (param_len == 0) {
6594		ctl_set_success(ctsio);
6595		ctl_done((union ctl_io *)ctsio);
6596		return (CTL_RETVAL_COMPLETE);
6597	}
6598
6599	/*
6600	 * Since we'll hit this the first time through, prior to
6601	 * allocation, we don't need to free a data buffer here.
6602	 */
6603	if (param_len < header_size) {
6604		ctl_set_param_len_error(ctsio);
6605		ctl_done((union ctl_io *)ctsio);
6606		return (CTL_RETVAL_COMPLETE);
6607	}
6608
6609	/*
6610	 * Allocate the data buffer and grab the user's data.  In theory,
6611	 * we shouldn't have to sanity check the parameter list length here
6612	 * because the maximum size is 64K.  We should be able to malloc
6613	 * that much without too many problems.
6614	 */
6615	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6616		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6617		ctsio->kern_data_len = param_len;
6618		ctsio->kern_total_len = param_len;
6619		ctsio->kern_data_resid = 0;
6620		ctsio->kern_rel_offset = 0;
6621		ctsio->kern_sg_entries = 0;
6622		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6623		ctsio->be_move_done = ctl_config_move_done;
6624		ctl_datamove((union ctl_io *)ctsio);
6625
6626		return (CTL_RETVAL_COMPLETE);
6627	}
6628
6629	switch (ctsio->cdb[0]) {
6630	case MODE_SELECT_6: {
6631		struct scsi_mode_header_6 *mh6;
6632
6633		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6634		bd_len = mh6->blk_desc_len;
6635		break;
6636	}
6637	case MODE_SELECT_10: {
6638		struct scsi_mode_header_10 *mh10;
6639
6640		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6641		bd_len = scsi_2btoul(mh10->blk_desc_len);
6642		break;
6643	}
6644	default:
6645		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6646		break;
6647	}
6648
6649	if (param_len < (header_size + bd_len)) {
6650		free(ctsio->kern_data_ptr, M_CTL);
6651		ctl_set_param_len_error(ctsio);
6652		ctl_done((union ctl_io *)ctsio);
6653		return (CTL_RETVAL_COMPLETE);
6654	}
6655
6656	/*
6657	 * Set the IO_CONT flag, so that if this I/O gets passed to
6658	 * ctl_config_write_done(), it'll get passed back to
6659	 * ctl_do_mode_select() for further processing, or completion if
6660	 * we're all done.
6661	 */
6662	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6663	ctsio->io_cont = ctl_do_mode_select;
6664
6665	modepage_info = (union ctl_modepage_info *)
6666		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6667
6668	memset(modepage_info, 0, sizeof(*modepage_info));
6669
6670	len_left = param_len - header_size - bd_len;
6671	len_used = header_size + bd_len;
6672
6673	modepage_info->header.len_left = len_left;
6674	modepage_info->header.len_used = len_used;
6675
6676	return (ctl_do_mode_select((union ctl_io *)ctsio));
6677}
6678
6679int
6680ctl_mode_sense(struct ctl_scsiio *ctsio)
6681{
6682	struct ctl_lun *lun;
6683	int pc, page_code, dbd, llba, subpage;
6684	int alloc_len, page_len, header_len, total_len;
6685	struct scsi_mode_block_descr *block_desc;
6686	struct ctl_page_index *page_index;
6687	int control_dev;
6688
6689	dbd = 0;
6690	llba = 0;
6691	block_desc = NULL;
6692	page_index = NULL;
6693
6694	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6695
6696	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6697
6698	if (lun->be_lun->lun_type != T_DIRECT)
6699		control_dev = 1;
6700	else
6701		control_dev = 0;
6702
6703	if (lun->flags & CTL_LUN_PR_RESERVED) {
6704		uint32_t residx;
6705
6706		/*
6707		 * XXX KDM need a lock here.
6708		 */
6709		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
6710		if ((lun->res_type == SPR_TYPE_EX_AC
6711		  && residx != lun->pr_res_idx)
6712		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
6713		   || lun->res_type == SPR_TYPE_EX_AC_AR)
6714		  && !lun->per_res[residx].registered)) {
6715			ctl_set_reservation_conflict(ctsio);
6716			ctl_done((union ctl_io *)ctsio);
6717			return (CTL_RETVAL_COMPLETE);
6718		}
6719	}
6720
6721	switch (ctsio->cdb[0]) {
6722	case MODE_SENSE_6: {
6723		struct scsi_mode_sense_6 *cdb;
6724
6725		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6726
6727		header_len = sizeof(struct scsi_mode_hdr_6);
6728		if (cdb->byte2 & SMS_DBD)
6729			dbd = 1;
6730		else
6731			header_len += sizeof(struct scsi_mode_block_descr);
6732
6733		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6734		page_code = cdb->page & SMS_PAGE_CODE;
6735		subpage = cdb->subpage;
6736		alloc_len = cdb->length;
6737		break;
6738	}
6739	case MODE_SENSE_10: {
6740		struct scsi_mode_sense_10 *cdb;
6741
6742		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6743
6744		header_len = sizeof(struct scsi_mode_hdr_10);
6745
6746		if (cdb->byte2 & SMS_DBD)
6747			dbd = 1;
6748		else
6749			header_len += sizeof(struct scsi_mode_block_descr);
6750		if (cdb->byte2 & SMS10_LLBAA)
6751			llba = 1;
6752		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6753		page_code = cdb->page & SMS_PAGE_CODE;
6754		subpage = cdb->subpage;
6755		alloc_len = scsi_2btoul(cdb->length);
6756		break;
6757	}
6758	default:
6759		ctl_set_invalid_opcode(ctsio);
6760		ctl_done((union ctl_io *)ctsio);
6761		return (CTL_RETVAL_COMPLETE);
6762		break; /* NOTREACHED */
6763	}
6764
6765	/*
6766	 * We have to make a first pass through to calculate the size of
6767	 * the pages that match the user's query.  Then we allocate enough
6768	 * memory to hold it, and actually copy the data into the buffer.
6769	 */
6770	switch (page_code) {
6771	case SMS_ALL_PAGES_PAGE: {
6772		int i;
6773
6774		page_len = 0;
6775
6776		/*
6777		 * At the moment, values other than 0 and 0xff here are
6778		 * reserved according to SPC-3.
6779		 */
6780		if ((subpage != SMS_SUBPAGE_PAGE_0)
6781		 && (subpage != SMS_SUBPAGE_ALL)) {
6782			ctl_set_invalid_field(ctsio,
6783					      /*sks_valid*/ 1,
6784					      /*command*/ 1,
6785					      /*field*/ 3,
6786					      /*bit_valid*/ 0,
6787					      /*bit*/ 0);
6788			ctl_done((union ctl_io *)ctsio);
6789			return (CTL_RETVAL_COMPLETE);
6790		}
6791
6792		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6793			if ((control_dev != 0)
6794			 && (lun->mode_pages.index[i].page_flags &
6795			     CTL_PAGE_FLAG_DISK_ONLY))
6796				continue;
6797
6798			/*
6799			 * We don't use this subpage if the user didn't
6800			 * request all subpages.
6801			 */
6802			if ((lun->mode_pages.index[i].subpage != 0)
6803			 && (subpage == SMS_SUBPAGE_PAGE_0))
6804				continue;
6805
6806#if 0
6807			printf("found page %#x len %d\n",
6808			       lun->mode_pages.index[i].page_code &
6809			       SMPH_PC_MASK,
6810			       lun->mode_pages.index[i].page_len);
6811#endif
6812			page_len += lun->mode_pages.index[i].page_len;
6813		}
6814		break;
6815	}
6816	default: {
6817		int i;
6818
6819		page_len = 0;
6820
6821		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6822			/* Look for the right page code */
6823			if ((lun->mode_pages.index[i].page_code &
6824			     SMPH_PC_MASK) != page_code)
6825				continue;
6826
6827			/* Look for the right subpage or the subpage wildcard*/
6828			if ((lun->mode_pages.index[i].subpage != subpage)
6829			 && (subpage != SMS_SUBPAGE_ALL))
6830				continue;
6831
6832			/* Make sure the page is supported for this dev type */
6833			if ((control_dev != 0)
6834			 && (lun->mode_pages.index[i].page_flags &
6835			     CTL_PAGE_FLAG_DISK_ONLY))
6836				continue;
6837
6838#if 0
6839			printf("found page %#x len %d\n",
6840			       lun->mode_pages.index[i].page_code &
6841			       SMPH_PC_MASK,
6842			       lun->mode_pages.index[i].page_len);
6843#endif
6844
6845			page_len += lun->mode_pages.index[i].page_len;
6846		}
6847
6848		if (page_len == 0) {
6849			ctl_set_invalid_field(ctsio,
6850					      /*sks_valid*/ 1,
6851					      /*command*/ 1,
6852					      /*field*/ 2,
6853					      /*bit_valid*/ 1,
6854					      /*bit*/ 5);
6855			ctl_done((union ctl_io *)ctsio);
6856			return (CTL_RETVAL_COMPLETE);
6857		}
6858		break;
6859	}
6860	}
6861
6862	total_len = header_len + page_len;
6863#if 0
6864	printf("header_len = %d, page_len = %d, total_len = %d\n",
6865	       header_len, page_len, total_len);
6866#endif
6867
6868	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6869	ctsio->kern_sg_entries = 0;
6870	ctsio->kern_data_resid = 0;
6871	ctsio->kern_rel_offset = 0;
6872	if (total_len < alloc_len) {
6873		ctsio->residual = alloc_len - total_len;
6874		ctsio->kern_data_len = total_len;
6875		ctsio->kern_total_len = total_len;
6876	} else {
6877		ctsio->residual = 0;
6878		ctsio->kern_data_len = alloc_len;
6879		ctsio->kern_total_len = alloc_len;
6880	}
6881
6882	switch (ctsio->cdb[0]) {
6883	case MODE_SENSE_6: {
6884		struct scsi_mode_hdr_6 *header;
6885
6886		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6887
6888		header->datalen = ctl_min(total_len - 1, 254);
6889
6890		if (dbd)
6891			header->block_descr_len = 0;
6892		else
6893			header->block_descr_len =
6894				sizeof(struct scsi_mode_block_descr);
6895		block_desc = (struct scsi_mode_block_descr *)&header[1];
6896		break;
6897	}
6898	case MODE_SENSE_10: {
6899		struct scsi_mode_hdr_10 *header;
6900		int datalen;
6901
6902		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6903
6904		datalen = ctl_min(total_len - 2, 65533);
6905		scsi_ulto2b(datalen, header->datalen);
6906		if (dbd)
6907			scsi_ulto2b(0, header->block_descr_len);
6908		else
6909			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6910				    header->block_descr_len);
6911		block_desc = (struct scsi_mode_block_descr *)&header[1];
6912		break;
6913	}
6914	default:
6915		panic("invalid CDB type %#x", ctsio->cdb[0]);
6916		break; /* NOTREACHED */
6917	}
6918
6919	/*
6920	 * If we've got a disk, use its blocksize in the block
6921	 * descriptor.  Otherwise, just set it to 0.
6922	 */
6923	if (dbd == 0) {
6924		if (control_dev != 0)
6925			scsi_ulto3b(lun->be_lun->blocksize,
6926				    block_desc->block_len);
6927		else
6928			scsi_ulto3b(0, block_desc->block_len);
6929	}
6930
6931	switch (page_code) {
6932	case SMS_ALL_PAGES_PAGE: {
6933		int i, data_used;
6934
6935		data_used = header_len;
6936		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6937			struct ctl_page_index *page_index;
6938
6939			page_index = &lun->mode_pages.index[i];
6940
6941			if ((control_dev != 0)
6942			 && (page_index->page_flags &
6943			    CTL_PAGE_FLAG_DISK_ONLY))
6944				continue;
6945
6946			/*
6947			 * We don't use this subpage if the user didn't
6948			 * request all subpages.  We already checked (above)
6949			 * to make sure the user only specified a subpage
6950			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6951			 */
6952			if ((page_index->subpage != 0)
6953			 && (subpage == SMS_SUBPAGE_PAGE_0))
6954				continue;
6955
6956			/*
6957			 * Call the handler, if it exists, to update the
6958			 * page to the latest values.
6959			 */
6960			if (page_index->sense_handler != NULL)
6961				page_index->sense_handler(ctsio, page_index,pc);
6962
6963			memcpy(ctsio->kern_data_ptr + data_used,
6964			       page_index->page_data +
6965			       (page_index->page_len * pc),
6966			       page_index->page_len);
6967			data_used += page_index->page_len;
6968		}
6969		break;
6970	}
6971	default: {
6972		int i, data_used;
6973
6974		data_used = header_len;
6975
6976		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6977			struct ctl_page_index *page_index;
6978
6979			page_index = &lun->mode_pages.index[i];
6980
6981			/* Look for the right page code */
6982			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6983				continue;
6984
6985			/* Look for the right subpage or the subpage wildcard*/
6986			if ((page_index->subpage != subpage)
6987			 && (subpage != SMS_SUBPAGE_ALL))
6988				continue;
6989
6990			/* Make sure the page is supported for this dev type */
6991			if ((control_dev != 0)
6992			 && (page_index->page_flags &
6993			     CTL_PAGE_FLAG_DISK_ONLY))
6994				continue;
6995
6996			/*
6997			 * Call the handler, if it exists, to update the
6998			 * page to the latest values.
6999			 */
7000			if (page_index->sense_handler != NULL)
7001				page_index->sense_handler(ctsio, page_index,pc);
7002
7003			memcpy(ctsio->kern_data_ptr + data_used,
7004			       page_index->page_data +
7005			       (page_index->page_len * pc),
7006			       page_index->page_len);
7007			data_used += page_index->page_len;
7008		}
7009		break;
7010	}
7011	}
7012
7013	ctsio->scsi_status = SCSI_STATUS_OK;
7014
7015	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7016	ctsio->be_move_done = ctl_config_move_done;
7017	ctl_datamove((union ctl_io *)ctsio);
7018
7019	return (CTL_RETVAL_COMPLETE);
7020}
7021
7022int
7023ctl_read_capacity(struct ctl_scsiio *ctsio)
7024{
7025	struct scsi_read_capacity *cdb;
7026	struct scsi_read_capacity_data *data;
7027	struct ctl_lun *lun;
7028	uint32_t lba;
7029
7030	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7031
7032	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7033
7034	lba = scsi_4btoul(cdb->addr);
7035	if (((cdb->pmi & SRC_PMI) == 0)
7036	 && (lba != 0)) {
7037		ctl_set_invalid_field(/*ctsio*/ ctsio,
7038				      /*sks_valid*/ 1,
7039				      /*command*/ 1,
7040				      /*field*/ 2,
7041				      /*bit_valid*/ 0,
7042				      /*bit*/ 0);
7043		ctl_done((union ctl_io *)ctsio);
7044		return (CTL_RETVAL_COMPLETE);
7045	}
7046
7047	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7048
7049	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7050	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7051	ctsio->residual = 0;
7052	ctsio->kern_data_len = sizeof(*data);
7053	ctsio->kern_total_len = sizeof(*data);
7054	ctsio->kern_data_resid = 0;
7055	ctsio->kern_rel_offset = 0;
7056	ctsio->kern_sg_entries = 0;
7057
7058	/*
7059	 * If the maximum LBA is greater than 0xfffffffe, the user must
7060	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7061	 * serivce action set.
7062	 */
7063	if (lun->be_lun->maxlba > 0xfffffffe)
7064		scsi_ulto4b(0xffffffff, data->addr);
7065	else
7066		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7067
7068	/*
7069	 * XXX KDM this may not be 512 bytes...
7070	 */
7071	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7072
7073	ctsio->scsi_status = SCSI_STATUS_OK;
7074
7075	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7076	ctsio->be_move_done = ctl_config_move_done;
7077	ctl_datamove((union ctl_io *)ctsio);
7078
7079	return (CTL_RETVAL_COMPLETE);
7080}
7081
7082int
7083ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7084{
7085	struct scsi_read_capacity_16 *cdb;
7086	struct scsi_read_capacity_data_long *data;
7087	struct ctl_lun *lun;
7088	uint64_t lba;
7089	uint32_t alloc_len;
7090
7091	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7092
7093	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7094
7095	alloc_len = scsi_4btoul(cdb->alloc_len);
7096	lba = scsi_8btou64(cdb->addr);
7097
7098	if ((cdb->reladr & SRC16_PMI)
7099	 && (lba != 0)) {
7100		ctl_set_invalid_field(/*ctsio*/ ctsio,
7101				      /*sks_valid*/ 1,
7102				      /*command*/ 1,
7103				      /*field*/ 2,
7104				      /*bit_valid*/ 0,
7105				      /*bit*/ 0);
7106		ctl_done((union ctl_io *)ctsio);
7107		return (CTL_RETVAL_COMPLETE);
7108	}
7109
7110	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7111
7112	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7113	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7114
7115	if (sizeof(*data) < alloc_len) {
7116		ctsio->residual = alloc_len - sizeof(*data);
7117		ctsio->kern_data_len = sizeof(*data);
7118		ctsio->kern_total_len = sizeof(*data);
7119	} else {
7120		ctsio->residual = 0;
7121		ctsio->kern_data_len = alloc_len;
7122		ctsio->kern_total_len = alloc_len;
7123	}
7124	ctsio->kern_data_resid = 0;
7125	ctsio->kern_rel_offset = 0;
7126	ctsio->kern_sg_entries = 0;
7127
7128	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7129	/* XXX KDM this may not be 512 bytes... */
7130	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7131	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7132	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7133	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7134		data->lalba_lbp[0] |= SRC16_LBPME;
7135
7136	ctsio->scsi_status = SCSI_STATUS_OK;
7137
7138	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7139	ctsio->be_move_done = ctl_config_move_done;
7140	ctl_datamove((union ctl_io *)ctsio);
7141
7142	return (CTL_RETVAL_COMPLETE);
7143}
7144
7145int
7146ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7147{
7148	struct scsi_maintenance_in *cdb;
7149	int retval;
7150	int alloc_len, ext, total_len = 0, g, p, pc, pg;
7151	int num_target_port_groups, num_target_ports, single;
7152	struct ctl_lun *lun;
7153	struct ctl_softc *softc;
7154	struct ctl_port *port;
7155	struct scsi_target_group_data *rtg_ptr;
7156	struct scsi_target_group_data_extended *rtg_ext_ptr;
7157	struct scsi_target_port_group_descriptor *tpg_desc;
7158
7159	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7160
7161	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7162	softc = control_softc;
7163	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7164
7165	retval = CTL_RETVAL_COMPLETE;
7166
7167	switch (cdb->byte2 & STG_PDF_MASK) {
7168	case STG_PDF_LENGTH:
7169		ext = 0;
7170		break;
7171	case STG_PDF_EXTENDED:
7172		ext = 1;
7173		break;
7174	default:
7175		ctl_set_invalid_field(/*ctsio*/ ctsio,
7176				      /*sks_valid*/ 1,
7177				      /*command*/ 1,
7178				      /*field*/ 2,
7179				      /*bit_valid*/ 1,
7180				      /*bit*/ 5);
7181		ctl_done((union ctl_io *)ctsio);
7182		return(retval);
7183	}
7184
7185	single = ctl_is_single;
7186	if (single)
7187		num_target_port_groups = 1;
7188	else
7189		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7190	num_target_ports = 0;
7191	mtx_lock(&softc->ctl_lock);
7192	STAILQ_FOREACH(port, &softc->port_list, links) {
7193		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7194			continue;
7195		if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7196			continue;
7197		num_target_ports++;
7198	}
7199	mtx_unlock(&softc->ctl_lock);
7200
7201	if (ext)
7202		total_len = sizeof(struct scsi_target_group_data_extended);
7203	else
7204		total_len = sizeof(struct scsi_target_group_data);
7205	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7206		num_target_port_groups +
7207	    sizeof(struct scsi_target_port_descriptor) *
7208		num_target_ports * num_target_port_groups;
7209
7210	alloc_len = scsi_4btoul(cdb->length);
7211
7212	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7213
7214	ctsio->kern_sg_entries = 0;
7215
7216	if (total_len < alloc_len) {
7217		ctsio->residual = alloc_len - total_len;
7218		ctsio->kern_data_len = total_len;
7219		ctsio->kern_total_len = total_len;
7220	} else {
7221		ctsio->residual = 0;
7222		ctsio->kern_data_len = alloc_len;
7223		ctsio->kern_total_len = alloc_len;
7224	}
7225	ctsio->kern_data_resid = 0;
7226	ctsio->kern_rel_offset = 0;
7227
7228	if (ext) {
7229		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7230		    ctsio->kern_data_ptr;
7231		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7232		rtg_ext_ptr->format_type = 0x10;
7233		rtg_ext_ptr->implicit_transition_time = 0;
7234		tpg_desc = &rtg_ext_ptr->groups[0];
7235	} else {
7236		rtg_ptr = (struct scsi_target_group_data *)
7237		    ctsio->kern_data_ptr;
7238		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7239		tpg_desc = &rtg_ptr->groups[0];
7240	}
7241
7242	pg = ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS;
7243	mtx_lock(&softc->ctl_lock);
7244	for (g = 0; g < num_target_port_groups; g++) {
7245		if (g == pg)
7246			tpg_desc->pref_state = TPG_PRIMARY |
7247			    TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7248		else
7249			tpg_desc->pref_state =
7250			    TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7251		tpg_desc->support = TPG_AO_SUP;
7252		if (!single)
7253			tpg_desc->support |= TPG_AN_SUP;
7254		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7255		tpg_desc->status = TPG_IMPLICIT;
7256		pc = 0;
7257		STAILQ_FOREACH(port, &softc->port_list, links) {
7258			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7259				continue;
7260			if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7261			    CTL_MAX_LUNS)
7262				continue;
7263			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7264			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7265			    relative_target_port_identifier);
7266			pc++;
7267		}
7268		tpg_desc->target_port_count = pc;
7269		tpg_desc = (struct scsi_target_port_group_descriptor *)
7270		    &tpg_desc->descriptors[pc];
7271	}
7272	mtx_unlock(&softc->ctl_lock);
7273
7274	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7275	ctsio->be_move_done = ctl_config_move_done;
7276
7277	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7278			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7279			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7280			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7281			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7282
7283	ctl_datamove((union ctl_io *)ctsio);
7284	return(retval);
7285}
7286
7287int
7288ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7289{
7290	struct ctl_lun *lun;
7291	struct scsi_report_supported_opcodes *cdb;
7292	const struct ctl_cmd_entry *entry, *sentry;
7293	struct scsi_report_supported_opcodes_all *all;
7294	struct scsi_report_supported_opcodes_descr *descr;
7295	struct scsi_report_supported_opcodes_one *one;
7296	int retval;
7297	int alloc_len, total_len;
7298	int opcode, service_action, i, j, num;
7299
7300	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7301
7302	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7303	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7304
7305	retval = CTL_RETVAL_COMPLETE;
7306
7307	opcode = cdb->requested_opcode;
7308	service_action = scsi_2btoul(cdb->requested_service_action);
7309	switch (cdb->options & RSO_OPTIONS_MASK) {
7310	case RSO_OPTIONS_ALL:
7311		num = 0;
7312		for (i = 0; i < 256; i++) {
7313			entry = &ctl_cmd_table[i];
7314			if (entry->flags & CTL_CMD_FLAG_SA5) {
7315				for (j = 0; j < 32; j++) {
7316					sentry = &((const struct ctl_cmd_entry *)
7317					    entry->execute)[j];
7318					if (ctl_cmd_applicable(
7319					    lun->be_lun->lun_type, sentry))
7320						num++;
7321				}
7322			} else {
7323				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7324				    entry))
7325					num++;
7326			}
7327		}
7328		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7329		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7330		break;
7331	case RSO_OPTIONS_OC:
7332		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7333			ctl_set_invalid_field(/*ctsio*/ ctsio,
7334					      /*sks_valid*/ 1,
7335					      /*command*/ 1,
7336					      /*field*/ 2,
7337					      /*bit_valid*/ 1,
7338					      /*bit*/ 2);
7339			ctl_done((union ctl_io *)ctsio);
7340			return (CTL_RETVAL_COMPLETE);
7341		}
7342		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7343		break;
7344	case RSO_OPTIONS_OC_SA:
7345		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7346		    service_action >= 32) {
7347			ctl_set_invalid_field(/*ctsio*/ ctsio,
7348					      /*sks_valid*/ 1,
7349					      /*command*/ 1,
7350					      /*field*/ 2,
7351					      /*bit_valid*/ 1,
7352					      /*bit*/ 2);
7353			ctl_done((union ctl_io *)ctsio);
7354			return (CTL_RETVAL_COMPLETE);
7355		}
7356		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7357		break;
7358	default:
7359		ctl_set_invalid_field(/*ctsio*/ ctsio,
7360				      /*sks_valid*/ 1,
7361				      /*command*/ 1,
7362				      /*field*/ 2,
7363				      /*bit_valid*/ 1,
7364				      /*bit*/ 2);
7365		ctl_done((union ctl_io *)ctsio);
7366		return (CTL_RETVAL_COMPLETE);
7367	}
7368
7369	alloc_len = scsi_4btoul(cdb->length);
7370
7371	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7372
7373	ctsio->kern_sg_entries = 0;
7374
7375	if (total_len < alloc_len) {
7376		ctsio->residual = alloc_len - total_len;
7377		ctsio->kern_data_len = total_len;
7378		ctsio->kern_total_len = total_len;
7379	} else {
7380		ctsio->residual = 0;
7381		ctsio->kern_data_len = alloc_len;
7382		ctsio->kern_total_len = alloc_len;
7383	}
7384	ctsio->kern_data_resid = 0;
7385	ctsio->kern_rel_offset = 0;
7386
7387	switch (cdb->options & RSO_OPTIONS_MASK) {
7388	case RSO_OPTIONS_ALL:
7389		all = (struct scsi_report_supported_opcodes_all *)
7390		    ctsio->kern_data_ptr;
7391		num = 0;
7392		for (i = 0; i < 256; i++) {
7393			entry = &ctl_cmd_table[i];
7394			if (entry->flags & CTL_CMD_FLAG_SA5) {
7395				for (j = 0; j < 32; j++) {
7396					sentry = &((const struct ctl_cmd_entry *)
7397					    entry->execute)[j];
7398					if (!ctl_cmd_applicable(
7399					    lun->be_lun->lun_type, sentry))
7400						continue;
7401					descr = &all->descr[num++];
7402					descr->opcode = i;
7403					scsi_ulto2b(j, descr->service_action);
7404					descr->flags = RSO_SERVACTV;
7405					scsi_ulto2b(sentry->length,
7406					    descr->cdb_length);
7407				}
7408			} else {
7409				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7410				    entry))
7411					continue;
7412				descr = &all->descr[num++];
7413				descr->opcode = i;
7414				scsi_ulto2b(0, descr->service_action);
7415				descr->flags = 0;
7416				scsi_ulto2b(entry->length, descr->cdb_length);
7417			}
7418		}
7419		scsi_ulto4b(
7420		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7421		    all->length);
7422		break;
7423	case RSO_OPTIONS_OC:
7424		one = (struct scsi_report_supported_opcodes_one *)
7425		    ctsio->kern_data_ptr;
7426		entry = &ctl_cmd_table[opcode];
7427		goto fill_one;
7428	case RSO_OPTIONS_OC_SA:
7429		one = (struct scsi_report_supported_opcodes_one *)
7430		    ctsio->kern_data_ptr;
7431		entry = &ctl_cmd_table[opcode];
7432		entry = &((const struct ctl_cmd_entry *)
7433		    entry->execute)[service_action];
7434fill_one:
7435		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7436			one->support = 3;
7437			scsi_ulto2b(entry->length, one->cdb_length);
7438			one->cdb_usage[0] = opcode;
7439			memcpy(&one->cdb_usage[1], entry->usage,
7440			    entry->length - 1);
7441		} else
7442			one->support = 1;
7443		break;
7444	}
7445
7446	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7447	ctsio->be_move_done = ctl_config_move_done;
7448
7449	ctl_datamove((union ctl_io *)ctsio);
7450	return(retval);
7451}
7452
7453int
7454ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7455{
7456	struct ctl_lun *lun;
7457	struct scsi_report_supported_tmf *cdb;
7458	struct scsi_report_supported_tmf_data *data;
7459	int retval;
7460	int alloc_len, total_len;
7461
7462	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7463
7464	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7465	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7466
7467	retval = CTL_RETVAL_COMPLETE;
7468
7469	total_len = sizeof(struct scsi_report_supported_tmf_data);
7470	alloc_len = scsi_4btoul(cdb->length);
7471
7472	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7473
7474	ctsio->kern_sg_entries = 0;
7475
7476	if (total_len < alloc_len) {
7477		ctsio->residual = alloc_len - total_len;
7478		ctsio->kern_data_len = total_len;
7479		ctsio->kern_total_len = total_len;
7480	} else {
7481		ctsio->residual = 0;
7482		ctsio->kern_data_len = alloc_len;
7483		ctsio->kern_total_len = alloc_len;
7484	}
7485	ctsio->kern_data_resid = 0;
7486	ctsio->kern_rel_offset = 0;
7487
7488	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7489	data->byte1 |= RST_ATS | RST_ATSS | RST_LURS | RST_TRS;
7490	data->byte2 |= RST_ITNRS;
7491
7492	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7493	ctsio->be_move_done = ctl_config_move_done;
7494
7495	ctl_datamove((union ctl_io *)ctsio);
7496	return (retval);
7497}
7498
7499int
7500ctl_report_timestamp(struct ctl_scsiio *ctsio)
7501{
7502	struct ctl_lun *lun;
7503	struct scsi_report_timestamp *cdb;
7504	struct scsi_report_timestamp_data *data;
7505	struct timeval tv;
7506	int64_t timestamp;
7507	int retval;
7508	int alloc_len, total_len;
7509
7510	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7511
7512	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7513	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7514
7515	retval = CTL_RETVAL_COMPLETE;
7516
7517	total_len = sizeof(struct scsi_report_timestamp_data);
7518	alloc_len = scsi_4btoul(cdb->length);
7519
7520	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7521
7522	ctsio->kern_sg_entries = 0;
7523
7524	if (total_len < alloc_len) {
7525		ctsio->residual = alloc_len - total_len;
7526		ctsio->kern_data_len = total_len;
7527		ctsio->kern_total_len = total_len;
7528	} else {
7529		ctsio->residual = 0;
7530		ctsio->kern_data_len = alloc_len;
7531		ctsio->kern_total_len = alloc_len;
7532	}
7533	ctsio->kern_data_resid = 0;
7534	ctsio->kern_rel_offset = 0;
7535
7536	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7537	scsi_ulto2b(sizeof(*data) - 2, data->length);
7538	data->origin = RTS_ORIG_OUTSIDE;
7539	getmicrotime(&tv);
7540	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7541	scsi_ulto4b(timestamp >> 16, data->timestamp);
7542	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7543
7544	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7545	ctsio->be_move_done = ctl_config_move_done;
7546
7547	ctl_datamove((union ctl_io *)ctsio);
7548	return (retval);
7549}
7550
7551int
7552ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7553{
7554	struct scsi_per_res_in *cdb;
7555	int alloc_len, total_len = 0;
7556	/* struct scsi_per_res_in_rsrv in_data; */
7557	struct ctl_lun *lun;
7558	struct ctl_softc *softc;
7559
7560	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7561
7562	softc = control_softc;
7563
7564	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7565
7566	alloc_len = scsi_2btoul(cdb->length);
7567
7568	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7569
7570retry:
7571	mtx_lock(&lun->lun_lock);
7572	switch (cdb->action) {
7573	case SPRI_RK: /* read keys */
7574		total_len = sizeof(struct scsi_per_res_in_keys) +
7575			lun->pr_key_count *
7576			sizeof(struct scsi_per_res_key);
7577		break;
7578	case SPRI_RR: /* read reservation */
7579		if (lun->flags & CTL_LUN_PR_RESERVED)
7580			total_len = sizeof(struct scsi_per_res_in_rsrv);
7581		else
7582			total_len = sizeof(struct scsi_per_res_in_header);
7583		break;
7584	case SPRI_RC: /* report capabilities */
7585		total_len = sizeof(struct scsi_per_res_cap);
7586		break;
7587	default:
7588		panic("Invalid PR type %x", cdb->action);
7589	}
7590	mtx_unlock(&lun->lun_lock);
7591
7592	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7593
7594	if (total_len < alloc_len) {
7595		ctsio->residual = alloc_len - total_len;
7596		ctsio->kern_data_len = total_len;
7597		ctsio->kern_total_len = total_len;
7598	} else {
7599		ctsio->residual = 0;
7600		ctsio->kern_data_len = alloc_len;
7601		ctsio->kern_total_len = alloc_len;
7602	}
7603
7604	ctsio->kern_data_resid = 0;
7605	ctsio->kern_rel_offset = 0;
7606	ctsio->kern_sg_entries = 0;
7607
7608	mtx_lock(&lun->lun_lock);
7609	switch (cdb->action) {
7610	case SPRI_RK: { // read keys
7611        struct scsi_per_res_in_keys *res_keys;
7612		int i, key_count;
7613
7614		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7615
7616		/*
7617		 * We had to drop the lock to allocate our buffer, which
7618		 * leaves time for someone to come in with another
7619		 * persistent reservation.  (That is unlikely, though,
7620		 * since this should be the only persistent reservation
7621		 * command active right now.)
7622		 */
7623		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7624		    (lun->pr_key_count *
7625		     sizeof(struct scsi_per_res_key)))){
7626			mtx_unlock(&lun->lun_lock);
7627			free(ctsio->kern_data_ptr, M_CTL);
7628			printf("%s: reservation length changed, retrying\n",
7629			       __func__);
7630			goto retry;
7631		}
7632
7633		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7634
7635		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7636			     lun->pr_key_count, res_keys->header.length);
7637
7638		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7639			if (!lun->per_res[i].registered)
7640				continue;
7641
7642			/*
7643			 * We used lun->pr_key_count to calculate the
7644			 * size to allocate.  If it turns out the number of
7645			 * initiators with the registered flag set is
7646			 * larger than that (i.e. they haven't been kept in
7647			 * sync), we've got a problem.
7648			 */
7649			if (key_count >= lun->pr_key_count) {
7650#ifdef NEEDTOPORT
7651				csevent_log(CSC_CTL | CSC_SHELF_SW |
7652					    CTL_PR_ERROR,
7653					    csevent_LogType_Fault,
7654					    csevent_AlertLevel_Yellow,
7655					    csevent_FRU_ShelfController,
7656					    csevent_FRU_Firmware,
7657				        csevent_FRU_Unknown,
7658					    "registered keys %d >= key "
7659					    "count %d", key_count,
7660					    lun->pr_key_count);
7661#endif
7662				key_count++;
7663				continue;
7664			}
7665			memcpy(res_keys->keys[key_count].key,
7666			       lun->per_res[i].res_key.key,
7667			       ctl_min(sizeof(res_keys->keys[key_count].key),
7668			       sizeof(lun->per_res[i].res_key)));
7669			key_count++;
7670		}
7671		break;
7672	}
7673	case SPRI_RR: { // read reservation
7674		struct scsi_per_res_in_rsrv *res;
7675		int tmp_len, header_only;
7676
7677		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7678
7679		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7680
7681		if (lun->flags & CTL_LUN_PR_RESERVED)
7682		{
7683			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7684			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7685				    res->header.length);
7686			header_only = 0;
7687		} else {
7688			tmp_len = sizeof(struct scsi_per_res_in_header);
7689			scsi_ulto4b(0, res->header.length);
7690			header_only = 1;
7691		}
7692
7693		/*
7694		 * We had to drop the lock to allocate our buffer, which
7695		 * leaves time for someone to come in with another
7696		 * persistent reservation.  (That is unlikely, though,
7697		 * since this should be the only persistent reservation
7698		 * command active right now.)
7699		 */
7700		if (tmp_len != total_len) {
7701			mtx_unlock(&lun->lun_lock);
7702			free(ctsio->kern_data_ptr, M_CTL);
7703			printf("%s: reservation status changed, retrying\n",
7704			       __func__);
7705			goto retry;
7706		}
7707
7708		/*
7709		 * No reservation held, so we're done.
7710		 */
7711		if (header_only != 0)
7712			break;
7713
7714		/*
7715		 * If the registration is an All Registrants type, the key
7716		 * is 0, since it doesn't really matter.
7717		 */
7718		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7719			memcpy(res->data.reservation,
7720			       &lun->per_res[lun->pr_res_idx].res_key,
7721			       sizeof(struct scsi_per_res_key));
7722		}
7723		res->data.scopetype = lun->res_type;
7724		break;
7725	}
7726	case SPRI_RC:     //report capabilities
7727	{
7728		struct scsi_per_res_cap *res_cap;
7729		uint16_t type_mask;
7730
7731		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7732		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7733		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_3;
7734		type_mask = SPRI_TM_WR_EX_AR |
7735			    SPRI_TM_EX_AC_RO |
7736			    SPRI_TM_WR_EX_RO |
7737			    SPRI_TM_EX_AC |
7738			    SPRI_TM_WR_EX |
7739			    SPRI_TM_EX_AC_AR;
7740		scsi_ulto2b(type_mask, res_cap->type_mask);
7741		break;
7742	}
7743	case SPRI_RS: //read full status
7744	default:
7745		/*
7746		 * This is a bug, because we just checked for this above,
7747		 * and should have returned an error.
7748		 */
7749		panic("Invalid PR type %x", cdb->action);
7750		break; /* NOTREACHED */
7751	}
7752	mtx_unlock(&lun->lun_lock);
7753
7754	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7755	ctsio->be_move_done = ctl_config_move_done;
7756
7757	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7758			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7759			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7760			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7761			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7762
7763	ctl_datamove((union ctl_io *)ctsio);
7764
7765	return (CTL_RETVAL_COMPLETE);
7766}
7767
7768/*
7769 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7770 * it should return.
7771 */
7772static int
7773ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7774		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7775		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7776		struct scsi_per_res_out_parms* param)
7777{
7778	union ctl_ha_msg persis_io;
7779	int retval, i;
7780	int isc_retval;
7781
7782	retval = 0;
7783
7784	mtx_lock(&lun->lun_lock);
7785	if (sa_res_key == 0) {
7786		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7787			/* validate scope and type */
7788			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7789			     SPR_LU_SCOPE) {
7790				mtx_unlock(&lun->lun_lock);
7791				ctl_set_invalid_field(/*ctsio*/ ctsio,
7792						      /*sks_valid*/ 1,
7793						      /*command*/ 1,
7794						      /*field*/ 2,
7795						      /*bit_valid*/ 1,
7796						      /*bit*/ 4);
7797				ctl_done((union ctl_io *)ctsio);
7798				return (1);
7799			}
7800
7801		        if (type>8 || type==2 || type==4 || type==0) {
7802				mtx_unlock(&lun->lun_lock);
7803				ctl_set_invalid_field(/*ctsio*/ ctsio,
7804       	           				      /*sks_valid*/ 1,
7805						      /*command*/ 1,
7806						      /*field*/ 2,
7807						      /*bit_valid*/ 1,
7808						      /*bit*/ 0);
7809				ctl_done((union ctl_io *)ctsio);
7810				return (1);
7811		        }
7812
7813			/* temporarily unregister this nexus */
7814			lun->per_res[residx].registered = 0;
7815
7816			/*
7817			 * Unregister everybody else and build UA for
7818			 * them
7819			 */
7820			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7821				if (lun->per_res[i].registered == 0)
7822					continue;
7823
7824				if (!persis_offset
7825				 && i <CTL_MAX_INITIATORS)
7826					lun->pending_sense[i].ua_pending |=
7827						CTL_UA_REG_PREEMPT;
7828				else if (persis_offset
7829				      && i >= persis_offset)
7830					lun->pending_sense[i-persis_offset
7831						].ua_pending |=
7832						CTL_UA_REG_PREEMPT;
7833				lun->per_res[i].registered = 0;
7834				memset(&lun->per_res[i].res_key, 0,
7835				       sizeof(struct scsi_per_res_key));
7836			}
7837			lun->per_res[residx].registered = 1;
7838			lun->pr_key_count = 1;
7839			lun->res_type = type;
7840			if (lun->res_type != SPR_TYPE_WR_EX_AR
7841			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7842				lun->pr_res_idx = residx;
7843
7844			/* send msg to other side */
7845			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7846			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7847			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7848			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7849			persis_io.pr.pr_info.res_type = type;
7850			memcpy(persis_io.pr.pr_info.sa_res_key,
7851			       param->serv_act_res_key,
7852			       sizeof(param->serv_act_res_key));
7853			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7854			     &persis_io, sizeof(persis_io), 0)) >
7855			     CTL_HA_STATUS_SUCCESS) {
7856				printf("CTL:Persis Out error returned "
7857				       "from ctl_ha_msg_send %d\n",
7858				       isc_retval);
7859			}
7860		} else {
7861			/* not all registrants */
7862			mtx_unlock(&lun->lun_lock);
7863			free(ctsio->kern_data_ptr, M_CTL);
7864			ctl_set_invalid_field(ctsio,
7865					      /*sks_valid*/ 1,
7866					      /*command*/ 0,
7867					      /*field*/ 8,
7868					      /*bit_valid*/ 0,
7869					      /*bit*/ 0);
7870			ctl_done((union ctl_io *)ctsio);
7871			return (1);
7872		}
7873	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7874		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7875		int found = 0;
7876
7877		if (res_key == sa_res_key) {
7878			/* special case */
7879			/*
7880			 * The spec implies this is not good but doesn't
7881			 * say what to do. There are two choices either
7882			 * generate a res conflict or check condition
7883			 * with illegal field in parameter data. Since
7884			 * that is what is done when the sa_res_key is
7885			 * zero I'll take that approach since this has
7886			 * to do with the sa_res_key.
7887			 */
7888			mtx_unlock(&lun->lun_lock);
7889			free(ctsio->kern_data_ptr, M_CTL);
7890			ctl_set_invalid_field(ctsio,
7891					      /*sks_valid*/ 1,
7892					      /*command*/ 0,
7893					      /*field*/ 8,
7894					      /*bit_valid*/ 0,
7895					      /*bit*/ 0);
7896			ctl_done((union ctl_io *)ctsio);
7897			return (1);
7898		}
7899
7900		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7901			if (lun->per_res[i].registered
7902			 && memcmp(param->serv_act_res_key,
7903			    lun->per_res[i].res_key.key,
7904			    sizeof(struct scsi_per_res_key)) != 0)
7905				continue;
7906
7907			found = 1;
7908			lun->per_res[i].registered = 0;
7909			memset(&lun->per_res[i].res_key, 0,
7910			       sizeof(struct scsi_per_res_key));
7911			lun->pr_key_count--;
7912
7913			if (!persis_offset
7914			 && i < CTL_MAX_INITIATORS)
7915				lun->pending_sense[i].ua_pending |=
7916					CTL_UA_REG_PREEMPT;
7917			else if (persis_offset
7918			      && i >= persis_offset)
7919				lun->pending_sense[i-persis_offset].ua_pending|=
7920					CTL_UA_REG_PREEMPT;
7921		}
7922		if (!found) {
7923			mtx_unlock(&lun->lun_lock);
7924			free(ctsio->kern_data_ptr, M_CTL);
7925			ctl_set_reservation_conflict(ctsio);
7926			ctl_done((union ctl_io *)ctsio);
7927			return (CTL_RETVAL_COMPLETE);
7928		}
7929		/* send msg to other side */
7930		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7931		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7932		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7933		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7934		persis_io.pr.pr_info.res_type = type;
7935		memcpy(persis_io.pr.pr_info.sa_res_key,
7936		       param->serv_act_res_key,
7937		       sizeof(param->serv_act_res_key));
7938		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7939		     &persis_io, sizeof(persis_io), 0)) >
7940		     CTL_HA_STATUS_SUCCESS) {
7941			printf("CTL:Persis Out error returned from "
7942			       "ctl_ha_msg_send %d\n", isc_retval);
7943		}
7944	} else {
7945		/* Reserved but not all registrants */
7946		/* sa_res_key is res holder */
7947		if (memcmp(param->serv_act_res_key,
7948                   lun->per_res[lun->pr_res_idx].res_key.key,
7949                   sizeof(struct scsi_per_res_key)) == 0) {
7950			/* validate scope and type */
7951			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7952			     SPR_LU_SCOPE) {
7953				mtx_unlock(&lun->lun_lock);
7954				ctl_set_invalid_field(/*ctsio*/ ctsio,
7955						      /*sks_valid*/ 1,
7956						      /*command*/ 1,
7957						      /*field*/ 2,
7958						      /*bit_valid*/ 1,
7959						      /*bit*/ 4);
7960				ctl_done((union ctl_io *)ctsio);
7961				return (1);
7962			}
7963
7964			if (type>8 || type==2 || type==4 || type==0) {
7965				mtx_unlock(&lun->lun_lock);
7966				ctl_set_invalid_field(/*ctsio*/ ctsio,
7967						      /*sks_valid*/ 1,
7968						      /*command*/ 1,
7969						      /*field*/ 2,
7970						      /*bit_valid*/ 1,
7971						      /*bit*/ 0);
7972				ctl_done((union ctl_io *)ctsio);
7973				return (1);
7974			}
7975
7976			/*
7977			 * Do the following:
7978			 * if sa_res_key != res_key remove all
7979			 * registrants w/sa_res_key and generate UA
7980			 * for these registrants(Registrations
7981			 * Preempted) if it wasn't an exclusive
7982			 * reservation generate UA(Reservations
7983			 * Preempted) for all other registered nexuses
7984			 * if the type has changed. Establish the new
7985			 * reservation and holder. If res_key and
7986			 * sa_res_key are the same do the above
7987			 * except don't unregister the res holder.
7988			 */
7989
7990			/*
7991			 * Temporarily unregister so it won't get
7992			 * removed or UA generated
7993			 */
7994			lun->per_res[residx].registered = 0;
7995			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7996				if (lun->per_res[i].registered == 0)
7997					continue;
7998
7999				if (memcmp(param->serv_act_res_key,
8000				    lun->per_res[i].res_key.key,
8001				    sizeof(struct scsi_per_res_key)) == 0) {
8002					lun->per_res[i].registered = 0;
8003					memset(&lun->per_res[i].res_key,
8004					       0,
8005					       sizeof(struct scsi_per_res_key));
8006					lun->pr_key_count--;
8007
8008					if (!persis_offset
8009					 && i < CTL_MAX_INITIATORS)
8010						lun->pending_sense[i
8011							].ua_pending |=
8012							CTL_UA_REG_PREEMPT;
8013					else if (persis_offset
8014					      && i >= persis_offset)
8015						lun->pending_sense[
8016						  i-persis_offset].ua_pending |=
8017						  CTL_UA_REG_PREEMPT;
8018				} else if (type != lun->res_type
8019					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8020					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8021						if (!persis_offset
8022						 && i < CTL_MAX_INITIATORS)
8023							lun->pending_sense[i
8024							].ua_pending |=
8025							CTL_UA_RES_RELEASE;
8026						else if (persis_offset
8027						      && i >= persis_offset)
8028							lun->pending_sense[
8029							i-persis_offset
8030							].ua_pending |=
8031							CTL_UA_RES_RELEASE;
8032				}
8033			}
8034			lun->per_res[residx].registered = 1;
8035			lun->res_type = type;
8036			if (lun->res_type != SPR_TYPE_WR_EX_AR
8037			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8038				lun->pr_res_idx = residx;
8039			else
8040				lun->pr_res_idx =
8041					CTL_PR_ALL_REGISTRANTS;
8042
8043			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8044			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8045			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8046			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8047			persis_io.pr.pr_info.res_type = type;
8048			memcpy(persis_io.pr.pr_info.sa_res_key,
8049			       param->serv_act_res_key,
8050			       sizeof(param->serv_act_res_key));
8051			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8052			     &persis_io, sizeof(persis_io), 0)) >
8053			     CTL_HA_STATUS_SUCCESS) {
8054				printf("CTL:Persis Out error returned "
8055				       "from ctl_ha_msg_send %d\n",
8056				       isc_retval);
8057			}
8058		} else {
8059			/*
8060			 * sa_res_key is not the res holder just
8061			 * remove registrants
8062			 */
8063			int found=0;
8064
8065			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8066				if (memcmp(param->serv_act_res_key,
8067				    lun->per_res[i].res_key.key,
8068				    sizeof(struct scsi_per_res_key)) != 0)
8069					continue;
8070
8071				found = 1;
8072				lun->per_res[i].registered = 0;
8073				memset(&lun->per_res[i].res_key, 0,
8074				       sizeof(struct scsi_per_res_key));
8075				lun->pr_key_count--;
8076
8077				if (!persis_offset
8078				 && i < CTL_MAX_INITIATORS)
8079					lun->pending_sense[i].ua_pending |=
8080						CTL_UA_REG_PREEMPT;
8081				else if (persis_offset
8082				      && i >= persis_offset)
8083					lun->pending_sense[
8084						i-persis_offset].ua_pending |=
8085						CTL_UA_REG_PREEMPT;
8086			}
8087
8088			if (!found) {
8089				mtx_unlock(&lun->lun_lock);
8090				free(ctsio->kern_data_ptr, M_CTL);
8091				ctl_set_reservation_conflict(ctsio);
8092				ctl_done((union ctl_io *)ctsio);
8093		        	return (1);
8094			}
8095			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8096			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8097			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8098			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8099			persis_io.pr.pr_info.res_type = type;
8100			memcpy(persis_io.pr.pr_info.sa_res_key,
8101			       param->serv_act_res_key,
8102			       sizeof(param->serv_act_res_key));
8103			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8104			     &persis_io, sizeof(persis_io), 0)) >
8105			     CTL_HA_STATUS_SUCCESS) {
8106				printf("CTL:Persis Out error returned "
8107				       "from ctl_ha_msg_send %d\n",
8108				isc_retval);
8109			}
8110		}
8111	}
8112
8113	lun->PRGeneration++;
8114	mtx_unlock(&lun->lun_lock);
8115
8116	return (retval);
8117}
8118
8119static void
8120ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8121{
8122	int i;
8123
8124	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8125	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8126	 || memcmp(&lun->per_res[lun->pr_res_idx].res_key,
8127		   msg->pr.pr_info.sa_res_key,
8128		   sizeof(struct scsi_per_res_key)) != 0) {
8129		uint64_t sa_res_key;
8130		sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8131
8132		if (sa_res_key == 0) {
8133			/* temporarily unregister this nexus */
8134			lun->per_res[msg->pr.pr_info.residx].registered = 0;
8135
8136			/*
8137			 * Unregister everybody else and build UA for
8138			 * them
8139			 */
8140			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8141				if (lun->per_res[i].registered == 0)
8142					continue;
8143
8144				if (!persis_offset
8145				 && i < CTL_MAX_INITIATORS)
8146					lun->pending_sense[i].ua_pending |=
8147						CTL_UA_REG_PREEMPT;
8148				else if (persis_offset && i >= persis_offset)
8149					lun->pending_sense[i -
8150						persis_offset].ua_pending |=
8151						CTL_UA_REG_PREEMPT;
8152				lun->per_res[i].registered = 0;
8153				memset(&lun->per_res[i].res_key, 0,
8154				       sizeof(struct scsi_per_res_key));
8155			}
8156
8157			lun->per_res[msg->pr.pr_info.residx].registered = 1;
8158			lun->pr_key_count = 1;
8159			lun->res_type = msg->pr.pr_info.res_type;
8160			if (lun->res_type != SPR_TYPE_WR_EX_AR
8161			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8162				lun->pr_res_idx = msg->pr.pr_info.residx;
8163		} else {
8164		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8165				if (memcmp(msg->pr.pr_info.sa_res_key,
8166		                   lun->per_res[i].res_key.key,
8167		                   sizeof(struct scsi_per_res_key)) != 0)
8168					continue;
8169
8170				lun->per_res[i].registered = 0;
8171				memset(&lun->per_res[i].res_key, 0,
8172				       sizeof(struct scsi_per_res_key));
8173				lun->pr_key_count--;
8174
8175				if (!persis_offset
8176				 && i < persis_offset)
8177					lun->pending_sense[i].ua_pending |=
8178						CTL_UA_REG_PREEMPT;
8179				else if (persis_offset
8180				      && i >= persis_offset)
8181					lun->pending_sense[i -
8182						persis_offset].ua_pending |=
8183						CTL_UA_REG_PREEMPT;
8184			}
8185		}
8186	} else {
8187		/*
8188		 * Temporarily unregister so it won't get removed
8189		 * or UA generated
8190		 */
8191		lun->per_res[msg->pr.pr_info.residx].registered = 0;
8192		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8193			if (lun->per_res[i].registered == 0)
8194				continue;
8195
8196			if (memcmp(msg->pr.pr_info.sa_res_key,
8197	                   lun->per_res[i].res_key.key,
8198	                   sizeof(struct scsi_per_res_key)) == 0) {
8199				lun->per_res[i].registered = 0;
8200				memset(&lun->per_res[i].res_key, 0,
8201				       sizeof(struct scsi_per_res_key));
8202				lun->pr_key_count--;
8203				if (!persis_offset
8204				 && i < CTL_MAX_INITIATORS)
8205					lun->pending_sense[i].ua_pending |=
8206						CTL_UA_REG_PREEMPT;
8207				else if (persis_offset
8208				      && i >= persis_offset)
8209					lun->pending_sense[i -
8210						persis_offset].ua_pending |=
8211						CTL_UA_REG_PREEMPT;
8212			} else if (msg->pr.pr_info.res_type != lun->res_type
8213				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8214				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8215					if (!persis_offset
8216					 && i < persis_offset)
8217						lun->pending_sense[i
8218							].ua_pending |=
8219							CTL_UA_RES_RELEASE;
8220					else if (persis_offset
8221					      && i >= persis_offset)
8222					lun->pending_sense[i -
8223						persis_offset].ua_pending |=
8224						CTL_UA_RES_RELEASE;
8225			}
8226		}
8227		lun->per_res[msg->pr.pr_info.residx].registered = 1;
8228		lun->res_type = msg->pr.pr_info.res_type;
8229		if (lun->res_type != SPR_TYPE_WR_EX_AR
8230		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8231			lun->pr_res_idx = msg->pr.pr_info.residx;
8232		else
8233			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8234	}
8235	lun->PRGeneration++;
8236
8237}
8238
8239
8240int
8241ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8242{
8243	int retval;
8244	int isc_retval;
8245	u_int32_t param_len;
8246	struct scsi_per_res_out *cdb;
8247	struct ctl_lun *lun;
8248	struct scsi_per_res_out_parms* param;
8249	struct ctl_softc *softc;
8250	uint32_t residx;
8251	uint64_t res_key, sa_res_key;
8252	uint8_t type;
8253	union ctl_ha_msg persis_io;
8254	int    i;
8255
8256	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8257
8258	retval = CTL_RETVAL_COMPLETE;
8259
8260	softc = control_softc;
8261
8262	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8263	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8264
8265	/*
8266	 * We only support whole-LUN scope.  The scope & type are ignored for
8267	 * register, register and ignore existing key and clear.
8268	 * We sometimes ignore scope and type on preempts too!!
8269	 * Verify reservation type here as well.
8270	 */
8271	type = cdb->scope_type & SPR_TYPE_MASK;
8272	if ((cdb->action == SPRO_RESERVE)
8273	 || (cdb->action == SPRO_RELEASE)) {
8274		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8275			ctl_set_invalid_field(/*ctsio*/ ctsio,
8276					      /*sks_valid*/ 1,
8277					      /*command*/ 1,
8278					      /*field*/ 2,
8279					      /*bit_valid*/ 1,
8280					      /*bit*/ 4);
8281			ctl_done((union ctl_io *)ctsio);
8282			return (CTL_RETVAL_COMPLETE);
8283		}
8284
8285		if (type>8 || type==2 || type==4 || type==0) {
8286			ctl_set_invalid_field(/*ctsio*/ ctsio,
8287					      /*sks_valid*/ 1,
8288					      /*command*/ 1,
8289					      /*field*/ 2,
8290					      /*bit_valid*/ 1,
8291					      /*bit*/ 0);
8292			ctl_done((union ctl_io *)ctsio);
8293			return (CTL_RETVAL_COMPLETE);
8294		}
8295	}
8296
8297	param_len = scsi_4btoul(cdb->length);
8298
8299	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8300		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8301		ctsio->kern_data_len = param_len;
8302		ctsio->kern_total_len = param_len;
8303		ctsio->kern_data_resid = 0;
8304		ctsio->kern_rel_offset = 0;
8305		ctsio->kern_sg_entries = 0;
8306		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8307		ctsio->be_move_done = ctl_config_move_done;
8308		ctl_datamove((union ctl_io *)ctsio);
8309
8310		return (CTL_RETVAL_COMPLETE);
8311	}
8312
8313	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8314
8315	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8316	res_key = scsi_8btou64(param->res_key.key);
8317	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8318
8319	/*
8320	 * Validate the reservation key here except for SPRO_REG_IGNO
8321	 * This must be done for all other service actions
8322	 */
8323	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8324		mtx_lock(&lun->lun_lock);
8325		if (lun->per_res[residx].registered) {
8326		    if (memcmp(param->res_key.key,
8327			       lun->per_res[residx].res_key.key,
8328			       ctl_min(sizeof(param->res_key),
8329			       sizeof(lun->per_res[residx].res_key))) != 0) {
8330				/*
8331				 * The current key passed in doesn't match
8332				 * the one the initiator previously
8333				 * registered.
8334				 */
8335				mtx_unlock(&lun->lun_lock);
8336				free(ctsio->kern_data_ptr, M_CTL);
8337				ctl_set_reservation_conflict(ctsio);
8338				ctl_done((union ctl_io *)ctsio);
8339				return (CTL_RETVAL_COMPLETE);
8340			}
8341		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8342			/*
8343			 * We are not registered
8344			 */
8345			mtx_unlock(&lun->lun_lock);
8346			free(ctsio->kern_data_ptr, M_CTL);
8347			ctl_set_reservation_conflict(ctsio);
8348			ctl_done((union ctl_io *)ctsio);
8349			return (CTL_RETVAL_COMPLETE);
8350		} else if (res_key != 0) {
8351			/*
8352			 * We are not registered and trying to register but
8353			 * the register key isn't zero.
8354			 */
8355			mtx_unlock(&lun->lun_lock);
8356			free(ctsio->kern_data_ptr, M_CTL);
8357			ctl_set_reservation_conflict(ctsio);
8358			ctl_done((union ctl_io *)ctsio);
8359			return (CTL_RETVAL_COMPLETE);
8360		}
8361		mtx_unlock(&lun->lun_lock);
8362	}
8363
8364	switch (cdb->action & SPRO_ACTION_MASK) {
8365	case SPRO_REGISTER:
8366	case SPRO_REG_IGNO: {
8367
8368#if 0
8369		printf("Registration received\n");
8370#endif
8371
8372		/*
8373		 * We don't support any of these options, as we report in
8374		 * the read capabilities request (see
8375		 * ctl_persistent_reserve_in(), above).
8376		 */
8377		if ((param->flags & SPR_SPEC_I_PT)
8378		 || (param->flags & SPR_ALL_TG_PT)
8379		 || (param->flags & SPR_APTPL)) {
8380			int bit_ptr;
8381
8382			if (param->flags & SPR_APTPL)
8383				bit_ptr = 0;
8384			else if (param->flags & SPR_ALL_TG_PT)
8385				bit_ptr = 2;
8386			else /* SPR_SPEC_I_PT */
8387				bit_ptr = 3;
8388
8389			free(ctsio->kern_data_ptr, M_CTL);
8390			ctl_set_invalid_field(ctsio,
8391					      /*sks_valid*/ 1,
8392					      /*command*/ 0,
8393					      /*field*/ 20,
8394					      /*bit_valid*/ 1,
8395					      /*bit*/ bit_ptr);
8396			ctl_done((union ctl_io *)ctsio);
8397			return (CTL_RETVAL_COMPLETE);
8398		}
8399
8400		mtx_lock(&lun->lun_lock);
8401
8402		/*
8403		 * The initiator wants to clear the
8404		 * key/unregister.
8405		 */
8406		if (sa_res_key == 0) {
8407			if ((res_key == 0
8408			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8409			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8410			  && !lun->per_res[residx].registered)) {
8411				mtx_unlock(&lun->lun_lock);
8412				goto done;
8413			}
8414
8415			lun->per_res[residx].registered = 0;
8416			memset(&lun->per_res[residx].res_key,
8417			       0, sizeof(lun->per_res[residx].res_key));
8418			lun->pr_key_count--;
8419
8420			if (residx == lun->pr_res_idx) {
8421				lun->flags &= ~CTL_LUN_PR_RESERVED;
8422				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8423
8424				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8425				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8426				 && lun->pr_key_count) {
8427					/*
8428					 * If the reservation is a registrants
8429					 * only type we need to generate a UA
8430					 * for other registered inits.  The
8431					 * sense code should be RESERVATIONS
8432					 * RELEASED
8433					 */
8434
8435					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8436						if (lun->per_res[
8437						    i+persis_offset].registered
8438						    == 0)
8439							continue;
8440						lun->pending_sense[i
8441							].ua_pending |=
8442							CTL_UA_RES_RELEASE;
8443					}
8444				}
8445				lun->res_type = 0;
8446			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8447				if (lun->pr_key_count==0) {
8448					lun->flags &= ~CTL_LUN_PR_RESERVED;
8449					lun->res_type = 0;
8450					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8451				}
8452			}
8453			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8454			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8455			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8456			persis_io.pr.pr_info.residx = residx;
8457			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8458			     &persis_io, sizeof(persis_io), 0 )) >
8459			     CTL_HA_STATUS_SUCCESS) {
8460				printf("CTL:Persis Out error returned from "
8461				       "ctl_ha_msg_send %d\n", isc_retval);
8462			}
8463		} else /* sa_res_key != 0 */ {
8464
8465			/*
8466			 * If we aren't registered currently then increment
8467			 * the key count and set the registered flag.
8468			 */
8469			if (!lun->per_res[residx].registered) {
8470				lun->pr_key_count++;
8471				lun->per_res[residx].registered = 1;
8472			}
8473
8474			memcpy(&lun->per_res[residx].res_key,
8475			       param->serv_act_res_key,
8476			       ctl_min(sizeof(param->serv_act_res_key),
8477			       sizeof(lun->per_res[residx].res_key)));
8478
8479			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8480			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8481			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8482			persis_io.pr.pr_info.residx = residx;
8483			memcpy(persis_io.pr.pr_info.sa_res_key,
8484			       param->serv_act_res_key,
8485			       sizeof(param->serv_act_res_key));
8486			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8487			     &persis_io, sizeof(persis_io), 0)) >
8488			     CTL_HA_STATUS_SUCCESS) {
8489				printf("CTL:Persis Out error returned from "
8490				       "ctl_ha_msg_send %d\n", isc_retval);
8491			}
8492		}
8493		lun->PRGeneration++;
8494		mtx_unlock(&lun->lun_lock);
8495
8496		break;
8497	}
8498	case SPRO_RESERVE:
8499#if 0
8500                printf("Reserve executed type %d\n", type);
8501#endif
8502		mtx_lock(&lun->lun_lock);
8503		if (lun->flags & CTL_LUN_PR_RESERVED) {
8504			/*
8505			 * if this isn't the reservation holder and it's
8506			 * not a "all registrants" type or if the type is
8507			 * different then we have a conflict
8508			 */
8509			if ((lun->pr_res_idx != residx
8510			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8511			 || lun->res_type != type) {
8512				mtx_unlock(&lun->lun_lock);
8513				free(ctsio->kern_data_ptr, M_CTL);
8514				ctl_set_reservation_conflict(ctsio);
8515				ctl_done((union ctl_io *)ctsio);
8516				return (CTL_RETVAL_COMPLETE);
8517			}
8518			mtx_unlock(&lun->lun_lock);
8519		} else /* create a reservation */ {
8520			/*
8521			 * If it's not an "all registrants" type record
8522			 * reservation holder
8523			 */
8524			if (type != SPR_TYPE_WR_EX_AR
8525			 && type != SPR_TYPE_EX_AC_AR)
8526				lun->pr_res_idx = residx; /* Res holder */
8527			else
8528				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8529
8530			lun->flags |= CTL_LUN_PR_RESERVED;
8531			lun->res_type = type;
8532
8533			mtx_unlock(&lun->lun_lock);
8534
8535			/* send msg to other side */
8536			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8537			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8538			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8539			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8540			persis_io.pr.pr_info.res_type = type;
8541			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8542			     &persis_io, sizeof(persis_io), 0)) >
8543			     CTL_HA_STATUS_SUCCESS) {
8544				printf("CTL:Persis Out error returned from "
8545				       "ctl_ha_msg_send %d\n", isc_retval);
8546			}
8547		}
8548		break;
8549
8550	case SPRO_RELEASE:
8551		mtx_lock(&lun->lun_lock);
8552		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8553			/* No reservation exists return good status */
8554			mtx_unlock(&lun->lun_lock);
8555			goto done;
8556		}
8557		/*
8558		 * Is this nexus a reservation holder?
8559		 */
8560		if (lun->pr_res_idx != residx
8561		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8562			/*
8563			 * not a res holder return good status but
8564			 * do nothing
8565			 */
8566			mtx_unlock(&lun->lun_lock);
8567			goto done;
8568		}
8569
8570		if (lun->res_type != type) {
8571			mtx_unlock(&lun->lun_lock);
8572			free(ctsio->kern_data_ptr, M_CTL);
8573			ctl_set_illegal_pr_release(ctsio);
8574			ctl_done((union ctl_io *)ctsio);
8575			return (CTL_RETVAL_COMPLETE);
8576		}
8577
8578		/* okay to release */
8579		lun->flags &= ~CTL_LUN_PR_RESERVED;
8580		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8581		lun->res_type = 0;
8582
8583		/*
8584		 * if this isn't an exclusive access
8585		 * res generate UA for all other
8586		 * registrants.
8587		 */
8588		if (type != SPR_TYPE_EX_AC
8589		 && type != SPR_TYPE_WR_EX) {
8590			/*
8591			 * temporarily unregister so we don't generate UA
8592			 */
8593			lun->per_res[residx].registered = 0;
8594
8595			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8596				if (lun->per_res[i+persis_offset].registered
8597				    == 0)
8598					continue;
8599				lun->pending_sense[i].ua_pending |=
8600					CTL_UA_RES_RELEASE;
8601			}
8602
8603			lun->per_res[residx].registered = 1;
8604		}
8605		mtx_unlock(&lun->lun_lock);
8606		/* Send msg to other side */
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_RELEASE;
8610		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8611		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8612			printf("CTL:Persis Out error returned from "
8613			       "ctl_ha_msg_send %d\n", isc_retval);
8614		}
8615		break;
8616
8617	case SPRO_CLEAR:
8618		/* send msg to other side */
8619
8620		mtx_lock(&lun->lun_lock);
8621		lun->flags &= ~CTL_LUN_PR_RESERVED;
8622		lun->res_type = 0;
8623		lun->pr_key_count = 0;
8624		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8625
8626
8627		memset(&lun->per_res[residx].res_key,
8628		       0, sizeof(lun->per_res[residx].res_key));
8629		lun->per_res[residx].registered = 0;
8630
8631		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8632			if (lun->per_res[i].registered) {
8633				if (!persis_offset && i < CTL_MAX_INITIATORS)
8634					lun->pending_sense[i].ua_pending |=
8635						CTL_UA_RES_PREEMPT;
8636				else if (persis_offset && i >= persis_offset)
8637					lun->pending_sense[i-persis_offset
8638					    ].ua_pending |= CTL_UA_RES_PREEMPT;
8639
8640				memset(&lun->per_res[i].res_key,
8641				       0, sizeof(struct scsi_per_res_key));
8642				lun->per_res[i].registered = 0;
8643			}
8644		lun->PRGeneration++;
8645		mtx_unlock(&lun->lun_lock);
8646		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8647		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8648		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8649		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8650		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8651			printf("CTL:Persis Out error returned from "
8652			       "ctl_ha_msg_send %d\n", isc_retval);
8653		}
8654		break;
8655
8656	case SPRO_PREEMPT: {
8657		int nretval;
8658
8659		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8660					  residx, ctsio, cdb, param);
8661		if (nretval != 0)
8662			return (CTL_RETVAL_COMPLETE);
8663		break;
8664	}
8665	default:
8666		panic("Invalid PR type %x", cdb->action);
8667	}
8668
8669done:
8670	free(ctsio->kern_data_ptr, M_CTL);
8671	ctl_set_success(ctsio);
8672	ctl_done((union ctl_io *)ctsio);
8673
8674	return (retval);
8675}
8676
8677/*
8678 * This routine is for handling a message from the other SC pertaining to
8679 * persistent reserve out. All the error checking will have been done
8680 * so only perorming the action need be done here to keep the two
8681 * in sync.
8682 */
8683static void
8684ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8685{
8686	struct ctl_lun *lun;
8687	struct ctl_softc *softc;
8688	int i;
8689	uint32_t targ_lun;
8690
8691	softc = control_softc;
8692
8693	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8694	lun = softc->ctl_luns[targ_lun];
8695	mtx_lock(&lun->lun_lock);
8696	switch(msg->pr.pr_info.action) {
8697	case CTL_PR_REG_KEY:
8698		if (!lun->per_res[msg->pr.pr_info.residx].registered) {
8699			lun->per_res[msg->pr.pr_info.residx].registered = 1;
8700			lun->pr_key_count++;
8701		}
8702		lun->PRGeneration++;
8703		memcpy(&lun->per_res[msg->pr.pr_info.residx].res_key,
8704		       msg->pr.pr_info.sa_res_key,
8705		       sizeof(struct scsi_per_res_key));
8706		break;
8707
8708	case CTL_PR_UNREG_KEY:
8709		lun->per_res[msg->pr.pr_info.residx].registered = 0;
8710		memset(&lun->per_res[msg->pr.pr_info.residx].res_key,
8711		       0, sizeof(struct scsi_per_res_key));
8712		lun->pr_key_count--;
8713
8714		/* XXX Need to see if the reservation has been released */
8715		/* if so do we need to generate UA? */
8716		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8717			lun->flags &= ~CTL_LUN_PR_RESERVED;
8718			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8719
8720			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8721			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8722			 && lun->pr_key_count) {
8723				/*
8724				 * If the reservation is a registrants
8725				 * only type we need to generate a UA
8726				 * for other registered inits.  The
8727				 * sense code should be RESERVATIONS
8728				 * RELEASED
8729				 */
8730
8731				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8732					if (lun->per_res[i+
8733					    persis_offset].registered == 0)
8734						continue;
8735
8736					lun->pending_sense[i
8737						].ua_pending |=
8738						CTL_UA_RES_RELEASE;
8739				}
8740			}
8741			lun->res_type = 0;
8742		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8743			if (lun->pr_key_count==0) {
8744				lun->flags &= ~CTL_LUN_PR_RESERVED;
8745				lun->res_type = 0;
8746				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8747			}
8748		}
8749		lun->PRGeneration++;
8750		break;
8751
8752	case CTL_PR_RESERVE:
8753		lun->flags |= CTL_LUN_PR_RESERVED;
8754		lun->res_type = msg->pr.pr_info.res_type;
8755		lun->pr_res_idx = msg->pr.pr_info.residx;
8756
8757		break;
8758
8759	case CTL_PR_RELEASE:
8760		/*
8761		 * if this isn't an exclusive access res generate UA for all
8762		 * other registrants.
8763		 */
8764		if (lun->res_type != SPR_TYPE_EX_AC
8765		 && lun->res_type != SPR_TYPE_WR_EX) {
8766			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8767				if (lun->per_res[i+persis_offset].registered)
8768					lun->pending_sense[i].ua_pending |=
8769						CTL_UA_RES_RELEASE;
8770		}
8771
8772		lun->flags &= ~CTL_LUN_PR_RESERVED;
8773		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8774		lun->res_type = 0;
8775		break;
8776
8777	case CTL_PR_PREEMPT:
8778		ctl_pro_preempt_other(lun, msg);
8779		break;
8780	case CTL_PR_CLEAR:
8781		lun->flags &= ~CTL_LUN_PR_RESERVED;
8782		lun->res_type = 0;
8783		lun->pr_key_count = 0;
8784		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8785
8786		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8787			if (lun->per_res[i].registered == 0)
8788				continue;
8789			if (!persis_offset
8790			 && i < CTL_MAX_INITIATORS)
8791				lun->pending_sense[i].ua_pending |=
8792					CTL_UA_RES_PREEMPT;
8793			else if (persis_offset
8794			      && i >= persis_offset)
8795   				lun->pending_sense[i-persis_offset].ua_pending|=
8796					CTL_UA_RES_PREEMPT;
8797			memset(&lun->per_res[i].res_key, 0,
8798			       sizeof(struct scsi_per_res_key));
8799			lun->per_res[i].registered = 0;
8800		}
8801		lun->PRGeneration++;
8802		break;
8803	}
8804
8805	mtx_unlock(&lun->lun_lock);
8806}
8807
8808int
8809ctl_read_write(struct ctl_scsiio *ctsio)
8810{
8811	struct ctl_lun *lun;
8812	struct ctl_lba_len_flags *lbalen;
8813	uint64_t lba;
8814	uint32_t num_blocks;
8815	int fua, dpo;
8816	int retval;
8817	int isread;
8818
8819	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8820
8821	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8822
8823	fua = 0;
8824	dpo = 0;
8825
8826	retval = CTL_RETVAL_COMPLETE;
8827
8828	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8829	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8830	if (lun->flags & CTL_LUN_PR_RESERVED && isread) {
8831		uint32_t residx;
8832
8833		/*
8834		 * XXX KDM need a lock here.
8835		 */
8836		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8837		if ((lun->res_type == SPR_TYPE_EX_AC
8838		  && residx != lun->pr_res_idx)
8839		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
8840		   || lun->res_type == SPR_TYPE_EX_AC_AR)
8841		  && !lun->per_res[residx].registered)) {
8842			ctl_set_reservation_conflict(ctsio);
8843			ctl_done((union ctl_io *)ctsio);
8844			return (CTL_RETVAL_COMPLETE);
8845	        }
8846	}
8847
8848	switch (ctsio->cdb[0]) {
8849	case READ_6:
8850	case WRITE_6: {
8851		struct scsi_rw_6 *cdb;
8852
8853		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8854
8855		lba = scsi_3btoul(cdb->addr);
8856		/* only 5 bits are valid in the most significant address byte */
8857		lba &= 0x1fffff;
8858		num_blocks = cdb->length;
8859		/*
8860		 * This is correct according to SBC-2.
8861		 */
8862		if (num_blocks == 0)
8863			num_blocks = 256;
8864		break;
8865	}
8866	case READ_10:
8867	case WRITE_10: {
8868		struct scsi_rw_10 *cdb;
8869
8870		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8871
8872		if (cdb->byte2 & SRW10_FUA)
8873			fua = 1;
8874		if (cdb->byte2 & SRW10_DPO)
8875			dpo = 1;
8876
8877		lba = scsi_4btoul(cdb->addr);
8878		num_blocks = scsi_2btoul(cdb->length);
8879		break;
8880	}
8881	case WRITE_VERIFY_10: {
8882		struct scsi_write_verify_10 *cdb;
8883
8884		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8885
8886		/*
8887		 * XXX KDM we should do actual write verify support at some
8888		 * point.  This is obviously fake, we're just translating
8889		 * things to a write.  So we don't even bother checking the
8890		 * BYTCHK field, since we don't do any verification.  If
8891		 * the user asks for it, we'll just pretend we did it.
8892		 */
8893		if (cdb->byte2 & SWV_DPO)
8894			dpo = 1;
8895
8896		lba = scsi_4btoul(cdb->addr);
8897		num_blocks = scsi_2btoul(cdb->length);
8898		break;
8899	}
8900	case READ_12:
8901	case WRITE_12: {
8902		struct scsi_rw_12 *cdb;
8903
8904		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8905
8906		if (cdb->byte2 & SRW12_FUA)
8907			fua = 1;
8908		if (cdb->byte2 & SRW12_DPO)
8909			dpo = 1;
8910		lba = scsi_4btoul(cdb->addr);
8911		num_blocks = scsi_4btoul(cdb->length);
8912		break;
8913	}
8914	case WRITE_VERIFY_12: {
8915		struct scsi_write_verify_12 *cdb;
8916
8917		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8918
8919		if (cdb->byte2 & SWV_DPO)
8920			dpo = 1;
8921
8922		lba = scsi_4btoul(cdb->addr);
8923		num_blocks = scsi_4btoul(cdb->length);
8924
8925		break;
8926	}
8927	case READ_16:
8928	case WRITE_16: {
8929		struct scsi_rw_16 *cdb;
8930
8931		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8932
8933		if (cdb->byte2 & SRW12_FUA)
8934			fua = 1;
8935		if (cdb->byte2 & SRW12_DPO)
8936			dpo = 1;
8937
8938		lba = scsi_8btou64(cdb->addr);
8939		num_blocks = scsi_4btoul(cdb->length);
8940		break;
8941	}
8942	case WRITE_VERIFY_16: {
8943		struct scsi_write_verify_16 *cdb;
8944
8945		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8946
8947		if (cdb->byte2 & SWV_DPO)
8948			dpo = 1;
8949
8950		lba = scsi_8btou64(cdb->addr);
8951		num_blocks = scsi_4btoul(cdb->length);
8952		break;
8953	}
8954	default:
8955		/*
8956		 * We got a command we don't support.  This shouldn't
8957		 * happen, commands should be filtered out above us.
8958		 */
8959		ctl_set_invalid_opcode(ctsio);
8960		ctl_done((union ctl_io *)ctsio);
8961
8962		return (CTL_RETVAL_COMPLETE);
8963		break; /* NOTREACHED */
8964	}
8965
8966	/*
8967	 * XXX KDM what do we do with the DPO and FUA bits?  FUA might be
8968	 * interesting for us, but if RAIDCore is in write-back mode,
8969	 * getting it to do write-through for a particular transaction may
8970	 * not be possible.
8971	 */
8972
8973	/*
8974	 * The first check is to make sure we're in bounds, the second
8975	 * check is to catch wrap-around problems.  If the lba + num blocks
8976	 * is less than the lba, then we've wrapped around and the block
8977	 * range is invalid anyway.
8978	 */
8979	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8980	 || ((lba + num_blocks) < lba)) {
8981		ctl_set_lba_out_of_range(ctsio);
8982		ctl_done((union ctl_io *)ctsio);
8983		return (CTL_RETVAL_COMPLETE);
8984	}
8985
8986	/*
8987	 * According to SBC-3, a transfer length of 0 is not an error.
8988	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8989	 * translates to 256 blocks for those commands.
8990	 */
8991	if (num_blocks == 0) {
8992		ctl_set_success(ctsio);
8993		ctl_done((union ctl_io *)ctsio);
8994		return (CTL_RETVAL_COMPLETE);
8995	}
8996
8997	lbalen = (struct ctl_lba_len_flags *)
8998	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8999	lbalen->lba = lba;
9000	lbalen->len = num_blocks;
9001	lbalen->flags = isread ? CTL_LLF_READ : CTL_LLF_WRITE;
9002
9003	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9004	ctsio->kern_rel_offset = 0;
9005
9006	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9007
9008	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9009
9010	return (retval);
9011}
9012
9013static int
9014ctl_cnw_cont(union ctl_io *io)
9015{
9016	struct ctl_scsiio *ctsio;
9017	struct ctl_lun *lun;
9018	struct ctl_lba_len_flags *lbalen;
9019	int retval;
9020
9021	ctsio = &io->scsiio;
9022	ctsio->io_hdr.status = CTL_STATUS_NONE;
9023	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9024	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9025	lbalen = (struct ctl_lba_len_flags *)
9026	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9027	lbalen->flags = CTL_LLF_WRITE;
9028
9029	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9030	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9031	return (retval);
9032}
9033
9034int
9035ctl_cnw(struct ctl_scsiio *ctsio)
9036{
9037	struct ctl_lun *lun;
9038	struct ctl_lba_len_flags *lbalen;
9039	uint64_t lba;
9040	uint32_t num_blocks;
9041	int fua, dpo;
9042	int retval;
9043
9044	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9045
9046	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9047
9048	fua = 0;
9049	dpo = 0;
9050
9051	retval = CTL_RETVAL_COMPLETE;
9052
9053	switch (ctsio->cdb[0]) {
9054	case COMPARE_AND_WRITE: {
9055		struct scsi_compare_and_write *cdb;
9056
9057		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9058
9059		if (cdb->byte2 & SRW10_FUA)
9060			fua = 1;
9061		if (cdb->byte2 & SRW10_DPO)
9062			dpo = 1;
9063		lba = scsi_8btou64(cdb->addr);
9064		num_blocks = cdb->length;
9065		break;
9066	}
9067	default:
9068		/*
9069		 * We got a command we don't support.  This shouldn't
9070		 * happen, commands should be filtered out above us.
9071		 */
9072		ctl_set_invalid_opcode(ctsio);
9073		ctl_done((union ctl_io *)ctsio);
9074
9075		return (CTL_RETVAL_COMPLETE);
9076		break; /* NOTREACHED */
9077	}
9078
9079	/*
9080	 * XXX KDM what do we do with the DPO and FUA bits?  FUA might be
9081	 * interesting for us, but if RAIDCore is in write-back mode,
9082	 * getting it to do write-through for a particular transaction may
9083	 * not be possible.
9084	 */
9085
9086	/*
9087	 * The first check is to make sure we're in bounds, the second
9088	 * check is to catch wrap-around problems.  If the lba + num blocks
9089	 * is less than the lba, then we've wrapped around and the block
9090	 * range is invalid anyway.
9091	 */
9092	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9093	 || ((lba + num_blocks) < lba)) {
9094		ctl_set_lba_out_of_range(ctsio);
9095		ctl_done((union ctl_io *)ctsio);
9096		return (CTL_RETVAL_COMPLETE);
9097	}
9098
9099	/*
9100	 * According to SBC-3, a transfer length of 0 is not an error.
9101	 */
9102	if (num_blocks == 0) {
9103		ctl_set_success(ctsio);
9104		ctl_done((union ctl_io *)ctsio);
9105		return (CTL_RETVAL_COMPLETE);
9106	}
9107
9108	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9109	ctsio->kern_rel_offset = 0;
9110
9111	/*
9112	 * Set the IO_CONT flag, so that if this I/O gets passed to
9113	 * ctl_data_submit_done(), it'll get passed back to
9114	 * ctl_ctl_cnw_cont() for further processing.
9115	 */
9116	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9117	ctsio->io_cont = ctl_cnw_cont;
9118
9119	lbalen = (struct ctl_lba_len_flags *)
9120	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9121	lbalen->lba = lba;
9122	lbalen->len = num_blocks;
9123	lbalen->flags = CTL_LLF_COMPARE;
9124
9125	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9126	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9127	return (retval);
9128}
9129
9130int
9131ctl_verify(struct ctl_scsiio *ctsio)
9132{
9133	struct ctl_lun *lun;
9134	struct ctl_lba_len_flags *lbalen;
9135	uint64_t lba;
9136	uint32_t num_blocks;
9137	int bytchk, dpo;
9138	int retval;
9139
9140	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9141
9142	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9143
9144	bytchk = 0;
9145	dpo = 0;
9146	retval = CTL_RETVAL_COMPLETE;
9147
9148	switch (ctsio->cdb[0]) {
9149	case VERIFY_10: {
9150		struct scsi_verify_10 *cdb;
9151
9152		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9153		if (cdb->byte2 & SVFY_BYTCHK)
9154			bytchk = 1;
9155		if (cdb->byte2 & SVFY_DPO)
9156			dpo = 1;
9157		lba = scsi_4btoul(cdb->addr);
9158		num_blocks = scsi_2btoul(cdb->length);
9159		break;
9160	}
9161	case VERIFY_12: {
9162		struct scsi_verify_12 *cdb;
9163
9164		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9165		if (cdb->byte2 & SVFY_BYTCHK)
9166			bytchk = 1;
9167		if (cdb->byte2 & SVFY_DPO)
9168			dpo = 1;
9169		lba = scsi_4btoul(cdb->addr);
9170		num_blocks = scsi_4btoul(cdb->length);
9171		break;
9172	}
9173	case VERIFY_16: {
9174		struct scsi_rw_16 *cdb;
9175
9176		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9177		if (cdb->byte2 & SVFY_BYTCHK)
9178			bytchk = 1;
9179		if (cdb->byte2 & SVFY_DPO)
9180			dpo = 1;
9181		lba = scsi_8btou64(cdb->addr);
9182		num_blocks = scsi_4btoul(cdb->length);
9183		break;
9184	}
9185	default:
9186		/*
9187		 * We got a command we don't support.  This shouldn't
9188		 * happen, commands should be filtered out above us.
9189		 */
9190		ctl_set_invalid_opcode(ctsio);
9191		ctl_done((union ctl_io *)ctsio);
9192		return (CTL_RETVAL_COMPLETE);
9193	}
9194
9195	/*
9196	 * The first check is to make sure we're in bounds, the second
9197	 * check is to catch wrap-around problems.  If the lba + num blocks
9198	 * is less than the lba, then we've wrapped around and the block
9199	 * range is invalid anyway.
9200	 */
9201	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9202	 || ((lba + num_blocks) < lba)) {
9203		ctl_set_lba_out_of_range(ctsio);
9204		ctl_done((union ctl_io *)ctsio);
9205		return (CTL_RETVAL_COMPLETE);
9206	}
9207
9208	/*
9209	 * According to SBC-3, a transfer length of 0 is not an error.
9210	 */
9211	if (num_blocks == 0) {
9212		ctl_set_success(ctsio);
9213		ctl_done((union ctl_io *)ctsio);
9214		return (CTL_RETVAL_COMPLETE);
9215	}
9216
9217	lbalen = (struct ctl_lba_len_flags *)
9218	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9219	lbalen->lba = lba;
9220	lbalen->len = num_blocks;
9221	if (bytchk) {
9222		lbalen->flags = CTL_LLF_COMPARE;
9223		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9224	} else {
9225		lbalen->flags = CTL_LLF_VERIFY;
9226		ctsio->kern_total_len = 0;
9227	}
9228	ctsio->kern_rel_offset = 0;
9229
9230	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9231	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9232	return (retval);
9233}
9234
9235int
9236ctl_report_luns(struct ctl_scsiio *ctsio)
9237{
9238	struct scsi_report_luns *cdb;
9239	struct scsi_report_luns_data *lun_data;
9240	struct ctl_lun *lun, *request_lun;
9241	int num_luns, retval;
9242	uint32_t alloc_len, lun_datalen;
9243	int num_filled, well_known;
9244	uint32_t initidx, targ_lun_id, lun_id;
9245
9246	retval = CTL_RETVAL_COMPLETE;
9247	well_known = 0;
9248
9249	cdb = (struct scsi_report_luns *)ctsio->cdb;
9250
9251	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9252
9253	mtx_lock(&control_softc->ctl_lock);
9254	num_luns = control_softc->num_luns;
9255	mtx_unlock(&control_softc->ctl_lock);
9256
9257	switch (cdb->select_report) {
9258	case RPL_REPORT_DEFAULT:
9259	case RPL_REPORT_ALL:
9260		break;
9261	case RPL_REPORT_WELLKNOWN:
9262		well_known = 1;
9263		num_luns = 0;
9264		break;
9265	default:
9266		ctl_set_invalid_field(ctsio,
9267				      /*sks_valid*/ 1,
9268				      /*command*/ 1,
9269				      /*field*/ 2,
9270				      /*bit_valid*/ 0,
9271				      /*bit*/ 0);
9272		ctl_done((union ctl_io *)ctsio);
9273		return (retval);
9274		break; /* NOTREACHED */
9275	}
9276
9277	alloc_len = scsi_4btoul(cdb->length);
9278	/*
9279	 * The initiator has to allocate at least 16 bytes for this request,
9280	 * so he can at least get the header and the first LUN.  Otherwise
9281	 * we reject the request (per SPC-3 rev 14, section 6.21).
9282	 */
9283	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9284	    sizeof(struct scsi_report_luns_lundata))) {
9285		ctl_set_invalid_field(ctsio,
9286				      /*sks_valid*/ 1,
9287				      /*command*/ 1,
9288				      /*field*/ 6,
9289				      /*bit_valid*/ 0,
9290				      /*bit*/ 0);
9291		ctl_done((union ctl_io *)ctsio);
9292		return (retval);
9293	}
9294
9295	request_lun = (struct ctl_lun *)
9296		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9297
9298	lun_datalen = sizeof(*lun_data) +
9299		(num_luns * sizeof(struct scsi_report_luns_lundata));
9300
9301	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9302	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9303	ctsio->kern_sg_entries = 0;
9304
9305	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9306
9307	mtx_lock(&control_softc->ctl_lock);
9308	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9309		lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9310		if (lun_id >= CTL_MAX_LUNS)
9311			continue;
9312		lun = control_softc->ctl_luns[lun_id];
9313		if (lun == NULL)
9314			continue;
9315
9316		if (targ_lun_id <= 0xff) {
9317			/*
9318			 * Peripheral addressing method, bus number 0.
9319			 */
9320			lun_data->luns[num_filled].lundata[0] =
9321				RPL_LUNDATA_ATYP_PERIPH;
9322			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9323			num_filled++;
9324		} else if (targ_lun_id <= 0x3fff) {
9325			/*
9326			 * Flat addressing method.
9327			 */
9328			lun_data->luns[num_filled].lundata[0] =
9329				RPL_LUNDATA_ATYP_FLAT |
9330				(targ_lun_id & RPL_LUNDATA_FLAT_LUN_MASK);
9331#ifdef OLDCTLHEADERS
9332				(SRLD_ADDR_FLAT << SRLD_ADDR_SHIFT) |
9333				(targ_lun_id & SRLD_BUS_LUN_MASK);
9334#endif
9335			lun_data->luns[num_filled].lundata[1] =
9336#ifdef OLDCTLHEADERS
9337				targ_lun_id >> SRLD_BUS_LUN_BITS;
9338#endif
9339				targ_lun_id >> RPL_LUNDATA_FLAT_LUN_BITS;
9340			num_filled++;
9341		} else {
9342			printf("ctl_report_luns: bogus LUN number %jd, "
9343			       "skipping\n", (intmax_t)targ_lun_id);
9344		}
9345		/*
9346		 * According to SPC-3, rev 14 section 6.21:
9347		 *
9348		 * "The execution of a REPORT LUNS command to any valid and
9349		 * installed logical unit shall clear the REPORTED LUNS DATA
9350		 * HAS CHANGED unit attention condition for all logical
9351		 * units of that target with respect to the requesting
9352		 * initiator. A valid and installed logical unit is one
9353		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9354		 * INQUIRY data (see 6.4.2)."
9355		 *
9356		 * If request_lun is NULL, the LUN this report luns command
9357		 * was issued to is either disabled or doesn't exist. In that
9358		 * case, we shouldn't clear any pending lun change unit
9359		 * attention.
9360		 */
9361		if (request_lun != NULL) {
9362			mtx_lock(&lun->lun_lock);
9363			lun->pending_sense[initidx].ua_pending &=
9364				~CTL_UA_LUN_CHANGE;
9365			mtx_unlock(&lun->lun_lock);
9366		}
9367	}
9368	mtx_unlock(&control_softc->ctl_lock);
9369
9370	/*
9371	 * It's quite possible that we've returned fewer LUNs than we allocated
9372	 * space for.  Trim it.
9373	 */
9374	lun_datalen = sizeof(*lun_data) +
9375		(num_filled * sizeof(struct scsi_report_luns_lundata));
9376
9377	if (lun_datalen < alloc_len) {
9378		ctsio->residual = alloc_len - lun_datalen;
9379		ctsio->kern_data_len = lun_datalen;
9380		ctsio->kern_total_len = lun_datalen;
9381	} else {
9382		ctsio->residual = 0;
9383		ctsio->kern_data_len = alloc_len;
9384		ctsio->kern_total_len = alloc_len;
9385	}
9386	ctsio->kern_data_resid = 0;
9387	ctsio->kern_rel_offset = 0;
9388	ctsio->kern_sg_entries = 0;
9389
9390	/*
9391	 * We set this to the actual data length, regardless of how much
9392	 * space we actually have to return results.  If the user looks at
9393	 * this value, he'll know whether or not he allocated enough space
9394	 * and reissue the command if necessary.  We don't support well
9395	 * known logical units, so if the user asks for that, return none.
9396	 */
9397	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9398
9399	/*
9400	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9401	 * this request.
9402	 */
9403	ctsio->scsi_status = SCSI_STATUS_OK;
9404
9405	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9406	ctsio->be_move_done = ctl_config_move_done;
9407	ctl_datamove((union ctl_io *)ctsio);
9408
9409	return (retval);
9410}
9411
9412int
9413ctl_request_sense(struct ctl_scsiio *ctsio)
9414{
9415	struct scsi_request_sense *cdb;
9416	struct scsi_sense_data *sense_ptr;
9417	struct ctl_lun *lun;
9418	uint32_t initidx;
9419	int have_error;
9420	scsi_sense_data_type sense_format;
9421
9422	cdb = (struct scsi_request_sense *)ctsio->cdb;
9423
9424	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9425
9426	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9427
9428	/*
9429	 * Determine which sense format the user wants.
9430	 */
9431	if (cdb->byte2 & SRS_DESC)
9432		sense_format = SSD_TYPE_DESC;
9433	else
9434		sense_format = SSD_TYPE_FIXED;
9435
9436	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9437	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9438	ctsio->kern_sg_entries = 0;
9439
9440	/*
9441	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9442	 * larger than the largest allowed value for the length field in the
9443	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9444	 */
9445	ctsio->residual = 0;
9446	ctsio->kern_data_len = cdb->length;
9447	ctsio->kern_total_len = cdb->length;
9448
9449	ctsio->kern_data_resid = 0;
9450	ctsio->kern_rel_offset = 0;
9451	ctsio->kern_sg_entries = 0;
9452
9453	/*
9454	 * If we don't have a LUN, we don't have any pending sense.
9455	 */
9456	if (lun == NULL)
9457		goto no_sense;
9458
9459	have_error = 0;
9460	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9461	/*
9462	 * Check for pending sense, and then for pending unit attentions.
9463	 * Pending sense gets returned first, then pending unit attentions.
9464	 */
9465	mtx_lock(&lun->lun_lock);
9466	if (ctl_is_set(lun->have_ca, initidx)) {
9467		scsi_sense_data_type stored_format;
9468
9469		/*
9470		 * Check to see which sense format was used for the stored
9471		 * sense data.
9472		 */
9473		stored_format = scsi_sense_type(
9474		    &lun->pending_sense[initidx].sense);
9475
9476		/*
9477		 * If the user requested a different sense format than the
9478		 * one we stored, then we need to convert it to the other
9479		 * format.  If we're going from descriptor to fixed format
9480		 * sense data, we may lose things in translation, depending
9481		 * on what options were used.
9482		 *
9483		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9484		 * for some reason we'll just copy it out as-is.
9485		 */
9486		if ((stored_format == SSD_TYPE_FIXED)
9487		 && (sense_format == SSD_TYPE_DESC))
9488			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9489			    &lun->pending_sense[initidx].sense,
9490			    (struct scsi_sense_data_desc *)sense_ptr);
9491		else if ((stored_format == SSD_TYPE_DESC)
9492		      && (sense_format == SSD_TYPE_FIXED))
9493			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9494			    &lun->pending_sense[initidx].sense,
9495			    (struct scsi_sense_data_fixed *)sense_ptr);
9496		else
9497			memcpy(sense_ptr, &lun->pending_sense[initidx].sense,
9498			       ctl_min(sizeof(*sense_ptr),
9499			       sizeof(lun->pending_sense[initidx].sense)));
9500
9501		ctl_clear_mask(lun->have_ca, initidx);
9502		have_error = 1;
9503	} else if (lun->pending_sense[initidx].ua_pending != CTL_UA_NONE) {
9504		ctl_ua_type ua_type;
9505
9506		ua_type = ctl_build_ua(lun->pending_sense[initidx].ua_pending,
9507				       sense_ptr, sense_format);
9508		if (ua_type != CTL_UA_NONE) {
9509			have_error = 1;
9510			/* We're reporting this UA, so clear it */
9511			lun->pending_sense[initidx].ua_pending &= ~ua_type;
9512		}
9513	}
9514	mtx_unlock(&lun->lun_lock);
9515
9516	/*
9517	 * We already have a pending error, return it.
9518	 */
9519	if (have_error != 0) {
9520		/*
9521		 * We report the SCSI status as OK, since the status of the
9522		 * request sense command itself is OK.
9523		 */
9524		ctsio->scsi_status = SCSI_STATUS_OK;
9525
9526		/*
9527		 * We report 0 for the sense length, because we aren't doing
9528		 * autosense in this case.  We're reporting sense as
9529		 * parameter data.
9530		 */
9531		ctsio->sense_len = 0;
9532		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9533		ctsio->be_move_done = ctl_config_move_done;
9534		ctl_datamove((union ctl_io *)ctsio);
9535
9536		return (CTL_RETVAL_COMPLETE);
9537	}
9538
9539no_sense:
9540
9541	/*
9542	 * No sense information to report, so we report that everything is
9543	 * okay.
9544	 */
9545	ctl_set_sense_data(sense_ptr,
9546			   lun,
9547			   sense_format,
9548			   /*current_error*/ 1,
9549			   /*sense_key*/ SSD_KEY_NO_SENSE,
9550			   /*asc*/ 0x00,
9551			   /*ascq*/ 0x00,
9552			   SSD_ELEM_NONE);
9553
9554	ctsio->scsi_status = SCSI_STATUS_OK;
9555
9556	/*
9557	 * We report 0 for the sense length, because we aren't doing
9558	 * autosense in this case.  We're reporting sense as parameter data.
9559	 */
9560	ctsio->sense_len = 0;
9561	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9562	ctsio->be_move_done = ctl_config_move_done;
9563	ctl_datamove((union ctl_io *)ctsio);
9564
9565	return (CTL_RETVAL_COMPLETE);
9566}
9567
9568int
9569ctl_tur(struct ctl_scsiio *ctsio)
9570{
9571	struct ctl_lun *lun;
9572
9573	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9574
9575	CTL_DEBUG_PRINT(("ctl_tur\n"));
9576
9577	if (lun == NULL)
9578		return (EINVAL);
9579
9580	ctsio->scsi_status = SCSI_STATUS_OK;
9581	ctsio->io_hdr.status = CTL_SUCCESS;
9582
9583	ctl_done((union ctl_io *)ctsio);
9584
9585	return (CTL_RETVAL_COMPLETE);
9586}
9587
9588#ifdef notyet
9589static int
9590ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9591{
9592
9593}
9594#endif
9595
9596static int
9597ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9598{
9599	struct scsi_vpd_supported_pages *pages;
9600	int sup_page_size;
9601	struct ctl_lun *lun;
9602
9603	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9604
9605	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9606	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9607	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9608	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9609	ctsio->kern_sg_entries = 0;
9610
9611	if (sup_page_size < alloc_len) {
9612		ctsio->residual = alloc_len - sup_page_size;
9613		ctsio->kern_data_len = sup_page_size;
9614		ctsio->kern_total_len = sup_page_size;
9615	} else {
9616		ctsio->residual = 0;
9617		ctsio->kern_data_len = alloc_len;
9618		ctsio->kern_total_len = alloc_len;
9619	}
9620	ctsio->kern_data_resid = 0;
9621	ctsio->kern_rel_offset = 0;
9622	ctsio->kern_sg_entries = 0;
9623
9624	/*
9625	 * The control device is always connected.  The disk device, on the
9626	 * other hand, may not be online all the time.  Need to change this
9627	 * to figure out whether the disk device is actually online or not.
9628	 */
9629	if (lun != NULL)
9630		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9631				lun->be_lun->lun_type;
9632	else
9633		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9634
9635	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9636	/* Supported VPD pages */
9637	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9638	/* Serial Number */
9639	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9640	/* Device Identification */
9641	pages->page_list[2] = SVPD_DEVICE_ID;
9642	/* SCSI Ports */
9643	pages->page_list[3] = SVPD_SCSI_PORTS;
9644	/* Block limits */
9645	pages->page_list[4] = SVPD_BLOCK_LIMITS;
9646	/* Logical Block Provisioning */
9647	pages->page_list[5] = SVPD_LBP;
9648
9649	ctsio->scsi_status = SCSI_STATUS_OK;
9650
9651	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9652	ctsio->be_move_done = ctl_config_move_done;
9653	ctl_datamove((union ctl_io *)ctsio);
9654
9655	return (CTL_RETVAL_COMPLETE);
9656}
9657
9658static int
9659ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9660{
9661	struct scsi_vpd_unit_serial_number *sn_ptr;
9662	struct ctl_lun *lun;
9663
9664	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9665
9666	ctsio->kern_data_ptr = malloc(sizeof(*sn_ptr), M_CTL, M_WAITOK | M_ZERO);
9667	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9668	ctsio->kern_sg_entries = 0;
9669
9670	if (sizeof(*sn_ptr) < alloc_len) {
9671		ctsio->residual = alloc_len - sizeof(*sn_ptr);
9672		ctsio->kern_data_len = sizeof(*sn_ptr);
9673		ctsio->kern_total_len = sizeof(*sn_ptr);
9674	} else {
9675		ctsio->residual = 0;
9676		ctsio->kern_data_len = alloc_len;
9677		ctsio->kern_total_len = alloc_len;
9678	}
9679	ctsio->kern_data_resid = 0;
9680	ctsio->kern_rel_offset = 0;
9681	ctsio->kern_sg_entries = 0;
9682
9683	/*
9684	 * The control device is always connected.  The disk device, on the
9685	 * other hand, may not be online all the time.  Need to change this
9686	 * to figure out whether the disk device is actually online or not.
9687	 */
9688	if (lun != NULL)
9689		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9690				  lun->be_lun->lun_type;
9691	else
9692		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9693
9694	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9695	sn_ptr->length = ctl_min(sizeof(*sn_ptr) - 4, CTL_SN_LEN);
9696	/*
9697	 * If we don't have a LUN, we just leave the serial number as
9698	 * all spaces.
9699	 */
9700	memset(sn_ptr->serial_num, 0x20, sizeof(sn_ptr->serial_num));
9701	if (lun != NULL) {
9702		strncpy((char *)sn_ptr->serial_num,
9703			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9704	}
9705	ctsio->scsi_status = SCSI_STATUS_OK;
9706
9707	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9708	ctsio->be_move_done = ctl_config_move_done;
9709	ctl_datamove((union ctl_io *)ctsio);
9710
9711	return (CTL_RETVAL_COMPLETE);
9712}
9713
9714
9715static int
9716ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9717{
9718	struct scsi_vpd_device_id *devid_ptr;
9719	struct scsi_vpd_id_descriptor *desc;
9720	struct ctl_softc *ctl_softc;
9721	struct ctl_lun *lun;
9722	struct ctl_port *port;
9723	int data_len;
9724	uint8_t proto;
9725
9726	ctl_softc = control_softc;
9727
9728	port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9729	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9730
9731	data_len = sizeof(struct scsi_vpd_device_id) +
9732	    sizeof(struct scsi_vpd_id_descriptor) +
9733		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9734	    sizeof(struct scsi_vpd_id_descriptor) +
9735		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9736	if (lun && lun->lun_devid)
9737		data_len += lun->lun_devid->len;
9738	if (port->port_devid)
9739		data_len += port->port_devid->len;
9740	if (port->target_devid)
9741		data_len += port->target_devid->len;
9742
9743	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9744	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9745	ctsio->kern_sg_entries = 0;
9746
9747	if (data_len < alloc_len) {
9748		ctsio->residual = alloc_len - data_len;
9749		ctsio->kern_data_len = data_len;
9750		ctsio->kern_total_len = data_len;
9751	} else {
9752		ctsio->residual = 0;
9753		ctsio->kern_data_len = alloc_len;
9754		ctsio->kern_total_len = alloc_len;
9755	}
9756	ctsio->kern_data_resid = 0;
9757	ctsio->kern_rel_offset = 0;
9758	ctsio->kern_sg_entries = 0;
9759
9760	/*
9761	 * The control device is always connected.  The disk device, on the
9762	 * other hand, may not be online all the time.
9763	 */
9764	if (lun != NULL)
9765		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9766				     lun->be_lun->lun_type;
9767	else
9768		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9769	devid_ptr->page_code = SVPD_DEVICE_ID;
9770	scsi_ulto2b(data_len - 4, devid_ptr->length);
9771
9772	if (port->port_type == CTL_PORT_FC)
9773		proto = SCSI_PROTO_FC << 4;
9774	else if (port->port_type == CTL_PORT_ISCSI)
9775		proto = SCSI_PROTO_ISCSI << 4;
9776	else
9777		proto = SCSI_PROTO_SPI << 4;
9778	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9779
9780	/*
9781	 * We're using a LUN association here.  i.e., this device ID is a
9782	 * per-LUN identifier.
9783	 */
9784	if (lun && lun->lun_devid) {
9785		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9786		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9787		    lun->lun_devid->len);
9788	}
9789
9790	/*
9791	 * This is for the WWPN which is a port association.
9792	 */
9793	if (port->port_devid) {
9794		memcpy(desc, port->port_devid->data, port->port_devid->len);
9795		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9796		    port->port_devid->len);
9797	}
9798
9799	/*
9800	 * This is for the Relative Target Port(type 4h) identifier
9801	 */
9802	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9803	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9804	    SVPD_ID_TYPE_RELTARG;
9805	desc->length = 4;
9806	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9807	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9808	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9809
9810	/*
9811	 * This is for the Target Port Group(type 5h) identifier
9812	 */
9813	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9814	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9815	    SVPD_ID_TYPE_TPORTGRP;
9816	desc->length = 4;
9817	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
9818	    &desc->identifier[2]);
9819	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9820	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9821
9822	/*
9823	 * This is for the Target identifier
9824	 */
9825	if (port->target_devid) {
9826		memcpy(desc, port->target_devid->data, port->target_devid->len);
9827	}
9828
9829	ctsio->scsi_status = SCSI_STATUS_OK;
9830	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9831	ctsio->be_move_done = ctl_config_move_done;
9832	ctl_datamove((union ctl_io *)ctsio);
9833
9834	return (CTL_RETVAL_COMPLETE);
9835}
9836
9837static int
9838ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9839{
9840	struct ctl_softc *softc = control_softc;
9841	struct scsi_vpd_scsi_ports *sp;
9842	struct scsi_vpd_port_designation *pd;
9843	struct scsi_vpd_port_designation_cont *pdc;
9844	struct ctl_lun *lun;
9845	struct ctl_port *port;
9846	int data_len, num_target_ports, id_len, g, pg, p;
9847	int num_target_port_groups, single;
9848
9849	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9850
9851	single = ctl_is_single;
9852	if (single)
9853		num_target_port_groups = 1;
9854	else
9855		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
9856	num_target_ports = 0;
9857	id_len = 0;
9858	mtx_lock(&softc->ctl_lock);
9859	STAILQ_FOREACH(port, &softc->port_list, links) {
9860		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9861			continue;
9862		if (ctl_map_lun_back(port->targ_port, lun->lun) >=
9863		    CTL_MAX_LUNS)
9864			continue;
9865		num_target_ports++;
9866		if (port->port_devid)
9867			id_len += port->port_devid->len;
9868	}
9869	mtx_unlock(&softc->ctl_lock);
9870
9871	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
9872	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9873	     sizeof(struct scsi_vpd_port_designation_cont)) + id_len;
9874	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9875	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9876	ctsio->kern_sg_entries = 0;
9877
9878	if (data_len < alloc_len) {
9879		ctsio->residual = alloc_len - data_len;
9880		ctsio->kern_data_len = data_len;
9881		ctsio->kern_total_len = data_len;
9882	} else {
9883		ctsio->residual = 0;
9884		ctsio->kern_data_len = alloc_len;
9885		ctsio->kern_total_len = alloc_len;
9886	}
9887	ctsio->kern_data_resid = 0;
9888	ctsio->kern_rel_offset = 0;
9889	ctsio->kern_sg_entries = 0;
9890
9891	/*
9892	 * The control device is always connected.  The disk device, on the
9893	 * other hand, may not be online all the time.  Need to change this
9894	 * to figure out whether the disk device is actually online or not.
9895	 */
9896	if (lun != NULL)
9897		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9898				  lun->be_lun->lun_type;
9899	else
9900		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9901
9902	sp->page_code = SVPD_SCSI_PORTS;
9903	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9904	    sp->page_length);
9905	pd = &sp->design[0];
9906
9907	mtx_lock(&softc->ctl_lock);
9908	if (softc->flags & CTL_FLAG_MASTER_SHELF)
9909		pg = 0;
9910	else
9911		pg = 1;
9912	for (g = 0; g < num_target_port_groups; g++) {
9913		STAILQ_FOREACH(port, &softc->port_list, links) {
9914			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9915				continue;
9916			if (ctl_map_lun_back(port->targ_port, lun->lun) >=
9917			    CTL_MAX_LUNS)
9918				continue;
9919			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
9920			scsi_ulto2b(p, pd->relative_port_id);
9921			scsi_ulto2b(0, pd->initiator_transportid_length);
9922			pdc = (struct scsi_vpd_port_designation_cont *)
9923			    &pd->initiator_transportid[0];
9924			if (port->port_devid && g == pg) {
9925				id_len = port->port_devid->len;
9926				scsi_ulto2b(port->port_devid->len,
9927				    pdc->target_port_descriptors_length);
9928				memcpy(pdc->target_port_descriptors,
9929				    port->port_devid->data, port->port_devid->len);
9930			} else {
9931				id_len = 0;
9932				scsi_ulto2b(0, pdc->target_port_descriptors_length);
9933			}
9934			pd = (struct scsi_vpd_port_designation *)
9935			    ((uint8_t *)pdc->target_port_descriptors + id_len);
9936		}
9937	}
9938	mtx_unlock(&softc->ctl_lock);
9939
9940	ctsio->scsi_status = SCSI_STATUS_OK;
9941	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9942	ctsio->be_move_done = ctl_config_move_done;
9943	ctl_datamove((union ctl_io *)ctsio);
9944
9945	return (CTL_RETVAL_COMPLETE);
9946}
9947
9948static int
9949ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9950{
9951	struct scsi_vpd_block_limits *bl_ptr;
9952	struct ctl_lun *lun;
9953	int bs;
9954
9955	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9956	bs = lun->be_lun->blocksize;
9957
9958	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9959	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9960	ctsio->kern_sg_entries = 0;
9961
9962	if (sizeof(*bl_ptr) < alloc_len) {
9963		ctsio->residual = alloc_len - sizeof(*bl_ptr);
9964		ctsio->kern_data_len = sizeof(*bl_ptr);
9965		ctsio->kern_total_len = sizeof(*bl_ptr);
9966	} else {
9967		ctsio->residual = 0;
9968		ctsio->kern_data_len = alloc_len;
9969		ctsio->kern_total_len = alloc_len;
9970	}
9971	ctsio->kern_data_resid = 0;
9972	ctsio->kern_rel_offset = 0;
9973	ctsio->kern_sg_entries = 0;
9974
9975	/*
9976	 * The control device is always connected.  The disk device, on the
9977	 * other hand, may not be online all the time.  Need to change this
9978	 * to figure out whether the disk device is actually online or not.
9979	 */
9980	if (lun != NULL)
9981		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9982				  lun->be_lun->lun_type;
9983	else
9984		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9985
9986	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9987	scsi_ulto2b(sizeof(*bl_ptr), bl_ptr->page_length);
9988	bl_ptr->max_cmp_write_len = 0xff;
9989	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9990	scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
9991	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9992		scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
9993		scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
9994	}
9995	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
9996
9997	ctsio->scsi_status = SCSI_STATUS_OK;
9998	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9999	ctsio->be_move_done = ctl_config_move_done;
10000	ctl_datamove((union ctl_io *)ctsio);
10001
10002	return (CTL_RETVAL_COMPLETE);
10003}
10004
10005static int
10006ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10007{
10008	struct scsi_vpd_logical_block_prov *lbp_ptr;
10009	struct ctl_lun *lun;
10010	int bs;
10011
10012	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10013	bs = lun->be_lun->blocksize;
10014
10015	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10016	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10017	ctsio->kern_sg_entries = 0;
10018
10019	if (sizeof(*lbp_ptr) < alloc_len) {
10020		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10021		ctsio->kern_data_len = sizeof(*lbp_ptr);
10022		ctsio->kern_total_len = sizeof(*lbp_ptr);
10023	} else {
10024		ctsio->residual = 0;
10025		ctsio->kern_data_len = alloc_len;
10026		ctsio->kern_total_len = alloc_len;
10027	}
10028	ctsio->kern_data_resid = 0;
10029	ctsio->kern_rel_offset = 0;
10030	ctsio->kern_sg_entries = 0;
10031
10032	/*
10033	 * The control device is always connected.  The disk device, on the
10034	 * other hand, may not be online all the time.  Need to change this
10035	 * to figure out whether the disk device is actually online or not.
10036	 */
10037	if (lun != NULL)
10038		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10039				  lun->be_lun->lun_type;
10040	else
10041		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10042
10043	lbp_ptr->page_code = SVPD_LBP;
10044	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
10045		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 | SVPD_LBP_WS10;
10046
10047	ctsio->scsi_status = SCSI_STATUS_OK;
10048	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10049	ctsio->be_move_done = ctl_config_move_done;
10050	ctl_datamove((union ctl_io *)ctsio);
10051
10052	return (CTL_RETVAL_COMPLETE);
10053}
10054
10055static int
10056ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10057{
10058	struct scsi_inquiry *cdb;
10059	struct ctl_lun *lun;
10060	int alloc_len, retval;
10061
10062	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10063	cdb = (struct scsi_inquiry *)ctsio->cdb;
10064
10065	retval = CTL_RETVAL_COMPLETE;
10066
10067	alloc_len = scsi_2btoul(cdb->length);
10068
10069	switch (cdb->page_code) {
10070	case SVPD_SUPPORTED_PAGES:
10071		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10072		break;
10073	case SVPD_UNIT_SERIAL_NUMBER:
10074		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10075		break;
10076	case SVPD_DEVICE_ID:
10077		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10078		break;
10079	case SVPD_SCSI_PORTS:
10080		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10081		break;
10082	case SVPD_BLOCK_LIMITS:
10083		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10084		break;
10085	case SVPD_LBP:
10086		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10087		break;
10088	default:
10089		ctl_set_invalid_field(ctsio,
10090				      /*sks_valid*/ 1,
10091				      /*command*/ 1,
10092				      /*field*/ 2,
10093				      /*bit_valid*/ 0,
10094				      /*bit*/ 0);
10095		ctl_done((union ctl_io *)ctsio);
10096		retval = CTL_RETVAL_COMPLETE;
10097		break;
10098	}
10099
10100	return (retval);
10101}
10102
10103static int
10104ctl_inquiry_std(struct ctl_scsiio *ctsio)
10105{
10106	struct scsi_inquiry_data *inq_ptr;
10107	struct scsi_inquiry *cdb;
10108	struct ctl_softc *ctl_softc;
10109	struct ctl_lun *lun;
10110	char *val;
10111	uint32_t alloc_len;
10112	int is_fc;
10113
10114	ctl_softc = control_softc;
10115
10116	/*
10117	 * Figure out whether we're talking to a Fibre Channel port or not.
10118	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10119	 * SCSI front ends.
10120	 */
10121	if (ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type !=
10122	    CTL_PORT_FC)
10123		is_fc = 0;
10124	else
10125		is_fc = 1;
10126
10127	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10128	cdb = (struct scsi_inquiry *)ctsio->cdb;
10129	alloc_len = scsi_2btoul(cdb->length);
10130
10131	/*
10132	 * We malloc the full inquiry data size here and fill it
10133	 * in.  If the user only asks for less, we'll give him
10134	 * that much.
10135	 */
10136	ctsio->kern_data_ptr = malloc(sizeof(*inq_ptr), M_CTL, M_WAITOK | M_ZERO);
10137	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10138	ctsio->kern_sg_entries = 0;
10139	ctsio->kern_data_resid = 0;
10140	ctsio->kern_rel_offset = 0;
10141
10142	if (sizeof(*inq_ptr) < alloc_len) {
10143		ctsio->residual = alloc_len - sizeof(*inq_ptr);
10144		ctsio->kern_data_len = sizeof(*inq_ptr);
10145		ctsio->kern_total_len = sizeof(*inq_ptr);
10146	} else {
10147		ctsio->residual = 0;
10148		ctsio->kern_data_len = alloc_len;
10149		ctsio->kern_total_len = alloc_len;
10150	}
10151
10152	/*
10153	 * If we have a LUN configured, report it as connected.  Otherwise,
10154	 * report that it is offline or no device is supported, depending
10155	 * on the value of inquiry_pq_no_lun.
10156	 *
10157	 * According to the spec (SPC-4 r34), the peripheral qualifier
10158	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10159	 *
10160	 * "A peripheral device having the specified peripheral device type
10161	 * is not connected to this logical unit. However, the device
10162	 * server is capable of supporting the specified peripheral device
10163	 * type on this logical unit."
10164	 *
10165	 * According to the same spec, the peripheral qualifier
10166	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10167	 *
10168	 * "The device server is not capable of supporting a peripheral
10169	 * device on this logical unit. For this peripheral qualifier the
10170	 * peripheral device type shall be set to 1Fh. All other peripheral
10171	 * device type values are reserved for this peripheral qualifier."
10172	 *
10173	 * Given the text, it would seem that we probably want to report that
10174	 * the LUN is offline here.  There is no LUN connected, but we can
10175	 * support a LUN at the given LUN number.
10176	 *
10177	 * In the real world, though, it sounds like things are a little
10178	 * different:
10179	 *
10180	 * - Linux, when presented with a LUN with the offline peripheral
10181	 *   qualifier, will create an sg driver instance for it.  So when
10182	 *   you attach it to CTL, you wind up with a ton of sg driver
10183	 *   instances.  (One for every LUN that Linux bothered to probe.)
10184	 *   Linux does this despite the fact that it issues a REPORT LUNs
10185	 *   to LUN 0 to get the inventory of supported LUNs.
10186	 *
10187	 * - There is other anecdotal evidence (from Emulex folks) about
10188	 *   arrays that use the offline peripheral qualifier for LUNs that
10189	 *   are on the "passive" path in an active/passive array.
10190	 *
10191	 * So the solution is provide a hopefully reasonable default
10192	 * (return bad/no LUN) and allow the user to change the behavior
10193	 * with a tunable/sysctl variable.
10194	 */
10195	if (lun != NULL)
10196		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10197				  lun->be_lun->lun_type;
10198	else if (ctl_softc->inquiry_pq_no_lun == 0)
10199		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10200	else
10201		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10202
10203	/* RMB in byte 2 is 0 */
10204	inq_ptr->version = SCSI_REV_SPC3;
10205
10206	/*
10207	 * According to SAM-3, even if a device only supports a single
10208	 * level of LUN addressing, it should still set the HISUP bit:
10209	 *
10210	 * 4.9.1 Logical unit numbers overview
10211	 *
10212	 * All logical unit number formats described in this standard are
10213	 * hierarchical in structure even when only a single level in that
10214	 * hierarchy is used. The HISUP bit shall be set to one in the
10215	 * standard INQUIRY data (see SPC-2) when any logical unit number
10216	 * format described in this standard is used.  Non-hierarchical
10217	 * formats are outside the scope of this standard.
10218	 *
10219	 * Therefore we set the HiSup bit here.
10220	 *
10221	 * The reponse format is 2, per SPC-3.
10222	 */
10223	inq_ptr->response_format = SID_HiSup | 2;
10224
10225	inq_ptr->additional_length = sizeof(*inq_ptr) - 4;
10226	CTL_DEBUG_PRINT(("additional_length = %d\n",
10227			 inq_ptr->additional_length));
10228
10229	inq_ptr->spc3_flags = SPC3_SID_TPGS_IMPLICIT;
10230	/* 16 bit addressing */
10231	if (is_fc == 0)
10232		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10233	/* XXX set the SID_MultiP bit here if we're actually going to
10234	   respond on multiple ports */
10235	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10236
10237	/* 16 bit data bus, synchronous transfers */
10238	/* XXX these flags don't apply for FC */
10239	if (is_fc == 0)
10240		inq_ptr->flags = SID_WBus16 | SID_Sync;
10241	/*
10242	 * XXX KDM do we want to support tagged queueing on the control
10243	 * device at all?
10244	 */
10245	if ((lun == NULL)
10246	 || (lun->be_lun->lun_type != T_PROCESSOR))
10247		inq_ptr->flags |= SID_CmdQue;
10248	/*
10249	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10250	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10251	 * name and 4 bytes for the revision.
10252	 */
10253	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10254	    "vendor")) == NULL) {
10255		strcpy(inq_ptr->vendor, CTL_VENDOR);
10256	} else {
10257		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10258		strncpy(inq_ptr->vendor, val,
10259		    min(sizeof(inq_ptr->vendor), strlen(val)));
10260	}
10261	if (lun == NULL) {
10262		strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
10263	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10264		switch (lun->be_lun->lun_type) {
10265		case T_DIRECT:
10266			strcpy(inq_ptr->product, CTL_DIRECT_PRODUCT);
10267			break;
10268		case T_PROCESSOR:
10269			strcpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT);
10270			break;
10271		default:
10272			strcpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT);
10273			break;
10274		}
10275	} else {
10276		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10277		strncpy(inq_ptr->product, val,
10278		    min(sizeof(inq_ptr->product), strlen(val)));
10279	}
10280
10281	/*
10282	 * XXX make this a macro somewhere so it automatically gets
10283	 * incremented when we make changes.
10284	 */
10285	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10286	    "revision")) == NULL) {
10287		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10288	} else {
10289		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10290		strncpy(inq_ptr->revision, val,
10291		    min(sizeof(inq_ptr->revision), strlen(val)));
10292	}
10293
10294	/*
10295	 * For parallel SCSI, we support double transition and single
10296	 * transition clocking.  We also support QAS (Quick Arbitration
10297	 * and Selection) and Information Unit transfers on both the
10298	 * control and array devices.
10299	 */
10300	if (is_fc == 0)
10301		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10302				    SID_SPI_IUS;
10303
10304	/* SAM-3 */
10305	scsi_ulto2b(0x0060, inq_ptr->version1);
10306	/* SPC-3 (no version claimed) XXX should we claim a version? */
10307	scsi_ulto2b(0x0300, inq_ptr->version2);
10308	if (is_fc) {
10309		/* FCP-2 ANSI INCITS.350:2003 */
10310		scsi_ulto2b(0x0917, inq_ptr->version3);
10311	} else {
10312		/* SPI-4 ANSI INCITS.362:200x */
10313		scsi_ulto2b(0x0B56, inq_ptr->version3);
10314	}
10315
10316	if (lun == NULL) {
10317		/* SBC-2 (no version claimed) XXX should we claim a version? */
10318		scsi_ulto2b(0x0320, inq_ptr->version4);
10319	} else {
10320		switch (lun->be_lun->lun_type) {
10321		case T_DIRECT:
10322			/*
10323			 * SBC-2 (no version claimed) XXX should we claim a
10324			 * version?
10325			 */
10326			scsi_ulto2b(0x0320, inq_ptr->version4);
10327			break;
10328		case T_PROCESSOR:
10329		default:
10330			break;
10331		}
10332	}
10333
10334	ctsio->scsi_status = SCSI_STATUS_OK;
10335	if (ctsio->kern_data_len > 0) {
10336		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10337		ctsio->be_move_done = ctl_config_move_done;
10338		ctl_datamove((union ctl_io *)ctsio);
10339	} else {
10340		ctsio->io_hdr.status = CTL_SUCCESS;
10341		ctl_done((union ctl_io *)ctsio);
10342	}
10343
10344	return (CTL_RETVAL_COMPLETE);
10345}
10346
10347int
10348ctl_inquiry(struct ctl_scsiio *ctsio)
10349{
10350	struct scsi_inquiry *cdb;
10351	int retval;
10352
10353	cdb = (struct scsi_inquiry *)ctsio->cdb;
10354
10355	retval = 0;
10356
10357	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10358
10359	/*
10360	 * Right now, we don't support the CmdDt inquiry information.
10361	 * This would be nice to support in the future.  When we do
10362	 * support it, we should change this test so that it checks to make
10363	 * sure SI_EVPD and SI_CMDDT aren't both set at the same time.
10364	 */
10365#ifdef notyet
10366	if (((cdb->byte2 & SI_EVPD)
10367	 && (cdb->byte2 & SI_CMDDT)))
10368#endif
10369	if (cdb->byte2 & SI_CMDDT) {
10370		/*
10371		 * Point to the SI_CMDDT bit.  We might change this
10372		 * when we support SI_CMDDT, but since both bits would be
10373		 * "wrong", this should probably just stay as-is then.
10374		 */
10375		ctl_set_invalid_field(ctsio,
10376				      /*sks_valid*/ 1,
10377				      /*command*/ 1,
10378				      /*field*/ 1,
10379				      /*bit_valid*/ 1,
10380				      /*bit*/ 1);
10381		ctl_done((union ctl_io *)ctsio);
10382		return (CTL_RETVAL_COMPLETE);
10383	}
10384	if (cdb->byte2 & SI_EVPD)
10385		retval = ctl_inquiry_evpd(ctsio);
10386#ifdef notyet
10387	else if (cdb->byte2 & SI_CMDDT)
10388		retval = ctl_inquiry_cmddt(ctsio);
10389#endif
10390	else
10391		retval = ctl_inquiry_std(ctsio);
10392
10393	return (retval);
10394}
10395
10396/*
10397 * For known CDB types, parse the LBA and length.
10398 */
10399static int
10400ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint32_t *len)
10401{
10402	if (io->io_hdr.io_type != CTL_IO_SCSI)
10403		return (1);
10404
10405	switch (io->scsiio.cdb[0]) {
10406	case COMPARE_AND_WRITE: {
10407		struct scsi_compare_and_write *cdb;
10408
10409		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10410
10411		*lba = scsi_8btou64(cdb->addr);
10412		*len = cdb->length;
10413		break;
10414	}
10415	case READ_6:
10416	case WRITE_6: {
10417		struct scsi_rw_6 *cdb;
10418
10419		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10420
10421		*lba = scsi_3btoul(cdb->addr);
10422		/* only 5 bits are valid in the most significant address byte */
10423		*lba &= 0x1fffff;
10424		*len = cdb->length;
10425		break;
10426	}
10427	case READ_10:
10428	case WRITE_10: {
10429		struct scsi_rw_10 *cdb;
10430
10431		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10432
10433		*lba = scsi_4btoul(cdb->addr);
10434		*len = scsi_2btoul(cdb->length);
10435		break;
10436	}
10437	case WRITE_VERIFY_10: {
10438		struct scsi_write_verify_10 *cdb;
10439
10440		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10441
10442		*lba = scsi_4btoul(cdb->addr);
10443		*len = scsi_2btoul(cdb->length);
10444		break;
10445	}
10446	case READ_12:
10447	case WRITE_12: {
10448		struct scsi_rw_12 *cdb;
10449
10450		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10451
10452		*lba = scsi_4btoul(cdb->addr);
10453		*len = scsi_4btoul(cdb->length);
10454		break;
10455	}
10456	case WRITE_VERIFY_12: {
10457		struct scsi_write_verify_12 *cdb;
10458
10459		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10460
10461		*lba = scsi_4btoul(cdb->addr);
10462		*len = scsi_4btoul(cdb->length);
10463		break;
10464	}
10465	case READ_16:
10466	case WRITE_16: {
10467		struct scsi_rw_16 *cdb;
10468
10469		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10470
10471		*lba = scsi_8btou64(cdb->addr);
10472		*len = scsi_4btoul(cdb->length);
10473		break;
10474	}
10475	case WRITE_VERIFY_16: {
10476		struct scsi_write_verify_16 *cdb;
10477
10478		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10479
10480
10481		*lba = scsi_8btou64(cdb->addr);
10482		*len = scsi_4btoul(cdb->length);
10483		break;
10484	}
10485	case WRITE_SAME_10: {
10486		struct scsi_write_same_10 *cdb;
10487
10488		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10489
10490		*lba = scsi_4btoul(cdb->addr);
10491		*len = scsi_2btoul(cdb->length);
10492		break;
10493	}
10494	case WRITE_SAME_16: {
10495		struct scsi_write_same_16 *cdb;
10496
10497		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10498
10499		*lba = scsi_8btou64(cdb->addr);
10500		*len = scsi_4btoul(cdb->length);
10501		break;
10502	}
10503	case VERIFY_10: {
10504		struct scsi_verify_10 *cdb;
10505
10506		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10507
10508		*lba = scsi_4btoul(cdb->addr);
10509		*len = scsi_2btoul(cdb->length);
10510		break;
10511	}
10512	case VERIFY_12: {
10513		struct scsi_verify_12 *cdb;
10514
10515		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10516
10517		*lba = scsi_4btoul(cdb->addr);
10518		*len = scsi_4btoul(cdb->length);
10519		break;
10520	}
10521	case VERIFY_16: {
10522		struct scsi_verify_16 *cdb;
10523
10524		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10525
10526		*lba = scsi_8btou64(cdb->addr);
10527		*len = scsi_4btoul(cdb->length);
10528		break;
10529	}
10530	default:
10531		return (1);
10532		break; /* NOTREACHED */
10533	}
10534
10535	return (0);
10536}
10537
10538static ctl_action
10539ctl_extent_check_lba(uint64_t lba1, uint32_t len1, uint64_t lba2, uint32_t len2)
10540{
10541	uint64_t endlba1, endlba2;
10542
10543	endlba1 = lba1 + len1 - 1;
10544	endlba2 = lba2 + len2 - 1;
10545
10546	if ((endlba1 < lba2)
10547	 || (endlba2 < lba1))
10548		return (CTL_ACTION_PASS);
10549	else
10550		return (CTL_ACTION_BLOCK);
10551}
10552
10553static ctl_action
10554ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10555{
10556	uint64_t lba1, lba2;
10557	uint32_t len1, len2;
10558	int retval;
10559
10560	retval = ctl_get_lba_len(io1, &lba1, &len1);
10561	if (retval != 0)
10562		return (CTL_ACTION_ERROR);
10563
10564	retval = ctl_get_lba_len(io2, &lba2, &len2);
10565	if (retval != 0)
10566		return (CTL_ACTION_ERROR);
10567
10568	return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10569}
10570
10571static ctl_action
10572ctl_check_for_blockage(union ctl_io *pending_io, union ctl_io *ooa_io)
10573{
10574	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10575	ctl_serialize_action *serialize_row;
10576
10577	/*
10578	 * The initiator attempted multiple untagged commands at the same
10579	 * time.  Can't do that.
10580	 */
10581	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10582	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10583	 && ((pending_io->io_hdr.nexus.targ_port ==
10584	      ooa_io->io_hdr.nexus.targ_port)
10585	  && (pending_io->io_hdr.nexus.initid.id ==
10586	      ooa_io->io_hdr.nexus.initid.id))
10587	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10588		return (CTL_ACTION_OVERLAP);
10589
10590	/*
10591	 * The initiator attempted to send multiple tagged commands with
10592	 * the same ID.  (It's fine if different initiators have the same
10593	 * tag ID.)
10594	 *
10595	 * Even if all of those conditions are true, we don't kill the I/O
10596	 * if the command ahead of us has been aborted.  We won't end up
10597	 * sending it to the FETD, and it's perfectly legal to resend a
10598	 * command with the same tag number as long as the previous
10599	 * instance of this tag number has been aborted somehow.
10600	 */
10601	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10602	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10603	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10604	 && ((pending_io->io_hdr.nexus.targ_port ==
10605	      ooa_io->io_hdr.nexus.targ_port)
10606	  && (pending_io->io_hdr.nexus.initid.id ==
10607	      ooa_io->io_hdr.nexus.initid.id))
10608	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10609		return (CTL_ACTION_OVERLAP_TAG);
10610
10611	/*
10612	 * If we get a head of queue tag, SAM-3 says that we should
10613	 * immediately execute it.
10614	 *
10615	 * What happens if this command would normally block for some other
10616	 * reason?  e.g. a request sense with a head of queue tag
10617	 * immediately after a write.  Normally that would block, but this
10618	 * will result in its getting executed immediately...
10619	 *
10620	 * We currently return "pass" instead of "skip", so we'll end up
10621	 * going through the rest of the queue to check for overlapped tags.
10622	 *
10623	 * XXX KDM check for other types of blockage first??
10624	 */
10625	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10626		return (CTL_ACTION_PASS);
10627
10628	/*
10629	 * Ordered tags have to block until all items ahead of them
10630	 * have completed.  If we get called with an ordered tag, we always
10631	 * block, if something else is ahead of us in the queue.
10632	 */
10633	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10634		return (CTL_ACTION_BLOCK);
10635
10636	/*
10637	 * Simple tags get blocked until all head of queue and ordered tags
10638	 * ahead of them have completed.  I'm lumping untagged commands in
10639	 * with simple tags here.  XXX KDM is that the right thing to do?
10640	 */
10641	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10642	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10643	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10644	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10645		return (CTL_ACTION_BLOCK);
10646
10647	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio);
10648	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio);
10649
10650	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10651
10652	switch (serialize_row[pending_entry->seridx]) {
10653	case CTL_SER_BLOCK:
10654		return (CTL_ACTION_BLOCK);
10655		break; /* NOTREACHED */
10656	case CTL_SER_EXTENT:
10657		return (ctl_extent_check(pending_io, ooa_io));
10658		break; /* NOTREACHED */
10659	case CTL_SER_PASS:
10660		return (CTL_ACTION_PASS);
10661		break; /* NOTREACHED */
10662	case CTL_SER_SKIP:
10663		return (CTL_ACTION_SKIP);
10664		break;
10665	default:
10666		panic("invalid serialization value %d",
10667		      serialize_row[pending_entry->seridx]);
10668		break; /* NOTREACHED */
10669	}
10670
10671	return (CTL_ACTION_ERROR);
10672}
10673
10674/*
10675 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10676 * Assumptions:
10677 * - pending_io is generally either incoming, or on the blocked queue
10678 * - starting I/O is the I/O we want to start the check with.
10679 */
10680static ctl_action
10681ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10682	      union ctl_io *starting_io)
10683{
10684	union ctl_io *ooa_io;
10685	ctl_action action;
10686
10687	mtx_assert(&lun->lun_lock, MA_OWNED);
10688
10689	/*
10690	 * Run back along the OOA queue, starting with the current
10691	 * blocked I/O and going through every I/O before it on the
10692	 * queue.  If starting_io is NULL, we'll just end up returning
10693	 * CTL_ACTION_PASS.
10694	 */
10695	for (ooa_io = starting_io; ooa_io != NULL;
10696	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10697	     ooa_links)){
10698
10699		/*
10700		 * This routine just checks to see whether
10701		 * cur_blocked is blocked by ooa_io, which is ahead
10702		 * of it in the queue.  It doesn't queue/dequeue
10703		 * cur_blocked.
10704		 */
10705		action = ctl_check_for_blockage(pending_io, ooa_io);
10706		switch (action) {
10707		case CTL_ACTION_BLOCK:
10708		case CTL_ACTION_OVERLAP:
10709		case CTL_ACTION_OVERLAP_TAG:
10710		case CTL_ACTION_SKIP:
10711		case CTL_ACTION_ERROR:
10712			return (action);
10713			break; /* NOTREACHED */
10714		case CTL_ACTION_PASS:
10715			break;
10716		default:
10717			panic("invalid action %d", action);
10718			break;  /* NOTREACHED */
10719		}
10720	}
10721
10722	return (CTL_ACTION_PASS);
10723}
10724
10725/*
10726 * Assumptions:
10727 * - An I/O has just completed, and has been removed from the per-LUN OOA
10728 *   queue, so some items on the blocked queue may now be unblocked.
10729 */
10730static int
10731ctl_check_blocked(struct ctl_lun *lun)
10732{
10733	union ctl_io *cur_blocked, *next_blocked;
10734
10735	mtx_assert(&lun->lun_lock, MA_OWNED);
10736
10737	/*
10738	 * Run forward from the head of the blocked queue, checking each
10739	 * entry against the I/Os prior to it on the OOA queue to see if
10740	 * there is still any blockage.
10741	 *
10742	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10743	 * with our removing a variable on it while it is traversing the
10744	 * list.
10745	 */
10746	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10747	     cur_blocked != NULL; cur_blocked = next_blocked) {
10748		union ctl_io *prev_ooa;
10749		ctl_action action;
10750
10751		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10752							  blocked_links);
10753
10754		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10755						      ctl_ooaq, ooa_links);
10756
10757		/*
10758		 * If cur_blocked happens to be the first item in the OOA
10759		 * queue now, prev_ooa will be NULL, and the action
10760		 * returned will just be CTL_ACTION_PASS.
10761		 */
10762		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
10763
10764		switch (action) {
10765		case CTL_ACTION_BLOCK:
10766			/* Nothing to do here, still blocked */
10767			break;
10768		case CTL_ACTION_OVERLAP:
10769		case CTL_ACTION_OVERLAP_TAG:
10770			/*
10771			 * This shouldn't happen!  In theory we've already
10772			 * checked this command for overlap...
10773			 */
10774			break;
10775		case CTL_ACTION_PASS:
10776		case CTL_ACTION_SKIP: {
10777			struct ctl_softc *softc;
10778			const struct ctl_cmd_entry *entry;
10779			uint32_t initidx;
10780			int isc_retval;
10781
10782			/*
10783			 * The skip case shouldn't happen, this transaction
10784			 * should have never made it onto the blocked queue.
10785			 */
10786			/*
10787			 * This I/O is no longer blocked, we can remove it
10788			 * from the blocked queue.  Since this is a TAILQ
10789			 * (doubly linked list), we can do O(1) removals
10790			 * from any place on the list.
10791			 */
10792			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
10793				     blocked_links);
10794			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10795
10796			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
10797				/*
10798				 * Need to send IO back to original side to
10799				 * run
10800				 */
10801				union ctl_ha_msg msg_info;
10802
10803				msg_info.hdr.original_sc =
10804					cur_blocked->io_hdr.original_sc;
10805				msg_info.hdr.serializing_sc = cur_blocked;
10806				msg_info.hdr.msg_type = CTL_MSG_R2R;
10807				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
10808				     &msg_info, sizeof(msg_info), 0)) >
10809				     CTL_HA_STATUS_SUCCESS) {
10810					printf("CTL:Check Blocked error from "
10811					       "ctl_ha_msg_send %d\n",
10812					       isc_retval);
10813				}
10814				break;
10815			}
10816			entry = ctl_get_cmd_entry(&cur_blocked->scsiio);
10817			softc = control_softc;
10818
10819			initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
10820
10821			/*
10822			 * Check this I/O for LUN state changes that may
10823			 * have happened while this command was blocked.
10824			 * The LUN state may have been changed by a command
10825			 * ahead of us in the queue, so we need to re-check
10826			 * for any states that can be caused by SCSI
10827			 * commands.
10828			 */
10829			if (ctl_scsiio_lun_check(softc, lun, entry,
10830						 &cur_blocked->scsiio) == 0) {
10831				cur_blocked->io_hdr.flags |=
10832				                      CTL_FLAG_IS_WAS_ON_RTR;
10833				ctl_enqueue_rtr(cur_blocked);
10834			} else
10835				ctl_done(cur_blocked);
10836			break;
10837		}
10838		default:
10839			/*
10840			 * This probably shouldn't happen -- we shouldn't
10841			 * get CTL_ACTION_ERROR, or anything else.
10842			 */
10843			break;
10844		}
10845	}
10846
10847	return (CTL_RETVAL_COMPLETE);
10848}
10849
10850/*
10851 * This routine (with one exception) checks LUN flags that can be set by
10852 * commands ahead of us in the OOA queue.  These flags have to be checked
10853 * when a command initially comes in, and when we pull a command off the
10854 * blocked queue and are preparing to execute it.  The reason we have to
10855 * check these flags for commands on the blocked queue is that the LUN
10856 * state may have been changed by a command ahead of us while we're on the
10857 * blocked queue.
10858 *
10859 * Ordering is somewhat important with these checks, so please pay
10860 * careful attention to the placement of any new checks.
10861 */
10862static int
10863ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
10864    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
10865{
10866	int retval;
10867
10868	retval = 0;
10869
10870	mtx_assert(&lun->lun_lock, MA_OWNED);
10871
10872	/*
10873	 * If this shelf is a secondary shelf controller, we have to reject
10874	 * any media access commands.
10875	 */
10876#if 0
10877	/* No longer needed for HA */
10878	if (((ctl_softc->flags & CTL_FLAG_MASTER_SHELF) == 0)
10879	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0)) {
10880		ctl_set_lun_standby(ctsio);
10881		retval = 1;
10882		goto bailout;
10883	}
10884#endif
10885
10886	/*
10887	 * Check for a reservation conflict.  If this command isn't allowed
10888	 * even on reserved LUNs, and if this initiator isn't the one who
10889	 * reserved us, reject the command with a reservation conflict.
10890	 */
10891	if ((lun->flags & CTL_LUN_RESERVED)
10892	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
10893		if ((ctsio->io_hdr.nexus.initid.id != lun->rsv_nexus.initid.id)
10894		 || (ctsio->io_hdr.nexus.targ_port != lun->rsv_nexus.targ_port)
10895		 || (ctsio->io_hdr.nexus.targ_target.id !=
10896		     lun->rsv_nexus.targ_target.id)) {
10897			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
10898			ctsio->io_hdr.status = CTL_SCSI_ERROR;
10899			retval = 1;
10900			goto bailout;
10901		}
10902	}
10903
10904	if ( (lun->flags & CTL_LUN_PR_RESERVED)
10905	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV) == 0)) {
10906		uint32_t residx;
10907
10908		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
10909		/*
10910		 * if we aren't registered or it's a res holder type
10911		 * reservation and this isn't the res holder then set a
10912		 * conflict.
10913		 * NOTE: Commands which might be allowed on write exclusive
10914		 * type reservations are checked in the particular command
10915		 * for a conflict. Read and SSU are the only ones.
10916		 */
10917		if (!lun->per_res[residx].registered
10918		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
10919			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
10920			ctsio->io_hdr.status = CTL_SCSI_ERROR;
10921			retval = 1;
10922			goto bailout;
10923		}
10924
10925	}
10926
10927	if ((lun->flags & CTL_LUN_OFFLINE)
10928	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
10929		ctl_set_lun_not_ready(ctsio);
10930		retval = 1;
10931		goto bailout;
10932	}
10933
10934	/*
10935	 * If the LUN is stopped, see if this particular command is allowed
10936	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
10937	 */
10938	if ((lun->flags & CTL_LUN_STOPPED)
10939	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
10940		/* "Logical unit not ready, initializing cmd. required" */
10941		ctl_set_lun_stopped(ctsio);
10942		retval = 1;
10943		goto bailout;
10944	}
10945
10946	if ((lun->flags & CTL_LUN_INOPERABLE)
10947	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
10948		/* "Medium format corrupted" */
10949		ctl_set_medium_format_corrupted(ctsio);
10950		retval = 1;
10951		goto bailout;
10952	}
10953
10954bailout:
10955	return (retval);
10956
10957}
10958
10959static void
10960ctl_failover_io(union ctl_io *io, int have_lock)
10961{
10962	ctl_set_busy(&io->scsiio);
10963	ctl_done(io);
10964}
10965
10966static void
10967ctl_failover(void)
10968{
10969	struct ctl_lun *lun;
10970	struct ctl_softc *ctl_softc;
10971	union ctl_io *next_io, *pending_io;
10972	union ctl_io *io;
10973	int lun_idx;
10974	int i;
10975
10976	ctl_softc = control_softc;
10977
10978	mtx_lock(&ctl_softc->ctl_lock);
10979	/*
10980	 * Remove any cmds from the other SC from the rtr queue.  These
10981	 * will obviously only be for LUNs for which we're the primary.
10982	 * We can't send status or get/send data for these commands.
10983	 * Since they haven't been executed yet, we can just remove them.
10984	 * We'll either abort them or delete them below, depending on
10985	 * which HA mode we're in.
10986	 */
10987#ifdef notyet
10988	mtx_lock(&ctl_softc->queue_lock);
10989	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
10990	     io != NULL; io = next_io) {
10991		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
10992		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
10993			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
10994				      ctl_io_hdr, links);
10995	}
10996	mtx_unlock(&ctl_softc->queue_lock);
10997#endif
10998
10999	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11000		lun = ctl_softc->ctl_luns[lun_idx];
11001		if (lun==NULL)
11002			continue;
11003
11004		/*
11005		 * Processor LUNs are primary on both sides.
11006		 * XXX will this always be true?
11007		 */
11008		if (lun->be_lun->lun_type == T_PROCESSOR)
11009			continue;
11010
11011		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11012		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11013			printf("FAILOVER: primary lun %d\n", lun_idx);
11014		        /*
11015			 * Remove all commands from the other SC. First from the
11016			 * blocked queue then from the ooa queue. Once we have
11017			 * removed them. Call ctl_check_blocked to see if there
11018			 * is anything that can run.
11019			 */
11020			for (io = (union ctl_io *)TAILQ_FIRST(
11021			     &lun->blocked_queue); io != NULL; io = next_io) {
11022
11023		        	next_io = (union ctl_io *)TAILQ_NEXT(
11024				    &io->io_hdr, blocked_links);
11025
11026				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11027					TAILQ_REMOVE(&lun->blocked_queue,
11028						     &io->io_hdr,blocked_links);
11029					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11030					TAILQ_REMOVE(&lun->ooa_queue,
11031						     &io->io_hdr, ooa_links);
11032
11033					ctl_free_io(io);
11034				}
11035			}
11036
11037			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11038	     		     io != NULL; io = next_io) {
11039
11040		        	next_io = (union ctl_io *)TAILQ_NEXT(
11041				    &io->io_hdr, ooa_links);
11042
11043				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11044
11045					TAILQ_REMOVE(&lun->ooa_queue,
11046						&io->io_hdr,
11047					     	ooa_links);
11048
11049					ctl_free_io(io);
11050				}
11051			}
11052			ctl_check_blocked(lun);
11053		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11054			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11055
11056			printf("FAILOVER: primary lun %d\n", lun_idx);
11057			/*
11058			 * Abort all commands from the other SC.  We can't
11059			 * send status back for them now.  These should get
11060			 * cleaned up when they are completed or come out
11061			 * for a datamove operation.
11062			 */
11063			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11064	     		     io != NULL; io = next_io) {
11065		        	next_io = (union ctl_io *)TAILQ_NEXT(
11066					&io->io_hdr, ooa_links);
11067
11068				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11069					io->io_hdr.flags |= CTL_FLAG_ABORT;
11070			}
11071		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11072			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11073
11074			printf("FAILOVER: secondary lun %d\n", lun_idx);
11075
11076			lun->flags |= CTL_LUN_PRIMARY_SC;
11077
11078			/*
11079			 * We send all I/O that was sent to this controller
11080			 * and redirected to the other side back with
11081			 * busy status, and have the initiator retry it.
11082			 * Figuring out how much data has been transferred,
11083			 * etc. and picking up where we left off would be
11084			 * very tricky.
11085			 *
11086			 * XXX KDM need to remove I/O from the blocked
11087			 * queue as well!
11088			 */
11089			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11090			     &lun->ooa_queue); pending_io != NULL;
11091			     pending_io = next_io) {
11092
11093				next_io =  (union ctl_io *)TAILQ_NEXT(
11094					&pending_io->io_hdr, ooa_links);
11095
11096				pending_io->io_hdr.flags &=
11097					~CTL_FLAG_SENT_2OTHER_SC;
11098
11099				if (pending_io->io_hdr.flags &
11100				    CTL_FLAG_IO_ACTIVE) {
11101					pending_io->io_hdr.flags |=
11102						CTL_FLAG_FAILOVER;
11103				} else {
11104					ctl_set_busy(&pending_io->scsiio);
11105					ctl_done(pending_io);
11106				}
11107			}
11108
11109			/*
11110			 * Build Unit Attention
11111			 */
11112			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11113				lun->pending_sense[i].ua_pending |=
11114				                     CTL_UA_ASYM_ACC_CHANGE;
11115			}
11116		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11117			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11118			printf("FAILOVER: secondary lun %d\n", lun_idx);
11119			/*
11120			 * if the first io on the OOA is not on the RtR queue
11121			 * add it.
11122			 */
11123			lun->flags |= CTL_LUN_PRIMARY_SC;
11124
11125			pending_io = (union ctl_io *)TAILQ_FIRST(
11126			    &lun->ooa_queue);
11127			if (pending_io==NULL) {
11128				printf("Nothing on OOA queue\n");
11129				continue;
11130			}
11131
11132			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11133			if ((pending_io->io_hdr.flags &
11134			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11135				pending_io->io_hdr.flags |=
11136				    CTL_FLAG_IS_WAS_ON_RTR;
11137				ctl_enqueue_rtr(pending_io);
11138			}
11139#if 0
11140			else
11141			{
11142				printf("Tag 0x%04x is running\n",
11143				      pending_io->scsiio.tag_num);
11144			}
11145#endif
11146
11147			next_io = (union ctl_io *)TAILQ_NEXT(
11148			    &pending_io->io_hdr, ooa_links);
11149			for (pending_io=next_io; pending_io != NULL;
11150			     pending_io = next_io) {
11151				pending_io->io_hdr.flags &=
11152				    ~CTL_FLAG_SENT_2OTHER_SC;
11153				next_io = (union ctl_io *)TAILQ_NEXT(
11154					&pending_io->io_hdr, ooa_links);
11155				if (pending_io->io_hdr.flags &
11156				    CTL_FLAG_IS_WAS_ON_RTR) {
11157#if 0
11158				        printf("Tag 0x%04x is running\n",
11159				      		pending_io->scsiio.tag_num);
11160#endif
11161					continue;
11162				}
11163
11164				switch (ctl_check_ooa(lun, pending_io,
11165			            (union ctl_io *)TAILQ_PREV(
11166				    &pending_io->io_hdr, ctl_ooaq,
11167				    ooa_links))) {
11168
11169				case CTL_ACTION_BLOCK:
11170					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11171							  &pending_io->io_hdr,
11172							  blocked_links);
11173					pending_io->io_hdr.flags |=
11174					    CTL_FLAG_BLOCKED;
11175					break;
11176				case CTL_ACTION_PASS:
11177				case CTL_ACTION_SKIP:
11178					pending_io->io_hdr.flags |=
11179					    CTL_FLAG_IS_WAS_ON_RTR;
11180					ctl_enqueue_rtr(pending_io);
11181					break;
11182				case CTL_ACTION_OVERLAP:
11183					ctl_set_overlapped_cmd(
11184					    (struct ctl_scsiio *)pending_io);
11185					ctl_done(pending_io);
11186					break;
11187				case CTL_ACTION_OVERLAP_TAG:
11188					ctl_set_overlapped_tag(
11189					    (struct ctl_scsiio *)pending_io,
11190					    pending_io->scsiio.tag_num & 0xff);
11191					ctl_done(pending_io);
11192					break;
11193				case CTL_ACTION_ERROR:
11194				default:
11195					ctl_set_internal_failure(
11196						(struct ctl_scsiio *)pending_io,
11197						0,  // sks_valid
11198						0); //retry count
11199					ctl_done(pending_io);
11200					break;
11201				}
11202			}
11203
11204			/*
11205			 * Build Unit Attention
11206			 */
11207			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11208				lun->pending_sense[i].ua_pending |=
11209				                     CTL_UA_ASYM_ACC_CHANGE;
11210			}
11211		} else {
11212			panic("Unhandled HA mode failover, LUN flags = %#x, "
11213			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11214		}
11215	}
11216	ctl_pause_rtr = 0;
11217	mtx_unlock(&ctl_softc->ctl_lock);
11218}
11219
11220static int
11221ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11222{
11223	struct ctl_lun *lun;
11224	const struct ctl_cmd_entry *entry;
11225	uint32_t initidx, targ_lun;
11226	int retval;
11227
11228	retval = 0;
11229
11230	lun = NULL;
11231
11232	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11233	if ((targ_lun < CTL_MAX_LUNS)
11234	 && (ctl_softc->ctl_luns[targ_lun] != NULL)) {
11235		lun = ctl_softc->ctl_luns[targ_lun];
11236		/*
11237		 * If the LUN is invalid, pretend that it doesn't exist.
11238		 * It will go away as soon as all pending I/O has been
11239		 * completed.
11240		 */
11241		if (lun->flags & CTL_LUN_DISABLED) {
11242			lun = NULL;
11243		} else {
11244			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11245			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11246				lun->be_lun;
11247			if (lun->be_lun->lun_type == T_PROCESSOR) {
11248				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11249			}
11250
11251			/*
11252			 * Every I/O goes into the OOA queue for a
11253			 * particular LUN, and stays there until completion.
11254			 */
11255			mtx_lock(&lun->lun_lock);
11256			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11257			    ooa_links);
11258		}
11259	} else {
11260		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11261		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11262	}
11263
11264	/* Get command entry and return error if it is unsuppotyed. */
11265	entry = ctl_validate_command(ctsio);
11266	if (entry == NULL) {
11267		if (lun)
11268			mtx_unlock(&lun->lun_lock);
11269		return (retval);
11270	}
11271
11272	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11273	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11274
11275	/*
11276	 * Check to see whether we can send this command to LUNs that don't
11277	 * exist.  This should pretty much only be the case for inquiry
11278	 * and request sense.  Further checks, below, really require having
11279	 * a LUN, so we can't really check the command anymore.  Just put
11280	 * it on the rtr queue.
11281	 */
11282	if (lun == NULL) {
11283		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11284			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11285			ctl_enqueue_rtr((union ctl_io *)ctsio);
11286			return (retval);
11287		}
11288
11289		ctl_set_unsupported_lun(ctsio);
11290		ctl_done((union ctl_io *)ctsio);
11291		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11292		return (retval);
11293	} else {
11294		/*
11295		 * Make sure we support this particular command on this LUN.
11296		 * e.g., we don't support writes to the control LUN.
11297		 */
11298		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11299			mtx_unlock(&lun->lun_lock);
11300			ctl_set_invalid_opcode(ctsio);
11301			ctl_done((union ctl_io *)ctsio);
11302			return (retval);
11303		}
11304	}
11305
11306	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11307
11308	/*
11309	 * If we've got a request sense, it'll clear the contingent
11310	 * allegiance condition.  Otherwise, if we have a CA condition for
11311	 * this initiator, clear it, because it sent down a command other
11312	 * than request sense.
11313	 */
11314	if ((ctsio->cdb[0] != REQUEST_SENSE)
11315	 && (ctl_is_set(lun->have_ca, initidx)))
11316		ctl_clear_mask(lun->have_ca, initidx);
11317
11318	/*
11319	 * If the command has this flag set, it handles its own unit
11320	 * attention reporting, we shouldn't do anything.  Otherwise we
11321	 * check for any pending unit attentions, and send them back to the
11322	 * initiator.  We only do this when a command initially comes in,
11323	 * not when we pull it off the blocked queue.
11324	 *
11325	 * According to SAM-3, section 5.3.2, the order that things get
11326	 * presented back to the host is basically unit attentions caused
11327	 * by some sort of reset event, busy status, reservation conflicts
11328	 * or task set full, and finally any other status.
11329	 *
11330	 * One issue here is that some of the unit attentions we report
11331	 * don't fall into the "reset" category (e.g. "reported luns data
11332	 * has changed").  So reporting it here, before the reservation
11333	 * check, may be technically wrong.  I guess the only thing to do
11334	 * would be to check for and report the reset events here, and then
11335	 * check for the other unit attention types after we check for a
11336	 * reservation conflict.
11337	 *
11338	 * XXX KDM need to fix this
11339	 */
11340	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11341		ctl_ua_type ua_type;
11342
11343		ua_type = lun->pending_sense[initidx].ua_pending;
11344		if (ua_type != CTL_UA_NONE) {
11345			scsi_sense_data_type sense_format;
11346
11347			if (lun != NULL)
11348				sense_format = (lun->flags &
11349				    CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11350				    SSD_TYPE_FIXED;
11351			else
11352				sense_format = SSD_TYPE_FIXED;
11353
11354			ua_type = ctl_build_ua(ua_type, &ctsio->sense_data,
11355					       sense_format);
11356			if (ua_type != CTL_UA_NONE) {
11357				ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11358				ctsio->io_hdr.status = CTL_SCSI_ERROR |
11359						       CTL_AUTOSENSE;
11360				ctsio->sense_len = SSD_FULL_SIZE;
11361				lun->pending_sense[initidx].ua_pending &=
11362					~ua_type;
11363				mtx_unlock(&lun->lun_lock);
11364				ctl_done((union ctl_io *)ctsio);
11365				return (retval);
11366			}
11367		}
11368	}
11369
11370
11371	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11372		mtx_unlock(&lun->lun_lock);
11373		ctl_done((union ctl_io *)ctsio);
11374		return (retval);
11375	}
11376
11377	/*
11378	 * XXX CHD this is where we want to send IO to other side if
11379	 * this LUN is secondary on this SC. We will need to make a copy
11380	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11381	 * the copy we send as FROM_OTHER.
11382	 * We also need to stuff the address of the original IO so we can
11383	 * find it easily. Something similar will need be done on the other
11384	 * side so when we are done we can find the copy.
11385	 */
11386	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11387		union ctl_ha_msg msg_info;
11388		int isc_retval;
11389
11390		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11391
11392		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11393		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11394#if 0
11395		printf("1. ctsio %p\n", ctsio);
11396#endif
11397		msg_info.hdr.serializing_sc = NULL;
11398		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11399		msg_info.scsi.tag_num = ctsio->tag_num;
11400		msg_info.scsi.tag_type = ctsio->tag_type;
11401		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11402
11403		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11404
11405		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11406		    (void *)&msg_info, sizeof(msg_info), 0)) >
11407		    CTL_HA_STATUS_SUCCESS) {
11408			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11409			       isc_retval);
11410			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11411		} else {
11412#if 0
11413			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11414#endif
11415		}
11416
11417		/*
11418		 * XXX KDM this I/O is off the incoming queue, but hasn't
11419		 * been inserted on any other queue.  We may need to come
11420		 * up with a holding queue while we wait for serialization
11421		 * so that we have an idea of what we're waiting for from
11422		 * the other side.
11423		 */
11424		mtx_unlock(&lun->lun_lock);
11425		return (retval);
11426	}
11427
11428	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11429			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11430			      ctl_ooaq, ooa_links))) {
11431	case CTL_ACTION_BLOCK:
11432		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11433		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11434				  blocked_links);
11435		mtx_unlock(&lun->lun_lock);
11436		return (retval);
11437	case CTL_ACTION_PASS:
11438	case CTL_ACTION_SKIP:
11439		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11440		mtx_unlock(&lun->lun_lock);
11441		ctl_enqueue_rtr((union ctl_io *)ctsio);
11442		break;
11443	case CTL_ACTION_OVERLAP:
11444		mtx_unlock(&lun->lun_lock);
11445		ctl_set_overlapped_cmd(ctsio);
11446		ctl_done((union ctl_io *)ctsio);
11447		break;
11448	case CTL_ACTION_OVERLAP_TAG:
11449		mtx_unlock(&lun->lun_lock);
11450		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11451		ctl_done((union ctl_io *)ctsio);
11452		break;
11453	case CTL_ACTION_ERROR:
11454	default:
11455		mtx_unlock(&lun->lun_lock);
11456		ctl_set_internal_failure(ctsio,
11457					 /*sks_valid*/ 0,
11458					 /*retry_count*/ 0);
11459		ctl_done((union ctl_io *)ctsio);
11460		break;
11461	}
11462	return (retval);
11463}
11464
11465const struct ctl_cmd_entry *
11466ctl_get_cmd_entry(struct ctl_scsiio *ctsio)
11467{
11468	const struct ctl_cmd_entry *entry;
11469	int service_action;
11470
11471	entry = &ctl_cmd_table[ctsio->cdb[0]];
11472	if (entry->flags & CTL_CMD_FLAG_SA5) {
11473		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11474		entry = &((const struct ctl_cmd_entry *)
11475		    entry->execute)[service_action];
11476	}
11477	return (entry);
11478}
11479
11480const struct ctl_cmd_entry *
11481ctl_validate_command(struct ctl_scsiio *ctsio)
11482{
11483	const struct ctl_cmd_entry *entry;
11484	int i;
11485	uint8_t diff;
11486
11487	entry = ctl_get_cmd_entry(ctsio);
11488	if (entry->execute == NULL) {
11489		ctl_set_invalid_opcode(ctsio);
11490		ctl_done((union ctl_io *)ctsio);
11491		return (NULL);
11492	}
11493	KASSERT(entry->length > 0,
11494	    ("Not defined length for command 0x%02x/0x%02x",
11495	     ctsio->cdb[0], ctsio->cdb[1]));
11496	for (i = 1; i < entry->length; i++) {
11497		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11498		if (diff == 0)
11499			continue;
11500		ctl_set_invalid_field(ctsio,
11501				      /*sks_valid*/ 1,
11502				      /*command*/ 1,
11503				      /*field*/ i,
11504				      /*bit_valid*/ 1,
11505				      /*bit*/ fls(diff) - 1);
11506		ctl_done((union ctl_io *)ctsio);
11507		return (NULL);
11508	}
11509	return (entry);
11510}
11511
11512static int
11513ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11514{
11515
11516	switch (lun_type) {
11517	case T_PROCESSOR:
11518		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11519		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11520			return (0);
11521		break;
11522	case T_DIRECT:
11523		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11524		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11525			return (0);
11526		break;
11527	default:
11528		return (0);
11529	}
11530	return (1);
11531}
11532
11533static int
11534ctl_scsiio(struct ctl_scsiio *ctsio)
11535{
11536	int retval;
11537	const struct ctl_cmd_entry *entry;
11538
11539	retval = CTL_RETVAL_COMPLETE;
11540
11541	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11542
11543	entry = ctl_get_cmd_entry(ctsio);
11544
11545	/*
11546	 * If this I/O has been aborted, just send it straight to
11547	 * ctl_done() without executing it.
11548	 */
11549	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11550		ctl_done((union ctl_io *)ctsio);
11551		goto bailout;
11552	}
11553
11554	/*
11555	 * All the checks should have been handled by ctl_scsiio_precheck().
11556	 * We should be clear now to just execute the I/O.
11557	 */
11558	retval = entry->execute(ctsio);
11559
11560bailout:
11561	return (retval);
11562}
11563
11564/*
11565 * Since we only implement one target right now, a bus reset simply resets
11566 * our single target.
11567 */
11568static int
11569ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11570{
11571	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11572}
11573
11574static int
11575ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11576		 ctl_ua_type ua_type)
11577{
11578	struct ctl_lun *lun;
11579	int retval;
11580
11581	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11582		union ctl_ha_msg msg_info;
11583
11584		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11585		msg_info.hdr.nexus = io->io_hdr.nexus;
11586		if (ua_type==CTL_UA_TARG_RESET)
11587			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11588		else
11589			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11590		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11591		msg_info.hdr.original_sc = NULL;
11592		msg_info.hdr.serializing_sc = NULL;
11593		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11594		    (void *)&msg_info, sizeof(msg_info), 0)) {
11595		}
11596	}
11597	retval = 0;
11598
11599	mtx_lock(&ctl_softc->ctl_lock);
11600	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11601		retval += ctl_lun_reset(lun, io, ua_type);
11602	mtx_unlock(&ctl_softc->ctl_lock);
11603
11604	return (retval);
11605}
11606
11607/*
11608 * The LUN should always be set.  The I/O is optional, and is used to
11609 * distinguish between I/Os sent by this initiator, and by other
11610 * initiators.  We set unit attention for initiators other than this one.
11611 * SAM-3 is vague on this point.  It does say that a unit attention should
11612 * be established for other initiators when a LUN is reset (see section
11613 * 5.7.3), but it doesn't specifically say that the unit attention should
11614 * be established for this particular initiator when a LUN is reset.  Here
11615 * is the relevant text, from SAM-3 rev 8:
11616 *
11617 * 5.7.2 When a SCSI initiator port aborts its own tasks
11618 *
11619 * When a SCSI initiator port causes its own task(s) to be aborted, no
11620 * notification that the task(s) have been aborted shall be returned to
11621 * the SCSI initiator port other than the completion response for the
11622 * command or task management function action that caused the task(s) to
11623 * be aborted and notification(s) associated with related effects of the
11624 * action (e.g., a reset unit attention condition).
11625 *
11626 * XXX KDM for now, we're setting unit attention for all initiators.
11627 */
11628static int
11629ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11630{
11631	union ctl_io *xio;
11632#if 0
11633	uint32_t initindex;
11634#endif
11635	int i;
11636
11637	mtx_lock(&lun->lun_lock);
11638	/*
11639	 * Run through the OOA queue and abort each I/O.
11640	 */
11641#if 0
11642	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11643#endif
11644	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11645	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11646		xio->io_hdr.flags |= CTL_FLAG_ABORT;
11647	}
11648
11649	/*
11650	 * This version sets unit attention for every
11651	 */
11652#if 0
11653	initindex = ctl_get_initindex(&io->io_hdr.nexus);
11654	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11655		if (initindex == i)
11656			continue;
11657		lun->pending_sense[i].ua_pending |= ua_type;
11658	}
11659#endif
11660
11661	/*
11662	 * A reset (any kind, really) clears reservations established with
11663	 * RESERVE/RELEASE.  It does not clear reservations established
11664	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11665	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11666	 * reservations made with the RESERVE/RELEASE commands, because
11667	 * those commands are obsolete in SPC-3.
11668	 */
11669	lun->flags &= ~CTL_LUN_RESERVED;
11670
11671	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11672		ctl_clear_mask(lun->have_ca, i);
11673		lun->pending_sense[i].ua_pending |= ua_type;
11674	}
11675	mtx_unlock(&lun->lun_lock);
11676
11677	return (0);
11678}
11679
11680static int
11681ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11682    int other_sc)
11683{
11684	union ctl_io *xio;
11685	int found;
11686
11687	mtx_assert(&lun->lun_lock, MA_OWNED);
11688
11689	/*
11690	 * Run through the OOA queue and attempt to find the given I/O.
11691	 * The target port, initiator ID, tag type and tag number have to
11692	 * match the values that we got from the initiator.  If we have an
11693	 * untagged command to abort, simply abort the first untagged command
11694	 * we come to.  We only allow one untagged command at a time of course.
11695	 */
11696	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11697	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11698
11699		if ((targ_port == xio->io_hdr.nexus.targ_port) &&
11700		    (init_id == xio->io_hdr.nexus.initid.id)) {
11701			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11702			found = 1;
11703			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11704				union ctl_ha_msg msg_info;
11705
11706				msg_info.hdr.nexus = xio->io_hdr.nexus;
11707				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11708				msg_info.task.tag_num = xio->scsiio.tag_num;
11709				msg_info.task.tag_type = xio->scsiio.tag_type;
11710				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11711				msg_info.hdr.original_sc = NULL;
11712				msg_info.hdr.serializing_sc = NULL;
11713				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11714				    (void *)&msg_info, sizeof(msg_info), 0);
11715			}
11716		}
11717	}
11718	return (found);
11719}
11720
11721static int
11722ctl_abort_task_set(union ctl_io *io)
11723{
11724	struct ctl_softc *softc = control_softc;
11725	struct ctl_lun *lun;
11726	uint32_t targ_lun;
11727
11728	/*
11729	 * Look up the LUN.
11730	 */
11731	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11732	mtx_lock(&softc->ctl_lock);
11733	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
11734		lun = softc->ctl_luns[targ_lun];
11735	else {
11736		mtx_unlock(&softc->ctl_lock);
11737		return (1);
11738	}
11739
11740	mtx_lock(&lun->lun_lock);
11741	mtx_unlock(&softc->ctl_lock);
11742	ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11743	    io->io_hdr.nexus.initid.id,
11744	    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11745	mtx_unlock(&lun->lun_lock);
11746	return (0);
11747}
11748
11749static int
11750ctl_i_t_nexus_reset(union ctl_io *io)
11751{
11752	struct ctl_softc *softc = control_softc;
11753	struct ctl_lun *lun;
11754	uint32_t initindex;
11755
11756	initindex = ctl_get_initindex(&io->io_hdr.nexus);
11757	mtx_lock(&softc->ctl_lock);
11758	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11759		mtx_lock(&lun->lun_lock);
11760		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11761		    io->io_hdr.nexus.initid.id,
11762		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11763		ctl_clear_mask(lun->have_ca, initindex);
11764		lun->pending_sense[initindex].ua_pending |= CTL_UA_I_T_NEXUS_LOSS;
11765		mtx_unlock(&lun->lun_lock);
11766	}
11767	mtx_unlock(&softc->ctl_lock);
11768	return (0);
11769}
11770
11771static int
11772ctl_abort_task(union ctl_io *io)
11773{
11774	union ctl_io *xio;
11775	struct ctl_lun *lun;
11776	struct ctl_softc *ctl_softc;
11777#if 0
11778	struct sbuf sb;
11779	char printbuf[128];
11780#endif
11781	int found;
11782	uint32_t targ_lun;
11783
11784	ctl_softc = control_softc;
11785	found = 0;
11786
11787	/*
11788	 * Look up the LUN.
11789	 */
11790	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11791	mtx_lock(&ctl_softc->ctl_lock);
11792	if ((targ_lun < CTL_MAX_LUNS)
11793	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
11794		lun = ctl_softc->ctl_luns[targ_lun];
11795	else {
11796		mtx_unlock(&ctl_softc->ctl_lock);
11797		goto bailout;
11798	}
11799
11800#if 0
11801	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11802	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11803#endif
11804
11805	mtx_lock(&lun->lun_lock);
11806	mtx_unlock(&ctl_softc->ctl_lock);
11807	/*
11808	 * Run through the OOA queue and attempt to find the given I/O.
11809	 * The target port, initiator ID, tag type and tag number have to
11810	 * match the values that we got from the initiator.  If we have an
11811	 * untagged command to abort, simply abort the first untagged command
11812	 * we come to.  We only allow one untagged command at a time of course.
11813	 */
11814#if 0
11815	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11816#endif
11817	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11818	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11819#if 0
11820		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
11821
11822		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
11823			    lun->lun, xio->scsiio.tag_num,
11824			    xio->scsiio.tag_type,
11825			    (xio->io_hdr.blocked_links.tqe_prev
11826			    == NULL) ? "" : " BLOCKED",
11827			    (xio->io_hdr.flags &
11828			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
11829			    (xio->io_hdr.flags &
11830			    CTL_FLAG_ABORT) ? " ABORT" : "",
11831			    (xio->io_hdr.flags &
11832			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
11833		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
11834		sbuf_finish(&sb);
11835		printf("%s\n", sbuf_data(&sb));
11836#endif
11837
11838		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
11839		 && (xio->io_hdr.nexus.initid.id ==
11840		     io->io_hdr.nexus.initid.id)) {
11841			/*
11842			 * If the abort says that the task is untagged, the
11843			 * task in the queue must be untagged.  Otherwise,
11844			 * we just check to see whether the tag numbers
11845			 * match.  This is because the QLogic firmware
11846			 * doesn't pass back the tag type in an abort
11847			 * request.
11848			 */
11849#if 0
11850			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
11851			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
11852			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
11853#endif
11854			/*
11855			 * XXX KDM we've got problems with FC, because it
11856			 * doesn't send down a tag type with aborts.  So we
11857			 * can only really go by the tag number...
11858			 * This may cause problems with parallel SCSI.
11859			 * Need to figure that out!!
11860			 */
11861			if (xio->scsiio.tag_num == io->taskio.tag_num) {
11862				xio->io_hdr.flags |= CTL_FLAG_ABORT;
11863				found = 1;
11864				if ((io->io_hdr.flags &
11865				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
11866				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11867					union ctl_ha_msg msg_info;
11868
11869					io->io_hdr.flags |=
11870					                CTL_FLAG_SENT_2OTHER_SC;
11871					msg_info.hdr.nexus = io->io_hdr.nexus;
11872					msg_info.task.task_action =
11873						CTL_TASK_ABORT_TASK;
11874					msg_info.task.tag_num =
11875						io->taskio.tag_num;
11876					msg_info.task.tag_type =
11877						io->taskio.tag_type;
11878					msg_info.hdr.msg_type =
11879						CTL_MSG_MANAGE_TASKS;
11880					msg_info.hdr.original_sc = NULL;
11881					msg_info.hdr.serializing_sc = NULL;
11882#if 0
11883					printf("Sent Abort to other side\n");
11884#endif
11885					if (CTL_HA_STATUS_SUCCESS !=
11886					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11887		    				(void *)&msg_info,
11888						sizeof(msg_info), 0)) {
11889					}
11890				}
11891#if 0
11892				printf("ctl_abort_task: found I/O to abort\n");
11893#endif
11894				break;
11895			}
11896		}
11897	}
11898	mtx_unlock(&lun->lun_lock);
11899
11900bailout:
11901
11902	if (found == 0) {
11903		/*
11904		 * This isn't really an error.  It's entirely possible for
11905		 * the abort and command completion to cross on the wire.
11906		 * This is more of an informative/diagnostic error.
11907		 */
11908#if 0
11909		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
11910		       "%d:%d:%d:%d tag %d type %d\n",
11911		       io->io_hdr.nexus.initid.id,
11912		       io->io_hdr.nexus.targ_port,
11913		       io->io_hdr.nexus.targ_target.id,
11914		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
11915		       io->taskio.tag_type);
11916#endif
11917		return (1);
11918	} else
11919		return (0);
11920}
11921
11922static void
11923ctl_run_task(union ctl_io *io)
11924{
11925	struct ctl_softc *ctl_softc;
11926	int retval;
11927	const char *task_desc;
11928
11929	CTL_DEBUG_PRINT(("ctl_run_task\n"));
11930
11931	ctl_softc = control_softc;
11932	retval = 0;
11933
11934	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
11935	    ("ctl_run_task: Unextected io_type %d\n",
11936	     io->io_hdr.io_type));
11937
11938	task_desc = ctl_scsi_task_string(&io->taskio);
11939	if (task_desc != NULL) {
11940#ifdef NEEDTOPORT
11941		csevent_log(CSC_CTL | CSC_SHELF_SW |
11942			    CTL_TASK_REPORT,
11943			    csevent_LogType_Trace,
11944			    csevent_Severity_Information,
11945			    csevent_AlertLevel_Green,
11946			    csevent_FRU_Firmware,
11947			    csevent_FRU_Unknown,
11948			    "CTL: received task: %s",task_desc);
11949#endif
11950	} else {
11951#ifdef NEEDTOPORT
11952		csevent_log(CSC_CTL | CSC_SHELF_SW |
11953			    CTL_TASK_REPORT,
11954			    csevent_LogType_Trace,
11955			    csevent_Severity_Information,
11956			    csevent_AlertLevel_Green,
11957			    csevent_FRU_Firmware,
11958			    csevent_FRU_Unknown,
11959			    "CTL: received unknown task "
11960			    "type: %d (%#x)",
11961			    io->taskio.task_action,
11962			    io->taskio.task_action);
11963#endif
11964	}
11965	switch (io->taskio.task_action) {
11966	case CTL_TASK_ABORT_TASK:
11967		retval = ctl_abort_task(io);
11968		break;
11969	case CTL_TASK_ABORT_TASK_SET:
11970		retval = ctl_abort_task_set(io);
11971		break;
11972	case CTL_TASK_CLEAR_ACA:
11973		break;
11974	case CTL_TASK_CLEAR_TASK_SET:
11975		break;
11976	case CTL_TASK_I_T_NEXUS_RESET:
11977		retval = ctl_i_t_nexus_reset(io);
11978		break;
11979	case CTL_TASK_LUN_RESET: {
11980		struct ctl_lun *lun;
11981		uint32_t targ_lun;
11982		int retval;
11983
11984		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11985		mtx_lock(&ctl_softc->ctl_lock);
11986		if ((targ_lun < CTL_MAX_LUNS)
11987		 && (ctl_softc->ctl_luns[targ_lun] != NULL))
11988			lun = ctl_softc->ctl_luns[targ_lun];
11989		else {
11990			mtx_unlock(&ctl_softc->ctl_lock);
11991			retval = 1;
11992			break;
11993		}
11994
11995		if (!(io->io_hdr.flags &
11996		    CTL_FLAG_FROM_OTHER_SC)) {
11997			union ctl_ha_msg msg_info;
11998
11999			io->io_hdr.flags |=
12000				CTL_FLAG_SENT_2OTHER_SC;
12001			msg_info.hdr.msg_type =
12002				CTL_MSG_MANAGE_TASKS;
12003			msg_info.hdr.nexus = io->io_hdr.nexus;
12004			msg_info.task.task_action =
12005				CTL_TASK_LUN_RESET;
12006			msg_info.hdr.original_sc = NULL;
12007			msg_info.hdr.serializing_sc = NULL;
12008			if (CTL_HA_STATUS_SUCCESS !=
12009			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12010			    (void *)&msg_info,
12011			    sizeof(msg_info), 0)) {
12012			}
12013		}
12014
12015		retval = ctl_lun_reset(lun, io,
12016				       CTL_UA_LUN_RESET);
12017		mtx_unlock(&ctl_softc->ctl_lock);
12018		break;
12019	}
12020	case CTL_TASK_TARGET_RESET:
12021		retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12022		break;
12023	case CTL_TASK_BUS_RESET:
12024		retval = ctl_bus_reset(ctl_softc, io);
12025		break;
12026	case CTL_TASK_PORT_LOGIN:
12027		break;
12028	case CTL_TASK_PORT_LOGOUT:
12029		break;
12030	default:
12031		printf("ctl_run_task: got unknown task management event %d\n",
12032		       io->taskio.task_action);
12033		break;
12034	}
12035	if (retval == 0)
12036		io->io_hdr.status = CTL_SUCCESS;
12037	else
12038		io->io_hdr.status = CTL_ERROR;
12039
12040	/*
12041	 * This will queue this I/O to the done queue, but the
12042	 * work thread won't be able to process it until we
12043	 * return and the lock is released.
12044	 */
12045	ctl_done(io);
12046}
12047
12048/*
12049 * For HA operation.  Handle commands that come in from the other
12050 * controller.
12051 */
12052static void
12053ctl_handle_isc(union ctl_io *io)
12054{
12055	int free_io;
12056	struct ctl_lun *lun;
12057	struct ctl_softc *ctl_softc;
12058	uint32_t targ_lun;
12059
12060	ctl_softc = control_softc;
12061
12062	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12063	lun = ctl_softc->ctl_luns[targ_lun];
12064
12065	switch (io->io_hdr.msg_type) {
12066	case CTL_MSG_SERIALIZE:
12067		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12068		break;
12069	case CTL_MSG_R2R: {
12070		const struct ctl_cmd_entry *entry;
12071
12072		/*
12073		 * This is only used in SER_ONLY mode.
12074		 */
12075		free_io = 0;
12076		entry = ctl_get_cmd_entry(&io->scsiio);
12077		mtx_lock(&lun->lun_lock);
12078		if (ctl_scsiio_lun_check(ctl_softc, lun,
12079		    entry, (struct ctl_scsiio *)io) != 0) {
12080			mtx_unlock(&lun->lun_lock);
12081			ctl_done(io);
12082			break;
12083		}
12084		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12085		mtx_unlock(&lun->lun_lock);
12086		ctl_enqueue_rtr(io);
12087		break;
12088	}
12089	case CTL_MSG_FINISH_IO:
12090		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12091			free_io = 0;
12092			ctl_done(io);
12093		} else {
12094			free_io = 1;
12095			mtx_lock(&lun->lun_lock);
12096			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12097				     ooa_links);
12098			ctl_check_blocked(lun);
12099			mtx_unlock(&lun->lun_lock);
12100		}
12101		break;
12102	case CTL_MSG_PERS_ACTION:
12103		ctl_hndl_per_res_out_on_other_sc(
12104			(union ctl_ha_msg *)&io->presio.pr_msg);
12105		free_io = 1;
12106		break;
12107	case CTL_MSG_BAD_JUJU:
12108		free_io = 0;
12109		ctl_done(io);
12110		break;
12111	case CTL_MSG_DATAMOVE:
12112		/* Only used in XFER mode */
12113		free_io = 0;
12114		ctl_datamove_remote(io);
12115		break;
12116	case CTL_MSG_DATAMOVE_DONE:
12117		/* Only used in XFER mode */
12118		free_io = 0;
12119		io->scsiio.be_move_done(io);
12120		break;
12121	default:
12122		free_io = 1;
12123		printf("%s: Invalid message type %d\n",
12124		       __func__, io->io_hdr.msg_type);
12125		break;
12126	}
12127	if (free_io)
12128		ctl_free_io(io);
12129
12130}
12131
12132
12133/*
12134 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12135 * there is no match.
12136 */
12137static ctl_lun_error_pattern
12138ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12139{
12140	const struct ctl_cmd_entry *entry;
12141	ctl_lun_error_pattern filtered_pattern, pattern;
12142
12143	pattern = desc->error_pattern;
12144
12145	/*
12146	 * XXX KDM we need more data passed into this function to match a
12147	 * custom pattern, and we actually need to implement custom pattern
12148	 * matching.
12149	 */
12150	if (pattern & CTL_LUN_PAT_CMD)
12151		return (CTL_LUN_PAT_CMD);
12152
12153	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12154		return (CTL_LUN_PAT_ANY);
12155
12156	entry = ctl_get_cmd_entry(ctsio);
12157
12158	filtered_pattern = entry->pattern & pattern;
12159
12160	/*
12161	 * If the user requested specific flags in the pattern (e.g.
12162	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12163	 * flags.
12164	 *
12165	 * If the user did not specify any flags, it doesn't matter whether
12166	 * or not the command supports the flags.
12167	 */
12168	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12169	     (pattern & ~CTL_LUN_PAT_MASK))
12170		return (CTL_LUN_PAT_NONE);
12171
12172	/*
12173	 * If the user asked for a range check, see if the requested LBA
12174	 * range overlaps with this command's LBA range.
12175	 */
12176	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12177		uint64_t lba1;
12178		uint32_t len1;
12179		ctl_action action;
12180		int retval;
12181
12182		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12183		if (retval != 0)
12184			return (CTL_LUN_PAT_NONE);
12185
12186		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12187					      desc->lba_range.len);
12188		/*
12189		 * A "pass" means that the LBA ranges don't overlap, so
12190		 * this doesn't match the user's range criteria.
12191		 */
12192		if (action == CTL_ACTION_PASS)
12193			return (CTL_LUN_PAT_NONE);
12194	}
12195
12196	return (filtered_pattern);
12197}
12198
12199static void
12200ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12201{
12202	struct ctl_error_desc *desc, *desc2;
12203
12204	mtx_assert(&lun->lun_lock, MA_OWNED);
12205
12206	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12207		ctl_lun_error_pattern pattern;
12208		/*
12209		 * Check to see whether this particular command matches
12210		 * the pattern in the descriptor.
12211		 */
12212		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12213		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12214			continue;
12215
12216		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12217		case CTL_LUN_INJ_ABORTED:
12218			ctl_set_aborted(&io->scsiio);
12219			break;
12220		case CTL_LUN_INJ_MEDIUM_ERR:
12221			ctl_set_medium_error(&io->scsiio);
12222			break;
12223		case CTL_LUN_INJ_UA:
12224			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12225			 * OCCURRED */
12226			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12227			break;
12228		case CTL_LUN_INJ_CUSTOM:
12229			/*
12230			 * We're assuming the user knows what he is doing.
12231			 * Just copy the sense information without doing
12232			 * checks.
12233			 */
12234			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12235			      ctl_min(sizeof(desc->custom_sense),
12236				      sizeof(io->scsiio.sense_data)));
12237			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12238			io->scsiio.sense_len = SSD_FULL_SIZE;
12239			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12240			break;
12241		case CTL_LUN_INJ_NONE:
12242		default:
12243			/*
12244			 * If this is an error injection type we don't know
12245			 * about, clear the continuous flag (if it is set)
12246			 * so it will get deleted below.
12247			 */
12248			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12249			break;
12250		}
12251		/*
12252		 * By default, each error injection action is a one-shot
12253		 */
12254		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12255			continue;
12256
12257		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12258
12259		free(desc, M_CTL);
12260	}
12261}
12262
12263#ifdef CTL_IO_DELAY
12264static void
12265ctl_datamove_timer_wakeup(void *arg)
12266{
12267	union ctl_io *io;
12268
12269	io = (union ctl_io *)arg;
12270
12271	ctl_datamove(io);
12272}
12273#endif /* CTL_IO_DELAY */
12274
12275void
12276ctl_datamove(union ctl_io *io)
12277{
12278	void (*fe_datamove)(union ctl_io *io);
12279
12280	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12281
12282	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12283
12284#ifdef CTL_TIME_IO
12285	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12286		char str[256];
12287		char path_str[64];
12288		struct sbuf sb;
12289
12290		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12291		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12292
12293		sbuf_cat(&sb, path_str);
12294		switch (io->io_hdr.io_type) {
12295		case CTL_IO_SCSI:
12296			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12297			sbuf_printf(&sb, "\n");
12298			sbuf_cat(&sb, path_str);
12299			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12300				    io->scsiio.tag_num, io->scsiio.tag_type);
12301			break;
12302		case CTL_IO_TASK:
12303			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12304				    "Tag Type: %d\n", io->taskio.task_action,
12305				    io->taskio.tag_num, io->taskio.tag_type);
12306			break;
12307		default:
12308			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12309			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12310			break;
12311		}
12312		sbuf_cat(&sb, path_str);
12313		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12314			    (intmax_t)time_uptime - io->io_hdr.start_time);
12315		sbuf_finish(&sb);
12316		printf("%s", sbuf_data(&sb));
12317	}
12318#endif /* CTL_TIME_IO */
12319
12320#ifdef CTL_IO_DELAY
12321	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12322		struct ctl_lun *lun;
12323
12324		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12325
12326		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12327	} else {
12328		struct ctl_lun *lun;
12329
12330		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12331		if ((lun != NULL)
12332		 && (lun->delay_info.datamove_delay > 0)) {
12333			struct callout *callout;
12334
12335			callout = (struct callout *)&io->io_hdr.timer_bytes;
12336			callout_init(callout, /*mpsafe*/ 1);
12337			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12338			callout_reset(callout,
12339				      lun->delay_info.datamove_delay * hz,
12340				      ctl_datamove_timer_wakeup, io);
12341			if (lun->delay_info.datamove_type ==
12342			    CTL_DELAY_TYPE_ONESHOT)
12343				lun->delay_info.datamove_delay = 0;
12344			return;
12345		}
12346	}
12347#endif
12348
12349	/*
12350	 * This command has been aborted.  Set the port status, so we fail
12351	 * the data move.
12352	 */
12353	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12354		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12355		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12356		       io->io_hdr.nexus.targ_port,
12357		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12358		       io->io_hdr.nexus.targ_lun);
12359		io->io_hdr.status = CTL_CMD_ABORTED;
12360		io->io_hdr.port_status = 31337;
12361		/*
12362		 * Note that the backend, in this case, will get the
12363		 * callback in its context.  In other cases it may get
12364		 * called in the frontend's interrupt thread context.
12365		 */
12366		io->scsiio.be_move_done(io);
12367		return;
12368	}
12369
12370	/*
12371	 * If we're in XFER mode and this I/O is from the other shelf
12372	 * controller, we need to send the DMA to the other side to
12373	 * actually transfer the data to/from the host.  In serialize only
12374	 * mode the transfer happens below CTL and ctl_datamove() is only
12375	 * called on the machine that originally received the I/O.
12376	 */
12377	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12378	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12379		union ctl_ha_msg msg;
12380		uint32_t sg_entries_sent;
12381		int do_sg_copy;
12382		int i;
12383
12384		memset(&msg, 0, sizeof(msg));
12385		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12386		msg.hdr.original_sc = io->io_hdr.original_sc;
12387		msg.hdr.serializing_sc = io;
12388		msg.hdr.nexus = io->io_hdr.nexus;
12389		msg.dt.flags = io->io_hdr.flags;
12390		/*
12391		 * We convert everything into a S/G list here.  We can't
12392		 * pass by reference, only by value between controllers.
12393		 * So we can't pass a pointer to the S/G list, only as many
12394		 * S/G entries as we can fit in here.  If it's possible for
12395		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12396		 * then we need to break this up into multiple transfers.
12397		 */
12398		if (io->scsiio.kern_sg_entries == 0) {
12399			msg.dt.kern_sg_entries = 1;
12400			/*
12401			 * If this is in cached memory, flush the cache
12402			 * before we send the DMA request to the other
12403			 * controller.  We want to do this in either the
12404			 * read or the write case.  The read case is
12405			 * straightforward.  In the write case, we want to
12406			 * make sure nothing is in the local cache that
12407			 * could overwrite the DMAed data.
12408			 */
12409			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12410				/*
12411				 * XXX KDM use bus_dmamap_sync() here.
12412				 */
12413			}
12414
12415			/*
12416			 * Convert to a physical address if this is a
12417			 * virtual address.
12418			 */
12419			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12420				msg.dt.sg_list[0].addr =
12421					io->scsiio.kern_data_ptr;
12422			} else {
12423				/*
12424				 * XXX KDM use busdma here!
12425				 */
12426#if 0
12427				msg.dt.sg_list[0].addr = (void *)
12428					vtophys(io->scsiio.kern_data_ptr);
12429#endif
12430			}
12431
12432			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12433			do_sg_copy = 0;
12434		} else {
12435			struct ctl_sg_entry *sgl;
12436
12437			do_sg_copy = 1;
12438			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12439			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12440			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12441				/*
12442				 * XXX KDM use bus_dmamap_sync() here.
12443				 */
12444			}
12445		}
12446
12447		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12448		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12449		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12450		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12451		msg.dt.sg_sequence = 0;
12452
12453		/*
12454		 * Loop until we've sent all of the S/G entries.  On the
12455		 * other end, we'll recompose these S/G entries into one
12456		 * contiguous list before passing it to the
12457		 */
12458		for (sg_entries_sent = 0; sg_entries_sent <
12459		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12460			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12461				sizeof(msg.dt.sg_list[0])),
12462				msg.dt.kern_sg_entries - sg_entries_sent);
12463
12464			if (do_sg_copy != 0) {
12465				struct ctl_sg_entry *sgl;
12466				int j;
12467
12468				sgl = (struct ctl_sg_entry *)
12469					io->scsiio.kern_data_ptr;
12470				/*
12471				 * If this is in cached memory, flush the cache
12472				 * before we send the DMA request to the other
12473				 * controller.  We want to do this in either
12474				 * the * read or the write case.  The read
12475				 * case is straightforward.  In the write
12476				 * case, we want to make sure nothing is
12477				 * in the local cache that could overwrite
12478				 * the DMAed data.
12479				 */
12480
12481				for (i = sg_entries_sent, j = 0;
12482				     i < msg.dt.cur_sg_entries; i++, j++) {
12483					if ((io->io_hdr.flags &
12484					     CTL_FLAG_NO_DATASYNC) == 0) {
12485						/*
12486						 * XXX KDM use bus_dmamap_sync()
12487						 */
12488					}
12489					if ((io->io_hdr.flags &
12490					     CTL_FLAG_BUS_ADDR) == 0) {
12491						/*
12492						 * XXX KDM use busdma.
12493						 */
12494#if 0
12495						msg.dt.sg_list[j].addr =(void *)
12496						       vtophys(sgl[i].addr);
12497#endif
12498					} else {
12499						msg.dt.sg_list[j].addr =
12500							sgl[i].addr;
12501					}
12502					msg.dt.sg_list[j].len = sgl[i].len;
12503				}
12504			}
12505
12506			sg_entries_sent += msg.dt.cur_sg_entries;
12507			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12508				msg.dt.sg_last = 1;
12509			else
12510				msg.dt.sg_last = 0;
12511
12512			/*
12513			 * XXX KDM drop and reacquire the lock here?
12514			 */
12515			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12516			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12517				/*
12518				 * XXX do something here.
12519				 */
12520			}
12521
12522			msg.dt.sent_sg_entries = sg_entries_sent;
12523		}
12524		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12525		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12526			ctl_failover_io(io, /*have_lock*/ 0);
12527
12528	} else {
12529
12530		/*
12531		 * Lookup the fe_datamove() function for this particular
12532		 * front end.
12533		 */
12534		fe_datamove =
12535		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12536
12537		fe_datamove(io);
12538	}
12539}
12540
12541static void
12542ctl_send_datamove_done(union ctl_io *io, int have_lock)
12543{
12544	union ctl_ha_msg msg;
12545	int isc_status;
12546
12547	memset(&msg, 0, sizeof(msg));
12548
12549	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12550	msg.hdr.original_sc = io;
12551	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12552	msg.hdr.nexus = io->io_hdr.nexus;
12553	msg.hdr.status = io->io_hdr.status;
12554	msg.scsi.tag_num = io->scsiio.tag_num;
12555	msg.scsi.tag_type = io->scsiio.tag_type;
12556	msg.scsi.scsi_status = io->scsiio.scsi_status;
12557	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12558	       sizeof(io->scsiio.sense_data));
12559	msg.scsi.sense_len = io->scsiio.sense_len;
12560	msg.scsi.sense_residual = io->scsiio.sense_residual;
12561	msg.scsi.fetd_status = io->io_hdr.port_status;
12562	msg.scsi.residual = io->scsiio.residual;
12563	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12564
12565	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12566		ctl_failover_io(io, /*have_lock*/ have_lock);
12567		return;
12568	}
12569
12570	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12571	if (isc_status > CTL_HA_STATUS_SUCCESS) {
12572		/* XXX do something if this fails */
12573	}
12574
12575}
12576
12577/*
12578 * The DMA to the remote side is done, now we need to tell the other side
12579 * we're done so it can continue with its data movement.
12580 */
12581static void
12582ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12583{
12584	union ctl_io *io;
12585
12586	io = rq->context;
12587
12588	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12589		printf("%s: ISC DMA write failed with error %d", __func__,
12590		       rq->ret);
12591		ctl_set_internal_failure(&io->scsiio,
12592					 /*sks_valid*/ 1,
12593					 /*retry_count*/ rq->ret);
12594	}
12595
12596	ctl_dt_req_free(rq);
12597
12598	/*
12599	 * In this case, we had to malloc the memory locally.  Free it.
12600	 */
12601	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12602		int i;
12603		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12604			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12605	}
12606	/*
12607	 * The data is in local and remote memory, so now we need to send
12608	 * status (good or back) back to the other side.
12609	 */
12610	ctl_send_datamove_done(io, /*have_lock*/ 0);
12611}
12612
12613/*
12614 * We've moved the data from the host/controller into local memory.  Now we
12615 * need to push it over to the remote controller's memory.
12616 */
12617static int
12618ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12619{
12620	int retval;
12621
12622	retval = 0;
12623
12624	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12625					  ctl_datamove_remote_write_cb);
12626
12627	return (retval);
12628}
12629
12630static void
12631ctl_datamove_remote_write(union ctl_io *io)
12632{
12633	int retval;
12634	void (*fe_datamove)(union ctl_io *io);
12635
12636	/*
12637	 * - Get the data from the host/HBA into local memory.
12638	 * - DMA memory from the local controller to the remote controller.
12639	 * - Send status back to the remote controller.
12640	 */
12641
12642	retval = ctl_datamove_remote_sgl_setup(io);
12643	if (retval != 0)
12644		return;
12645
12646	/* Switch the pointer over so the FETD knows what to do */
12647	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12648
12649	/*
12650	 * Use a custom move done callback, since we need to send completion
12651	 * back to the other controller, not to the backend on this side.
12652	 */
12653	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12654
12655	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12656
12657	fe_datamove(io);
12658
12659	return;
12660
12661}
12662
12663static int
12664ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12665{
12666#if 0
12667	char str[256];
12668	char path_str[64];
12669	struct sbuf sb;
12670#endif
12671
12672	/*
12673	 * In this case, we had to malloc the memory locally.  Free it.
12674	 */
12675	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12676		int i;
12677		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12678			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12679	}
12680
12681#if 0
12682	scsi_path_string(io, path_str, sizeof(path_str));
12683	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12684	sbuf_cat(&sb, path_str);
12685	scsi_command_string(&io->scsiio, NULL, &sb);
12686	sbuf_printf(&sb, "\n");
12687	sbuf_cat(&sb, path_str);
12688	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12689		    io->scsiio.tag_num, io->scsiio.tag_type);
12690	sbuf_cat(&sb, path_str);
12691	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12692		    io->io_hdr.flags, io->io_hdr.status);
12693	sbuf_finish(&sb);
12694	printk("%s", sbuf_data(&sb));
12695#endif
12696
12697
12698	/*
12699	 * The read is done, now we need to send status (good or bad) back
12700	 * to the other side.
12701	 */
12702	ctl_send_datamove_done(io, /*have_lock*/ 0);
12703
12704	return (0);
12705}
12706
12707static void
12708ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12709{
12710	union ctl_io *io;
12711	void (*fe_datamove)(union ctl_io *io);
12712
12713	io = rq->context;
12714
12715	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12716		printf("%s: ISC DMA read failed with error %d", __func__,
12717		       rq->ret);
12718		ctl_set_internal_failure(&io->scsiio,
12719					 /*sks_valid*/ 1,
12720					 /*retry_count*/ rq->ret);
12721	}
12722
12723	ctl_dt_req_free(rq);
12724
12725	/* Switch the pointer over so the FETD knows what to do */
12726	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12727
12728	/*
12729	 * Use a custom move done callback, since we need to send completion
12730	 * back to the other controller, not to the backend on this side.
12731	 */
12732	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12733
12734	/* XXX KDM add checks like the ones in ctl_datamove? */
12735
12736	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12737
12738	fe_datamove(io);
12739}
12740
12741static int
12742ctl_datamove_remote_sgl_setup(union ctl_io *io)
12743{
12744	struct ctl_sg_entry *local_sglist, *remote_sglist;
12745	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
12746	struct ctl_softc *softc;
12747	int retval;
12748	int i;
12749
12750	retval = 0;
12751	softc = control_softc;
12752
12753	local_sglist = io->io_hdr.local_sglist;
12754	local_dma_sglist = io->io_hdr.local_dma_sglist;
12755	remote_sglist = io->io_hdr.remote_sglist;
12756	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
12757
12758	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
12759		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
12760			local_sglist[i].len = remote_sglist[i].len;
12761
12762			/*
12763			 * XXX Detect the situation where the RS-level I/O
12764			 * redirector on the other side has already read the
12765			 * data off of the AOR RS on this side, and
12766			 * transferred it to remote (mirror) memory on the
12767			 * other side.  Since we already have the data in
12768			 * memory here, we just need to use it.
12769			 *
12770			 * XXX KDM this can probably be removed once we
12771			 * get the cache device code in and take the
12772			 * current AOR implementation out.
12773			 */
12774#ifdef NEEDTOPORT
12775			if ((remote_sglist[i].addr >=
12776			     (void *)vtophys(softc->mirr->addr))
12777			 && (remote_sglist[i].addr <
12778			     ((void *)vtophys(softc->mirr->addr) +
12779			     CacheMirrorOffset))) {
12780				local_sglist[i].addr = remote_sglist[i].addr -
12781					CacheMirrorOffset;
12782				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12783				     CTL_FLAG_DATA_IN)
12784					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
12785			} else {
12786				local_sglist[i].addr = remote_sglist[i].addr +
12787					CacheMirrorOffset;
12788			}
12789#endif
12790#if 0
12791			printf("%s: local %p, remote %p, len %d\n",
12792			       __func__, local_sglist[i].addr,
12793			       remote_sglist[i].addr, local_sglist[i].len);
12794#endif
12795		}
12796	} else {
12797		uint32_t len_to_go;
12798
12799		/*
12800		 * In this case, we don't have automatically allocated
12801		 * memory for this I/O on this controller.  This typically
12802		 * happens with internal CTL I/O -- e.g. inquiry, mode
12803		 * sense, etc.  Anything coming from RAIDCore will have
12804		 * a mirror area available.
12805		 */
12806		len_to_go = io->scsiio.kern_data_len;
12807
12808		/*
12809		 * Clear the no datasync flag, we have to use malloced
12810		 * buffers.
12811		 */
12812		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
12813
12814		/*
12815		 * The difficult thing here is that the size of the various
12816		 * S/G segments may be different than the size from the
12817		 * remote controller.  That'll make it harder when DMAing
12818		 * the data back to the other side.
12819		 */
12820		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
12821		     sizeof(io->io_hdr.remote_sglist[0])) &&
12822		     (len_to_go > 0); i++) {
12823			local_sglist[i].len = ctl_min(len_to_go, 131072);
12824			CTL_SIZE_8B(local_dma_sglist[i].len,
12825				    local_sglist[i].len);
12826			local_sglist[i].addr =
12827				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
12828
12829			local_dma_sglist[i].addr = local_sglist[i].addr;
12830
12831			if (local_sglist[i].addr == NULL) {
12832				int j;
12833
12834				printf("malloc failed for %zd bytes!",
12835				       local_dma_sglist[i].len);
12836				for (j = 0; j < i; j++) {
12837					free(local_sglist[j].addr, M_CTL);
12838				}
12839				ctl_set_internal_failure(&io->scsiio,
12840							 /*sks_valid*/ 1,
12841							 /*retry_count*/ 4857);
12842				retval = 1;
12843				goto bailout_error;
12844
12845			}
12846			/* XXX KDM do we need a sync here? */
12847
12848			len_to_go -= local_sglist[i].len;
12849		}
12850		/*
12851		 * Reset the number of S/G entries accordingly.  The
12852		 * original number of S/G entries is available in
12853		 * rem_sg_entries.
12854		 */
12855		io->scsiio.kern_sg_entries = i;
12856
12857#if 0
12858		printf("%s: kern_sg_entries = %d\n", __func__,
12859		       io->scsiio.kern_sg_entries);
12860		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12861			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
12862			       local_sglist[i].addr, local_sglist[i].len,
12863			       local_dma_sglist[i].len);
12864#endif
12865	}
12866
12867
12868	return (retval);
12869
12870bailout_error:
12871
12872	ctl_send_datamove_done(io, /*have_lock*/ 0);
12873
12874	return (retval);
12875}
12876
12877static int
12878ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12879			 ctl_ha_dt_cb callback)
12880{
12881	struct ctl_ha_dt_req *rq;
12882	struct ctl_sg_entry *remote_sglist, *local_sglist;
12883	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
12884	uint32_t local_used, remote_used, total_used;
12885	int retval;
12886	int i, j;
12887
12888	retval = 0;
12889
12890	rq = ctl_dt_req_alloc();
12891
12892	/*
12893	 * If we failed to allocate the request, and if the DMA didn't fail
12894	 * anyway, set busy status.  This is just a resource allocation
12895	 * failure.
12896	 */
12897	if ((rq == NULL)
12898	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
12899		ctl_set_busy(&io->scsiio);
12900
12901	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
12902
12903		if (rq != NULL)
12904			ctl_dt_req_free(rq);
12905
12906		/*
12907		 * The data move failed.  We need to return status back
12908		 * to the other controller.  No point in trying to DMA
12909		 * data to the remote controller.
12910		 */
12911
12912		ctl_send_datamove_done(io, /*have_lock*/ 0);
12913
12914		retval = 1;
12915
12916		goto bailout;
12917	}
12918
12919	local_sglist = io->io_hdr.local_sglist;
12920	local_dma_sglist = io->io_hdr.local_dma_sglist;
12921	remote_sglist = io->io_hdr.remote_sglist;
12922	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
12923	local_used = 0;
12924	remote_used = 0;
12925	total_used = 0;
12926
12927	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
12928		rq->ret = CTL_HA_STATUS_SUCCESS;
12929		rq->context = io;
12930		callback(rq);
12931		goto bailout;
12932	}
12933
12934	/*
12935	 * Pull/push the data over the wire from/to the other controller.
12936	 * This takes into account the possibility that the local and
12937	 * remote sglists may not be identical in terms of the size of
12938	 * the elements and the number of elements.
12939	 *
12940	 * One fundamental assumption here is that the length allocated for
12941	 * both the local and remote sglists is identical.  Otherwise, we've
12942	 * essentially got a coding error of some sort.
12943	 */
12944	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12945		int isc_ret;
12946		uint32_t cur_len, dma_length;
12947		uint8_t *tmp_ptr;
12948
12949		rq->id = CTL_HA_DATA_CTL;
12950		rq->command = command;
12951		rq->context = io;
12952
12953		/*
12954		 * Both pointers should be aligned.  But it is possible
12955		 * that the allocation length is not.  They should both
12956		 * also have enough slack left over at the end, though,
12957		 * to round up to the next 8 byte boundary.
12958		 */
12959		cur_len = ctl_min(local_sglist[i].len - local_used,
12960				  remote_sglist[j].len - remote_used);
12961
12962		/*
12963		 * In this case, we have a size issue and need to decrease
12964		 * the size, except in the case where we actually have less
12965		 * than 8 bytes left.  In that case, we need to increase
12966		 * the DMA length to get the last bit.
12967		 */
12968		if ((cur_len & 0x7) != 0) {
12969			if (cur_len > 0x7) {
12970				cur_len = cur_len - (cur_len & 0x7);
12971				dma_length = cur_len;
12972			} else {
12973				CTL_SIZE_8B(dma_length, cur_len);
12974			}
12975
12976		} else
12977			dma_length = cur_len;
12978
12979		/*
12980		 * If we had to allocate memory for this I/O, instead of using
12981		 * the non-cached mirror memory, we'll need to flush the cache
12982		 * before trying to DMA to the other controller.
12983		 *
12984		 * We could end up doing this multiple times for the same
12985		 * segment if we have a larger local segment than remote
12986		 * segment.  That shouldn't be an issue.
12987		 */
12988		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12989			/*
12990			 * XXX KDM use bus_dmamap_sync() here.
12991			 */
12992		}
12993
12994		rq->size = dma_length;
12995
12996		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12997		tmp_ptr += local_used;
12998
12999		/* Use physical addresses when talking to ISC hardware */
13000		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13001			/* XXX KDM use busdma */
13002#if 0
13003			rq->local = vtophys(tmp_ptr);
13004#endif
13005		} else
13006			rq->local = tmp_ptr;
13007
13008		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13009		tmp_ptr += remote_used;
13010		rq->remote = tmp_ptr;
13011
13012		rq->callback = NULL;
13013
13014		local_used += cur_len;
13015		if (local_used >= local_sglist[i].len) {
13016			i++;
13017			local_used = 0;
13018		}
13019
13020		remote_used += cur_len;
13021		if (remote_used >= remote_sglist[j].len) {
13022			j++;
13023			remote_used = 0;
13024		}
13025		total_used += cur_len;
13026
13027		if (total_used >= io->scsiio.kern_data_len)
13028			rq->callback = callback;
13029
13030		if ((rq->size & 0x7) != 0) {
13031			printf("%s: warning: size %d is not on 8b boundary\n",
13032			       __func__, rq->size);
13033		}
13034		if (((uintptr_t)rq->local & 0x7) != 0) {
13035			printf("%s: warning: local %p not on 8b boundary\n",
13036			       __func__, rq->local);
13037		}
13038		if (((uintptr_t)rq->remote & 0x7) != 0) {
13039			printf("%s: warning: remote %p not on 8b boundary\n",
13040			       __func__, rq->local);
13041		}
13042#if 0
13043		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13044		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13045		       rq->local, rq->remote, rq->size);
13046#endif
13047
13048		isc_ret = ctl_dt_single(rq);
13049		if (isc_ret == CTL_HA_STATUS_WAIT)
13050			continue;
13051
13052		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13053			rq->ret = CTL_HA_STATUS_SUCCESS;
13054		} else {
13055			rq->ret = isc_ret;
13056		}
13057		callback(rq);
13058		goto bailout;
13059	}
13060
13061bailout:
13062	return (retval);
13063
13064}
13065
13066static void
13067ctl_datamove_remote_read(union ctl_io *io)
13068{
13069	int retval;
13070	int i;
13071
13072	/*
13073	 * This will send an error to the other controller in the case of a
13074	 * failure.
13075	 */
13076	retval = ctl_datamove_remote_sgl_setup(io);
13077	if (retval != 0)
13078		return;
13079
13080	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13081					  ctl_datamove_remote_read_cb);
13082	if ((retval != 0)
13083	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13084		/*
13085		 * Make sure we free memory if there was an error..  The
13086		 * ctl_datamove_remote_xfer() function will send the
13087		 * datamove done message, or call the callback with an
13088		 * error if there is a problem.
13089		 */
13090		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13091			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13092	}
13093
13094	return;
13095}
13096
13097/*
13098 * Process a datamove request from the other controller.  This is used for
13099 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13100 * first.  Once that is complete, the data gets DMAed into the remote
13101 * controller's memory.  For reads, we DMA from the remote controller's
13102 * memory into our memory first, and then move it out to the FETD.
13103 */
13104static void
13105ctl_datamove_remote(union ctl_io *io)
13106{
13107	struct ctl_softc *softc;
13108
13109	softc = control_softc;
13110
13111	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13112
13113	/*
13114	 * Note that we look for an aborted I/O here, but don't do some of
13115	 * the other checks that ctl_datamove() normally does.  We don't
13116	 * need to run the task queue, because this I/O is on the ISC
13117	 * queue, which is executed by the work thread after the task queue.
13118	 * We don't need to run the datamove delay code, since that should
13119	 * have been done if need be on the other controller.
13120	 */
13121	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13122
13123		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13124		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13125		       io->io_hdr.nexus.targ_port,
13126		       io->io_hdr.nexus.targ_target.id,
13127		       io->io_hdr.nexus.targ_lun);
13128		io->io_hdr.status = CTL_CMD_ABORTED;
13129		io->io_hdr.port_status = 31338;
13130
13131		ctl_send_datamove_done(io, /*have_lock*/ 0);
13132
13133		return;
13134	}
13135
13136	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13137		ctl_datamove_remote_write(io);
13138	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13139		ctl_datamove_remote_read(io);
13140	} else {
13141		union ctl_ha_msg msg;
13142		struct scsi_sense_data *sense;
13143		uint8_t sks[3];
13144		int retry_count;
13145
13146		memset(&msg, 0, sizeof(msg));
13147
13148		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13149		msg.hdr.status = CTL_SCSI_ERROR;
13150		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13151
13152		retry_count = 4243;
13153
13154		sense = &msg.scsi.sense_data;
13155		sks[0] = SSD_SCS_VALID;
13156		sks[1] = (retry_count >> 8) & 0xff;
13157		sks[2] = retry_count & 0xff;
13158
13159		/* "Internal target failure" */
13160		scsi_set_sense_data(sense,
13161				    /*sense_format*/ SSD_TYPE_NONE,
13162				    /*current_error*/ 1,
13163				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13164				    /*asc*/ 0x44,
13165				    /*ascq*/ 0x00,
13166				    /*type*/ SSD_ELEM_SKS,
13167				    /*size*/ sizeof(sks),
13168				    /*data*/ sks,
13169				    SSD_ELEM_NONE);
13170
13171		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13172		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13173			ctl_failover_io(io, /*have_lock*/ 1);
13174			return;
13175		}
13176
13177		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13178		    CTL_HA_STATUS_SUCCESS) {
13179			/* XXX KDM what to do if this fails? */
13180		}
13181		return;
13182	}
13183
13184}
13185
13186static int
13187ctl_process_done(union ctl_io *io)
13188{
13189	struct ctl_lun *lun;
13190	struct ctl_softc *ctl_softc;
13191	void (*fe_done)(union ctl_io *io);
13192	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13193
13194	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13195
13196	fe_done =
13197	    control_softc->ctl_ports[targ_port]->fe_done;
13198
13199#ifdef CTL_TIME_IO
13200	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13201		char str[256];
13202		char path_str[64];
13203		struct sbuf sb;
13204
13205		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13206		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13207
13208		sbuf_cat(&sb, path_str);
13209		switch (io->io_hdr.io_type) {
13210		case CTL_IO_SCSI:
13211			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13212			sbuf_printf(&sb, "\n");
13213			sbuf_cat(&sb, path_str);
13214			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13215				    io->scsiio.tag_num, io->scsiio.tag_type);
13216			break;
13217		case CTL_IO_TASK:
13218			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13219				    "Tag Type: %d\n", io->taskio.task_action,
13220				    io->taskio.tag_num, io->taskio.tag_type);
13221			break;
13222		default:
13223			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13224			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13225			break;
13226		}
13227		sbuf_cat(&sb, path_str);
13228		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13229			    (intmax_t)time_uptime - io->io_hdr.start_time);
13230		sbuf_finish(&sb);
13231		printf("%s", sbuf_data(&sb));
13232	}
13233#endif /* CTL_TIME_IO */
13234
13235	switch (io->io_hdr.io_type) {
13236	case CTL_IO_SCSI:
13237		break;
13238	case CTL_IO_TASK:
13239		if (bootverbose || verbose > 0)
13240			ctl_io_error_print(io, NULL);
13241		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13242			ctl_free_io(io);
13243		else
13244			fe_done(io);
13245		return (CTL_RETVAL_COMPLETE);
13246		break;
13247	default:
13248		printf("ctl_process_done: invalid io type %d\n",
13249		       io->io_hdr.io_type);
13250		panic("ctl_process_done: invalid io type %d\n",
13251		      io->io_hdr.io_type);
13252		break; /* NOTREACHED */
13253	}
13254
13255	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13256	if (lun == NULL) {
13257		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13258				 io->io_hdr.nexus.targ_mapped_lun));
13259		fe_done(io);
13260		goto bailout;
13261	}
13262	ctl_softc = lun->ctl_softc;
13263
13264	mtx_lock(&lun->lun_lock);
13265
13266	/*
13267	 * Check to see if we have any errors to inject here.  We only
13268	 * inject errors for commands that don't already have errors set.
13269	 */
13270	if ((STAILQ_FIRST(&lun->error_list) != NULL)
13271	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
13272		ctl_inject_error(lun, io);
13273
13274	/*
13275	 * XXX KDM how do we treat commands that aren't completed
13276	 * successfully?
13277	 *
13278	 * XXX KDM should we also track I/O latency?
13279	 */
13280	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13281	    io->io_hdr.io_type == CTL_IO_SCSI) {
13282#ifdef CTL_TIME_IO
13283		struct bintime cur_bt;
13284#endif
13285		int type;
13286
13287		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13288		    CTL_FLAG_DATA_IN)
13289			type = CTL_STATS_READ;
13290		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13291		    CTL_FLAG_DATA_OUT)
13292			type = CTL_STATS_WRITE;
13293		else
13294			type = CTL_STATS_NO_IO;
13295
13296		lun->stats.ports[targ_port].bytes[type] +=
13297		    io->scsiio.kern_total_len;
13298		lun->stats.ports[targ_port].operations[type]++;
13299#ifdef CTL_TIME_IO
13300		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13301		   &io->io_hdr.dma_bt);
13302		lun->stats.ports[targ_port].num_dmas[type] +=
13303		    io->io_hdr.num_dmas;
13304		getbintime(&cur_bt);
13305		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13306		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13307#endif
13308	}
13309
13310	/*
13311	 * Remove this from the OOA queue.
13312	 */
13313	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13314
13315	/*
13316	 * Run through the blocked queue on this LUN and see if anything
13317	 * has become unblocked, now that this transaction is done.
13318	 */
13319	ctl_check_blocked(lun);
13320
13321	/*
13322	 * If the LUN has been invalidated, free it if there is nothing
13323	 * left on its OOA queue.
13324	 */
13325	if ((lun->flags & CTL_LUN_INVALID)
13326	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13327		mtx_unlock(&lun->lun_lock);
13328		mtx_lock(&ctl_softc->ctl_lock);
13329		ctl_free_lun(lun);
13330		mtx_unlock(&ctl_softc->ctl_lock);
13331	} else
13332		mtx_unlock(&lun->lun_lock);
13333
13334	/*
13335	 * If this command has been aborted, make sure we set the status
13336	 * properly.  The FETD is responsible for freeing the I/O and doing
13337	 * whatever it needs to do to clean up its state.
13338	 */
13339	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13340		io->io_hdr.status = CTL_CMD_ABORTED;
13341
13342	/*
13343	 * We print out status for every task management command.  For SCSI
13344	 * commands, we filter out any unit attention errors; they happen
13345	 * on every boot, and would clutter up the log.  Note:  task
13346	 * management commands aren't printed here, they are printed above,
13347	 * since they should never even make it down here.
13348	 */
13349	switch (io->io_hdr.io_type) {
13350	case CTL_IO_SCSI: {
13351		int error_code, sense_key, asc, ascq;
13352
13353		sense_key = 0;
13354
13355		if (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR)
13356		 && (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13357			/*
13358			 * Since this is just for printing, no need to
13359			 * show errors here.
13360			 */
13361			scsi_extract_sense_len(&io->scsiio.sense_data,
13362					       io->scsiio.sense_len,
13363					       &error_code,
13364					       &sense_key,
13365					       &asc,
13366					       &ascq,
13367					       /*show_errors*/ 0);
13368		}
13369
13370		if (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
13371		 && (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SCSI_ERROR)
13372		  || (io->scsiio.scsi_status != SCSI_STATUS_CHECK_COND)
13373		  || (sense_key != SSD_KEY_UNIT_ATTENTION))) {
13374
13375			if ((time_uptime - ctl_softc->last_print_jiffies) <= 0){
13376				ctl_softc->skipped_prints++;
13377			} else {
13378				uint32_t skipped_prints;
13379
13380				skipped_prints = ctl_softc->skipped_prints;
13381
13382				ctl_softc->skipped_prints = 0;
13383				ctl_softc->last_print_jiffies = time_uptime;
13384
13385				if (skipped_prints > 0) {
13386#ifdef NEEDTOPORT
13387					csevent_log(CSC_CTL | CSC_SHELF_SW |
13388					    CTL_ERROR_REPORT,
13389					    csevent_LogType_Trace,
13390					    csevent_Severity_Information,
13391					    csevent_AlertLevel_Green,
13392					    csevent_FRU_Firmware,
13393					    csevent_FRU_Unknown,
13394					    "High CTL error volume, %d prints "
13395					    "skipped", skipped_prints);
13396#endif
13397				}
13398				if (bootverbose || verbose > 0)
13399					ctl_io_error_print(io, NULL);
13400			}
13401		}
13402		break;
13403	}
13404	case CTL_IO_TASK:
13405		if (bootverbose || verbose > 0)
13406			ctl_io_error_print(io, NULL);
13407		break;
13408	default:
13409		break;
13410	}
13411
13412	/*
13413	 * Tell the FETD or the other shelf controller we're done with this
13414	 * command.  Note that only SCSI commands get to this point.  Task
13415	 * management commands are completed above.
13416	 *
13417	 * We only send status to the other controller if we're in XFER
13418	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13419	 * received the I/O (from CTL's perspective), and so the status is
13420	 * generated there.
13421	 *
13422	 * XXX KDM if we hold the lock here, we could cause a deadlock
13423	 * if the frontend comes back in in this context to queue
13424	 * something.
13425	 */
13426	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13427	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13428		union ctl_ha_msg msg;
13429
13430		memset(&msg, 0, sizeof(msg));
13431		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13432		msg.hdr.original_sc = io->io_hdr.original_sc;
13433		msg.hdr.nexus = io->io_hdr.nexus;
13434		msg.hdr.status = io->io_hdr.status;
13435		msg.scsi.scsi_status = io->scsiio.scsi_status;
13436		msg.scsi.tag_num = io->scsiio.tag_num;
13437		msg.scsi.tag_type = io->scsiio.tag_type;
13438		msg.scsi.sense_len = io->scsiio.sense_len;
13439		msg.scsi.sense_residual = io->scsiio.sense_residual;
13440		msg.scsi.residual = io->scsiio.residual;
13441		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13442		       sizeof(io->scsiio.sense_data));
13443		/*
13444		 * We copy this whether or not this is an I/O-related
13445		 * command.  Otherwise, we'd have to go and check to see
13446		 * whether it's a read/write command, and it really isn't
13447		 * worth it.
13448		 */
13449		memcpy(&msg.scsi.lbalen,
13450		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13451		       sizeof(msg.scsi.lbalen));
13452
13453		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13454				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13455			/* XXX do something here */
13456		}
13457
13458		ctl_free_io(io);
13459	} else
13460		fe_done(io);
13461
13462bailout:
13463
13464	return (CTL_RETVAL_COMPLETE);
13465}
13466
13467/*
13468 * Front end should call this if it doesn't do autosense.  When the request
13469 * sense comes back in from the initiator, we'll dequeue this and send it.
13470 */
13471int
13472ctl_queue_sense(union ctl_io *io)
13473{
13474	struct ctl_lun *lun;
13475	struct ctl_softc *ctl_softc;
13476	uint32_t initidx, targ_lun;
13477
13478	ctl_softc = control_softc;
13479
13480	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13481
13482	/*
13483	 * LUN lookup will likely move to the ctl_work_thread() once we
13484	 * have our new queueing infrastructure (that doesn't put things on
13485	 * a per-LUN queue initially).  That is so that we can handle
13486	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13487	 * can't deal with that right now.
13488	 */
13489	mtx_lock(&ctl_softc->ctl_lock);
13490
13491	/*
13492	 * If we don't have a LUN for this, just toss the sense
13493	 * information.
13494	 */
13495	targ_lun = io->io_hdr.nexus.targ_lun;
13496	targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13497	if ((targ_lun < CTL_MAX_LUNS)
13498	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
13499		lun = ctl_softc->ctl_luns[targ_lun];
13500	else
13501		goto bailout;
13502
13503	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13504
13505	mtx_lock(&lun->lun_lock);
13506	/*
13507	 * Already have CA set for this LUN...toss the sense information.
13508	 */
13509	if (ctl_is_set(lun->have_ca, initidx)) {
13510		mtx_unlock(&lun->lun_lock);
13511		goto bailout;
13512	}
13513
13514	memcpy(&lun->pending_sense[initidx].sense, &io->scsiio.sense_data,
13515	       ctl_min(sizeof(lun->pending_sense[initidx].sense),
13516	       sizeof(io->scsiio.sense_data)));
13517	ctl_set_mask(lun->have_ca, initidx);
13518	mtx_unlock(&lun->lun_lock);
13519
13520bailout:
13521	mtx_unlock(&ctl_softc->ctl_lock);
13522
13523	ctl_free_io(io);
13524
13525	return (CTL_RETVAL_COMPLETE);
13526}
13527
13528/*
13529 * Primary command inlet from frontend ports.  All SCSI and task I/O
13530 * requests must go through this function.
13531 */
13532int
13533ctl_queue(union ctl_io *io)
13534{
13535	struct ctl_softc *ctl_softc;
13536
13537	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13538
13539	ctl_softc = control_softc;
13540
13541#ifdef CTL_TIME_IO
13542	io->io_hdr.start_time = time_uptime;
13543	getbintime(&io->io_hdr.start_bt);
13544#endif /* CTL_TIME_IO */
13545
13546	/* Map FE-specific LUN ID into global one. */
13547	io->io_hdr.nexus.targ_mapped_lun =
13548	    ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13549
13550	switch (io->io_hdr.io_type) {
13551	case CTL_IO_SCSI:
13552	case CTL_IO_TASK:
13553		ctl_enqueue_incoming(io);
13554		break;
13555	default:
13556		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13557		return (EINVAL);
13558	}
13559
13560	return (CTL_RETVAL_COMPLETE);
13561}
13562
13563#ifdef CTL_IO_DELAY
13564static void
13565ctl_done_timer_wakeup(void *arg)
13566{
13567	union ctl_io *io;
13568
13569	io = (union ctl_io *)arg;
13570	ctl_done(io);
13571}
13572#endif /* CTL_IO_DELAY */
13573
13574void
13575ctl_done(union ctl_io *io)
13576{
13577	struct ctl_softc *ctl_softc;
13578
13579	ctl_softc = control_softc;
13580
13581	/*
13582	 * Enable this to catch duplicate completion issues.
13583	 */
13584#if 0
13585	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13586		printf("%s: type %d msg %d cdb %x iptl: "
13587		       "%d:%d:%d:%d tag 0x%04x "
13588		       "flag %#x status %x\n",
13589			__func__,
13590			io->io_hdr.io_type,
13591			io->io_hdr.msg_type,
13592			io->scsiio.cdb[0],
13593			io->io_hdr.nexus.initid.id,
13594			io->io_hdr.nexus.targ_port,
13595			io->io_hdr.nexus.targ_target.id,
13596			io->io_hdr.nexus.targ_lun,
13597			(io->io_hdr.io_type ==
13598			CTL_IO_TASK) ?
13599			io->taskio.tag_num :
13600			io->scsiio.tag_num,
13601		        io->io_hdr.flags,
13602			io->io_hdr.status);
13603	} else
13604		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13605#endif
13606
13607	/*
13608	 * This is an internal copy of an I/O, and should not go through
13609	 * the normal done processing logic.
13610	 */
13611	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13612		return;
13613
13614	/*
13615	 * We need to send a msg to the serializing shelf to finish the IO
13616	 * as well.  We don't send a finish message to the other shelf if
13617	 * this is a task management command.  Task management commands
13618	 * aren't serialized in the OOA queue, but rather just executed on
13619	 * both shelf controllers for commands that originated on that
13620	 * controller.
13621	 */
13622	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13623	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
13624		union ctl_ha_msg msg_io;
13625
13626		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13627		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13628		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13629		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13630		}
13631		/* continue on to finish IO */
13632	}
13633#ifdef CTL_IO_DELAY
13634	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13635		struct ctl_lun *lun;
13636
13637		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13638
13639		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13640	} else {
13641		struct ctl_lun *lun;
13642
13643		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13644
13645		if ((lun != NULL)
13646		 && (lun->delay_info.done_delay > 0)) {
13647			struct callout *callout;
13648
13649			callout = (struct callout *)&io->io_hdr.timer_bytes;
13650			callout_init(callout, /*mpsafe*/ 1);
13651			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13652			callout_reset(callout,
13653				      lun->delay_info.done_delay * hz,
13654				      ctl_done_timer_wakeup, io);
13655			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13656				lun->delay_info.done_delay = 0;
13657			return;
13658		}
13659	}
13660#endif /* CTL_IO_DELAY */
13661
13662	ctl_enqueue_done(io);
13663}
13664
13665int
13666ctl_isc(struct ctl_scsiio *ctsio)
13667{
13668	struct ctl_lun *lun;
13669	int retval;
13670
13671	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13672
13673	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13674
13675	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13676
13677	retval = lun->backend->data_submit((union ctl_io *)ctsio);
13678
13679	return (retval);
13680}
13681
13682
13683static void
13684ctl_work_thread(void *arg)
13685{
13686	struct ctl_thread *thr = (struct ctl_thread *)arg;
13687	struct ctl_softc *softc = thr->ctl_softc;
13688	union ctl_io *io;
13689	int retval;
13690
13691	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13692
13693	for (;;) {
13694		retval = 0;
13695
13696		/*
13697		 * We handle the queues in this order:
13698		 * - ISC
13699		 * - done queue (to free up resources, unblock other commands)
13700		 * - RtR queue
13701		 * - incoming queue
13702		 *
13703		 * If those queues are empty, we break out of the loop and
13704		 * go to sleep.
13705		 */
13706		mtx_lock(&thr->queue_lock);
13707		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13708		if (io != NULL) {
13709			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13710			mtx_unlock(&thr->queue_lock);
13711			ctl_handle_isc(io);
13712			continue;
13713		}
13714		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13715		if (io != NULL) {
13716			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13717			/* clear any blocked commands, call fe_done */
13718			mtx_unlock(&thr->queue_lock);
13719			retval = ctl_process_done(io);
13720			continue;
13721		}
13722		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13723		if (io != NULL) {
13724			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13725			mtx_unlock(&thr->queue_lock);
13726			if (io->io_hdr.io_type == CTL_IO_TASK)
13727				ctl_run_task(io);
13728			else
13729				ctl_scsiio_precheck(softc, &io->scsiio);
13730			continue;
13731		}
13732		if (!ctl_pause_rtr) {
13733			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13734			if (io != NULL) {
13735				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13736				mtx_unlock(&thr->queue_lock);
13737				retval = ctl_scsiio(&io->scsiio);
13738				if (retval != CTL_RETVAL_COMPLETE)
13739					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13740				continue;
13741			}
13742		}
13743
13744		/* Sleep until we have something to do. */
13745		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13746	}
13747}
13748
13749static void
13750ctl_lun_thread(void *arg)
13751{
13752	struct ctl_softc *softc = (struct ctl_softc *)arg;
13753	struct ctl_be_lun *be_lun;
13754	int retval;
13755
13756	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13757
13758	for (;;) {
13759		retval = 0;
13760		mtx_lock(&softc->ctl_lock);
13761		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13762		if (be_lun != NULL) {
13763			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13764			mtx_unlock(&softc->ctl_lock);
13765			ctl_create_lun(be_lun);
13766			continue;
13767		}
13768
13769		/* Sleep until we have something to do. */
13770		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13771		    PDROP | PRIBIO, "-", 0);
13772	}
13773}
13774
13775static void
13776ctl_enqueue_incoming(union ctl_io *io)
13777{
13778	struct ctl_softc *softc = control_softc;
13779	struct ctl_thread *thr;
13780	u_int idx;
13781
13782	idx = (io->io_hdr.nexus.targ_port * 127 +
13783	       io->io_hdr.nexus.initid.id) % worker_threads;
13784	thr = &softc->threads[idx];
13785	mtx_lock(&thr->queue_lock);
13786	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13787	mtx_unlock(&thr->queue_lock);
13788	wakeup(thr);
13789}
13790
13791static void
13792ctl_enqueue_rtr(union ctl_io *io)
13793{
13794	struct ctl_softc *softc = control_softc;
13795	struct ctl_thread *thr;
13796
13797	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13798	mtx_lock(&thr->queue_lock);
13799	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13800	mtx_unlock(&thr->queue_lock);
13801	wakeup(thr);
13802}
13803
13804static void
13805ctl_enqueue_done(union ctl_io *io)
13806{
13807	struct ctl_softc *softc = control_softc;
13808	struct ctl_thread *thr;
13809
13810	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13811	mtx_lock(&thr->queue_lock);
13812	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13813	mtx_unlock(&thr->queue_lock);
13814	wakeup(thr);
13815}
13816
13817static void
13818ctl_enqueue_isc(union ctl_io *io)
13819{
13820	struct ctl_softc *softc = control_softc;
13821	struct ctl_thread *thr;
13822
13823	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13824	mtx_lock(&thr->queue_lock);
13825	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13826	mtx_unlock(&thr->queue_lock);
13827	wakeup(thr);
13828}
13829
13830/* Initialization and failover */
13831
13832void
13833ctl_init_isc_msg(void)
13834{
13835	printf("CTL: Still calling this thing\n");
13836}
13837
13838/*
13839 * Init component
13840 * 	Initializes component into configuration defined by bootMode
13841 *	(see hasc-sv.c)
13842 *  	returns hasc_Status:
13843 * 		OK
13844 *		ERROR - fatal error
13845 */
13846static ctl_ha_comp_status
13847ctl_isc_init(struct ctl_ha_component *c)
13848{
13849	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
13850
13851	c->status = ret;
13852	return ret;
13853}
13854
13855/* Start component
13856 * 	Starts component in state requested. If component starts successfully,
13857 *	it must set its own state to the requestrd state
13858 *	When requested state is HASC_STATE_HA, the component may refine it
13859 * 	by adding _SLAVE or _MASTER flags.
13860 *	Currently allowed state transitions are:
13861 *	UNKNOWN->HA		- initial startup
13862 *	UNKNOWN->SINGLE - initial startup when no parter detected
13863 *	HA->SINGLE		- failover
13864 * returns ctl_ha_comp_status:
13865 * 		OK	- component successfully started in requested state
13866 *		FAILED  - could not start the requested state, failover may
13867 * 			  be possible
13868 *		ERROR	- fatal error detected, no future startup possible
13869 */
13870static ctl_ha_comp_status
13871ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
13872{
13873	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
13874
13875	printf("%s: go\n", __func__);
13876
13877	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
13878	if (c->state == CTL_HA_STATE_UNKNOWN ) {
13879		ctl_is_single = 0;
13880		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
13881		    != CTL_HA_STATUS_SUCCESS) {
13882			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
13883			ret = CTL_HA_COMP_STATUS_ERROR;
13884		}
13885	} else if (CTL_HA_STATE_IS_HA(c->state)
13886		&& CTL_HA_STATE_IS_SINGLE(state)){
13887		// HA->SINGLE transition
13888	        ctl_failover();
13889		ctl_is_single = 1;
13890	} else {
13891		printf("ctl_isc_start:Invalid state transition %X->%X\n",
13892		       c->state, state);
13893		ret = CTL_HA_COMP_STATUS_ERROR;
13894	}
13895	if (CTL_HA_STATE_IS_SINGLE(state))
13896		ctl_is_single = 1;
13897
13898	c->state = state;
13899	c->status = ret;
13900	return ret;
13901}
13902
13903/*
13904 * Quiesce component
13905 * The component must clear any error conditions (set status to OK) and
13906 * prepare itself to another Start call
13907 * returns ctl_ha_comp_status:
13908 * 	OK
13909 *	ERROR
13910 */
13911static ctl_ha_comp_status
13912ctl_isc_quiesce(struct ctl_ha_component *c)
13913{
13914	int ret = CTL_HA_COMP_STATUS_OK;
13915
13916	ctl_pause_rtr = 1;
13917	c->status = ret;
13918	return ret;
13919}
13920
13921struct ctl_ha_component ctl_ha_component_ctlisc =
13922{
13923	.name = "CTL ISC",
13924	.state = CTL_HA_STATE_UNKNOWN,
13925	.init = ctl_isc_init,
13926	.start = ctl_isc_start,
13927	.quiesce = ctl_isc_quiesce
13928};
13929
13930/*
13931 *  vim: ts=8
13932 */
13933