ctl.c revision 288731
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$
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 288731 2015-10-05 08:55:59Z mav $");
46
47#include <sys/param.h>
48#include <sys/systm.h>
49#include <sys/ctype.h>
50#include <sys/kernel.h>
51#include <sys/types.h>
52#include <sys/kthread.h>
53#include <sys/bio.h>
54#include <sys/fcntl.h>
55#include <sys/lock.h>
56#include <sys/module.h>
57#include <sys/mutex.h>
58#include <sys/condvar.h>
59#include <sys/malloc.h>
60#include <sys/conf.h>
61#include <sys/ioccom.h>
62#include <sys/queue.h>
63#include <sys/sbuf.h>
64#include <sys/smp.h>
65#include <sys/endian.h>
66#include <sys/sysctl.h>
67#include <vm/uma.h>
68
69#include <cam/cam.h>
70#include <cam/scsi/scsi_all.h>
71#include <cam/scsi/scsi_da.h>
72#include <cam/ctl/ctl_io.h>
73#include <cam/ctl/ctl.h>
74#include <cam/ctl/ctl_frontend.h>
75#include <cam/ctl/ctl_util.h>
76#include <cam/ctl/ctl_backend.h>
77#include <cam/ctl/ctl_ioctl.h>
78#include <cam/ctl/ctl_ha.h>
79#include <cam/ctl/ctl_private.h>
80#include <cam/ctl/ctl_debug.h>
81#include <cam/ctl/ctl_scsi_all.h>
82#include <cam/ctl/ctl_error.h>
83
84struct ctl_softc *control_softc = NULL;
85
86/*
87 * Size and alignment macros needed for Copan-specific HA hardware.  These
88 * can go away when the HA code is re-written, and uses busdma for any
89 * hardware.
90 */
91#define	CTL_ALIGN_8B(target, source, type)				\
92	if (((uint32_t)source & 0x7) != 0)				\
93		target = (type)(source + (0x8 - ((uint32_t)source & 0x7)));\
94	else								\
95		target = (type)source;
96
97#define	CTL_SIZE_8B(target, size)					\
98	if ((size & 0x7) != 0)						\
99		target = size + (0x8 - (size & 0x7));			\
100	else								\
101		target = size;
102
103#define CTL_ALIGN_8B_MARGIN	16
104
105/*
106 * Template mode pages.
107 */
108
109/*
110 * Note that these are default values only.  The actual values will be
111 * filled in when the user does a mode sense.
112 */
113const static struct copan_debugconf_subpage debugconf_page_default = {
114	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
115	DBGCNF_SUBPAGE_CODE,		/* subpage */
116	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
117	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
118	DBGCNF_VERSION,			/* page_version */
119	{CTL_TIME_IO_DEFAULT_SECS>>8,
120	 CTL_TIME_IO_DEFAULT_SECS>>0},	/* ctl_time_io_secs */
121};
122
123const static struct copan_debugconf_subpage debugconf_page_changeable = {
124	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
125	DBGCNF_SUBPAGE_CODE,		/* subpage */
126	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
127	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
128	0,				/* page_version */
129	{0xff,0xff},			/* ctl_time_io_secs */
130};
131
132const static struct scsi_da_rw_recovery_page rw_er_page_default = {
133	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
134	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
135	/*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
136	/*read_retry_count*/0,
137	/*correction_span*/0,
138	/*head_offset_count*/0,
139	/*data_strobe_offset_cnt*/0,
140	/*byte8*/SMS_RWER_LBPERE,
141	/*write_retry_count*/0,
142	/*reserved2*/0,
143	/*recovery_time_limit*/{0, 0},
144};
145
146const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
147	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
148	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
149	/*byte3*/0,
150	/*read_retry_count*/0,
151	/*correction_span*/0,
152	/*head_offset_count*/0,
153	/*data_strobe_offset_cnt*/0,
154	/*byte8*/0,
155	/*write_retry_count*/0,
156	/*reserved2*/0,
157	/*recovery_time_limit*/{0, 0},
158};
159
160const static struct scsi_format_page format_page_default = {
161	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
162	/*page_length*/sizeof(struct scsi_format_page) - 2,
163	/*tracks_per_zone*/ {0, 0},
164	/*alt_sectors_per_zone*/ {0, 0},
165	/*alt_tracks_per_zone*/ {0, 0},
166	/*alt_tracks_per_lun*/ {0, 0},
167	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
168			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
169	/*bytes_per_sector*/ {0, 0},
170	/*interleave*/ {0, 0},
171	/*track_skew*/ {0, 0},
172	/*cylinder_skew*/ {0, 0},
173	/*flags*/ SFP_HSEC,
174	/*reserved*/ {0, 0, 0}
175};
176
177const static struct scsi_format_page format_page_changeable = {
178	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
179	/*page_length*/sizeof(struct scsi_format_page) - 2,
180	/*tracks_per_zone*/ {0, 0},
181	/*alt_sectors_per_zone*/ {0, 0},
182	/*alt_tracks_per_zone*/ {0, 0},
183	/*alt_tracks_per_lun*/ {0, 0},
184	/*sectors_per_track*/ {0, 0},
185	/*bytes_per_sector*/ {0, 0},
186	/*interleave*/ {0, 0},
187	/*track_skew*/ {0, 0},
188	/*cylinder_skew*/ {0, 0},
189	/*flags*/ 0,
190	/*reserved*/ {0, 0, 0}
191};
192
193const static struct scsi_rigid_disk_page rigid_disk_page_default = {
194	/*page_code*/SMS_RIGID_DISK_PAGE,
195	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
196	/*cylinders*/ {0, 0, 0},
197	/*heads*/ CTL_DEFAULT_HEADS,
198	/*start_write_precomp*/ {0, 0, 0},
199	/*start_reduced_current*/ {0, 0, 0},
200	/*step_rate*/ {0, 0},
201	/*landing_zone_cylinder*/ {0, 0, 0},
202	/*rpl*/ SRDP_RPL_DISABLED,
203	/*rotational_offset*/ 0,
204	/*reserved1*/ 0,
205	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
206			   CTL_DEFAULT_ROTATION_RATE & 0xff},
207	/*reserved2*/ {0, 0}
208};
209
210const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
211	/*page_code*/SMS_RIGID_DISK_PAGE,
212	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
213	/*cylinders*/ {0, 0, 0},
214	/*heads*/ 0,
215	/*start_write_precomp*/ {0, 0, 0},
216	/*start_reduced_current*/ {0, 0, 0},
217	/*step_rate*/ {0, 0},
218	/*landing_zone_cylinder*/ {0, 0, 0},
219	/*rpl*/ 0,
220	/*rotational_offset*/ 0,
221	/*reserved1*/ 0,
222	/*rotation_rate*/ {0, 0},
223	/*reserved2*/ {0, 0}
224};
225
226const static struct scsi_caching_page caching_page_default = {
227	/*page_code*/SMS_CACHING_PAGE,
228	/*page_length*/sizeof(struct scsi_caching_page) - 2,
229	/*flags1*/ SCP_DISC | SCP_WCE,
230	/*ret_priority*/ 0,
231	/*disable_pf_transfer_len*/ {0xff, 0xff},
232	/*min_prefetch*/ {0, 0},
233	/*max_prefetch*/ {0xff, 0xff},
234	/*max_pf_ceiling*/ {0xff, 0xff},
235	/*flags2*/ 0,
236	/*cache_segments*/ 0,
237	/*cache_seg_size*/ {0, 0},
238	/*reserved*/ 0,
239	/*non_cache_seg_size*/ {0, 0, 0}
240};
241
242const static struct scsi_caching_page caching_page_changeable = {
243	/*page_code*/SMS_CACHING_PAGE,
244	/*page_length*/sizeof(struct scsi_caching_page) - 2,
245	/*flags1*/ SCP_WCE | SCP_RCD,
246	/*ret_priority*/ 0,
247	/*disable_pf_transfer_len*/ {0, 0},
248	/*min_prefetch*/ {0, 0},
249	/*max_prefetch*/ {0, 0},
250	/*max_pf_ceiling*/ {0, 0},
251	/*flags2*/ 0,
252	/*cache_segments*/ 0,
253	/*cache_seg_size*/ {0, 0},
254	/*reserved*/ 0,
255	/*non_cache_seg_size*/ {0, 0, 0}
256};
257
258const static struct scsi_control_page control_page_default = {
259	/*page_code*/SMS_CONTROL_MODE_PAGE,
260	/*page_length*/sizeof(struct scsi_control_page) - 2,
261	/*rlec*/0,
262	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
263	/*eca_and_aen*/0,
264	/*flags4*/SCP_TAS,
265	/*aen_holdoff_period*/{0, 0},
266	/*busy_timeout_period*/{0, 0},
267	/*extended_selftest_completion_time*/{0, 0}
268};
269
270const static struct scsi_control_page control_page_changeable = {
271	/*page_code*/SMS_CONTROL_MODE_PAGE,
272	/*page_length*/sizeof(struct scsi_control_page) - 2,
273	/*rlec*/SCP_DSENSE,
274	/*queue_flags*/SCP_QUEUE_ALG_MASK,
275	/*eca_and_aen*/SCP_SWP,
276	/*flags4*/0,
277	/*aen_holdoff_period*/{0, 0},
278	/*busy_timeout_period*/{0, 0},
279	/*extended_selftest_completion_time*/{0, 0}
280};
281
282const static struct scsi_info_exceptions_page ie_page_default = {
283	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
284	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
285	/*info_flags*/SIEP_FLAGS_DEXCPT,
286	/*mrie*/0,
287	/*interval_timer*/{0, 0, 0, 0},
288	/*report_count*/{0, 0, 0, 0}
289};
290
291const static struct scsi_info_exceptions_page ie_page_changeable = {
292	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
293	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
294	/*info_flags*/0,
295	/*mrie*/0,
296	/*interval_timer*/{0, 0, 0, 0},
297	/*report_count*/{0, 0, 0, 0}
298};
299
300#define CTL_LBPM_LEN	(sizeof(struct ctl_logical_block_provisioning_page) - 4)
301
302const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
303	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
304	/*subpage_code*/0x02,
305	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
306	/*flags*/0,
307	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
308	/*descr*/{}},
309	{{/*flags*/0,
310	  /*resource*/0x01,
311	  /*reserved*/{0, 0},
312	  /*count*/{0, 0, 0, 0}},
313	 {/*flags*/0,
314	  /*resource*/0x02,
315	  /*reserved*/{0, 0},
316	  /*count*/{0, 0, 0, 0}},
317	 {/*flags*/0,
318	  /*resource*/0xf1,
319	  /*reserved*/{0, 0},
320	  /*count*/{0, 0, 0, 0}},
321	 {/*flags*/0,
322	  /*resource*/0xf2,
323	  /*reserved*/{0, 0},
324	  /*count*/{0, 0, 0, 0}}
325	}
326};
327
328const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
329	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
330	/*subpage_code*/0x02,
331	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
332	/*flags*/0,
333	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
334	/*descr*/{}},
335	{{/*flags*/0,
336	  /*resource*/0,
337	  /*reserved*/{0, 0},
338	  /*count*/{0, 0, 0, 0}},
339	 {/*flags*/0,
340	  /*resource*/0,
341	  /*reserved*/{0, 0},
342	  /*count*/{0, 0, 0, 0}},
343	 {/*flags*/0,
344	  /*resource*/0,
345	  /*reserved*/{0, 0},
346	  /*count*/{0, 0, 0, 0}},
347	 {/*flags*/0,
348	  /*resource*/0,
349	  /*reserved*/{0, 0},
350	  /*count*/{0, 0, 0, 0}}
351	}
352};
353
354/*
355 * XXX KDM move these into the softc.
356 */
357static int rcv_sync_msg;
358static uint8_t ctl_pause_rtr;
359
360SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
361static int worker_threads = -1;
362TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
363SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
364    &worker_threads, 1, "Number of worker threads");
365static int ctl_debug = CTL_DEBUG_NONE;
366TUNABLE_INT("kern.cam.ctl.debug", &ctl_debug);
367SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
368    &ctl_debug, 0, "Enabled debug flags");
369
370/*
371 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
372 * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
373 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
374 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
375 */
376#define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
377
378#ifdef notyet
379static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
380				  int param);
381static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
382#endif
383static int ctl_init(void);
384void ctl_shutdown(void);
385static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
386static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
387static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
388static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
389			      struct ctl_ooa *ooa_hdr,
390			      struct ctl_ooa_entry *kern_entries);
391static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
392		     struct thread *td);
393static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
394			 struct ctl_be_lun *be_lun);
395static int ctl_free_lun(struct ctl_lun *lun);
396static void ctl_create_lun(struct ctl_be_lun *be_lun);
397static struct ctl_port * ctl_io_port(struct ctl_io_hdr *io_hdr);
398/**
399static void ctl_failover_change_pages(struct ctl_softc *softc,
400				      struct ctl_scsiio *ctsio, int master);
401**/
402
403static int ctl_do_mode_select(union ctl_io *io);
404static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
405			   uint64_t res_key, uint64_t sa_res_key,
406			   uint8_t type, uint32_t residx,
407			   struct ctl_scsiio *ctsio,
408			   struct scsi_per_res_out *cdb,
409			   struct scsi_per_res_out_parms* param);
410static void ctl_pro_preempt_other(struct ctl_lun *lun,
411				  union ctl_ha_msg *msg);
412static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
413static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
414static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
415static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
416static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
417static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
418static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
419					 int alloc_len);
420static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
421					 int alloc_len);
422static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
423static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
424static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
425static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
426static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
427static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
428    bool seq);
429static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
430static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
431    union ctl_io *pending_io, union ctl_io *ooa_io);
432static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
433				union ctl_io *starting_io);
434static int ctl_check_blocked(struct ctl_lun *lun);
435static int ctl_scsiio_lun_check(struct ctl_lun *lun,
436				const struct ctl_cmd_entry *entry,
437				struct ctl_scsiio *ctsio);
438//static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
439#ifdef notyet
440static void ctl_failover(void);
441#endif
442static void ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
443			 ctl_ua_type ua_type);
444static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
445			       struct ctl_scsiio *ctsio);
446static int ctl_scsiio(struct ctl_scsiio *ctsio);
447
448static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
449static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
450			    ctl_ua_type ua_type);
451static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
452			 ctl_ua_type ua_type);
453static int ctl_abort_task(union ctl_io *io);
454static int ctl_abort_task_set(union ctl_io *io);
455static int ctl_i_t_nexus_reset(union ctl_io *io);
456static void ctl_run_task(union ctl_io *io);
457#ifdef CTL_IO_DELAY
458static void ctl_datamove_timer_wakeup(void *arg);
459static void ctl_done_timer_wakeup(void *arg);
460#endif /* CTL_IO_DELAY */
461
462static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
463static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
464static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
465static void ctl_datamove_remote_write(union ctl_io *io);
466static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
467static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
468static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
469static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
470				    ctl_ha_dt_cb callback);
471static void ctl_datamove_remote_read(union ctl_io *io);
472static void ctl_datamove_remote(union ctl_io *io);
473static int ctl_process_done(union ctl_io *io);
474static void ctl_lun_thread(void *arg);
475static void ctl_thresh_thread(void *arg);
476static void ctl_work_thread(void *arg);
477static void ctl_enqueue_incoming(union ctl_io *io);
478static void ctl_enqueue_rtr(union ctl_io *io);
479static void ctl_enqueue_done(union ctl_io *io);
480#ifdef notyet
481static void ctl_enqueue_isc(union ctl_io *io);
482#endif
483static const struct ctl_cmd_entry *
484    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
485static const struct ctl_cmd_entry *
486    ctl_validate_command(struct ctl_scsiio *ctsio);
487static int ctl_cmd_applicable(uint8_t lun_type,
488    const struct ctl_cmd_entry *entry);
489
490/*
491 * Load the serialization table.  This isn't very pretty, but is probably
492 * the easiest way to do it.
493 */
494#include "ctl_ser_table.c"
495
496/*
497 * We only need to define open, close and ioctl routines for this driver.
498 */
499static struct cdevsw ctl_cdevsw = {
500	.d_version =	D_VERSION,
501	.d_flags =	0,
502	.d_open =	ctl_open,
503	.d_close =	ctl_close,
504	.d_ioctl =	ctl_ioctl,
505	.d_name =	"ctl",
506};
507
508
509MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
510
511static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
512
513static moduledata_t ctl_moduledata = {
514	"ctl",
515	ctl_module_event_handler,
516	NULL
517};
518
519DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
520MODULE_VERSION(ctl, 1);
521
522#ifdef notyet
523static void
524ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
525			    union ctl_ha_msg *msg_info)
526{
527	struct ctl_scsiio *ctsio;
528
529	if (msg_info->hdr.original_sc == NULL) {
530		printf("%s: original_sc == NULL!\n", __func__);
531		/* XXX KDM now what? */
532		return;
533	}
534
535	ctsio = &msg_info->hdr.original_sc->scsiio;
536	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
537	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
538	ctsio->io_hdr.status = msg_info->hdr.status;
539	ctsio->scsi_status = msg_info->scsi.scsi_status;
540	ctsio->sense_len = msg_info->scsi.sense_len;
541	ctsio->sense_residual = msg_info->scsi.sense_residual;
542	ctsio->residual = msg_info->scsi.residual;
543	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
544	       sizeof(ctsio->sense_data));
545	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
546	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
547	ctl_enqueue_isc((union ctl_io *)ctsio);
548}
549
550static void
551ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
552				union ctl_ha_msg *msg_info)
553{
554	struct ctl_scsiio *ctsio;
555
556	if (msg_info->hdr.serializing_sc == NULL) {
557		printf("%s: serializing_sc == NULL!\n", __func__);
558		/* XXX KDM now what? */
559		return;
560	}
561
562	ctsio = &msg_info->hdr.serializing_sc->scsiio;
563#if 0
564	/*
565	 * Attempt to catch the situation where an I/O has
566	 * been freed, and we're using it again.
567	 */
568	if (ctsio->io_hdr.io_type == 0xff) {
569		union ctl_io *tmp_io;
570		tmp_io = (union ctl_io *)ctsio;
571		printf("%s: %p use after free!\n", __func__,
572		       ctsio);
573		printf("%s: type %d msg %d cdb %x iptl: "
574		       "%u:%u:%u tag 0x%04x "
575		       "flag %#x status %x\n",
576			__func__,
577			tmp_io->io_hdr.io_type,
578			tmp_io->io_hdr.msg_type,
579			tmp_io->scsiio.cdb[0],
580			tmp_io->io_hdr.nexus.initid,
581			tmp_io->io_hdr.nexus.targ_port,
582			tmp_io->io_hdr.nexus.targ_lun,
583			(tmp_io->io_hdr.io_type ==
584			CTL_IO_TASK) ?
585			tmp_io->taskio.tag_num :
586			tmp_io->scsiio.tag_num,
587		        tmp_io->io_hdr.flags,
588			tmp_io->io_hdr.status);
589	}
590#endif
591	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
592	ctl_enqueue_isc((union ctl_io *)ctsio);
593}
594
595/*
596 * ISC (Inter Shelf Communication) event handler.  Events from the HA
597 * subsystem come in here.
598 */
599static void
600ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
601{
602	struct ctl_softc *softc;
603	union ctl_io *io;
604	struct ctl_prio *presio;
605	ctl_ha_status isc_status;
606
607	softc = control_softc;
608	io = NULL;
609
610
611#if 0
612	printf("CTL: Isc Msg event %d\n", event);
613#endif
614	if (event == CTL_HA_EVT_MSG_RECV) {
615		union ctl_ha_msg msg_info;
616
617		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
618					     sizeof(msg_info), /*wait*/ 0);
619#if 0
620		printf("CTL: msg_type %d\n", msg_info.msg_type);
621#endif
622		if (isc_status != 0) {
623			printf("Error receiving message, status = %d\n",
624			       isc_status);
625			return;
626		}
627
628		switch (msg_info.hdr.msg_type) {
629		case CTL_MSG_SERIALIZE:
630#if 0
631			printf("Serialize\n");
632#endif
633			io = ctl_alloc_io_nowait(softc->othersc_pool);
634			if (io == NULL) {
635				printf("ctl_isc_event_handler: can't allocate "
636				       "ctl_io!\n");
637				/* Bad Juju */
638				/* Need to set busy and send msg back */
639				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
640				msg_info.hdr.status = CTL_SCSI_ERROR;
641				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
642				msg_info.scsi.sense_len = 0;
643			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
644				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
645				}
646				goto bailout;
647			}
648			ctl_zero_io(io);
649			// populate ctsio from msg_info
650			io->io_hdr.io_type = CTL_IO_SCSI;
651			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
652			io->io_hdr.original_sc = msg_info.hdr.original_sc;
653#if 0
654			printf("pOrig %x\n", (int)msg_info.original_sc);
655#endif
656			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
657					    CTL_FLAG_IO_ACTIVE;
658			/*
659			 * If we're in serialization-only mode, we don't
660			 * want to go through full done processing.  Thus
661			 * the COPY flag.
662			 *
663			 * XXX KDM add another flag that is more specific.
664			 */
665			if (softc->ha_mode == CTL_HA_MODE_SER_ONLY)
666				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
667			io->io_hdr.nexus = msg_info.hdr.nexus;
668#if 0
669			printf("port %u, iid %u, lun %u\n",
670			       io->io_hdr.nexus.targ_port,
671			       io->io_hdr.nexus.initid,
672			       io->io_hdr.nexus.targ_lun);
673#endif
674			io->scsiio.tag_num = msg_info.scsi.tag_num;
675			io->scsiio.tag_type = msg_info.scsi.tag_type;
676			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
677			       CTL_MAX_CDBLEN);
678			if (softc->ha_mode == CTL_HA_MODE_XFER) {
679				const struct ctl_cmd_entry *entry;
680
681				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
682				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
683				io->io_hdr.flags |=
684					entry->flags & CTL_FLAG_DATA_MASK;
685			}
686			ctl_enqueue_isc(io);
687			break;
688
689		/* Performed on the Originating SC, XFER mode only */
690		case CTL_MSG_DATAMOVE: {
691			struct ctl_sg_entry *sgl;
692			int i, j;
693
694			io = msg_info.hdr.original_sc;
695			if (io == NULL) {
696				printf("%s: original_sc == NULL!\n", __func__);
697				/* XXX KDM do something here */
698				break;
699			}
700			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
701			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
702			/*
703			 * Keep track of this, we need to send it back over
704			 * when the datamove is complete.
705			 */
706			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
707
708			if (msg_info.dt.sg_sequence == 0) {
709				/*
710				 * XXX KDM we use the preallocated S/G list
711				 * here, but we'll need to change this to
712				 * dynamic allocation if we need larger S/G
713				 * lists.
714				 */
715				if (msg_info.dt.kern_sg_entries >
716				    sizeof(io->io_hdr.remote_sglist) /
717				    sizeof(io->io_hdr.remote_sglist[0])) {
718					printf("%s: number of S/G entries "
719					    "needed %u > allocated num %zd\n",
720					    __func__,
721					    msg_info.dt.kern_sg_entries,
722					    sizeof(io->io_hdr.remote_sglist)/
723					    sizeof(io->io_hdr.remote_sglist[0]));
724
725					/*
726					 * XXX KDM send a message back to
727					 * the other side to shut down the
728					 * DMA.  The error will come back
729					 * through via the normal channel.
730					 */
731					break;
732				}
733				sgl = io->io_hdr.remote_sglist;
734				memset(sgl, 0,
735				       sizeof(io->io_hdr.remote_sglist));
736
737				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
738
739				io->scsiio.kern_sg_entries =
740					msg_info.dt.kern_sg_entries;
741				io->scsiio.rem_sg_entries =
742					msg_info.dt.kern_sg_entries;
743				io->scsiio.kern_data_len =
744					msg_info.dt.kern_data_len;
745				io->scsiio.kern_total_len =
746					msg_info.dt.kern_total_len;
747				io->scsiio.kern_data_resid =
748					msg_info.dt.kern_data_resid;
749				io->scsiio.kern_rel_offset =
750					msg_info.dt.kern_rel_offset;
751				/*
752				 * Clear out per-DMA flags.
753				 */
754				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
755				/*
756				 * Add per-DMA flags that are set for this
757				 * particular DMA request.
758				 */
759				io->io_hdr.flags |= msg_info.dt.flags &
760						    CTL_FLAG_RDMA_MASK;
761			} else
762				sgl = (struct ctl_sg_entry *)
763					io->scsiio.kern_data_ptr;
764
765			for (i = msg_info.dt.sent_sg_entries, j = 0;
766			     i < (msg_info.dt.sent_sg_entries +
767			     msg_info.dt.cur_sg_entries); i++, j++) {
768				sgl[i].addr = msg_info.dt.sg_list[j].addr;
769				sgl[i].len = msg_info.dt.sg_list[j].len;
770
771#if 0
772				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
773				       __func__,
774				       msg_info.dt.sg_list[j].addr,
775				       msg_info.dt.sg_list[j].len,
776				       sgl[i].addr, sgl[i].len, j, i);
777#endif
778			}
779#if 0
780			memcpy(&sgl[msg_info.dt.sent_sg_entries],
781			       msg_info.dt.sg_list,
782			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
783#endif
784
785			/*
786			 * If this is the last piece of the I/O, we've got
787			 * the full S/G list.  Queue processing in the thread.
788			 * Otherwise wait for the next piece.
789			 */
790			if (msg_info.dt.sg_last != 0)
791				ctl_enqueue_isc(io);
792			break;
793		}
794		/* Performed on the Serializing (primary) SC, XFER mode only */
795		case CTL_MSG_DATAMOVE_DONE: {
796			if (msg_info.hdr.serializing_sc == NULL) {
797				printf("%s: serializing_sc == NULL!\n",
798				       __func__);
799				/* XXX KDM now what? */
800				break;
801			}
802			/*
803			 * We grab the sense information here in case
804			 * there was a failure, so we can return status
805			 * back to the initiator.
806			 */
807			io = msg_info.hdr.serializing_sc;
808			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
809			io->io_hdr.status = msg_info.hdr.status;
810			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
811			io->scsiio.sense_len = msg_info.scsi.sense_len;
812			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
813			io->io_hdr.port_status = msg_info.scsi.fetd_status;
814			io->scsiio.residual = msg_info.scsi.residual;
815			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
816			       sizeof(io->scsiio.sense_data));
817			ctl_enqueue_isc(io);
818			break;
819		}
820
821		/* Preformed on Originating SC, SER_ONLY mode */
822		case CTL_MSG_R2R:
823			io = msg_info.hdr.original_sc;
824			if (io == NULL) {
825				printf("%s: Major Bummer\n", __func__);
826				return;
827			} else {
828#if 0
829				printf("pOrig %x\n",(int) ctsio);
830#endif
831			}
832			io->io_hdr.msg_type = CTL_MSG_R2R;
833			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
834			ctl_enqueue_isc(io);
835			break;
836
837		/*
838		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
839		 * mode.
840		 * Performed on the Originating (i.e. secondary) SC in XFER
841		 * mode
842		 */
843		case CTL_MSG_FINISH_IO:
844			if (softc->ha_mode == CTL_HA_MODE_XFER)
845				ctl_isc_handler_finish_xfer(softc,
846							    &msg_info);
847			else
848				ctl_isc_handler_finish_ser_only(softc,
849								&msg_info);
850			break;
851
852		/* Preformed on Originating SC */
853		case CTL_MSG_BAD_JUJU:
854			io = msg_info.hdr.original_sc;
855			if (io == NULL) {
856				printf("%s: Bad JUJU!, original_sc is NULL!\n",
857				       __func__);
858				break;
859			}
860			ctl_copy_sense_data(&msg_info, io);
861			/*
862			 * IO should have already been cleaned up on other
863			 * SC so clear this flag so we won't send a message
864			 * back to finish the IO there.
865			 */
866			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
867			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
868
869			/* io = msg_info.hdr.serializing_sc; */
870			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
871			ctl_enqueue_isc(io);
872			break;
873
874		/* Handle resets sent from the other side */
875		case CTL_MSG_MANAGE_TASKS: {
876			struct ctl_taskio *taskio;
877			taskio = (struct ctl_taskio *)ctl_alloc_io_nowait(
878			    softc->othersc_pool);
879			if (taskio == NULL) {
880				printf("ctl_isc_event_handler: can't allocate "
881				       "ctl_io!\n");
882				/* Bad Juju */
883				/* should I just call the proper reset func
884				   here??? */
885				goto bailout;
886			}
887			ctl_zero_io((union ctl_io *)taskio);
888			taskio->io_hdr.io_type = CTL_IO_TASK;
889			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
890			taskio->io_hdr.nexus = msg_info.hdr.nexus;
891			taskio->task_action = msg_info.task.task_action;
892			taskio->tag_num = msg_info.task.tag_num;
893			taskio->tag_type = msg_info.task.tag_type;
894#ifdef CTL_TIME_IO
895			taskio->io_hdr.start_time = time_uptime;
896			getbintime(&taskio->io_hdr.start_bt);
897#if 0
898			cs_prof_gettime(&taskio->io_hdr.start_ticks);
899#endif
900#endif /* CTL_TIME_IO */
901			ctl_run_task((union ctl_io *)taskio);
902			break;
903		}
904		/* Persistent Reserve action which needs attention */
905		case CTL_MSG_PERS_ACTION:
906			presio = (struct ctl_prio *)ctl_alloc_io_nowait(
907			    softc->othersc_pool);
908			if (presio == NULL) {
909				printf("ctl_isc_event_handler: can't allocate "
910				       "ctl_io!\n");
911				/* Bad Juju */
912				/* Need to set busy and send msg back */
913				goto bailout;
914			}
915			ctl_zero_io((union ctl_io *)presio);
916			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
917			presio->pr_msg = msg_info.pr;
918			ctl_enqueue_isc((union ctl_io *)presio);
919			break;
920		case CTL_MSG_SYNC_FE:
921			rcv_sync_msg = 1;
922			break;
923		default:
924		        printf("How did I get here?\n");
925		}
926	} else if (event == CTL_HA_EVT_MSG_SENT) {
927		if (param != CTL_HA_STATUS_SUCCESS) {
928			printf("Bad status from ctl_ha_msg_send status %d\n",
929			       param);
930		}
931		return;
932	} else if (event == CTL_HA_EVT_DISCONNECT) {
933		printf("CTL: Got a disconnect from Isc\n");
934		return;
935	} else {
936		printf("ctl_isc_event_handler: Unknown event %d\n", event);
937		return;
938	}
939
940bailout:
941	return;
942}
943
944static void
945ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
946{
947	struct scsi_sense_data *sense;
948
949	sense = &dest->scsiio.sense_data;
950	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
951	dest->scsiio.scsi_status = src->scsi.scsi_status;
952	dest->scsiio.sense_len = src->scsi.sense_len;
953	dest->io_hdr.status = src->hdr.status;
954}
955#endif
956
957static void
958ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
959{
960	ctl_ua_type *pu;
961
962	mtx_assert(&lun->lun_lock, MA_OWNED);
963	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
964	if (pu == NULL)
965		return;
966	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
967}
968
969static void
970ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
971{
972	int i, j;
973
974	mtx_assert(&lun->lun_lock, MA_OWNED);
975	for (i = 0; i < CTL_MAX_PORTS; i++) {
976		if (lun->pending_ua[i] == NULL)
977			continue;
978		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
979			if (i * CTL_MAX_INIT_PER_PORT + j == except)
980				continue;
981			lun->pending_ua[i][j] |= ua;
982		}
983	}
984}
985
986static void
987ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
988{
989	ctl_ua_type *pu;
990
991	mtx_assert(&lun->lun_lock, MA_OWNED);
992	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
993	if (pu == NULL)
994		return;
995	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
996}
997
998static void
999ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1000{
1001	int i, j;
1002
1003	mtx_assert(&lun->lun_lock, MA_OWNED);
1004	for (i = 0; i < CTL_MAX_PORTS; i++) {
1005		if (lun->pending_ua[i] == NULL)
1006			continue;
1007		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1008			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1009				continue;
1010			lun->pending_ua[i][j] &= ~ua;
1011		}
1012	}
1013}
1014
1015static void
1016ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1017    ctl_ua_type ua_type)
1018{
1019	struct ctl_lun *lun;
1020
1021	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1022	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1023		mtx_lock(&lun->lun_lock);
1024		ctl_clr_ua(lun, initidx, ua_type);
1025		mtx_unlock(&lun->lun_lock);
1026	}
1027}
1028
1029static int
1030ctl_ha_state_sysctl(SYSCTL_HANDLER_ARGS)
1031{
1032	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1033	struct ctl_lun *lun;
1034	int error, value;
1035
1036	if (softc->flags & CTL_FLAG_ACTIVE_SHELF)
1037		value = 0;
1038	else
1039		value = 1;
1040
1041	error = sysctl_handle_int(oidp, &value, 0, req);
1042	if ((error != 0) || (req->newptr == NULL))
1043		return (error);
1044
1045	mtx_lock(&softc->ctl_lock);
1046	if (value == 0)
1047		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1048	else
1049		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1050	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1051		mtx_lock(&lun->lun_lock);
1052		ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1053		mtx_unlock(&lun->lun_lock);
1054	}
1055	mtx_unlock(&softc->ctl_lock);
1056	return (0);
1057}
1058
1059static int
1060ctl_init(void)
1061{
1062	struct ctl_softc *softc;
1063	void *other_pool;
1064	int i, error, retval;
1065	//int isc_retval;
1066
1067	retval = 0;
1068	ctl_pause_rtr = 0;
1069        rcv_sync_msg = 0;
1070
1071	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1072			       M_WAITOK | M_ZERO);
1073	softc = control_softc;
1074
1075	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1076			      "cam/ctl");
1077
1078	softc->dev->si_drv1 = softc;
1079
1080	/*
1081	 * By default, return a "bad LUN" peripheral qualifier for unknown
1082	 * LUNs.  The user can override this default using the tunable or
1083	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
1084	 */
1085	softc->inquiry_pq_no_lun = 1;
1086	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
1087			  &softc->inquiry_pq_no_lun);
1088	sysctl_ctx_init(&softc->sysctl_ctx);
1089	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1090		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1091		CTLFLAG_RD, 0, "CAM Target Layer");
1092
1093	if (softc->sysctl_tree == NULL) {
1094		printf("%s: unable to allocate sysctl tree\n", __func__);
1095		destroy_dev(softc->dev);
1096		free(control_softc, M_DEVBUF);
1097		control_softc = NULL;
1098		return (ENOMEM);
1099	}
1100
1101	SYSCTL_ADD_INT(&softc->sysctl_ctx,
1102		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1103		       "inquiry_pq_no_lun", CTLFLAG_RW,
1104		       &softc->inquiry_pq_no_lun, 0,
1105		       "Report no lun possible for invalid LUNs");
1106
1107	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1108	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1109	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1110	softc->open_count = 0;
1111
1112	/*
1113	 * Default to actually sending a SYNCHRONIZE CACHE command down to
1114	 * the drive.
1115	 */
1116	softc->flags = CTL_FLAG_REAL_SYNC;
1117
1118	/*
1119	 * In Copan's HA scheme, the "master" and "slave" roles are
1120	 * figured out through the slot the controller is in.  Although it
1121	 * is an active/active system, someone has to be in charge.
1122	 */
1123	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1124	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1125	    "HA head ID (0 - no HA)");
1126	if (softc->ha_id == 0) {
1127		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1128		softc->is_single = 1;
1129		softc->port_offset = 0;
1130	} else
1131		softc->port_offset = (softc->ha_id - 1) * CTL_MAX_PORTS;
1132	softc->persis_offset = softc->port_offset * CTL_MAX_INIT_PER_PORT;
1133
1134	STAILQ_INIT(&softc->lun_list);
1135	STAILQ_INIT(&softc->pending_lun_queue);
1136	STAILQ_INIT(&softc->fe_list);
1137	STAILQ_INIT(&softc->port_list);
1138	STAILQ_INIT(&softc->be_list);
1139	ctl_tpc_init(softc);
1140
1141	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1142	                    &other_pool) != 0)
1143	{
1144		printf("ctl: can't allocate %d entry other SC pool, "
1145		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1146		return (ENOMEM);
1147	}
1148	softc->othersc_pool = other_pool;
1149
1150	if (worker_threads <= 0)
1151		worker_threads = max(1, mp_ncpus / 4);
1152	if (worker_threads > CTL_MAX_THREADS)
1153		worker_threads = CTL_MAX_THREADS;
1154
1155	for (i = 0; i < worker_threads; i++) {
1156		struct ctl_thread *thr = &softc->threads[i];
1157
1158		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1159		thr->ctl_softc = softc;
1160		STAILQ_INIT(&thr->incoming_queue);
1161		STAILQ_INIT(&thr->rtr_queue);
1162		STAILQ_INIT(&thr->done_queue);
1163		STAILQ_INIT(&thr->isc_queue);
1164
1165		error = kproc_kthread_add(ctl_work_thread, thr,
1166		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1167		if (error != 0) {
1168			printf("error creating CTL work thread!\n");
1169			ctl_pool_free(other_pool);
1170			return (error);
1171		}
1172	}
1173	error = kproc_kthread_add(ctl_lun_thread, softc,
1174	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1175	if (error != 0) {
1176		printf("error creating CTL lun thread!\n");
1177		ctl_pool_free(other_pool);
1178		return (error);
1179	}
1180	error = kproc_kthread_add(ctl_thresh_thread, softc,
1181	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1182	if (error != 0) {
1183		printf("error creating CTL threshold thread!\n");
1184		ctl_pool_free(other_pool);
1185		return (error);
1186	}
1187
1188	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1189	    OID_AUTO, "ha_state", CTLTYPE_INT | CTLFLAG_RWTUN,
1190	    softc, 0, ctl_ha_state_sysctl, "I", "HA state for this head");
1191	return (0);
1192}
1193
1194void
1195ctl_shutdown(void)
1196{
1197	struct ctl_softc *softc;
1198	struct ctl_lun *lun, *next_lun;
1199
1200	softc = (struct ctl_softc *)control_softc;
1201
1202	mtx_lock(&softc->ctl_lock);
1203
1204	/*
1205	 * Free up each LUN.
1206	 */
1207	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1208		next_lun = STAILQ_NEXT(lun, links);
1209		ctl_free_lun(lun);
1210	}
1211
1212	mtx_unlock(&softc->ctl_lock);
1213
1214#if 0
1215	ctl_shutdown_thread(softc->work_thread);
1216	mtx_destroy(&softc->queue_lock);
1217#endif
1218
1219	ctl_tpc_shutdown(softc);
1220	uma_zdestroy(softc->io_zone);
1221	mtx_destroy(&softc->ctl_lock);
1222
1223	destroy_dev(softc->dev);
1224
1225	sysctl_ctx_free(&softc->sysctl_ctx);
1226
1227	free(control_softc, M_DEVBUF);
1228	control_softc = NULL;
1229}
1230
1231static int
1232ctl_module_event_handler(module_t mod, int what, void *arg)
1233{
1234
1235	switch (what) {
1236	case MOD_LOAD:
1237		return (ctl_init());
1238	case MOD_UNLOAD:
1239		return (EBUSY);
1240	default:
1241		return (EOPNOTSUPP);
1242	}
1243}
1244
1245/*
1246 * XXX KDM should we do some access checks here?  Bump a reference count to
1247 * prevent a CTL module from being unloaded while someone has it open?
1248 */
1249static int
1250ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1251{
1252	return (0);
1253}
1254
1255static int
1256ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1257{
1258	return (0);
1259}
1260
1261int
1262ctl_port_enable(ctl_port_type port_type)
1263{
1264	struct ctl_softc *softc = control_softc;
1265	struct ctl_port *port;
1266
1267	if (softc->is_single == 0) {
1268		union ctl_ha_msg msg_info;
1269		int isc_retval;
1270
1271#if 0
1272		printf("%s: HA mode, synchronizing frontend enable\n",
1273		        __func__);
1274#endif
1275		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1276	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1277		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1278			printf("Sync msg send error retval %d\n", isc_retval);
1279		}
1280		if (!rcv_sync_msg) {
1281			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1282			        sizeof(msg_info), 1);
1283		}
1284#if 0
1285        	printf("CTL:Frontend Enable\n");
1286	} else {
1287		printf("%s: single mode, skipping frontend synchronization\n",
1288		        __func__);
1289#endif
1290	}
1291
1292	STAILQ_FOREACH(port, &softc->port_list, links) {
1293		if (port_type & port->port_type)
1294		{
1295#if 0
1296			printf("port %d\n", port->targ_port);
1297#endif
1298			ctl_port_online(port);
1299		}
1300	}
1301
1302	return (0);
1303}
1304
1305int
1306ctl_port_disable(ctl_port_type port_type)
1307{
1308	struct ctl_softc *softc;
1309	struct ctl_port *port;
1310
1311	softc = control_softc;
1312
1313	STAILQ_FOREACH(port, &softc->port_list, links) {
1314		if (port_type & port->port_type)
1315			ctl_port_offline(port);
1316	}
1317
1318	return (0);
1319}
1320
1321/*
1322 * Returns 0 for success, 1 for failure.
1323 * Currently the only failure mode is if there aren't enough entries
1324 * allocated.  So, in case of a failure, look at num_entries_dropped,
1325 * reallocate and try again.
1326 */
1327int
1328ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1329	      int *num_entries_filled, int *num_entries_dropped,
1330	      ctl_port_type port_type, int no_virtual)
1331{
1332	struct ctl_softc *softc;
1333	struct ctl_port *port;
1334	int entries_dropped, entries_filled;
1335	int retval;
1336	int i;
1337
1338	softc = control_softc;
1339
1340	retval = 0;
1341	entries_filled = 0;
1342	entries_dropped = 0;
1343
1344	i = 0;
1345	mtx_lock(&softc->ctl_lock);
1346	STAILQ_FOREACH(port, &softc->port_list, links) {
1347		struct ctl_port_entry *entry;
1348
1349		if ((port->port_type & port_type) == 0)
1350			continue;
1351
1352		if ((no_virtual != 0)
1353		 && (port->virtual_port != 0))
1354			continue;
1355
1356		if (entries_filled >= num_entries_alloced) {
1357			entries_dropped++;
1358			continue;
1359		}
1360		entry = &entries[i];
1361
1362		entry->port_type = port->port_type;
1363		strlcpy(entry->port_name, port->port_name,
1364			sizeof(entry->port_name));
1365		entry->physical_port = port->physical_port;
1366		entry->virtual_port = port->virtual_port;
1367		entry->wwnn = port->wwnn;
1368		entry->wwpn = port->wwpn;
1369
1370		i++;
1371		entries_filled++;
1372	}
1373
1374	mtx_unlock(&softc->ctl_lock);
1375
1376	if (entries_dropped > 0)
1377		retval = 1;
1378
1379	*num_entries_dropped = entries_dropped;
1380	*num_entries_filled = entries_filled;
1381
1382	return (retval);
1383}
1384
1385/*
1386 * Remove an initiator by port number and initiator ID.
1387 * Returns 0 for success, -1 for failure.
1388 */
1389int
1390ctl_remove_initiator(struct ctl_port *port, int iid)
1391{
1392	struct ctl_softc *softc = control_softc;
1393
1394	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1395
1396	if (iid > CTL_MAX_INIT_PER_PORT) {
1397		printf("%s: initiator ID %u > maximun %u!\n",
1398		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1399		return (-1);
1400	}
1401
1402	mtx_lock(&softc->ctl_lock);
1403	port->wwpn_iid[iid].in_use--;
1404	port->wwpn_iid[iid].last_use = time_uptime;
1405	mtx_unlock(&softc->ctl_lock);
1406
1407	return (0);
1408}
1409
1410/*
1411 * Add an initiator to the initiator map.
1412 * Returns iid for success, < 0 for failure.
1413 */
1414int
1415ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1416{
1417	struct ctl_softc *softc = control_softc;
1418	time_t best_time;
1419	int i, best;
1420
1421	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1422
1423	if (iid >= CTL_MAX_INIT_PER_PORT) {
1424		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1425		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1426		free(name, M_CTL);
1427		return (-1);
1428	}
1429
1430	mtx_lock(&softc->ctl_lock);
1431
1432	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1433		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1434			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1435				iid = i;
1436				break;
1437			}
1438			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1439			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1440				iid = i;
1441				break;
1442			}
1443		}
1444	}
1445
1446	if (iid < 0) {
1447		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1448			if (port->wwpn_iid[i].in_use == 0 &&
1449			    port->wwpn_iid[i].wwpn == 0 &&
1450			    port->wwpn_iid[i].name == NULL) {
1451				iid = i;
1452				break;
1453			}
1454		}
1455	}
1456
1457	if (iid < 0) {
1458		best = -1;
1459		best_time = INT32_MAX;
1460		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1461			if (port->wwpn_iid[i].in_use == 0) {
1462				if (port->wwpn_iid[i].last_use < best_time) {
1463					best = i;
1464					best_time = port->wwpn_iid[i].last_use;
1465				}
1466			}
1467		}
1468		iid = best;
1469	}
1470
1471	if (iid < 0) {
1472		mtx_unlock(&softc->ctl_lock);
1473		free(name, M_CTL);
1474		return (-2);
1475	}
1476
1477	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1478		/*
1479		 * This is not an error yet.
1480		 */
1481		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1482#if 0
1483			printf("%s: port %d iid %u WWPN %#jx arrived"
1484			    " again\n", __func__, port->targ_port,
1485			    iid, (uintmax_t)wwpn);
1486#endif
1487			goto take;
1488		}
1489		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1490		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1491#if 0
1492			printf("%s: port %d iid %u name '%s' arrived"
1493			    " again\n", __func__, port->targ_port,
1494			    iid, name);
1495#endif
1496			goto take;
1497		}
1498
1499		/*
1500		 * This is an error, but what do we do about it?  The
1501		 * driver is telling us we have a new WWPN for this
1502		 * initiator ID, so we pretty much need to use it.
1503		 */
1504		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1505		    " but WWPN %#jx '%s' is still at that address\n",
1506		    __func__, port->targ_port, iid, wwpn, name,
1507		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1508		    port->wwpn_iid[iid].name);
1509
1510		/*
1511		 * XXX KDM clear have_ca and ua_pending on each LUN for
1512		 * this initiator.
1513		 */
1514	}
1515take:
1516	free(port->wwpn_iid[iid].name, M_CTL);
1517	port->wwpn_iid[iid].name = name;
1518	port->wwpn_iid[iid].wwpn = wwpn;
1519	port->wwpn_iid[iid].in_use++;
1520	mtx_unlock(&softc->ctl_lock);
1521
1522	return (iid);
1523}
1524
1525static int
1526ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1527{
1528	int len;
1529
1530	switch (port->port_type) {
1531	case CTL_PORT_FC:
1532	{
1533		struct scsi_transportid_fcp *id =
1534		    (struct scsi_transportid_fcp *)buf;
1535		if (port->wwpn_iid[iid].wwpn == 0)
1536			return (0);
1537		memset(id, 0, sizeof(*id));
1538		id->format_protocol = SCSI_PROTO_FC;
1539		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1540		return (sizeof(*id));
1541	}
1542	case CTL_PORT_ISCSI:
1543	{
1544		struct scsi_transportid_iscsi_port *id =
1545		    (struct scsi_transportid_iscsi_port *)buf;
1546		if (port->wwpn_iid[iid].name == NULL)
1547			return (0);
1548		memset(id, 0, 256);
1549		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1550		    SCSI_PROTO_ISCSI;
1551		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1552		len = roundup2(min(len, 252), 4);
1553		scsi_ulto2b(len, id->additional_length);
1554		return (sizeof(*id) + len);
1555	}
1556	case CTL_PORT_SAS:
1557	{
1558		struct scsi_transportid_sas *id =
1559		    (struct scsi_transportid_sas *)buf;
1560		if (port->wwpn_iid[iid].wwpn == 0)
1561			return (0);
1562		memset(id, 0, sizeof(*id));
1563		id->format_protocol = SCSI_PROTO_SAS;
1564		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1565		return (sizeof(*id));
1566	}
1567	default:
1568	{
1569		struct scsi_transportid_spi *id =
1570		    (struct scsi_transportid_spi *)buf;
1571		memset(id, 0, sizeof(*id));
1572		id->format_protocol = SCSI_PROTO_SPI;
1573		scsi_ulto2b(iid, id->scsi_addr);
1574		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1575		return (sizeof(*id));
1576	}
1577	}
1578}
1579
1580/*
1581 * Serialize a command that went down the "wrong" side, and so was sent to
1582 * this controller for execution.  The logic is a little different than the
1583 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1584 * sent back to the other side, but in the success case, we execute the
1585 * command on this side (XFER mode) or tell the other side to execute it
1586 * (SER_ONLY mode).
1587 */
1588static int
1589ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1590{
1591	struct ctl_softc *softc;
1592	union ctl_ha_msg msg_info;
1593	struct ctl_lun *lun;
1594	int retval = 0;
1595	uint32_t targ_lun;
1596
1597	softc = control_softc;
1598
1599	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1600	lun = softc->ctl_luns[targ_lun];
1601	if (lun==NULL)
1602	{
1603		/*
1604		 * Why isn't LUN defined? The other side wouldn't
1605		 * send a cmd if the LUN is undefined.
1606		 */
1607		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1608
1609		/* "Logical unit not supported" */
1610		ctl_set_sense_data(&msg_info.scsi.sense_data,
1611				   lun,
1612				   /*sense_format*/SSD_TYPE_NONE,
1613				   /*current_error*/ 1,
1614				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1615				   /*asc*/ 0x25,
1616				   /*ascq*/ 0x00,
1617				   SSD_ELEM_NONE);
1618
1619		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1620		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1621		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1622		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1623		msg_info.hdr.serializing_sc = NULL;
1624		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1625	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1626				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1627		}
1628		return(1);
1629
1630	}
1631
1632	mtx_lock(&lun->lun_lock);
1633    	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1634
1635	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1636		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1637		 ooa_links))) {
1638	case CTL_ACTION_BLOCK:
1639		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1640		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1641				  blocked_links);
1642		break;
1643	case CTL_ACTION_PASS:
1644	case CTL_ACTION_SKIP:
1645		if (softc->ha_mode == CTL_HA_MODE_XFER) {
1646			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1647			ctl_enqueue_rtr((union ctl_io *)ctsio);
1648		} else {
1649
1650			/* send msg back to other side */
1651			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1652			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1653			msg_info.hdr.msg_type = CTL_MSG_R2R;
1654#if 0
1655			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1656#endif
1657		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1658			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1659			}
1660		}
1661		break;
1662	case CTL_ACTION_OVERLAP:
1663		/* OVERLAPPED COMMANDS ATTEMPTED */
1664		ctl_set_sense_data(&msg_info.scsi.sense_data,
1665				   lun,
1666				   /*sense_format*/SSD_TYPE_NONE,
1667				   /*current_error*/ 1,
1668				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1669				   /*asc*/ 0x4E,
1670				   /*ascq*/ 0x00,
1671				   SSD_ELEM_NONE);
1672
1673		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1674		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1675		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1676		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1677		msg_info.hdr.serializing_sc = NULL;
1678		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1679#if 0
1680		printf("BAD JUJU:Major Bummer Overlap\n");
1681#endif
1682		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1683		retval = 1;
1684		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1685		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1686		}
1687		break;
1688	case CTL_ACTION_OVERLAP_TAG:
1689		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1690		ctl_set_sense_data(&msg_info.scsi.sense_data,
1691				   lun,
1692				   /*sense_format*/SSD_TYPE_NONE,
1693				   /*current_error*/ 1,
1694				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1695				   /*asc*/ 0x4D,
1696				   /*ascq*/ ctsio->tag_num & 0xff,
1697				   SSD_ELEM_NONE);
1698
1699		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1700		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1701		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1702		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1703		msg_info.hdr.serializing_sc = NULL;
1704		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1705#if 0
1706		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1707#endif
1708		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1709		retval = 1;
1710		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1711		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1712		}
1713		break;
1714	case CTL_ACTION_ERROR:
1715	default:
1716		/* "Internal target failure" */
1717		ctl_set_sense_data(&msg_info.scsi.sense_data,
1718				   lun,
1719				   /*sense_format*/SSD_TYPE_NONE,
1720				   /*current_error*/ 1,
1721				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1722				   /*asc*/ 0x44,
1723				   /*ascq*/ 0x00,
1724				   SSD_ELEM_NONE);
1725
1726		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1727		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1728		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1729		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1730		msg_info.hdr.serializing_sc = NULL;
1731		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1732#if 0
1733		printf("BAD JUJU:Major Bummer HW Error\n");
1734#endif
1735		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1736		retval = 1;
1737		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1738		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1739		}
1740		break;
1741	}
1742	mtx_unlock(&lun->lun_lock);
1743	return (retval);
1744}
1745
1746/*
1747 * Returns 0 for success, errno for failure.
1748 */
1749static int
1750ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
1751		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
1752{
1753	union ctl_io *io;
1754	int retval;
1755
1756	retval = 0;
1757
1758	mtx_lock(&lun->lun_lock);
1759	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
1760	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
1761	     ooa_links)) {
1762		struct ctl_ooa_entry *entry;
1763
1764		/*
1765		 * If we've got more than we can fit, just count the
1766		 * remaining entries.
1767		 */
1768		if (*cur_fill_num >= ooa_hdr->alloc_num)
1769			continue;
1770
1771		entry = &kern_entries[*cur_fill_num];
1772
1773		entry->tag_num = io->scsiio.tag_num;
1774		entry->lun_num = lun->lun;
1775#ifdef CTL_TIME_IO
1776		entry->start_bt = io->io_hdr.start_bt;
1777#endif
1778		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
1779		entry->cdb_len = io->scsiio.cdb_len;
1780		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
1781			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
1782
1783		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
1784			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
1785
1786		if (io->io_hdr.flags & CTL_FLAG_ABORT)
1787			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
1788
1789		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
1790			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
1791
1792		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
1793			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
1794	}
1795	mtx_unlock(&lun->lun_lock);
1796
1797	return (retval);
1798}
1799
1800static void *
1801ctl_copyin_alloc(void *user_addr, int len, char *error_str,
1802		 size_t error_str_len)
1803{
1804	void *kptr;
1805
1806	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
1807
1808	if (copyin(user_addr, kptr, len) != 0) {
1809		snprintf(error_str, error_str_len, "Error copying %d bytes "
1810			 "from user address %p to kernel address %p", len,
1811			 user_addr, kptr);
1812		free(kptr, M_CTL);
1813		return (NULL);
1814	}
1815
1816	return (kptr);
1817}
1818
1819static void
1820ctl_free_args(int num_args, struct ctl_be_arg *args)
1821{
1822	int i;
1823
1824	if (args == NULL)
1825		return;
1826
1827	for (i = 0; i < num_args; i++) {
1828		free(args[i].kname, M_CTL);
1829		free(args[i].kvalue, M_CTL);
1830	}
1831
1832	free(args, M_CTL);
1833}
1834
1835static struct ctl_be_arg *
1836ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
1837		char *error_str, size_t error_str_len)
1838{
1839	struct ctl_be_arg *args;
1840	int i;
1841
1842	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
1843				error_str, error_str_len);
1844
1845	if (args == NULL)
1846		goto bailout;
1847
1848	for (i = 0; i < num_args; i++) {
1849		args[i].kname = NULL;
1850		args[i].kvalue = NULL;
1851	}
1852
1853	for (i = 0; i < num_args; i++) {
1854		uint8_t *tmpptr;
1855
1856		args[i].kname = ctl_copyin_alloc(args[i].name,
1857			args[i].namelen, error_str, error_str_len);
1858		if (args[i].kname == NULL)
1859			goto bailout;
1860
1861		if (args[i].kname[args[i].namelen - 1] != '\0') {
1862			snprintf(error_str, error_str_len, "Argument %d "
1863				 "name is not NUL-terminated", i);
1864			goto bailout;
1865		}
1866
1867		if (args[i].flags & CTL_BEARG_RD) {
1868			tmpptr = ctl_copyin_alloc(args[i].value,
1869				args[i].vallen, error_str, error_str_len);
1870			if (tmpptr == NULL)
1871				goto bailout;
1872			if ((args[i].flags & CTL_BEARG_ASCII)
1873			 && (tmpptr[args[i].vallen - 1] != '\0')) {
1874				snprintf(error_str, error_str_len, "Argument "
1875				    "%d value is not NUL-terminated", i);
1876				goto bailout;
1877			}
1878			args[i].kvalue = tmpptr;
1879		} else {
1880			args[i].kvalue = malloc(args[i].vallen,
1881			    M_CTL, M_WAITOK | M_ZERO);
1882		}
1883	}
1884
1885	return (args);
1886bailout:
1887
1888	ctl_free_args(num_args, args);
1889
1890	return (NULL);
1891}
1892
1893static void
1894ctl_copyout_args(int num_args, struct ctl_be_arg *args)
1895{
1896	int i;
1897
1898	for (i = 0; i < num_args; i++) {
1899		if (args[i].flags & CTL_BEARG_WR)
1900			copyout(args[i].kvalue, args[i].value, args[i].vallen);
1901	}
1902}
1903
1904/*
1905 * Escape characters that are illegal or not recommended in XML.
1906 */
1907int
1908ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
1909{
1910	char *end = str + size;
1911	int retval;
1912
1913	retval = 0;
1914
1915	for (; *str && str < end; str++) {
1916		switch (*str) {
1917		case '&':
1918			retval = sbuf_printf(sb, "&amp;");
1919			break;
1920		case '>':
1921			retval = sbuf_printf(sb, "&gt;");
1922			break;
1923		case '<':
1924			retval = sbuf_printf(sb, "&lt;");
1925			break;
1926		default:
1927			retval = sbuf_putc(sb, *str);
1928			break;
1929		}
1930
1931		if (retval != 0)
1932			break;
1933
1934	}
1935
1936	return (retval);
1937}
1938
1939static void
1940ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
1941{
1942	struct scsi_vpd_id_descriptor *desc;
1943	int i;
1944
1945	if (id == NULL || id->len < 4)
1946		return;
1947	desc = (struct scsi_vpd_id_descriptor *)id->data;
1948	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
1949	case SVPD_ID_TYPE_T10:
1950		sbuf_printf(sb, "t10.");
1951		break;
1952	case SVPD_ID_TYPE_EUI64:
1953		sbuf_printf(sb, "eui.");
1954		break;
1955	case SVPD_ID_TYPE_NAA:
1956		sbuf_printf(sb, "naa.");
1957		break;
1958	case SVPD_ID_TYPE_SCSI_NAME:
1959		break;
1960	}
1961	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
1962	case SVPD_ID_CODESET_BINARY:
1963		for (i = 0; i < desc->length; i++)
1964			sbuf_printf(sb, "%02x", desc->identifier[i]);
1965		break;
1966	case SVPD_ID_CODESET_ASCII:
1967		sbuf_printf(sb, "%.*s", (int)desc->length,
1968		    (char *)desc->identifier);
1969		break;
1970	case SVPD_ID_CODESET_UTF8:
1971		sbuf_printf(sb, "%s", (char *)desc->identifier);
1972		break;
1973	}
1974}
1975
1976static int
1977ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
1978	  struct thread *td)
1979{
1980	struct ctl_softc *softc;
1981	int retval;
1982
1983	softc = control_softc;
1984
1985	retval = 0;
1986
1987	switch (cmd) {
1988	case CTL_IO:
1989		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
1990		break;
1991	case CTL_ENABLE_PORT:
1992	case CTL_DISABLE_PORT:
1993	case CTL_SET_PORT_WWNS: {
1994		struct ctl_port *port;
1995		struct ctl_port_entry *entry;
1996
1997		entry = (struct ctl_port_entry *)addr;
1998
1999		mtx_lock(&softc->ctl_lock);
2000		STAILQ_FOREACH(port, &softc->port_list, links) {
2001			int action, done;
2002
2003			action = 0;
2004			done = 0;
2005
2006			if ((entry->port_type == CTL_PORT_NONE)
2007			 && (entry->targ_port == port->targ_port)) {
2008				/*
2009				 * If the user only wants to enable or
2010				 * disable or set WWNs on a specific port,
2011				 * do the operation and we're done.
2012				 */
2013				action = 1;
2014				done = 1;
2015			} else if (entry->port_type & port->port_type) {
2016				/*
2017				 * Compare the user's type mask with the
2018				 * particular frontend type to see if we
2019				 * have a match.
2020				 */
2021				action = 1;
2022				done = 0;
2023
2024				/*
2025				 * Make sure the user isn't trying to set
2026				 * WWNs on multiple ports at the same time.
2027				 */
2028				if (cmd == CTL_SET_PORT_WWNS) {
2029					printf("%s: Can't set WWNs on "
2030					       "multiple ports\n", __func__);
2031					retval = EINVAL;
2032					break;
2033				}
2034			}
2035			if (action != 0) {
2036				/*
2037				 * XXX KDM we have to drop the lock here,
2038				 * because the online/offline operations
2039				 * can potentially block.  We need to
2040				 * reference count the frontends so they
2041				 * can't go away,
2042				 */
2043				mtx_unlock(&softc->ctl_lock);
2044
2045				if (cmd == CTL_ENABLE_PORT) {
2046					ctl_port_online(port);
2047				} else if (cmd == CTL_DISABLE_PORT) {
2048					ctl_port_offline(port);
2049				}
2050
2051				mtx_lock(&softc->ctl_lock);
2052
2053				if (cmd == CTL_SET_PORT_WWNS)
2054					ctl_port_set_wwns(port,
2055					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2056					    1 : 0, entry->wwnn,
2057					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2058					    1 : 0, entry->wwpn);
2059			}
2060			if (done != 0)
2061				break;
2062		}
2063		mtx_unlock(&softc->ctl_lock);
2064		break;
2065	}
2066	case CTL_GET_PORT_LIST: {
2067		struct ctl_port *port;
2068		struct ctl_port_list *list;
2069		int i;
2070
2071		list = (struct ctl_port_list *)addr;
2072
2073		if (list->alloc_len != (list->alloc_num *
2074		    sizeof(struct ctl_port_entry))) {
2075			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2076			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2077			       "%zu\n", __func__, list->alloc_len,
2078			       list->alloc_num, sizeof(struct ctl_port_entry));
2079			retval = EINVAL;
2080			break;
2081		}
2082		list->fill_len = 0;
2083		list->fill_num = 0;
2084		list->dropped_num = 0;
2085		i = 0;
2086		mtx_lock(&softc->ctl_lock);
2087		STAILQ_FOREACH(port, &softc->port_list, links) {
2088			struct ctl_port_entry entry, *list_entry;
2089
2090			if (list->fill_num >= list->alloc_num) {
2091				list->dropped_num++;
2092				continue;
2093			}
2094
2095			entry.port_type = port->port_type;
2096			strlcpy(entry.port_name, port->port_name,
2097				sizeof(entry.port_name));
2098			entry.targ_port = port->targ_port;
2099			entry.physical_port = port->physical_port;
2100			entry.virtual_port = port->virtual_port;
2101			entry.wwnn = port->wwnn;
2102			entry.wwpn = port->wwpn;
2103			if (port->status & CTL_PORT_STATUS_ONLINE)
2104				entry.online = 1;
2105			else
2106				entry.online = 0;
2107
2108			list_entry = &list->entries[i];
2109
2110			retval = copyout(&entry, list_entry, sizeof(entry));
2111			if (retval != 0) {
2112				printf("%s: CTL_GET_PORT_LIST: copyout "
2113				       "returned %d\n", __func__, retval);
2114				break;
2115			}
2116			i++;
2117			list->fill_num++;
2118			list->fill_len += sizeof(entry);
2119		}
2120		mtx_unlock(&softc->ctl_lock);
2121
2122		/*
2123		 * If this is non-zero, we had a copyout fault, so there's
2124		 * probably no point in attempting to set the status inside
2125		 * the structure.
2126		 */
2127		if (retval != 0)
2128			break;
2129
2130		if (list->dropped_num > 0)
2131			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2132		else
2133			list->status = CTL_PORT_LIST_OK;
2134		break;
2135	}
2136	case CTL_DUMP_OOA: {
2137		struct ctl_lun *lun;
2138		union ctl_io *io;
2139		char printbuf[128];
2140		struct sbuf sb;
2141
2142		mtx_lock(&softc->ctl_lock);
2143		printf("Dumping OOA queues:\n");
2144		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2145			mtx_lock(&lun->lun_lock);
2146			for (io = (union ctl_io *)TAILQ_FIRST(
2147			     &lun->ooa_queue); io != NULL;
2148			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2149			     ooa_links)) {
2150				sbuf_new(&sb, printbuf, sizeof(printbuf),
2151					 SBUF_FIXEDLEN);
2152				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2153					    (intmax_t)lun->lun,
2154					    io->scsiio.tag_num,
2155					    (io->io_hdr.flags &
2156					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2157					    (io->io_hdr.flags &
2158					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2159					    (io->io_hdr.flags &
2160					    CTL_FLAG_ABORT) ? " ABORT" : "",
2161			                    (io->io_hdr.flags &
2162		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2163				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2164				sbuf_finish(&sb);
2165				printf("%s\n", sbuf_data(&sb));
2166			}
2167			mtx_unlock(&lun->lun_lock);
2168		}
2169		printf("OOA queues dump done\n");
2170		mtx_unlock(&softc->ctl_lock);
2171		break;
2172	}
2173	case CTL_GET_OOA: {
2174		struct ctl_lun *lun;
2175		struct ctl_ooa *ooa_hdr;
2176		struct ctl_ooa_entry *entries;
2177		uint32_t cur_fill_num;
2178
2179		ooa_hdr = (struct ctl_ooa *)addr;
2180
2181		if ((ooa_hdr->alloc_len == 0)
2182		 || (ooa_hdr->alloc_num == 0)) {
2183			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2184			       "must be non-zero\n", __func__,
2185			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2186			retval = EINVAL;
2187			break;
2188		}
2189
2190		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2191		    sizeof(struct ctl_ooa_entry))) {
2192			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2193			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2194			       __func__, ooa_hdr->alloc_len,
2195			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2196			retval = EINVAL;
2197			break;
2198		}
2199
2200		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2201		if (entries == NULL) {
2202			printf("%s: could not allocate %d bytes for OOA "
2203			       "dump\n", __func__, ooa_hdr->alloc_len);
2204			retval = ENOMEM;
2205			break;
2206		}
2207
2208		mtx_lock(&softc->ctl_lock);
2209		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2210		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2211		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2212			mtx_unlock(&softc->ctl_lock);
2213			free(entries, M_CTL);
2214			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2215			       __func__, (uintmax_t)ooa_hdr->lun_num);
2216			retval = EINVAL;
2217			break;
2218		}
2219
2220		cur_fill_num = 0;
2221
2222		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2223			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2224				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2225					ooa_hdr, entries);
2226				if (retval != 0)
2227					break;
2228			}
2229			if (retval != 0) {
2230				mtx_unlock(&softc->ctl_lock);
2231				free(entries, M_CTL);
2232				break;
2233			}
2234		} else {
2235			lun = softc->ctl_luns[ooa_hdr->lun_num];
2236
2237			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2238						    entries);
2239		}
2240		mtx_unlock(&softc->ctl_lock);
2241
2242		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2243		ooa_hdr->fill_len = ooa_hdr->fill_num *
2244			sizeof(struct ctl_ooa_entry);
2245		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2246		if (retval != 0) {
2247			printf("%s: error copying out %d bytes for OOA dump\n",
2248			       __func__, ooa_hdr->fill_len);
2249		}
2250
2251		getbintime(&ooa_hdr->cur_bt);
2252
2253		if (cur_fill_num > ooa_hdr->alloc_num) {
2254			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2255			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2256		} else {
2257			ooa_hdr->dropped_num = 0;
2258			ooa_hdr->status = CTL_OOA_OK;
2259		}
2260
2261		free(entries, M_CTL);
2262		break;
2263	}
2264	case CTL_CHECK_OOA: {
2265		union ctl_io *io;
2266		struct ctl_lun *lun;
2267		struct ctl_ooa_info *ooa_info;
2268
2269
2270		ooa_info = (struct ctl_ooa_info *)addr;
2271
2272		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2273			ooa_info->status = CTL_OOA_INVALID_LUN;
2274			break;
2275		}
2276		mtx_lock(&softc->ctl_lock);
2277		lun = softc->ctl_luns[ooa_info->lun_id];
2278		if (lun == NULL) {
2279			mtx_unlock(&softc->ctl_lock);
2280			ooa_info->status = CTL_OOA_INVALID_LUN;
2281			break;
2282		}
2283		mtx_lock(&lun->lun_lock);
2284		mtx_unlock(&softc->ctl_lock);
2285		ooa_info->num_entries = 0;
2286		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2287		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2288		     &io->io_hdr, ooa_links)) {
2289			ooa_info->num_entries++;
2290		}
2291		mtx_unlock(&lun->lun_lock);
2292
2293		ooa_info->status = CTL_OOA_SUCCESS;
2294
2295		break;
2296	}
2297	case CTL_DELAY_IO: {
2298		struct ctl_io_delay_info *delay_info;
2299#ifdef CTL_IO_DELAY
2300		struct ctl_lun *lun;
2301#endif /* CTL_IO_DELAY */
2302
2303		delay_info = (struct ctl_io_delay_info *)addr;
2304
2305#ifdef CTL_IO_DELAY
2306		mtx_lock(&softc->ctl_lock);
2307
2308		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2309		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2310			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2311		} else {
2312			lun = softc->ctl_luns[delay_info->lun_id];
2313			mtx_lock(&lun->lun_lock);
2314
2315			delay_info->status = CTL_DELAY_STATUS_OK;
2316
2317			switch (delay_info->delay_type) {
2318			case CTL_DELAY_TYPE_CONT:
2319				break;
2320			case CTL_DELAY_TYPE_ONESHOT:
2321				break;
2322			default:
2323				delay_info->status =
2324					CTL_DELAY_STATUS_INVALID_TYPE;
2325				break;
2326			}
2327
2328			switch (delay_info->delay_loc) {
2329			case CTL_DELAY_LOC_DATAMOVE:
2330				lun->delay_info.datamove_type =
2331					delay_info->delay_type;
2332				lun->delay_info.datamove_delay =
2333					delay_info->delay_secs;
2334				break;
2335			case CTL_DELAY_LOC_DONE:
2336				lun->delay_info.done_type =
2337					delay_info->delay_type;
2338				lun->delay_info.done_delay =
2339					delay_info->delay_secs;
2340				break;
2341			default:
2342				delay_info->status =
2343					CTL_DELAY_STATUS_INVALID_LOC;
2344				break;
2345			}
2346			mtx_unlock(&lun->lun_lock);
2347		}
2348
2349		mtx_unlock(&softc->ctl_lock);
2350#else
2351		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2352#endif /* CTL_IO_DELAY */
2353		break;
2354	}
2355	case CTL_REALSYNC_SET: {
2356		int *syncstate;
2357
2358		syncstate = (int *)addr;
2359
2360		mtx_lock(&softc->ctl_lock);
2361		switch (*syncstate) {
2362		case 0:
2363			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2364			break;
2365		case 1:
2366			softc->flags |= CTL_FLAG_REAL_SYNC;
2367			break;
2368		default:
2369			retval = EINVAL;
2370			break;
2371		}
2372		mtx_unlock(&softc->ctl_lock);
2373		break;
2374	}
2375	case CTL_REALSYNC_GET: {
2376		int *syncstate;
2377
2378		syncstate = (int*)addr;
2379
2380		mtx_lock(&softc->ctl_lock);
2381		if (softc->flags & CTL_FLAG_REAL_SYNC)
2382			*syncstate = 1;
2383		else
2384			*syncstate = 0;
2385		mtx_unlock(&softc->ctl_lock);
2386
2387		break;
2388	}
2389	case CTL_SETSYNC:
2390	case CTL_GETSYNC: {
2391		struct ctl_sync_info *sync_info;
2392		struct ctl_lun *lun;
2393
2394		sync_info = (struct ctl_sync_info *)addr;
2395
2396		mtx_lock(&softc->ctl_lock);
2397		lun = softc->ctl_luns[sync_info->lun_id];
2398		if (lun == NULL) {
2399			mtx_unlock(&softc->ctl_lock);
2400			sync_info->status = CTL_GS_SYNC_NO_LUN;
2401		}
2402		/*
2403		 * Get or set the sync interval.  We're not bounds checking
2404		 * in the set case, hopefully the user won't do something
2405		 * silly.
2406		 */
2407		mtx_lock(&lun->lun_lock);
2408		mtx_unlock(&softc->ctl_lock);
2409		if (cmd == CTL_GETSYNC)
2410			sync_info->sync_interval = lun->sync_interval;
2411		else
2412			lun->sync_interval = sync_info->sync_interval;
2413		mtx_unlock(&lun->lun_lock);
2414
2415		sync_info->status = CTL_GS_SYNC_OK;
2416
2417		break;
2418	}
2419	case CTL_GETSTATS: {
2420		struct ctl_stats *stats;
2421		struct ctl_lun *lun;
2422		int i;
2423
2424		stats = (struct ctl_stats *)addr;
2425
2426		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2427		     stats->alloc_len) {
2428			stats->status = CTL_SS_NEED_MORE_SPACE;
2429			stats->num_luns = softc->num_luns;
2430			break;
2431		}
2432		/*
2433		 * XXX KDM no locking here.  If the LUN list changes,
2434		 * things can blow up.
2435		 */
2436		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2437		     i++, lun = STAILQ_NEXT(lun, links)) {
2438			retval = copyout(&lun->stats, &stats->lun_stats[i],
2439					 sizeof(lun->stats));
2440			if (retval != 0)
2441				break;
2442		}
2443		stats->num_luns = softc->num_luns;
2444		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2445				 softc->num_luns;
2446		stats->status = CTL_SS_OK;
2447#ifdef CTL_TIME_IO
2448		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2449#else
2450		stats->flags = CTL_STATS_FLAG_NONE;
2451#endif
2452		getnanouptime(&stats->timestamp);
2453		break;
2454	}
2455	case CTL_ERROR_INJECT: {
2456		struct ctl_error_desc *err_desc, *new_err_desc;
2457		struct ctl_lun *lun;
2458
2459		err_desc = (struct ctl_error_desc *)addr;
2460
2461		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2462				      M_WAITOK | M_ZERO);
2463		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2464
2465		mtx_lock(&softc->ctl_lock);
2466		lun = softc->ctl_luns[err_desc->lun_id];
2467		if (lun == NULL) {
2468			mtx_unlock(&softc->ctl_lock);
2469			free(new_err_desc, M_CTL);
2470			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2471			       __func__, (uintmax_t)err_desc->lun_id);
2472			retval = EINVAL;
2473			break;
2474		}
2475		mtx_lock(&lun->lun_lock);
2476		mtx_unlock(&softc->ctl_lock);
2477
2478		/*
2479		 * We could do some checking here to verify the validity
2480		 * of the request, but given the complexity of error
2481		 * injection requests, the checking logic would be fairly
2482		 * complex.
2483		 *
2484		 * For now, if the request is invalid, it just won't get
2485		 * executed and might get deleted.
2486		 */
2487		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2488
2489		/*
2490		 * XXX KDM check to make sure the serial number is unique,
2491		 * in case we somehow manage to wrap.  That shouldn't
2492		 * happen for a very long time, but it's the right thing to
2493		 * do.
2494		 */
2495		new_err_desc->serial = lun->error_serial;
2496		err_desc->serial = lun->error_serial;
2497		lun->error_serial++;
2498
2499		mtx_unlock(&lun->lun_lock);
2500		break;
2501	}
2502	case CTL_ERROR_INJECT_DELETE: {
2503		struct ctl_error_desc *delete_desc, *desc, *desc2;
2504		struct ctl_lun *lun;
2505		int delete_done;
2506
2507		delete_desc = (struct ctl_error_desc *)addr;
2508		delete_done = 0;
2509
2510		mtx_lock(&softc->ctl_lock);
2511		lun = softc->ctl_luns[delete_desc->lun_id];
2512		if (lun == NULL) {
2513			mtx_unlock(&softc->ctl_lock);
2514			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2515			       __func__, (uintmax_t)delete_desc->lun_id);
2516			retval = EINVAL;
2517			break;
2518		}
2519		mtx_lock(&lun->lun_lock);
2520		mtx_unlock(&softc->ctl_lock);
2521		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2522			if (desc->serial != delete_desc->serial)
2523				continue;
2524
2525			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2526				      links);
2527			free(desc, M_CTL);
2528			delete_done = 1;
2529		}
2530		mtx_unlock(&lun->lun_lock);
2531		if (delete_done == 0) {
2532			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2533			       "error serial %ju on LUN %u\n", __func__,
2534			       delete_desc->serial, delete_desc->lun_id);
2535			retval = EINVAL;
2536			break;
2537		}
2538		break;
2539	}
2540	case CTL_DUMP_STRUCTS: {
2541		int i, j, k;
2542		struct ctl_port *port;
2543		struct ctl_frontend *fe;
2544
2545		mtx_lock(&softc->ctl_lock);
2546		printf("CTL Persistent Reservation information start:\n");
2547		for (i = 0; i < CTL_MAX_LUNS; i++) {
2548			struct ctl_lun *lun;
2549
2550			lun = softc->ctl_luns[i];
2551
2552			if ((lun == NULL)
2553			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
2554				continue;
2555
2556			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
2557				if (lun->pr_keys[j] == NULL)
2558					continue;
2559				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2560					if (lun->pr_keys[j][k] == 0)
2561						continue;
2562					printf("  LUN %d port %d iid %d key "
2563					       "%#jx\n", i, j, k,
2564					       (uintmax_t)lun->pr_keys[j][k]);
2565				}
2566			}
2567		}
2568		printf("CTL Persistent Reservation information end\n");
2569		printf("CTL Ports:\n");
2570		STAILQ_FOREACH(port, &softc->port_list, links) {
2571			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2572			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2573			       port->frontend->name, port->port_type,
2574			       port->physical_port, port->virtual_port,
2575			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2576			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2577				if (port->wwpn_iid[j].in_use == 0 &&
2578				    port->wwpn_iid[j].wwpn == 0 &&
2579				    port->wwpn_iid[j].name == NULL)
2580					continue;
2581
2582				printf("    iid %u use %d WWPN %#jx '%s'\n",
2583				    j, port->wwpn_iid[j].in_use,
2584				    (uintmax_t)port->wwpn_iid[j].wwpn,
2585				    port->wwpn_iid[j].name);
2586			}
2587		}
2588		printf("CTL Port information end\n");
2589		mtx_unlock(&softc->ctl_lock);
2590		/*
2591		 * XXX KDM calling this without a lock.  We'd likely want
2592		 * to drop the lock before calling the frontend's dump
2593		 * routine anyway.
2594		 */
2595		printf("CTL Frontends:\n");
2596		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2597			printf("  Frontend '%s'\n", fe->name);
2598			if (fe->fe_dump != NULL)
2599				fe->fe_dump();
2600		}
2601		printf("CTL Frontend information end\n");
2602		break;
2603	}
2604	case CTL_LUN_REQ: {
2605		struct ctl_lun_req *lun_req;
2606		struct ctl_backend_driver *backend;
2607
2608		lun_req = (struct ctl_lun_req *)addr;
2609
2610		backend = ctl_backend_find(lun_req->backend);
2611		if (backend == NULL) {
2612			lun_req->status = CTL_LUN_ERROR;
2613			snprintf(lun_req->error_str,
2614				 sizeof(lun_req->error_str),
2615				 "Backend \"%s\" not found.",
2616				 lun_req->backend);
2617			break;
2618		}
2619		if (lun_req->num_be_args > 0) {
2620			lun_req->kern_be_args = ctl_copyin_args(
2621				lun_req->num_be_args,
2622				lun_req->be_args,
2623				lun_req->error_str,
2624				sizeof(lun_req->error_str));
2625			if (lun_req->kern_be_args == NULL) {
2626				lun_req->status = CTL_LUN_ERROR;
2627				break;
2628			}
2629		}
2630
2631		retval = backend->ioctl(dev, cmd, addr, flag, td);
2632
2633		if (lun_req->num_be_args > 0) {
2634			ctl_copyout_args(lun_req->num_be_args,
2635				      lun_req->kern_be_args);
2636			ctl_free_args(lun_req->num_be_args,
2637				      lun_req->kern_be_args);
2638		}
2639		break;
2640	}
2641	case CTL_LUN_LIST: {
2642		struct sbuf *sb;
2643		struct ctl_lun *lun;
2644		struct ctl_lun_list *list;
2645		struct ctl_option *opt;
2646
2647		list = (struct ctl_lun_list *)addr;
2648
2649		/*
2650		 * Allocate a fixed length sbuf here, based on the length
2651		 * of the user's buffer.  We could allocate an auto-extending
2652		 * buffer, and then tell the user how much larger our
2653		 * amount of data is than his buffer, but that presents
2654		 * some problems:
2655		 *
2656		 * 1.  The sbuf(9) routines use a blocking malloc, and so
2657		 *     we can't hold a lock while calling them with an
2658		 *     auto-extending buffer.
2659 		 *
2660		 * 2.  There is not currently a LUN reference counting
2661		 *     mechanism, outside of outstanding transactions on
2662		 *     the LUN's OOA queue.  So a LUN could go away on us
2663		 *     while we're getting the LUN number, backend-specific
2664		 *     information, etc.  Thus, given the way things
2665		 *     currently work, we need to hold the CTL lock while
2666		 *     grabbing LUN information.
2667		 *
2668		 * So, from the user's standpoint, the best thing to do is
2669		 * allocate what he thinks is a reasonable buffer length,
2670		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
2671		 * double the buffer length and try again.  (And repeat
2672		 * that until he succeeds.)
2673		 */
2674		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
2675		if (sb == NULL) {
2676			list->status = CTL_LUN_LIST_ERROR;
2677			snprintf(list->error_str, sizeof(list->error_str),
2678				 "Unable to allocate %d bytes for LUN list",
2679				 list->alloc_len);
2680			break;
2681		}
2682
2683		sbuf_printf(sb, "<ctllunlist>\n");
2684
2685		mtx_lock(&softc->ctl_lock);
2686		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2687			mtx_lock(&lun->lun_lock);
2688			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
2689					     (uintmax_t)lun->lun);
2690
2691			/*
2692			 * Bail out as soon as we see that we've overfilled
2693			 * the buffer.
2694			 */
2695			if (retval != 0)
2696				break;
2697
2698			retval = sbuf_printf(sb, "\t<backend_type>%s"
2699					     "</backend_type>\n",
2700					     (lun->backend == NULL) ?  "none" :
2701					     lun->backend->name);
2702
2703			if (retval != 0)
2704				break;
2705
2706			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
2707					     lun->be_lun->lun_type);
2708
2709			if (retval != 0)
2710				break;
2711
2712			if (lun->backend == NULL) {
2713				retval = sbuf_printf(sb, "</lun>\n");
2714				if (retval != 0)
2715					break;
2716				continue;
2717			}
2718
2719			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
2720					     (lun->be_lun->maxlba > 0) ?
2721					     lun->be_lun->maxlba + 1 : 0);
2722
2723			if (retval != 0)
2724				break;
2725
2726			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
2727					     lun->be_lun->blocksize);
2728
2729			if (retval != 0)
2730				break;
2731
2732			retval = sbuf_printf(sb, "\t<serial_number>");
2733
2734			if (retval != 0)
2735				break;
2736
2737			retval = ctl_sbuf_printf_esc(sb,
2738			    lun->be_lun->serial_num,
2739			    sizeof(lun->be_lun->serial_num));
2740
2741			if (retval != 0)
2742				break;
2743
2744			retval = sbuf_printf(sb, "</serial_number>\n");
2745
2746			if (retval != 0)
2747				break;
2748
2749			retval = sbuf_printf(sb, "\t<device_id>");
2750
2751			if (retval != 0)
2752				break;
2753
2754			retval = ctl_sbuf_printf_esc(sb,
2755			    lun->be_lun->device_id,
2756			    sizeof(lun->be_lun->device_id));
2757
2758			if (retval != 0)
2759				break;
2760
2761			retval = sbuf_printf(sb, "</device_id>\n");
2762
2763			if (retval != 0)
2764				break;
2765
2766			if (lun->backend->lun_info != NULL) {
2767				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
2768				if (retval != 0)
2769					break;
2770			}
2771			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
2772				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
2773				    opt->name, opt->value, opt->name);
2774				if (retval != 0)
2775					break;
2776			}
2777
2778			retval = sbuf_printf(sb, "</lun>\n");
2779
2780			if (retval != 0)
2781				break;
2782			mtx_unlock(&lun->lun_lock);
2783		}
2784		if (lun != NULL)
2785			mtx_unlock(&lun->lun_lock);
2786		mtx_unlock(&softc->ctl_lock);
2787
2788		if ((retval != 0)
2789		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
2790			retval = 0;
2791			sbuf_delete(sb);
2792			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
2793			snprintf(list->error_str, sizeof(list->error_str),
2794				 "Out of space, %d bytes is too small",
2795				 list->alloc_len);
2796			break;
2797		}
2798
2799		sbuf_finish(sb);
2800
2801		retval = copyout(sbuf_data(sb), list->lun_xml,
2802				 sbuf_len(sb) + 1);
2803
2804		list->fill_len = sbuf_len(sb) + 1;
2805		list->status = CTL_LUN_LIST_OK;
2806		sbuf_delete(sb);
2807		break;
2808	}
2809	case CTL_ISCSI: {
2810		struct ctl_iscsi *ci;
2811		struct ctl_frontend *fe;
2812
2813		ci = (struct ctl_iscsi *)addr;
2814
2815		fe = ctl_frontend_find("iscsi");
2816		if (fe == NULL) {
2817			ci->status = CTL_ISCSI_ERROR;
2818			snprintf(ci->error_str, sizeof(ci->error_str),
2819			    "Frontend \"iscsi\" not found.");
2820			break;
2821		}
2822
2823		retval = fe->ioctl(dev, cmd, addr, flag, td);
2824		break;
2825	}
2826	case CTL_PORT_REQ: {
2827		struct ctl_req *req;
2828		struct ctl_frontend *fe;
2829
2830		req = (struct ctl_req *)addr;
2831
2832		fe = ctl_frontend_find(req->driver);
2833		if (fe == NULL) {
2834			req->status = CTL_LUN_ERROR;
2835			snprintf(req->error_str, sizeof(req->error_str),
2836			    "Frontend \"%s\" not found.", req->driver);
2837			break;
2838		}
2839		if (req->num_args > 0) {
2840			req->kern_args = ctl_copyin_args(req->num_args,
2841			    req->args, req->error_str, sizeof(req->error_str));
2842			if (req->kern_args == NULL) {
2843				req->status = CTL_LUN_ERROR;
2844				break;
2845			}
2846		}
2847
2848		retval = fe->ioctl(dev, cmd, addr, flag, td);
2849
2850		if (req->num_args > 0) {
2851			ctl_copyout_args(req->num_args, req->kern_args);
2852			ctl_free_args(req->num_args, req->kern_args);
2853		}
2854		break;
2855	}
2856	case CTL_PORT_LIST: {
2857		struct sbuf *sb;
2858		struct ctl_port *port;
2859		struct ctl_lun_list *list;
2860		struct ctl_option *opt;
2861		int j;
2862		uint32_t plun;
2863
2864		list = (struct ctl_lun_list *)addr;
2865
2866		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
2867		if (sb == NULL) {
2868			list->status = CTL_LUN_LIST_ERROR;
2869			snprintf(list->error_str, sizeof(list->error_str),
2870				 "Unable to allocate %d bytes for LUN list",
2871				 list->alloc_len);
2872			break;
2873		}
2874
2875		sbuf_printf(sb, "<ctlportlist>\n");
2876
2877		mtx_lock(&softc->ctl_lock);
2878		STAILQ_FOREACH(port, &softc->port_list, links) {
2879			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
2880					     (uintmax_t)port->targ_port);
2881
2882			/*
2883			 * Bail out as soon as we see that we've overfilled
2884			 * the buffer.
2885			 */
2886			if (retval != 0)
2887				break;
2888
2889			retval = sbuf_printf(sb, "\t<frontend_type>%s"
2890			    "</frontend_type>\n", port->frontend->name);
2891			if (retval != 0)
2892				break;
2893
2894			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
2895					     port->port_type);
2896			if (retval != 0)
2897				break;
2898
2899			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
2900			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
2901			if (retval != 0)
2902				break;
2903
2904			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
2905			    port->port_name);
2906			if (retval != 0)
2907				break;
2908
2909			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
2910			    port->physical_port);
2911			if (retval != 0)
2912				break;
2913
2914			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
2915			    port->virtual_port);
2916			if (retval != 0)
2917				break;
2918
2919			if (port->target_devid != NULL) {
2920				sbuf_printf(sb, "\t<target>");
2921				ctl_id_sbuf(port->target_devid, sb);
2922				sbuf_printf(sb, "</target>\n");
2923			}
2924
2925			if (port->port_devid != NULL) {
2926				sbuf_printf(sb, "\t<port>");
2927				ctl_id_sbuf(port->port_devid, sb);
2928				sbuf_printf(sb, "</port>\n");
2929			}
2930
2931			if (port->port_info != NULL) {
2932				retval = port->port_info(port->onoff_arg, sb);
2933				if (retval != 0)
2934					break;
2935			}
2936			STAILQ_FOREACH(opt, &port->options, links) {
2937				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
2938				    opt->name, opt->value, opt->name);
2939				if (retval != 0)
2940					break;
2941			}
2942
2943			if (port->lun_map != NULL) {
2944				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
2945				for (j = 0; j < CTL_MAX_LUNS; j++) {
2946					plun = ctl_lun_map_from_port(port, j);
2947					if (plun >= CTL_MAX_LUNS)
2948						continue;
2949					sbuf_printf(sb,
2950					    "\t<lun id=\"%u\">%u</lun>\n",
2951					    j, plun);
2952				}
2953			}
2954
2955			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2956				if (port->wwpn_iid[j].in_use == 0 ||
2957				    (port->wwpn_iid[j].wwpn == 0 &&
2958				     port->wwpn_iid[j].name == NULL))
2959					continue;
2960
2961				if (port->wwpn_iid[j].name != NULL)
2962					retval = sbuf_printf(sb,
2963					    "\t<initiator id=\"%u\">%s</initiator>\n",
2964					    j, port->wwpn_iid[j].name);
2965				else
2966					retval = sbuf_printf(sb,
2967					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
2968					    j, port->wwpn_iid[j].wwpn);
2969				if (retval != 0)
2970					break;
2971			}
2972			if (retval != 0)
2973				break;
2974
2975			retval = sbuf_printf(sb, "</targ_port>\n");
2976			if (retval != 0)
2977				break;
2978		}
2979		mtx_unlock(&softc->ctl_lock);
2980
2981		if ((retval != 0)
2982		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
2983			retval = 0;
2984			sbuf_delete(sb);
2985			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
2986			snprintf(list->error_str, sizeof(list->error_str),
2987				 "Out of space, %d bytes is too small",
2988				 list->alloc_len);
2989			break;
2990		}
2991
2992		sbuf_finish(sb);
2993
2994		retval = copyout(sbuf_data(sb), list->lun_xml,
2995				 sbuf_len(sb) + 1);
2996
2997		list->fill_len = sbuf_len(sb) + 1;
2998		list->status = CTL_LUN_LIST_OK;
2999		sbuf_delete(sb);
3000		break;
3001	}
3002	case CTL_LUN_MAP: {
3003		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3004		struct ctl_port *port;
3005
3006		mtx_lock(&softc->ctl_lock);
3007		if (lm->port >= CTL_MAX_PORTS ||
3008		    (port = softc->ctl_ports[lm->port]) == NULL) {
3009			mtx_unlock(&softc->ctl_lock);
3010			return (ENXIO);
3011		}
3012		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3013		if (lm->plun < CTL_MAX_LUNS) {
3014			if (lm->lun == UINT32_MAX)
3015				retval = ctl_lun_map_unset(port, lm->plun);
3016			else if (lm->lun < CTL_MAX_LUNS &&
3017			    softc->ctl_luns[lm->lun] != NULL)
3018				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3019			else
3020				return (ENXIO);
3021		} else if (lm->plun == UINT32_MAX) {
3022			if (lm->lun == UINT32_MAX)
3023				retval = ctl_lun_map_deinit(port);
3024			else
3025				retval = ctl_lun_map_init(port);
3026		} else
3027			return (ENXIO);
3028		break;
3029	}
3030	default: {
3031		/* XXX KDM should we fix this? */
3032#if 0
3033		struct ctl_backend_driver *backend;
3034		unsigned int type;
3035		int found;
3036
3037		found = 0;
3038
3039		/*
3040		 * We encode the backend type as the ioctl type for backend
3041		 * ioctls.  So parse it out here, and then search for a
3042		 * backend of this type.
3043		 */
3044		type = _IOC_TYPE(cmd);
3045
3046		STAILQ_FOREACH(backend, &softc->be_list, links) {
3047			if (backend->type == type) {
3048				found = 1;
3049				break;
3050			}
3051		}
3052		if (found == 0) {
3053			printf("ctl: unknown ioctl command %#lx or backend "
3054			       "%d\n", cmd, type);
3055			retval = EINVAL;
3056			break;
3057		}
3058		retval = backend->ioctl(dev, cmd, addr, flag, td);
3059#endif
3060		retval = ENOTTY;
3061		break;
3062	}
3063	}
3064	return (retval);
3065}
3066
3067uint32_t
3068ctl_get_initindex(struct ctl_nexus *nexus)
3069{
3070	if (nexus->targ_port < CTL_MAX_PORTS)
3071		return (nexus->initid +
3072			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3073	else
3074		return (nexus->initid +
3075		       ((nexus->targ_port - CTL_MAX_PORTS) *
3076			CTL_MAX_INIT_PER_PORT));
3077}
3078
3079uint32_t
3080ctl_get_resindex(struct ctl_nexus *nexus)
3081{
3082	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3083}
3084
3085uint32_t
3086ctl_port_idx(int port_num)
3087{
3088	if (port_num < CTL_MAX_PORTS)
3089		return(port_num);
3090	else
3091		return(port_num - CTL_MAX_PORTS);
3092}
3093
3094int
3095ctl_lun_map_init(struct ctl_port *port)
3096{
3097	struct ctl_softc *softc = control_softc;
3098	struct ctl_lun *lun;
3099	uint32_t i;
3100
3101	if (port->lun_map == NULL)
3102		port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3103		    M_CTL, M_NOWAIT);
3104	if (port->lun_map == NULL)
3105		return (ENOMEM);
3106	for (i = 0; i < CTL_MAX_LUNS; i++)
3107		port->lun_map[i] = UINT32_MAX;
3108	if (port->status & CTL_PORT_STATUS_ONLINE &&
3109	    port->lun_disable != NULL) {
3110		STAILQ_FOREACH(lun, &softc->lun_list, links)
3111			port->lun_disable(port->targ_lun_arg, lun->lun);
3112	}
3113	return (0);
3114}
3115
3116int
3117ctl_lun_map_deinit(struct ctl_port *port)
3118{
3119	struct ctl_softc *softc = control_softc;
3120	struct ctl_lun *lun;
3121
3122	if (port->lun_map == NULL)
3123		return (0);
3124	free(port->lun_map, M_CTL);
3125	port->lun_map = NULL;
3126	if (port->status & CTL_PORT_STATUS_ONLINE &&
3127	    port->lun_enable != NULL) {
3128		STAILQ_FOREACH(lun, &softc->lun_list, links)
3129			port->lun_enable(port->targ_lun_arg, lun->lun);
3130	}
3131	return (0);
3132}
3133
3134int
3135ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3136{
3137	int status;
3138	uint32_t old;
3139
3140	if (port->lun_map == NULL) {
3141		status = ctl_lun_map_init(port);
3142		if (status != 0)
3143			return (status);
3144	}
3145	old = port->lun_map[plun];
3146	port->lun_map[plun] = glun;
3147	if ((port->status & CTL_PORT_STATUS_ONLINE) && old >= CTL_MAX_LUNS &&
3148	    port->lun_enable != NULL)
3149		port->lun_enable(port->targ_lun_arg, plun);
3150	return (0);
3151}
3152
3153int
3154ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3155{
3156	uint32_t old;
3157
3158	if (port->lun_map == NULL)
3159		return (0);
3160	old = port->lun_map[plun];
3161	port->lun_map[plun] = UINT32_MAX;
3162	if ((port->status & CTL_PORT_STATUS_ONLINE) && old < CTL_MAX_LUNS &&
3163	    port->lun_disable != NULL)
3164		port->lun_disable(port->targ_lun_arg, plun);
3165	return (0);
3166}
3167
3168uint32_t
3169ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3170{
3171
3172	if (port == NULL)
3173		return (UINT32_MAX);
3174	if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3175		return (lun_id);
3176	return (port->lun_map[lun_id]);
3177}
3178
3179uint32_t
3180ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3181{
3182	uint32_t i;
3183
3184	if (port == NULL)
3185		return (UINT32_MAX);
3186	if (port->lun_map == NULL)
3187		return (lun_id);
3188	for (i = 0; i < CTL_MAX_LUNS; i++) {
3189		if (port->lun_map[i] == lun_id)
3190			return (i);
3191	}
3192	return (UINT32_MAX);
3193}
3194
3195static struct ctl_port *
3196ctl_io_port(struct ctl_io_hdr *io_hdr)
3197{
3198	int port_num;
3199
3200	port_num = io_hdr->nexus.targ_port;
3201	return (control_softc->ctl_ports[ctl_port_idx(port_num)]);
3202}
3203
3204/*
3205 * Note:  This only works for bitmask sizes that are at least 32 bits, and
3206 * that are a power of 2.
3207 */
3208int
3209ctl_ffz(uint32_t *mask, uint32_t size)
3210{
3211	uint32_t num_chunks, num_pieces;
3212	int i, j;
3213
3214	num_chunks = (size >> 5);
3215	if (num_chunks == 0)
3216		num_chunks++;
3217	num_pieces = MIN((sizeof(uint32_t) * 8), size);
3218
3219	for (i = 0; i < num_chunks; i++) {
3220		for (j = 0; j < num_pieces; j++) {
3221			if ((mask[i] & (1 << j)) == 0)
3222				return ((i << 5) + j);
3223		}
3224	}
3225
3226	return (-1);
3227}
3228
3229int
3230ctl_set_mask(uint32_t *mask, uint32_t bit)
3231{
3232	uint32_t chunk, piece;
3233
3234	chunk = bit >> 5;
3235	piece = bit % (sizeof(uint32_t) * 8);
3236
3237	if ((mask[chunk] & (1 << piece)) != 0)
3238		return (-1);
3239	else
3240		mask[chunk] |= (1 << piece);
3241
3242	return (0);
3243}
3244
3245int
3246ctl_clear_mask(uint32_t *mask, uint32_t bit)
3247{
3248	uint32_t chunk, piece;
3249
3250	chunk = bit >> 5;
3251	piece = bit % (sizeof(uint32_t) * 8);
3252
3253	if ((mask[chunk] & (1 << piece)) == 0)
3254		return (-1);
3255	else
3256		mask[chunk] &= ~(1 << piece);
3257
3258	return (0);
3259}
3260
3261int
3262ctl_is_set(uint32_t *mask, uint32_t bit)
3263{
3264	uint32_t chunk, piece;
3265
3266	chunk = bit >> 5;
3267	piece = bit % (sizeof(uint32_t) * 8);
3268
3269	if ((mask[chunk] & (1 << piece)) == 0)
3270		return (0);
3271	else
3272		return (1);
3273}
3274
3275static uint64_t
3276ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3277{
3278	uint64_t *t;
3279
3280	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3281	if (t == NULL)
3282		return (0);
3283	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3284}
3285
3286static void
3287ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3288{
3289	uint64_t *t;
3290
3291	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3292	if (t == NULL)
3293		return;
3294	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3295}
3296
3297static void
3298ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3299{
3300	uint64_t *p;
3301	u_int i;
3302
3303	i = residx/CTL_MAX_INIT_PER_PORT;
3304	if (lun->pr_keys[i] != NULL)
3305		return;
3306	mtx_unlock(&lun->lun_lock);
3307	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3308	    M_WAITOK | M_ZERO);
3309	mtx_lock(&lun->lun_lock);
3310	if (lun->pr_keys[i] == NULL)
3311		lun->pr_keys[i] = p;
3312	else
3313		free(p, M_CTL);
3314}
3315
3316static void
3317ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3318{
3319	uint64_t *t;
3320
3321	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3322	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3323	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3324}
3325
3326/*
3327 * ctl_softc, pool_name, total_ctl_io are passed in.
3328 * npool is passed out.
3329 */
3330int
3331ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3332		uint32_t total_ctl_io, void **npool)
3333{
3334#ifdef IO_POOLS
3335	struct ctl_io_pool *pool;
3336
3337	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3338					    M_NOWAIT | M_ZERO);
3339	if (pool == NULL)
3340		return (ENOMEM);
3341
3342	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3343	pool->ctl_softc = ctl_softc;
3344	pool->zone = uma_zsecond_create(pool->name, NULL,
3345	    NULL, NULL, NULL, ctl_softc->io_zone);
3346	/* uma_prealloc(pool->zone, total_ctl_io); */
3347
3348	*npool = pool;
3349#else
3350	*npool = ctl_softc->io_zone;
3351#endif
3352	return (0);
3353}
3354
3355void
3356ctl_pool_free(struct ctl_io_pool *pool)
3357{
3358
3359	if (pool == NULL)
3360		return;
3361
3362#ifdef IO_POOLS
3363	uma_zdestroy(pool->zone);
3364	free(pool, M_CTL);
3365#endif
3366}
3367
3368union ctl_io *
3369ctl_alloc_io(void *pool_ref)
3370{
3371	union ctl_io *io;
3372#ifdef IO_POOLS
3373	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3374
3375	io = uma_zalloc(pool->zone, M_WAITOK);
3376#else
3377	io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3378#endif
3379	if (io != NULL)
3380		io->io_hdr.pool = pool_ref;
3381	return (io);
3382}
3383
3384union ctl_io *
3385ctl_alloc_io_nowait(void *pool_ref)
3386{
3387	union ctl_io *io;
3388#ifdef IO_POOLS
3389	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3390
3391	io = uma_zalloc(pool->zone, M_NOWAIT);
3392#else
3393	io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3394#endif
3395	if (io != NULL)
3396		io->io_hdr.pool = pool_ref;
3397	return (io);
3398}
3399
3400void
3401ctl_free_io(union ctl_io *io)
3402{
3403#ifdef IO_POOLS
3404	struct ctl_io_pool *pool;
3405#endif
3406
3407	if (io == NULL)
3408		return;
3409
3410#ifdef IO_POOLS
3411	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3412	uma_zfree(pool->zone, io);
3413#else
3414	uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3415#endif
3416}
3417
3418void
3419ctl_zero_io(union ctl_io *io)
3420{
3421	void *pool_ref;
3422
3423	if (io == NULL)
3424		return;
3425
3426	/*
3427	 * May need to preserve linked list pointers at some point too.
3428	 */
3429	pool_ref = io->io_hdr.pool;
3430	memset(io, 0, sizeof(*io));
3431	io->io_hdr.pool = pool_ref;
3432}
3433
3434/*
3435 * This routine is currently used for internal copies of ctl_ios that need
3436 * to persist for some reason after we've already returned status to the
3437 * FETD.  (Thus the flag set.)
3438 *
3439 * XXX XXX
3440 * Note that this makes a blind copy of all fields in the ctl_io, except
3441 * for the pool reference.  This includes any memory that has been
3442 * allocated!  That memory will no longer be valid after done has been
3443 * called, so this would be VERY DANGEROUS for command that actually does
3444 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3445 * start and stop commands, which don't transfer any data, so this is not a
3446 * problem.  If it is used for anything else, the caller would also need to
3447 * allocate data buffer space and this routine would need to be modified to
3448 * copy the data buffer(s) as well.
3449 */
3450void
3451ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3452{
3453	void *pool_ref;
3454
3455	if ((src == NULL)
3456	 || (dest == NULL))
3457		return;
3458
3459	/*
3460	 * May need to preserve linked list pointers at some point too.
3461	 */
3462	pool_ref = dest->io_hdr.pool;
3463
3464	memcpy(dest, src, MIN(sizeof(*src), sizeof(*dest)));
3465
3466	dest->io_hdr.pool = pool_ref;
3467	/*
3468	 * We need to know that this is an internal copy, and doesn't need
3469	 * to get passed back to the FETD that allocated it.
3470	 */
3471	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3472}
3473
3474int
3475ctl_expand_number(const char *buf, uint64_t *num)
3476{
3477	char *endptr;
3478	uint64_t number;
3479	unsigned shift;
3480
3481	number = strtoq(buf, &endptr, 0);
3482
3483	switch (tolower((unsigned char)*endptr)) {
3484	case 'e':
3485		shift = 60;
3486		break;
3487	case 'p':
3488		shift = 50;
3489		break;
3490	case 't':
3491		shift = 40;
3492		break;
3493	case 'g':
3494		shift = 30;
3495		break;
3496	case 'm':
3497		shift = 20;
3498		break;
3499	case 'k':
3500		shift = 10;
3501		break;
3502	case 'b':
3503	case '\0': /* No unit. */
3504		*num = number;
3505		return (0);
3506	default:
3507		/* Unrecognized unit. */
3508		return (-1);
3509	}
3510
3511	if ((number << shift) >> shift != number) {
3512		/* Overflow */
3513		return (-1);
3514	}
3515	*num = number << shift;
3516	return (0);
3517}
3518
3519
3520/*
3521 * This routine could be used in the future to load default and/or saved
3522 * mode page parameters for a particuar lun.
3523 */
3524static int
3525ctl_init_page_index(struct ctl_lun *lun)
3526{
3527	int i;
3528	struct ctl_page_index *page_index;
3529	const char *value;
3530	uint64_t ival;
3531
3532	memcpy(&lun->mode_pages.index, page_index_template,
3533	       sizeof(page_index_template));
3534
3535	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3536
3537		page_index = &lun->mode_pages.index[i];
3538		/*
3539		 * If this is a disk-only mode page, there's no point in
3540		 * setting it up.  For some pages, we have to have some
3541		 * basic information about the disk in order to calculate the
3542		 * mode page data.
3543		 */
3544		if ((lun->be_lun->lun_type != T_DIRECT)
3545		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3546			continue;
3547
3548		switch (page_index->page_code & SMPH_PC_MASK) {
3549		case SMS_RW_ERROR_RECOVERY_PAGE: {
3550			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3551				panic("subpage is incorrect!");
3552			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3553			       &rw_er_page_default,
3554			       sizeof(rw_er_page_default));
3555			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3556			       &rw_er_page_changeable,
3557			       sizeof(rw_er_page_changeable));
3558			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3559			       &rw_er_page_default,
3560			       sizeof(rw_er_page_default));
3561			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3562			       &rw_er_page_default,
3563			       sizeof(rw_er_page_default));
3564			page_index->page_data =
3565				(uint8_t *)lun->mode_pages.rw_er_page;
3566			break;
3567		}
3568		case SMS_FORMAT_DEVICE_PAGE: {
3569			struct scsi_format_page *format_page;
3570
3571			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3572				panic("subpage is incorrect!");
3573
3574			/*
3575			 * Sectors per track are set above.  Bytes per
3576			 * sector need to be set here on a per-LUN basis.
3577			 */
3578			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3579			       &format_page_default,
3580			       sizeof(format_page_default));
3581			memcpy(&lun->mode_pages.format_page[
3582			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
3583			       sizeof(format_page_changeable));
3584			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3585			       &format_page_default,
3586			       sizeof(format_page_default));
3587			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3588			       &format_page_default,
3589			       sizeof(format_page_default));
3590
3591			format_page = &lun->mode_pages.format_page[
3592				CTL_PAGE_CURRENT];
3593			scsi_ulto2b(lun->be_lun->blocksize,
3594				    format_page->bytes_per_sector);
3595
3596			format_page = &lun->mode_pages.format_page[
3597				CTL_PAGE_DEFAULT];
3598			scsi_ulto2b(lun->be_lun->blocksize,
3599				    format_page->bytes_per_sector);
3600
3601			format_page = &lun->mode_pages.format_page[
3602				CTL_PAGE_SAVED];
3603			scsi_ulto2b(lun->be_lun->blocksize,
3604				    format_page->bytes_per_sector);
3605
3606			page_index->page_data =
3607				(uint8_t *)lun->mode_pages.format_page;
3608			break;
3609		}
3610		case SMS_RIGID_DISK_PAGE: {
3611			struct scsi_rigid_disk_page *rigid_disk_page;
3612			uint32_t sectors_per_cylinder;
3613			uint64_t cylinders;
3614#ifndef	__XSCALE__
3615			int shift;
3616#endif /* !__XSCALE__ */
3617
3618			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3619				panic("invalid subpage value %d",
3620				      page_index->subpage);
3621
3622			/*
3623			 * Rotation rate and sectors per track are set
3624			 * above.  We calculate the cylinders here based on
3625			 * capacity.  Due to the number of heads and
3626			 * sectors per track we're using, smaller arrays
3627			 * may turn out to have 0 cylinders.  Linux and
3628			 * FreeBSD don't pay attention to these mode pages
3629			 * to figure out capacity, but Solaris does.  It
3630			 * seems to deal with 0 cylinders just fine, and
3631			 * works out a fake geometry based on the capacity.
3632			 */
3633			memcpy(&lun->mode_pages.rigid_disk_page[
3634			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
3635			       sizeof(rigid_disk_page_default));
3636			memcpy(&lun->mode_pages.rigid_disk_page[
3637			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
3638			       sizeof(rigid_disk_page_changeable));
3639
3640			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
3641				CTL_DEFAULT_HEADS;
3642
3643			/*
3644			 * The divide method here will be more accurate,
3645			 * probably, but results in floating point being
3646			 * used in the kernel on i386 (__udivdi3()).  On the
3647			 * XScale, though, __udivdi3() is implemented in
3648			 * software.
3649			 *
3650			 * The shift method for cylinder calculation is
3651			 * accurate if sectors_per_cylinder is a power of
3652			 * 2.  Otherwise it might be slightly off -- you
3653			 * might have a bit of a truncation problem.
3654			 */
3655#ifdef	__XSCALE__
3656			cylinders = (lun->be_lun->maxlba + 1) /
3657				sectors_per_cylinder;
3658#else
3659			for (shift = 31; shift > 0; shift--) {
3660				if (sectors_per_cylinder & (1 << shift))
3661					break;
3662			}
3663			cylinders = (lun->be_lun->maxlba + 1) >> shift;
3664#endif
3665
3666			/*
3667			 * We've basically got 3 bytes, or 24 bits for the
3668			 * cylinder size in the mode page.  If we're over,
3669			 * just round down to 2^24.
3670			 */
3671			if (cylinders > 0xffffff)
3672				cylinders = 0xffffff;
3673
3674			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
3675				CTL_PAGE_DEFAULT];
3676			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
3677
3678			if ((value = ctl_get_opt(&lun->be_lun->options,
3679			    "rpm")) != NULL) {
3680				scsi_ulto2b(strtol(value, NULL, 0),
3681				     rigid_disk_page->rotation_rate);
3682			}
3683
3684			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
3685			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
3686			       sizeof(rigid_disk_page_default));
3687			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
3688			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
3689			       sizeof(rigid_disk_page_default));
3690
3691			page_index->page_data =
3692				(uint8_t *)lun->mode_pages.rigid_disk_page;
3693			break;
3694		}
3695		case SMS_CACHING_PAGE: {
3696			struct scsi_caching_page *caching_page;
3697
3698			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3699				panic("invalid subpage value %d",
3700				      page_index->subpage);
3701			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
3702			       &caching_page_default,
3703			       sizeof(caching_page_default));
3704			memcpy(&lun->mode_pages.caching_page[
3705			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
3706			       sizeof(caching_page_changeable));
3707			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
3708			       &caching_page_default,
3709			       sizeof(caching_page_default));
3710			caching_page = &lun->mode_pages.caching_page[
3711			    CTL_PAGE_SAVED];
3712			value = ctl_get_opt(&lun->be_lun->options, "writecache");
3713			if (value != NULL && strcmp(value, "off") == 0)
3714				caching_page->flags1 &= ~SCP_WCE;
3715			value = ctl_get_opt(&lun->be_lun->options, "readcache");
3716			if (value != NULL && strcmp(value, "off") == 0)
3717				caching_page->flags1 |= SCP_RCD;
3718			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
3719			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
3720			       sizeof(caching_page_default));
3721			page_index->page_data =
3722				(uint8_t *)lun->mode_pages.caching_page;
3723			break;
3724		}
3725		case SMS_CONTROL_MODE_PAGE: {
3726			struct scsi_control_page *control_page;
3727
3728			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3729				panic("invalid subpage value %d",
3730				      page_index->subpage);
3731
3732			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
3733			       &control_page_default,
3734			       sizeof(control_page_default));
3735			memcpy(&lun->mode_pages.control_page[
3736			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
3737			       sizeof(control_page_changeable));
3738			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
3739			       &control_page_default,
3740			       sizeof(control_page_default));
3741			control_page = &lun->mode_pages.control_page[
3742			    CTL_PAGE_SAVED];
3743			value = ctl_get_opt(&lun->be_lun->options, "reordering");
3744			if (value != NULL && strcmp(value, "unrestricted") == 0) {
3745				control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
3746				control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
3747			}
3748			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
3749			       &lun->mode_pages.control_page[CTL_PAGE_SAVED],
3750			       sizeof(control_page_default));
3751			page_index->page_data =
3752				(uint8_t *)lun->mode_pages.control_page;
3753			break;
3754
3755		}
3756		case SMS_INFO_EXCEPTIONS_PAGE: {
3757			switch (page_index->subpage) {
3758			case SMS_SUBPAGE_PAGE_0:
3759				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
3760				       &ie_page_default,
3761				       sizeof(ie_page_default));
3762				memcpy(&lun->mode_pages.ie_page[
3763				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
3764				       sizeof(ie_page_changeable));
3765				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
3766				       &ie_page_default,
3767				       sizeof(ie_page_default));
3768				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
3769				       &ie_page_default,
3770				       sizeof(ie_page_default));
3771				page_index->page_data =
3772					(uint8_t *)lun->mode_pages.ie_page;
3773				break;
3774			case 0x02: {
3775				struct ctl_logical_block_provisioning_page *page;
3776
3777				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
3778				       &lbp_page_default,
3779				       sizeof(lbp_page_default));
3780				memcpy(&lun->mode_pages.lbp_page[
3781				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
3782				       sizeof(lbp_page_changeable));
3783				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
3784				       &lbp_page_default,
3785				       sizeof(lbp_page_default));
3786				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
3787				value = ctl_get_opt(&lun->be_lun->options,
3788				    "avail-threshold");
3789				if (value != NULL &&
3790				    ctl_expand_number(value, &ival) == 0) {
3791					page->descr[0].flags |= SLBPPD_ENABLED |
3792					    SLBPPD_ARMING_DEC;
3793					if (lun->be_lun->blocksize)
3794						ival /= lun->be_lun->blocksize;
3795					else
3796						ival /= 512;
3797					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
3798					    page->descr[0].count);
3799				}
3800				value = ctl_get_opt(&lun->be_lun->options,
3801				    "used-threshold");
3802				if (value != NULL &&
3803				    ctl_expand_number(value, &ival) == 0) {
3804					page->descr[1].flags |= SLBPPD_ENABLED |
3805					    SLBPPD_ARMING_INC;
3806					if (lun->be_lun->blocksize)
3807						ival /= lun->be_lun->blocksize;
3808					else
3809						ival /= 512;
3810					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
3811					    page->descr[1].count);
3812				}
3813				value = ctl_get_opt(&lun->be_lun->options,
3814				    "pool-avail-threshold");
3815				if (value != NULL &&
3816				    ctl_expand_number(value, &ival) == 0) {
3817					page->descr[2].flags |= SLBPPD_ENABLED |
3818					    SLBPPD_ARMING_DEC;
3819					if (lun->be_lun->blocksize)
3820						ival /= lun->be_lun->blocksize;
3821					else
3822						ival /= 512;
3823					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
3824					    page->descr[2].count);
3825				}
3826				value = ctl_get_opt(&lun->be_lun->options,
3827				    "pool-used-threshold");
3828				if (value != NULL &&
3829				    ctl_expand_number(value, &ival) == 0) {
3830					page->descr[3].flags |= SLBPPD_ENABLED |
3831					    SLBPPD_ARMING_INC;
3832					if (lun->be_lun->blocksize)
3833						ival /= lun->be_lun->blocksize;
3834					else
3835						ival /= 512;
3836					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
3837					    page->descr[3].count);
3838				}
3839				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
3840				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
3841				       sizeof(lbp_page_default));
3842				page_index->page_data =
3843					(uint8_t *)lun->mode_pages.lbp_page;
3844			}}
3845			break;
3846		}
3847		case SMS_VENDOR_SPECIFIC_PAGE:{
3848			switch (page_index->subpage) {
3849			case DBGCNF_SUBPAGE_CODE: {
3850				struct copan_debugconf_subpage *current_page,
3851							       *saved_page;
3852
3853				memcpy(&lun->mode_pages.debugconf_subpage[
3854				       CTL_PAGE_CURRENT],
3855				       &debugconf_page_default,
3856				       sizeof(debugconf_page_default));
3857				memcpy(&lun->mode_pages.debugconf_subpage[
3858				       CTL_PAGE_CHANGEABLE],
3859				       &debugconf_page_changeable,
3860				       sizeof(debugconf_page_changeable));
3861				memcpy(&lun->mode_pages.debugconf_subpage[
3862				       CTL_PAGE_DEFAULT],
3863				       &debugconf_page_default,
3864				       sizeof(debugconf_page_default));
3865				memcpy(&lun->mode_pages.debugconf_subpage[
3866				       CTL_PAGE_SAVED],
3867				       &debugconf_page_default,
3868				       sizeof(debugconf_page_default));
3869				page_index->page_data =
3870					(uint8_t *)lun->mode_pages.debugconf_subpage;
3871
3872				current_page = (struct copan_debugconf_subpage *)
3873					(page_index->page_data +
3874					 (page_index->page_len *
3875					  CTL_PAGE_CURRENT));
3876				saved_page = (struct copan_debugconf_subpage *)
3877					(page_index->page_data +
3878					 (page_index->page_len *
3879					  CTL_PAGE_SAVED));
3880				break;
3881			}
3882			default:
3883				panic("invalid subpage value %d",
3884				      page_index->subpage);
3885				break;
3886			}
3887   			break;
3888		}
3889		default:
3890			panic("invalid page value %d",
3891			      page_index->page_code & SMPH_PC_MASK);
3892			break;
3893    	}
3894	}
3895
3896	return (CTL_RETVAL_COMPLETE);
3897}
3898
3899static int
3900ctl_init_log_page_index(struct ctl_lun *lun)
3901{
3902	struct ctl_page_index *page_index;
3903	int i, j, k, prev;
3904
3905	memcpy(&lun->log_pages.index, log_page_index_template,
3906	       sizeof(log_page_index_template));
3907
3908	prev = -1;
3909	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
3910
3911		page_index = &lun->log_pages.index[i];
3912		/*
3913		 * If this is a disk-only mode page, there's no point in
3914		 * setting it up.  For some pages, we have to have some
3915		 * basic information about the disk in order to calculate the
3916		 * mode page data.
3917		 */
3918		if ((lun->be_lun->lun_type != T_DIRECT)
3919		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3920			continue;
3921
3922		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
3923		     lun->backend->lun_attr == NULL)
3924			continue;
3925
3926		if (page_index->page_code != prev) {
3927			lun->log_pages.pages_page[j] = page_index->page_code;
3928			prev = page_index->page_code;
3929			j++;
3930		}
3931		lun->log_pages.subpages_page[k*2] = page_index->page_code;
3932		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
3933		k++;
3934	}
3935	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
3936	lun->log_pages.index[0].page_len = j;
3937	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
3938	lun->log_pages.index[1].page_len = k * 2;
3939	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
3940	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
3941	lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
3942	lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
3943
3944	return (CTL_RETVAL_COMPLETE);
3945}
3946
3947static int
3948hex2bin(const char *str, uint8_t *buf, int buf_size)
3949{
3950	int i;
3951	u_char c;
3952
3953	memset(buf, 0, buf_size);
3954	while (isspace(str[0]))
3955		str++;
3956	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
3957		str += 2;
3958	buf_size *= 2;
3959	for (i = 0; str[i] != 0 && i < buf_size; i++) {
3960		c = str[i];
3961		if (isdigit(c))
3962			c -= '0';
3963		else if (isalpha(c))
3964			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
3965		else
3966			break;
3967		if (c >= 16)
3968			break;
3969		if ((i & 1) == 0)
3970			buf[i / 2] |= (c << 4);
3971		else
3972			buf[i / 2] |= c;
3973	}
3974	return ((i + 1) / 2);
3975}
3976
3977/*
3978 * LUN allocation.
3979 *
3980 * Requirements:
3981 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
3982 *   wants us to allocate the LUN and he can block.
3983 * - ctl_softc is always set
3984 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
3985 *
3986 * Returns 0 for success, non-zero (errno) for failure.
3987 */
3988static int
3989ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
3990	      struct ctl_be_lun *const be_lun)
3991{
3992	struct ctl_lun *nlun, *lun;
3993	struct scsi_vpd_id_descriptor *desc;
3994	struct scsi_vpd_id_t10 *t10id;
3995	const char *eui, *naa, *scsiname, *vendor;
3996	int lun_number, i, lun_malloced;
3997	int devidlen, idlen1, idlen2 = 0, len;
3998
3999	if (be_lun == NULL)
4000		return (EINVAL);
4001
4002	/*
4003	 * We currently only support Direct Access or Processor LUN types.
4004	 */
4005	switch (be_lun->lun_type) {
4006	case T_DIRECT:
4007		break;
4008	case T_PROCESSOR:
4009		break;
4010	case T_SEQUENTIAL:
4011	case T_CHANGER:
4012	default:
4013		be_lun->lun_config_status(be_lun->be_lun,
4014					  CTL_LUN_CONFIG_FAILURE);
4015		break;
4016	}
4017	if (ctl_lun == NULL) {
4018		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4019		lun_malloced = 1;
4020	} else {
4021		lun_malloced = 0;
4022		lun = ctl_lun;
4023	}
4024
4025	memset(lun, 0, sizeof(*lun));
4026	if (lun_malloced)
4027		lun->flags = CTL_LUN_MALLOCED;
4028
4029	/* Generate LUN ID. */
4030	devidlen = max(CTL_DEVID_MIN_LEN,
4031	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4032	idlen1 = sizeof(*t10id) + devidlen;
4033	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4034	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4035	if (scsiname != NULL) {
4036		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4037		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4038	}
4039	eui = ctl_get_opt(&be_lun->options, "eui");
4040	if (eui != NULL) {
4041		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4042	}
4043	naa = ctl_get_opt(&be_lun->options, "naa");
4044	if (naa != NULL) {
4045		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4046	}
4047	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4048	    M_CTL, M_WAITOK | M_ZERO);
4049	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4050	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4051	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4052	desc->length = idlen1;
4053	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4054	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4055	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4056		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4057	} else {
4058		strncpy(t10id->vendor, vendor,
4059		    min(sizeof(t10id->vendor), strlen(vendor)));
4060	}
4061	strncpy((char *)t10id->vendor_spec_id,
4062	    (char *)be_lun->device_id, devidlen);
4063	if (scsiname != NULL) {
4064		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4065		    desc->length);
4066		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4067		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4068		    SVPD_ID_TYPE_SCSI_NAME;
4069		desc->length = idlen2;
4070		strlcpy(desc->identifier, scsiname, idlen2);
4071	}
4072	if (eui != NULL) {
4073		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4074		    desc->length);
4075		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4076		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4077		    SVPD_ID_TYPE_EUI64;
4078		desc->length = hex2bin(eui, desc->identifier, 16);
4079		desc->length = desc->length > 12 ? 16 :
4080		    (desc->length > 8 ? 12 : 8);
4081		len -= 16 - desc->length;
4082	}
4083	if (naa != NULL) {
4084		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4085		    desc->length);
4086		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4087		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4088		    SVPD_ID_TYPE_NAA;
4089		desc->length = hex2bin(naa, desc->identifier, 16);
4090		desc->length = desc->length > 8 ? 16 : 8;
4091		len -= 16 - desc->length;
4092	}
4093	lun->lun_devid->len = len;
4094
4095	mtx_lock(&ctl_softc->ctl_lock);
4096	/*
4097	 * See if the caller requested a particular LUN number.  If so, see
4098	 * if it is available.  Otherwise, allocate the first available LUN.
4099	 */
4100	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4101		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4102		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4103			mtx_unlock(&ctl_softc->ctl_lock);
4104			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4105				printf("ctl: requested LUN ID %d is higher "
4106				       "than CTL_MAX_LUNS - 1 (%d)\n",
4107				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4108			} else {
4109				/*
4110				 * XXX KDM return an error, or just assign
4111				 * another LUN ID in this case??
4112				 */
4113				printf("ctl: requested LUN ID %d is already "
4114				       "in use\n", be_lun->req_lun_id);
4115			}
4116			if (lun->flags & CTL_LUN_MALLOCED)
4117				free(lun, M_CTL);
4118			be_lun->lun_config_status(be_lun->be_lun,
4119						  CTL_LUN_CONFIG_FAILURE);
4120			return (ENOSPC);
4121		}
4122		lun_number = be_lun->req_lun_id;
4123	} else {
4124		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4125		if (lun_number == -1) {
4126			mtx_unlock(&ctl_softc->ctl_lock);
4127			printf("ctl: can't allocate LUN, out of LUNs\n");
4128			if (lun->flags & CTL_LUN_MALLOCED)
4129				free(lun, M_CTL);
4130			be_lun->lun_config_status(be_lun->be_lun,
4131						  CTL_LUN_CONFIG_FAILURE);
4132			return (ENOSPC);
4133		}
4134	}
4135	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4136
4137	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4138	lun->lun = lun_number;
4139	lun->be_lun = be_lun;
4140	/*
4141	 * The processor LUN is always enabled.  Disk LUNs come on line
4142	 * disabled, and must be enabled by the backend.
4143	 */
4144	lun->flags |= CTL_LUN_DISABLED;
4145	lun->backend = be_lun->be;
4146	be_lun->ctl_lun = lun;
4147	be_lun->lun_id = lun_number;
4148	atomic_add_int(&be_lun->be->num_luns, 1);
4149	if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4150		lun->flags |= CTL_LUN_OFFLINE;
4151
4152	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4153		lun->flags |= CTL_LUN_STOPPED;
4154
4155	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4156		lun->flags |= CTL_LUN_INOPERABLE;
4157
4158	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4159		lun->flags |= CTL_LUN_PRIMARY_SC;
4160
4161	lun->ctl_softc = ctl_softc;
4162#ifdef CTL_TIME_IO
4163	lun->last_busy = getsbinuptime();
4164#endif
4165	TAILQ_INIT(&lun->ooa_queue);
4166	TAILQ_INIT(&lun->blocked_queue);
4167	STAILQ_INIT(&lun->error_list);
4168	ctl_tpc_lun_init(lun);
4169
4170	/*
4171	 * Initialize the mode and log page index.
4172	 */
4173	ctl_init_page_index(lun);
4174	ctl_init_log_page_index(lun);
4175
4176	/*
4177	 * Now, before we insert this lun on the lun list, set the lun
4178	 * inventory changed UA for all other luns.
4179	 */
4180	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4181		mtx_lock(&nlun->lun_lock);
4182		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4183		mtx_unlock(&nlun->lun_lock);
4184	}
4185
4186	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4187
4188	ctl_softc->ctl_luns[lun_number] = lun;
4189
4190	ctl_softc->num_luns++;
4191
4192	/* Setup statistics gathering */
4193	lun->stats.device_type = be_lun->lun_type;
4194	lun->stats.lun_number = lun_number;
4195	if (lun->stats.device_type == T_DIRECT)
4196		lun->stats.blocksize = be_lun->blocksize;
4197	else
4198		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4199	for (i = 0;i < CTL_MAX_PORTS;i++)
4200		lun->stats.ports[i].targ_port = i;
4201
4202	mtx_unlock(&ctl_softc->ctl_lock);
4203
4204	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4205	return (0);
4206}
4207
4208/*
4209 * Delete a LUN.
4210 * Assumptions:
4211 * - LUN has already been marked invalid and any pending I/O has been taken
4212 *   care of.
4213 */
4214static int
4215ctl_free_lun(struct ctl_lun *lun)
4216{
4217	struct ctl_softc *softc;
4218	struct ctl_lun *nlun;
4219	int i;
4220
4221	softc = lun->ctl_softc;
4222
4223	mtx_assert(&softc->ctl_lock, MA_OWNED);
4224
4225	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4226
4227	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4228
4229	softc->ctl_luns[lun->lun] = NULL;
4230
4231	if (!TAILQ_EMPTY(&lun->ooa_queue))
4232		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4233
4234	softc->num_luns--;
4235
4236	/*
4237	 * Tell the backend to free resources, if this LUN has a backend.
4238	 */
4239	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4240	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4241
4242	ctl_tpc_lun_shutdown(lun);
4243	mtx_destroy(&lun->lun_lock);
4244	free(lun->lun_devid, M_CTL);
4245	for (i = 0; i < CTL_MAX_PORTS; i++)
4246		free(lun->pending_ua[i], M_CTL);
4247	for (i = 0; i < 2 * CTL_MAX_PORTS; i++)
4248		free(lun->pr_keys[i], M_CTL);
4249	free(lun->write_buffer, M_CTL);
4250	if (lun->flags & CTL_LUN_MALLOCED)
4251		free(lun, M_CTL);
4252
4253	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4254		mtx_lock(&nlun->lun_lock);
4255		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4256		mtx_unlock(&nlun->lun_lock);
4257	}
4258
4259	return (0);
4260}
4261
4262static void
4263ctl_create_lun(struct ctl_be_lun *be_lun)
4264{
4265	struct ctl_softc *softc;
4266
4267	softc = control_softc;
4268
4269	/*
4270	 * ctl_alloc_lun() should handle all potential failure cases.
4271	 */
4272	ctl_alloc_lun(softc, NULL, be_lun);
4273}
4274
4275int
4276ctl_add_lun(struct ctl_be_lun *be_lun)
4277{
4278	struct ctl_softc *softc = control_softc;
4279
4280	mtx_lock(&softc->ctl_lock);
4281	STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4282	mtx_unlock(&softc->ctl_lock);
4283	wakeup(&softc->pending_lun_queue);
4284
4285	return (0);
4286}
4287
4288int
4289ctl_enable_lun(struct ctl_be_lun *be_lun)
4290{
4291	struct ctl_softc *softc;
4292	struct ctl_port *port, *nport;
4293	struct ctl_lun *lun;
4294	int retval;
4295
4296	lun = (struct ctl_lun *)be_lun->ctl_lun;
4297	softc = lun->ctl_softc;
4298
4299	mtx_lock(&softc->ctl_lock);
4300	mtx_lock(&lun->lun_lock);
4301	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4302		/*
4303		 * eh?  Why did we get called if the LUN is already
4304		 * enabled?
4305		 */
4306		mtx_unlock(&lun->lun_lock);
4307		mtx_unlock(&softc->ctl_lock);
4308		return (0);
4309	}
4310	lun->flags &= ~CTL_LUN_DISABLED;
4311	mtx_unlock(&lun->lun_lock);
4312
4313	for (port = STAILQ_FIRST(&softc->port_list); port != NULL; port = nport) {
4314		nport = STAILQ_NEXT(port, links);
4315		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4316		    port->lun_map != NULL || port->lun_enable == NULL)
4317			continue;
4318
4319		/*
4320		 * Drop the lock while we call the FETD's enable routine.
4321		 * This can lead to a callback into CTL (at least in the
4322		 * case of the internal initiator frontend.
4323		 */
4324		mtx_unlock(&softc->ctl_lock);
4325		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4326		mtx_lock(&softc->ctl_lock);
4327		if (retval != 0) {
4328			printf("%s: FETD %s port %d returned error "
4329			       "%d for lun_enable on lun %jd\n",
4330			       __func__, port->port_name, port->targ_port,
4331			       retval, (intmax_t)lun->lun);
4332		}
4333	}
4334
4335	mtx_unlock(&softc->ctl_lock);
4336
4337	return (0);
4338}
4339
4340int
4341ctl_disable_lun(struct ctl_be_lun *be_lun)
4342{
4343	struct ctl_softc *softc;
4344	struct ctl_port *port;
4345	struct ctl_lun *lun;
4346	int retval;
4347
4348	lun = (struct ctl_lun *)be_lun->ctl_lun;
4349	softc = lun->ctl_softc;
4350
4351	mtx_lock(&softc->ctl_lock);
4352	mtx_lock(&lun->lun_lock);
4353	if (lun->flags & CTL_LUN_DISABLED) {
4354		mtx_unlock(&lun->lun_lock);
4355		mtx_unlock(&softc->ctl_lock);
4356		return (0);
4357	}
4358	lun->flags |= CTL_LUN_DISABLED;
4359	mtx_unlock(&lun->lun_lock);
4360
4361	STAILQ_FOREACH(port, &softc->port_list, links) {
4362		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4363		    port->lun_map != NULL || port->lun_disable == NULL)
4364			continue;
4365
4366		/*
4367		 * Drop the lock before we call the frontend's disable
4368		 * routine, to avoid lock order reversals.
4369		 *
4370		 * XXX KDM what happens if the frontend list changes while
4371		 * we're traversing it?  It's unlikely, but should be handled.
4372		 */
4373		mtx_unlock(&softc->ctl_lock);
4374		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4375		mtx_lock(&softc->ctl_lock);
4376		if (retval != 0) {
4377			printf("%s: FETD %s port %d returned error "
4378			       "%d for lun_disable on lun %jd\n",
4379			       __func__, port->port_name, port->targ_port,
4380			       retval, (intmax_t)lun->lun);
4381		}
4382	}
4383
4384	mtx_unlock(&softc->ctl_lock);
4385
4386	return (0);
4387}
4388
4389int
4390ctl_start_lun(struct ctl_be_lun *be_lun)
4391{
4392	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4393
4394	mtx_lock(&lun->lun_lock);
4395	lun->flags &= ~CTL_LUN_STOPPED;
4396	mtx_unlock(&lun->lun_lock);
4397	return (0);
4398}
4399
4400int
4401ctl_stop_lun(struct ctl_be_lun *be_lun)
4402{
4403	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4404
4405	mtx_lock(&lun->lun_lock);
4406	lun->flags |= CTL_LUN_STOPPED;
4407	mtx_unlock(&lun->lun_lock);
4408	return (0);
4409}
4410
4411int
4412ctl_lun_offline(struct ctl_be_lun *be_lun)
4413{
4414	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4415
4416	mtx_lock(&lun->lun_lock);
4417	lun->flags |= CTL_LUN_OFFLINE;
4418	mtx_unlock(&lun->lun_lock);
4419	return (0);
4420}
4421
4422int
4423ctl_lun_online(struct ctl_be_lun *be_lun)
4424{
4425	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4426
4427	mtx_lock(&lun->lun_lock);
4428	lun->flags &= ~CTL_LUN_OFFLINE;
4429	mtx_unlock(&lun->lun_lock);
4430	return (0);
4431}
4432
4433int
4434ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4435{
4436	struct ctl_softc *softc;
4437	struct ctl_lun *lun;
4438
4439	lun = (struct ctl_lun *)be_lun->ctl_lun;
4440	softc = lun->ctl_softc;
4441
4442	mtx_lock(&lun->lun_lock);
4443
4444	/*
4445	 * The LUN needs to be disabled before it can be marked invalid.
4446	 */
4447	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4448		mtx_unlock(&lun->lun_lock);
4449		return (-1);
4450	}
4451	/*
4452	 * Mark the LUN invalid.
4453	 */
4454	lun->flags |= CTL_LUN_INVALID;
4455
4456	/*
4457	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4458	 * If we have something in the OOA queue, we'll free it when the
4459	 * last I/O completes.
4460	 */
4461	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4462		mtx_unlock(&lun->lun_lock);
4463		mtx_lock(&softc->ctl_lock);
4464		ctl_free_lun(lun);
4465		mtx_unlock(&softc->ctl_lock);
4466	} else
4467		mtx_unlock(&lun->lun_lock);
4468
4469	return (0);
4470}
4471
4472int
4473ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4474{
4475	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4476
4477	mtx_lock(&lun->lun_lock);
4478	lun->flags |= CTL_LUN_INOPERABLE;
4479	mtx_unlock(&lun->lun_lock);
4480	return (0);
4481}
4482
4483int
4484ctl_lun_operable(struct ctl_be_lun *be_lun)
4485{
4486	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4487
4488	mtx_lock(&lun->lun_lock);
4489	lun->flags &= ~CTL_LUN_INOPERABLE;
4490	mtx_unlock(&lun->lun_lock);
4491	return (0);
4492}
4493
4494void
4495ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4496{
4497	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4498
4499	mtx_lock(&lun->lun_lock);
4500	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGED);
4501	mtx_unlock(&lun->lun_lock);
4502}
4503
4504/*
4505 * Backend "memory move is complete" callback for requests that never
4506 * make it down to say RAIDCore's configuration code.
4507 */
4508int
4509ctl_config_move_done(union ctl_io *io)
4510{
4511	int retval;
4512
4513	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4514	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4515	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
4516
4517	if ((io->io_hdr.port_status != 0) &&
4518	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4519	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4520		/*
4521		 * For hardware error sense keys, the sense key
4522		 * specific value is defined to be a retry count,
4523		 * but we use it to pass back an internal FETD
4524		 * error code.  XXX KDM  Hopefully the FETD is only
4525		 * using 16 bits for an error code, since that's
4526		 * all the space we have in the sks field.
4527		 */
4528		ctl_set_internal_failure(&io->scsiio,
4529					 /*sks_valid*/ 1,
4530					 /*retry_count*/
4531					 io->io_hdr.port_status);
4532	}
4533
4534	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
4535	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4536	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
4537	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
4538		/*
4539		 * XXX KDM just assuming a single pointer here, and not a
4540		 * S/G list.  If we start using S/G lists for config data,
4541		 * we'll need to know how to clean them up here as well.
4542		 */
4543		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4544			free(io->scsiio.kern_data_ptr, M_CTL);
4545		ctl_done(io);
4546		retval = CTL_RETVAL_COMPLETE;
4547	} else {
4548		/*
4549		 * XXX KDM now we need to continue data movement.  Some
4550		 * options:
4551		 * - call ctl_scsiio() again?  We don't do this for data
4552		 *   writes, because for those at least we know ahead of
4553		 *   time where the write will go and how long it is.  For
4554		 *   config writes, though, that information is largely
4555		 *   contained within the write itself, thus we need to
4556		 *   parse out the data again.
4557		 *
4558		 * - Call some other function once the data is in?
4559		 */
4560		if (ctl_debug & CTL_DEBUG_CDB_DATA)
4561			ctl_data_print(io);
4562
4563		/*
4564		 * XXX KDM call ctl_scsiio() again for now, and check flag
4565		 * bits to see whether we're allocated or not.
4566		 */
4567		retval = ctl_scsiio(&io->scsiio);
4568	}
4569	return (retval);
4570}
4571
4572/*
4573 * This gets called by a backend driver when it is done with a
4574 * data_submit method.
4575 */
4576void
4577ctl_data_submit_done(union ctl_io *io)
4578{
4579	/*
4580	 * If the IO_CONT flag is set, we need to call the supplied
4581	 * function to continue processing the I/O, instead of completing
4582	 * the I/O just yet.
4583	 *
4584	 * If there is an error, though, we don't want to keep processing.
4585	 * Instead, just send status back to the initiator.
4586	 */
4587	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
4588	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
4589	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4590	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4591		io->scsiio.io_cont(io);
4592		return;
4593	}
4594	ctl_done(io);
4595}
4596
4597/*
4598 * This gets called by a backend driver when it is done with a
4599 * configuration write.
4600 */
4601void
4602ctl_config_write_done(union ctl_io *io)
4603{
4604	uint8_t *buf;
4605
4606	/*
4607	 * If the IO_CONT flag is set, we need to call the supplied
4608	 * function to continue processing the I/O, instead of completing
4609	 * the I/O just yet.
4610	 *
4611	 * If there is an error, though, we don't want to keep processing.
4612	 * Instead, just send status back to the initiator.
4613	 */
4614	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
4615	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
4616	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4617	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4618		io->scsiio.io_cont(io);
4619		return;
4620	}
4621	/*
4622	 * Since a configuration write can be done for commands that actually
4623	 * have data allocated, like write buffer, and commands that have
4624	 * no data, like start/stop unit, we need to check here.
4625	 */
4626	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4627		buf = io->scsiio.kern_data_ptr;
4628	else
4629		buf = NULL;
4630	ctl_done(io);
4631	if (buf)
4632		free(buf, M_CTL);
4633}
4634
4635void
4636ctl_config_read_done(union ctl_io *io)
4637{
4638	uint8_t *buf;
4639
4640	/*
4641	 * If there is some error -- we are done, skip data transfer.
4642	 */
4643	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
4644	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4645	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
4646		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4647			buf = io->scsiio.kern_data_ptr;
4648		else
4649			buf = NULL;
4650		ctl_done(io);
4651		if (buf)
4652			free(buf, M_CTL);
4653		return;
4654	}
4655
4656	/*
4657	 * If the IO_CONT flag is set, we need to call the supplied
4658	 * function to continue processing the I/O, instead of completing
4659	 * the I/O just yet.
4660	 */
4661	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
4662		io->scsiio.io_cont(io);
4663		return;
4664	}
4665
4666	ctl_datamove(io);
4667}
4668
4669/*
4670 * SCSI release command.
4671 */
4672int
4673ctl_scsi_release(struct ctl_scsiio *ctsio)
4674{
4675	int length, longid, thirdparty_id, resv_id;
4676	struct ctl_lun *lun;
4677	uint32_t residx;
4678
4679	length = 0;
4680	resv_id = 0;
4681
4682	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
4683
4684	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
4685	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
4686
4687	switch (ctsio->cdb[0]) {
4688	case RELEASE_10: {
4689		struct scsi_release_10 *cdb;
4690
4691		cdb = (struct scsi_release_10 *)ctsio->cdb;
4692
4693		if (cdb->byte2 & SR10_LONGID)
4694			longid = 1;
4695		else
4696			thirdparty_id = cdb->thirdparty_id;
4697
4698		resv_id = cdb->resv_id;
4699		length = scsi_2btoul(cdb->length);
4700		break;
4701	}
4702	}
4703
4704
4705	/*
4706	 * XXX KDM right now, we only support LUN reservation.  We don't
4707	 * support 3rd party reservations, or extent reservations, which
4708	 * might actually need the parameter list.  If we've gotten this
4709	 * far, we've got a LUN reservation.  Anything else got kicked out
4710	 * above.  So, according to SPC, ignore the length.
4711	 */
4712	length = 0;
4713
4714	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
4715	 && (length > 0)) {
4716		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
4717		ctsio->kern_data_len = length;
4718		ctsio->kern_total_len = length;
4719		ctsio->kern_data_resid = 0;
4720		ctsio->kern_rel_offset = 0;
4721		ctsio->kern_sg_entries = 0;
4722		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
4723		ctsio->be_move_done = ctl_config_move_done;
4724		ctl_datamove((union ctl_io *)ctsio);
4725
4726		return (CTL_RETVAL_COMPLETE);
4727	}
4728
4729	if (length > 0)
4730		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
4731
4732	mtx_lock(&lun->lun_lock);
4733
4734	/*
4735	 * According to SPC, it is not an error for an intiator to attempt
4736	 * to release a reservation on a LUN that isn't reserved, or that
4737	 * is reserved by another initiator.  The reservation can only be
4738	 * released, though, by the initiator who made it or by one of
4739	 * several reset type events.
4740	 */
4741	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
4742			lun->flags &= ~CTL_LUN_RESERVED;
4743
4744	mtx_unlock(&lun->lun_lock);
4745
4746	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
4747		free(ctsio->kern_data_ptr, M_CTL);
4748		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
4749	}
4750
4751	ctl_set_success(ctsio);
4752	ctl_done((union ctl_io *)ctsio);
4753	return (CTL_RETVAL_COMPLETE);
4754}
4755
4756int
4757ctl_scsi_reserve(struct ctl_scsiio *ctsio)
4758{
4759	int extent, thirdparty, longid;
4760	int resv_id, length;
4761	uint64_t thirdparty_id;
4762	struct ctl_lun *lun;
4763	uint32_t residx;
4764
4765	extent = 0;
4766	thirdparty = 0;
4767	longid = 0;
4768	resv_id = 0;
4769	length = 0;
4770	thirdparty_id = 0;
4771
4772	CTL_DEBUG_PRINT(("ctl_reserve\n"));
4773
4774	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
4775	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
4776
4777	switch (ctsio->cdb[0]) {
4778	case RESERVE_10: {
4779		struct scsi_reserve_10 *cdb;
4780
4781		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
4782
4783		if (cdb->byte2 & SR10_LONGID)
4784			longid = 1;
4785		else
4786			thirdparty_id = cdb->thirdparty_id;
4787
4788		resv_id = cdb->resv_id;
4789		length = scsi_2btoul(cdb->length);
4790		break;
4791	}
4792	}
4793
4794	/*
4795	 * XXX KDM right now, we only support LUN reservation.  We don't
4796	 * support 3rd party reservations, or extent reservations, which
4797	 * might actually need the parameter list.  If we've gotten this
4798	 * far, we've got a LUN reservation.  Anything else got kicked out
4799	 * above.  So, according to SPC, ignore the length.
4800	 */
4801	length = 0;
4802
4803	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
4804	 && (length > 0)) {
4805		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
4806		ctsio->kern_data_len = length;
4807		ctsio->kern_total_len = length;
4808		ctsio->kern_data_resid = 0;
4809		ctsio->kern_rel_offset = 0;
4810		ctsio->kern_sg_entries = 0;
4811		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
4812		ctsio->be_move_done = ctl_config_move_done;
4813		ctl_datamove((union ctl_io *)ctsio);
4814
4815		return (CTL_RETVAL_COMPLETE);
4816	}
4817
4818	if (length > 0)
4819		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
4820
4821	mtx_lock(&lun->lun_lock);
4822	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
4823		ctl_set_reservation_conflict(ctsio);
4824		goto bailout;
4825	}
4826
4827	lun->flags |= CTL_LUN_RESERVED;
4828	lun->res_idx = residx;
4829
4830	ctl_set_success(ctsio);
4831
4832bailout:
4833	mtx_unlock(&lun->lun_lock);
4834
4835	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
4836		free(ctsio->kern_data_ptr, M_CTL);
4837		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
4838	}
4839
4840	ctl_done((union ctl_io *)ctsio);
4841	return (CTL_RETVAL_COMPLETE);
4842}
4843
4844int
4845ctl_start_stop(struct ctl_scsiio *ctsio)
4846{
4847	struct scsi_start_stop_unit *cdb;
4848	struct ctl_lun *lun;
4849	int retval;
4850
4851	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
4852
4853	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
4854	retval = 0;
4855
4856	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
4857
4858	/*
4859	 * XXX KDM
4860	 * We don't support the immediate bit on a stop unit.  In order to
4861	 * do that, we would need to code up a way to know that a stop is
4862	 * pending, and hold off any new commands until it completes, one
4863	 * way or another.  Then we could accept or reject those commands
4864	 * depending on its status.  We would almost need to do the reverse
4865	 * of what we do below for an immediate start -- return the copy of
4866	 * the ctl_io to the FETD with status to send to the host (and to
4867	 * free the copy!) and then free the original I/O once the stop
4868	 * actually completes.  That way, the OOA queue mechanism can work
4869	 * to block commands that shouldn't proceed.  Another alternative
4870	 * would be to put the copy in the queue in place of the original,
4871	 * and return the original back to the caller.  That could be
4872	 * slightly safer..
4873	 */
4874	if ((cdb->byte2 & SSS_IMMED)
4875	 && ((cdb->how & SSS_START) == 0)) {
4876		ctl_set_invalid_field(ctsio,
4877				      /*sks_valid*/ 1,
4878				      /*command*/ 1,
4879				      /*field*/ 1,
4880				      /*bit_valid*/ 1,
4881				      /*bit*/ 0);
4882		ctl_done((union ctl_io *)ctsio);
4883		return (CTL_RETVAL_COMPLETE);
4884	}
4885
4886	if ((lun->flags & CTL_LUN_PR_RESERVED)
4887	 && ((cdb->how & SSS_START)==0)) {
4888		uint32_t residx;
4889
4890		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
4891		if (ctl_get_prkey(lun, residx) == 0
4892		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
4893
4894			ctl_set_reservation_conflict(ctsio);
4895			ctl_done((union ctl_io *)ctsio);
4896			return (CTL_RETVAL_COMPLETE);
4897		}
4898	}
4899
4900	/*
4901	 * If there is no backend on this device, we can't start or stop
4902	 * it.  In theory we shouldn't get any start/stop commands in the
4903	 * first place at this level if the LUN doesn't have a backend.
4904	 * That should get stopped by the command decode code.
4905	 */
4906	if (lun->backend == NULL) {
4907		ctl_set_invalid_opcode(ctsio);
4908		ctl_done((union ctl_io *)ctsio);
4909		return (CTL_RETVAL_COMPLETE);
4910	}
4911
4912	/*
4913	 * XXX KDM Copan-specific offline behavior.
4914	 * Figure out a reasonable way to port this?
4915	 */
4916#ifdef NEEDTOPORT
4917	mtx_lock(&lun->lun_lock);
4918
4919	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
4920	 && (lun->flags & CTL_LUN_OFFLINE)) {
4921		/*
4922		 * If the LUN is offline, and the on/offline bit isn't set,
4923		 * reject the start or stop.  Otherwise, let it through.
4924		 */
4925		mtx_unlock(&lun->lun_lock);
4926		ctl_set_lun_not_ready(ctsio);
4927		ctl_done((union ctl_io *)ctsio);
4928	} else {
4929		mtx_unlock(&lun->lun_lock);
4930#endif /* NEEDTOPORT */
4931		/*
4932		 * This could be a start or a stop when we're online,
4933		 * or a stop/offline or start/online.  A start or stop when
4934		 * we're offline is covered in the case above.
4935		 */
4936		/*
4937		 * In the non-immediate case, we send the request to
4938		 * the backend and return status to the user when
4939		 * it is done.
4940		 *
4941		 * In the immediate case, we allocate a new ctl_io
4942		 * to hold a copy of the request, and send that to
4943		 * the backend.  We then set good status on the
4944		 * user's request and return it immediately.
4945		 */
4946		if (cdb->byte2 & SSS_IMMED) {
4947			union ctl_io *new_io;
4948
4949			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
4950			ctl_copy_io((union ctl_io *)ctsio, new_io);
4951			retval = lun->backend->config_write(new_io);
4952			ctl_set_success(ctsio);
4953			ctl_done((union ctl_io *)ctsio);
4954		} else {
4955			retval = lun->backend->config_write(
4956				(union ctl_io *)ctsio);
4957		}
4958#ifdef NEEDTOPORT
4959	}
4960#endif
4961	return (retval);
4962}
4963
4964/*
4965 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
4966 * we don't really do anything with the LBA and length fields if the user
4967 * passes them in.  Instead we'll just flush out the cache for the entire
4968 * LUN.
4969 */
4970int
4971ctl_sync_cache(struct ctl_scsiio *ctsio)
4972{
4973	struct ctl_lun *lun;
4974	struct ctl_softc *softc;
4975	struct ctl_lba_len_flags *lbalen;
4976	uint64_t starting_lba;
4977	uint32_t block_count;
4978	int retval;
4979	uint8_t byte2;
4980
4981	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
4982
4983	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
4984	softc = lun->ctl_softc;
4985	retval = 0;
4986
4987	switch (ctsio->cdb[0]) {
4988	case SYNCHRONIZE_CACHE: {
4989		struct scsi_sync_cache *cdb;
4990		cdb = (struct scsi_sync_cache *)ctsio->cdb;
4991
4992		starting_lba = scsi_4btoul(cdb->begin_lba);
4993		block_count = scsi_2btoul(cdb->lb_count);
4994		byte2 = cdb->byte2;
4995		break;
4996	}
4997	case SYNCHRONIZE_CACHE_16: {
4998		struct scsi_sync_cache_16 *cdb;
4999		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5000
5001		starting_lba = scsi_8btou64(cdb->begin_lba);
5002		block_count = scsi_4btoul(cdb->lb_count);
5003		byte2 = cdb->byte2;
5004		break;
5005	}
5006	default:
5007		ctl_set_invalid_opcode(ctsio);
5008		ctl_done((union ctl_io *)ctsio);
5009		goto bailout;
5010		break; /* NOTREACHED */
5011	}
5012
5013	/*
5014	 * We check the LBA and length, but don't do anything with them.
5015	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5016	 * get flushed.  This check will just help satisfy anyone who wants
5017	 * to see an error for an out of range LBA.
5018	 */
5019	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5020		ctl_set_lba_out_of_range(ctsio);
5021		ctl_done((union ctl_io *)ctsio);
5022		goto bailout;
5023	}
5024
5025	/*
5026	 * If this LUN has no backend, we can't flush the cache anyway.
5027	 */
5028	if (lun->backend == NULL) {
5029		ctl_set_invalid_opcode(ctsio);
5030		ctl_done((union ctl_io *)ctsio);
5031		goto bailout;
5032	}
5033
5034	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5035	lbalen->lba = starting_lba;
5036	lbalen->len = block_count;
5037	lbalen->flags = byte2;
5038
5039	/*
5040	 * Check to see whether we're configured to send the SYNCHRONIZE
5041	 * CACHE command directly to the back end.
5042	 */
5043	mtx_lock(&lun->lun_lock);
5044	if ((softc->flags & CTL_FLAG_REAL_SYNC)
5045	 && (++(lun->sync_count) >= lun->sync_interval)) {
5046		lun->sync_count = 0;
5047		mtx_unlock(&lun->lun_lock);
5048		retval = lun->backend->config_write((union ctl_io *)ctsio);
5049	} else {
5050		mtx_unlock(&lun->lun_lock);
5051		ctl_set_success(ctsio);
5052		ctl_done((union ctl_io *)ctsio);
5053	}
5054
5055bailout:
5056
5057	return (retval);
5058}
5059
5060int
5061ctl_format(struct ctl_scsiio *ctsio)
5062{
5063	struct scsi_format *cdb;
5064	struct ctl_lun *lun;
5065	int length, defect_list_len;
5066
5067	CTL_DEBUG_PRINT(("ctl_format\n"));
5068
5069	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5070
5071	cdb = (struct scsi_format *)ctsio->cdb;
5072
5073	length = 0;
5074	if (cdb->byte2 & SF_FMTDATA) {
5075		if (cdb->byte2 & SF_LONGLIST)
5076			length = sizeof(struct scsi_format_header_long);
5077		else
5078			length = sizeof(struct scsi_format_header_short);
5079	}
5080
5081	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5082	 && (length > 0)) {
5083		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5084		ctsio->kern_data_len = length;
5085		ctsio->kern_total_len = length;
5086		ctsio->kern_data_resid = 0;
5087		ctsio->kern_rel_offset = 0;
5088		ctsio->kern_sg_entries = 0;
5089		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5090		ctsio->be_move_done = ctl_config_move_done;
5091		ctl_datamove((union ctl_io *)ctsio);
5092
5093		return (CTL_RETVAL_COMPLETE);
5094	}
5095
5096	defect_list_len = 0;
5097
5098	if (cdb->byte2 & SF_FMTDATA) {
5099		if (cdb->byte2 & SF_LONGLIST) {
5100			struct scsi_format_header_long *header;
5101
5102			header = (struct scsi_format_header_long *)
5103				ctsio->kern_data_ptr;
5104
5105			defect_list_len = scsi_4btoul(header->defect_list_len);
5106			if (defect_list_len != 0) {
5107				ctl_set_invalid_field(ctsio,
5108						      /*sks_valid*/ 1,
5109						      /*command*/ 0,
5110						      /*field*/ 2,
5111						      /*bit_valid*/ 0,
5112						      /*bit*/ 0);
5113				goto bailout;
5114			}
5115		} else {
5116			struct scsi_format_header_short *header;
5117
5118			header = (struct scsi_format_header_short *)
5119				ctsio->kern_data_ptr;
5120
5121			defect_list_len = scsi_2btoul(header->defect_list_len);
5122			if (defect_list_len != 0) {
5123				ctl_set_invalid_field(ctsio,
5124						      /*sks_valid*/ 1,
5125						      /*command*/ 0,
5126						      /*field*/ 2,
5127						      /*bit_valid*/ 0,
5128						      /*bit*/ 0);
5129				goto bailout;
5130			}
5131		}
5132	}
5133
5134	/*
5135	 * The format command will clear out the "Medium format corrupted"
5136	 * status if set by the configuration code.  That status is really
5137	 * just a way to notify the host that we have lost the media, and
5138	 * get them to issue a command that will basically make them think
5139	 * they're blowing away the media.
5140	 */
5141	mtx_lock(&lun->lun_lock);
5142	lun->flags &= ~CTL_LUN_INOPERABLE;
5143	mtx_unlock(&lun->lun_lock);
5144
5145	ctl_set_success(ctsio);
5146bailout:
5147
5148	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5149		free(ctsio->kern_data_ptr, M_CTL);
5150		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5151	}
5152
5153	ctl_done((union ctl_io *)ctsio);
5154	return (CTL_RETVAL_COMPLETE);
5155}
5156
5157int
5158ctl_read_buffer(struct ctl_scsiio *ctsio)
5159{
5160	struct scsi_read_buffer *cdb;
5161	struct ctl_lun *lun;
5162	int buffer_offset, len;
5163	static uint8_t descr[4];
5164	static uint8_t echo_descr[4] = { 0 };
5165
5166	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5167
5168	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5169	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5170
5171	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5172	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5173	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5174		ctl_set_invalid_field(ctsio,
5175				      /*sks_valid*/ 1,
5176				      /*command*/ 1,
5177				      /*field*/ 1,
5178				      /*bit_valid*/ 1,
5179				      /*bit*/ 4);
5180		ctl_done((union ctl_io *)ctsio);
5181		return (CTL_RETVAL_COMPLETE);
5182	}
5183
5184	len = scsi_3btoul(cdb->length);
5185	buffer_offset = scsi_3btoul(cdb->offset);
5186
5187	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5188		ctl_set_invalid_field(ctsio,
5189				      /*sks_valid*/ 1,
5190				      /*command*/ 1,
5191				      /*field*/ 6,
5192				      /*bit_valid*/ 0,
5193				      /*bit*/ 0);
5194		ctl_done((union ctl_io *)ctsio);
5195		return (CTL_RETVAL_COMPLETE);
5196	}
5197
5198	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5199		descr[0] = 0;
5200		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5201		ctsio->kern_data_ptr = descr;
5202		len = min(len, sizeof(descr));
5203	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5204		ctsio->kern_data_ptr = echo_descr;
5205		len = min(len, sizeof(echo_descr));
5206	} else {
5207		if (lun->write_buffer == NULL) {
5208			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5209			    M_CTL, M_WAITOK);
5210		}
5211		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5212	}
5213	ctsio->kern_data_len = len;
5214	ctsio->kern_total_len = len;
5215	ctsio->kern_data_resid = 0;
5216	ctsio->kern_rel_offset = 0;
5217	ctsio->kern_sg_entries = 0;
5218	ctl_set_success(ctsio);
5219	ctsio->be_move_done = ctl_config_move_done;
5220	ctl_datamove((union ctl_io *)ctsio);
5221	return (CTL_RETVAL_COMPLETE);
5222}
5223
5224int
5225ctl_write_buffer(struct ctl_scsiio *ctsio)
5226{
5227	struct scsi_write_buffer *cdb;
5228	struct ctl_lun *lun;
5229	int buffer_offset, len;
5230
5231	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5232
5233	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5234	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5235
5236	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5237		ctl_set_invalid_field(ctsio,
5238				      /*sks_valid*/ 1,
5239				      /*command*/ 1,
5240				      /*field*/ 1,
5241				      /*bit_valid*/ 1,
5242				      /*bit*/ 4);
5243		ctl_done((union ctl_io *)ctsio);
5244		return (CTL_RETVAL_COMPLETE);
5245	}
5246
5247	len = scsi_3btoul(cdb->length);
5248	buffer_offset = scsi_3btoul(cdb->offset);
5249
5250	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5251		ctl_set_invalid_field(ctsio,
5252				      /*sks_valid*/ 1,
5253				      /*command*/ 1,
5254				      /*field*/ 6,
5255				      /*bit_valid*/ 0,
5256				      /*bit*/ 0);
5257		ctl_done((union ctl_io *)ctsio);
5258		return (CTL_RETVAL_COMPLETE);
5259	}
5260
5261	/*
5262	 * If we've got a kernel request that hasn't been malloced yet,
5263	 * malloc it and tell the caller the data buffer is here.
5264	 */
5265	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5266		if (lun->write_buffer == NULL) {
5267			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5268			    M_CTL, M_WAITOK);
5269		}
5270		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5271		ctsio->kern_data_len = len;
5272		ctsio->kern_total_len = len;
5273		ctsio->kern_data_resid = 0;
5274		ctsio->kern_rel_offset = 0;
5275		ctsio->kern_sg_entries = 0;
5276		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5277		ctsio->be_move_done = ctl_config_move_done;
5278		ctl_datamove((union ctl_io *)ctsio);
5279
5280		return (CTL_RETVAL_COMPLETE);
5281	}
5282
5283	ctl_set_success(ctsio);
5284	ctl_done((union ctl_io *)ctsio);
5285	return (CTL_RETVAL_COMPLETE);
5286}
5287
5288int
5289ctl_write_same(struct ctl_scsiio *ctsio)
5290{
5291	struct ctl_lun *lun;
5292	struct ctl_lba_len_flags *lbalen;
5293	uint64_t lba;
5294	uint32_t num_blocks;
5295	int len, retval;
5296	uint8_t byte2;
5297
5298	retval = CTL_RETVAL_COMPLETE;
5299
5300	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5301
5302	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5303
5304	switch (ctsio->cdb[0]) {
5305	case WRITE_SAME_10: {
5306		struct scsi_write_same_10 *cdb;
5307
5308		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5309
5310		lba = scsi_4btoul(cdb->addr);
5311		num_blocks = scsi_2btoul(cdb->length);
5312		byte2 = cdb->byte2;
5313		break;
5314	}
5315	case WRITE_SAME_16: {
5316		struct scsi_write_same_16 *cdb;
5317
5318		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5319
5320		lba = scsi_8btou64(cdb->addr);
5321		num_blocks = scsi_4btoul(cdb->length);
5322		byte2 = cdb->byte2;
5323		break;
5324	}
5325	default:
5326		/*
5327		 * We got a command we don't support.  This shouldn't
5328		 * happen, commands should be filtered out above us.
5329		 */
5330		ctl_set_invalid_opcode(ctsio);
5331		ctl_done((union ctl_io *)ctsio);
5332
5333		return (CTL_RETVAL_COMPLETE);
5334		break; /* NOTREACHED */
5335	}
5336
5337	/* NDOB and ANCHOR flags can be used only together with UNMAP */
5338	if ((byte2 & SWS_UNMAP) == 0 &&
5339	    (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5340		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5341		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5342		ctl_done((union ctl_io *)ctsio);
5343		return (CTL_RETVAL_COMPLETE);
5344	}
5345
5346	/*
5347	 * The first check is to make sure we're in bounds, the second
5348	 * check is to catch wrap-around problems.  If the lba + num blocks
5349	 * is less than the lba, then we've wrapped around and the block
5350	 * range is invalid anyway.
5351	 */
5352	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5353	 || ((lba + num_blocks) < lba)) {
5354		ctl_set_lba_out_of_range(ctsio);
5355		ctl_done((union ctl_io *)ctsio);
5356		return (CTL_RETVAL_COMPLETE);
5357	}
5358
5359	/* Zero number of blocks means "to the last logical block" */
5360	if (num_blocks == 0) {
5361		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5362			ctl_set_invalid_field(ctsio,
5363					      /*sks_valid*/ 0,
5364					      /*command*/ 1,
5365					      /*field*/ 0,
5366					      /*bit_valid*/ 0,
5367					      /*bit*/ 0);
5368			ctl_done((union ctl_io *)ctsio);
5369			return (CTL_RETVAL_COMPLETE);
5370		}
5371		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5372	}
5373
5374	len = lun->be_lun->blocksize;
5375
5376	/*
5377	 * If we've got a kernel request that hasn't been malloced yet,
5378	 * malloc it and tell the caller the data buffer is here.
5379	 */
5380	if ((byte2 & SWS_NDOB) == 0 &&
5381	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5382		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5383		ctsio->kern_data_len = len;
5384		ctsio->kern_total_len = len;
5385		ctsio->kern_data_resid = 0;
5386		ctsio->kern_rel_offset = 0;
5387		ctsio->kern_sg_entries = 0;
5388		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5389		ctsio->be_move_done = ctl_config_move_done;
5390		ctl_datamove((union ctl_io *)ctsio);
5391
5392		return (CTL_RETVAL_COMPLETE);
5393	}
5394
5395	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5396	lbalen->lba = lba;
5397	lbalen->len = num_blocks;
5398	lbalen->flags = byte2;
5399	retval = lun->backend->config_write((union ctl_io *)ctsio);
5400
5401	return (retval);
5402}
5403
5404int
5405ctl_unmap(struct ctl_scsiio *ctsio)
5406{
5407	struct ctl_lun *lun;
5408	struct scsi_unmap *cdb;
5409	struct ctl_ptr_len_flags *ptrlen;
5410	struct scsi_unmap_header *hdr;
5411	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5412	uint64_t lba;
5413	uint32_t num_blocks;
5414	int len, retval;
5415	uint8_t byte2;
5416
5417	retval = CTL_RETVAL_COMPLETE;
5418
5419	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5420
5421	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5422	cdb = (struct scsi_unmap *)ctsio->cdb;
5423
5424	len = scsi_2btoul(cdb->length);
5425	byte2 = cdb->byte2;
5426
5427	/*
5428	 * If we've got a kernel request that hasn't been malloced yet,
5429	 * malloc it and tell the caller the data buffer is here.
5430	 */
5431	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5432		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5433		ctsio->kern_data_len = len;
5434		ctsio->kern_total_len = len;
5435		ctsio->kern_data_resid = 0;
5436		ctsio->kern_rel_offset = 0;
5437		ctsio->kern_sg_entries = 0;
5438		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5439		ctsio->be_move_done = ctl_config_move_done;
5440		ctl_datamove((union ctl_io *)ctsio);
5441
5442		return (CTL_RETVAL_COMPLETE);
5443	}
5444
5445	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5446	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5447	if (len < sizeof (*hdr) ||
5448	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5449	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5450	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5451		ctl_set_invalid_field(ctsio,
5452				      /*sks_valid*/ 0,
5453				      /*command*/ 0,
5454				      /*field*/ 0,
5455				      /*bit_valid*/ 0,
5456				      /*bit*/ 0);
5457		goto done;
5458	}
5459	len = scsi_2btoul(hdr->desc_length);
5460	buf = (struct scsi_unmap_desc *)(hdr + 1);
5461	end = buf + len / sizeof(*buf);
5462
5463	endnz = buf;
5464	for (range = buf; range < end; range++) {
5465		lba = scsi_8btou64(range->lba);
5466		num_blocks = scsi_4btoul(range->length);
5467		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5468		 || ((lba + num_blocks) < lba)) {
5469			ctl_set_lba_out_of_range(ctsio);
5470			ctl_done((union ctl_io *)ctsio);
5471			return (CTL_RETVAL_COMPLETE);
5472		}
5473		if (num_blocks != 0)
5474			endnz = range + 1;
5475	}
5476
5477	/*
5478	 * Block backend can not handle zero last range.
5479	 * Filter it out and return if there is nothing left.
5480	 */
5481	len = (uint8_t *)endnz - (uint8_t *)buf;
5482	if (len == 0) {
5483		ctl_set_success(ctsio);
5484		goto done;
5485	}
5486
5487	mtx_lock(&lun->lun_lock);
5488	ptrlen = (struct ctl_ptr_len_flags *)
5489	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5490	ptrlen->ptr = (void *)buf;
5491	ptrlen->len = len;
5492	ptrlen->flags = byte2;
5493	ctl_check_blocked(lun);
5494	mtx_unlock(&lun->lun_lock);
5495
5496	retval = lun->backend->config_write((union ctl_io *)ctsio);
5497	return (retval);
5498
5499done:
5500	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5501		free(ctsio->kern_data_ptr, M_CTL);
5502		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5503	}
5504	ctl_done((union ctl_io *)ctsio);
5505	return (CTL_RETVAL_COMPLETE);
5506}
5507
5508/*
5509 * Note that this function currently doesn't actually do anything inside
5510 * CTL to enforce things if the DQue bit is turned on.
5511 *
5512 * Also note that this function can't be used in the default case, because
5513 * the DQue bit isn't set in the changeable mask for the control mode page
5514 * anyway.  This is just here as an example for how to implement a page
5515 * handler, and a placeholder in case we want to allow the user to turn
5516 * tagged queueing on and off.
5517 *
5518 * The D_SENSE bit handling is functional, however, and will turn
5519 * descriptor sense on and off for a given LUN.
5520 */
5521int
5522ctl_control_page_handler(struct ctl_scsiio *ctsio,
5523			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5524{
5525	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5526	struct ctl_lun *lun;
5527	int set_ua;
5528	uint32_t initidx;
5529
5530	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5531	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5532	set_ua = 0;
5533
5534	user_cp = (struct scsi_control_page *)page_ptr;
5535	current_cp = (struct scsi_control_page *)
5536		(page_index->page_data + (page_index->page_len *
5537		CTL_PAGE_CURRENT));
5538	saved_cp = (struct scsi_control_page *)
5539		(page_index->page_data + (page_index->page_len *
5540		CTL_PAGE_SAVED));
5541
5542	mtx_lock(&lun->lun_lock);
5543	if (((current_cp->rlec & SCP_DSENSE) == 0)
5544	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
5545		/*
5546		 * Descriptor sense is currently turned off and the user
5547		 * wants to turn it on.
5548		 */
5549		current_cp->rlec |= SCP_DSENSE;
5550		saved_cp->rlec |= SCP_DSENSE;
5551		lun->flags |= CTL_LUN_SENSE_DESC;
5552		set_ua = 1;
5553	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
5554		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
5555		/*
5556		 * Descriptor sense is currently turned on, and the user
5557		 * wants to turn it off.
5558		 */
5559		current_cp->rlec &= ~SCP_DSENSE;
5560		saved_cp->rlec &= ~SCP_DSENSE;
5561		lun->flags &= ~CTL_LUN_SENSE_DESC;
5562		set_ua = 1;
5563	}
5564	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
5565	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
5566		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5567		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5568		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5569		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5570		set_ua = 1;
5571	}
5572	if ((current_cp->eca_and_aen & SCP_SWP) !=
5573	    (user_cp->eca_and_aen & SCP_SWP)) {
5574		current_cp->eca_and_aen &= ~SCP_SWP;
5575		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5576		saved_cp->eca_and_aen &= ~SCP_SWP;
5577		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5578		set_ua = 1;
5579	}
5580	if (set_ua != 0)
5581		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5582	mtx_unlock(&lun->lun_lock);
5583
5584	return (0);
5585}
5586
5587int
5588ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
5589		     struct ctl_page_index *page_index, uint8_t *page_ptr)
5590{
5591	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
5592	struct ctl_lun *lun;
5593	int set_ua;
5594	uint32_t initidx;
5595
5596	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5597	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5598	set_ua = 0;
5599
5600	user_cp = (struct scsi_caching_page *)page_ptr;
5601	current_cp = (struct scsi_caching_page *)
5602		(page_index->page_data + (page_index->page_len *
5603		CTL_PAGE_CURRENT));
5604	saved_cp = (struct scsi_caching_page *)
5605		(page_index->page_data + (page_index->page_len *
5606		CTL_PAGE_SAVED));
5607
5608	mtx_lock(&lun->lun_lock);
5609	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
5610	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
5611		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5612		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5613		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5614		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5615		set_ua = 1;
5616	}
5617	if (set_ua != 0)
5618		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5619	mtx_unlock(&lun->lun_lock);
5620
5621	return (0);
5622}
5623
5624int
5625ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
5626				struct ctl_page_index *page_index,
5627				uint8_t *page_ptr)
5628{
5629	uint8_t *c;
5630	int i;
5631
5632	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
5633	ctl_time_io_secs =
5634		(c[0] << 8) |
5635		(c[1] << 0) |
5636		0;
5637	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
5638	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
5639	printf("page data:");
5640	for (i=0; i<8; i++)
5641		printf(" %.2x",page_ptr[i]);
5642	printf("\n");
5643	return (0);
5644}
5645
5646int
5647ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
5648			       struct ctl_page_index *page_index,
5649			       int pc)
5650{
5651	struct copan_debugconf_subpage *page;
5652
5653	page = (struct copan_debugconf_subpage *)page_index->page_data +
5654		(page_index->page_len * pc);
5655
5656	switch (pc) {
5657	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
5658	case SMS_PAGE_CTRL_DEFAULT >> 6:
5659	case SMS_PAGE_CTRL_SAVED >> 6:
5660		/*
5661		 * We don't update the changable or default bits for this page.
5662		 */
5663		break;
5664	case SMS_PAGE_CTRL_CURRENT >> 6:
5665		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
5666		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
5667		break;
5668	default:
5669#ifdef NEEDTOPORT
5670		EPRINT(0, "Invalid PC %d!!", pc);
5671#endif /* NEEDTOPORT */
5672		break;
5673	}
5674	return (0);
5675}
5676
5677
5678static int
5679ctl_do_mode_select(union ctl_io *io)
5680{
5681	struct scsi_mode_page_header *page_header;
5682	struct ctl_page_index *page_index;
5683	struct ctl_scsiio *ctsio;
5684	int control_dev, page_len;
5685	int page_len_offset, page_len_size;
5686	union ctl_modepage_info *modepage_info;
5687	struct ctl_lun *lun;
5688	int *len_left, *len_used;
5689	int retval, i;
5690
5691	ctsio = &io->scsiio;
5692	page_index = NULL;
5693	page_len = 0;
5694	retval = CTL_RETVAL_COMPLETE;
5695
5696	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5697
5698	if (lun->be_lun->lun_type != T_DIRECT)
5699		control_dev = 1;
5700	else
5701		control_dev = 0;
5702
5703	modepage_info = (union ctl_modepage_info *)
5704		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5705	len_left = &modepage_info->header.len_left;
5706	len_used = &modepage_info->header.len_used;
5707
5708do_next_page:
5709
5710	page_header = (struct scsi_mode_page_header *)
5711		(ctsio->kern_data_ptr + *len_used);
5712
5713	if (*len_left == 0) {
5714		free(ctsio->kern_data_ptr, M_CTL);
5715		ctl_set_success(ctsio);
5716		ctl_done((union ctl_io *)ctsio);
5717		return (CTL_RETVAL_COMPLETE);
5718	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
5719
5720		free(ctsio->kern_data_ptr, M_CTL);
5721		ctl_set_param_len_error(ctsio);
5722		ctl_done((union ctl_io *)ctsio);
5723		return (CTL_RETVAL_COMPLETE);
5724
5725	} else if ((page_header->page_code & SMPH_SPF)
5726		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
5727
5728		free(ctsio->kern_data_ptr, M_CTL);
5729		ctl_set_param_len_error(ctsio);
5730		ctl_done((union ctl_io *)ctsio);
5731		return (CTL_RETVAL_COMPLETE);
5732	}
5733
5734
5735	/*
5736	 * XXX KDM should we do something with the block descriptor?
5737	 */
5738	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5739
5740		if ((control_dev != 0)
5741		 && (lun->mode_pages.index[i].page_flags &
5742		     CTL_PAGE_FLAG_DISK_ONLY))
5743			continue;
5744
5745		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
5746		    (page_header->page_code & SMPH_PC_MASK))
5747			continue;
5748
5749		/*
5750		 * If neither page has a subpage code, then we've got a
5751		 * match.
5752		 */
5753		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
5754		 && ((page_header->page_code & SMPH_SPF) == 0)) {
5755			page_index = &lun->mode_pages.index[i];
5756			page_len = page_header->page_length;
5757			break;
5758		}
5759
5760		/*
5761		 * If both pages have subpages, then the subpage numbers
5762		 * have to match.
5763		 */
5764		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
5765		  && (page_header->page_code & SMPH_SPF)) {
5766			struct scsi_mode_page_header_sp *sph;
5767
5768			sph = (struct scsi_mode_page_header_sp *)page_header;
5769
5770			if (lun->mode_pages.index[i].subpage ==
5771			    sph->subpage) {
5772				page_index = &lun->mode_pages.index[i];
5773				page_len = scsi_2btoul(sph->page_length);
5774				break;
5775			}
5776		}
5777	}
5778
5779	/*
5780	 * If we couldn't find the page, or if we don't have a mode select
5781	 * handler for it, send back an error to the user.
5782	 */
5783	if ((page_index == NULL)
5784	 || (page_index->select_handler == NULL)) {
5785		ctl_set_invalid_field(ctsio,
5786				      /*sks_valid*/ 1,
5787				      /*command*/ 0,
5788				      /*field*/ *len_used,
5789				      /*bit_valid*/ 0,
5790				      /*bit*/ 0);
5791		free(ctsio->kern_data_ptr, M_CTL);
5792		ctl_done((union ctl_io *)ctsio);
5793		return (CTL_RETVAL_COMPLETE);
5794	}
5795
5796	if (page_index->page_code & SMPH_SPF) {
5797		page_len_offset = 2;
5798		page_len_size = 2;
5799	} else {
5800		page_len_size = 1;
5801		page_len_offset = 1;
5802	}
5803
5804	/*
5805	 * If the length the initiator gives us isn't the one we specify in
5806	 * the mode page header, or if they didn't specify enough data in
5807	 * the CDB to avoid truncating this page, kick out the request.
5808	 */
5809	if ((page_len != (page_index->page_len - page_len_offset -
5810			  page_len_size))
5811	 || (*len_left < page_index->page_len)) {
5812
5813
5814		ctl_set_invalid_field(ctsio,
5815				      /*sks_valid*/ 1,
5816				      /*command*/ 0,
5817				      /*field*/ *len_used + page_len_offset,
5818				      /*bit_valid*/ 0,
5819				      /*bit*/ 0);
5820		free(ctsio->kern_data_ptr, M_CTL);
5821		ctl_done((union ctl_io *)ctsio);
5822		return (CTL_RETVAL_COMPLETE);
5823	}
5824
5825	/*
5826	 * Run through the mode page, checking to make sure that the bits
5827	 * the user changed are actually legal for him to change.
5828	 */
5829	for (i = 0; i < page_index->page_len; i++) {
5830		uint8_t *user_byte, *change_mask, *current_byte;
5831		int bad_bit;
5832		int j;
5833
5834		user_byte = (uint8_t *)page_header + i;
5835		change_mask = page_index->page_data +
5836			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
5837		current_byte = page_index->page_data +
5838			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
5839
5840		/*
5841		 * Check to see whether the user set any bits in this byte
5842		 * that he is not allowed to set.
5843		 */
5844		if ((*user_byte & ~(*change_mask)) ==
5845		    (*current_byte & ~(*change_mask)))
5846			continue;
5847
5848		/*
5849		 * Go through bit by bit to determine which one is illegal.
5850		 */
5851		bad_bit = 0;
5852		for (j = 7; j >= 0; j--) {
5853			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
5854			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
5855				bad_bit = i;
5856				break;
5857			}
5858		}
5859		ctl_set_invalid_field(ctsio,
5860				      /*sks_valid*/ 1,
5861				      /*command*/ 0,
5862				      /*field*/ *len_used + i,
5863				      /*bit_valid*/ 1,
5864				      /*bit*/ bad_bit);
5865		free(ctsio->kern_data_ptr, M_CTL);
5866		ctl_done((union ctl_io *)ctsio);
5867		return (CTL_RETVAL_COMPLETE);
5868	}
5869
5870	/*
5871	 * Decrement these before we call the page handler, since we may
5872	 * end up getting called back one way or another before the handler
5873	 * returns to this context.
5874	 */
5875	*len_left -= page_index->page_len;
5876	*len_used += page_index->page_len;
5877
5878	retval = page_index->select_handler(ctsio, page_index,
5879					    (uint8_t *)page_header);
5880
5881	/*
5882	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
5883	 * wait until this queued command completes to finish processing
5884	 * the mode page.  If it returns anything other than
5885	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
5886	 * already set the sense information, freed the data pointer, and
5887	 * completed the io for us.
5888	 */
5889	if (retval != CTL_RETVAL_COMPLETE)
5890		goto bailout_no_done;
5891
5892	/*
5893	 * If the initiator sent us more than one page, parse the next one.
5894	 */
5895	if (*len_left > 0)
5896		goto do_next_page;
5897
5898	ctl_set_success(ctsio);
5899	free(ctsio->kern_data_ptr, M_CTL);
5900	ctl_done((union ctl_io *)ctsio);
5901
5902bailout_no_done:
5903
5904	return (CTL_RETVAL_COMPLETE);
5905
5906}
5907
5908int
5909ctl_mode_select(struct ctl_scsiio *ctsio)
5910{
5911	int param_len, pf, sp;
5912	int header_size, bd_len;
5913	int len_left, len_used;
5914	struct ctl_page_index *page_index;
5915	struct ctl_lun *lun;
5916	int control_dev, page_len;
5917	union ctl_modepage_info *modepage_info;
5918	int retval;
5919
5920	pf = 0;
5921	sp = 0;
5922	page_len = 0;
5923	len_used = 0;
5924	len_left = 0;
5925	retval = 0;
5926	bd_len = 0;
5927	page_index = NULL;
5928
5929	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5930
5931	if (lun->be_lun->lun_type != T_DIRECT)
5932		control_dev = 1;
5933	else
5934		control_dev = 0;
5935
5936	switch (ctsio->cdb[0]) {
5937	case MODE_SELECT_6: {
5938		struct scsi_mode_select_6 *cdb;
5939
5940		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
5941
5942		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
5943		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
5944
5945		param_len = cdb->length;
5946		header_size = sizeof(struct scsi_mode_header_6);
5947		break;
5948	}
5949	case MODE_SELECT_10: {
5950		struct scsi_mode_select_10 *cdb;
5951
5952		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
5953
5954		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
5955		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
5956
5957		param_len = scsi_2btoul(cdb->length);
5958		header_size = sizeof(struct scsi_mode_header_10);
5959		break;
5960	}
5961	default:
5962		ctl_set_invalid_opcode(ctsio);
5963		ctl_done((union ctl_io *)ctsio);
5964		return (CTL_RETVAL_COMPLETE);
5965		break; /* NOTREACHED */
5966	}
5967
5968	/*
5969	 * From SPC-3:
5970	 * "A parameter list length of zero indicates that the Data-Out Buffer
5971	 * shall be empty. This condition shall not be considered as an error."
5972	 */
5973	if (param_len == 0) {
5974		ctl_set_success(ctsio);
5975		ctl_done((union ctl_io *)ctsio);
5976		return (CTL_RETVAL_COMPLETE);
5977	}
5978
5979	/*
5980	 * Since we'll hit this the first time through, prior to
5981	 * allocation, we don't need to free a data buffer here.
5982	 */
5983	if (param_len < header_size) {
5984		ctl_set_param_len_error(ctsio);
5985		ctl_done((union ctl_io *)ctsio);
5986		return (CTL_RETVAL_COMPLETE);
5987	}
5988
5989	/*
5990	 * Allocate the data buffer and grab the user's data.  In theory,
5991	 * we shouldn't have to sanity check the parameter list length here
5992	 * because the maximum size is 64K.  We should be able to malloc
5993	 * that much without too many problems.
5994	 */
5995	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5996		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
5997		ctsio->kern_data_len = param_len;
5998		ctsio->kern_total_len = param_len;
5999		ctsio->kern_data_resid = 0;
6000		ctsio->kern_rel_offset = 0;
6001		ctsio->kern_sg_entries = 0;
6002		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6003		ctsio->be_move_done = ctl_config_move_done;
6004		ctl_datamove((union ctl_io *)ctsio);
6005
6006		return (CTL_RETVAL_COMPLETE);
6007	}
6008
6009	switch (ctsio->cdb[0]) {
6010	case MODE_SELECT_6: {
6011		struct scsi_mode_header_6 *mh6;
6012
6013		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6014		bd_len = mh6->blk_desc_len;
6015		break;
6016	}
6017	case MODE_SELECT_10: {
6018		struct scsi_mode_header_10 *mh10;
6019
6020		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6021		bd_len = scsi_2btoul(mh10->blk_desc_len);
6022		break;
6023	}
6024	default:
6025		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6026		break;
6027	}
6028
6029	if (param_len < (header_size + bd_len)) {
6030		free(ctsio->kern_data_ptr, M_CTL);
6031		ctl_set_param_len_error(ctsio);
6032		ctl_done((union ctl_io *)ctsio);
6033		return (CTL_RETVAL_COMPLETE);
6034	}
6035
6036	/*
6037	 * Set the IO_CONT flag, so that if this I/O gets passed to
6038	 * ctl_config_write_done(), it'll get passed back to
6039	 * ctl_do_mode_select() for further processing, or completion if
6040	 * we're all done.
6041	 */
6042	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6043	ctsio->io_cont = ctl_do_mode_select;
6044
6045	modepage_info = (union ctl_modepage_info *)
6046		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6047
6048	memset(modepage_info, 0, sizeof(*modepage_info));
6049
6050	len_left = param_len - header_size - bd_len;
6051	len_used = header_size + bd_len;
6052
6053	modepage_info->header.len_left = len_left;
6054	modepage_info->header.len_used = len_used;
6055
6056	return (ctl_do_mode_select((union ctl_io *)ctsio));
6057}
6058
6059int
6060ctl_mode_sense(struct ctl_scsiio *ctsio)
6061{
6062	struct ctl_lun *lun;
6063	int pc, page_code, dbd, llba, subpage;
6064	int alloc_len, page_len, header_len, total_len;
6065	struct scsi_mode_block_descr *block_desc;
6066	struct ctl_page_index *page_index;
6067	int control_dev;
6068
6069	dbd = 0;
6070	llba = 0;
6071	block_desc = NULL;
6072	page_index = NULL;
6073
6074	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6075
6076	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6077
6078	if (lun->be_lun->lun_type != T_DIRECT)
6079		control_dev = 1;
6080	else
6081		control_dev = 0;
6082
6083	switch (ctsio->cdb[0]) {
6084	case MODE_SENSE_6: {
6085		struct scsi_mode_sense_6 *cdb;
6086
6087		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6088
6089		header_len = sizeof(struct scsi_mode_hdr_6);
6090		if (cdb->byte2 & SMS_DBD)
6091			dbd = 1;
6092		else
6093			header_len += sizeof(struct scsi_mode_block_descr);
6094
6095		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6096		page_code = cdb->page & SMS_PAGE_CODE;
6097		subpage = cdb->subpage;
6098		alloc_len = cdb->length;
6099		break;
6100	}
6101	case MODE_SENSE_10: {
6102		struct scsi_mode_sense_10 *cdb;
6103
6104		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6105
6106		header_len = sizeof(struct scsi_mode_hdr_10);
6107
6108		if (cdb->byte2 & SMS_DBD)
6109			dbd = 1;
6110		else
6111			header_len += sizeof(struct scsi_mode_block_descr);
6112		if (cdb->byte2 & SMS10_LLBAA)
6113			llba = 1;
6114		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6115		page_code = cdb->page & SMS_PAGE_CODE;
6116		subpage = cdb->subpage;
6117		alloc_len = scsi_2btoul(cdb->length);
6118		break;
6119	}
6120	default:
6121		ctl_set_invalid_opcode(ctsio);
6122		ctl_done((union ctl_io *)ctsio);
6123		return (CTL_RETVAL_COMPLETE);
6124		break; /* NOTREACHED */
6125	}
6126
6127	/*
6128	 * We have to make a first pass through to calculate the size of
6129	 * the pages that match the user's query.  Then we allocate enough
6130	 * memory to hold it, and actually copy the data into the buffer.
6131	 */
6132	switch (page_code) {
6133	case SMS_ALL_PAGES_PAGE: {
6134		int i;
6135
6136		page_len = 0;
6137
6138		/*
6139		 * At the moment, values other than 0 and 0xff here are
6140		 * reserved according to SPC-3.
6141		 */
6142		if ((subpage != SMS_SUBPAGE_PAGE_0)
6143		 && (subpage != SMS_SUBPAGE_ALL)) {
6144			ctl_set_invalid_field(ctsio,
6145					      /*sks_valid*/ 1,
6146					      /*command*/ 1,
6147					      /*field*/ 3,
6148					      /*bit_valid*/ 0,
6149					      /*bit*/ 0);
6150			ctl_done((union ctl_io *)ctsio);
6151			return (CTL_RETVAL_COMPLETE);
6152		}
6153
6154		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6155			if ((control_dev != 0)
6156			 && (lun->mode_pages.index[i].page_flags &
6157			     CTL_PAGE_FLAG_DISK_ONLY))
6158				continue;
6159
6160			/*
6161			 * We don't use this subpage if the user didn't
6162			 * request all subpages.
6163			 */
6164			if ((lun->mode_pages.index[i].subpage != 0)
6165			 && (subpage == SMS_SUBPAGE_PAGE_0))
6166				continue;
6167
6168#if 0
6169			printf("found page %#x len %d\n",
6170			       lun->mode_pages.index[i].page_code &
6171			       SMPH_PC_MASK,
6172			       lun->mode_pages.index[i].page_len);
6173#endif
6174			page_len += lun->mode_pages.index[i].page_len;
6175		}
6176		break;
6177	}
6178	default: {
6179		int i;
6180
6181		page_len = 0;
6182
6183		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6184			/* Look for the right page code */
6185			if ((lun->mode_pages.index[i].page_code &
6186			     SMPH_PC_MASK) != page_code)
6187				continue;
6188
6189			/* Look for the right subpage or the subpage wildcard*/
6190			if ((lun->mode_pages.index[i].subpage != subpage)
6191			 && (subpage != SMS_SUBPAGE_ALL))
6192				continue;
6193
6194			/* Make sure the page is supported for this dev type */
6195			if ((control_dev != 0)
6196			 && (lun->mode_pages.index[i].page_flags &
6197			     CTL_PAGE_FLAG_DISK_ONLY))
6198				continue;
6199
6200#if 0
6201			printf("found page %#x len %d\n",
6202			       lun->mode_pages.index[i].page_code &
6203			       SMPH_PC_MASK,
6204			       lun->mode_pages.index[i].page_len);
6205#endif
6206
6207			page_len += lun->mode_pages.index[i].page_len;
6208		}
6209
6210		if (page_len == 0) {
6211			ctl_set_invalid_field(ctsio,
6212					      /*sks_valid*/ 1,
6213					      /*command*/ 1,
6214					      /*field*/ 2,
6215					      /*bit_valid*/ 1,
6216					      /*bit*/ 5);
6217			ctl_done((union ctl_io *)ctsio);
6218			return (CTL_RETVAL_COMPLETE);
6219		}
6220		break;
6221	}
6222	}
6223
6224	total_len = header_len + page_len;
6225#if 0
6226	printf("header_len = %d, page_len = %d, total_len = %d\n",
6227	       header_len, page_len, total_len);
6228#endif
6229
6230	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6231	ctsio->kern_sg_entries = 0;
6232	ctsio->kern_data_resid = 0;
6233	ctsio->kern_rel_offset = 0;
6234	if (total_len < alloc_len) {
6235		ctsio->residual = alloc_len - total_len;
6236		ctsio->kern_data_len = total_len;
6237		ctsio->kern_total_len = total_len;
6238	} else {
6239		ctsio->residual = 0;
6240		ctsio->kern_data_len = alloc_len;
6241		ctsio->kern_total_len = alloc_len;
6242	}
6243
6244	switch (ctsio->cdb[0]) {
6245	case MODE_SENSE_6: {
6246		struct scsi_mode_hdr_6 *header;
6247
6248		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6249
6250		header->datalen = MIN(total_len - 1, 254);
6251		if (control_dev == 0) {
6252			header->dev_specific = 0x10; /* DPOFUA */
6253			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6254			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6255			    .eca_and_aen & SCP_SWP) != 0)
6256				    header->dev_specific |= 0x80; /* WP */
6257		}
6258		if (dbd)
6259			header->block_descr_len = 0;
6260		else
6261			header->block_descr_len =
6262				sizeof(struct scsi_mode_block_descr);
6263		block_desc = (struct scsi_mode_block_descr *)&header[1];
6264		break;
6265	}
6266	case MODE_SENSE_10: {
6267		struct scsi_mode_hdr_10 *header;
6268		int datalen;
6269
6270		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6271
6272		datalen = MIN(total_len - 2, 65533);
6273		scsi_ulto2b(datalen, header->datalen);
6274		if (control_dev == 0) {
6275			header->dev_specific = 0x10; /* DPOFUA */
6276			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6277			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6278			    .eca_and_aen & SCP_SWP) != 0)
6279				    header->dev_specific |= 0x80; /* WP */
6280		}
6281		if (dbd)
6282			scsi_ulto2b(0, header->block_descr_len);
6283		else
6284			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6285				    header->block_descr_len);
6286		block_desc = (struct scsi_mode_block_descr *)&header[1];
6287		break;
6288	}
6289	default:
6290		panic("invalid CDB type %#x", ctsio->cdb[0]);
6291		break; /* NOTREACHED */
6292	}
6293
6294	/*
6295	 * If we've got a disk, use its blocksize in the block
6296	 * descriptor.  Otherwise, just set it to 0.
6297	 */
6298	if (dbd == 0) {
6299		if (control_dev == 0)
6300			scsi_ulto3b(lun->be_lun->blocksize,
6301				    block_desc->block_len);
6302		else
6303			scsi_ulto3b(0, block_desc->block_len);
6304	}
6305
6306	switch (page_code) {
6307	case SMS_ALL_PAGES_PAGE: {
6308		int i, data_used;
6309
6310		data_used = header_len;
6311		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6312			struct ctl_page_index *page_index;
6313
6314			page_index = &lun->mode_pages.index[i];
6315
6316			if ((control_dev != 0)
6317			 && (page_index->page_flags &
6318			    CTL_PAGE_FLAG_DISK_ONLY))
6319				continue;
6320
6321			/*
6322			 * We don't use this subpage if the user didn't
6323			 * request all subpages.  We already checked (above)
6324			 * to make sure the user only specified a subpage
6325			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6326			 */
6327			if ((page_index->subpage != 0)
6328			 && (subpage == SMS_SUBPAGE_PAGE_0))
6329				continue;
6330
6331			/*
6332			 * Call the handler, if it exists, to update the
6333			 * page to the latest values.
6334			 */
6335			if (page_index->sense_handler != NULL)
6336				page_index->sense_handler(ctsio, page_index,pc);
6337
6338			memcpy(ctsio->kern_data_ptr + data_used,
6339			       page_index->page_data +
6340			       (page_index->page_len * pc),
6341			       page_index->page_len);
6342			data_used += page_index->page_len;
6343		}
6344		break;
6345	}
6346	default: {
6347		int i, data_used;
6348
6349		data_used = header_len;
6350
6351		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6352			struct ctl_page_index *page_index;
6353
6354			page_index = &lun->mode_pages.index[i];
6355
6356			/* Look for the right page code */
6357			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6358				continue;
6359
6360			/* Look for the right subpage or the subpage wildcard*/
6361			if ((page_index->subpage != subpage)
6362			 && (subpage != SMS_SUBPAGE_ALL))
6363				continue;
6364
6365			/* Make sure the page is supported for this dev type */
6366			if ((control_dev != 0)
6367			 && (page_index->page_flags &
6368			     CTL_PAGE_FLAG_DISK_ONLY))
6369				continue;
6370
6371			/*
6372			 * Call the handler, if it exists, to update the
6373			 * page to the latest values.
6374			 */
6375			if (page_index->sense_handler != NULL)
6376				page_index->sense_handler(ctsio, page_index,pc);
6377
6378			memcpy(ctsio->kern_data_ptr + data_used,
6379			       page_index->page_data +
6380			       (page_index->page_len * pc),
6381			       page_index->page_len);
6382			data_used += page_index->page_len;
6383		}
6384		break;
6385	}
6386	}
6387
6388	ctl_set_success(ctsio);
6389	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6390	ctsio->be_move_done = ctl_config_move_done;
6391	ctl_datamove((union ctl_io *)ctsio);
6392	return (CTL_RETVAL_COMPLETE);
6393}
6394
6395int
6396ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6397			       struct ctl_page_index *page_index,
6398			       int pc)
6399{
6400	struct ctl_lun *lun;
6401	struct scsi_log_param_header *phdr;
6402	uint8_t *data;
6403	uint64_t val;
6404
6405	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6406	data = page_index->page_data;
6407
6408	if (lun->backend->lun_attr != NULL &&
6409	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6410	     != UINT64_MAX) {
6411		phdr = (struct scsi_log_param_header *)data;
6412		scsi_ulto2b(0x0001, phdr->param_code);
6413		phdr->param_control = SLP_LBIN | SLP_LP;
6414		phdr->param_len = 8;
6415		data = (uint8_t *)(phdr + 1);
6416		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6417		data[4] = 0x02; /* per-pool */
6418		data += phdr->param_len;
6419	}
6420
6421	if (lun->backend->lun_attr != NULL &&
6422	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6423	     != UINT64_MAX) {
6424		phdr = (struct scsi_log_param_header *)data;
6425		scsi_ulto2b(0x0002, phdr->param_code);
6426		phdr->param_control = SLP_LBIN | SLP_LP;
6427		phdr->param_len = 8;
6428		data = (uint8_t *)(phdr + 1);
6429		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6430		data[4] = 0x01; /* per-LUN */
6431		data += phdr->param_len;
6432	}
6433
6434	if (lun->backend->lun_attr != NULL &&
6435	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6436	     != UINT64_MAX) {
6437		phdr = (struct scsi_log_param_header *)data;
6438		scsi_ulto2b(0x00f1, phdr->param_code);
6439		phdr->param_control = SLP_LBIN | SLP_LP;
6440		phdr->param_len = 8;
6441		data = (uint8_t *)(phdr + 1);
6442		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6443		data[4] = 0x02; /* per-pool */
6444		data += phdr->param_len;
6445	}
6446
6447	if (lun->backend->lun_attr != NULL &&
6448	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6449	     != UINT64_MAX) {
6450		phdr = (struct scsi_log_param_header *)data;
6451		scsi_ulto2b(0x00f2, phdr->param_code);
6452		phdr->param_control = SLP_LBIN | SLP_LP;
6453		phdr->param_len = 8;
6454		data = (uint8_t *)(phdr + 1);
6455		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6456		data[4] = 0x02; /* per-pool */
6457		data += phdr->param_len;
6458	}
6459
6460	page_index->page_len = data - page_index->page_data;
6461	return (0);
6462}
6463
6464int
6465ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6466			       struct ctl_page_index *page_index,
6467			       int pc)
6468{
6469	struct ctl_lun *lun;
6470	struct stat_page *data;
6471	uint64_t rn, wn, rb, wb;
6472	struct bintime rt, wt;
6473	int i;
6474
6475	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6476	data = (struct stat_page *)page_index->page_data;
6477
6478	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6479	data->sap.hdr.param_control = SLP_LBIN;
6480	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6481	    sizeof(struct scsi_log_param_header);
6482	rn = wn = rb = wb = 0;
6483	bintime_clear(&rt);
6484	bintime_clear(&wt);
6485	for (i = 0; i < CTL_MAX_PORTS; i++) {
6486		rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6487		wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6488		rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6489		wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6490		bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6491		bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6492	}
6493	scsi_u64to8b(rn, data->sap.read_num);
6494	scsi_u64to8b(wn, data->sap.write_num);
6495	if (lun->stats.blocksize > 0) {
6496		scsi_u64to8b(wb / lun->stats.blocksize,
6497		    data->sap.recvieved_lba);
6498		scsi_u64to8b(rb / lun->stats.blocksize,
6499		    data->sap.transmitted_lba);
6500	}
6501	scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6502	    data->sap.read_int);
6503	scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6504	    data->sap.write_int);
6505	scsi_u64to8b(0, data->sap.weighted_num);
6506	scsi_u64to8b(0, data->sap.weighted_int);
6507	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6508	data->it.hdr.param_control = SLP_LBIN;
6509	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6510	    sizeof(struct scsi_log_param_header);
6511#ifdef CTL_TIME_IO
6512	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6513#endif
6514	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6515	data->it.hdr.param_control = SLP_LBIN;
6516	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6517	    sizeof(struct scsi_log_param_header);
6518	scsi_ulto4b(3, data->ti.exponent);
6519	scsi_ulto4b(1, data->ti.integer);
6520
6521	page_index->page_len = sizeof(*data);
6522	return (0);
6523}
6524
6525int
6526ctl_log_sense(struct ctl_scsiio *ctsio)
6527{
6528	struct ctl_lun *lun;
6529	int i, pc, page_code, subpage;
6530	int alloc_len, total_len;
6531	struct ctl_page_index *page_index;
6532	struct scsi_log_sense *cdb;
6533	struct scsi_log_header *header;
6534
6535	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6536
6537	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6538	cdb = (struct scsi_log_sense *)ctsio->cdb;
6539	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6540	page_code = cdb->page & SLS_PAGE_CODE;
6541	subpage = cdb->subpage;
6542	alloc_len = scsi_2btoul(cdb->length);
6543
6544	page_index = NULL;
6545	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6546		page_index = &lun->log_pages.index[i];
6547
6548		/* Look for the right page code */
6549		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6550			continue;
6551
6552		/* Look for the right subpage or the subpage wildcard*/
6553		if (page_index->subpage != subpage)
6554			continue;
6555
6556		break;
6557	}
6558	if (i >= CTL_NUM_LOG_PAGES) {
6559		ctl_set_invalid_field(ctsio,
6560				      /*sks_valid*/ 1,
6561				      /*command*/ 1,
6562				      /*field*/ 2,
6563				      /*bit_valid*/ 0,
6564				      /*bit*/ 0);
6565		ctl_done((union ctl_io *)ctsio);
6566		return (CTL_RETVAL_COMPLETE);
6567	}
6568
6569	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6570
6571	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6572	ctsio->kern_sg_entries = 0;
6573	ctsio->kern_data_resid = 0;
6574	ctsio->kern_rel_offset = 0;
6575	if (total_len < alloc_len) {
6576		ctsio->residual = alloc_len - total_len;
6577		ctsio->kern_data_len = total_len;
6578		ctsio->kern_total_len = total_len;
6579	} else {
6580		ctsio->residual = 0;
6581		ctsio->kern_data_len = alloc_len;
6582		ctsio->kern_total_len = alloc_len;
6583	}
6584
6585	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6586	header->page = page_index->page_code;
6587	if (page_index->subpage) {
6588		header->page |= SL_SPF;
6589		header->subpage = page_index->subpage;
6590	}
6591	scsi_ulto2b(page_index->page_len, header->datalen);
6592
6593	/*
6594	 * Call the handler, if it exists, to update the
6595	 * page to the latest values.
6596	 */
6597	if (page_index->sense_handler != NULL)
6598		page_index->sense_handler(ctsio, page_index, pc);
6599
6600	memcpy(header + 1, page_index->page_data, page_index->page_len);
6601
6602	ctl_set_success(ctsio);
6603	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6604	ctsio->be_move_done = ctl_config_move_done;
6605	ctl_datamove((union ctl_io *)ctsio);
6606	return (CTL_RETVAL_COMPLETE);
6607}
6608
6609int
6610ctl_read_capacity(struct ctl_scsiio *ctsio)
6611{
6612	struct scsi_read_capacity *cdb;
6613	struct scsi_read_capacity_data *data;
6614	struct ctl_lun *lun;
6615	uint32_t lba;
6616
6617	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6618
6619	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6620
6621	lba = scsi_4btoul(cdb->addr);
6622	if (((cdb->pmi & SRC_PMI) == 0)
6623	 && (lba != 0)) {
6624		ctl_set_invalid_field(/*ctsio*/ ctsio,
6625				      /*sks_valid*/ 1,
6626				      /*command*/ 1,
6627				      /*field*/ 2,
6628				      /*bit_valid*/ 0,
6629				      /*bit*/ 0);
6630		ctl_done((union ctl_io *)ctsio);
6631		return (CTL_RETVAL_COMPLETE);
6632	}
6633
6634	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6635
6636	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6637	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6638	ctsio->residual = 0;
6639	ctsio->kern_data_len = sizeof(*data);
6640	ctsio->kern_total_len = sizeof(*data);
6641	ctsio->kern_data_resid = 0;
6642	ctsio->kern_rel_offset = 0;
6643	ctsio->kern_sg_entries = 0;
6644
6645	/*
6646	 * If the maximum LBA is greater than 0xfffffffe, the user must
6647	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6648	 * serivce action set.
6649	 */
6650	if (lun->be_lun->maxlba > 0xfffffffe)
6651		scsi_ulto4b(0xffffffff, data->addr);
6652	else
6653		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6654
6655	/*
6656	 * XXX KDM this may not be 512 bytes...
6657	 */
6658	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6659
6660	ctl_set_success(ctsio);
6661	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6662	ctsio->be_move_done = ctl_config_move_done;
6663	ctl_datamove((union ctl_io *)ctsio);
6664	return (CTL_RETVAL_COMPLETE);
6665}
6666
6667int
6668ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6669{
6670	struct scsi_read_capacity_16 *cdb;
6671	struct scsi_read_capacity_data_long *data;
6672	struct ctl_lun *lun;
6673	uint64_t lba;
6674	uint32_t alloc_len;
6675
6676	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6677
6678	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6679
6680	alloc_len = scsi_4btoul(cdb->alloc_len);
6681	lba = scsi_8btou64(cdb->addr);
6682
6683	if ((cdb->reladr & SRC16_PMI)
6684	 && (lba != 0)) {
6685		ctl_set_invalid_field(/*ctsio*/ ctsio,
6686				      /*sks_valid*/ 1,
6687				      /*command*/ 1,
6688				      /*field*/ 2,
6689				      /*bit_valid*/ 0,
6690				      /*bit*/ 0);
6691		ctl_done((union ctl_io *)ctsio);
6692		return (CTL_RETVAL_COMPLETE);
6693	}
6694
6695	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6696
6697	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6698	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6699
6700	if (sizeof(*data) < alloc_len) {
6701		ctsio->residual = alloc_len - sizeof(*data);
6702		ctsio->kern_data_len = sizeof(*data);
6703		ctsio->kern_total_len = sizeof(*data);
6704	} else {
6705		ctsio->residual = 0;
6706		ctsio->kern_data_len = alloc_len;
6707		ctsio->kern_total_len = alloc_len;
6708	}
6709	ctsio->kern_data_resid = 0;
6710	ctsio->kern_rel_offset = 0;
6711	ctsio->kern_sg_entries = 0;
6712
6713	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6714	/* XXX KDM this may not be 512 bytes... */
6715	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6716	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6717	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
6718	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
6719		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
6720
6721	ctl_set_success(ctsio);
6722	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6723	ctsio->be_move_done = ctl_config_move_done;
6724	ctl_datamove((union ctl_io *)ctsio);
6725	return (CTL_RETVAL_COMPLETE);
6726}
6727
6728int
6729ctl_get_lba_status(struct ctl_scsiio *ctsio)
6730{
6731	struct scsi_get_lba_status *cdb;
6732	struct scsi_get_lba_status_data *data;
6733	struct ctl_lun *lun;
6734	struct ctl_lba_len_flags *lbalen;
6735	uint64_t lba;
6736	uint32_t alloc_len, total_len;
6737	int retval;
6738
6739	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
6740
6741	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6742	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
6743	lba = scsi_8btou64(cdb->addr);
6744	alloc_len = scsi_4btoul(cdb->alloc_len);
6745
6746	if (lba > lun->be_lun->maxlba) {
6747		ctl_set_lba_out_of_range(ctsio);
6748		ctl_done((union ctl_io *)ctsio);
6749		return (CTL_RETVAL_COMPLETE);
6750	}
6751
6752	total_len = sizeof(*data) + sizeof(data->descr[0]);
6753	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6754	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
6755
6756	if (total_len < alloc_len) {
6757		ctsio->residual = alloc_len - total_len;
6758		ctsio->kern_data_len = total_len;
6759		ctsio->kern_total_len = total_len;
6760	} else {
6761		ctsio->residual = 0;
6762		ctsio->kern_data_len = alloc_len;
6763		ctsio->kern_total_len = alloc_len;
6764	}
6765	ctsio->kern_data_resid = 0;
6766	ctsio->kern_rel_offset = 0;
6767	ctsio->kern_sg_entries = 0;
6768
6769	/* Fill dummy data in case backend can't tell anything. */
6770	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
6771	scsi_u64to8b(lba, data->descr[0].addr);
6772	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
6773	    data->descr[0].length);
6774	data->descr[0].status = 0; /* Mapped or unknown. */
6775
6776	ctl_set_success(ctsio);
6777	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6778	ctsio->be_move_done = ctl_config_move_done;
6779
6780	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6781	lbalen->lba = lba;
6782	lbalen->len = total_len;
6783	lbalen->flags = 0;
6784	retval = lun->backend->config_read((union ctl_io *)ctsio);
6785	return (CTL_RETVAL_COMPLETE);
6786}
6787
6788int
6789ctl_read_defect(struct ctl_scsiio *ctsio)
6790{
6791	struct scsi_read_defect_data_10 *ccb10;
6792	struct scsi_read_defect_data_12 *ccb12;
6793	struct scsi_read_defect_data_hdr_10 *data10;
6794	struct scsi_read_defect_data_hdr_12 *data12;
6795	uint32_t alloc_len, data_len;
6796	uint8_t format;
6797
6798	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
6799
6800	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
6801		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
6802		format = ccb10->format;
6803		alloc_len = scsi_2btoul(ccb10->alloc_length);
6804		data_len = sizeof(*data10);
6805	} else {
6806		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
6807		format = ccb12->format;
6808		alloc_len = scsi_4btoul(ccb12->alloc_length);
6809		data_len = sizeof(*data12);
6810	}
6811	if (alloc_len == 0) {
6812		ctl_set_success(ctsio);
6813		ctl_done((union ctl_io *)ctsio);
6814		return (CTL_RETVAL_COMPLETE);
6815	}
6816
6817	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
6818	if (data_len < alloc_len) {
6819		ctsio->residual = alloc_len - data_len;
6820		ctsio->kern_data_len = data_len;
6821		ctsio->kern_total_len = data_len;
6822	} else {
6823		ctsio->residual = 0;
6824		ctsio->kern_data_len = alloc_len;
6825		ctsio->kern_total_len = alloc_len;
6826	}
6827	ctsio->kern_data_resid = 0;
6828	ctsio->kern_rel_offset = 0;
6829	ctsio->kern_sg_entries = 0;
6830
6831	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
6832		data10 = (struct scsi_read_defect_data_hdr_10 *)
6833		    ctsio->kern_data_ptr;
6834		data10->format = format;
6835		scsi_ulto2b(0, data10->length);
6836	} else {
6837		data12 = (struct scsi_read_defect_data_hdr_12 *)
6838		    ctsio->kern_data_ptr;
6839		data12->format = format;
6840		scsi_ulto2b(0, data12->generation);
6841		scsi_ulto4b(0, data12->length);
6842	}
6843
6844	ctl_set_success(ctsio);
6845	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6846	ctsio->be_move_done = ctl_config_move_done;
6847	ctl_datamove((union ctl_io *)ctsio);
6848	return (CTL_RETVAL_COMPLETE);
6849}
6850
6851int
6852ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
6853{
6854	struct scsi_maintenance_in *cdb;
6855	int retval;
6856	int alloc_len, ext, total_len = 0, g, p, pc, pg, gs, os;
6857	int num_target_port_groups, num_target_ports;
6858	struct ctl_lun *lun;
6859	struct ctl_softc *softc;
6860	struct ctl_port *port;
6861	struct scsi_target_group_data *rtg_ptr;
6862	struct scsi_target_group_data_extended *rtg_ext_ptr;
6863	struct scsi_target_port_group_descriptor *tpg_desc;
6864
6865	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
6866
6867	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
6868	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6869	softc = lun->ctl_softc;
6870
6871	retval = CTL_RETVAL_COMPLETE;
6872
6873	switch (cdb->byte2 & STG_PDF_MASK) {
6874	case STG_PDF_LENGTH:
6875		ext = 0;
6876		break;
6877	case STG_PDF_EXTENDED:
6878		ext = 1;
6879		break;
6880	default:
6881		ctl_set_invalid_field(/*ctsio*/ ctsio,
6882				      /*sks_valid*/ 1,
6883				      /*command*/ 1,
6884				      /*field*/ 2,
6885				      /*bit_valid*/ 1,
6886				      /*bit*/ 5);
6887		ctl_done((union ctl_io *)ctsio);
6888		return(retval);
6889	}
6890
6891	if (softc->is_single)
6892		num_target_port_groups = 1;
6893	else
6894		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
6895	num_target_ports = 0;
6896	mtx_lock(&softc->ctl_lock);
6897	STAILQ_FOREACH(port, &softc->port_list, links) {
6898		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
6899			continue;
6900		if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
6901			continue;
6902		num_target_ports++;
6903	}
6904	mtx_unlock(&softc->ctl_lock);
6905
6906	if (ext)
6907		total_len = sizeof(struct scsi_target_group_data_extended);
6908	else
6909		total_len = sizeof(struct scsi_target_group_data);
6910	total_len += sizeof(struct scsi_target_port_group_descriptor) *
6911		num_target_port_groups +
6912	    sizeof(struct scsi_target_port_descriptor) *
6913		num_target_ports * num_target_port_groups;
6914
6915	alloc_len = scsi_4btoul(cdb->length);
6916
6917	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6918
6919	ctsio->kern_sg_entries = 0;
6920
6921	if (total_len < alloc_len) {
6922		ctsio->residual = alloc_len - total_len;
6923		ctsio->kern_data_len = total_len;
6924		ctsio->kern_total_len = total_len;
6925	} else {
6926		ctsio->residual = 0;
6927		ctsio->kern_data_len = alloc_len;
6928		ctsio->kern_total_len = alloc_len;
6929	}
6930	ctsio->kern_data_resid = 0;
6931	ctsio->kern_rel_offset = 0;
6932
6933	if (ext) {
6934		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
6935		    ctsio->kern_data_ptr;
6936		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
6937		rtg_ext_ptr->format_type = 0x10;
6938		rtg_ext_ptr->implicit_transition_time = 0;
6939		tpg_desc = &rtg_ext_ptr->groups[0];
6940	} else {
6941		rtg_ptr = (struct scsi_target_group_data *)
6942		    ctsio->kern_data_ptr;
6943		scsi_ulto4b(total_len - 4, rtg_ptr->length);
6944		tpg_desc = &rtg_ptr->groups[0];
6945	}
6946
6947	mtx_lock(&softc->ctl_lock);
6948	pg = softc->port_offset / CTL_MAX_PORTS;
6949	if (softc->flags & CTL_FLAG_ACTIVE_SHELF) {
6950		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY) {
6951			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
6952			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
6953		} else if (lun->flags & CTL_LUN_PRIMARY_SC) {
6954			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
6955			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
6956		} else {
6957			gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
6958			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
6959		}
6960	} else {
6961		gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
6962		os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
6963	}
6964	for (g = 0; g < num_target_port_groups; g++) {
6965		tpg_desc->pref_state = (g == pg) ? gs : os;
6966		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP;
6967		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
6968		tpg_desc->status = TPG_IMPLICIT;
6969		pc = 0;
6970		STAILQ_FOREACH(port, &softc->port_list, links) {
6971			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
6972				continue;
6973			if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
6974				continue;
6975			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
6976			scsi_ulto2b(p, tpg_desc->descriptors[pc].
6977			    relative_target_port_identifier);
6978			pc++;
6979		}
6980		tpg_desc->target_port_count = pc;
6981		tpg_desc = (struct scsi_target_port_group_descriptor *)
6982		    &tpg_desc->descriptors[pc];
6983	}
6984	mtx_unlock(&softc->ctl_lock);
6985
6986	ctl_set_success(ctsio);
6987	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6988	ctsio->be_move_done = ctl_config_move_done;
6989	ctl_datamove((union ctl_io *)ctsio);
6990	return(retval);
6991}
6992
6993int
6994ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
6995{
6996	struct ctl_lun *lun;
6997	struct scsi_report_supported_opcodes *cdb;
6998	const struct ctl_cmd_entry *entry, *sentry;
6999	struct scsi_report_supported_opcodes_all *all;
7000	struct scsi_report_supported_opcodes_descr *descr;
7001	struct scsi_report_supported_opcodes_one *one;
7002	int retval;
7003	int alloc_len, total_len;
7004	int opcode, service_action, i, j, num;
7005
7006	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7007
7008	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7009	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7010
7011	retval = CTL_RETVAL_COMPLETE;
7012
7013	opcode = cdb->requested_opcode;
7014	service_action = scsi_2btoul(cdb->requested_service_action);
7015	switch (cdb->options & RSO_OPTIONS_MASK) {
7016	case RSO_OPTIONS_ALL:
7017		num = 0;
7018		for (i = 0; i < 256; i++) {
7019			entry = &ctl_cmd_table[i];
7020			if (entry->flags & CTL_CMD_FLAG_SA5) {
7021				for (j = 0; j < 32; j++) {
7022					sentry = &((const struct ctl_cmd_entry *)
7023					    entry->execute)[j];
7024					if (ctl_cmd_applicable(
7025					    lun->be_lun->lun_type, sentry))
7026						num++;
7027				}
7028			} else {
7029				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7030				    entry))
7031					num++;
7032			}
7033		}
7034		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7035		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7036		break;
7037	case RSO_OPTIONS_OC:
7038		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7039			ctl_set_invalid_field(/*ctsio*/ ctsio,
7040					      /*sks_valid*/ 1,
7041					      /*command*/ 1,
7042					      /*field*/ 2,
7043					      /*bit_valid*/ 1,
7044					      /*bit*/ 2);
7045			ctl_done((union ctl_io *)ctsio);
7046			return (CTL_RETVAL_COMPLETE);
7047		}
7048		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7049		break;
7050	case RSO_OPTIONS_OC_SA:
7051		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7052		    service_action >= 32) {
7053			ctl_set_invalid_field(/*ctsio*/ ctsio,
7054					      /*sks_valid*/ 1,
7055					      /*command*/ 1,
7056					      /*field*/ 2,
7057					      /*bit_valid*/ 1,
7058					      /*bit*/ 2);
7059			ctl_done((union ctl_io *)ctsio);
7060			return (CTL_RETVAL_COMPLETE);
7061		}
7062		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7063		break;
7064	default:
7065		ctl_set_invalid_field(/*ctsio*/ ctsio,
7066				      /*sks_valid*/ 1,
7067				      /*command*/ 1,
7068				      /*field*/ 2,
7069				      /*bit_valid*/ 1,
7070				      /*bit*/ 2);
7071		ctl_done((union ctl_io *)ctsio);
7072		return (CTL_RETVAL_COMPLETE);
7073	}
7074
7075	alloc_len = scsi_4btoul(cdb->length);
7076
7077	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7078
7079	ctsio->kern_sg_entries = 0;
7080
7081	if (total_len < alloc_len) {
7082		ctsio->residual = alloc_len - total_len;
7083		ctsio->kern_data_len = total_len;
7084		ctsio->kern_total_len = total_len;
7085	} else {
7086		ctsio->residual = 0;
7087		ctsio->kern_data_len = alloc_len;
7088		ctsio->kern_total_len = alloc_len;
7089	}
7090	ctsio->kern_data_resid = 0;
7091	ctsio->kern_rel_offset = 0;
7092
7093	switch (cdb->options & RSO_OPTIONS_MASK) {
7094	case RSO_OPTIONS_ALL:
7095		all = (struct scsi_report_supported_opcodes_all *)
7096		    ctsio->kern_data_ptr;
7097		num = 0;
7098		for (i = 0; i < 256; i++) {
7099			entry = &ctl_cmd_table[i];
7100			if (entry->flags & CTL_CMD_FLAG_SA5) {
7101				for (j = 0; j < 32; j++) {
7102					sentry = &((const struct ctl_cmd_entry *)
7103					    entry->execute)[j];
7104					if (!ctl_cmd_applicable(
7105					    lun->be_lun->lun_type, sentry))
7106						continue;
7107					descr = &all->descr[num++];
7108					descr->opcode = i;
7109					scsi_ulto2b(j, descr->service_action);
7110					descr->flags = RSO_SERVACTV;
7111					scsi_ulto2b(sentry->length,
7112					    descr->cdb_length);
7113				}
7114			} else {
7115				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7116				    entry))
7117					continue;
7118				descr = &all->descr[num++];
7119				descr->opcode = i;
7120				scsi_ulto2b(0, descr->service_action);
7121				descr->flags = 0;
7122				scsi_ulto2b(entry->length, descr->cdb_length);
7123			}
7124		}
7125		scsi_ulto4b(
7126		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7127		    all->length);
7128		break;
7129	case RSO_OPTIONS_OC:
7130		one = (struct scsi_report_supported_opcodes_one *)
7131		    ctsio->kern_data_ptr;
7132		entry = &ctl_cmd_table[opcode];
7133		goto fill_one;
7134	case RSO_OPTIONS_OC_SA:
7135		one = (struct scsi_report_supported_opcodes_one *)
7136		    ctsio->kern_data_ptr;
7137		entry = &ctl_cmd_table[opcode];
7138		entry = &((const struct ctl_cmd_entry *)
7139		    entry->execute)[service_action];
7140fill_one:
7141		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7142			one->support = 3;
7143			scsi_ulto2b(entry->length, one->cdb_length);
7144			one->cdb_usage[0] = opcode;
7145			memcpy(&one->cdb_usage[1], entry->usage,
7146			    entry->length - 1);
7147		} else
7148			one->support = 1;
7149		break;
7150	}
7151
7152	ctl_set_success(ctsio);
7153	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7154	ctsio->be_move_done = ctl_config_move_done;
7155	ctl_datamove((union ctl_io *)ctsio);
7156	return(retval);
7157}
7158
7159int
7160ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7161{
7162	struct scsi_report_supported_tmf *cdb;
7163	struct scsi_report_supported_tmf_data *data;
7164	int retval;
7165	int alloc_len, total_len;
7166
7167	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7168
7169	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7170
7171	retval = CTL_RETVAL_COMPLETE;
7172
7173	total_len = sizeof(struct scsi_report_supported_tmf_data);
7174	alloc_len = scsi_4btoul(cdb->length);
7175
7176	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7177
7178	ctsio->kern_sg_entries = 0;
7179
7180	if (total_len < alloc_len) {
7181		ctsio->residual = alloc_len - total_len;
7182		ctsio->kern_data_len = total_len;
7183		ctsio->kern_total_len = total_len;
7184	} else {
7185		ctsio->residual = 0;
7186		ctsio->kern_data_len = alloc_len;
7187		ctsio->kern_total_len = alloc_len;
7188	}
7189	ctsio->kern_data_resid = 0;
7190	ctsio->kern_rel_offset = 0;
7191
7192	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7193	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7194	data->byte2 |= RST_ITNRS;
7195
7196	ctl_set_success(ctsio);
7197	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7198	ctsio->be_move_done = ctl_config_move_done;
7199	ctl_datamove((union ctl_io *)ctsio);
7200	return (retval);
7201}
7202
7203int
7204ctl_report_timestamp(struct ctl_scsiio *ctsio)
7205{
7206	struct scsi_report_timestamp *cdb;
7207	struct scsi_report_timestamp_data *data;
7208	struct timeval tv;
7209	int64_t timestamp;
7210	int retval;
7211	int alloc_len, total_len;
7212
7213	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7214
7215	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7216
7217	retval = CTL_RETVAL_COMPLETE;
7218
7219	total_len = sizeof(struct scsi_report_timestamp_data);
7220	alloc_len = scsi_4btoul(cdb->length);
7221
7222	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7223
7224	ctsio->kern_sg_entries = 0;
7225
7226	if (total_len < alloc_len) {
7227		ctsio->residual = alloc_len - total_len;
7228		ctsio->kern_data_len = total_len;
7229		ctsio->kern_total_len = total_len;
7230	} else {
7231		ctsio->residual = 0;
7232		ctsio->kern_data_len = alloc_len;
7233		ctsio->kern_total_len = alloc_len;
7234	}
7235	ctsio->kern_data_resid = 0;
7236	ctsio->kern_rel_offset = 0;
7237
7238	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7239	scsi_ulto2b(sizeof(*data) - 2, data->length);
7240	data->origin = RTS_ORIG_OUTSIDE;
7241	getmicrotime(&tv);
7242	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7243	scsi_ulto4b(timestamp >> 16, data->timestamp);
7244	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7245
7246	ctl_set_success(ctsio);
7247	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7248	ctsio->be_move_done = ctl_config_move_done;
7249	ctl_datamove((union ctl_io *)ctsio);
7250	return (retval);
7251}
7252
7253int
7254ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7255{
7256	struct scsi_per_res_in *cdb;
7257	int alloc_len, total_len = 0;
7258	/* struct scsi_per_res_in_rsrv in_data; */
7259	struct ctl_lun *lun;
7260	struct ctl_softc *softc;
7261	uint64_t key;
7262
7263	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7264
7265	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7266
7267	alloc_len = scsi_2btoul(cdb->length);
7268
7269	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7270	softc = lun->ctl_softc;
7271
7272retry:
7273	mtx_lock(&lun->lun_lock);
7274	switch (cdb->action) {
7275	case SPRI_RK: /* read keys */
7276		total_len = sizeof(struct scsi_per_res_in_keys) +
7277			lun->pr_key_count *
7278			sizeof(struct scsi_per_res_key);
7279		break;
7280	case SPRI_RR: /* read reservation */
7281		if (lun->flags & CTL_LUN_PR_RESERVED)
7282			total_len = sizeof(struct scsi_per_res_in_rsrv);
7283		else
7284			total_len = sizeof(struct scsi_per_res_in_header);
7285		break;
7286	case SPRI_RC: /* report capabilities */
7287		total_len = sizeof(struct scsi_per_res_cap);
7288		break;
7289	case SPRI_RS: /* read full status */
7290		total_len = sizeof(struct scsi_per_res_in_header) +
7291		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7292		    lun->pr_key_count;
7293		break;
7294	default:
7295		panic("Invalid PR type %x", cdb->action);
7296	}
7297	mtx_unlock(&lun->lun_lock);
7298
7299	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7300
7301	if (total_len < alloc_len) {
7302		ctsio->residual = alloc_len - total_len;
7303		ctsio->kern_data_len = total_len;
7304		ctsio->kern_total_len = total_len;
7305	} else {
7306		ctsio->residual = 0;
7307		ctsio->kern_data_len = alloc_len;
7308		ctsio->kern_total_len = alloc_len;
7309	}
7310
7311	ctsio->kern_data_resid = 0;
7312	ctsio->kern_rel_offset = 0;
7313	ctsio->kern_sg_entries = 0;
7314
7315	mtx_lock(&lun->lun_lock);
7316	switch (cdb->action) {
7317	case SPRI_RK: { // read keys
7318        struct scsi_per_res_in_keys *res_keys;
7319		int i, key_count;
7320
7321		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7322
7323		/*
7324		 * We had to drop the lock to allocate our buffer, which
7325		 * leaves time for someone to come in with another
7326		 * persistent reservation.  (That is unlikely, though,
7327		 * since this should be the only persistent reservation
7328		 * command active right now.)
7329		 */
7330		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7331		    (lun->pr_key_count *
7332		     sizeof(struct scsi_per_res_key)))){
7333			mtx_unlock(&lun->lun_lock);
7334			free(ctsio->kern_data_ptr, M_CTL);
7335			printf("%s: reservation length changed, retrying\n",
7336			       __func__);
7337			goto retry;
7338		}
7339
7340		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7341
7342		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7343			     lun->pr_key_count, res_keys->header.length);
7344
7345		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7346			if ((key = ctl_get_prkey(lun, i)) == 0)
7347				continue;
7348
7349			/*
7350			 * We used lun->pr_key_count to calculate the
7351			 * size to allocate.  If it turns out the number of
7352			 * initiators with the registered flag set is
7353			 * larger than that (i.e. they haven't been kept in
7354			 * sync), we've got a problem.
7355			 */
7356			if (key_count >= lun->pr_key_count) {
7357#ifdef NEEDTOPORT
7358				csevent_log(CSC_CTL | CSC_SHELF_SW |
7359					    CTL_PR_ERROR,
7360					    csevent_LogType_Fault,
7361					    csevent_AlertLevel_Yellow,
7362					    csevent_FRU_ShelfController,
7363					    csevent_FRU_Firmware,
7364				        csevent_FRU_Unknown,
7365					    "registered keys %d >= key "
7366					    "count %d", key_count,
7367					    lun->pr_key_count);
7368#endif
7369				key_count++;
7370				continue;
7371			}
7372			scsi_u64to8b(key, res_keys->keys[key_count].key);
7373			key_count++;
7374		}
7375		break;
7376	}
7377	case SPRI_RR: { // read reservation
7378		struct scsi_per_res_in_rsrv *res;
7379		int tmp_len, header_only;
7380
7381		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7382
7383		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7384
7385		if (lun->flags & CTL_LUN_PR_RESERVED)
7386		{
7387			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7388			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7389				    res->header.length);
7390			header_only = 0;
7391		} else {
7392			tmp_len = sizeof(struct scsi_per_res_in_header);
7393			scsi_ulto4b(0, res->header.length);
7394			header_only = 1;
7395		}
7396
7397		/*
7398		 * We had to drop the lock to allocate our buffer, which
7399		 * leaves time for someone to come in with another
7400		 * persistent reservation.  (That is unlikely, though,
7401		 * since this should be the only persistent reservation
7402		 * command active right now.)
7403		 */
7404		if (tmp_len != total_len) {
7405			mtx_unlock(&lun->lun_lock);
7406			free(ctsio->kern_data_ptr, M_CTL);
7407			printf("%s: reservation status changed, retrying\n",
7408			       __func__);
7409			goto retry;
7410		}
7411
7412		/*
7413		 * No reservation held, so we're done.
7414		 */
7415		if (header_only != 0)
7416			break;
7417
7418		/*
7419		 * If the registration is an All Registrants type, the key
7420		 * is 0, since it doesn't really matter.
7421		 */
7422		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7423			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7424			    res->data.reservation);
7425		}
7426		res->data.scopetype = lun->res_type;
7427		break;
7428	}
7429	case SPRI_RC:     //report capabilities
7430	{
7431		struct scsi_per_res_cap *res_cap;
7432		uint16_t type_mask;
7433
7434		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7435		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7436		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7437		type_mask = SPRI_TM_WR_EX_AR |
7438			    SPRI_TM_EX_AC_RO |
7439			    SPRI_TM_WR_EX_RO |
7440			    SPRI_TM_EX_AC |
7441			    SPRI_TM_WR_EX |
7442			    SPRI_TM_EX_AC_AR;
7443		scsi_ulto2b(type_mask, res_cap->type_mask);
7444		break;
7445	}
7446	case SPRI_RS: { // read full status
7447		struct scsi_per_res_in_full *res_status;
7448		struct scsi_per_res_in_full_desc *res_desc;
7449		struct ctl_port *port;
7450		int i, len;
7451
7452		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7453
7454		/*
7455		 * We had to drop the lock to allocate our buffer, which
7456		 * leaves time for someone to come in with another
7457		 * persistent reservation.  (That is unlikely, though,
7458		 * since this should be the only persistent reservation
7459		 * command active right now.)
7460		 */
7461		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7462		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7463		     lun->pr_key_count)){
7464			mtx_unlock(&lun->lun_lock);
7465			free(ctsio->kern_data_ptr, M_CTL);
7466			printf("%s: reservation length changed, retrying\n",
7467			       __func__);
7468			goto retry;
7469		}
7470
7471		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7472
7473		res_desc = &res_status->desc[0];
7474		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7475			if ((key = ctl_get_prkey(lun, i)) == 0)
7476				continue;
7477
7478			scsi_u64to8b(key, res_desc->res_key.key);
7479			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7480			    (lun->pr_res_idx == i ||
7481			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7482				res_desc->flags = SPRI_FULL_R_HOLDER;
7483				res_desc->scopetype = lun->res_type;
7484			}
7485			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7486			    res_desc->rel_trgt_port_id);
7487			len = 0;
7488			port = softc->ctl_ports[
7489			    ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
7490			if (port != NULL)
7491				len = ctl_create_iid(port,
7492				    i % CTL_MAX_INIT_PER_PORT,
7493				    res_desc->transport_id);
7494			scsi_ulto4b(len, res_desc->additional_length);
7495			res_desc = (struct scsi_per_res_in_full_desc *)
7496			    &res_desc->transport_id[len];
7497		}
7498		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7499		    res_status->header.length);
7500		break;
7501	}
7502	default:
7503		/*
7504		 * This is a bug, because we just checked for this above,
7505		 * and should have returned an error.
7506		 */
7507		panic("Invalid PR type %x", cdb->action);
7508		break; /* NOTREACHED */
7509	}
7510	mtx_unlock(&lun->lun_lock);
7511
7512	ctl_set_success(ctsio);
7513	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7514	ctsio->be_move_done = ctl_config_move_done;
7515	ctl_datamove((union ctl_io *)ctsio);
7516	return (CTL_RETVAL_COMPLETE);
7517}
7518
7519static void
7520ctl_est_res_ua(struct ctl_lun *lun, uint32_t residx, ctl_ua_type ua)
7521{
7522	int off = lun->ctl_softc->persis_offset;
7523
7524	if (residx >= off && residx < off + CTL_MAX_INITIATORS)
7525		ctl_est_ua(lun, residx - off, ua);
7526}
7527
7528/*
7529 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7530 * it should return.
7531 */
7532static int
7533ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7534		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7535		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7536		struct scsi_per_res_out_parms* param)
7537{
7538	union ctl_ha_msg persis_io;
7539	int retval, i;
7540	int isc_retval;
7541
7542	retval = 0;
7543
7544	mtx_lock(&lun->lun_lock);
7545	if (sa_res_key == 0) {
7546		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7547			/* validate scope and type */
7548			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7549			     SPR_LU_SCOPE) {
7550				mtx_unlock(&lun->lun_lock);
7551				ctl_set_invalid_field(/*ctsio*/ ctsio,
7552						      /*sks_valid*/ 1,
7553						      /*command*/ 1,
7554						      /*field*/ 2,
7555						      /*bit_valid*/ 1,
7556						      /*bit*/ 4);
7557				ctl_done((union ctl_io *)ctsio);
7558				return (1);
7559			}
7560
7561		        if (type>8 || type==2 || type==4 || type==0) {
7562				mtx_unlock(&lun->lun_lock);
7563				ctl_set_invalid_field(/*ctsio*/ ctsio,
7564       	           				      /*sks_valid*/ 1,
7565						      /*command*/ 1,
7566						      /*field*/ 2,
7567						      /*bit_valid*/ 1,
7568						      /*bit*/ 0);
7569				ctl_done((union ctl_io *)ctsio);
7570				return (1);
7571		        }
7572
7573			/*
7574			 * Unregister everybody else and build UA for
7575			 * them
7576			 */
7577			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7578				if (i == residx || ctl_get_prkey(lun, i) == 0)
7579					continue;
7580
7581				ctl_clr_prkey(lun, i);
7582				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
7583			}
7584			lun->pr_key_count = 1;
7585			lun->res_type = type;
7586			if (lun->res_type != SPR_TYPE_WR_EX_AR
7587			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7588				lun->pr_res_idx = residx;
7589
7590			/* send msg to other side */
7591			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7592			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7593			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7594			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7595			persis_io.pr.pr_info.res_type = type;
7596			memcpy(persis_io.pr.pr_info.sa_res_key,
7597			       param->serv_act_res_key,
7598			       sizeof(param->serv_act_res_key));
7599			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7600			     &persis_io, sizeof(persis_io), 0)) >
7601			     CTL_HA_STATUS_SUCCESS) {
7602				printf("CTL:Persis Out error returned "
7603				       "from ctl_ha_msg_send %d\n",
7604				       isc_retval);
7605			}
7606		} else {
7607			/* not all registrants */
7608			mtx_unlock(&lun->lun_lock);
7609			free(ctsio->kern_data_ptr, M_CTL);
7610			ctl_set_invalid_field(ctsio,
7611					      /*sks_valid*/ 1,
7612					      /*command*/ 0,
7613					      /*field*/ 8,
7614					      /*bit_valid*/ 0,
7615					      /*bit*/ 0);
7616			ctl_done((union ctl_io *)ctsio);
7617			return (1);
7618		}
7619	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7620		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7621		int found = 0;
7622
7623		if (res_key == sa_res_key) {
7624			/* special case */
7625			/*
7626			 * The spec implies this is not good but doesn't
7627			 * say what to do. There are two choices either
7628			 * generate a res conflict or check condition
7629			 * with illegal field in parameter data. Since
7630			 * that is what is done when the sa_res_key is
7631			 * zero I'll take that approach since this has
7632			 * to do with the sa_res_key.
7633			 */
7634			mtx_unlock(&lun->lun_lock);
7635			free(ctsio->kern_data_ptr, M_CTL);
7636			ctl_set_invalid_field(ctsio,
7637					      /*sks_valid*/ 1,
7638					      /*command*/ 0,
7639					      /*field*/ 8,
7640					      /*bit_valid*/ 0,
7641					      /*bit*/ 0);
7642			ctl_done((union ctl_io *)ctsio);
7643			return (1);
7644		}
7645
7646		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7647			if (ctl_get_prkey(lun, i) != sa_res_key)
7648				continue;
7649
7650			found = 1;
7651			ctl_clr_prkey(lun, i);
7652			lun->pr_key_count--;
7653			ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
7654		}
7655		if (!found) {
7656			mtx_unlock(&lun->lun_lock);
7657			free(ctsio->kern_data_ptr, M_CTL);
7658			ctl_set_reservation_conflict(ctsio);
7659			ctl_done((union ctl_io *)ctsio);
7660			return (CTL_RETVAL_COMPLETE);
7661		}
7662		/* send msg to other side */
7663		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7664		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7665		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7666		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7667		persis_io.pr.pr_info.res_type = type;
7668		memcpy(persis_io.pr.pr_info.sa_res_key,
7669		       param->serv_act_res_key,
7670		       sizeof(param->serv_act_res_key));
7671		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7672		     &persis_io, sizeof(persis_io), 0)) >
7673		     CTL_HA_STATUS_SUCCESS) {
7674			printf("CTL:Persis Out error returned from "
7675			       "ctl_ha_msg_send %d\n", isc_retval);
7676		}
7677	} else {
7678		/* Reserved but not all registrants */
7679		/* sa_res_key is res holder */
7680		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7681			/* validate scope and type */
7682			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7683			     SPR_LU_SCOPE) {
7684				mtx_unlock(&lun->lun_lock);
7685				ctl_set_invalid_field(/*ctsio*/ ctsio,
7686						      /*sks_valid*/ 1,
7687						      /*command*/ 1,
7688						      /*field*/ 2,
7689						      /*bit_valid*/ 1,
7690						      /*bit*/ 4);
7691				ctl_done((union ctl_io *)ctsio);
7692				return (1);
7693			}
7694
7695			if (type>8 || type==2 || type==4 || type==0) {
7696				mtx_unlock(&lun->lun_lock);
7697				ctl_set_invalid_field(/*ctsio*/ ctsio,
7698						      /*sks_valid*/ 1,
7699						      /*command*/ 1,
7700						      /*field*/ 2,
7701						      /*bit_valid*/ 1,
7702						      /*bit*/ 0);
7703				ctl_done((union ctl_io *)ctsio);
7704				return (1);
7705			}
7706
7707			/*
7708			 * Do the following:
7709			 * if sa_res_key != res_key remove all
7710			 * registrants w/sa_res_key and generate UA
7711			 * for these registrants(Registrations
7712			 * Preempted) if it wasn't an exclusive
7713			 * reservation generate UA(Reservations
7714			 * Preempted) for all other registered nexuses
7715			 * if the type has changed. Establish the new
7716			 * reservation and holder. If res_key and
7717			 * sa_res_key are the same do the above
7718			 * except don't unregister the res holder.
7719			 */
7720
7721			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7722				if (i == residx || ctl_get_prkey(lun, i) == 0)
7723					continue;
7724
7725				if (sa_res_key == ctl_get_prkey(lun, i)) {
7726					ctl_clr_prkey(lun, i);
7727					lun->pr_key_count--;
7728					ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
7729				} else if (type != lun->res_type
7730					&& (lun->res_type == SPR_TYPE_WR_EX_RO
7731					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
7732					ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
7733				}
7734			}
7735			lun->res_type = type;
7736			if (lun->res_type != SPR_TYPE_WR_EX_AR
7737			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7738				lun->pr_res_idx = residx;
7739			else
7740				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7741
7742			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7743			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7744			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7745			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7746			persis_io.pr.pr_info.res_type = type;
7747			memcpy(persis_io.pr.pr_info.sa_res_key,
7748			       param->serv_act_res_key,
7749			       sizeof(param->serv_act_res_key));
7750			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7751			     &persis_io, sizeof(persis_io), 0)) >
7752			     CTL_HA_STATUS_SUCCESS) {
7753				printf("CTL:Persis Out error returned "
7754				       "from ctl_ha_msg_send %d\n",
7755				       isc_retval);
7756			}
7757		} else {
7758			/*
7759			 * sa_res_key is not the res holder just
7760			 * remove registrants
7761			 */
7762			int found=0;
7763
7764			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7765				if (sa_res_key != ctl_get_prkey(lun, i))
7766					continue;
7767
7768				found = 1;
7769				ctl_clr_prkey(lun, i);
7770				lun->pr_key_count--;
7771				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
7772			}
7773
7774			if (!found) {
7775				mtx_unlock(&lun->lun_lock);
7776				free(ctsio->kern_data_ptr, M_CTL);
7777				ctl_set_reservation_conflict(ctsio);
7778				ctl_done((union ctl_io *)ctsio);
7779		        	return (1);
7780			}
7781			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7782			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7783			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7784			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7785			persis_io.pr.pr_info.res_type = type;
7786			memcpy(persis_io.pr.pr_info.sa_res_key,
7787			       param->serv_act_res_key,
7788			       sizeof(param->serv_act_res_key));
7789			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7790			     &persis_io, sizeof(persis_io), 0)) >
7791			     CTL_HA_STATUS_SUCCESS) {
7792				printf("CTL:Persis Out error returned "
7793				       "from ctl_ha_msg_send %d\n",
7794				isc_retval);
7795			}
7796		}
7797	}
7798
7799	lun->PRGeneration++;
7800	mtx_unlock(&lun->lun_lock);
7801
7802	return (retval);
7803}
7804
7805static void
7806ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
7807{
7808	uint64_t sa_res_key;
7809	int i;
7810
7811	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
7812
7813	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7814	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
7815	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
7816		if (sa_res_key == 0) {
7817			/*
7818			 * Unregister everybody else and build UA for
7819			 * them
7820			 */
7821			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7822				if (i == msg->pr.pr_info.residx ||
7823				    ctl_get_prkey(lun, i) == 0)
7824					continue;
7825
7826				ctl_clr_prkey(lun, i);
7827				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
7828			}
7829
7830			lun->pr_key_count = 1;
7831			lun->res_type = msg->pr.pr_info.res_type;
7832			if (lun->res_type != SPR_TYPE_WR_EX_AR
7833			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7834				lun->pr_res_idx = msg->pr.pr_info.residx;
7835		} else {
7836		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7837				if (sa_res_key == ctl_get_prkey(lun, i))
7838					continue;
7839
7840				ctl_clr_prkey(lun, i);
7841				lun->pr_key_count--;
7842				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
7843			}
7844		}
7845	} else {
7846		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7847			if (i == msg->pr.pr_info.residx ||
7848			    ctl_get_prkey(lun, i) == 0)
7849				continue;
7850
7851			if (sa_res_key == ctl_get_prkey(lun, i)) {
7852				ctl_clr_prkey(lun, i);
7853				lun->pr_key_count--;
7854				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
7855			} else if (msg->pr.pr_info.res_type != lun->res_type
7856				&& (lun->res_type == SPR_TYPE_WR_EX_RO
7857				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
7858				ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
7859			}
7860		}
7861		lun->res_type = msg->pr.pr_info.res_type;
7862		if (lun->res_type != SPR_TYPE_WR_EX_AR
7863		 && lun->res_type != SPR_TYPE_EX_AC_AR)
7864			lun->pr_res_idx = msg->pr.pr_info.residx;
7865		else
7866			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7867	}
7868	lun->PRGeneration++;
7869
7870}
7871
7872
7873int
7874ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
7875{
7876	int retval;
7877	int isc_retval;
7878	u_int32_t param_len;
7879	struct scsi_per_res_out *cdb;
7880	struct ctl_lun *lun;
7881	struct scsi_per_res_out_parms* param;
7882	struct ctl_softc *softc;
7883	uint32_t residx;
7884	uint64_t res_key, sa_res_key, key;
7885	uint8_t type;
7886	union ctl_ha_msg persis_io;
7887	int    i;
7888
7889	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
7890
7891	retval = CTL_RETVAL_COMPLETE;
7892
7893	cdb = (struct scsi_per_res_out *)ctsio->cdb;
7894	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7895	softc = lun->ctl_softc;
7896
7897	/*
7898	 * We only support whole-LUN scope.  The scope & type are ignored for
7899	 * register, register and ignore existing key and clear.
7900	 * We sometimes ignore scope and type on preempts too!!
7901	 * Verify reservation type here as well.
7902	 */
7903	type = cdb->scope_type & SPR_TYPE_MASK;
7904	if ((cdb->action == SPRO_RESERVE)
7905	 || (cdb->action == SPRO_RELEASE)) {
7906		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
7907			ctl_set_invalid_field(/*ctsio*/ ctsio,
7908					      /*sks_valid*/ 1,
7909					      /*command*/ 1,
7910					      /*field*/ 2,
7911					      /*bit_valid*/ 1,
7912					      /*bit*/ 4);
7913			ctl_done((union ctl_io *)ctsio);
7914			return (CTL_RETVAL_COMPLETE);
7915		}
7916
7917		if (type>8 || type==2 || type==4 || type==0) {
7918			ctl_set_invalid_field(/*ctsio*/ ctsio,
7919					      /*sks_valid*/ 1,
7920					      /*command*/ 1,
7921					      /*field*/ 2,
7922					      /*bit_valid*/ 1,
7923					      /*bit*/ 0);
7924			ctl_done((union ctl_io *)ctsio);
7925			return (CTL_RETVAL_COMPLETE);
7926		}
7927	}
7928
7929	param_len = scsi_4btoul(cdb->length);
7930
7931	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
7932		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
7933		ctsio->kern_data_len = param_len;
7934		ctsio->kern_total_len = param_len;
7935		ctsio->kern_data_resid = 0;
7936		ctsio->kern_rel_offset = 0;
7937		ctsio->kern_sg_entries = 0;
7938		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7939		ctsio->be_move_done = ctl_config_move_done;
7940		ctl_datamove((union ctl_io *)ctsio);
7941
7942		return (CTL_RETVAL_COMPLETE);
7943	}
7944
7945	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
7946
7947	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
7948	res_key = scsi_8btou64(param->res_key.key);
7949	sa_res_key = scsi_8btou64(param->serv_act_res_key);
7950
7951	/*
7952	 * Validate the reservation key here except for SPRO_REG_IGNO
7953	 * This must be done for all other service actions
7954	 */
7955	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
7956		mtx_lock(&lun->lun_lock);
7957		if ((key = ctl_get_prkey(lun, residx)) != 0) {
7958			if (res_key != key) {
7959				/*
7960				 * The current key passed in doesn't match
7961				 * the one the initiator previously
7962				 * registered.
7963				 */
7964				mtx_unlock(&lun->lun_lock);
7965				free(ctsio->kern_data_ptr, M_CTL);
7966				ctl_set_reservation_conflict(ctsio);
7967				ctl_done((union ctl_io *)ctsio);
7968				return (CTL_RETVAL_COMPLETE);
7969			}
7970		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
7971			/*
7972			 * We are not registered
7973			 */
7974			mtx_unlock(&lun->lun_lock);
7975			free(ctsio->kern_data_ptr, M_CTL);
7976			ctl_set_reservation_conflict(ctsio);
7977			ctl_done((union ctl_io *)ctsio);
7978			return (CTL_RETVAL_COMPLETE);
7979		} else if (res_key != 0) {
7980			/*
7981			 * We are not registered and trying to register but
7982			 * the register key isn't zero.
7983			 */
7984			mtx_unlock(&lun->lun_lock);
7985			free(ctsio->kern_data_ptr, M_CTL);
7986			ctl_set_reservation_conflict(ctsio);
7987			ctl_done((union ctl_io *)ctsio);
7988			return (CTL_RETVAL_COMPLETE);
7989		}
7990		mtx_unlock(&lun->lun_lock);
7991	}
7992
7993	switch (cdb->action & SPRO_ACTION_MASK) {
7994	case SPRO_REGISTER:
7995	case SPRO_REG_IGNO: {
7996
7997#if 0
7998		printf("Registration received\n");
7999#endif
8000
8001		/*
8002		 * We don't support any of these options, as we report in
8003		 * the read capabilities request (see
8004		 * ctl_persistent_reserve_in(), above).
8005		 */
8006		if ((param->flags & SPR_SPEC_I_PT)
8007		 || (param->flags & SPR_ALL_TG_PT)
8008		 || (param->flags & SPR_APTPL)) {
8009			int bit_ptr;
8010
8011			if (param->flags & SPR_APTPL)
8012				bit_ptr = 0;
8013			else if (param->flags & SPR_ALL_TG_PT)
8014				bit_ptr = 2;
8015			else /* SPR_SPEC_I_PT */
8016				bit_ptr = 3;
8017
8018			free(ctsio->kern_data_ptr, M_CTL);
8019			ctl_set_invalid_field(ctsio,
8020					      /*sks_valid*/ 1,
8021					      /*command*/ 0,
8022					      /*field*/ 20,
8023					      /*bit_valid*/ 1,
8024					      /*bit*/ bit_ptr);
8025			ctl_done((union ctl_io *)ctsio);
8026			return (CTL_RETVAL_COMPLETE);
8027		}
8028
8029		mtx_lock(&lun->lun_lock);
8030
8031		/*
8032		 * The initiator wants to clear the
8033		 * key/unregister.
8034		 */
8035		if (sa_res_key == 0) {
8036			if ((res_key == 0
8037			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8038			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8039			  && ctl_get_prkey(lun, residx) == 0)) {
8040				mtx_unlock(&lun->lun_lock);
8041				goto done;
8042			}
8043
8044			ctl_clr_prkey(lun, residx);
8045			lun->pr_key_count--;
8046
8047			if (residx == lun->pr_res_idx) {
8048				lun->flags &= ~CTL_LUN_PR_RESERVED;
8049				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8050
8051				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8052				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8053				 && lun->pr_key_count) {
8054					/*
8055					 * If the reservation is a registrants
8056					 * only type we need to generate a UA
8057					 * for other registered inits.  The
8058					 * sense code should be RESERVATIONS
8059					 * RELEASED
8060					 */
8061
8062					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8063						if (ctl_get_prkey(lun, i +
8064						    softc->persis_offset) == 0)
8065							continue;
8066						ctl_est_ua(lun, i,
8067						    CTL_UA_RES_RELEASE);
8068					}
8069				}
8070				lun->res_type = 0;
8071			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8072				if (lun->pr_key_count==0) {
8073					lun->flags &= ~CTL_LUN_PR_RESERVED;
8074					lun->res_type = 0;
8075					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8076				}
8077			}
8078			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8079			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8080			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8081			persis_io.pr.pr_info.residx = residx;
8082			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8083			     &persis_io, sizeof(persis_io), 0 )) >
8084			     CTL_HA_STATUS_SUCCESS) {
8085				printf("CTL:Persis Out error returned from "
8086				       "ctl_ha_msg_send %d\n", isc_retval);
8087			}
8088		} else /* sa_res_key != 0 */ {
8089
8090			/*
8091			 * If we aren't registered currently then increment
8092			 * the key count and set the registered flag.
8093			 */
8094			ctl_alloc_prkey(lun, residx);
8095			if (ctl_get_prkey(lun, residx) == 0)
8096				lun->pr_key_count++;
8097			ctl_set_prkey(lun, residx, sa_res_key);
8098
8099			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8100			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8101			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8102			persis_io.pr.pr_info.residx = residx;
8103			memcpy(persis_io.pr.pr_info.sa_res_key,
8104			       param->serv_act_res_key,
8105			       sizeof(param->serv_act_res_key));
8106			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8107			     &persis_io, sizeof(persis_io), 0)) >
8108			     CTL_HA_STATUS_SUCCESS) {
8109				printf("CTL:Persis Out error returned from "
8110				       "ctl_ha_msg_send %d\n", isc_retval);
8111			}
8112		}
8113		lun->PRGeneration++;
8114		mtx_unlock(&lun->lun_lock);
8115
8116		break;
8117	}
8118	case SPRO_RESERVE:
8119#if 0
8120                printf("Reserve executed type %d\n", type);
8121#endif
8122		mtx_lock(&lun->lun_lock);
8123		if (lun->flags & CTL_LUN_PR_RESERVED) {
8124			/*
8125			 * if this isn't the reservation holder and it's
8126			 * not a "all registrants" type or if the type is
8127			 * different then we have a conflict
8128			 */
8129			if ((lun->pr_res_idx != residx
8130			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8131			 || lun->res_type != type) {
8132				mtx_unlock(&lun->lun_lock);
8133				free(ctsio->kern_data_ptr, M_CTL);
8134				ctl_set_reservation_conflict(ctsio);
8135				ctl_done((union ctl_io *)ctsio);
8136				return (CTL_RETVAL_COMPLETE);
8137			}
8138			mtx_unlock(&lun->lun_lock);
8139		} else /* create a reservation */ {
8140			/*
8141			 * If it's not an "all registrants" type record
8142			 * reservation holder
8143			 */
8144			if (type != SPR_TYPE_WR_EX_AR
8145			 && type != SPR_TYPE_EX_AC_AR)
8146				lun->pr_res_idx = residx; /* Res holder */
8147			else
8148				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8149
8150			lun->flags |= CTL_LUN_PR_RESERVED;
8151			lun->res_type = type;
8152
8153			mtx_unlock(&lun->lun_lock);
8154
8155			/* send msg to other side */
8156			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8157			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8158			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8159			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8160			persis_io.pr.pr_info.res_type = type;
8161			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8162			     &persis_io, sizeof(persis_io), 0)) >
8163			     CTL_HA_STATUS_SUCCESS) {
8164				printf("CTL:Persis Out error returned from "
8165				       "ctl_ha_msg_send %d\n", isc_retval);
8166			}
8167		}
8168		break;
8169
8170	case SPRO_RELEASE:
8171		mtx_lock(&lun->lun_lock);
8172		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8173			/* No reservation exists return good status */
8174			mtx_unlock(&lun->lun_lock);
8175			goto done;
8176		}
8177		/*
8178		 * Is this nexus a reservation holder?
8179		 */
8180		if (lun->pr_res_idx != residx
8181		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8182			/*
8183			 * not a res holder return good status but
8184			 * do nothing
8185			 */
8186			mtx_unlock(&lun->lun_lock);
8187			goto done;
8188		}
8189
8190		if (lun->res_type != type) {
8191			mtx_unlock(&lun->lun_lock);
8192			free(ctsio->kern_data_ptr, M_CTL);
8193			ctl_set_illegal_pr_release(ctsio);
8194			ctl_done((union ctl_io *)ctsio);
8195			return (CTL_RETVAL_COMPLETE);
8196		}
8197
8198		/* okay to release */
8199		lun->flags &= ~CTL_LUN_PR_RESERVED;
8200		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8201		lun->res_type = 0;
8202
8203		/*
8204		 * if this isn't an exclusive access
8205		 * res generate UA for all other
8206		 * registrants.
8207		 */
8208		if (type != SPR_TYPE_EX_AC
8209		 && type != SPR_TYPE_WR_EX) {
8210			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8211				if (i == residx ||
8212				    ctl_get_prkey(lun,
8213				     i + softc->persis_offset) == 0)
8214					continue;
8215				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8216			}
8217		}
8218		mtx_unlock(&lun->lun_lock);
8219		/* Send msg to other side */
8220		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8221		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8222		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8223		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8224		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8225			printf("CTL:Persis Out error returned from "
8226			       "ctl_ha_msg_send %d\n", isc_retval);
8227		}
8228		break;
8229
8230	case SPRO_CLEAR:
8231		/* send msg to other side */
8232
8233		mtx_lock(&lun->lun_lock);
8234		lun->flags &= ~CTL_LUN_PR_RESERVED;
8235		lun->res_type = 0;
8236		lun->pr_key_count = 0;
8237		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8238
8239		ctl_clr_prkey(lun, residx);
8240		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8241			if (ctl_get_prkey(lun, i) != 0) {
8242				ctl_clr_prkey(lun, i);
8243				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8244			}
8245		lun->PRGeneration++;
8246		mtx_unlock(&lun->lun_lock);
8247		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8248		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8249		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8250		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8251		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8252			printf("CTL:Persis Out error returned from "
8253			       "ctl_ha_msg_send %d\n", isc_retval);
8254		}
8255		break;
8256
8257	case SPRO_PREEMPT:
8258	case SPRO_PRE_ABO: {
8259		int nretval;
8260
8261		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8262					  residx, ctsio, cdb, param);
8263		if (nretval != 0)
8264			return (CTL_RETVAL_COMPLETE);
8265		break;
8266	}
8267	default:
8268		panic("Invalid PR type %x", cdb->action);
8269	}
8270
8271done:
8272	free(ctsio->kern_data_ptr, M_CTL);
8273	ctl_set_success(ctsio);
8274	ctl_done((union ctl_io *)ctsio);
8275
8276	return (retval);
8277}
8278
8279/*
8280 * This routine is for handling a message from the other SC pertaining to
8281 * persistent reserve out. All the error checking will have been done
8282 * so only perorming the action need be done here to keep the two
8283 * in sync.
8284 */
8285static void
8286ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8287{
8288	struct ctl_lun *lun;
8289	struct ctl_softc *softc;
8290	int i;
8291	uint32_t targ_lun;
8292
8293	softc = control_softc;
8294
8295	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8296	lun = softc->ctl_luns[targ_lun];
8297	mtx_lock(&lun->lun_lock);
8298	switch(msg->pr.pr_info.action) {
8299	case CTL_PR_REG_KEY:
8300		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8301		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8302			lun->pr_key_count++;
8303		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8304		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8305		lun->PRGeneration++;
8306		break;
8307
8308	case CTL_PR_UNREG_KEY:
8309		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8310		lun->pr_key_count--;
8311
8312		/* XXX Need to see if the reservation has been released */
8313		/* if so do we need to generate UA? */
8314		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8315			lun->flags &= ~CTL_LUN_PR_RESERVED;
8316			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8317
8318			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8319			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8320			 && lun->pr_key_count) {
8321				/*
8322				 * If the reservation is a registrants
8323				 * only type we need to generate a UA
8324				 * for other registered inits.  The
8325				 * sense code should be RESERVATIONS
8326				 * RELEASED
8327				 */
8328
8329				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8330					if (ctl_get_prkey(lun, i +
8331					    softc->persis_offset) == 0)
8332						continue;
8333
8334					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8335				}
8336			}
8337			lun->res_type = 0;
8338		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8339			if (lun->pr_key_count==0) {
8340				lun->flags &= ~CTL_LUN_PR_RESERVED;
8341				lun->res_type = 0;
8342				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8343			}
8344		}
8345		lun->PRGeneration++;
8346		break;
8347
8348	case CTL_PR_RESERVE:
8349		lun->flags |= CTL_LUN_PR_RESERVED;
8350		lun->res_type = msg->pr.pr_info.res_type;
8351		lun->pr_res_idx = msg->pr.pr_info.residx;
8352
8353		break;
8354
8355	case CTL_PR_RELEASE:
8356		/*
8357		 * if this isn't an exclusive access res generate UA for all
8358		 * other registrants.
8359		 */
8360		if (lun->res_type != SPR_TYPE_EX_AC
8361		 && lun->res_type != SPR_TYPE_WR_EX) {
8362			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8363				if (ctl_get_prkey(lun, i + softc->persis_offset) != 0)
8364					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8365		}
8366
8367		lun->flags &= ~CTL_LUN_PR_RESERVED;
8368		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8369		lun->res_type = 0;
8370		break;
8371
8372	case CTL_PR_PREEMPT:
8373		ctl_pro_preempt_other(lun, msg);
8374		break;
8375	case CTL_PR_CLEAR:
8376		lun->flags &= ~CTL_LUN_PR_RESERVED;
8377		lun->res_type = 0;
8378		lun->pr_key_count = 0;
8379		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8380
8381		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8382			if (ctl_get_prkey(lun, i) == 0)
8383				continue;
8384			ctl_clr_prkey(lun, i);
8385			ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8386		}
8387		lun->PRGeneration++;
8388		break;
8389	}
8390
8391	mtx_unlock(&lun->lun_lock);
8392}
8393
8394int
8395ctl_read_write(struct ctl_scsiio *ctsio)
8396{
8397	struct ctl_lun *lun;
8398	struct ctl_lba_len_flags *lbalen;
8399	uint64_t lba;
8400	uint32_t num_blocks;
8401	int flags, retval;
8402	int isread;
8403
8404	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8405
8406	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8407
8408	flags = 0;
8409	retval = CTL_RETVAL_COMPLETE;
8410
8411	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8412	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8413	switch (ctsio->cdb[0]) {
8414	case READ_6:
8415	case WRITE_6: {
8416		struct scsi_rw_6 *cdb;
8417
8418		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8419
8420		lba = scsi_3btoul(cdb->addr);
8421		/* only 5 bits are valid in the most significant address byte */
8422		lba &= 0x1fffff;
8423		num_blocks = cdb->length;
8424		/*
8425		 * This is correct according to SBC-2.
8426		 */
8427		if (num_blocks == 0)
8428			num_blocks = 256;
8429		break;
8430	}
8431	case READ_10:
8432	case WRITE_10: {
8433		struct scsi_rw_10 *cdb;
8434
8435		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8436		if (cdb->byte2 & SRW10_FUA)
8437			flags |= CTL_LLF_FUA;
8438		if (cdb->byte2 & SRW10_DPO)
8439			flags |= CTL_LLF_DPO;
8440		lba = scsi_4btoul(cdb->addr);
8441		num_blocks = scsi_2btoul(cdb->length);
8442		break;
8443	}
8444	case WRITE_VERIFY_10: {
8445		struct scsi_write_verify_10 *cdb;
8446
8447		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8448		flags |= CTL_LLF_FUA;
8449		if (cdb->byte2 & SWV_DPO)
8450			flags |= CTL_LLF_DPO;
8451		lba = scsi_4btoul(cdb->addr);
8452		num_blocks = scsi_2btoul(cdb->length);
8453		break;
8454	}
8455	case READ_12:
8456	case WRITE_12: {
8457		struct scsi_rw_12 *cdb;
8458
8459		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8460		if (cdb->byte2 & SRW12_FUA)
8461			flags |= CTL_LLF_FUA;
8462		if (cdb->byte2 & SRW12_DPO)
8463			flags |= CTL_LLF_DPO;
8464		lba = scsi_4btoul(cdb->addr);
8465		num_blocks = scsi_4btoul(cdb->length);
8466		break;
8467	}
8468	case WRITE_VERIFY_12: {
8469		struct scsi_write_verify_12 *cdb;
8470
8471		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8472		flags |= CTL_LLF_FUA;
8473		if (cdb->byte2 & SWV_DPO)
8474			flags |= CTL_LLF_DPO;
8475		lba = scsi_4btoul(cdb->addr);
8476		num_blocks = scsi_4btoul(cdb->length);
8477		break;
8478	}
8479	case READ_16:
8480	case WRITE_16: {
8481		struct scsi_rw_16 *cdb;
8482
8483		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8484		if (cdb->byte2 & SRW12_FUA)
8485			flags |= CTL_LLF_FUA;
8486		if (cdb->byte2 & SRW12_DPO)
8487			flags |= CTL_LLF_DPO;
8488		lba = scsi_8btou64(cdb->addr);
8489		num_blocks = scsi_4btoul(cdb->length);
8490		break;
8491	}
8492	case WRITE_ATOMIC_16: {
8493		struct scsi_rw_16 *cdb;
8494
8495		if (lun->be_lun->atomicblock == 0) {
8496			ctl_set_invalid_opcode(ctsio);
8497			ctl_done((union ctl_io *)ctsio);
8498			return (CTL_RETVAL_COMPLETE);
8499		}
8500
8501		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8502		if (cdb->byte2 & SRW12_FUA)
8503			flags |= CTL_LLF_FUA;
8504		if (cdb->byte2 & SRW12_DPO)
8505			flags |= CTL_LLF_DPO;
8506		lba = scsi_8btou64(cdb->addr);
8507		num_blocks = scsi_4btoul(cdb->length);
8508		if (num_blocks > lun->be_lun->atomicblock) {
8509			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8510			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8511			    /*bit*/ 0);
8512			ctl_done((union ctl_io *)ctsio);
8513			return (CTL_RETVAL_COMPLETE);
8514		}
8515		break;
8516	}
8517	case WRITE_VERIFY_16: {
8518		struct scsi_write_verify_16 *cdb;
8519
8520		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8521		flags |= CTL_LLF_FUA;
8522		if (cdb->byte2 & SWV_DPO)
8523			flags |= CTL_LLF_DPO;
8524		lba = scsi_8btou64(cdb->addr);
8525		num_blocks = scsi_4btoul(cdb->length);
8526		break;
8527	}
8528	default:
8529		/*
8530		 * We got a command we don't support.  This shouldn't
8531		 * happen, commands should be filtered out above us.
8532		 */
8533		ctl_set_invalid_opcode(ctsio);
8534		ctl_done((union ctl_io *)ctsio);
8535
8536		return (CTL_RETVAL_COMPLETE);
8537		break; /* NOTREACHED */
8538	}
8539
8540	/*
8541	 * The first check is to make sure we're in bounds, the second
8542	 * check is to catch wrap-around problems.  If the lba + num blocks
8543	 * is less than the lba, then we've wrapped around and the block
8544	 * range is invalid anyway.
8545	 */
8546	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8547	 || ((lba + num_blocks) < lba)) {
8548		ctl_set_lba_out_of_range(ctsio);
8549		ctl_done((union ctl_io *)ctsio);
8550		return (CTL_RETVAL_COMPLETE);
8551	}
8552
8553	/*
8554	 * According to SBC-3, a transfer length of 0 is not an error.
8555	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8556	 * translates to 256 blocks for those commands.
8557	 */
8558	if (num_blocks == 0) {
8559		ctl_set_success(ctsio);
8560		ctl_done((union ctl_io *)ctsio);
8561		return (CTL_RETVAL_COMPLETE);
8562	}
8563
8564	/* Set FUA and/or DPO if caches are disabled. */
8565	if (isread) {
8566		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8567		    SCP_RCD) != 0)
8568			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8569	} else {
8570		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8571		    SCP_WCE) == 0)
8572			flags |= CTL_LLF_FUA;
8573	}
8574
8575	lbalen = (struct ctl_lba_len_flags *)
8576	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8577	lbalen->lba = lba;
8578	lbalen->len = num_blocks;
8579	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8580
8581	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8582	ctsio->kern_rel_offset = 0;
8583
8584	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8585
8586	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8587
8588	return (retval);
8589}
8590
8591static int
8592ctl_cnw_cont(union ctl_io *io)
8593{
8594	struct ctl_scsiio *ctsio;
8595	struct ctl_lun *lun;
8596	struct ctl_lba_len_flags *lbalen;
8597	int retval;
8598
8599	ctsio = &io->scsiio;
8600	ctsio->io_hdr.status = CTL_STATUS_NONE;
8601	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8602	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8603	lbalen = (struct ctl_lba_len_flags *)
8604	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8605	lbalen->flags &= ~CTL_LLF_COMPARE;
8606	lbalen->flags |= CTL_LLF_WRITE;
8607
8608	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8609	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8610	return (retval);
8611}
8612
8613int
8614ctl_cnw(struct ctl_scsiio *ctsio)
8615{
8616	struct ctl_lun *lun;
8617	struct ctl_lba_len_flags *lbalen;
8618	uint64_t lba;
8619	uint32_t num_blocks;
8620	int flags, retval;
8621
8622	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8623
8624	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8625
8626	flags = 0;
8627	retval = CTL_RETVAL_COMPLETE;
8628
8629	switch (ctsio->cdb[0]) {
8630	case COMPARE_AND_WRITE: {
8631		struct scsi_compare_and_write *cdb;
8632
8633		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8634		if (cdb->byte2 & SRW10_FUA)
8635			flags |= CTL_LLF_FUA;
8636		if (cdb->byte2 & SRW10_DPO)
8637			flags |= CTL_LLF_DPO;
8638		lba = scsi_8btou64(cdb->addr);
8639		num_blocks = cdb->length;
8640		break;
8641	}
8642	default:
8643		/*
8644		 * We got a command we don't support.  This shouldn't
8645		 * happen, commands should be filtered out above us.
8646		 */
8647		ctl_set_invalid_opcode(ctsio);
8648		ctl_done((union ctl_io *)ctsio);
8649
8650		return (CTL_RETVAL_COMPLETE);
8651		break; /* NOTREACHED */
8652	}
8653
8654	/*
8655	 * The first check is to make sure we're in bounds, the second
8656	 * check is to catch wrap-around problems.  If the lba + num blocks
8657	 * is less than the lba, then we've wrapped around and the block
8658	 * range is invalid anyway.
8659	 */
8660	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8661	 || ((lba + num_blocks) < lba)) {
8662		ctl_set_lba_out_of_range(ctsio);
8663		ctl_done((union ctl_io *)ctsio);
8664		return (CTL_RETVAL_COMPLETE);
8665	}
8666
8667	/*
8668	 * According to SBC-3, a transfer length of 0 is not an error.
8669	 */
8670	if (num_blocks == 0) {
8671		ctl_set_success(ctsio);
8672		ctl_done((union ctl_io *)ctsio);
8673		return (CTL_RETVAL_COMPLETE);
8674	}
8675
8676	/* Set FUA if write cache is disabled. */
8677	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8678	    SCP_WCE) == 0)
8679		flags |= CTL_LLF_FUA;
8680
8681	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8682	ctsio->kern_rel_offset = 0;
8683
8684	/*
8685	 * Set the IO_CONT flag, so that if this I/O gets passed to
8686	 * ctl_data_submit_done(), it'll get passed back to
8687	 * ctl_ctl_cnw_cont() for further processing.
8688	 */
8689	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8690	ctsio->io_cont = ctl_cnw_cont;
8691
8692	lbalen = (struct ctl_lba_len_flags *)
8693	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8694	lbalen->lba = lba;
8695	lbalen->len = num_blocks;
8696	lbalen->flags = CTL_LLF_COMPARE | flags;
8697
8698	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8699	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8700	return (retval);
8701}
8702
8703int
8704ctl_verify(struct ctl_scsiio *ctsio)
8705{
8706	struct ctl_lun *lun;
8707	struct ctl_lba_len_flags *lbalen;
8708	uint64_t lba;
8709	uint32_t num_blocks;
8710	int bytchk, flags;
8711	int retval;
8712
8713	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8714
8715	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8716
8717	bytchk = 0;
8718	flags = CTL_LLF_FUA;
8719	retval = CTL_RETVAL_COMPLETE;
8720
8721	switch (ctsio->cdb[0]) {
8722	case VERIFY_10: {
8723		struct scsi_verify_10 *cdb;
8724
8725		cdb = (struct scsi_verify_10 *)ctsio->cdb;
8726		if (cdb->byte2 & SVFY_BYTCHK)
8727			bytchk = 1;
8728		if (cdb->byte2 & SVFY_DPO)
8729			flags |= CTL_LLF_DPO;
8730		lba = scsi_4btoul(cdb->addr);
8731		num_blocks = scsi_2btoul(cdb->length);
8732		break;
8733	}
8734	case VERIFY_12: {
8735		struct scsi_verify_12 *cdb;
8736
8737		cdb = (struct scsi_verify_12 *)ctsio->cdb;
8738		if (cdb->byte2 & SVFY_BYTCHK)
8739			bytchk = 1;
8740		if (cdb->byte2 & SVFY_DPO)
8741			flags |= CTL_LLF_DPO;
8742		lba = scsi_4btoul(cdb->addr);
8743		num_blocks = scsi_4btoul(cdb->length);
8744		break;
8745	}
8746	case VERIFY_16: {
8747		struct scsi_rw_16 *cdb;
8748
8749		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8750		if (cdb->byte2 & SVFY_BYTCHK)
8751			bytchk = 1;
8752		if (cdb->byte2 & SVFY_DPO)
8753			flags |= CTL_LLF_DPO;
8754		lba = scsi_8btou64(cdb->addr);
8755		num_blocks = scsi_4btoul(cdb->length);
8756		break;
8757	}
8758	default:
8759		/*
8760		 * We got a command we don't support.  This shouldn't
8761		 * happen, commands should be filtered out above us.
8762		 */
8763		ctl_set_invalid_opcode(ctsio);
8764		ctl_done((union ctl_io *)ctsio);
8765		return (CTL_RETVAL_COMPLETE);
8766	}
8767
8768	/*
8769	 * The first check is to make sure we're in bounds, the second
8770	 * check is to catch wrap-around problems.  If the lba + num blocks
8771	 * is less than the lba, then we've wrapped around and the block
8772	 * range is invalid anyway.
8773	 */
8774	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8775	 || ((lba + num_blocks) < lba)) {
8776		ctl_set_lba_out_of_range(ctsio);
8777		ctl_done((union ctl_io *)ctsio);
8778		return (CTL_RETVAL_COMPLETE);
8779	}
8780
8781	/*
8782	 * According to SBC-3, a transfer length of 0 is not an error.
8783	 */
8784	if (num_blocks == 0) {
8785		ctl_set_success(ctsio);
8786		ctl_done((union ctl_io *)ctsio);
8787		return (CTL_RETVAL_COMPLETE);
8788	}
8789
8790	lbalen = (struct ctl_lba_len_flags *)
8791	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8792	lbalen->lba = lba;
8793	lbalen->len = num_blocks;
8794	if (bytchk) {
8795		lbalen->flags = CTL_LLF_COMPARE | flags;
8796		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8797	} else {
8798		lbalen->flags = CTL_LLF_VERIFY | flags;
8799		ctsio->kern_total_len = 0;
8800	}
8801	ctsio->kern_rel_offset = 0;
8802
8803	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
8804	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8805	return (retval);
8806}
8807
8808int
8809ctl_report_luns(struct ctl_scsiio *ctsio)
8810{
8811	struct ctl_softc *softc = control_softc;
8812	struct scsi_report_luns *cdb;
8813	struct scsi_report_luns_data *lun_data;
8814	struct ctl_lun *lun, *request_lun;
8815	struct ctl_port *port;
8816	int num_luns, retval;
8817	uint32_t alloc_len, lun_datalen;
8818	int num_filled, well_known;
8819	uint32_t initidx, targ_lun_id, lun_id;
8820
8821	retval = CTL_RETVAL_COMPLETE;
8822	well_known = 0;
8823
8824	cdb = (struct scsi_report_luns *)ctsio->cdb;
8825	port = ctl_io_port(&ctsio->io_hdr);
8826
8827	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
8828
8829	mtx_lock(&softc->ctl_lock);
8830	num_luns = 0;
8831	for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
8832		if (ctl_lun_map_from_port(port, targ_lun_id) < CTL_MAX_LUNS)
8833			num_luns++;
8834	}
8835	mtx_unlock(&softc->ctl_lock);
8836
8837	switch (cdb->select_report) {
8838	case RPL_REPORT_DEFAULT:
8839	case RPL_REPORT_ALL:
8840		break;
8841	case RPL_REPORT_WELLKNOWN:
8842		well_known = 1;
8843		num_luns = 0;
8844		break;
8845	default:
8846		ctl_set_invalid_field(ctsio,
8847				      /*sks_valid*/ 1,
8848				      /*command*/ 1,
8849				      /*field*/ 2,
8850				      /*bit_valid*/ 0,
8851				      /*bit*/ 0);
8852		ctl_done((union ctl_io *)ctsio);
8853		return (retval);
8854		break; /* NOTREACHED */
8855	}
8856
8857	alloc_len = scsi_4btoul(cdb->length);
8858	/*
8859	 * The initiator has to allocate at least 16 bytes for this request,
8860	 * so he can at least get the header and the first LUN.  Otherwise
8861	 * we reject the request (per SPC-3 rev 14, section 6.21).
8862	 */
8863	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
8864	    sizeof(struct scsi_report_luns_lundata))) {
8865		ctl_set_invalid_field(ctsio,
8866				      /*sks_valid*/ 1,
8867				      /*command*/ 1,
8868				      /*field*/ 6,
8869				      /*bit_valid*/ 0,
8870				      /*bit*/ 0);
8871		ctl_done((union ctl_io *)ctsio);
8872		return (retval);
8873	}
8874
8875	request_lun = (struct ctl_lun *)
8876		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8877
8878	lun_datalen = sizeof(*lun_data) +
8879		(num_luns * sizeof(struct scsi_report_luns_lundata));
8880
8881	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
8882	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
8883	ctsio->kern_sg_entries = 0;
8884
8885	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8886
8887	mtx_lock(&softc->ctl_lock);
8888	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
8889		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
8890		if (lun_id >= CTL_MAX_LUNS)
8891			continue;
8892		lun = softc->ctl_luns[lun_id];
8893		if (lun == NULL)
8894			continue;
8895
8896		if (targ_lun_id <= 0xff) {
8897			/*
8898			 * Peripheral addressing method, bus number 0.
8899			 */
8900			lun_data->luns[num_filled].lundata[0] =
8901				RPL_LUNDATA_ATYP_PERIPH;
8902			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
8903			num_filled++;
8904		} else if (targ_lun_id <= 0x3fff) {
8905			/*
8906			 * Flat addressing method.
8907			 */
8908			lun_data->luns[num_filled].lundata[0] =
8909				RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
8910			lun_data->luns[num_filled].lundata[1] =
8911				(targ_lun_id & 0xff);
8912			num_filled++;
8913		} else if (targ_lun_id <= 0xffffff) {
8914			/*
8915			 * Extended flat addressing method.
8916			 */
8917			lun_data->luns[num_filled].lundata[0] =
8918			    RPL_LUNDATA_ATYP_EXTLUN | 0x12;
8919			scsi_ulto3b(targ_lun_id,
8920			    &lun_data->luns[num_filled].lundata[1]);
8921			num_filled++;
8922		} else {
8923			printf("ctl_report_luns: bogus LUN number %jd, "
8924			       "skipping\n", (intmax_t)targ_lun_id);
8925		}
8926		/*
8927		 * According to SPC-3, rev 14 section 6.21:
8928		 *
8929		 * "The execution of a REPORT LUNS command to any valid and
8930		 * installed logical unit shall clear the REPORTED LUNS DATA
8931		 * HAS CHANGED unit attention condition for all logical
8932		 * units of that target with respect to the requesting
8933		 * initiator. A valid and installed logical unit is one
8934		 * having a PERIPHERAL QUALIFIER of 000b in the standard
8935		 * INQUIRY data (see 6.4.2)."
8936		 *
8937		 * If request_lun is NULL, the LUN this report luns command
8938		 * was issued to is either disabled or doesn't exist. In that
8939		 * case, we shouldn't clear any pending lun change unit
8940		 * attention.
8941		 */
8942		if (request_lun != NULL) {
8943			mtx_lock(&lun->lun_lock);
8944			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
8945			mtx_unlock(&lun->lun_lock);
8946		}
8947	}
8948	mtx_unlock(&softc->ctl_lock);
8949
8950	/*
8951	 * It's quite possible that we've returned fewer LUNs than we allocated
8952	 * space for.  Trim it.
8953	 */
8954	lun_datalen = sizeof(*lun_data) +
8955		(num_filled * sizeof(struct scsi_report_luns_lundata));
8956
8957	if (lun_datalen < alloc_len) {
8958		ctsio->residual = alloc_len - lun_datalen;
8959		ctsio->kern_data_len = lun_datalen;
8960		ctsio->kern_total_len = lun_datalen;
8961	} else {
8962		ctsio->residual = 0;
8963		ctsio->kern_data_len = alloc_len;
8964		ctsio->kern_total_len = alloc_len;
8965	}
8966	ctsio->kern_data_resid = 0;
8967	ctsio->kern_rel_offset = 0;
8968	ctsio->kern_sg_entries = 0;
8969
8970	/*
8971	 * We set this to the actual data length, regardless of how much
8972	 * space we actually have to return results.  If the user looks at
8973	 * this value, he'll know whether or not he allocated enough space
8974	 * and reissue the command if necessary.  We don't support well
8975	 * known logical units, so if the user asks for that, return none.
8976	 */
8977	scsi_ulto4b(lun_datalen - 8, lun_data->length);
8978
8979	/*
8980	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
8981	 * this request.
8982	 */
8983	ctl_set_success(ctsio);
8984	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8985	ctsio->be_move_done = ctl_config_move_done;
8986	ctl_datamove((union ctl_io *)ctsio);
8987	return (retval);
8988}
8989
8990int
8991ctl_request_sense(struct ctl_scsiio *ctsio)
8992{
8993	struct scsi_request_sense *cdb;
8994	struct scsi_sense_data *sense_ptr;
8995	struct ctl_softc *ctl_softc;
8996	struct ctl_lun *lun;
8997	uint32_t initidx;
8998	int have_error;
8999	scsi_sense_data_type sense_format;
9000	ctl_ua_type ua_type;
9001
9002	cdb = (struct scsi_request_sense *)ctsio->cdb;
9003
9004	ctl_softc = control_softc;
9005	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9006
9007	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9008
9009	/*
9010	 * Determine which sense format the user wants.
9011	 */
9012	if (cdb->byte2 & SRS_DESC)
9013		sense_format = SSD_TYPE_DESC;
9014	else
9015		sense_format = SSD_TYPE_FIXED;
9016
9017	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9018	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9019	ctsio->kern_sg_entries = 0;
9020
9021	/*
9022	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9023	 * larger than the largest allowed value for the length field in the
9024	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9025	 */
9026	ctsio->residual = 0;
9027	ctsio->kern_data_len = cdb->length;
9028	ctsio->kern_total_len = cdb->length;
9029
9030	ctsio->kern_data_resid = 0;
9031	ctsio->kern_rel_offset = 0;
9032	ctsio->kern_sg_entries = 0;
9033
9034	/*
9035	 * If we don't have a LUN, we don't have any pending sense.
9036	 */
9037	if (lun == NULL)
9038		goto no_sense;
9039
9040	have_error = 0;
9041	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9042	/*
9043	 * Check for pending sense, and then for pending unit attentions.
9044	 * Pending sense gets returned first, then pending unit attentions.
9045	 */
9046	mtx_lock(&lun->lun_lock);
9047#ifdef CTL_WITH_CA
9048	if (ctl_is_set(lun->have_ca, initidx)) {
9049		scsi_sense_data_type stored_format;
9050
9051		/*
9052		 * Check to see which sense format was used for the stored
9053		 * sense data.
9054		 */
9055		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9056
9057		/*
9058		 * If the user requested a different sense format than the
9059		 * one we stored, then we need to convert it to the other
9060		 * format.  If we're going from descriptor to fixed format
9061		 * sense data, we may lose things in translation, depending
9062		 * on what options were used.
9063		 *
9064		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9065		 * for some reason we'll just copy it out as-is.
9066		 */
9067		if ((stored_format == SSD_TYPE_FIXED)
9068		 && (sense_format == SSD_TYPE_DESC))
9069			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9070			    &lun->pending_sense[initidx],
9071			    (struct scsi_sense_data_desc *)sense_ptr);
9072		else if ((stored_format == SSD_TYPE_DESC)
9073		      && (sense_format == SSD_TYPE_FIXED))
9074			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9075			    &lun->pending_sense[initidx],
9076			    (struct scsi_sense_data_fixed *)sense_ptr);
9077		else
9078			memcpy(sense_ptr, &lun->pending_sense[initidx],
9079			       MIN(sizeof(*sense_ptr),
9080			       sizeof(lun->pending_sense[initidx])));
9081
9082		ctl_clear_mask(lun->have_ca, initidx);
9083		have_error = 1;
9084	} else
9085#endif
9086	{
9087		ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9088		if (ua_type != CTL_UA_NONE)
9089			have_error = 1;
9090		if (ua_type == CTL_UA_LUN_CHANGE) {
9091			mtx_unlock(&lun->lun_lock);
9092			mtx_lock(&ctl_softc->ctl_lock);
9093			ctl_clr_ua_allluns(ctl_softc, initidx, ua_type);
9094			mtx_unlock(&ctl_softc->ctl_lock);
9095			mtx_lock(&lun->lun_lock);
9096		}
9097
9098	}
9099	mtx_unlock(&lun->lun_lock);
9100
9101	/*
9102	 * We already have a pending error, return it.
9103	 */
9104	if (have_error != 0) {
9105		/*
9106		 * We report the SCSI status as OK, since the status of the
9107		 * request sense command itself is OK.
9108		 * We report 0 for the sense length, because we aren't doing
9109		 * autosense in this case.  We're reporting sense as
9110		 * parameter data.
9111		 */
9112		ctl_set_success(ctsio);
9113		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9114		ctsio->be_move_done = ctl_config_move_done;
9115		ctl_datamove((union ctl_io *)ctsio);
9116		return (CTL_RETVAL_COMPLETE);
9117	}
9118
9119no_sense:
9120
9121	/*
9122	 * No sense information to report, so we report that everything is
9123	 * okay.
9124	 */
9125	ctl_set_sense_data(sense_ptr,
9126			   lun,
9127			   sense_format,
9128			   /*current_error*/ 1,
9129			   /*sense_key*/ SSD_KEY_NO_SENSE,
9130			   /*asc*/ 0x00,
9131			   /*ascq*/ 0x00,
9132			   SSD_ELEM_NONE);
9133
9134	/*
9135	 * We report 0 for the sense length, because we aren't doing
9136	 * autosense in this case.  We're reporting sense as parameter data.
9137	 */
9138	ctl_set_success(ctsio);
9139	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9140	ctsio->be_move_done = ctl_config_move_done;
9141	ctl_datamove((union ctl_io *)ctsio);
9142	return (CTL_RETVAL_COMPLETE);
9143}
9144
9145int
9146ctl_tur(struct ctl_scsiio *ctsio)
9147{
9148
9149	CTL_DEBUG_PRINT(("ctl_tur\n"));
9150
9151	ctl_set_success(ctsio);
9152	ctl_done((union ctl_io *)ctsio);
9153
9154	return (CTL_RETVAL_COMPLETE);
9155}
9156
9157#ifdef notyet
9158static int
9159ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9160{
9161
9162}
9163#endif
9164
9165/*
9166 * SCSI VPD page 0x00, the Supported VPD Pages page.
9167 */
9168static int
9169ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9170{
9171	struct scsi_vpd_supported_pages *pages;
9172	int sup_page_size;
9173	struct ctl_lun *lun;
9174	int p;
9175
9176	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9177
9178	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9179	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9180	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9181	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9182	ctsio->kern_sg_entries = 0;
9183
9184	if (sup_page_size < alloc_len) {
9185		ctsio->residual = alloc_len - sup_page_size;
9186		ctsio->kern_data_len = sup_page_size;
9187		ctsio->kern_total_len = sup_page_size;
9188	} else {
9189		ctsio->residual = 0;
9190		ctsio->kern_data_len = alloc_len;
9191		ctsio->kern_total_len = alloc_len;
9192	}
9193	ctsio->kern_data_resid = 0;
9194	ctsio->kern_rel_offset = 0;
9195	ctsio->kern_sg_entries = 0;
9196
9197	/*
9198	 * The control device is always connected.  The disk device, on the
9199	 * other hand, may not be online all the time.  Need to change this
9200	 * to figure out whether the disk device is actually online or not.
9201	 */
9202	if (lun != NULL)
9203		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9204				lun->be_lun->lun_type;
9205	else
9206		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9207
9208	p = 0;
9209	/* Supported VPD pages */
9210	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9211	/* Serial Number */
9212	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9213	/* Device Identification */
9214	pages->page_list[p++] = SVPD_DEVICE_ID;
9215	/* Extended INQUIRY Data */
9216	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9217	/* Mode Page Policy */
9218	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9219	/* SCSI Ports */
9220	pages->page_list[p++] = SVPD_SCSI_PORTS;
9221	/* Third-party Copy */
9222	pages->page_list[p++] = SVPD_SCSI_TPC;
9223	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9224		/* Block limits */
9225		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9226		/* Block Device Characteristics */
9227		pages->page_list[p++] = SVPD_BDC;
9228		/* Logical Block Provisioning */
9229		pages->page_list[p++] = SVPD_LBP;
9230	}
9231	pages->length = p;
9232
9233	ctl_set_success(ctsio);
9234	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9235	ctsio->be_move_done = ctl_config_move_done;
9236	ctl_datamove((union ctl_io *)ctsio);
9237	return (CTL_RETVAL_COMPLETE);
9238}
9239
9240/*
9241 * SCSI VPD page 0x80, the Unit Serial Number page.
9242 */
9243static int
9244ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9245{
9246	struct scsi_vpd_unit_serial_number *sn_ptr;
9247	struct ctl_lun *lun;
9248	int data_len;
9249
9250	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9251
9252	data_len = 4 + CTL_SN_LEN;
9253	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9254	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9255	if (data_len < alloc_len) {
9256		ctsio->residual = alloc_len - data_len;
9257		ctsio->kern_data_len = data_len;
9258		ctsio->kern_total_len = data_len;
9259	} else {
9260		ctsio->residual = 0;
9261		ctsio->kern_data_len = alloc_len;
9262		ctsio->kern_total_len = alloc_len;
9263	}
9264	ctsio->kern_data_resid = 0;
9265	ctsio->kern_rel_offset = 0;
9266	ctsio->kern_sg_entries = 0;
9267
9268	/*
9269	 * The control device is always connected.  The disk device, on the
9270	 * other hand, may not be online all the time.  Need to change this
9271	 * to figure out whether the disk device is actually online or not.
9272	 */
9273	if (lun != NULL)
9274		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9275				  lun->be_lun->lun_type;
9276	else
9277		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9278
9279	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9280	sn_ptr->length = CTL_SN_LEN;
9281	/*
9282	 * If we don't have a LUN, we just leave the serial number as
9283	 * all spaces.
9284	 */
9285	if (lun != NULL) {
9286		strncpy((char *)sn_ptr->serial_num,
9287			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9288	} else
9289		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9290
9291	ctl_set_success(ctsio);
9292	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9293	ctsio->be_move_done = ctl_config_move_done;
9294	ctl_datamove((union ctl_io *)ctsio);
9295	return (CTL_RETVAL_COMPLETE);
9296}
9297
9298
9299/*
9300 * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9301 */
9302static int
9303ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9304{
9305	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9306	struct ctl_lun *lun;
9307	int data_len;
9308
9309	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9310
9311	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9312	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9313	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9314	ctsio->kern_sg_entries = 0;
9315
9316	if (data_len < alloc_len) {
9317		ctsio->residual = alloc_len - data_len;
9318		ctsio->kern_data_len = data_len;
9319		ctsio->kern_total_len = data_len;
9320	} else {
9321		ctsio->residual = 0;
9322		ctsio->kern_data_len = alloc_len;
9323		ctsio->kern_total_len = alloc_len;
9324	}
9325	ctsio->kern_data_resid = 0;
9326	ctsio->kern_rel_offset = 0;
9327	ctsio->kern_sg_entries = 0;
9328
9329	/*
9330	 * The control device is always connected.  The disk device, on the
9331	 * other hand, may not be online all the time.
9332	 */
9333	if (lun != NULL)
9334		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9335				     lun->be_lun->lun_type;
9336	else
9337		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9338	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9339	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9340	/*
9341	 * We support head of queue, ordered and simple tags.
9342	 */
9343	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9344	/*
9345	 * Volatile cache supported.
9346	 */
9347	eid_ptr->flags3 = SVPD_EID_V_SUP;
9348
9349	/*
9350	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9351	 * attention for a particular IT nexus on all LUNs once we report
9352	 * it to that nexus once.  This bit is required as of SPC-4.
9353	 */
9354	eid_ptr->flags4 = SVPD_EID_LUICLT;
9355
9356	/*
9357	 * XXX KDM in order to correctly answer this, we would need
9358	 * information from the SIM to determine how much sense data it
9359	 * can send.  So this would really be a path inquiry field, most
9360	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9361	 * but the hardware may or may not be able to support that much.
9362	 * 0 just means that the maximum sense data length is not reported.
9363	 */
9364	eid_ptr->max_sense_length = 0;
9365
9366	ctl_set_success(ctsio);
9367	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9368	ctsio->be_move_done = ctl_config_move_done;
9369	ctl_datamove((union ctl_io *)ctsio);
9370	return (CTL_RETVAL_COMPLETE);
9371}
9372
9373static int
9374ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9375{
9376	struct scsi_vpd_mode_page_policy *mpp_ptr;
9377	struct ctl_lun *lun;
9378	int data_len;
9379
9380	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9381
9382	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9383	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9384
9385	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9386	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9387	ctsio->kern_sg_entries = 0;
9388
9389	if (data_len < alloc_len) {
9390		ctsio->residual = alloc_len - data_len;
9391		ctsio->kern_data_len = data_len;
9392		ctsio->kern_total_len = data_len;
9393	} else {
9394		ctsio->residual = 0;
9395		ctsio->kern_data_len = alloc_len;
9396		ctsio->kern_total_len = alloc_len;
9397	}
9398	ctsio->kern_data_resid = 0;
9399	ctsio->kern_rel_offset = 0;
9400	ctsio->kern_sg_entries = 0;
9401
9402	/*
9403	 * The control device is always connected.  The disk device, on the
9404	 * other hand, may not be online all the time.
9405	 */
9406	if (lun != NULL)
9407		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9408				     lun->be_lun->lun_type;
9409	else
9410		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9411	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9412	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9413	mpp_ptr->descr[0].page_code = 0x3f;
9414	mpp_ptr->descr[0].subpage_code = 0xff;
9415	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9416
9417	ctl_set_success(ctsio);
9418	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9419	ctsio->be_move_done = ctl_config_move_done;
9420	ctl_datamove((union ctl_io *)ctsio);
9421	return (CTL_RETVAL_COMPLETE);
9422}
9423
9424/*
9425 * SCSI VPD page 0x83, the Device Identification page.
9426 */
9427static int
9428ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9429{
9430	struct scsi_vpd_device_id *devid_ptr;
9431	struct scsi_vpd_id_descriptor *desc;
9432	struct ctl_softc *softc;
9433	struct ctl_lun *lun;
9434	struct ctl_port *port;
9435	int data_len;
9436	uint8_t proto;
9437
9438	softc = control_softc;
9439
9440	port = softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9441	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9442
9443	data_len = sizeof(struct scsi_vpd_device_id) +
9444	    sizeof(struct scsi_vpd_id_descriptor) +
9445		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9446	    sizeof(struct scsi_vpd_id_descriptor) +
9447		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9448	if (lun && lun->lun_devid)
9449		data_len += lun->lun_devid->len;
9450	if (port->port_devid)
9451		data_len += port->port_devid->len;
9452	if (port->target_devid)
9453		data_len += port->target_devid->len;
9454
9455	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9456	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9457	ctsio->kern_sg_entries = 0;
9458
9459	if (data_len < alloc_len) {
9460		ctsio->residual = alloc_len - data_len;
9461		ctsio->kern_data_len = data_len;
9462		ctsio->kern_total_len = data_len;
9463	} else {
9464		ctsio->residual = 0;
9465		ctsio->kern_data_len = alloc_len;
9466		ctsio->kern_total_len = alloc_len;
9467	}
9468	ctsio->kern_data_resid = 0;
9469	ctsio->kern_rel_offset = 0;
9470	ctsio->kern_sg_entries = 0;
9471
9472	/*
9473	 * The control device is always connected.  The disk device, on the
9474	 * other hand, may not be online all the time.
9475	 */
9476	if (lun != NULL)
9477		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9478				     lun->be_lun->lun_type;
9479	else
9480		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9481	devid_ptr->page_code = SVPD_DEVICE_ID;
9482	scsi_ulto2b(data_len - 4, devid_ptr->length);
9483
9484	if (port->port_type == CTL_PORT_FC)
9485		proto = SCSI_PROTO_FC << 4;
9486	else if (port->port_type == CTL_PORT_ISCSI)
9487		proto = SCSI_PROTO_ISCSI << 4;
9488	else
9489		proto = SCSI_PROTO_SPI << 4;
9490	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9491
9492	/*
9493	 * We're using a LUN association here.  i.e., this device ID is a
9494	 * per-LUN identifier.
9495	 */
9496	if (lun && lun->lun_devid) {
9497		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9498		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9499		    lun->lun_devid->len);
9500	}
9501
9502	/*
9503	 * This is for the WWPN which is a port association.
9504	 */
9505	if (port->port_devid) {
9506		memcpy(desc, port->port_devid->data, port->port_devid->len);
9507		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9508		    port->port_devid->len);
9509	}
9510
9511	/*
9512	 * This is for the Relative Target Port(type 4h) identifier
9513	 */
9514	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9515	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9516	    SVPD_ID_TYPE_RELTARG;
9517	desc->length = 4;
9518	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9519	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9520	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9521
9522	/*
9523	 * This is for the Target Port Group(type 5h) identifier
9524	 */
9525	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9526	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9527	    SVPD_ID_TYPE_TPORTGRP;
9528	desc->length = 4;
9529	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
9530	    &desc->identifier[2]);
9531	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9532	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9533
9534	/*
9535	 * This is for the Target identifier
9536	 */
9537	if (port->target_devid) {
9538		memcpy(desc, port->target_devid->data, port->target_devid->len);
9539	}
9540
9541	ctl_set_success(ctsio);
9542	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9543	ctsio->be_move_done = ctl_config_move_done;
9544	ctl_datamove((union ctl_io *)ctsio);
9545	return (CTL_RETVAL_COMPLETE);
9546}
9547
9548static int
9549ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9550{
9551	struct ctl_softc *softc = control_softc;
9552	struct scsi_vpd_scsi_ports *sp;
9553	struct scsi_vpd_port_designation *pd;
9554	struct scsi_vpd_port_designation_cont *pdc;
9555	struct ctl_lun *lun;
9556	struct ctl_port *port;
9557	int data_len, num_target_ports, iid_len, id_len, g, pg, p;
9558	int num_target_port_groups;
9559
9560	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9561
9562	if (softc->is_single)
9563		num_target_port_groups = 1;
9564	else
9565		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
9566	num_target_ports = 0;
9567	iid_len = 0;
9568	id_len = 0;
9569	mtx_lock(&softc->ctl_lock);
9570	STAILQ_FOREACH(port, &softc->port_list, links) {
9571		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9572			continue;
9573		if (lun != NULL &&
9574		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9575			continue;
9576		num_target_ports++;
9577		if (port->init_devid)
9578			iid_len += port->init_devid->len;
9579		if (port->port_devid)
9580			id_len += port->port_devid->len;
9581	}
9582	mtx_unlock(&softc->ctl_lock);
9583
9584	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
9585	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9586	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9587	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9588	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9589	ctsio->kern_sg_entries = 0;
9590
9591	if (data_len < alloc_len) {
9592		ctsio->residual = alloc_len - data_len;
9593		ctsio->kern_data_len = data_len;
9594		ctsio->kern_total_len = data_len;
9595	} else {
9596		ctsio->residual = 0;
9597		ctsio->kern_data_len = alloc_len;
9598		ctsio->kern_total_len = alloc_len;
9599	}
9600	ctsio->kern_data_resid = 0;
9601	ctsio->kern_rel_offset = 0;
9602	ctsio->kern_sg_entries = 0;
9603
9604	/*
9605	 * The control device is always connected.  The disk device, on the
9606	 * other hand, may not be online all the time.  Need to change this
9607	 * to figure out whether the disk device is actually online or not.
9608	 */
9609	if (lun != NULL)
9610		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9611				  lun->be_lun->lun_type;
9612	else
9613		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9614
9615	sp->page_code = SVPD_SCSI_PORTS;
9616	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9617	    sp->page_length);
9618	pd = &sp->design[0];
9619
9620	mtx_lock(&softc->ctl_lock);
9621	pg = softc->port_offset / CTL_MAX_PORTS;
9622	for (g = 0; g < num_target_port_groups; g++) {
9623		STAILQ_FOREACH(port, &softc->port_list, links) {
9624			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9625				continue;
9626			if (lun != NULL &&
9627			    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9628				continue;
9629			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
9630			scsi_ulto2b(p, pd->relative_port_id);
9631			if (port->init_devid && g == pg) {
9632				iid_len = port->init_devid->len;
9633				memcpy(pd->initiator_transportid,
9634				    port->init_devid->data, port->init_devid->len);
9635			} else
9636				iid_len = 0;
9637			scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9638			pdc = (struct scsi_vpd_port_designation_cont *)
9639			    (&pd->initiator_transportid[iid_len]);
9640			if (port->port_devid && g == pg) {
9641				id_len = port->port_devid->len;
9642				memcpy(pdc->target_port_descriptors,
9643				    port->port_devid->data, port->port_devid->len);
9644			} else
9645				id_len = 0;
9646			scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9647			pd = (struct scsi_vpd_port_designation *)
9648			    ((uint8_t *)pdc->target_port_descriptors + id_len);
9649		}
9650	}
9651	mtx_unlock(&softc->ctl_lock);
9652
9653	ctl_set_success(ctsio);
9654	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9655	ctsio->be_move_done = ctl_config_move_done;
9656	ctl_datamove((union ctl_io *)ctsio);
9657	return (CTL_RETVAL_COMPLETE);
9658}
9659
9660static int
9661ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9662{
9663	struct scsi_vpd_block_limits *bl_ptr;
9664	struct ctl_lun *lun;
9665	int bs;
9666
9667	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9668
9669	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9670	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9671	ctsio->kern_sg_entries = 0;
9672
9673	if (sizeof(*bl_ptr) < alloc_len) {
9674		ctsio->residual = alloc_len - sizeof(*bl_ptr);
9675		ctsio->kern_data_len = sizeof(*bl_ptr);
9676		ctsio->kern_total_len = sizeof(*bl_ptr);
9677	} else {
9678		ctsio->residual = 0;
9679		ctsio->kern_data_len = alloc_len;
9680		ctsio->kern_total_len = alloc_len;
9681	}
9682	ctsio->kern_data_resid = 0;
9683	ctsio->kern_rel_offset = 0;
9684	ctsio->kern_sg_entries = 0;
9685
9686	/*
9687	 * The control device is always connected.  The disk device, on the
9688	 * other hand, may not be online all the time.  Need to change this
9689	 * to figure out whether the disk device is actually online or not.
9690	 */
9691	if (lun != NULL)
9692		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9693				  lun->be_lun->lun_type;
9694	else
9695		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9696
9697	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9698	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9699	bl_ptr->max_cmp_write_len = 0xff;
9700	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9701	if (lun != NULL) {
9702		bs = lun->be_lun->blocksize;
9703		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9704		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9705			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
9706			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
9707			if (lun->be_lun->ublockexp != 0) {
9708				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9709				    bl_ptr->opt_unmap_grain);
9710				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9711				    bl_ptr->unmap_grain_align);
9712			}
9713		}
9714		scsi_ulto4b(lun->be_lun->atomicblock,
9715		    bl_ptr->max_atomic_transfer_length);
9716		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9717		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9718	}
9719	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
9720
9721	ctl_set_success(ctsio);
9722	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9723	ctsio->be_move_done = ctl_config_move_done;
9724	ctl_datamove((union ctl_io *)ctsio);
9725	return (CTL_RETVAL_COMPLETE);
9726}
9727
9728static int
9729ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9730{
9731	struct scsi_vpd_block_device_characteristics *bdc_ptr;
9732	struct ctl_lun *lun;
9733	const char *value;
9734	u_int i;
9735
9736	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9737
9738	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9739	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9740	ctsio->kern_sg_entries = 0;
9741
9742	if (sizeof(*bdc_ptr) < alloc_len) {
9743		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
9744		ctsio->kern_data_len = sizeof(*bdc_ptr);
9745		ctsio->kern_total_len = sizeof(*bdc_ptr);
9746	} else {
9747		ctsio->residual = 0;
9748		ctsio->kern_data_len = alloc_len;
9749		ctsio->kern_total_len = alloc_len;
9750	}
9751	ctsio->kern_data_resid = 0;
9752	ctsio->kern_rel_offset = 0;
9753	ctsio->kern_sg_entries = 0;
9754
9755	/*
9756	 * The control device is always connected.  The disk device, on the
9757	 * other hand, may not be online all the time.  Need to change this
9758	 * to figure out whether the disk device is actually online or not.
9759	 */
9760	if (lun != NULL)
9761		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9762				  lun->be_lun->lun_type;
9763	else
9764		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9765	bdc_ptr->page_code = SVPD_BDC;
9766	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9767	if (lun != NULL &&
9768	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
9769		i = strtol(value, NULL, 0);
9770	else
9771		i = CTL_DEFAULT_ROTATION_RATE;
9772	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9773	if (lun != NULL &&
9774	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
9775		i = strtol(value, NULL, 0);
9776	else
9777		i = 0;
9778	bdc_ptr->wab_wac_ff = (i & 0x0f);
9779	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9780
9781	ctl_set_success(ctsio);
9782	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9783	ctsio->be_move_done = ctl_config_move_done;
9784	ctl_datamove((union ctl_io *)ctsio);
9785	return (CTL_RETVAL_COMPLETE);
9786}
9787
9788static int
9789ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9790{
9791	struct scsi_vpd_logical_block_prov *lbp_ptr;
9792	struct ctl_lun *lun;
9793
9794	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9795
9796	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9797	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9798	ctsio->kern_sg_entries = 0;
9799
9800	if (sizeof(*lbp_ptr) < alloc_len) {
9801		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
9802		ctsio->kern_data_len = sizeof(*lbp_ptr);
9803		ctsio->kern_total_len = sizeof(*lbp_ptr);
9804	} else {
9805		ctsio->residual = 0;
9806		ctsio->kern_data_len = alloc_len;
9807		ctsio->kern_total_len = alloc_len;
9808	}
9809	ctsio->kern_data_resid = 0;
9810	ctsio->kern_rel_offset = 0;
9811	ctsio->kern_sg_entries = 0;
9812
9813	/*
9814	 * The control device is always connected.  The disk device, on the
9815	 * other hand, may not be online all the time.  Need to change this
9816	 * to figure out whether the disk device is actually online or not.
9817	 */
9818	if (lun != NULL)
9819		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9820				  lun->be_lun->lun_type;
9821	else
9822		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9823
9824	lbp_ptr->page_code = SVPD_LBP;
9825	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
9826	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
9827	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9828		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
9829		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
9830		lbp_ptr->prov_type = SVPD_LBP_THIN;
9831	}
9832
9833	ctl_set_success(ctsio);
9834	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9835	ctsio->be_move_done = ctl_config_move_done;
9836	ctl_datamove((union ctl_io *)ctsio);
9837	return (CTL_RETVAL_COMPLETE);
9838}
9839
9840/*
9841 * INQUIRY with the EVPD bit set.
9842 */
9843static int
9844ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
9845{
9846	struct ctl_lun *lun;
9847	struct scsi_inquiry *cdb;
9848	int alloc_len, retval;
9849
9850	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9851	cdb = (struct scsi_inquiry *)ctsio->cdb;
9852	alloc_len = scsi_2btoul(cdb->length);
9853
9854	switch (cdb->page_code) {
9855	case SVPD_SUPPORTED_PAGES:
9856		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
9857		break;
9858	case SVPD_UNIT_SERIAL_NUMBER:
9859		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
9860		break;
9861	case SVPD_DEVICE_ID:
9862		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
9863		break;
9864	case SVPD_EXTENDED_INQUIRY_DATA:
9865		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
9866		break;
9867	case SVPD_MODE_PAGE_POLICY:
9868		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
9869		break;
9870	case SVPD_SCSI_PORTS:
9871		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
9872		break;
9873	case SVPD_SCSI_TPC:
9874		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
9875		break;
9876	case SVPD_BLOCK_LIMITS:
9877		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9878			goto err;
9879		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
9880		break;
9881	case SVPD_BDC:
9882		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9883			goto err;
9884		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
9885		break;
9886	case SVPD_LBP:
9887		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9888			goto err;
9889		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
9890		break;
9891	default:
9892err:
9893		ctl_set_invalid_field(ctsio,
9894				      /*sks_valid*/ 1,
9895				      /*command*/ 1,
9896				      /*field*/ 2,
9897				      /*bit_valid*/ 0,
9898				      /*bit*/ 0);
9899		ctl_done((union ctl_io *)ctsio);
9900		retval = CTL_RETVAL_COMPLETE;
9901		break;
9902	}
9903
9904	return (retval);
9905}
9906
9907/*
9908 * Standard INQUIRY data.
9909 */
9910static int
9911ctl_inquiry_std(struct ctl_scsiio *ctsio)
9912{
9913	struct scsi_inquiry_data *inq_ptr;
9914	struct scsi_inquiry *cdb;
9915	struct ctl_softc *softc;
9916	struct ctl_lun *lun;
9917	char *val;
9918	uint32_t alloc_len, data_len;
9919	ctl_port_type port_type;
9920
9921	softc = control_softc;
9922
9923	/*
9924	 * Figure out whether we're talking to a Fibre Channel port or not.
9925	 * We treat the ioctl front end, and any SCSI adapters, as packetized
9926	 * SCSI front ends.
9927	 */
9928	port_type = softc->ctl_ports[
9929	    ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
9930	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
9931		port_type = CTL_PORT_SCSI;
9932
9933	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9934	cdb = (struct scsi_inquiry *)ctsio->cdb;
9935	alloc_len = scsi_2btoul(cdb->length);
9936
9937	/*
9938	 * We malloc the full inquiry data size here and fill it
9939	 * in.  If the user only asks for less, we'll give him
9940	 * that much.
9941	 */
9942	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
9943	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9944	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
9945	ctsio->kern_sg_entries = 0;
9946	ctsio->kern_data_resid = 0;
9947	ctsio->kern_rel_offset = 0;
9948
9949	if (data_len < alloc_len) {
9950		ctsio->residual = alloc_len - data_len;
9951		ctsio->kern_data_len = data_len;
9952		ctsio->kern_total_len = data_len;
9953	} else {
9954		ctsio->residual = 0;
9955		ctsio->kern_data_len = alloc_len;
9956		ctsio->kern_total_len = alloc_len;
9957	}
9958
9959	/*
9960	 * If we have a LUN configured, report it as connected.  Otherwise,
9961	 * report that it is offline or no device is supported, depending
9962	 * on the value of inquiry_pq_no_lun.
9963	 *
9964	 * According to the spec (SPC-4 r34), the peripheral qualifier
9965	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
9966	 *
9967	 * "A peripheral device having the specified peripheral device type
9968	 * is not connected to this logical unit. However, the device
9969	 * server is capable of supporting the specified peripheral device
9970	 * type on this logical unit."
9971	 *
9972	 * According to the same spec, the peripheral qualifier
9973	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
9974	 *
9975	 * "The device server is not capable of supporting a peripheral
9976	 * device on this logical unit. For this peripheral qualifier the
9977	 * peripheral device type shall be set to 1Fh. All other peripheral
9978	 * device type values are reserved for this peripheral qualifier."
9979	 *
9980	 * Given the text, it would seem that we probably want to report that
9981	 * the LUN is offline here.  There is no LUN connected, but we can
9982	 * support a LUN at the given LUN number.
9983	 *
9984	 * In the real world, though, it sounds like things are a little
9985	 * different:
9986	 *
9987	 * - Linux, when presented with a LUN with the offline peripheral
9988	 *   qualifier, will create an sg driver instance for it.  So when
9989	 *   you attach it to CTL, you wind up with a ton of sg driver
9990	 *   instances.  (One for every LUN that Linux bothered to probe.)
9991	 *   Linux does this despite the fact that it issues a REPORT LUNs
9992	 *   to LUN 0 to get the inventory of supported LUNs.
9993	 *
9994	 * - There is other anecdotal evidence (from Emulex folks) about
9995	 *   arrays that use the offline peripheral qualifier for LUNs that
9996	 *   are on the "passive" path in an active/passive array.
9997	 *
9998	 * So the solution is provide a hopefully reasonable default
9999	 * (return bad/no LUN) and allow the user to change the behavior
10000	 * with a tunable/sysctl variable.
10001	 */
10002	if (lun != NULL)
10003		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10004				  lun->be_lun->lun_type;
10005	else if (softc->inquiry_pq_no_lun == 0)
10006		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10007	else
10008		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10009
10010	/* RMB in byte 2 is 0 */
10011	inq_ptr->version = SCSI_REV_SPC4;
10012
10013	/*
10014	 * According to SAM-3, even if a device only supports a single
10015	 * level of LUN addressing, it should still set the HISUP bit:
10016	 *
10017	 * 4.9.1 Logical unit numbers overview
10018	 *
10019	 * All logical unit number formats described in this standard are
10020	 * hierarchical in structure even when only a single level in that
10021	 * hierarchy is used. The HISUP bit shall be set to one in the
10022	 * standard INQUIRY data (see SPC-2) when any logical unit number
10023	 * format described in this standard is used.  Non-hierarchical
10024	 * formats are outside the scope of this standard.
10025	 *
10026	 * Therefore we set the HiSup bit here.
10027	 *
10028	 * The reponse format is 2, per SPC-3.
10029	 */
10030	inq_ptr->response_format = SID_HiSup | 2;
10031
10032	inq_ptr->additional_length = data_len -
10033	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10034	CTL_DEBUG_PRINT(("additional_length = %d\n",
10035			 inq_ptr->additional_length));
10036
10037	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10038	/* 16 bit addressing */
10039	if (port_type == CTL_PORT_SCSI)
10040		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10041	/* XXX set the SID_MultiP bit here if we're actually going to
10042	   respond on multiple ports */
10043	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10044
10045	/* 16 bit data bus, synchronous transfers */
10046	if (port_type == CTL_PORT_SCSI)
10047		inq_ptr->flags = SID_WBus16 | SID_Sync;
10048	/*
10049	 * XXX KDM do we want to support tagged queueing on the control
10050	 * device at all?
10051	 */
10052	if ((lun == NULL)
10053	 || (lun->be_lun->lun_type != T_PROCESSOR))
10054		inq_ptr->flags |= SID_CmdQue;
10055	/*
10056	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10057	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10058	 * name and 4 bytes for the revision.
10059	 */
10060	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10061	    "vendor")) == NULL) {
10062		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10063	} else {
10064		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10065		strncpy(inq_ptr->vendor, val,
10066		    min(sizeof(inq_ptr->vendor), strlen(val)));
10067	}
10068	if (lun == NULL) {
10069		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10070		    sizeof(inq_ptr->product));
10071	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10072		switch (lun->be_lun->lun_type) {
10073		case T_DIRECT:
10074			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10075			    sizeof(inq_ptr->product));
10076			break;
10077		case T_PROCESSOR:
10078			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10079			    sizeof(inq_ptr->product));
10080			break;
10081		default:
10082			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10083			    sizeof(inq_ptr->product));
10084			break;
10085		}
10086	} else {
10087		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10088		strncpy(inq_ptr->product, val,
10089		    min(sizeof(inq_ptr->product), strlen(val)));
10090	}
10091
10092	/*
10093	 * XXX make this a macro somewhere so it automatically gets
10094	 * incremented when we make changes.
10095	 */
10096	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10097	    "revision")) == NULL) {
10098		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10099	} else {
10100		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10101		strncpy(inq_ptr->revision, val,
10102		    min(sizeof(inq_ptr->revision), strlen(val)));
10103	}
10104
10105	/*
10106	 * For parallel SCSI, we support double transition and single
10107	 * transition clocking.  We also support QAS (Quick Arbitration
10108	 * and Selection) and Information Unit transfers on both the
10109	 * control and array devices.
10110	 */
10111	if (port_type == CTL_PORT_SCSI)
10112		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10113				    SID_SPI_IUS;
10114
10115	/* SAM-5 (no version claimed) */
10116	scsi_ulto2b(0x00A0, inq_ptr->version1);
10117	/* SPC-4 (no version claimed) */
10118	scsi_ulto2b(0x0460, inq_ptr->version2);
10119	if (port_type == CTL_PORT_FC) {
10120		/* FCP-2 ANSI INCITS.350:2003 */
10121		scsi_ulto2b(0x0917, inq_ptr->version3);
10122	} else if (port_type == CTL_PORT_SCSI) {
10123		/* SPI-4 ANSI INCITS.362:200x */
10124		scsi_ulto2b(0x0B56, inq_ptr->version3);
10125	} else if (port_type == CTL_PORT_ISCSI) {
10126		/* iSCSI (no version claimed) */
10127		scsi_ulto2b(0x0960, inq_ptr->version3);
10128	} else if (port_type == CTL_PORT_SAS) {
10129		/* SAS (no version claimed) */
10130		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10131	}
10132
10133	if (lun == NULL) {
10134		/* SBC-4 (no version claimed) */
10135		scsi_ulto2b(0x0600, inq_ptr->version4);
10136	} else {
10137		switch (lun->be_lun->lun_type) {
10138		case T_DIRECT:
10139			/* SBC-4 (no version claimed) */
10140			scsi_ulto2b(0x0600, inq_ptr->version4);
10141			break;
10142		case T_PROCESSOR:
10143		default:
10144			break;
10145		}
10146	}
10147
10148	ctl_set_success(ctsio);
10149	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10150	ctsio->be_move_done = ctl_config_move_done;
10151	ctl_datamove((union ctl_io *)ctsio);
10152	return (CTL_RETVAL_COMPLETE);
10153}
10154
10155int
10156ctl_inquiry(struct ctl_scsiio *ctsio)
10157{
10158	struct scsi_inquiry *cdb;
10159	int retval;
10160
10161	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10162
10163	cdb = (struct scsi_inquiry *)ctsio->cdb;
10164	if (cdb->byte2 & SI_EVPD)
10165		retval = ctl_inquiry_evpd(ctsio);
10166	else if (cdb->page_code == 0)
10167		retval = ctl_inquiry_std(ctsio);
10168	else {
10169		ctl_set_invalid_field(ctsio,
10170				      /*sks_valid*/ 1,
10171				      /*command*/ 1,
10172				      /*field*/ 2,
10173				      /*bit_valid*/ 0,
10174				      /*bit*/ 0);
10175		ctl_done((union ctl_io *)ctsio);
10176		return (CTL_RETVAL_COMPLETE);
10177	}
10178
10179	return (retval);
10180}
10181
10182/*
10183 * For known CDB types, parse the LBA and length.
10184 */
10185static int
10186ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10187{
10188	if (io->io_hdr.io_type != CTL_IO_SCSI)
10189		return (1);
10190
10191	switch (io->scsiio.cdb[0]) {
10192	case COMPARE_AND_WRITE: {
10193		struct scsi_compare_and_write *cdb;
10194
10195		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10196
10197		*lba = scsi_8btou64(cdb->addr);
10198		*len = cdb->length;
10199		break;
10200	}
10201	case READ_6:
10202	case WRITE_6: {
10203		struct scsi_rw_6 *cdb;
10204
10205		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10206
10207		*lba = scsi_3btoul(cdb->addr);
10208		/* only 5 bits are valid in the most significant address byte */
10209		*lba &= 0x1fffff;
10210		*len = cdb->length;
10211		break;
10212	}
10213	case READ_10:
10214	case WRITE_10: {
10215		struct scsi_rw_10 *cdb;
10216
10217		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10218
10219		*lba = scsi_4btoul(cdb->addr);
10220		*len = scsi_2btoul(cdb->length);
10221		break;
10222	}
10223	case WRITE_VERIFY_10: {
10224		struct scsi_write_verify_10 *cdb;
10225
10226		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10227
10228		*lba = scsi_4btoul(cdb->addr);
10229		*len = scsi_2btoul(cdb->length);
10230		break;
10231	}
10232	case READ_12:
10233	case WRITE_12: {
10234		struct scsi_rw_12 *cdb;
10235
10236		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10237
10238		*lba = scsi_4btoul(cdb->addr);
10239		*len = scsi_4btoul(cdb->length);
10240		break;
10241	}
10242	case WRITE_VERIFY_12: {
10243		struct scsi_write_verify_12 *cdb;
10244
10245		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10246
10247		*lba = scsi_4btoul(cdb->addr);
10248		*len = scsi_4btoul(cdb->length);
10249		break;
10250	}
10251	case READ_16:
10252	case WRITE_16:
10253	case WRITE_ATOMIC_16: {
10254		struct scsi_rw_16 *cdb;
10255
10256		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10257
10258		*lba = scsi_8btou64(cdb->addr);
10259		*len = scsi_4btoul(cdb->length);
10260		break;
10261	}
10262	case WRITE_VERIFY_16: {
10263		struct scsi_write_verify_16 *cdb;
10264
10265		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10266
10267		*lba = scsi_8btou64(cdb->addr);
10268		*len = scsi_4btoul(cdb->length);
10269		break;
10270	}
10271	case WRITE_SAME_10: {
10272		struct scsi_write_same_10 *cdb;
10273
10274		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10275
10276		*lba = scsi_4btoul(cdb->addr);
10277		*len = scsi_2btoul(cdb->length);
10278		break;
10279	}
10280	case WRITE_SAME_16: {
10281		struct scsi_write_same_16 *cdb;
10282
10283		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10284
10285		*lba = scsi_8btou64(cdb->addr);
10286		*len = scsi_4btoul(cdb->length);
10287		break;
10288	}
10289	case VERIFY_10: {
10290		struct scsi_verify_10 *cdb;
10291
10292		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10293
10294		*lba = scsi_4btoul(cdb->addr);
10295		*len = scsi_2btoul(cdb->length);
10296		break;
10297	}
10298	case VERIFY_12: {
10299		struct scsi_verify_12 *cdb;
10300
10301		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10302
10303		*lba = scsi_4btoul(cdb->addr);
10304		*len = scsi_4btoul(cdb->length);
10305		break;
10306	}
10307	case VERIFY_16: {
10308		struct scsi_verify_16 *cdb;
10309
10310		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10311
10312		*lba = scsi_8btou64(cdb->addr);
10313		*len = scsi_4btoul(cdb->length);
10314		break;
10315	}
10316	case UNMAP: {
10317		*lba = 0;
10318		*len = UINT64_MAX;
10319		break;
10320	}
10321	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10322		struct scsi_get_lba_status *cdb;
10323
10324		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10325		*lba = scsi_8btou64(cdb->addr);
10326		*len = UINT32_MAX;
10327		break;
10328	}
10329	default:
10330		return (1);
10331		break; /* NOTREACHED */
10332	}
10333
10334	return (0);
10335}
10336
10337static ctl_action
10338ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10339    bool seq)
10340{
10341	uint64_t endlba1, endlba2;
10342
10343	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10344	endlba2 = lba2 + len2 - 1;
10345
10346	if ((endlba1 < lba2) || (endlba2 < lba1))
10347		return (CTL_ACTION_PASS);
10348	else
10349		return (CTL_ACTION_BLOCK);
10350}
10351
10352static int
10353ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10354{
10355	struct ctl_ptr_len_flags *ptrlen;
10356	struct scsi_unmap_desc *buf, *end, *range;
10357	uint64_t lba;
10358	uint32_t len;
10359
10360	/* If not UNMAP -- go other way. */
10361	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10362	    io->scsiio.cdb[0] != UNMAP)
10363		return (CTL_ACTION_ERROR);
10364
10365	/* If UNMAP without data -- block and wait for data. */
10366	ptrlen = (struct ctl_ptr_len_flags *)
10367	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10368	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10369	    ptrlen->ptr == NULL)
10370		return (CTL_ACTION_BLOCK);
10371
10372	/* UNMAP with data -- check for collision. */
10373	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10374	end = buf + ptrlen->len / sizeof(*buf);
10375	for (range = buf; range < end; range++) {
10376		lba = scsi_8btou64(range->lba);
10377		len = scsi_4btoul(range->length);
10378		if ((lba < lba2 + len2) && (lba + len > lba2))
10379			return (CTL_ACTION_BLOCK);
10380	}
10381	return (CTL_ACTION_PASS);
10382}
10383
10384static ctl_action
10385ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10386{
10387	uint64_t lba1, lba2;
10388	uint64_t len1, len2;
10389	int retval;
10390
10391	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10392		return (CTL_ACTION_ERROR);
10393
10394	retval = ctl_extent_check_unmap(io1, lba2, len2);
10395	if (retval != CTL_ACTION_ERROR)
10396		return (retval);
10397
10398	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10399		return (CTL_ACTION_ERROR);
10400
10401	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10402}
10403
10404static ctl_action
10405ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10406{
10407	uint64_t lba1, lba2;
10408	uint64_t len1, len2;
10409
10410	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10411		return (CTL_ACTION_ERROR);
10412	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10413		return (CTL_ACTION_ERROR);
10414
10415	if (lba1 + len1 == lba2)
10416		return (CTL_ACTION_BLOCK);
10417	return (CTL_ACTION_PASS);
10418}
10419
10420static ctl_action
10421ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10422    union ctl_io *ooa_io)
10423{
10424	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10425	ctl_serialize_action *serialize_row;
10426
10427	/*
10428	 * The initiator attempted multiple untagged commands at the same
10429	 * time.  Can't do that.
10430	 */
10431	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10432	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10433	 && ((pending_io->io_hdr.nexus.targ_port ==
10434	      ooa_io->io_hdr.nexus.targ_port)
10435	  && (pending_io->io_hdr.nexus.initid ==
10436	      ooa_io->io_hdr.nexus.initid))
10437	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10438	      CTL_FLAG_STATUS_SENT)) == 0))
10439		return (CTL_ACTION_OVERLAP);
10440
10441	/*
10442	 * The initiator attempted to send multiple tagged commands with
10443	 * the same ID.  (It's fine if different initiators have the same
10444	 * tag ID.)
10445	 *
10446	 * Even if all of those conditions are true, we don't kill the I/O
10447	 * if the command ahead of us has been aborted.  We won't end up
10448	 * sending it to the FETD, and it's perfectly legal to resend a
10449	 * command with the same tag number as long as the previous
10450	 * instance of this tag number has been aborted somehow.
10451	 */
10452	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10453	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10454	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10455	 && ((pending_io->io_hdr.nexus.targ_port ==
10456	      ooa_io->io_hdr.nexus.targ_port)
10457	  && (pending_io->io_hdr.nexus.initid ==
10458	      ooa_io->io_hdr.nexus.initid))
10459	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10460	      CTL_FLAG_STATUS_SENT)) == 0))
10461		return (CTL_ACTION_OVERLAP_TAG);
10462
10463	/*
10464	 * If we get a head of queue tag, SAM-3 says that we should
10465	 * immediately execute it.
10466	 *
10467	 * What happens if this command would normally block for some other
10468	 * reason?  e.g. a request sense with a head of queue tag
10469	 * immediately after a write.  Normally that would block, but this
10470	 * will result in its getting executed immediately...
10471	 *
10472	 * We currently return "pass" instead of "skip", so we'll end up
10473	 * going through the rest of the queue to check for overlapped tags.
10474	 *
10475	 * XXX KDM check for other types of blockage first??
10476	 */
10477	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10478		return (CTL_ACTION_PASS);
10479
10480	/*
10481	 * Ordered tags have to block until all items ahead of them
10482	 * have completed.  If we get called with an ordered tag, we always
10483	 * block, if something else is ahead of us in the queue.
10484	 */
10485	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10486		return (CTL_ACTION_BLOCK);
10487
10488	/*
10489	 * Simple tags get blocked until all head of queue and ordered tags
10490	 * ahead of them have completed.  I'm lumping untagged commands in
10491	 * with simple tags here.  XXX KDM is that the right thing to do?
10492	 */
10493	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10494	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10495	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10496	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10497		return (CTL_ACTION_BLOCK);
10498
10499	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10500	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10501
10502	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10503
10504	switch (serialize_row[pending_entry->seridx]) {
10505	case CTL_SER_BLOCK:
10506		return (CTL_ACTION_BLOCK);
10507	case CTL_SER_EXTENT:
10508		return (ctl_extent_check(ooa_io, pending_io,
10509		    (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10510	case CTL_SER_EXTENTOPT:
10511		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10512		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10513			return (ctl_extent_check(ooa_io, pending_io,
10514			    (lun->be_lun &&
10515			     lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10516		return (CTL_ACTION_PASS);
10517	case CTL_SER_EXTENTSEQ:
10518		if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
10519			return (ctl_extent_check_seq(ooa_io, pending_io));
10520		return (CTL_ACTION_PASS);
10521	case CTL_SER_PASS:
10522		return (CTL_ACTION_PASS);
10523	case CTL_SER_BLOCKOPT:
10524		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10525		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10526			return (CTL_ACTION_BLOCK);
10527		return (CTL_ACTION_PASS);
10528	case CTL_SER_SKIP:
10529		return (CTL_ACTION_SKIP);
10530	default:
10531		panic("invalid serialization value %d",
10532		      serialize_row[pending_entry->seridx]);
10533	}
10534
10535	return (CTL_ACTION_ERROR);
10536}
10537
10538/*
10539 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10540 * Assumptions:
10541 * - pending_io is generally either incoming, or on the blocked queue
10542 * - starting I/O is the I/O we want to start the check with.
10543 */
10544static ctl_action
10545ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10546	      union ctl_io *starting_io)
10547{
10548	union ctl_io *ooa_io;
10549	ctl_action action;
10550
10551	mtx_assert(&lun->lun_lock, MA_OWNED);
10552
10553	/*
10554	 * Run back along the OOA queue, starting with the current
10555	 * blocked I/O and going through every I/O before it on the
10556	 * queue.  If starting_io is NULL, we'll just end up returning
10557	 * CTL_ACTION_PASS.
10558	 */
10559	for (ooa_io = starting_io; ooa_io != NULL;
10560	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10561	     ooa_links)){
10562
10563		/*
10564		 * This routine just checks to see whether
10565		 * cur_blocked is blocked by ooa_io, which is ahead
10566		 * of it in the queue.  It doesn't queue/dequeue
10567		 * cur_blocked.
10568		 */
10569		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10570		switch (action) {
10571		case CTL_ACTION_BLOCK:
10572		case CTL_ACTION_OVERLAP:
10573		case CTL_ACTION_OVERLAP_TAG:
10574		case CTL_ACTION_SKIP:
10575		case CTL_ACTION_ERROR:
10576			return (action);
10577			break; /* NOTREACHED */
10578		case CTL_ACTION_PASS:
10579			break;
10580		default:
10581			panic("invalid action %d", action);
10582			break;  /* NOTREACHED */
10583		}
10584	}
10585
10586	return (CTL_ACTION_PASS);
10587}
10588
10589/*
10590 * Assumptions:
10591 * - An I/O has just completed, and has been removed from the per-LUN OOA
10592 *   queue, so some items on the blocked queue may now be unblocked.
10593 */
10594static int
10595ctl_check_blocked(struct ctl_lun *lun)
10596{
10597	union ctl_io *cur_blocked, *next_blocked;
10598
10599	mtx_assert(&lun->lun_lock, MA_OWNED);
10600
10601	/*
10602	 * Run forward from the head of the blocked queue, checking each
10603	 * entry against the I/Os prior to it on the OOA queue to see if
10604	 * there is still any blockage.
10605	 *
10606	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10607	 * with our removing a variable on it while it is traversing the
10608	 * list.
10609	 */
10610	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10611	     cur_blocked != NULL; cur_blocked = next_blocked) {
10612		union ctl_io *prev_ooa;
10613		ctl_action action;
10614
10615		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10616							  blocked_links);
10617
10618		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10619						      ctl_ooaq, ooa_links);
10620
10621		/*
10622		 * If cur_blocked happens to be the first item in the OOA
10623		 * queue now, prev_ooa will be NULL, and the action
10624		 * returned will just be CTL_ACTION_PASS.
10625		 */
10626		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
10627
10628		switch (action) {
10629		case CTL_ACTION_BLOCK:
10630			/* Nothing to do here, still blocked */
10631			break;
10632		case CTL_ACTION_OVERLAP:
10633		case CTL_ACTION_OVERLAP_TAG:
10634			/*
10635			 * This shouldn't happen!  In theory we've already
10636			 * checked this command for overlap...
10637			 */
10638			break;
10639		case CTL_ACTION_PASS:
10640		case CTL_ACTION_SKIP: {
10641			const struct ctl_cmd_entry *entry;
10642			int isc_retval;
10643
10644			/*
10645			 * The skip case shouldn't happen, this transaction
10646			 * should have never made it onto the blocked queue.
10647			 */
10648			/*
10649			 * This I/O is no longer blocked, we can remove it
10650			 * from the blocked queue.  Since this is a TAILQ
10651			 * (doubly linked list), we can do O(1) removals
10652			 * from any place on the list.
10653			 */
10654			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
10655				     blocked_links);
10656			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10657
10658			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
10659				/*
10660				 * Need to send IO back to original side to
10661				 * run
10662				 */
10663				union ctl_ha_msg msg_info;
10664
10665				msg_info.hdr.original_sc =
10666					cur_blocked->io_hdr.original_sc;
10667				msg_info.hdr.serializing_sc = cur_blocked;
10668				msg_info.hdr.msg_type = CTL_MSG_R2R;
10669				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
10670				     &msg_info, sizeof(msg_info), 0)) >
10671				     CTL_HA_STATUS_SUCCESS) {
10672					printf("CTL:Check Blocked error from "
10673					       "ctl_ha_msg_send %d\n",
10674					       isc_retval);
10675				}
10676				break;
10677			}
10678			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
10679
10680			/*
10681			 * Check this I/O for LUN state changes that may
10682			 * have happened while this command was blocked.
10683			 * The LUN state may have been changed by a command
10684			 * ahead of us in the queue, so we need to re-check
10685			 * for any states that can be caused by SCSI
10686			 * commands.
10687			 */
10688			if (ctl_scsiio_lun_check(lun, entry,
10689						 &cur_blocked->scsiio) == 0) {
10690				cur_blocked->io_hdr.flags |=
10691				                      CTL_FLAG_IS_WAS_ON_RTR;
10692				ctl_enqueue_rtr(cur_blocked);
10693			} else
10694				ctl_done(cur_blocked);
10695			break;
10696		}
10697		default:
10698			/*
10699			 * This probably shouldn't happen -- we shouldn't
10700			 * get CTL_ACTION_ERROR, or anything else.
10701			 */
10702			break;
10703		}
10704	}
10705
10706	return (CTL_RETVAL_COMPLETE);
10707}
10708
10709/*
10710 * This routine (with one exception) checks LUN flags that can be set by
10711 * commands ahead of us in the OOA queue.  These flags have to be checked
10712 * when a command initially comes in, and when we pull a command off the
10713 * blocked queue and are preparing to execute it.  The reason we have to
10714 * check these flags for commands on the blocked queue is that the LUN
10715 * state may have been changed by a command ahead of us while we're on the
10716 * blocked queue.
10717 *
10718 * Ordering is somewhat important with these checks, so please pay
10719 * careful attention to the placement of any new checks.
10720 */
10721static int
10722ctl_scsiio_lun_check(struct ctl_lun *lun,
10723    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
10724{
10725	struct ctl_softc *softc = lun->ctl_softc;
10726	int retval;
10727	uint32_t residx;
10728
10729	retval = 0;
10730
10731	mtx_assert(&lun->lun_lock, MA_OWNED);
10732
10733	/*
10734	 * If this shelf is a secondary shelf controller, we have to reject
10735	 * any media access commands.
10736	 */
10737	if ((softc->flags & CTL_FLAG_ACTIVE_SHELF) == 0 &&
10738	    (entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0) {
10739		ctl_set_lun_standby(ctsio);
10740		retval = 1;
10741		goto bailout;
10742	}
10743
10744	if (entry->pattern & CTL_LUN_PAT_WRITE) {
10745		if (lun->be_lun &&
10746		    lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
10747			ctl_set_sense(ctsio, /*current_error*/ 1,
10748			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
10749			    /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
10750			retval = 1;
10751			goto bailout;
10752		}
10753		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
10754		    .eca_and_aen & SCP_SWP) != 0) {
10755			ctl_set_sense(ctsio, /*current_error*/ 1,
10756			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
10757			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
10758			retval = 1;
10759			goto bailout;
10760		}
10761	}
10762
10763	/*
10764	 * Check for a reservation conflict.  If this command isn't allowed
10765	 * even on reserved LUNs, and if this initiator isn't the one who
10766	 * reserved us, reject the command with a reservation conflict.
10767	 */
10768	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
10769	if ((lun->flags & CTL_LUN_RESERVED)
10770	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
10771		if (lun->res_idx != residx) {
10772			ctl_set_reservation_conflict(ctsio);
10773			retval = 1;
10774			goto bailout;
10775		}
10776	}
10777
10778	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
10779	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
10780		/* No reservation or command is allowed. */;
10781	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
10782	    (lun->res_type == SPR_TYPE_WR_EX ||
10783	     lun->res_type == SPR_TYPE_WR_EX_RO ||
10784	     lun->res_type == SPR_TYPE_WR_EX_AR)) {
10785		/* The command is allowed for Write Exclusive resv. */;
10786	} else {
10787		/*
10788		 * if we aren't registered or it's a res holder type
10789		 * reservation and this isn't the res holder then set a
10790		 * conflict.
10791		 */
10792		if (ctl_get_prkey(lun, residx) == 0
10793		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
10794			ctl_set_reservation_conflict(ctsio);
10795			retval = 1;
10796			goto bailout;
10797		}
10798
10799	}
10800
10801	if ((lun->flags & CTL_LUN_OFFLINE)
10802	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
10803		ctl_set_lun_not_ready(ctsio);
10804		retval = 1;
10805		goto bailout;
10806	}
10807
10808	/*
10809	 * If the LUN is stopped, see if this particular command is allowed
10810	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
10811	 */
10812	if ((lun->flags & CTL_LUN_STOPPED)
10813	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
10814		/* "Logical unit not ready, initializing cmd. required" */
10815		ctl_set_lun_stopped(ctsio);
10816		retval = 1;
10817		goto bailout;
10818	}
10819
10820	if ((lun->flags & CTL_LUN_INOPERABLE)
10821	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
10822		/* "Medium format corrupted" */
10823		ctl_set_medium_format_corrupted(ctsio);
10824		retval = 1;
10825		goto bailout;
10826	}
10827
10828bailout:
10829	return (retval);
10830
10831}
10832
10833static void
10834ctl_failover_io(union ctl_io *io, int have_lock)
10835{
10836	ctl_set_busy(&io->scsiio);
10837	ctl_done(io);
10838}
10839
10840#ifdef notyet
10841static void
10842ctl_failover(void)
10843{
10844	struct ctl_lun *lun;
10845	struct ctl_softc *softc;
10846	union ctl_io *next_io, *pending_io;
10847	union ctl_io *io;
10848	int lun_idx;
10849
10850	softc = control_softc;
10851
10852	mtx_lock(&softc->ctl_lock);
10853	/*
10854	 * Remove any cmds from the other SC from the rtr queue.  These
10855	 * will obviously only be for LUNs for which we're the primary.
10856	 * We can't send status or get/send data for these commands.
10857	 * Since they haven't been executed yet, we can just remove them.
10858	 * We'll either abort them or delete them below, depending on
10859	 * which HA mode we're in.
10860	 */
10861#ifdef notyet
10862	mtx_lock(&softc->queue_lock);
10863	for (io = (union ctl_io *)STAILQ_FIRST(&softc->rtr_queue);
10864	     io != NULL; io = next_io) {
10865		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
10866		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
10867			STAILQ_REMOVE(&softc->rtr_queue, &io->io_hdr,
10868				      ctl_io_hdr, links);
10869	}
10870	mtx_unlock(&softc->queue_lock);
10871#endif
10872
10873	for (lun_idx=0; lun_idx < softc->num_luns; lun_idx++) {
10874		lun = softc->ctl_luns[lun_idx];
10875		if (lun==NULL)
10876			continue;
10877
10878		/*
10879		 * Processor LUNs are primary on both sides.
10880		 * XXX will this always be true?
10881		 */
10882		if (lun->be_lun->lun_type == T_PROCESSOR)
10883			continue;
10884
10885		if ((lun->flags & CTL_LUN_PRIMARY_SC)
10886		 && (softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
10887			printf("FAILOVER: primary lun %d\n", lun_idx);
10888		        /*
10889			 * Remove all commands from the other SC. First from the
10890			 * blocked queue then from the ooa queue. Once we have
10891			 * removed them. Call ctl_check_blocked to see if there
10892			 * is anything that can run.
10893			 */
10894			for (io = (union ctl_io *)TAILQ_FIRST(
10895			     &lun->blocked_queue); io != NULL; io = next_io) {
10896
10897		        	next_io = (union ctl_io *)TAILQ_NEXT(
10898				    &io->io_hdr, blocked_links);
10899
10900				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
10901					TAILQ_REMOVE(&lun->blocked_queue,
10902						     &io->io_hdr,blocked_links);
10903					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10904					TAILQ_REMOVE(&lun->ooa_queue,
10905						     &io->io_hdr, ooa_links);
10906
10907					ctl_free_io(io);
10908				}
10909			}
10910
10911			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
10912	     		     io != NULL; io = next_io) {
10913
10914		        	next_io = (union ctl_io *)TAILQ_NEXT(
10915				    &io->io_hdr, ooa_links);
10916
10917				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
10918
10919					TAILQ_REMOVE(&lun->ooa_queue,
10920						&io->io_hdr,
10921					     	ooa_links);
10922
10923					ctl_free_io(io);
10924				}
10925			}
10926			ctl_check_blocked(lun);
10927		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
10928			&& (softc->ha_mode == CTL_HA_MODE_XFER)) {
10929
10930			printf("FAILOVER: primary lun %d\n", lun_idx);
10931			/*
10932			 * Abort all commands from the other SC.  We can't
10933			 * send status back for them now.  These should get
10934			 * cleaned up when they are completed or come out
10935			 * for a datamove operation.
10936			 */
10937			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
10938	     		     io != NULL; io = next_io) {
10939		        	next_io = (union ctl_io *)TAILQ_NEXT(
10940					&io->io_hdr, ooa_links);
10941
10942				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
10943					io->io_hdr.flags |= CTL_FLAG_ABORT;
10944			}
10945		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
10946			&& (softc->ha_mode == CTL_HA_MODE_XFER)) {
10947
10948			printf("FAILOVER: secondary lun %d\n", lun_idx);
10949
10950			lun->flags |= CTL_LUN_PRIMARY_SC;
10951
10952			/*
10953			 * We send all I/O that was sent to this controller
10954			 * and redirected to the other side back with
10955			 * busy status, and have the initiator retry it.
10956			 * Figuring out how much data has been transferred,
10957			 * etc. and picking up where we left off would be
10958			 * very tricky.
10959			 *
10960			 * XXX KDM need to remove I/O from the blocked
10961			 * queue as well!
10962			 */
10963			for (pending_io = (union ctl_io *)TAILQ_FIRST(
10964			     &lun->ooa_queue); pending_io != NULL;
10965			     pending_io = next_io) {
10966
10967				next_io =  (union ctl_io *)TAILQ_NEXT(
10968					&pending_io->io_hdr, ooa_links);
10969
10970				pending_io->io_hdr.flags &=
10971					~CTL_FLAG_SENT_2OTHER_SC;
10972
10973				if (pending_io->io_hdr.flags &
10974				    CTL_FLAG_IO_ACTIVE) {
10975					pending_io->io_hdr.flags |=
10976						CTL_FLAG_FAILOVER;
10977				} else {
10978					ctl_set_busy(&pending_io->scsiio);
10979					ctl_done(pending_io);
10980				}
10981			}
10982
10983			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
10984		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
10985			&& (softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
10986			printf("FAILOVER: secondary lun %d\n", lun_idx);
10987			/*
10988			 * if the first io on the OOA is not on the RtR queue
10989			 * add it.
10990			 */
10991			lun->flags |= CTL_LUN_PRIMARY_SC;
10992
10993			pending_io = (union ctl_io *)TAILQ_FIRST(
10994			    &lun->ooa_queue);
10995			if (pending_io==NULL) {
10996				printf("Nothing on OOA queue\n");
10997				continue;
10998			}
10999
11000			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11001			if ((pending_io->io_hdr.flags &
11002			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11003				pending_io->io_hdr.flags |=
11004				    CTL_FLAG_IS_WAS_ON_RTR;
11005				ctl_enqueue_rtr(pending_io);
11006			}
11007#if 0
11008			else
11009			{
11010				printf("Tag 0x%04x is running\n",
11011				      pending_io->scsiio.tag_num);
11012			}
11013#endif
11014
11015			next_io = (union ctl_io *)TAILQ_NEXT(
11016			    &pending_io->io_hdr, ooa_links);
11017			for (pending_io=next_io; pending_io != NULL;
11018			     pending_io = next_io) {
11019				pending_io->io_hdr.flags &=
11020				    ~CTL_FLAG_SENT_2OTHER_SC;
11021				next_io = (union ctl_io *)TAILQ_NEXT(
11022					&pending_io->io_hdr, ooa_links);
11023				if (pending_io->io_hdr.flags &
11024				    CTL_FLAG_IS_WAS_ON_RTR) {
11025#if 0
11026				        printf("Tag 0x%04x is running\n",
11027				      		pending_io->scsiio.tag_num);
11028#endif
11029					continue;
11030				}
11031
11032				switch (ctl_check_ooa(lun, pending_io,
11033			            (union ctl_io *)TAILQ_PREV(
11034				    &pending_io->io_hdr, ctl_ooaq,
11035				    ooa_links))) {
11036
11037				case CTL_ACTION_BLOCK:
11038					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11039							  &pending_io->io_hdr,
11040							  blocked_links);
11041					pending_io->io_hdr.flags |=
11042					    CTL_FLAG_BLOCKED;
11043					break;
11044				case CTL_ACTION_PASS:
11045				case CTL_ACTION_SKIP:
11046					pending_io->io_hdr.flags |=
11047					    CTL_FLAG_IS_WAS_ON_RTR;
11048					ctl_enqueue_rtr(pending_io);
11049					break;
11050				case CTL_ACTION_OVERLAP:
11051					ctl_set_overlapped_cmd(
11052					    (struct ctl_scsiio *)pending_io);
11053					ctl_done(pending_io);
11054					break;
11055				case CTL_ACTION_OVERLAP_TAG:
11056					ctl_set_overlapped_tag(
11057					    (struct ctl_scsiio *)pending_io,
11058					    pending_io->scsiio.tag_num & 0xff);
11059					ctl_done(pending_io);
11060					break;
11061				case CTL_ACTION_ERROR:
11062				default:
11063					ctl_set_internal_failure(
11064						(struct ctl_scsiio *)pending_io,
11065						0,  // sks_valid
11066						0); //retry count
11067					ctl_done(pending_io);
11068					break;
11069				}
11070			}
11071
11072			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11073		} else {
11074			panic("Unhandled HA mode failover, LUN flags = %#x, "
11075			      "ha_mode = #%x", lun->flags, softc->ha_mode);
11076		}
11077	}
11078	ctl_pause_rtr = 0;
11079	mtx_unlock(&softc->ctl_lock);
11080}
11081#endif
11082
11083static int
11084ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11085{
11086	struct ctl_lun *lun;
11087	const struct ctl_cmd_entry *entry;
11088	uint32_t initidx, targ_lun;
11089	int retval;
11090
11091	retval = 0;
11092
11093	lun = NULL;
11094
11095	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11096	if ((targ_lun < CTL_MAX_LUNS)
11097	 && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11098		/*
11099		 * If the LUN is invalid, pretend that it doesn't exist.
11100		 * It will go away as soon as all pending I/O has been
11101		 * completed.
11102		 */
11103		mtx_lock(&lun->lun_lock);
11104		if (lun->flags & CTL_LUN_DISABLED) {
11105			mtx_unlock(&lun->lun_lock);
11106			lun = NULL;
11107			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11108			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11109		} else {
11110			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11111			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11112				lun->be_lun;
11113			if (lun->be_lun->lun_type == T_PROCESSOR) {
11114				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11115			}
11116
11117			/*
11118			 * Every I/O goes into the OOA queue for a
11119			 * particular LUN, and stays there until completion.
11120			 */
11121#ifdef CTL_TIME_IO
11122			if (TAILQ_EMPTY(&lun->ooa_queue)) {
11123				lun->idle_time += getsbinuptime() -
11124				    lun->last_busy;
11125			}
11126#endif
11127			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11128			    ooa_links);
11129		}
11130	} else {
11131		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11132		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11133	}
11134
11135	/* Get command entry and return error if it is unsuppotyed. */
11136	entry = ctl_validate_command(ctsio);
11137	if (entry == NULL) {
11138		if (lun)
11139			mtx_unlock(&lun->lun_lock);
11140		return (retval);
11141	}
11142
11143	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11144	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11145
11146	/*
11147	 * Check to see whether we can send this command to LUNs that don't
11148	 * exist.  This should pretty much only be the case for inquiry
11149	 * and request sense.  Further checks, below, really require having
11150	 * a LUN, so we can't really check the command anymore.  Just put
11151	 * it on the rtr queue.
11152	 */
11153	if (lun == NULL) {
11154		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11155			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11156			ctl_enqueue_rtr((union ctl_io *)ctsio);
11157			return (retval);
11158		}
11159
11160		ctl_set_unsupported_lun(ctsio);
11161		ctl_done((union ctl_io *)ctsio);
11162		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11163		return (retval);
11164	} else {
11165		/*
11166		 * Make sure we support this particular command on this LUN.
11167		 * e.g., we don't support writes to the control LUN.
11168		 */
11169		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11170			mtx_unlock(&lun->lun_lock);
11171			ctl_set_invalid_opcode(ctsio);
11172			ctl_done((union ctl_io *)ctsio);
11173			return (retval);
11174		}
11175	}
11176
11177	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11178
11179#ifdef CTL_WITH_CA
11180	/*
11181	 * If we've got a request sense, it'll clear the contingent
11182	 * allegiance condition.  Otherwise, if we have a CA condition for
11183	 * this initiator, clear it, because it sent down a command other
11184	 * than request sense.
11185	 */
11186	if ((ctsio->cdb[0] != REQUEST_SENSE)
11187	 && (ctl_is_set(lun->have_ca, initidx)))
11188		ctl_clear_mask(lun->have_ca, initidx);
11189#endif
11190
11191	/*
11192	 * If the command has this flag set, it handles its own unit
11193	 * attention reporting, we shouldn't do anything.  Otherwise we
11194	 * check for any pending unit attentions, and send them back to the
11195	 * initiator.  We only do this when a command initially comes in,
11196	 * not when we pull it off the blocked queue.
11197	 *
11198	 * According to SAM-3, section 5.3.2, the order that things get
11199	 * presented back to the host is basically unit attentions caused
11200	 * by some sort of reset event, busy status, reservation conflicts
11201	 * or task set full, and finally any other status.
11202	 *
11203	 * One issue here is that some of the unit attentions we report
11204	 * don't fall into the "reset" category (e.g. "reported luns data
11205	 * has changed").  So reporting it here, before the reservation
11206	 * check, may be technically wrong.  I guess the only thing to do
11207	 * would be to check for and report the reset events here, and then
11208	 * check for the other unit attention types after we check for a
11209	 * reservation conflict.
11210	 *
11211	 * XXX KDM need to fix this
11212	 */
11213	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11214		ctl_ua_type ua_type;
11215		scsi_sense_data_type sense_format;
11216
11217		if (lun->flags & CTL_LUN_SENSE_DESC)
11218			sense_format = SSD_TYPE_DESC;
11219		else
11220			sense_format = SSD_TYPE_FIXED;
11221
11222		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11223		    sense_format);
11224		if (ua_type != CTL_UA_NONE) {
11225			mtx_unlock(&lun->lun_lock);
11226			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11227			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11228			ctsio->sense_len = SSD_FULL_SIZE;
11229			ctl_done((union ctl_io *)ctsio);
11230			return (retval);
11231		}
11232	}
11233
11234
11235	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11236		mtx_unlock(&lun->lun_lock);
11237		ctl_done((union ctl_io *)ctsio);
11238		return (retval);
11239	}
11240
11241	/*
11242	 * XXX CHD this is where we want to send IO to other side if
11243	 * this LUN is secondary on this SC. We will need to make a copy
11244	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11245	 * the copy we send as FROM_OTHER.
11246	 * We also need to stuff the address of the original IO so we can
11247	 * find it easily. Something similar will need be done on the other
11248	 * side so when we are done we can find the copy.
11249	 */
11250	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11251		union ctl_ha_msg msg_info;
11252		int isc_retval;
11253
11254		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11255
11256		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11257		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11258#if 0
11259		printf("1. ctsio %p\n", ctsio);
11260#endif
11261		msg_info.hdr.serializing_sc = NULL;
11262		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11263		msg_info.scsi.tag_num = ctsio->tag_num;
11264		msg_info.scsi.tag_type = ctsio->tag_type;
11265		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11266
11267		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11268
11269		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11270		    (void *)&msg_info, sizeof(msg_info), 0)) >
11271		    CTL_HA_STATUS_SUCCESS) {
11272			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11273			       isc_retval);
11274			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11275		} else {
11276#if 0
11277			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11278#endif
11279		}
11280
11281		/*
11282		 * XXX KDM this I/O is off the incoming queue, but hasn't
11283		 * been inserted on any other queue.  We may need to come
11284		 * up with a holding queue while we wait for serialization
11285		 * so that we have an idea of what we're waiting for from
11286		 * the other side.
11287		 */
11288		mtx_unlock(&lun->lun_lock);
11289		return (retval);
11290	}
11291
11292	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11293			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11294			      ctl_ooaq, ooa_links))) {
11295	case CTL_ACTION_BLOCK:
11296		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11297		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11298				  blocked_links);
11299		mtx_unlock(&lun->lun_lock);
11300		return (retval);
11301	case CTL_ACTION_PASS:
11302	case CTL_ACTION_SKIP:
11303		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11304		mtx_unlock(&lun->lun_lock);
11305		ctl_enqueue_rtr((union ctl_io *)ctsio);
11306		break;
11307	case CTL_ACTION_OVERLAP:
11308		mtx_unlock(&lun->lun_lock);
11309		ctl_set_overlapped_cmd(ctsio);
11310		ctl_done((union ctl_io *)ctsio);
11311		break;
11312	case CTL_ACTION_OVERLAP_TAG:
11313		mtx_unlock(&lun->lun_lock);
11314		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11315		ctl_done((union ctl_io *)ctsio);
11316		break;
11317	case CTL_ACTION_ERROR:
11318	default:
11319		mtx_unlock(&lun->lun_lock);
11320		ctl_set_internal_failure(ctsio,
11321					 /*sks_valid*/ 0,
11322					 /*retry_count*/ 0);
11323		ctl_done((union ctl_io *)ctsio);
11324		break;
11325	}
11326	return (retval);
11327}
11328
11329const struct ctl_cmd_entry *
11330ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11331{
11332	const struct ctl_cmd_entry *entry;
11333	int service_action;
11334
11335	entry = &ctl_cmd_table[ctsio->cdb[0]];
11336	if (sa)
11337		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11338	if (entry->flags & CTL_CMD_FLAG_SA5) {
11339		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11340		entry = &((const struct ctl_cmd_entry *)
11341		    entry->execute)[service_action];
11342	}
11343	return (entry);
11344}
11345
11346const struct ctl_cmd_entry *
11347ctl_validate_command(struct ctl_scsiio *ctsio)
11348{
11349	const struct ctl_cmd_entry *entry;
11350	int i, sa;
11351	uint8_t diff;
11352
11353	entry = ctl_get_cmd_entry(ctsio, &sa);
11354	if (entry->execute == NULL) {
11355		if (sa)
11356			ctl_set_invalid_field(ctsio,
11357					      /*sks_valid*/ 1,
11358					      /*command*/ 1,
11359					      /*field*/ 1,
11360					      /*bit_valid*/ 1,
11361					      /*bit*/ 4);
11362		else
11363			ctl_set_invalid_opcode(ctsio);
11364		ctl_done((union ctl_io *)ctsio);
11365		return (NULL);
11366	}
11367	KASSERT(entry->length > 0,
11368	    ("Not defined length for command 0x%02x/0x%02x",
11369	     ctsio->cdb[0], ctsio->cdb[1]));
11370	for (i = 1; i < entry->length; i++) {
11371		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11372		if (diff == 0)
11373			continue;
11374		ctl_set_invalid_field(ctsio,
11375				      /*sks_valid*/ 1,
11376				      /*command*/ 1,
11377				      /*field*/ i,
11378				      /*bit_valid*/ 1,
11379				      /*bit*/ fls(diff) - 1);
11380		ctl_done((union ctl_io *)ctsio);
11381		return (NULL);
11382	}
11383	return (entry);
11384}
11385
11386static int
11387ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11388{
11389
11390	switch (lun_type) {
11391	case T_PROCESSOR:
11392		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11393		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11394			return (0);
11395		break;
11396	case T_DIRECT:
11397		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11398		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11399			return (0);
11400		break;
11401	default:
11402		return (0);
11403	}
11404	return (1);
11405}
11406
11407static int
11408ctl_scsiio(struct ctl_scsiio *ctsio)
11409{
11410	int retval;
11411	const struct ctl_cmd_entry *entry;
11412
11413	retval = CTL_RETVAL_COMPLETE;
11414
11415	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11416
11417	entry = ctl_get_cmd_entry(ctsio, NULL);
11418
11419	/*
11420	 * If this I/O has been aborted, just send it straight to
11421	 * ctl_done() without executing it.
11422	 */
11423	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11424		ctl_done((union ctl_io *)ctsio);
11425		goto bailout;
11426	}
11427
11428	/*
11429	 * All the checks should have been handled by ctl_scsiio_precheck().
11430	 * We should be clear now to just execute the I/O.
11431	 */
11432	retval = entry->execute(ctsio);
11433
11434bailout:
11435	return (retval);
11436}
11437
11438/*
11439 * Since we only implement one target right now, a bus reset simply resets
11440 * our single target.
11441 */
11442static int
11443ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11444{
11445	return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11446}
11447
11448static int
11449ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11450		 ctl_ua_type ua_type)
11451{
11452	struct ctl_lun *lun;
11453	int retval;
11454
11455	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11456		union ctl_ha_msg msg_info;
11457
11458		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11459		msg_info.hdr.nexus = io->io_hdr.nexus;
11460		if (ua_type==CTL_UA_TARG_RESET)
11461			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11462		else
11463			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11464		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11465		msg_info.hdr.original_sc = NULL;
11466		msg_info.hdr.serializing_sc = NULL;
11467		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11468		    (void *)&msg_info, sizeof(msg_info), 0)) {
11469		}
11470	}
11471	retval = 0;
11472
11473	mtx_lock(&softc->ctl_lock);
11474	STAILQ_FOREACH(lun, &softc->lun_list, links)
11475		retval += ctl_lun_reset(lun, io, ua_type);
11476	mtx_unlock(&softc->ctl_lock);
11477
11478	return (retval);
11479}
11480
11481/*
11482 * The LUN should always be set.  The I/O is optional, and is used to
11483 * distinguish between I/Os sent by this initiator, and by other
11484 * initiators.  We set unit attention for initiators other than this one.
11485 * SAM-3 is vague on this point.  It does say that a unit attention should
11486 * be established for other initiators when a LUN is reset (see section
11487 * 5.7.3), but it doesn't specifically say that the unit attention should
11488 * be established for this particular initiator when a LUN is reset.  Here
11489 * is the relevant text, from SAM-3 rev 8:
11490 *
11491 * 5.7.2 When a SCSI initiator port aborts its own tasks
11492 *
11493 * When a SCSI initiator port causes its own task(s) to be aborted, no
11494 * notification that the task(s) have been aborted shall be returned to
11495 * the SCSI initiator port other than the completion response for the
11496 * command or task management function action that caused the task(s) to
11497 * be aborted and notification(s) associated with related effects of the
11498 * action (e.g., a reset unit attention condition).
11499 *
11500 * XXX KDM for now, we're setting unit attention for all initiators.
11501 */
11502static int
11503ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11504{
11505	union ctl_io *xio;
11506#if 0
11507	uint32_t initidx;
11508#endif
11509#ifdef CTL_WITH_CA
11510	int i;
11511#endif
11512
11513	mtx_lock(&lun->lun_lock);
11514	/*
11515	 * Run through the OOA queue and abort each I/O.
11516	 */
11517	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11518	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11519		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11520	}
11521
11522	/*
11523	 * This version sets unit attention for every
11524	 */
11525#if 0
11526	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11527	ctl_est_ua_all(lun, initidx, ua_type);
11528#else
11529	ctl_est_ua_all(lun, -1, ua_type);
11530#endif
11531
11532	/*
11533	 * A reset (any kind, really) clears reservations established with
11534	 * RESERVE/RELEASE.  It does not clear reservations established
11535	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11536	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11537	 * reservations made with the RESERVE/RELEASE commands, because
11538	 * those commands are obsolete in SPC-3.
11539	 */
11540	lun->flags &= ~CTL_LUN_RESERVED;
11541
11542#ifdef CTL_WITH_CA
11543	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11544		ctl_clear_mask(lun->have_ca, i);
11545#endif
11546	mtx_unlock(&lun->lun_lock);
11547
11548	return (0);
11549}
11550
11551static void
11552ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11553    int other_sc)
11554{
11555	union ctl_io *xio;
11556
11557	mtx_assert(&lun->lun_lock, MA_OWNED);
11558
11559	/*
11560	 * Run through the OOA queue and attempt to find the given I/O.
11561	 * The target port, initiator ID, tag type and tag number have to
11562	 * match the values that we got from the initiator.  If we have an
11563	 * untagged command to abort, simply abort the first untagged command
11564	 * we come to.  We only allow one untagged command at a time of course.
11565	 */
11566	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11567	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11568
11569		if ((targ_port == UINT32_MAX ||
11570		     targ_port == xio->io_hdr.nexus.targ_port) &&
11571		    (init_id == UINT32_MAX ||
11572		     init_id == xio->io_hdr.nexus.initid)) {
11573			if (targ_port != xio->io_hdr.nexus.targ_port ||
11574			    init_id != xio->io_hdr.nexus.initid)
11575				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11576			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11577			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11578				union ctl_ha_msg msg_info;
11579
11580				msg_info.hdr.nexus = xio->io_hdr.nexus;
11581				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11582				msg_info.task.tag_num = xio->scsiio.tag_num;
11583				msg_info.task.tag_type = xio->scsiio.tag_type;
11584				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11585				msg_info.hdr.original_sc = NULL;
11586				msg_info.hdr.serializing_sc = NULL;
11587				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11588				    (void *)&msg_info, sizeof(msg_info), 0);
11589			}
11590		}
11591	}
11592}
11593
11594static int
11595ctl_abort_task_set(union ctl_io *io)
11596{
11597	struct ctl_softc *softc = control_softc;
11598	struct ctl_lun *lun;
11599	uint32_t targ_lun;
11600
11601	/*
11602	 * Look up the LUN.
11603	 */
11604	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11605	mtx_lock(&softc->ctl_lock);
11606	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
11607		lun = softc->ctl_luns[targ_lun];
11608	else {
11609		mtx_unlock(&softc->ctl_lock);
11610		return (1);
11611	}
11612
11613	mtx_lock(&lun->lun_lock);
11614	mtx_unlock(&softc->ctl_lock);
11615	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11616		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11617		    io->io_hdr.nexus.initid,
11618		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11619	} else { /* CTL_TASK_CLEAR_TASK_SET */
11620		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11621		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11622	}
11623	mtx_unlock(&lun->lun_lock);
11624	return (0);
11625}
11626
11627static int
11628ctl_i_t_nexus_reset(union ctl_io *io)
11629{
11630	struct ctl_softc *softc = control_softc;
11631	struct ctl_lun *lun;
11632	uint32_t initidx, residx;
11633
11634	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11635	residx = ctl_get_resindex(&io->io_hdr.nexus);
11636	mtx_lock(&softc->ctl_lock);
11637	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11638		mtx_lock(&lun->lun_lock);
11639		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11640		    io->io_hdr.nexus.initid,
11641		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11642#ifdef CTL_WITH_CA
11643		ctl_clear_mask(lun->have_ca, initidx);
11644#endif
11645		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
11646			lun->flags &= ~CTL_LUN_RESERVED;
11647		ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
11648		mtx_unlock(&lun->lun_lock);
11649	}
11650	mtx_unlock(&softc->ctl_lock);
11651	return (0);
11652}
11653
11654static int
11655ctl_abort_task(union ctl_io *io)
11656{
11657	union ctl_io *xio;
11658	struct ctl_lun *lun;
11659	struct ctl_softc *softc;
11660#if 0
11661	struct sbuf sb;
11662	char printbuf[128];
11663#endif
11664	int found;
11665	uint32_t targ_lun;
11666
11667	softc = control_softc;
11668	found = 0;
11669
11670	/*
11671	 * Look up the LUN.
11672	 */
11673	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11674	mtx_lock(&softc->ctl_lock);
11675	if ((targ_lun < CTL_MAX_LUNS)
11676	 && (softc->ctl_luns[targ_lun] != NULL))
11677		lun = softc->ctl_luns[targ_lun];
11678	else {
11679		mtx_unlock(&softc->ctl_lock);
11680		return (1);
11681	}
11682
11683#if 0
11684	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11685	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11686#endif
11687
11688	mtx_lock(&lun->lun_lock);
11689	mtx_unlock(&softc->ctl_lock);
11690	/*
11691	 * Run through the OOA queue and attempt to find the given I/O.
11692	 * The target port, initiator ID, tag type and tag number have to
11693	 * match the values that we got from the initiator.  If we have an
11694	 * untagged command to abort, simply abort the first untagged command
11695	 * we come to.  We only allow one untagged command at a time of course.
11696	 */
11697	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11698	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11699#if 0
11700		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
11701
11702		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
11703			    lun->lun, xio->scsiio.tag_num,
11704			    xio->scsiio.tag_type,
11705			    (xio->io_hdr.blocked_links.tqe_prev
11706			    == NULL) ? "" : " BLOCKED",
11707			    (xio->io_hdr.flags &
11708			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
11709			    (xio->io_hdr.flags &
11710			    CTL_FLAG_ABORT) ? " ABORT" : "",
11711			    (xio->io_hdr.flags &
11712			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
11713		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
11714		sbuf_finish(&sb);
11715		printf("%s\n", sbuf_data(&sb));
11716#endif
11717
11718		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
11719		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
11720		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
11721			continue;
11722
11723		/*
11724		 * If the abort says that the task is untagged, the
11725		 * task in the queue must be untagged.  Otherwise,
11726		 * we just check to see whether the tag numbers
11727		 * match.  This is because the QLogic firmware
11728		 * doesn't pass back the tag type in an abort
11729		 * request.
11730		 */
11731#if 0
11732		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
11733		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
11734		 || (xio->scsiio.tag_num == io->taskio.tag_num))
11735#endif
11736		/*
11737		 * XXX KDM we've got problems with FC, because it
11738		 * doesn't send down a tag type with aborts.  So we
11739		 * can only really go by the tag number...
11740		 * This may cause problems with parallel SCSI.
11741		 * Need to figure that out!!
11742		 */
11743		if (xio->scsiio.tag_num == io->taskio.tag_num) {
11744			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11745			found = 1;
11746			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
11747			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11748				union ctl_ha_msg msg_info;
11749
11750				io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11751				msg_info.hdr.nexus = io->io_hdr.nexus;
11752				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11753				msg_info.task.tag_num = io->taskio.tag_num;
11754				msg_info.task.tag_type = io->taskio.tag_type;
11755				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11756				msg_info.hdr.original_sc = NULL;
11757				msg_info.hdr.serializing_sc = NULL;
11758#if 0
11759				printf("Sent Abort to other side\n");
11760#endif
11761				if (ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11762				    (void *)&msg_info, sizeof(msg_info), 0) !=
11763				    CTL_HA_STATUS_SUCCESS) {
11764				}
11765			}
11766#if 0
11767			printf("ctl_abort_task: found I/O to abort\n");
11768#endif
11769		}
11770	}
11771	mtx_unlock(&lun->lun_lock);
11772
11773	if (found == 0) {
11774		/*
11775		 * This isn't really an error.  It's entirely possible for
11776		 * the abort and command completion to cross on the wire.
11777		 * This is more of an informative/diagnostic error.
11778		 */
11779#if 0
11780		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
11781		       "%u:%u:%u tag %d type %d\n",
11782		       io->io_hdr.nexus.initid,
11783		       io->io_hdr.nexus.targ_port,
11784		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
11785		       io->taskio.tag_type);
11786#endif
11787	}
11788	return (0);
11789}
11790
11791static void
11792ctl_run_task(union ctl_io *io)
11793{
11794	struct ctl_softc *softc = control_softc;
11795	int retval = 1;
11796	const char *task_desc;
11797
11798	CTL_DEBUG_PRINT(("ctl_run_task\n"));
11799
11800	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
11801	    ("ctl_run_task: Unextected io_type %d\n",
11802	     io->io_hdr.io_type));
11803
11804	task_desc = ctl_scsi_task_string(&io->taskio);
11805	if (task_desc != NULL) {
11806#ifdef NEEDTOPORT
11807		csevent_log(CSC_CTL | CSC_SHELF_SW |
11808			    CTL_TASK_REPORT,
11809			    csevent_LogType_Trace,
11810			    csevent_Severity_Information,
11811			    csevent_AlertLevel_Green,
11812			    csevent_FRU_Firmware,
11813			    csevent_FRU_Unknown,
11814			    "CTL: received task: %s",task_desc);
11815#endif
11816	} else {
11817#ifdef NEEDTOPORT
11818		csevent_log(CSC_CTL | CSC_SHELF_SW |
11819			    CTL_TASK_REPORT,
11820			    csevent_LogType_Trace,
11821			    csevent_Severity_Information,
11822			    csevent_AlertLevel_Green,
11823			    csevent_FRU_Firmware,
11824			    csevent_FRU_Unknown,
11825			    "CTL: received unknown task "
11826			    "type: %d (%#x)",
11827			    io->taskio.task_action,
11828			    io->taskio.task_action);
11829#endif
11830	}
11831	switch (io->taskio.task_action) {
11832	case CTL_TASK_ABORT_TASK:
11833		retval = ctl_abort_task(io);
11834		break;
11835	case CTL_TASK_ABORT_TASK_SET:
11836	case CTL_TASK_CLEAR_TASK_SET:
11837		retval = ctl_abort_task_set(io);
11838		break;
11839	case CTL_TASK_CLEAR_ACA:
11840		break;
11841	case CTL_TASK_I_T_NEXUS_RESET:
11842		retval = ctl_i_t_nexus_reset(io);
11843		break;
11844	case CTL_TASK_LUN_RESET: {
11845		struct ctl_lun *lun;
11846		uint32_t targ_lun;
11847
11848		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11849		mtx_lock(&softc->ctl_lock);
11850		if ((targ_lun < CTL_MAX_LUNS)
11851		 && (softc->ctl_luns[targ_lun] != NULL))
11852			lun = softc->ctl_luns[targ_lun];
11853		else {
11854			mtx_unlock(&softc->ctl_lock);
11855			retval = 1;
11856			break;
11857		}
11858
11859		if (!(io->io_hdr.flags &
11860		    CTL_FLAG_FROM_OTHER_SC)) {
11861			union ctl_ha_msg msg_info;
11862
11863			io->io_hdr.flags |=
11864				CTL_FLAG_SENT_2OTHER_SC;
11865			msg_info.hdr.msg_type =
11866				CTL_MSG_MANAGE_TASKS;
11867			msg_info.hdr.nexus = io->io_hdr.nexus;
11868			msg_info.task.task_action =
11869				CTL_TASK_LUN_RESET;
11870			msg_info.hdr.original_sc = NULL;
11871			msg_info.hdr.serializing_sc = NULL;
11872			if (CTL_HA_STATUS_SUCCESS !=
11873			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11874			    (void *)&msg_info,
11875			    sizeof(msg_info), 0)) {
11876			}
11877		}
11878
11879		retval = ctl_lun_reset(lun, io,
11880				       CTL_UA_LUN_RESET);
11881		mtx_unlock(&softc->ctl_lock);
11882		break;
11883	}
11884	case CTL_TASK_TARGET_RESET:
11885		retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
11886		break;
11887	case CTL_TASK_BUS_RESET:
11888		retval = ctl_bus_reset(softc, io);
11889		break;
11890	case CTL_TASK_PORT_LOGIN:
11891		break;
11892	case CTL_TASK_PORT_LOGOUT:
11893		break;
11894	default:
11895		printf("ctl_run_task: got unknown task management event %d\n",
11896		       io->taskio.task_action);
11897		break;
11898	}
11899	if (retval == 0)
11900		io->io_hdr.status = CTL_SUCCESS;
11901	else
11902		io->io_hdr.status = CTL_ERROR;
11903	ctl_done(io);
11904}
11905
11906/*
11907 * For HA operation.  Handle commands that come in from the other
11908 * controller.
11909 */
11910static void
11911ctl_handle_isc(union ctl_io *io)
11912{
11913	int free_io;
11914	struct ctl_lun *lun;
11915	struct ctl_softc *softc;
11916	uint32_t targ_lun;
11917
11918	softc = control_softc;
11919
11920	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11921	lun = softc->ctl_luns[targ_lun];
11922
11923	switch (io->io_hdr.msg_type) {
11924	case CTL_MSG_SERIALIZE:
11925		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
11926		break;
11927	case CTL_MSG_R2R: {
11928		const struct ctl_cmd_entry *entry;
11929
11930		/*
11931		 * This is only used in SER_ONLY mode.
11932		 */
11933		free_io = 0;
11934		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
11935		mtx_lock(&lun->lun_lock);
11936		if (ctl_scsiio_lun_check(lun,
11937		    entry, (struct ctl_scsiio *)io) != 0) {
11938			mtx_unlock(&lun->lun_lock);
11939			ctl_done(io);
11940			break;
11941		}
11942		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11943		mtx_unlock(&lun->lun_lock);
11944		ctl_enqueue_rtr(io);
11945		break;
11946	}
11947	case CTL_MSG_FINISH_IO:
11948		if (softc->ha_mode == CTL_HA_MODE_XFER) {
11949			free_io = 0;
11950			ctl_done(io);
11951		} else {
11952			free_io = 1;
11953			mtx_lock(&lun->lun_lock);
11954			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
11955				     ooa_links);
11956			ctl_check_blocked(lun);
11957			mtx_unlock(&lun->lun_lock);
11958		}
11959		break;
11960	case CTL_MSG_PERS_ACTION:
11961		ctl_hndl_per_res_out_on_other_sc(
11962			(union ctl_ha_msg *)&io->presio.pr_msg);
11963		free_io = 1;
11964		break;
11965	case CTL_MSG_BAD_JUJU:
11966		free_io = 0;
11967		ctl_done(io);
11968		break;
11969	case CTL_MSG_DATAMOVE:
11970		/* Only used in XFER mode */
11971		free_io = 0;
11972		ctl_datamove_remote(io);
11973		break;
11974	case CTL_MSG_DATAMOVE_DONE:
11975		/* Only used in XFER mode */
11976		free_io = 0;
11977		io->scsiio.be_move_done(io);
11978		break;
11979	default:
11980		free_io = 1;
11981		printf("%s: Invalid message type %d\n",
11982		       __func__, io->io_hdr.msg_type);
11983		break;
11984	}
11985	if (free_io)
11986		ctl_free_io(io);
11987
11988}
11989
11990
11991/*
11992 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
11993 * there is no match.
11994 */
11995static ctl_lun_error_pattern
11996ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
11997{
11998	const struct ctl_cmd_entry *entry;
11999	ctl_lun_error_pattern filtered_pattern, pattern;
12000
12001	pattern = desc->error_pattern;
12002
12003	/*
12004	 * XXX KDM we need more data passed into this function to match a
12005	 * custom pattern, and we actually need to implement custom pattern
12006	 * matching.
12007	 */
12008	if (pattern & CTL_LUN_PAT_CMD)
12009		return (CTL_LUN_PAT_CMD);
12010
12011	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12012		return (CTL_LUN_PAT_ANY);
12013
12014	entry = ctl_get_cmd_entry(ctsio, NULL);
12015
12016	filtered_pattern = entry->pattern & pattern;
12017
12018	/*
12019	 * If the user requested specific flags in the pattern (e.g.
12020	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12021	 * flags.
12022	 *
12023	 * If the user did not specify any flags, it doesn't matter whether
12024	 * or not the command supports the flags.
12025	 */
12026	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12027	     (pattern & ~CTL_LUN_PAT_MASK))
12028		return (CTL_LUN_PAT_NONE);
12029
12030	/*
12031	 * If the user asked for a range check, see if the requested LBA
12032	 * range overlaps with this command's LBA range.
12033	 */
12034	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12035		uint64_t lba1;
12036		uint64_t len1;
12037		ctl_action action;
12038		int retval;
12039
12040		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12041		if (retval != 0)
12042			return (CTL_LUN_PAT_NONE);
12043
12044		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12045					      desc->lba_range.len, FALSE);
12046		/*
12047		 * A "pass" means that the LBA ranges don't overlap, so
12048		 * this doesn't match the user's range criteria.
12049		 */
12050		if (action == CTL_ACTION_PASS)
12051			return (CTL_LUN_PAT_NONE);
12052	}
12053
12054	return (filtered_pattern);
12055}
12056
12057static void
12058ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12059{
12060	struct ctl_error_desc *desc, *desc2;
12061
12062	mtx_assert(&lun->lun_lock, MA_OWNED);
12063
12064	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12065		ctl_lun_error_pattern pattern;
12066		/*
12067		 * Check to see whether this particular command matches
12068		 * the pattern in the descriptor.
12069		 */
12070		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12071		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12072			continue;
12073
12074		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12075		case CTL_LUN_INJ_ABORTED:
12076			ctl_set_aborted(&io->scsiio);
12077			break;
12078		case CTL_LUN_INJ_MEDIUM_ERR:
12079			ctl_set_medium_error(&io->scsiio);
12080			break;
12081		case CTL_LUN_INJ_UA:
12082			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12083			 * OCCURRED */
12084			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12085			break;
12086		case CTL_LUN_INJ_CUSTOM:
12087			/*
12088			 * We're assuming the user knows what he is doing.
12089			 * Just copy the sense information without doing
12090			 * checks.
12091			 */
12092			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12093			      MIN(sizeof(desc->custom_sense),
12094				  sizeof(io->scsiio.sense_data)));
12095			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12096			io->scsiio.sense_len = SSD_FULL_SIZE;
12097			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12098			break;
12099		case CTL_LUN_INJ_NONE:
12100		default:
12101			/*
12102			 * If this is an error injection type we don't know
12103			 * about, clear the continuous flag (if it is set)
12104			 * so it will get deleted below.
12105			 */
12106			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12107			break;
12108		}
12109		/*
12110		 * By default, each error injection action is a one-shot
12111		 */
12112		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12113			continue;
12114
12115		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12116
12117		free(desc, M_CTL);
12118	}
12119}
12120
12121#ifdef CTL_IO_DELAY
12122static void
12123ctl_datamove_timer_wakeup(void *arg)
12124{
12125	union ctl_io *io;
12126
12127	io = (union ctl_io *)arg;
12128
12129	ctl_datamove(io);
12130}
12131#endif /* CTL_IO_DELAY */
12132
12133void
12134ctl_datamove(union ctl_io *io)
12135{
12136	void (*fe_datamove)(union ctl_io *io);
12137
12138	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12139
12140	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12141
12142#ifdef CTL_TIME_IO
12143	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12144		char str[256];
12145		char path_str[64];
12146		struct sbuf sb;
12147
12148		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12149		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12150
12151		sbuf_cat(&sb, path_str);
12152		switch (io->io_hdr.io_type) {
12153		case CTL_IO_SCSI:
12154			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12155			sbuf_printf(&sb, "\n");
12156			sbuf_cat(&sb, path_str);
12157			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12158				    io->scsiio.tag_num, io->scsiio.tag_type);
12159			break;
12160		case CTL_IO_TASK:
12161			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12162				    "Tag Type: %d\n", io->taskio.task_action,
12163				    io->taskio.tag_num, io->taskio.tag_type);
12164			break;
12165		default:
12166			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12167			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12168			break;
12169		}
12170		sbuf_cat(&sb, path_str);
12171		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12172			    (intmax_t)time_uptime - io->io_hdr.start_time);
12173		sbuf_finish(&sb);
12174		printf("%s", sbuf_data(&sb));
12175	}
12176#endif /* CTL_TIME_IO */
12177
12178#ifdef CTL_IO_DELAY
12179	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12180		struct ctl_lun *lun;
12181
12182		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12183
12184		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12185	} else {
12186		struct ctl_lun *lun;
12187
12188		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12189		if ((lun != NULL)
12190		 && (lun->delay_info.datamove_delay > 0)) {
12191
12192			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12193			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12194			callout_reset(&io->io_hdr.delay_callout,
12195				      lun->delay_info.datamove_delay * hz,
12196				      ctl_datamove_timer_wakeup, io);
12197			if (lun->delay_info.datamove_type ==
12198			    CTL_DELAY_TYPE_ONESHOT)
12199				lun->delay_info.datamove_delay = 0;
12200			return;
12201		}
12202	}
12203#endif
12204
12205	/*
12206	 * This command has been aborted.  Set the port status, so we fail
12207	 * the data move.
12208	 */
12209	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12210		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12211		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12212		       io->io_hdr.nexus.targ_port,
12213		       io->io_hdr.nexus.targ_lun);
12214		io->io_hdr.port_status = 31337;
12215		/*
12216		 * Note that the backend, in this case, will get the
12217		 * callback in its context.  In other cases it may get
12218		 * called in the frontend's interrupt thread context.
12219		 */
12220		io->scsiio.be_move_done(io);
12221		return;
12222	}
12223
12224	/* Don't confuse frontend with zero length data move. */
12225	if (io->scsiio.kern_data_len == 0) {
12226		io->scsiio.be_move_done(io);
12227		return;
12228	}
12229
12230	/*
12231	 * If we're in XFER mode and this I/O is from the other shelf
12232	 * controller, we need to send the DMA to the other side to
12233	 * actually transfer the data to/from the host.  In serialize only
12234	 * mode the transfer happens below CTL and ctl_datamove() is only
12235	 * called on the machine that originally received the I/O.
12236	 */
12237	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12238	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12239		union ctl_ha_msg msg;
12240		uint32_t sg_entries_sent;
12241		int do_sg_copy;
12242		int i;
12243
12244		memset(&msg, 0, sizeof(msg));
12245		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12246		msg.hdr.original_sc = io->io_hdr.original_sc;
12247		msg.hdr.serializing_sc = io;
12248		msg.hdr.nexus = io->io_hdr.nexus;
12249		msg.dt.flags = io->io_hdr.flags;
12250		/*
12251		 * We convert everything into a S/G list here.  We can't
12252		 * pass by reference, only by value between controllers.
12253		 * So we can't pass a pointer to the S/G list, only as many
12254		 * S/G entries as we can fit in here.  If it's possible for
12255		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12256		 * then we need to break this up into multiple transfers.
12257		 */
12258		if (io->scsiio.kern_sg_entries == 0) {
12259			msg.dt.kern_sg_entries = 1;
12260			/*
12261			 * If this is in cached memory, flush the cache
12262			 * before we send the DMA request to the other
12263			 * controller.  We want to do this in either the
12264			 * read or the write case.  The read case is
12265			 * straightforward.  In the write case, we want to
12266			 * make sure nothing is in the local cache that
12267			 * could overwrite the DMAed data.
12268			 */
12269			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12270				/*
12271				 * XXX KDM use bus_dmamap_sync() here.
12272				 */
12273			}
12274
12275			/*
12276			 * Convert to a physical address if this is a
12277			 * virtual address.
12278			 */
12279			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12280				msg.dt.sg_list[0].addr =
12281					io->scsiio.kern_data_ptr;
12282			} else {
12283				/*
12284				 * XXX KDM use busdma here!
12285				 */
12286#if 0
12287				msg.dt.sg_list[0].addr = (void *)
12288					vtophys(io->scsiio.kern_data_ptr);
12289#endif
12290			}
12291
12292			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12293			do_sg_copy = 0;
12294		} else {
12295			struct ctl_sg_entry *sgl;
12296
12297			do_sg_copy = 1;
12298			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12299			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12300			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12301				/*
12302				 * XXX KDM use bus_dmamap_sync() here.
12303				 */
12304			}
12305		}
12306
12307		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12308		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12309		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12310		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12311		msg.dt.sg_sequence = 0;
12312
12313		/*
12314		 * Loop until we've sent all of the S/G entries.  On the
12315		 * other end, we'll recompose these S/G entries into one
12316		 * contiguous list before passing it to the
12317		 */
12318		for (sg_entries_sent = 0; sg_entries_sent <
12319		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12320			msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list)/
12321				sizeof(msg.dt.sg_list[0])),
12322				msg.dt.kern_sg_entries - sg_entries_sent);
12323
12324			if (do_sg_copy != 0) {
12325				struct ctl_sg_entry *sgl;
12326				int j;
12327
12328				sgl = (struct ctl_sg_entry *)
12329					io->scsiio.kern_data_ptr;
12330				/*
12331				 * If this is in cached memory, flush the cache
12332				 * before we send the DMA request to the other
12333				 * controller.  We want to do this in either
12334				 * the * read or the write case.  The read
12335				 * case is straightforward.  In the write
12336				 * case, we want to make sure nothing is
12337				 * in the local cache that could overwrite
12338				 * the DMAed data.
12339				 */
12340
12341				for (i = sg_entries_sent, j = 0;
12342				     i < msg.dt.cur_sg_entries; i++, j++) {
12343					if ((io->io_hdr.flags &
12344					     CTL_FLAG_NO_DATASYNC) == 0) {
12345						/*
12346						 * XXX KDM use bus_dmamap_sync()
12347						 */
12348					}
12349					if ((io->io_hdr.flags &
12350					     CTL_FLAG_BUS_ADDR) == 0) {
12351						/*
12352						 * XXX KDM use busdma.
12353						 */
12354#if 0
12355						msg.dt.sg_list[j].addr =(void *)
12356						       vtophys(sgl[i].addr);
12357#endif
12358					} else {
12359						msg.dt.sg_list[j].addr =
12360							sgl[i].addr;
12361					}
12362					msg.dt.sg_list[j].len = sgl[i].len;
12363				}
12364			}
12365
12366			sg_entries_sent += msg.dt.cur_sg_entries;
12367			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12368				msg.dt.sg_last = 1;
12369			else
12370				msg.dt.sg_last = 0;
12371
12372			/*
12373			 * XXX KDM drop and reacquire the lock here?
12374			 */
12375			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12376			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12377				/*
12378				 * XXX do something here.
12379				 */
12380			}
12381
12382			msg.dt.sent_sg_entries = sg_entries_sent;
12383		}
12384		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12385		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12386			ctl_failover_io(io, /*have_lock*/ 0);
12387
12388	} else {
12389
12390		/*
12391		 * Lookup the fe_datamove() function for this particular
12392		 * front end.
12393		 */
12394		fe_datamove =
12395		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12396
12397		fe_datamove(io);
12398	}
12399}
12400
12401static void
12402ctl_send_datamove_done(union ctl_io *io, int have_lock)
12403{
12404	union ctl_ha_msg msg;
12405	int isc_status;
12406
12407	memset(&msg, 0, sizeof(msg));
12408
12409	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12410	msg.hdr.original_sc = io;
12411	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12412	msg.hdr.nexus = io->io_hdr.nexus;
12413	msg.hdr.status = io->io_hdr.status;
12414	msg.scsi.tag_num = io->scsiio.tag_num;
12415	msg.scsi.tag_type = io->scsiio.tag_type;
12416	msg.scsi.scsi_status = io->scsiio.scsi_status;
12417	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12418	       sizeof(io->scsiio.sense_data));
12419	msg.scsi.sense_len = io->scsiio.sense_len;
12420	msg.scsi.sense_residual = io->scsiio.sense_residual;
12421	msg.scsi.fetd_status = io->io_hdr.port_status;
12422	msg.scsi.residual = io->scsiio.residual;
12423	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12424
12425	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12426		ctl_failover_io(io, /*have_lock*/ have_lock);
12427		return;
12428	}
12429
12430	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12431	if (isc_status > CTL_HA_STATUS_SUCCESS) {
12432		/* XXX do something if this fails */
12433	}
12434
12435}
12436
12437/*
12438 * The DMA to the remote side is done, now we need to tell the other side
12439 * we're done so it can continue with its data movement.
12440 */
12441static void
12442ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12443{
12444	union ctl_io *io;
12445
12446	io = rq->context;
12447
12448	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12449		printf("%s: ISC DMA write failed with error %d", __func__,
12450		       rq->ret);
12451		ctl_set_internal_failure(&io->scsiio,
12452					 /*sks_valid*/ 1,
12453					 /*retry_count*/ rq->ret);
12454	}
12455
12456	ctl_dt_req_free(rq);
12457
12458	/*
12459	 * In this case, we had to malloc the memory locally.  Free it.
12460	 */
12461	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12462		int i;
12463		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12464			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12465	}
12466	/*
12467	 * The data is in local and remote memory, so now we need to send
12468	 * status (good or back) back to the other side.
12469	 */
12470	ctl_send_datamove_done(io, /*have_lock*/ 0);
12471}
12472
12473/*
12474 * We've moved the data from the host/controller into local memory.  Now we
12475 * need to push it over to the remote controller's memory.
12476 */
12477static int
12478ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12479{
12480	int retval;
12481
12482	retval = 0;
12483
12484	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12485					  ctl_datamove_remote_write_cb);
12486
12487	return (retval);
12488}
12489
12490static void
12491ctl_datamove_remote_write(union ctl_io *io)
12492{
12493	int retval;
12494	void (*fe_datamove)(union ctl_io *io);
12495
12496	/*
12497	 * - Get the data from the host/HBA into local memory.
12498	 * - DMA memory from the local controller to the remote controller.
12499	 * - Send status back to the remote controller.
12500	 */
12501
12502	retval = ctl_datamove_remote_sgl_setup(io);
12503	if (retval != 0)
12504		return;
12505
12506	/* Switch the pointer over so the FETD knows what to do */
12507	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12508
12509	/*
12510	 * Use a custom move done callback, since we need to send completion
12511	 * back to the other controller, not to the backend on this side.
12512	 */
12513	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12514
12515	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12516
12517	fe_datamove(io);
12518
12519	return;
12520
12521}
12522
12523static int
12524ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12525{
12526#if 0
12527	char str[256];
12528	char path_str[64];
12529	struct sbuf sb;
12530#endif
12531
12532	/*
12533	 * In this case, we had to malloc the memory locally.  Free it.
12534	 */
12535	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12536		int i;
12537		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12538			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12539	}
12540
12541#if 0
12542	scsi_path_string(io, path_str, sizeof(path_str));
12543	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12544	sbuf_cat(&sb, path_str);
12545	scsi_command_string(&io->scsiio, NULL, &sb);
12546	sbuf_printf(&sb, "\n");
12547	sbuf_cat(&sb, path_str);
12548	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12549		    io->scsiio.tag_num, io->scsiio.tag_type);
12550	sbuf_cat(&sb, path_str);
12551	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12552		    io->io_hdr.flags, io->io_hdr.status);
12553	sbuf_finish(&sb);
12554	printk("%s", sbuf_data(&sb));
12555#endif
12556
12557
12558	/*
12559	 * The read is done, now we need to send status (good or bad) back
12560	 * to the other side.
12561	 */
12562	ctl_send_datamove_done(io, /*have_lock*/ 0);
12563
12564	return (0);
12565}
12566
12567static void
12568ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12569{
12570	union ctl_io *io;
12571	void (*fe_datamove)(union ctl_io *io);
12572
12573	io = rq->context;
12574
12575	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12576		printf("%s: ISC DMA read failed with error %d", __func__,
12577		       rq->ret);
12578		ctl_set_internal_failure(&io->scsiio,
12579					 /*sks_valid*/ 1,
12580					 /*retry_count*/ rq->ret);
12581	}
12582
12583	ctl_dt_req_free(rq);
12584
12585	/* Switch the pointer over so the FETD knows what to do */
12586	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12587
12588	/*
12589	 * Use a custom move done callback, since we need to send completion
12590	 * back to the other controller, not to the backend on this side.
12591	 */
12592	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12593
12594	/* XXX KDM add checks like the ones in ctl_datamove? */
12595
12596	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12597
12598	fe_datamove(io);
12599}
12600
12601static int
12602ctl_datamove_remote_sgl_setup(union ctl_io *io)
12603{
12604	struct ctl_sg_entry *local_sglist, *remote_sglist;
12605	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
12606	struct ctl_softc *softc;
12607	int retval;
12608	int i;
12609
12610	retval = 0;
12611	softc = control_softc;
12612
12613	local_sglist = io->io_hdr.local_sglist;
12614	local_dma_sglist = io->io_hdr.local_dma_sglist;
12615	remote_sglist = io->io_hdr.remote_sglist;
12616	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
12617
12618	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
12619		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
12620			local_sglist[i].len = remote_sglist[i].len;
12621
12622			/*
12623			 * XXX Detect the situation where the RS-level I/O
12624			 * redirector on the other side has already read the
12625			 * data off of the AOR RS on this side, and
12626			 * transferred it to remote (mirror) memory on the
12627			 * other side.  Since we already have the data in
12628			 * memory here, we just need to use it.
12629			 *
12630			 * XXX KDM this can probably be removed once we
12631			 * get the cache device code in and take the
12632			 * current AOR implementation out.
12633			 */
12634#ifdef NEEDTOPORT
12635			if ((remote_sglist[i].addr >=
12636			     (void *)vtophys(softc->mirr->addr))
12637			 && (remote_sglist[i].addr <
12638			     ((void *)vtophys(softc->mirr->addr) +
12639			     CacheMirrorOffset))) {
12640				local_sglist[i].addr = remote_sglist[i].addr -
12641					CacheMirrorOffset;
12642				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12643				     CTL_FLAG_DATA_IN)
12644					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
12645			} else {
12646				local_sglist[i].addr = remote_sglist[i].addr +
12647					CacheMirrorOffset;
12648			}
12649#endif
12650#if 0
12651			printf("%s: local %p, remote %p, len %d\n",
12652			       __func__, local_sglist[i].addr,
12653			       remote_sglist[i].addr, local_sglist[i].len);
12654#endif
12655		}
12656	} else {
12657		uint32_t len_to_go;
12658
12659		/*
12660		 * In this case, we don't have automatically allocated
12661		 * memory for this I/O on this controller.  This typically
12662		 * happens with internal CTL I/O -- e.g. inquiry, mode
12663		 * sense, etc.  Anything coming from RAIDCore will have
12664		 * a mirror area available.
12665		 */
12666		len_to_go = io->scsiio.kern_data_len;
12667
12668		/*
12669		 * Clear the no datasync flag, we have to use malloced
12670		 * buffers.
12671		 */
12672		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
12673
12674		/*
12675		 * The difficult thing here is that the size of the various
12676		 * S/G segments may be different than the size from the
12677		 * remote controller.  That'll make it harder when DMAing
12678		 * the data back to the other side.
12679		 */
12680		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
12681		     sizeof(io->io_hdr.remote_sglist[0])) &&
12682		     (len_to_go > 0); i++) {
12683			local_sglist[i].len = MIN(len_to_go, 131072);
12684			CTL_SIZE_8B(local_dma_sglist[i].len,
12685				    local_sglist[i].len);
12686			local_sglist[i].addr =
12687				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
12688
12689			local_dma_sglist[i].addr = local_sglist[i].addr;
12690
12691			if (local_sglist[i].addr == NULL) {
12692				int j;
12693
12694				printf("malloc failed for %zd bytes!",
12695				       local_dma_sglist[i].len);
12696				for (j = 0; j < i; j++) {
12697					free(local_sglist[j].addr, M_CTL);
12698				}
12699				ctl_set_internal_failure(&io->scsiio,
12700							 /*sks_valid*/ 1,
12701							 /*retry_count*/ 4857);
12702				retval = 1;
12703				goto bailout_error;
12704
12705			}
12706			/* XXX KDM do we need a sync here? */
12707
12708			len_to_go -= local_sglist[i].len;
12709		}
12710		/*
12711		 * Reset the number of S/G entries accordingly.  The
12712		 * original number of S/G entries is available in
12713		 * rem_sg_entries.
12714		 */
12715		io->scsiio.kern_sg_entries = i;
12716
12717#if 0
12718		printf("%s: kern_sg_entries = %d\n", __func__,
12719		       io->scsiio.kern_sg_entries);
12720		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12721			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
12722			       local_sglist[i].addr, local_sglist[i].len,
12723			       local_dma_sglist[i].len);
12724#endif
12725	}
12726
12727
12728	return (retval);
12729
12730bailout_error:
12731
12732	ctl_send_datamove_done(io, /*have_lock*/ 0);
12733
12734	return (retval);
12735}
12736
12737static int
12738ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12739			 ctl_ha_dt_cb callback)
12740{
12741	struct ctl_ha_dt_req *rq;
12742	struct ctl_sg_entry *remote_sglist, *local_sglist;
12743	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
12744	uint32_t local_used, remote_used, total_used;
12745	int retval;
12746	int i, j;
12747
12748	retval = 0;
12749
12750	rq = ctl_dt_req_alloc();
12751
12752	/*
12753	 * If we failed to allocate the request, and if the DMA didn't fail
12754	 * anyway, set busy status.  This is just a resource allocation
12755	 * failure.
12756	 */
12757	if ((rq == NULL)
12758	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
12759		ctl_set_busy(&io->scsiio);
12760
12761	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
12762
12763		if (rq != NULL)
12764			ctl_dt_req_free(rq);
12765
12766		/*
12767		 * The data move failed.  We need to return status back
12768		 * to the other controller.  No point in trying to DMA
12769		 * data to the remote controller.
12770		 */
12771
12772		ctl_send_datamove_done(io, /*have_lock*/ 0);
12773
12774		retval = 1;
12775
12776		goto bailout;
12777	}
12778
12779	local_sglist = io->io_hdr.local_sglist;
12780	local_dma_sglist = io->io_hdr.local_dma_sglist;
12781	remote_sglist = io->io_hdr.remote_sglist;
12782	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
12783	local_used = 0;
12784	remote_used = 0;
12785	total_used = 0;
12786
12787	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
12788		rq->ret = CTL_HA_STATUS_SUCCESS;
12789		rq->context = io;
12790		callback(rq);
12791		goto bailout;
12792	}
12793
12794	/*
12795	 * Pull/push the data over the wire from/to the other controller.
12796	 * This takes into account the possibility that the local and
12797	 * remote sglists may not be identical in terms of the size of
12798	 * the elements and the number of elements.
12799	 *
12800	 * One fundamental assumption here is that the length allocated for
12801	 * both the local and remote sglists is identical.  Otherwise, we've
12802	 * essentially got a coding error of some sort.
12803	 */
12804	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12805		int isc_ret;
12806		uint32_t cur_len, dma_length;
12807		uint8_t *tmp_ptr;
12808
12809		rq->id = CTL_HA_DATA_CTL;
12810		rq->command = command;
12811		rq->context = io;
12812
12813		/*
12814		 * Both pointers should be aligned.  But it is possible
12815		 * that the allocation length is not.  They should both
12816		 * also have enough slack left over at the end, though,
12817		 * to round up to the next 8 byte boundary.
12818		 */
12819		cur_len = MIN(local_sglist[i].len - local_used,
12820			      remote_sglist[j].len - remote_used);
12821
12822		/*
12823		 * In this case, we have a size issue and need to decrease
12824		 * the size, except in the case where we actually have less
12825		 * than 8 bytes left.  In that case, we need to increase
12826		 * the DMA length to get the last bit.
12827		 */
12828		if ((cur_len & 0x7) != 0) {
12829			if (cur_len > 0x7) {
12830				cur_len = cur_len - (cur_len & 0x7);
12831				dma_length = cur_len;
12832			} else {
12833				CTL_SIZE_8B(dma_length, cur_len);
12834			}
12835
12836		} else
12837			dma_length = cur_len;
12838
12839		/*
12840		 * If we had to allocate memory for this I/O, instead of using
12841		 * the non-cached mirror memory, we'll need to flush the cache
12842		 * before trying to DMA to the other controller.
12843		 *
12844		 * We could end up doing this multiple times for the same
12845		 * segment if we have a larger local segment than remote
12846		 * segment.  That shouldn't be an issue.
12847		 */
12848		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12849			/*
12850			 * XXX KDM use bus_dmamap_sync() here.
12851			 */
12852		}
12853
12854		rq->size = dma_length;
12855
12856		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12857		tmp_ptr += local_used;
12858
12859		/* Use physical addresses when talking to ISC hardware */
12860		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12861			/* XXX KDM use busdma */
12862#if 0
12863			rq->local = vtophys(tmp_ptr);
12864#endif
12865		} else
12866			rq->local = tmp_ptr;
12867
12868		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12869		tmp_ptr += remote_used;
12870		rq->remote = tmp_ptr;
12871
12872		rq->callback = NULL;
12873
12874		local_used += cur_len;
12875		if (local_used >= local_sglist[i].len) {
12876			i++;
12877			local_used = 0;
12878		}
12879
12880		remote_used += cur_len;
12881		if (remote_used >= remote_sglist[j].len) {
12882			j++;
12883			remote_used = 0;
12884		}
12885		total_used += cur_len;
12886
12887		if (total_used >= io->scsiio.kern_data_len)
12888			rq->callback = callback;
12889
12890		if ((rq->size & 0x7) != 0) {
12891			printf("%s: warning: size %d is not on 8b boundary\n",
12892			       __func__, rq->size);
12893		}
12894		if (((uintptr_t)rq->local & 0x7) != 0) {
12895			printf("%s: warning: local %p not on 8b boundary\n",
12896			       __func__, rq->local);
12897		}
12898		if (((uintptr_t)rq->remote & 0x7) != 0) {
12899			printf("%s: warning: remote %p not on 8b boundary\n",
12900			       __func__, rq->local);
12901		}
12902#if 0
12903		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
12904		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
12905		       rq->local, rq->remote, rq->size);
12906#endif
12907
12908		isc_ret = ctl_dt_single(rq);
12909		if (isc_ret == CTL_HA_STATUS_WAIT)
12910			continue;
12911
12912		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
12913			rq->ret = CTL_HA_STATUS_SUCCESS;
12914		} else {
12915			rq->ret = isc_ret;
12916		}
12917		callback(rq);
12918		goto bailout;
12919	}
12920
12921bailout:
12922	return (retval);
12923
12924}
12925
12926static void
12927ctl_datamove_remote_read(union ctl_io *io)
12928{
12929	int retval;
12930	int i;
12931
12932	/*
12933	 * This will send an error to the other controller in the case of a
12934	 * failure.
12935	 */
12936	retval = ctl_datamove_remote_sgl_setup(io);
12937	if (retval != 0)
12938		return;
12939
12940	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12941					  ctl_datamove_remote_read_cb);
12942	if ((retval != 0)
12943	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
12944		/*
12945		 * Make sure we free memory if there was an error..  The
12946		 * ctl_datamove_remote_xfer() function will send the
12947		 * datamove done message, or call the callback with an
12948		 * error if there is a problem.
12949		 */
12950		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12951			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12952	}
12953
12954	return;
12955}
12956
12957/*
12958 * Process a datamove request from the other controller.  This is used for
12959 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12960 * first.  Once that is complete, the data gets DMAed into the remote
12961 * controller's memory.  For reads, we DMA from the remote controller's
12962 * memory into our memory first, and then move it out to the FETD.
12963 */
12964static void
12965ctl_datamove_remote(union ctl_io *io)
12966{
12967	struct ctl_softc *softc;
12968
12969	softc = control_softc;
12970
12971	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
12972
12973	/*
12974	 * Note that we look for an aborted I/O here, but don't do some of
12975	 * the other checks that ctl_datamove() normally does.
12976	 * We don't need to run the datamove delay code, since that should
12977	 * have been done if need be on the other controller.
12978	 */
12979	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12980		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
12981		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12982		       io->io_hdr.nexus.targ_port,
12983		       io->io_hdr.nexus.targ_lun);
12984		io->io_hdr.port_status = 31338;
12985		ctl_send_datamove_done(io, /*have_lock*/ 0);
12986		return;
12987	}
12988
12989	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
12990		ctl_datamove_remote_write(io);
12991	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
12992		ctl_datamove_remote_read(io);
12993	} else {
12994		union ctl_ha_msg msg;
12995		struct scsi_sense_data *sense;
12996		uint8_t sks[3];
12997		int retry_count;
12998
12999		memset(&msg, 0, sizeof(msg));
13000
13001		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13002		msg.hdr.status = CTL_SCSI_ERROR;
13003		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13004
13005		retry_count = 4243;
13006
13007		sense = &msg.scsi.sense_data;
13008		sks[0] = SSD_SCS_VALID;
13009		sks[1] = (retry_count >> 8) & 0xff;
13010		sks[2] = retry_count & 0xff;
13011
13012		/* "Internal target failure" */
13013		scsi_set_sense_data(sense,
13014				    /*sense_format*/ SSD_TYPE_NONE,
13015				    /*current_error*/ 1,
13016				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13017				    /*asc*/ 0x44,
13018				    /*ascq*/ 0x00,
13019				    /*type*/ SSD_ELEM_SKS,
13020				    /*size*/ sizeof(sks),
13021				    /*data*/ sks,
13022				    SSD_ELEM_NONE);
13023
13024		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13025		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13026			ctl_failover_io(io, /*have_lock*/ 1);
13027			return;
13028		}
13029
13030		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13031		    CTL_HA_STATUS_SUCCESS) {
13032			/* XXX KDM what to do if this fails? */
13033		}
13034		return;
13035	}
13036
13037}
13038
13039static int
13040ctl_process_done(union ctl_io *io)
13041{
13042	struct ctl_lun *lun;
13043	struct ctl_softc *softc = control_softc;
13044	void (*fe_done)(union ctl_io *io);
13045	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13046
13047	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13048
13049	fe_done = softc->ctl_ports[targ_port]->fe_done;
13050
13051#ifdef CTL_TIME_IO
13052	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13053		char str[256];
13054		char path_str[64];
13055		struct sbuf sb;
13056
13057		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13058		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13059
13060		sbuf_cat(&sb, path_str);
13061		switch (io->io_hdr.io_type) {
13062		case CTL_IO_SCSI:
13063			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13064			sbuf_printf(&sb, "\n");
13065			sbuf_cat(&sb, path_str);
13066			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13067				    io->scsiio.tag_num, io->scsiio.tag_type);
13068			break;
13069		case CTL_IO_TASK:
13070			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13071				    "Tag Type: %d\n", io->taskio.task_action,
13072				    io->taskio.tag_num, io->taskio.tag_type);
13073			break;
13074		default:
13075			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13076			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13077			break;
13078		}
13079		sbuf_cat(&sb, path_str);
13080		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13081			    (intmax_t)time_uptime - io->io_hdr.start_time);
13082		sbuf_finish(&sb);
13083		printf("%s", sbuf_data(&sb));
13084	}
13085#endif /* CTL_TIME_IO */
13086
13087	switch (io->io_hdr.io_type) {
13088	case CTL_IO_SCSI:
13089		break;
13090	case CTL_IO_TASK:
13091		if (ctl_debug & CTL_DEBUG_INFO)
13092			ctl_io_error_print(io, NULL);
13093		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13094			ctl_free_io(io);
13095		else
13096			fe_done(io);
13097		return (CTL_RETVAL_COMPLETE);
13098	default:
13099		panic("ctl_process_done: invalid io type %d\n",
13100		      io->io_hdr.io_type);
13101		break; /* NOTREACHED */
13102	}
13103
13104	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13105	if (lun == NULL) {
13106		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13107				 io->io_hdr.nexus.targ_mapped_lun));
13108		goto bailout;
13109	}
13110
13111	mtx_lock(&lun->lun_lock);
13112
13113	/*
13114	 * Check to see if we have any errors to inject here.  We only
13115	 * inject errors for commands that don't already have errors set.
13116	 */
13117	if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
13118	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13119	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13120		ctl_inject_error(lun, io);
13121
13122	/*
13123	 * XXX KDM how do we treat commands that aren't completed
13124	 * successfully?
13125	 *
13126	 * XXX KDM should we also track I/O latency?
13127	 */
13128	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13129	    io->io_hdr.io_type == CTL_IO_SCSI) {
13130#ifdef CTL_TIME_IO
13131		struct bintime cur_bt;
13132#endif
13133		int type;
13134
13135		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13136		    CTL_FLAG_DATA_IN)
13137			type = CTL_STATS_READ;
13138		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13139		    CTL_FLAG_DATA_OUT)
13140			type = CTL_STATS_WRITE;
13141		else
13142			type = CTL_STATS_NO_IO;
13143
13144		lun->stats.ports[targ_port].bytes[type] +=
13145		    io->scsiio.kern_total_len;
13146		lun->stats.ports[targ_port].operations[type]++;
13147#ifdef CTL_TIME_IO
13148		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13149		   &io->io_hdr.dma_bt);
13150		lun->stats.ports[targ_port].num_dmas[type] +=
13151		    io->io_hdr.num_dmas;
13152		getbintime(&cur_bt);
13153		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13154		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13155#endif
13156	}
13157
13158	/*
13159	 * Remove this from the OOA queue.
13160	 */
13161	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13162#ifdef CTL_TIME_IO
13163	if (TAILQ_EMPTY(&lun->ooa_queue))
13164		lun->last_busy = getsbinuptime();
13165#endif
13166
13167	/*
13168	 * Run through the blocked queue on this LUN and see if anything
13169	 * has become unblocked, now that this transaction is done.
13170	 */
13171	ctl_check_blocked(lun);
13172
13173	/*
13174	 * If the LUN has been invalidated, free it if there is nothing
13175	 * left on its OOA queue.
13176	 */
13177	if ((lun->flags & CTL_LUN_INVALID)
13178	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13179		mtx_unlock(&lun->lun_lock);
13180		mtx_lock(&softc->ctl_lock);
13181		ctl_free_lun(lun);
13182		mtx_unlock(&softc->ctl_lock);
13183	} else
13184		mtx_unlock(&lun->lun_lock);
13185
13186bailout:
13187
13188	/*
13189	 * If this command has been aborted, make sure we set the status
13190	 * properly.  The FETD is responsible for freeing the I/O and doing
13191	 * whatever it needs to do to clean up its state.
13192	 */
13193	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13194		ctl_set_task_aborted(&io->scsiio);
13195
13196	/*
13197	 * If enabled, print command error status.
13198	 */
13199	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13200	    (ctl_debug & CTL_DEBUG_INFO) != 0)
13201		ctl_io_error_print(io, NULL);
13202
13203	/*
13204	 * Tell the FETD or the other shelf controller we're done with this
13205	 * command.  Note that only SCSI commands get to this point.  Task
13206	 * management commands are completed above.
13207	 *
13208	 * We only send status to the other controller if we're in XFER
13209	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13210	 * received the I/O (from CTL's perspective), and so the status is
13211	 * generated there.
13212	 *
13213	 * XXX KDM if we hold the lock here, we could cause a deadlock
13214	 * if the frontend comes back in in this context to queue
13215	 * something.
13216	 */
13217	if ((softc->ha_mode == CTL_HA_MODE_XFER)
13218	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13219		union ctl_ha_msg msg;
13220
13221		memset(&msg, 0, sizeof(msg));
13222		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13223		msg.hdr.original_sc = io->io_hdr.original_sc;
13224		msg.hdr.nexus = io->io_hdr.nexus;
13225		msg.hdr.status = io->io_hdr.status;
13226		msg.scsi.scsi_status = io->scsiio.scsi_status;
13227		msg.scsi.tag_num = io->scsiio.tag_num;
13228		msg.scsi.tag_type = io->scsiio.tag_type;
13229		msg.scsi.sense_len = io->scsiio.sense_len;
13230		msg.scsi.sense_residual = io->scsiio.sense_residual;
13231		msg.scsi.residual = io->scsiio.residual;
13232		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13233		       sizeof(io->scsiio.sense_data));
13234		/*
13235		 * We copy this whether or not this is an I/O-related
13236		 * command.  Otherwise, we'd have to go and check to see
13237		 * whether it's a read/write command, and it really isn't
13238		 * worth it.
13239		 */
13240		memcpy(&msg.scsi.lbalen,
13241		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13242		       sizeof(msg.scsi.lbalen));
13243
13244		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13245				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13246			/* XXX do something here */
13247		}
13248
13249		ctl_free_io(io);
13250	} else
13251		fe_done(io);
13252
13253	return (CTL_RETVAL_COMPLETE);
13254}
13255
13256#ifdef CTL_WITH_CA
13257/*
13258 * Front end should call this if it doesn't do autosense.  When the request
13259 * sense comes back in from the initiator, we'll dequeue this and send it.
13260 */
13261int
13262ctl_queue_sense(union ctl_io *io)
13263{
13264	struct ctl_lun *lun;
13265	struct ctl_port *port;
13266	struct ctl_softc *softc;
13267	uint32_t initidx, targ_lun;
13268
13269	softc = control_softc;
13270
13271	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13272
13273	/*
13274	 * LUN lookup will likely move to the ctl_work_thread() once we
13275	 * have our new queueing infrastructure (that doesn't put things on
13276	 * a per-LUN queue initially).  That is so that we can handle
13277	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13278	 * can't deal with that right now.
13279	 */
13280	mtx_lock(&softc->ctl_lock);
13281
13282	/*
13283	 * If we don't have a LUN for this, just toss the sense
13284	 * information.
13285	 */
13286	port = ctl_io_port(&ctsio->io_hdr);
13287	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13288	if ((targ_lun < CTL_MAX_LUNS)
13289	 && (softc->ctl_luns[targ_lun] != NULL))
13290		lun = softc->ctl_luns[targ_lun];
13291	else
13292		goto bailout;
13293
13294	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13295
13296	mtx_lock(&lun->lun_lock);
13297	/*
13298	 * Already have CA set for this LUN...toss the sense information.
13299	 */
13300	if (ctl_is_set(lun->have_ca, initidx)) {
13301		mtx_unlock(&lun->lun_lock);
13302		goto bailout;
13303	}
13304
13305	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13306	       MIN(sizeof(lun->pending_sense[initidx]),
13307	       sizeof(io->scsiio.sense_data)));
13308	ctl_set_mask(lun->have_ca, initidx);
13309	mtx_unlock(&lun->lun_lock);
13310
13311bailout:
13312	mtx_unlock(&softc->ctl_lock);
13313
13314	ctl_free_io(io);
13315
13316	return (CTL_RETVAL_COMPLETE);
13317}
13318#endif
13319
13320/*
13321 * Primary command inlet from frontend ports.  All SCSI and task I/O
13322 * requests must go through this function.
13323 */
13324int
13325ctl_queue(union ctl_io *io)
13326{
13327	struct ctl_port *port;
13328
13329	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13330
13331#ifdef CTL_TIME_IO
13332	io->io_hdr.start_time = time_uptime;
13333	getbintime(&io->io_hdr.start_bt);
13334#endif /* CTL_TIME_IO */
13335
13336	/* Map FE-specific LUN ID into global one. */
13337	port = ctl_io_port(&io->io_hdr);
13338	io->io_hdr.nexus.targ_mapped_lun =
13339	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13340
13341	switch (io->io_hdr.io_type) {
13342	case CTL_IO_SCSI:
13343	case CTL_IO_TASK:
13344		if (ctl_debug & CTL_DEBUG_CDB)
13345			ctl_io_print(io);
13346		ctl_enqueue_incoming(io);
13347		break;
13348	default:
13349		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13350		return (EINVAL);
13351	}
13352
13353	return (CTL_RETVAL_COMPLETE);
13354}
13355
13356#ifdef CTL_IO_DELAY
13357static void
13358ctl_done_timer_wakeup(void *arg)
13359{
13360	union ctl_io *io;
13361
13362	io = (union ctl_io *)arg;
13363	ctl_done(io);
13364}
13365#endif /* CTL_IO_DELAY */
13366
13367void
13368ctl_done(union ctl_io *io)
13369{
13370
13371	/*
13372	 * Enable this to catch duplicate completion issues.
13373	 */
13374#if 0
13375	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13376		printf("%s: type %d msg %d cdb %x iptl: "
13377		       "%u:%u:%u tag 0x%04x "
13378		       "flag %#x status %x\n",
13379			__func__,
13380			io->io_hdr.io_type,
13381			io->io_hdr.msg_type,
13382			io->scsiio.cdb[0],
13383			io->io_hdr.nexus.initid,
13384			io->io_hdr.nexus.targ_port,
13385			io->io_hdr.nexus.targ_lun,
13386			(io->io_hdr.io_type ==
13387			CTL_IO_TASK) ?
13388			io->taskio.tag_num :
13389			io->scsiio.tag_num,
13390		        io->io_hdr.flags,
13391			io->io_hdr.status);
13392	} else
13393		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13394#endif
13395
13396	/*
13397	 * This is an internal copy of an I/O, and should not go through
13398	 * the normal done processing logic.
13399	 */
13400	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13401		return;
13402
13403	/*
13404	 * We need to send a msg to the serializing shelf to finish the IO
13405	 * as well.  We don't send a finish message to the other shelf if
13406	 * this is a task management command.  Task management commands
13407	 * aren't serialized in the OOA queue, but rather just executed on
13408	 * both shelf controllers for commands that originated on that
13409	 * controller.
13410	 */
13411	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13412	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
13413		union ctl_ha_msg msg_io;
13414
13415		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13416		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13417		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13418		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13419		}
13420		/* continue on to finish IO */
13421	}
13422#ifdef CTL_IO_DELAY
13423	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13424		struct ctl_lun *lun;
13425
13426		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13427
13428		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13429	} else {
13430		struct ctl_lun *lun;
13431
13432		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13433
13434		if ((lun != NULL)
13435		 && (lun->delay_info.done_delay > 0)) {
13436
13437			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13438			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13439			callout_reset(&io->io_hdr.delay_callout,
13440				      lun->delay_info.done_delay * hz,
13441				      ctl_done_timer_wakeup, io);
13442			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13443				lun->delay_info.done_delay = 0;
13444			return;
13445		}
13446	}
13447#endif /* CTL_IO_DELAY */
13448
13449	ctl_enqueue_done(io);
13450}
13451
13452int
13453ctl_isc(struct ctl_scsiio *ctsio)
13454{
13455	struct ctl_lun *lun;
13456	int retval;
13457
13458	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13459
13460	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13461
13462	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13463
13464	retval = lun->backend->data_submit((union ctl_io *)ctsio);
13465
13466	return (retval);
13467}
13468
13469
13470static void
13471ctl_work_thread(void *arg)
13472{
13473	struct ctl_thread *thr = (struct ctl_thread *)arg;
13474	struct ctl_softc *softc = thr->ctl_softc;
13475	union ctl_io *io;
13476	int retval;
13477
13478	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13479
13480	for (;;) {
13481		retval = 0;
13482
13483		/*
13484		 * We handle the queues in this order:
13485		 * - ISC
13486		 * - done queue (to free up resources, unblock other commands)
13487		 * - RtR queue
13488		 * - incoming queue
13489		 *
13490		 * If those queues are empty, we break out of the loop and
13491		 * go to sleep.
13492		 */
13493		mtx_lock(&thr->queue_lock);
13494		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13495		if (io != NULL) {
13496			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13497			mtx_unlock(&thr->queue_lock);
13498			ctl_handle_isc(io);
13499			continue;
13500		}
13501		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13502		if (io != NULL) {
13503			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13504			/* clear any blocked commands, call fe_done */
13505			mtx_unlock(&thr->queue_lock);
13506			retval = ctl_process_done(io);
13507			continue;
13508		}
13509		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13510		if (io != NULL) {
13511			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13512			mtx_unlock(&thr->queue_lock);
13513			if (io->io_hdr.io_type == CTL_IO_TASK)
13514				ctl_run_task(io);
13515			else
13516				ctl_scsiio_precheck(softc, &io->scsiio);
13517			continue;
13518		}
13519		if (!ctl_pause_rtr) {
13520			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13521			if (io != NULL) {
13522				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13523				mtx_unlock(&thr->queue_lock);
13524				retval = ctl_scsiio(&io->scsiio);
13525				if (retval != CTL_RETVAL_COMPLETE)
13526					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13527				continue;
13528			}
13529		}
13530
13531		/* Sleep until we have something to do. */
13532		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13533	}
13534}
13535
13536static void
13537ctl_lun_thread(void *arg)
13538{
13539	struct ctl_softc *softc = (struct ctl_softc *)arg;
13540	struct ctl_be_lun *be_lun;
13541	int retval;
13542
13543	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13544
13545	for (;;) {
13546		retval = 0;
13547		mtx_lock(&softc->ctl_lock);
13548		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13549		if (be_lun != NULL) {
13550			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13551			mtx_unlock(&softc->ctl_lock);
13552			ctl_create_lun(be_lun);
13553			continue;
13554		}
13555
13556		/* Sleep until we have something to do. */
13557		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13558		    PDROP | PRIBIO, "-", 0);
13559	}
13560}
13561
13562static void
13563ctl_thresh_thread(void *arg)
13564{
13565	struct ctl_softc *softc = (struct ctl_softc *)arg;
13566	struct ctl_lun *lun;
13567	struct ctl_be_lun *be_lun;
13568	struct scsi_da_rw_recovery_page *rwpage;
13569	struct ctl_logical_block_provisioning_page *page;
13570	const char *attr;
13571	uint64_t thres, val;
13572	int i, e;
13573
13574	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13575
13576	for (;;) {
13577		mtx_lock(&softc->ctl_lock);
13578		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13579			be_lun = lun->be_lun;
13580			if ((lun->flags & CTL_LUN_DISABLED) ||
13581			    (lun->flags & CTL_LUN_OFFLINE) ||
13582			    lun->backend->lun_attr == NULL)
13583				continue;
13584			rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13585			if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13586				continue;
13587			e = 0;
13588			page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13589			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13590				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13591					continue;
13592				thres = scsi_4btoul(page->descr[i].count);
13593				thres <<= CTL_LBP_EXPONENT;
13594				switch (page->descr[i].resource) {
13595				case 0x01:
13596					attr = "blocksavail";
13597					break;
13598				case 0x02:
13599					attr = "blocksused";
13600					break;
13601				case 0xf1:
13602					attr = "poolblocksavail";
13603					break;
13604				case 0xf2:
13605					attr = "poolblocksused";
13606					break;
13607				default:
13608					continue;
13609				}
13610				mtx_unlock(&softc->ctl_lock); // XXX
13611				val = lun->backend->lun_attr(
13612				    lun->be_lun->be_lun, attr);
13613				mtx_lock(&softc->ctl_lock);
13614				if (val == UINT64_MAX)
13615					continue;
13616				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13617				    == SLBPPD_ARMING_INC)
13618					e |= (val >= thres);
13619				else
13620					e |= (val <= thres);
13621			}
13622			mtx_lock(&lun->lun_lock);
13623			if (e) {
13624				if (lun->lasttpt == 0 ||
13625				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13626					lun->lasttpt = time_uptime;
13627					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13628				}
13629			} else {
13630				lun->lasttpt = 0;
13631				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13632			}
13633			mtx_unlock(&lun->lun_lock);
13634		}
13635		mtx_unlock(&softc->ctl_lock);
13636		pause("-", CTL_LBP_PERIOD * hz);
13637	}
13638}
13639
13640static void
13641ctl_enqueue_incoming(union ctl_io *io)
13642{
13643	struct ctl_softc *softc = control_softc;
13644	struct ctl_thread *thr;
13645	u_int idx;
13646
13647	idx = (io->io_hdr.nexus.targ_port * 127 +
13648	       io->io_hdr.nexus.initid) % worker_threads;
13649	thr = &softc->threads[idx];
13650	mtx_lock(&thr->queue_lock);
13651	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13652	mtx_unlock(&thr->queue_lock);
13653	wakeup(thr);
13654}
13655
13656static void
13657ctl_enqueue_rtr(union ctl_io *io)
13658{
13659	struct ctl_softc *softc = control_softc;
13660	struct ctl_thread *thr;
13661
13662	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13663	mtx_lock(&thr->queue_lock);
13664	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13665	mtx_unlock(&thr->queue_lock);
13666	wakeup(thr);
13667}
13668
13669static void
13670ctl_enqueue_done(union ctl_io *io)
13671{
13672	struct ctl_softc *softc = control_softc;
13673	struct ctl_thread *thr;
13674
13675	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13676	mtx_lock(&thr->queue_lock);
13677	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13678	mtx_unlock(&thr->queue_lock);
13679	wakeup(thr);
13680}
13681
13682#ifdef notyet
13683static void
13684ctl_enqueue_isc(union ctl_io *io)
13685{
13686	struct ctl_softc *softc = control_softc;
13687	struct ctl_thread *thr;
13688
13689	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13690	mtx_lock(&thr->queue_lock);
13691	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13692	mtx_unlock(&thr->queue_lock);
13693	wakeup(thr);
13694}
13695
13696/* Initialization and failover */
13697
13698void
13699ctl_init_isc_msg(void)
13700{
13701	printf("CTL: Still calling this thing\n");
13702}
13703
13704/*
13705 * Init component
13706 * 	Initializes component into configuration defined by bootMode
13707 *	(see hasc-sv.c)
13708 *  	returns hasc_Status:
13709 * 		OK
13710 *		ERROR - fatal error
13711 */
13712static ctl_ha_comp_status
13713ctl_isc_init(struct ctl_ha_component *c)
13714{
13715	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
13716
13717	c->status = ret;
13718	return ret;
13719}
13720
13721/* Start component
13722 * 	Starts component in state requested. If component starts successfully,
13723 *	it must set its own state to the requestrd state
13724 *	When requested state is HASC_STATE_HA, the component may refine it
13725 * 	by adding _SLAVE or _MASTER flags.
13726 *	Currently allowed state transitions are:
13727 *	UNKNOWN->HA		- initial startup
13728 *	UNKNOWN->SINGLE - initial startup when no parter detected
13729 *	HA->SINGLE		- failover
13730 * returns ctl_ha_comp_status:
13731 * 		OK	- component successfully started in requested state
13732 *		FAILED  - could not start the requested state, failover may
13733 * 			  be possible
13734 *		ERROR	- fatal error detected, no future startup possible
13735 */
13736static ctl_ha_comp_status
13737ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
13738{
13739	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
13740
13741	printf("%s: go\n", __func__);
13742
13743	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
13744	if (c->state == CTL_HA_STATE_UNKNOWN ) {
13745		control_softc->is_single = 0;
13746		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
13747		    != CTL_HA_STATUS_SUCCESS) {
13748			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
13749			ret = CTL_HA_COMP_STATUS_ERROR;
13750		}
13751	} else if (CTL_HA_STATE_IS_HA(c->state)
13752		&& CTL_HA_STATE_IS_SINGLE(state)){
13753		// HA->SINGLE transition
13754	        ctl_failover();
13755		control_softc->is_single = 1;
13756	} else {
13757		printf("ctl_isc_start:Invalid state transition %X->%X\n",
13758		       c->state, state);
13759		ret = CTL_HA_COMP_STATUS_ERROR;
13760	}
13761	if (CTL_HA_STATE_IS_SINGLE(state))
13762		control_softc->is_single = 1;
13763
13764	c->state = state;
13765	c->status = ret;
13766	return ret;
13767}
13768
13769/*
13770 * Quiesce component
13771 * The component must clear any error conditions (set status to OK) and
13772 * prepare itself to another Start call
13773 * returns ctl_ha_comp_status:
13774 * 	OK
13775 *	ERROR
13776 */
13777static ctl_ha_comp_status
13778ctl_isc_quiesce(struct ctl_ha_component *c)
13779{
13780	int ret = CTL_HA_COMP_STATUS_OK;
13781
13782	ctl_pause_rtr = 1;
13783	c->status = ret;
13784	return ret;
13785}
13786
13787struct ctl_ha_component ctl_ha_component_ctlisc =
13788{
13789	.name = "CTL ISC",
13790	.state = CTL_HA_STATE_UNKNOWN,
13791	.init = ctl_isc_init,
13792	.start = ctl_isc_start,
13793	.quiesce = ctl_isc_quiesce
13794};
13795#endif
13796
13797/*
13798 *  vim: ts=8
13799 */
13800