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