ctl.c revision 274732
1/*-
2 * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3 * Copyright (c) 2012 The FreeBSD Foundation
4 * All rights reserved.
5 *
6 * Portions of this software were developed by Edward Tomasz Napierala
7 * under sponsorship from the FreeBSD Foundation.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions, and the following disclaimer,
14 *    without modification.
15 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
16 *    substantially similar to the "NO WARRANTY" disclaimer below
17 *    ("Disclaimer") and any redistribution must be conditioned upon
18 *    including a substantially similar Disclaimer requirement for further
19 *    binary redistribution.
20 *
21 * NO WARRANTY
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
25 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
31 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGES.
33 *
34 * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/ctl.c#8 $
35 */
36/*
37 * CAM Target Layer, a SCSI device emulation subsystem.
38 *
39 * Author: Ken Merry <ken@FreeBSD.org>
40 */
41
42#define _CTL_C
43
44#include <sys/cdefs.h>
45__FBSDID("$FreeBSD: stable/10/sys/cam/ctl/ctl.c 274732 2014-11-20 01:55:12Z 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
68#include <cam/cam.h>
69#include <cam/scsi/scsi_all.h>
70#include <cam/scsi/scsi_da.h>
71#include <cam/ctl/ctl_io.h>
72#include <cam/ctl/ctl.h>
73#include <cam/ctl/ctl_frontend.h>
74#include <cam/ctl/ctl_frontend_internal.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 */
113static 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
123static 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
132static 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
146static 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
160static 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
177static 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
193static 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
210static 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
226static 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
242static 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
258static 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
270static 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
282static 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
291static 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
302static 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
328static 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 int persis_offset;
359static uint8_t ctl_pause_rtr;
360static int     ctl_is_single = 1;
361
362SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
363static int worker_threads = -1;
364TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
365SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
366    &worker_threads, 1, "Number of worker threads");
367static int ctl_debug = CTL_DEBUG_NONE;
368TUNABLE_INT("kern.cam.ctl.debug", &ctl_debug);
369SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
370    &ctl_debug, 0, "Enabled debug flags");
371
372/*
373 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
374 * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
375 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
376 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
377 */
378#define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
379
380static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
381				  int param);
382static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
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 void ctl_ioctl_online(void *arg);
388static void ctl_ioctl_offline(void *arg);
389static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
390static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
391static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
392static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
393static int ctl_ioctl_submit_wait(union ctl_io *io);
394static void ctl_ioctl_datamove(union ctl_io *io);
395static void ctl_ioctl_done(union ctl_io *io);
396static void ctl_ioctl_hard_startstop_callback(void *arg,
397					      struct cfi_metatask *metatask);
398static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
399static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
400			      struct ctl_ooa *ooa_hdr,
401			      struct ctl_ooa_entry *kern_entries);
402static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
403		     struct thread *td);
404static uint32_t ctl_map_lun(int port_num, uint32_t lun);
405static uint32_t ctl_map_lun_back(int port_num, uint32_t lun);
406#ifdef unused
407static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
408				   uint32_t targ_target, uint32_t targ_lun,
409				   int can_wait);
410static void ctl_kfree_io(union ctl_io *io);
411#endif /* unused */
412static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
413			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
414static int ctl_free_lun(struct ctl_lun *lun);
415static void ctl_create_lun(struct ctl_be_lun *be_lun);
416/**
417static void ctl_failover_change_pages(struct ctl_softc *softc,
418				      struct ctl_scsiio *ctsio, int master);
419**/
420
421static int ctl_do_mode_select(union ctl_io *io);
422static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
423			   uint64_t res_key, uint64_t sa_res_key,
424			   uint8_t type, uint32_t residx,
425			   struct ctl_scsiio *ctsio,
426			   struct scsi_per_res_out *cdb,
427			   struct scsi_per_res_out_parms* param);
428static void ctl_pro_preempt_other(struct ctl_lun *lun,
429				  union ctl_ha_msg *msg);
430static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
431static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
432static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
433static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
434static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
435static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
436static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
437					 int alloc_len);
438static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
439					 int alloc_len);
440static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
441static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
442static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
443static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
444static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
445static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
446static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
447    union ctl_io *pending_io, union ctl_io *ooa_io);
448static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
449				union ctl_io *starting_io);
450static int ctl_check_blocked(struct ctl_lun *lun);
451static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
452				struct ctl_lun *lun,
453				const struct ctl_cmd_entry *entry,
454				struct ctl_scsiio *ctsio);
455//static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
456static void ctl_failover(void);
457static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
458			       struct ctl_scsiio *ctsio);
459static int ctl_scsiio(struct ctl_scsiio *ctsio);
460
461static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
462static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
463			    ctl_ua_type ua_type);
464static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
465			 ctl_ua_type ua_type);
466static int ctl_abort_task(union ctl_io *io);
467static int ctl_abort_task_set(union ctl_io *io);
468static int ctl_i_t_nexus_reset(union ctl_io *io);
469static void ctl_run_task(union ctl_io *io);
470#ifdef CTL_IO_DELAY
471static void ctl_datamove_timer_wakeup(void *arg);
472static void ctl_done_timer_wakeup(void *arg);
473#endif /* CTL_IO_DELAY */
474
475static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
476static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
477static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
478static void ctl_datamove_remote_write(union ctl_io *io);
479static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
480static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
481static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
482static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
483				    ctl_ha_dt_cb callback);
484static void ctl_datamove_remote_read(union ctl_io *io);
485static void ctl_datamove_remote(union ctl_io *io);
486static int ctl_process_done(union ctl_io *io);
487static void ctl_lun_thread(void *arg);
488static void ctl_thresh_thread(void *arg);
489static void ctl_work_thread(void *arg);
490static void ctl_enqueue_incoming(union ctl_io *io);
491static void ctl_enqueue_rtr(union ctl_io *io);
492static void ctl_enqueue_done(union ctl_io *io);
493static void ctl_enqueue_isc(union ctl_io *io);
494static const struct ctl_cmd_entry *
495    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
496static const struct ctl_cmd_entry *
497    ctl_validate_command(struct ctl_scsiio *ctsio);
498static int ctl_cmd_applicable(uint8_t lun_type,
499    const struct ctl_cmd_entry *entry);
500
501/*
502 * Load the serialization table.  This isn't very pretty, but is probably
503 * the easiest way to do it.
504 */
505#include "ctl_ser_table.c"
506
507/*
508 * We only need to define open, close and ioctl routines for this driver.
509 */
510static struct cdevsw ctl_cdevsw = {
511	.d_version =	D_VERSION,
512	.d_flags =	0,
513	.d_open =	ctl_open,
514	.d_close =	ctl_close,
515	.d_ioctl =	ctl_ioctl,
516	.d_name =	"ctl",
517};
518
519
520MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
521MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
522
523static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
524
525static moduledata_t ctl_moduledata = {
526	"ctl",
527	ctl_module_event_handler,
528	NULL
529};
530
531DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
532MODULE_VERSION(ctl, 1);
533
534static struct ctl_frontend ioctl_frontend =
535{
536	.name = "ioctl",
537};
538
539static void
540ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
541			    union ctl_ha_msg *msg_info)
542{
543	struct ctl_scsiio *ctsio;
544
545	if (msg_info->hdr.original_sc == NULL) {
546		printf("%s: original_sc == NULL!\n", __func__);
547		/* XXX KDM now what? */
548		return;
549	}
550
551	ctsio = &msg_info->hdr.original_sc->scsiio;
552	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
553	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
554	ctsio->io_hdr.status = msg_info->hdr.status;
555	ctsio->scsi_status = msg_info->scsi.scsi_status;
556	ctsio->sense_len = msg_info->scsi.sense_len;
557	ctsio->sense_residual = msg_info->scsi.sense_residual;
558	ctsio->residual = msg_info->scsi.residual;
559	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
560	       sizeof(ctsio->sense_data));
561	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
562	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
563	ctl_enqueue_isc((union ctl_io *)ctsio);
564}
565
566static void
567ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
568				union ctl_ha_msg *msg_info)
569{
570	struct ctl_scsiio *ctsio;
571
572	if (msg_info->hdr.serializing_sc == NULL) {
573		printf("%s: serializing_sc == NULL!\n", __func__);
574		/* XXX KDM now what? */
575		return;
576	}
577
578	ctsio = &msg_info->hdr.serializing_sc->scsiio;
579#if 0
580	/*
581	 * Attempt to catch the situation where an I/O has
582	 * been freed, and we're using it again.
583	 */
584	if (ctsio->io_hdr.io_type == 0xff) {
585		union ctl_io *tmp_io;
586		tmp_io = (union ctl_io *)ctsio;
587		printf("%s: %p use after free!\n", __func__,
588		       ctsio);
589		printf("%s: type %d msg %d cdb %x iptl: "
590		       "%d:%d:%d:%d tag 0x%04x "
591		       "flag %#x status %x\n",
592			__func__,
593			tmp_io->io_hdr.io_type,
594			tmp_io->io_hdr.msg_type,
595			tmp_io->scsiio.cdb[0],
596			tmp_io->io_hdr.nexus.initid.id,
597			tmp_io->io_hdr.nexus.targ_port,
598			tmp_io->io_hdr.nexus.targ_target.id,
599			tmp_io->io_hdr.nexus.targ_lun,
600			(tmp_io->io_hdr.io_type ==
601			CTL_IO_TASK) ?
602			tmp_io->taskio.tag_num :
603			tmp_io->scsiio.tag_num,
604		        tmp_io->io_hdr.flags,
605			tmp_io->io_hdr.status);
606	}
607#endif
608	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
609	ctl_enqueue_isc((union ctl_io *)ctsio);
610}
611
612/*
613 * ISC (Inter Shelf Communication) event handler.  Events from the HA
614 * subsystem come in here.
615 */
616static void
617ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
618{
619	struct ctl_softc *ctl_softc;
620	union ctl_io *io;
621	struct ctl_prio *presio;
622	ctl_ha_status isc_status;
623
624	ctl_softc = control_softc;
625	io = NULL;
626
627
628#if 0
629	printf("CTL: Isc Msg event %d\n", event);
630#endif
631	if (event == CTL_HA_EVT_MSG_RECV) {
632		union ctl_ha_msg msg_info;
633
634		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
635					     sizeof(msg_info), /*wait*/ 0);
636#if 0
637		printf("CTL: msg_type %d\n", msg_info.msg_type);
638#endif
639		if (isc_status != 0) {
640			printf("Error receiving message, status = %d\n",
641			       isc_status);
642			return;
643		}
644
645		switch (msg_info.hdr.msg_type) {
646		case CTL_MSG_SERIALIZE:
647#if 0
648			printf("Serialize\n");
649#endif
650			io = ctl_alloc_io((void *)ctl_softc->othersc_pool);
651			if (io == NULL) {
652				printf("ctl_isc_event_handler: can't allocate "
653				       "ctl_io!\n");
654				/* Bad Juju */
655				/* Need to set busy and send msg back */
656				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
657				msg_info.hdr.status = CTL_SCSI_ERROR;
658				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
659				msg_info.scsi.sense_len = 0;
660			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
661				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
662				}
663				goto bailout;
664			}
665			ctl_zero_io(io);
666			// populate ctsio from msg_info
667			io->io_hdr.io_type = CTL_IO_SCSI;
668			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
669			io->io_hdr.original_sc = msg_info.hdr.original_sc;
670#if 0
671			printf("pOrig %x\n", (int)msg_info.original_sc);
672#endif
673			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
674					    CTL_FLAG_IO_ACTIVE;
675			/*
676			 * If we're in serialization-only mode, we don't
677			 * want to go through full done processing.  Thus
678			 * the COPY flag.
679			 *
680			 * XXX KDM add another flag that is more specific.
681			 */
682			if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
683				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
684			io->io_hdr.nexus = msg_info.hdr.nexus;
685#if 0
686			printf("targ %d, port %d, iid %d, lun %d\n",
687			       io->io_hdr.nexus.targ_target.id,
688			       io->io_hdr.nexus.targ_port,
689			       io->io_hdr.nexus.initid.id,
690			       io->io_hdr.nexus.targ_lun);
691#endif
692			io->scsiio.tag_num = msg_info.scsi.tag_num;
693			io->scsiio.tag_type = msg_info.scsi.tag_type;
694			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
695			       CTL_MAX_CDBLEN);
696			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
697				const struct ctl_cmd_entry *entry;
698
699				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
700				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
701				io->io_hdr.flags |=
702					entry->flags & CTL_FLAG_DATA_MASK;
703			}
704			ctl_enqueue_isc(io);
705			break;
706
707		/* Performed on the Originating SC, XFER mode only */
708		case CTL_MSG_DATAMOVE: {
709			struct ctl_sg_entry *sgl;
710			int i, j;
711
712			io = msg_info.hdr.original_sc;
713			if (io == NULL) {
714				printf("%s: original_sc == NULL!\n", __func__);
715				/* XXX KDM do something here */
716				break;
717			}
718			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
719			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
720			/*
721			 * Keep track of this, we need to send it back over
722			 * when the datamove is complete.
723			 */
724			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
725
726			if (msg_info.dt.sg_sequence == 0) {
727				/*
728				 * XXX KDM we use the preallocated S/G list
729				 * here, but we'll need to change this to
730				 * dynamic allocation if we need larger S/G
731				 * lists.
732				 */
733				if (msg_info.dt.kern_sg_entries >
734				    sizeof(io->io_hdr.remote_sglist) /
735				    sizeof(io->io_hdr.remote_sglist[0])) {
736					printf("%s: number of S/G entries "
737					    "needed %u > allocated num %zd\n",
738					    __func__,
739					    msg_info.dt.kern_sg_entries,
740					    sizeof(io->io_hdr.remote_sglist)/
741					    sizeof(io->io_hdr.remote_sglist[0]));
742
743					/*
744					 * XXX KDM send a message back to
745					 * the other side to shut down the
746					 * DMA.  The error will come back
747					 * through via the normal channel.
748					 */
749					break;
750				}
751				sgl = io->io_hdr.remote_sglist;
752				memset(sgl, 0,
753				       sizeof(io->io_hdr.remote_sglist));
754
755				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
756
757				io->scsiio.kern_sg_entries =
758					msg_info.dt.kern_sg_entries;
759				io->scsiio.rem_sg_entries =
760					msg_info.dt.kern_sg_entries;
761				io->scsiio.kern_data_len =
762					msg_info.dt.kern_data_len;
763				io->scsiio.kern_total_len =
764					msg_info.dt.kern_total_len;
765				io->scsiio.kern_data_resid =
766					msg_info.dt.kern_data_resid;
767				io->scsiio.kern_rel_offset =
768					msg_info.dt.kern_rel_offset;
769				/*
770				 * Clear out per-DMA flags.
771				 */
772				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
773				/*
774				 * Add per-DMA flags that are set for this
775				 * particular DMA request.
776				 */
777				io->io_hdr.flags |= msg_info.dt.flags &
778						    CTL_FLAG_RDMA_MASK;
779			} else
780				sgl = (struct ctl_sg_entry *)
781					io->scsiio.kern_data_ptr;
782
783			for (i = msg_info.dt.sent_sg_entries, j = 0;
784			     i < (msg_info.dt.sent_sg_entries +
785			     msg_info.dt.cur_sg_entries); i++, j++) {
786				sgl[i].addr = msg_info.dt.sg_list[j].addr;
787				sgl[i].len = msg_info.dt.sg_list[j].len;
788
789#if 0
790				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
791				       __func__,
792				       msg_info.dt.sg_list[j].addr,
793				       msg_info.dt.sg_list[j].len,
794				       sgl[i].addr, sgl[i].len, j, i);
795#endif
796			}
797#if 0
798			memcpy(&sgl[msg_info.dt.sent_sg_entries],
799			       msg_info.dt.sg_list,
800			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
801#endif
802
803			/*
804			 * If this is the last piece of the I/O, we've got
805			 * the full S/G list.  Queue processing in the thread.
806			 * Otherwise wait for the next piece.
807			 */
808			if (msg_info.dt.sg_last != 0)
809				ctl_enqueue_isc(io);
810			break;
811		}
812		/* Performed on the Serializing (primary) SC, XFER mode only */
813		case CTL_MSG_DATAMOVE_DONE: {
814			if (msg_info.hdr.serializing_sc == NULL) {
815				printf("%s: serializing_sc == NULL!\n",
816				       __func__);
817				/* XXX KDM now what? */
818				break;
819			}
820			/*
821			 * We grab the sense information here in case
822			 * there was a failure, so we can return status
823			 * back to the initiator.
824			 */
825			io = msg_info.hdr.serializing_sc;
826			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
827			io->io_hdr.status = msg_info.hdr.status;
828			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
829			io->scsiio.sense_len = msg_info.scsi.sense_len;
830			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
831			io->io_hdr.port_status = msg_info.scsi.fetd_status;
832			io->scsiio.residual = msg_info.scsi.residual;
833			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
834			       sizeof(io->scsiio.sense_data));
835			ctl_enqueue_isc(io);
836			break;
837		}
838
839		/* Preformed on Originating SC, SER_ONLY mode */
840		case CTL_MSG_R2R:
841			io = msg_info.hdr.original_sc;
842			if (io == NULL) {
843				printf("%s: Major Bummer\n", __func__);
844				return;
845			} else {
846#if 0
847				printf("pOrig %x\n",(int) ctsio);
848#endif
849			}
850			io->io_hdr.msg_type = CTL_MSG_R2R;
851			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
852			ctl_enqueue_isc(io);
853			break;
854
855		/*
856		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
857		 * mode.
858		 * Performed on the Originating (i.e. secondary) SC in XFER
859		 * mode
860		 */
861		case CTL_MSG_FINISH_IO:
862			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
863				ctl_isc_handler_finish_xfer(ctl_softc,
864							    &msg_info);
865			else
866				ctl_isc_handler_finish_ser_only(ctl_softc,
867								&msg_info);
868			break;
869
870		/* Preformed on Originating SC */
871		case CTL_MSG_BAD_JUJU:
872			io = msg_info.hdr.original_sc;
873			if (io == NULL) {
874				printf("%s: Bad JUJU!, original_sc is NULL!\n",
875				       __func__);
876				break;
877			}
878			ctl_copy_sense_data(&msg_info, io);
879			/*
880			 * IO should have already been cleaned up on other
881			 * SC so clear this flag so we won't send a message
882			 * back to finish the IO there.
883			 */
884			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
885			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
886
887			/* io = msg_info.hdr.serializing_sc; */
888			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
889			ctl_enqueue_isc(io);
890			break;
891
892		/* Handle resets sent from the other side */
893		case CTL_MSG_MANAGE_TASKS: {
894			struct ctl_taskio *taskio;
895			taskio = (struct ctl_taskio *)ctl_alloc_io(
896				(void *)ctl_softc->othersc_pool);
897			if (taskio == NULL) {
898				printf("ctl_isc_event_handler: can't allocate "
899				       "ctl_io!\n");
900				/* Bad Juju */
901				/* should I just call the proper reset func
902				   here??? */
903				goto bailout;
904			}
905			ctl_zero_io((union ctl_io *)taskio);
906			taskio->io_hdr.io_type = CTL_IO_TASK;
907			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
908			taskio->io_hdr.nexus = msg_info.hdr.nexus;
909			taskio->task_action = msg_info.task.task_action;
910			taskio->tag_num = msg_info.task.tag_num;
911			taskio->tag_type = msg_info.task.tag_type;
912#ifdef CTL_TIME_IO
913			taskio->io_hdr.start_time = time_uptime;
914			getbintime(&taskio->io_hdr.start_bt);
915#if 0
916			cs_prof_gettime(&taskio->io_hdr.start_ticks);
917#endif
918#endif /* CTL_TIME_IO */
919			ctl_run_task((union ctl_io *)taskio);
920			break;
921		}
922		/* Persistent Reserve action which needs attention */
923		case CTL_MSG_PERS_ACTION:
924			presio = (struct ctl_prio *)ctl_alloc_io(
925				(void *)ctl_softc->othersc_pool);
926			if (presio == NULL) {
927				printf("ctl_isc_event_handler: can't allocate "
928				       "ctl_io!\n");
929				/* Bad Juju */
930				/* Need to set busy and send msg back */
931				goto bailout;
932			}
933			ctl_zero_io((union ctl_io *)presio);
934			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
935			presio->pr_msg = msg_info.pr;
936			ctl_enqueue_isc((union ctl_io *)presio);
937			break;
938		case CTL_MSG_SYNC_FE:
939			rcv_sync_msg = 1;
940			break;
941		default:
942		        printf("How did I get here?\n");
943		}
944	} else if (event == CTL_HA_EVT_MSG_SENT) {
945		if (param != CTL_HA_STATUS_SUCCESS) {
946			printf("Bad status from ctl_ha_msg_send status %d\n",
947			       param);
948		}
949		return;
950	} else if (event == CTL_HA_EVT_DISCONNECT) {
951		printf("CTL: Got a disconnect from Isc\n");
952		return;
953	} else {
954		printf("ctl_isc_event_handler: Unknown event %d\n", event);
955		return;
956	}
957
958bailout:
959	return;
960}
961
962static void
963ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
964{
965	struct scsi_sense_data *sense;
966
967	sense = &dest->scsiio.sense_data;
968	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
969	dest->scsiio.scsi_status = src->scsi.scsi_status;
970	dest->scsiio.sense_len = src->scsi.sense_len;
971	dest->io_hdr.status = src->hdr.status;
972}
973
974static int
975ctl_init(void)
976{
977	struct ctl_softc *softc;
978	struct ctl_io_pool *internal_pool, *emergency_pool, *other_pool;
979	struct ctl_port *port;
980        uint8_t sc_id =0;
981	int i, error, retval;
982	//int isc_retval;
983
984	retval = 0;
985	ctl_pause_rtr = 0;
986        rcv_sync_msg = 0;
987
988	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
989			       M_WAITOK | M_ZERO);
990	softc = control_softc;
991
992	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
993			      "cam/ctl");
994
995	softc->dev->si_drv1 = softc;
996
997	/*
998	 * By default, return a "bad LUN" peripheral qualifier for unknown
999	 * LUNs.  The user can override this default using the tunable or
1000	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
1001	 */
1002	softc->inquiry_pq_no_lun = 1;
1003	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
1004			  &softc->inquiry_pq_no_lun);
1005	sysctl_ctx_init(&softc->sysctl_ctx);
1006	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1007		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1008		CTLFLAG_RD, 0, "CAM Target Layer");
1009
1010	if (softc->sysctl_tree == NULL) {
1011		printf("%s: unable to allocate sysctl tree\n", __func__);
1012		destroy_dev(softc->dev);
1013		free(control_softc, M_DEVBUF);
1014		control_softc = NULL;
1015		return (ENOMEM);
1016	}
1017
1018	SYSCTL_ADD_INT(&softc->sysctl_ctx,
1019		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1020		       "inquiry_pq_no_lun", CTLFLAG_RW,
1021		       &softc->inquiry_pq_no_lun, 0,
1022		       "Report no lun possible for invalid LUNs");
1023
1024	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1025	mtx_init(&softc->pool_lock, "CTL pool mutex", NULL, MTX_DEF);
1026	softc->open_count = 0;
1027
1028	/*
1029	 * Default to actually sending a SYNCHRONIZE CACHE command down to
1030	 * the drive.
1031	 */
1032	softc->flags = CTL_FLAG_REAL_SYNC;
1033
1034	/*
1035	 * In Copan's HA scheme, the "master" and "slave" roles are
1036	 * figured out through the slot the controller is in.  Although it
1037	 * is an active/active system, someone has to be in charge.
1038 	 */
1039#ifdef NEEDTOPORT
1040        scmicro_rw(SCMICRO_GET_SHELF_ID, &sc_id);
1041#endif
1042
1043        if (sc_id == 0) {
1044		softc->flags |= CTL_FLAG_MASTER_SHELF;
1045		persis_offset = 0;
1046	} else
1047		persis_offset = CTL_MAX_INITIATORS;
1048
1049	/*
1050	 * XXX KDM need to figure out where we want to get our target ID
1051	 * and WWID.  Is it different on each port?
1052	 */
1053	softc->target.id = 0;
1054	softc->target.wwid[0] = 0x12345678;
1055	softc->target.wwid[1] = 0x87654321;
1056	STAILQ_INIT(&softc->lun_list);
1057	STAILQ_INIT(&softc->pending_lun_queue);
1058	STAILQ_INIT(&softc->fe_list);
1059	STAILQ_INIT(&softc->port_list);
1060	STAILQ_INIT(&softc->be_list);
1061	STAILQ_INIT(&softc->io_pools);
1062	ctl_tpc_init(softc);
1063
1064	if (ctl_pool_create(softc, CTL_POOL_INTERNAL, CTL_POOL_ENTRIES_INTERNAL,
1065			    &internal_pool)!= 0){
1066		printf("ctl: can't allocate %d entry internal pool, "
1067		       "exiting\n", CTL_POOL_ENTRIES_INTERNAL);
1068		return (ENOMEM);
1069	}
1070
1071	if (ctl_pool_create(softc, CTL_POOL_EMERGENCY,
1072			    CTL_POOL_ENTRIES_EMERGENCY, &emergency_pool) != 0) {
1073		printf("ctl: can't allocate %d entry emergency pool, "
1074		       "exiting\n", CTL_POOL_ENTRIES_EMERGENCY);
1075		ctl_pool_free(internal_pool);
1076		return (ENOMEM);
1077	}
1078
1079	if (ctl_pool_create(softc, CTL_POOL_4OTHERSC, CTL_POOL_ENTRIES_OTHER_SC,
1080	                    &other_pool) != 0)
1081	{
1082		printf("ctl: can't allocate %d entry other SC pool, "
1083		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1084		ctl_pool_free(internal_pool);
1085		ctl_pool_free(emergency_pool);
1086		return (ENOMEM);
1087	}
1088
1089	softc->internal_pool = internal_pool;
1090	softc->emergency_pool = emergency_pool;
1091	softc->othersc_pool = other_pool;
1092
1093	if (worker_threads <= 0)
1094		worker_threads = max(1, mp_ncpus / 4);
1095	if (worker_threads > CTL_MAX_THREADS)
1096		worker_threads = CTL_MAX_THREADS;
1097
1098	for (i = 0; i < worker_threads; i++) {
1099		struct ctl_thread *thr = &softc->threads[i];
1100
1101		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1102		thr->ctl_softc = softc;
1103		STAILQ_INIT(&thr->incoming_queue);
1104		STAILQ_INIT(&thr->rtr_queue);
1105		STAILQ_INIT(&thr->done_queue);
1106		STAILQ_INIT(&thr->isc_queue);
1107
1108		error = kproc_kthread_add(ctl_work_thread, thr,
1109		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1110		if (error != 0) {
1111			printf("error creating CTL work thread!\n");
1112			ctl_pool_free(internal_pool);
1113			ctl_pool_free(emergency_pool);
1114			ctl_pool_free(other_pool);
1115			return (error);
1116		}
1117	}
1118	error = kproc_kthread_add(ctl_lun_thread, softc,
1119	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1120	if (error != 0) {
1121		printf("error creating CTL lun thread!\n");
1122		ctl_pool_free(internal_pool);
1123		ctl_pool_free(emergency_pool);
1124		ctl_pool_free(other_pool);
1125		return (error);
1126	}
1127	error = kproc_kthread_add(ctl_thresh_thread, softc,
1128	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1129	if (error != 0) {
1130		printf("error creating CTL threshold thread!\n");
1131		ctl_pool_free(internal_pool);
1132		ctl_pool_free(emergency_pool);
1133		ctl_pool_free(other_pool);
1134		return (error);
1135	}
1136	if (bootverbose)
1137		printf("ctl: CAM Target Layer loaded\n");
1138
1139	/*
1140	 * Initialize the ioctl front end.
1141	 */
1142	ctl_frontend_register(&ioctl_frontend);
1143	port = &softc->ioctl_info.port;
1144	port->frontend = &ioctl_frontend;
1145	sprintf(softc->ioctl_info.port_name, "ioctl");
1146	port->port_type = CTL_PORT_IOCTL;
1147	port->num_requested_ctl_io = 100;
1148	port->port_name = softc->ioctl_info.port_name;
1149	port->port_online = ctl_ioctl_online;
1150	port->port_offline = ctl_ioctl_offline;
1151	port->onoff_arg = &softc->ioctl_info;
1152	port->lun_enable = ctl_ioctl_lun_enable;
1153	port->lun_disable = ctl_ioctl_lun_disable;
1154	port->targ_lun_arg = &softc->ioctl_info;
1155	port->fe_datamove = ctl_ioctl_datamove;
1156	port->fe_done = ctl_ioctl_done;
1157	port->max_targets = 15;
1158	port->max_target_id = 15;
1159
1160	if (ctl_port_register(&softc->ioctl_info.port,
1161	                  (softc->flags & CTL_FLAG_MASTER_SHELF)) != 0) {
1162		printf("ctl: ioctl front end registration failed, will "
1163		       "continue anyway\n");
1164	}
1165
1166#ifdef CTL_IO_DELAY
1167	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1168		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1169		       sizeof(struct callout), CTL_TIMER_BYTES);
1170		return (EINVAL);
1171	}
1172#endif /* CTL_IO_DELAY */
1173
1174	return (0);
1175}
1176
1177void
1178ctl_shutdown(void)
1179{
1180	struct ctl_softc *softc;
1181	struct ctl_lun *lun, *next_lun;
1182	struct ctl_io_pool *pool;
1183
1184	softc = (struct ctl_softc *)control_softc;
1185
1186	if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1187		printf("ctl: ioctl front end deregistration failed\n");
1188
1189	mtx_lock(&softc->ctl_lock);
1190
1191	/*
1192	 * Free up each LUN.
1193	 */
1194	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1195		next_lun = STAILQ_NEXT(lun, links);
1196		ctl_free_lun(lun);
1197	}
1198
1199	mtx_unlock(&softc->ctl_lock);
1200
1201	ctl_frontend_deregister(&ioctl_frontend);
1202
1203	/*
1204	 * This will rip the rug out from under any FETDs or anyone else
1205	 * that has a pool allocated.  Since we increment our module
1206	 * refcount any time someone outside the main CTL module allocates
1207	 * a pool, we shouldn't have any problems here.  The user won't be
1208	 * able to unload the CTL module until client modules have
1209	 * successfully unloaded.
1210	 */
1211	while ((pool = STAILQ_FIRST(&softc->io_pools)) != NULL)
1212		ctl_pool_free(pool);
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	mtx_destroy(&softc->pool_lock);
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	if (bootverbose)
1231		printf("ctl: CAM Target Layer unloaded\n");
1232}
1233
1234static int
1235ctl_module_event_handler(module_t mod, int what, void *arg)
1236{
1237
1238	switch (what) {
1239	case MOD_LOAD:
1240		return (ctl_init());
1241	case MOD_UNLOAD:
1242		return (EBUSY);
1243	default:
1244		return (EOPNOTSUPP);
1245	}
1246}
1247
1248/*
1249 * XXX KDM should we do some access checks here?  Bump a reference count to
1250 * prevent a CTL module from being unloaded while someone has it open?
1251 */
1252static int
1253ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1254{
1255	return (0);
1256}
1257
1258static int
1259ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1260{
1261	return (0);
1262}
1263
1264int
1265ctl_port_enable(ctl_port_type port_type)
1266{
1267	struct ctl_softc *softc;
1268	struct ctl_port *port;
1269
1270	if (ctl_is_single == 0) {
1271		union ctl_ha_msg msg_info;
1272		int isc_retval;
1273
1274#if 0
1275		printf("%s: HA mode, synchronizing frontend enable\n",
1276		        __func__);
1277#endif
1278		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1279	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1280		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1281			printf("Sync msg send error retval %d\n", isc_retval);
1282		}
1283		if (!rcv_sync_msg) {
1284			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1285			        sizeof(msg_info), 1);
1286		}
1287#if 0
1288        	printf("CTL:Frontend Enable\n");
1289	} else {
1290		printf("%s: single mode, skipping frontend synchronization\n",
1291		        __func__);
1292#endif
1293	}
1294
1295	softc = control_softc;
1296
1297	STAILQ_FOREACH(port, &softc->port_list, links) {
1298		if (port_type & port->port_type)
1299		{
1300#if 0
1301			printf("port %d\n", port->targ_port);
1302#endif
1303			ctl_port_online(port);
1304		}
1305	}
1306
1307	return (0);
1308}
1309
1310int
1311ctl_port_disable(ctl_port_type port_type)
1312{
1313	struct ctl_softc *softc;
1314	struct ctl_port *port;
1315
1316	softc = control_softc;
1317
1318	STAILQ_FOREACH(port, &softc->port_list, links) {
1319		if (port_type & port->port_type)
1320			ctl_port_offline(port);
1321	}
1322
1323	return (0);
1324}
1325
1326/*
1327 * Returns 0 for success, 1 for failure.
1328 * Currently the only failure mode is if there aren't enough entries
1329 * allocated.  So, in case of a failure, look at num_entries_dropped,
1330 * reallocate and try again.
1331 */
1332int
1333ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1334	      int *num_entries_filled, int *num_entries_dropped,
1335	      ctl_port_type port_type, int no_virtual)
1336{
1337	struct ctl_softc *softc;
1338	struct ctl_port *port;
1339	int entries_dropped, entries_filled;
1340	int retval;
1341	int i;
1342
1343	softc = control_softc;
1344
1345	retval = 0;
1346	entries_filled = 0;
1347	entries_dropped = 0;
1348
1349	i = 0;
1350	mtx_lock(&softc->ctl_lock);
1351	STAILQ_FOREACH(port, &softc->port_list, links) {
1352		struct ctl_port_entry *entry;
1353
1354		if ((port->port_type & port_type) == 0)
1355			continue;
1356
1357		if ((no_virtual != 0)
1358		 && (port->virtual_port != 0))
1359			continue;
1360
1361		if (entries_filled >= num_entries_alloced) {
1362			entries_dropped++;
1363			continue;
1364		}
1365		entry = &entries[i];
1366
1367		entry->port_type = port->port_type;
1368		strlcpy(entry->port_name, port->port_name,
1369			sizeof(entry->port_name));
1370		entry->physical_port = port->physical_port;
1371		entry->virtual_port = port->virtual_port;
1372		entry->wwnn = port->wwnn;
1373		entry->wwpn = port->wwpn;
1374
1375		i++;
1376		entries_filled++;
1377	}
1378
1379	mtx_unlock(&softc->ctl_lock);
1380
1381	if (entries_dropped > 0)
1382		retval = 1;
1383
1384	*num_entries_dropped = entries_dropped;
1385	*num_entries_filled = entries_filled;
1386
1387	return (retval);
1388}
1389
1390static void
1391ctl_ioctl_online(void *arg)
1392{
1393	struct ctl_ioctl_info *ioctl_info;
1394
1395	ioctl_info = (struct ctl_ioctl_info *)arg;
1396
1397	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1398}
1399
1400static void
1401ctl_ioctl_offline(void *arg)
1402{
1403	struct ctl_ioctl_info *ioctl_info;
1404
1405	ioctl_info = (struct ctl_ioctl_info *)arg;
1406
1407	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1408}
1409
1410/*
1411 * Remove an initiator by port number and initiator ID.
1412 * Returns 0 for success, -1 for failure.
1413 */
1414int
1415ctl_remove_initiator(struct ctl_port *port, int iid)
1416{
1417	struct ctl_softc *softc = control_softc;
1418
1419	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1420
1421	if (iid > CTL_MAX_INIT_PER_PORT) {
1422		printf("%s: initiator ID %u > maximun %u!\n",
1423		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1424		return (-1);
1425	}
1426
1427	mtx_lock(&softc->ctl_lock);
1428	port->wwpn_iid[iid].in_use--;
1429	port->wwpn_iid[iid].last_use = time_uptime;
1430	mtx_unlock(&softc->ctl_lock);
1431
1432	return (0);
1433}
1434
1435/*
1436 * Add an initiator to the initiator map.
1437 * Returns iid for success, < 0 for failure.
1438 */
1439int
1440ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1441{
1442	struct ctl_softc *softc = control_softc;
1443	time_t best_time;
1444	int i, best;
1445
1446	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1447
1448	if (iid >= CTL_MAX_INIT_PER_PORT) {
1449		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1450		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1451		free(name, M_CTL);
1452		return (-1);
1453	}
1454
1455	mtx_lock(&softc->ctl_lock);
1456
1457	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1458		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1459			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1460				iid = i;
1461				break;
1462			}
1463			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1464			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1465				iid = i;
1466				break;
1467			}
1468		}
1469	}
1470
1471	if (iid < 0) {
1472		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1473			if (port->wwpn_iid[i].in_use == 0 &&
1474			    port->wwpn_iid[i].wwpn == 0 &&
1475			    port->wwpn_iid[i].name == NULL) {
1476				iid = i;
1477				break;
1478			}
1479		}
1480	}
1481
1482	if (iid < 0) {
1483		best = -1;
1484		best_time = INT32_MAX;
1485		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1486			if (port->wwpn_iid[i].in_use == 0) {
1487				if (port->wwpn_iid[i].last_use < best_time) {
1488					best = i;
1489					best_time = port->wwpn_iid[i].last_use;
1490				}
1491			}
1492		}
1493		iid = best;
1494	}
1495
1496	if (iid < 0) {
1497		mtx_unlock(&softc->ctl_lock);
1498		free(name, M_CTL);
1499		return (-2);
1500	}
1501
1502	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1503		/*
1504		 * This is not an error yet.
1505		 */
1506		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1507#if 0
1508			printf("%s: port %d iid %u WWPN %#jx arrived"
1509			    " again\n", __func__, port->targ_port,
1510			    iid, (uintmax_t)wwpn);
1511#endif
1512			goto take;
1513		}
1514		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1515		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1516#if 0
1517			printf("%s: port %d iid %u name '%s' arrived"
1518			    " again\n", __func__, port->targ_port,
1519			    iid, name);
1520#endif
1521			goto take;
1522		}
1523
1524		/*
1525		 * This is an error, but what do we do about it?  The
1526		 * driver is telling us we have a new WWPN for this
1527		 * initiator ID, so we pretty much need to use it.
1528		 */
1529		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1530		    " but WWPN %#jx '%s' is still at that address\n",
1531		    __func__, port->targ_port, iid, wwpn, name,
1532		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1533		    port->wwpn_iid[iid].name);
1534
1535		/*
1536		 * XXX KDM clear have_ca and ua_pending on each LUN for
1537		 * this initiator.
1538		 */
1539	}
1540take:
1541	free(port->wwpn_iid[iid].name, M_CTL);
1542	port->wwpn_iid[iid].name = name;
1543	port->wwpn_iid[iid].wwpn = wwpn;
1544	port->wwpn_iid[iid].in_use++;
1545	mtx_unlock(&softc->ctl_lock);
1546
1547	return (iid);
1548}
1549
1550static int
1551ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1552{
1553	int len;
1554
1555	switch (port->port_type) {
1556	case CTL_PORT_FC:
1557	{
1558		struct scsi_transportid_fcp *id =
1559		    (struct scsi_transportid_fcp *)buf;
1560		if (port->wwpn_iid[iid].wwpn == 0)
1561			return (0);
1562		memset(id, 0, sizeof(*id));
1563		id->format_protocol = SCSI_PROTO_FC;
1564		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1565		return (sizeof(*id));
1566	}
1567	case CTL_PORT_ISCSI:
1568	{
1569		struct scsi_transportid_iscsi_port *id =
1570		    (struct scsi_transportid_iscsi_port *)buf;
1571		if (port->wwpn_iid[iid].name == NULL)
1572			return (0);
1573		memset(id, 0, 256);
1574		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1575		    SCSI_PROTO_ISCSI;
1576		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1577		len = roundup2(min(len, 252), 4);
1578		scsi_ulto2b(len, id->additional_length);
1579		return (sizeof(*id) + len);
1580	}
1581	case CTL_PORT_SAS:
1582	{
1583		struct scsi_transportid_sas *id =
1584		    (struct scsi_transportid_sas *)buf;
1585		if (port->wwpn_iid[iid].wwpn == 0)
1586			return (0);
1587		memset(id, 0, sizeof(*id));
1588		id->format_protocol = SCSI_PROTO_SAS;
1589		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1590		return (sizeof(*id));
1591	}
1592	default:
1593	{
1594		struct scsi_transportid_spi *id =
1595		    (struct scsi_transportid_spi *)buf;
1596		memset(id, 0, sizeof(*id));
1597		id->format_protocol = SCSI_PROTO_SPI;
1598		scsi_ulto2b(iid, id->scsi_addr);
1599		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1600		return (sizeof(*id));
1601	}
1602	}
1603}
1604
1605static int
1606ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1607{
1608	return (0);
1609}
1610
1611static int
1612ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1613{
1614	return (0);
1615}
1616
1617/*
1618 * Data movement routine for the CTL ioctl frontend port.
1619 */
1620static int
1621ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1622{
1623	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1624	struct ctl_sg_entry ext_entry, kern_entry;
1625	int ext_sglen, ext_sg_entries, kern_sg_entries;
1626	int ext_sg_start, ext_offset;
1627	int len_to_copy, len_copied;
1628	int kern_watermark, ext_watermark;
1629	int ext_sglist_malloced;
1630	int i, j;
1631
1632	ext_sglist_malloced = 0;
1633	ext_sg_start = 0;
1634	ext_offset = 0;
1635
1636	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1637
1638	/*
1639	 * If this flag is set, fake the data transfer.
1640	 */
1641	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1642		ctsio->ext_data_filled = ctsio->ext_data_len;
1643		goto bailout;
1644	}
1645
1646	/*
1647	 * To simplify things here, if we have a single buffer, stick it in
1648	 * a S/G entry and just make it a single entry S/G list.
1649	 */
1650	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1651		int len_seen;
1652
1653		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1654
1655		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1656							   M_WAITOK);
1657		ext_sglist_malloced = 1;
1658		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1659				   ext_sglen) != 0) {
1660			ctl_set_internal_failure(ctsio,
1661						 /*sks_valid*/ 0,
1662						 /*retry_count*/ 0);
1663			goto bailout;
1664		}
1665		ext_sg_entries = ctsio->ext_sg_entries;
1666		len_seen = 0;
1667		for (i = 0; i < ext_sg_entries; i++) {
1668			if ((len_seen + ext_sglist[i].len) >=
1669			     ctsio->ext_data_filled) {
1670				ext_sg_start = i;
1671				ext_offset = ctsio->ext_data_filled - len_seen;
1672				break;
1673			}
1674			len_seen += ext_sglist[i].len;
1675		}
1676	} else {
1677		ext_sglist = &ext_entry;
1678		ext_sglist->addr = ctsio->ext_data_ptr;
1679		ext_sglist->len = ctsio->ext_data_len;
1680		ext_sg_entries = 1;
1681		ext_sg_start = 0;
1682		ext_offset = ctsio->ext_data_filled;
1683	}
1684
1685	if (ctsio->kern_sg_entries > 0) {
1686		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1687		kern_sg_entries = ctsio->kern_sg_entries;
1688	} else {
1689		kern_sglist = &kern_entry;
1690		kern_sglist->addr = ctsio->kern_data_ptr;
1691		kern_sglist->len = ctsio->kern_data_len;
1692		kern_sg_entries = 1;
1693	}
1694
1695
1696	kern_watermark = 0;
1697	ext_watermark = ext_offset;
1698	len_copied = 0;
1699	for (i = ext_sg_start, j = 0;
1700	     i < ext_sg_entries && j < kern_sg_entries;) {
1701		uint8_t *ext_ptr, *kern_ptr;
1702
1703		len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1704				      kern_sglist[j].len - kern_watermark);
1705
1706		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1707		ext_ptr = ext_ptr + ext_watermark;
1708		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1709			/*
1710			 * XXX KDM fix this!
1711			 */
1712			panic("need to implement bus address support");
1713#if 0
1714			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1715#endif
1716		} else
1717			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1718		kern_ptr = kern_ptr + kern_watermark;
1719
1720		kern_watermark += len_to_copy;
1721		ext_watermark += len_to_copy;
1722
1723		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1724		     CTL_FLAG_DATA_IN) {
1725			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1726					 "bytes to user\n", len_to_copy));
1727			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1728					 "to %p\n", kern_ptr, ext_ptr));
1729			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1730				ctl_set_internal_failure(ctsio,
1731							 /*sks_valid*/ 0,
1732							 /*retry_count*/ 0);
1733				goto bailout;
1734			}
1735		} else {
1736			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1737					 "bytes from user\n", len_to_copy));
1738			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1739					 "to %p\n", ext_ptr, kern_ptr));
1740			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1741				ctl_set_internal_failure(ctsio,
1742							 /*sks_valid*/ 0,
1743							 /*retry_count*/0);
1744				goto bailout;
1745			}
1746		}
1747
1748		len_copied += len_to_copy;
1749
1750		if (ext_sglist[i].len == ext_watermark) {
1751			i++;
1752			ext_watermark = 0;
1753		}
1754
1755		if (kern_sglist[j].len == kern_watermark) {
1756			j++;
1757			kern_watermark = 0;
1758		}
1759	}
1760
1761	ctsio->ext_data_filled += len_copied;
1762
1763	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1764			 "kern_sg_entries: %d\n", ext_sg_entries,
1765			 kern_sg_entries));
1766	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1767			 "kern_data_len = %d\n", ctsio->ext_data_len,
1768			 ctsio->kern_data_len));
1769
1770
1771	/* XXX KDM set residual?? */
1772bailout:
1773
1774	if (ext_sglist_malloced != 0)
1775		free(ext_sglist, M_CTL);
1776
1777	return (CTL_RETVAL_COMPLETE);
1778}
1779
1780/*
1781 * Serialize a command that went down the "wrong" side, and so was sent to
1782 * this controller for execution.  The logic is a little different than the
1783 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1784 * sent back to the other side, but in the success case, we execute the
1785 * command on this side (XFER mode) or tell the other side to execute it
1786 * (SER_ONLY mode).
1787 */
1788static int
1789ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1790{
1791	struct ctl_softc *ctl_softc;
1792	union ctl_ha_msg msg_info;
1793	struct ctl_lun *lun;
1794	int retval = 0;
1795	uint32_t targ_lun;
1796
1797	ctl_softc = control_softc;
1798
1799	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1800	lun = ctl_softc->ctl_luns[targ_lun];
1801	if (lun==NULL)
1802	{
1803		/*
1804		 * Why isn't LUN defined? The other side wouldn't
1805		 * send a cmd if the LUN is undefined.
1806		 */
1807		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1808
1809		/* "Logical unit not supported" */
1810		ctl_set_sense_data(&msg_info.scsi.sense_data,
1811				   lun,
1812				   /*sense_format*/SSD_TYPE_NONE,
1813				   /*current_error*/ 1,
1814				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1815				   /*asc*/ 0x25,
1816				   /*ascq*/ 0x00,
1817				   SSD_ELEM_NONE);
1818
1819		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1820		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1821		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1822		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1823		msg_info.hdr.serializing_sc = NULL;
1824		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1825	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1826				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1827		}
1828		return(1);
1829
1830	}
1831
1832	mtx_lock(&lun->lun_lock);
1833    	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1834
1835	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1836		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1837		 ooa_links))) {
1838	case CTL_ACTION_BLOCK:
1839		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1840		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1841				  blocked_links);
1842		break;
1843	case CTL_ACTION_PASS:
1844	case CTL_ACTION_SKIP:
1845		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1846			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1847			ctl_enqueue_rtr((union ctl_io *)ctsio);
1848		} else {
1849
1850			/* send msg back to other side */
1851			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1852			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1853			msg_info.hdr.msg_type = CTL_MSG_R2R;
1854#if 0
1855			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1856#endif
1857		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1858			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1859			}
1860		}
1861		break;
1862	case CTL_ACTION_OVERLAP:
1863		/* OVERLAPPED COMMANDS ATTEMPTED */
1864		ctl_set_sense_data(&msg_info.scsi.sense_data,
1865				   lun,
1866				   /*sense_format*/SSD_TYPE_NONE,
1867				   /*current_error*/ 1,
1868				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1869				   /*asc*/ 0x4E,
1870				   /*ascq*/ 0x00,
1871				   SSD_ELEM_NONE);
1872
1873		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1874		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1875		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1876		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1877		msg_info.hdr.serializing_sc = NULL;
1878		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1879#if 0
1880		printf("BAD JUJU:Major Bummer Overlap\n");
1881#endif
1882		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1883		retval = 1;
1884		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1885		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1886		}
1887		break;
1888	case CTL_ACTION_OVERLAP_TAG:
1889		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1890		ctl_set_sense_data(&msg_info.scsi.sense_data,
1891				   lun,
1892				   /*sense_format*/SSD_TYPE_NONE,
1893				   /*current_error*/ 1,
1894				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1895				   /*asc*/ 0x4D,
1896				   /*ascq*/ ctsio->tag_num & 0xff,
1897				   SSD_ELEM_NONE);
1898
1899		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1900		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1901		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1902		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1903		msg_info.hdr.serializing_sc = NULL;
1904		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1905#if 0
1906		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1907#endif
1908		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1909		retval = 1;
1910		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1911		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1912		}
1913		break;
1914	case CTL_ACTION_ERROR:
1915	default:
1916		/* "Internal target failure" */
1917		ctl_set_sense_data(&msg_info.scsi.sense_data,
1918				   lun,
1919				   /*sense_format*/SSD_TYPE_NONE,
1920				   /*current_error*/ 1,
1921				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1922				   /*asc*/ 0x44,
1923				   /*ascq*/ 0x00,
1924				   SSD_ELEM_NONE);
1925
1926		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1927		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1928		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1929		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1930		msg_info.hdr.serializing_sc = NULL;
1931		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1932#if 0
1933		printf("BAD JUJU:Major Bummer HW Error\n");
1934#endif
1935		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1936		retval = 1;
1937		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1938		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1939		}
1940		break;
1941	}
1942	mtx_unlock(&lun->lun_lock);
1943	return (retval);
1944}
1945
1946static int
1947ctl_ioctl_submit_wait(union ctl_io *io)
1948{
1949	struct ctl_fe_ioctl_params params;
1950	ctl_fe_ioctl_state last_state;
1951	int done, retval;
1952
1953	retval = 0;
1954
1955	bzero(&params, sizeof(params));
1956
1957	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1958	cv_init(&params.sem, "ctlioccv");
1959	params.state = CTL_IOCTL_INPROG;
1960	last_state = params.state;
1961
1962	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1963
1964	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1965
1966	/* This shouldn't happen */
1967	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1968		return (retval);
1969
1970	done = 0;
1971
1972	do {
1973		mtx_lock(&params.ioctl_mtx);
1974		/*
1975		 * Check the state here, and don't sleep if the state has
1976		 * already changed (i.e. wakeup has already occured, but we
1977		 * weren't waiting yet).
1978		 */
1979		if (params.state == last_state) {
1980			/* XXX KDM cv_wait_sig instead? */
1981			cv_wait(&params.sem, &params.ioctl_mtx);
1982		}
1983		last_state = params.state;
1984
1985		switch (params.state) {
1986		case CTL_IOCTL_INPROG:
1987			/* Why did we wake up? */
1988			/* XXX KDM error here? */
1989			mtx_unlock(&params.ioctl_mtx);
1990			break;
1991		case CTL_IOCTL_DATAMOVE:
1992			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1993
1994			/*
1995			 * change last_state back to INPROG to avoid
1996			 * deadlock on subsequent data moves.
1997			 */
1998			params.state = last_state = CTL_IOCTL_INPROG;
1999
2000			mtx_unlock(&params.ioctl_mtx);
2001			ctl_ioctl_do_datamove(&io->scsiio);
2002			/*
2003			 * Note that in some cases, most notably writes,
2004			 * this will queue the I/O and call us back later.
2005			 * In other cases, generally reads, this routine
2006			 * will immediately call back and wake us up,
2007			 * probably using our own context.
2008			 */
2009			io->scsiio.be_move_done(io);
2010			break;
2011		case CTL_IOCTL_DONE:
2012			mtx_unlock(&params.ioctl_mtx);
2013			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
2014			done = 1;
2015			break;
2016		default:
2017			mtx_unlock(&params.ioctl_mtx);
2018			/* XXX KDM error here? */
2019			break;
2020		}
2021	} while (done == 0);
2022
2023	mtx_destroy(&params.ioctl_mtx);
2024	cv_destroy(&params.sem);
2025
2026	return (CTL_RETVAL_COMPLETE);
2027}
2028
2029static void
2030ctl_ioctl_datamove(union ctl_io *io)
2031{
2032	struct ctl_fe_ioctl_params *params;
2033
2034	params = (struct ctl_fe_ioctl_params *)
2035		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2036
2037	mtx_lock(&params->ioctl_mtx);
2038	params->state = CTL_IOCTL_DATAMOVE;
2039	cv_broadcast(&params->sem);
2040	mtx_unlock(&params->ioctl_mtx);
2041}
2042
2043static void
2044ctl_ioctl_done(union ctl_io *io)
2045{
2046	struct ctl_fe_ioctl_params *params;
2047
2048	params = (struct ctl_fe_ioctl_params *)
2049		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2050
2051	mtx_lock(&params->ioctl_mtx);
2052	params->state = CTL_IOCTL_DONE;
2053	cv_broadcast(&params->sem);
2054	mtx_unlock(&params->ioctl_mtx);
2055}
2056
2057static void
2058ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2059{
2060	struct ctl_fe_ioctl_startstop_info *sd_info;
2061
2062	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2063
2064	sd_info->hs_info.status = metatask->status;
2065	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2066	sd_info->hs_info.luns_complete =
2067		metatask->taskinfo.startstop.luns_complete;
2068	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2069
2070	cv_broadcast(&sd_info->sem);
2071}
2072
2073static void
2074ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2075{
2076	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2077
2078	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2079
2080	mtx_lock(fe_bbr_info->lock);
2081	fe_bbr_info->bbr_info->status = metatask->status;
2082	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2083	fe_bbr_info->wakeup_done = 1;
2084	mtx_unlock(fe_bbr_info->lock);
2085
2086	cv_broadcast(&fe_bbr_info->sem);
2087}
2088
2089/*
2090 * Returns 0 for success, errno for failure.
2091 */
2092static int
2093ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2094		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2095{
2096	union ctl_io *io;
2097	int retval;
2098
2099	retval = 0;
2100
2101	mtx_lock(&lun->lun_lock);
2102	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2103	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2104	     ooa_links)) {
2105		struct ctl_ooa_entry *entry;
2106
2107		/*
2108		 * If we've got more than we can fit, just count the
2109		 * remaining entries.
2110		 */
2111		if (*cur_fill_num >= ooa_hdr->alloc_num)
2112			continue;
2113
2114		entry = &kern_entries[*cur_fill_num];
2115
2116		entry->tag_num = io->scsiio.tag_num;
2117		entry->lun_num = lun->lun;
2118#ifdef CTL_TIME_IO
2119		entry->start_bt = io->io_hdr.start_bt;
2120#endif
2121		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2122		entry->cdb_len = io->scsiio.cdb_len;
2123		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2124			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2125
2126		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2127			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2128
2129		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2130			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2131
2132		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2133			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2134
2135		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2136			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2137	}
2138	mtx_unlock(&lun->lun_lock);
2139
2140	return (retval);
2141}
2142
2143static void *
2144ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2145		 size_t error_str_len)
2146{
2147	void *kptr;
2148
2149	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2150
2151	if (copyin(user_addr, kptr, len) != 0) {
2152		snprintf(error_str, error_str_len, "Error copying %d bytes "
2153			 "from user address %p to kernel address %p", len,
2154			 user_addr, kptr);
2155		free(kptr, M_CTL);
2156		return (NULL);
2157	}
2158
2159	return (kptr);
2160}
2161
2162static void
2163ctl_free_args(int num_args, struct ctl_be_arg *args)
2164{
2165	int i;
2166
2167	if (args == NULL)
2168		return;
2169
2170	for (i = 0; i < num_args; i++) {
2171		free(args[i].kname, M_CTL);
2172		free(args[i].kvalue, M_CTL);
2173	}
2174
2175	free(args, M_CTL);
2176}
2177
2178static struct ctl_be_arg *
2179ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2180		char *error_str, size_t error_str_len)
2181{
2182	struct ctl_be_arg *args;
2183	int i;
2184
2185	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2186				error_str, error_str_len);
2187
2188	if (args == NULL)
2189		goto bailout;
2190
2191	for (i = 0; i < num_args; i++) {
2192		args[i].kname = NULL;
2193		args[i].kvalue = NULL;
2194	}
2195
2196	for (i = 0; i < num_args; i++) {
2197		uint8_t *tmpptr;
2198
2199		args[i].kname = ctl_copyin_alloc(args[i].name,
2200			args[i].namelen, error_str, error_str_len);
2201		if (args[i].kname == NULL)
2202			goto bailout;
2203
2204		if (args[i].kname[args[i].namelen - 1] != '\0') {
2205			snprintf(error_str, error_str_len, "Argument %d "
2206				 "name is not NUL-terminated", i);
2207			goto bailout;
2208		}
2209
2210		if (args[i].flags & CTL_BEARG_RD) {
2211			tmpptr = ctl_copyin_alloc(args[i].value,
2212				args[i].vallen, error_str, error_str_len);
2213			if (tmpptr == NULL)
2214				goto bailout;
2215			if ((args[i].flags & CTL_BEARG_ASCII)
2216			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2217				snprintf(error_str, error_str_len, "Argument "
2218				    "%d value is not NUL-terminated", i);
2219				goto bailout;
2220			}
2221			args[i].kvalue = tmpptr;
2222		} else {
2223			args[i].kvalue = malloc(args[i].vallen,
2224			    M_CTL, M_WAITOK | M_ZERO);
2225		}
2226	}
2227
2228	return (args);
2229bailout:
2230
2231	ctl_free_args(num_args, args);
2232
2233	return (NULL);
2234}
2235
2236static void
2237ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2238{
2239	int i;
2240
2241	for (i = 0; i < num_args; i++) {
2242		if (args[i].flags & CTL_BEARG_WR)
2243			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2244	}
2245}
2246
2247/*
2248 * Escape characters that are illegal or not recommended in XML.
2249 */
2250int
2251ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2252{
2253	char *end = str + size;
2254	int retval;
2255
2256	retval = 0;
2257
2258	for (; *str && str < end; str++) {
2259		switch (*str) {
2260		case '&':
2261			retval = sbuf_printf(sb, "&amp;");
2262			break;
2263		case '>':
2264			retval = sbuf_printf(sb, "&gt;");
2265			break;
2266		case '<':
2267			retval = sbuf_printf(sb, "&lt;");
2268			break;
2269		default:
2270			retval = sbuf_putc(sb, *str);
2271			break;
2272		}
2273
2274		if (retval != 0)
2275			break;
2276
2277	}
2278
2279	return (retval);
2280}
2281
2282static void
2283ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2284{
2285	struct scsi_vpd_id_descriptor *desc;
2286	int i;
2287
2288	if (id == NULL || id->len < 4)
2289		return;
2290	desc = (struct scsi_vpd_id_descriptor *)id->data;
2291	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2292	case SVPD_ID_TYPE_T10:
2293		sbuf_printf(sb, "t10.");
2294		break;
2295	case SVPD_ID_TYPE_EUI64:
2296		sbuf_printf(sb, "eui.");
2297		break;
2298	case SVPD_ID_TYPE_NAA:
2299		sbuf_printf(sb, "naa.");
2300		break;
2301	case SVPD_ID_TYPE_SCSI_NAME:
2302		break;
2303	}
2304	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2305	case SVPD_ID_CODESET_BINARY:
2306		for (i = 0; i < desc->length; i++)
2307			sbuf_printf(sb, "%02x", desc->identifier[i]);
2308		break;
2309	case SVPD_ID_CODESET_ASCII:
2310		sbuf_printf(sb, "%.*s", (int)desc->length,
2311		    (char *)desc->identifier);
2312		break;
2313	case SVPD_ID_CODESET_UTF8:
2314		sbuf_printf(sb, "%s", (char *)desc->identifier);
2315		break;
2316	}
2317}
2318
2319static int
2320ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2321	  struct thread *td)
2322{
2323	struct ctl_softc *softc;
2324	int retval;
2325
2326	softc = control_softc;
2327
2328	retval = 0;
2329
2330	switch (cmd) {
2331	case CTL_IO: {
2332		union ctl_io *io;
2333		void *pool_tmp;
2334
2335		/*
2336		 * If we haven't been "enabled", don't allow any SCSI I/O
2337		 * to this FETD.
2338		 */
2339		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2340			retval = EPERM;
2341			break;
2342		}
2343
2344		io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2345		if (io == NULL) {
2346			printf("ctl_ioctl: can't allocate ctl_io!\n");
2347			retval = ENOSPC;
2348			break;
2349		}
2350
2351		/*
2352		 * Need to save the pool reference so it doesn't get
2353		 * spammed by the user's ctl_io.
2354		 */
2355		pool_tmp = io->io_hdr.pool;
2356
2357		memcpy(io, (void *)addr, sizeof(*io));
2358
2359		io->io_hdr.pool = pool_tmp;
2360		/*
2361		 * No status yet, so make sure the status is set properly.
2362		 */
2363		io->io_hdr.status = CTL_STATUS_NONE;
2364
2365		/*
2366		 * The user sets the initiator ID, target and LUN IDs.
2367		 */
2368		io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2369		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2370		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2371		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2372			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2373
2374		retval = ctl_ioctl_submit_wait(io);
2375
2376		if (retval != 0) {
2377			ctl_free_io(io);
2378			break;
2379		}
2380
2381		memcpy((void *)addr, io, sizeof(*io));
2382
2383		/* return this to our pool */
2384		ctl_free_io(io);
2385
2386		break;
2387	}
2388	case CTL_ENABLE_PORT:
2389	case CTL_DISABLE_PORT:
2390	case CTL_SET_PORT_WWNS: {
2391		struct ctl_port *port;
2392		struct ctl_port_entry *entry;
2393
2394		entry = (struct ctl_port_entry *)addr;
2395
2396		mtx_lock(&softc->ctl_lock);
2397		STAILQ_FOREACH(port, &softc->port_list, links) {
2398			int action, done;
2399
2400			action = 0;
2401			done = 0;
2402
2403			if ((entry->port_type == CTL_PORT_NONE)
2404			 && (entry->targ_port == port->targ_port)) {
2405				/*
2406				 * If the user only wants to enable or
2407				 * disable or set WWNs on a specific port,
2408				 * do the operation and we're done.
2409				 */
2410				action = 1;
2411				done = 1;
2412			} else if (entry->port_type & port->port_type) {
2413				/*
2414				 * Compare the user's type mask with the
2415				 * particular frontend type to see if we
2416				 * have a match.
2417				 */
2418				action = 1;
2419				done = 0;
2420
2421				/*
2422				 * Make sure the user isn't trying to set
2423				 * WWNs on multiple ports at the same time.
2424				 */
2425				if (cmd == CTL_SET_PORT_WWNS) {
2426					printf("%s: Can't set WWNs on "
2427					       "multiple ports\n", __func__);
2428					retval = EINVAL;
2429					break;
2430				}
2431			}
2432			if (action != 0) {
2433				/*
2434				 * XXX KDM we have to drop the lock here,
2435				 * because the online/offline operations
2436				 * can potentially block.  We need to
2437				 * reference count the frontends so they
2438				 * can't go away,
2439				 */
2440				mtx_unlock(&softc->ctl_lock);
2441
2442				if (cmd == CTL_ENABLE_PORT) {
2443					struct ctl_lun *lun;
2444
2445					STAILQ_FOREACH(lun, &softc->lun_list,
2446						       links) {
2447						port->lun_enable(port->targ_lun_arg,
2448						    lun->target,
2449						    lun->lun);
2450					}
2451
2452					ctl_port_online(port);
2453				} else if (cmd == CTL_DISABLE_PORT) {
2454					struct ctl_lun *lun;
2455
2456					ctl_port_offline(port);
2457
2458					STAILQ_FOREACH(lun, &softc->lun_list,
2459						       links) {
2460						port->lun_disable(
2461						    port->targ_lun_arg,
2462						    lun->target,
2463						    lun->lun);
2464					}
2465				}
2466
2467				mtx_lock(&softc->ctl_lock);
2468
2469				if (cmd == CTL_SET_PORT_WWNS)
2470					ctl_port_set_wwns(port,
2471					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2472					    1 : 0, entry->wwnn,
2473					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2474					    1 : 0, entry->wwpn);
2475			}
2476			if (done != 0)
2477				break;
2478		}
2479		mtx_unlock(&softc->ctl_lock);
2480		break;
2481	}
2482	case CTL_GET_PORT_LIST: {
2483		struct ctl_port *port;
2484		struct ctl_port_list *list;
2485		int i;
2486
2487		list = (struct ctl_port_list *)addr;
2488
2489		if (list->alloc_len != (list->alloc_num *
2490		    sizeof(struct ctl_port_entry))) {
2491			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2492			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2493			       "%zu\n", __func__, list->alloc_len,
2494			       list->alloc_num, sizeof(struct ctl_port_entry));
2495			retval = EINVAL;
2496			break;
2497		}
2498		list->fill_len = 0;
2499		list->fill_num = 0;
2500		list->dropped_num = 0;
2501		i = 0;
2502		mtx_lock(&softc->ctl_lock);
2503		STAILQ_FOREACH(port, &softc->port_list, links) {
2504			struct ctl_port_entry entry, *list_entry;
2505
2506			if (list->fill_num >= list->alloc_num) {
2507				list->dropped_num++;
2508				continue;
2509			}
2510
2511			entry.port_type = port->port_type;
2512			strlcpy(entry.port_name, port->port_name,
2513				sizeof(entry.port_name));
2514			entry.targ_port = port->targ_port;
2515			entry.physical_port = port->physical_port;
2516			entry.virtual_port = port->virtual_port;
2517			entry.wwnn = port->wwnn;
2518			entry.wwpn = port->wwpn;
2519			if (port->status & CTL_PORT_STATUS_ONLINE)
2520				entry.online = 1;
2521			else
2522				entry.online = 0;
2523
2524			list_entry = &list->entries[i];
2525
2526			retval = copyout(&entry, list_entry, sizeof(entry));
2527			if (retval != 0) {
2528				printf("%s: CTL_GET_PORT_LIST: copyout "
2529				       "returned %d\n", __func__, retval);
2530				break;
2531			}
2532			i++;
2533			list->fill_num++;
2534			list->fill_len += sizeof(entry);
2535		}
2536		mtx_unlock(&softc->ctl_lock);
2537
2538		/*
2539		 * If this is non-zero, we had a copyout fault, so there's
2540		 * probably no point in attempting to set the status inside
2541		 * the structure.
2542		 */
2543		if (retval != 0)
2544			break;
2545
2546		if (list->dropped_num > 0)
2547			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2548		else
2549			list->status = CTL_PORT_LIST_OK;
2550		break;
2551	}
2552	case CTL_DUMP_OOA: {
2553		struct ctl_lun *lun;
2554		union ctl_io *io;
2555		char printbuf[128];
2556		struct sbuf sb;
2557
2558		mtx_lock(&softc->ctl_lock);
2559		printf("Dumping OOA queues:\n");
2560		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2561			mtx_lock(&lun->lun_lock);
2562			for (io = (union ctl_io *)TAILQ_FIRST(
2563			     &lun->ooa_queue); io != NULL;
2564			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2565			     ooa_links)) {
2566				sbuf_new(&sb, printbuf, sizeof(printbuf),
2567					 SBUF_FIXEDLEN);
2568				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2569					    (intmax_t)lun->lun,
2570					    io->scsiio.tag_num,
2571					    (io->io_hdr.flags &
2572					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2573					    (io->io_hdr.flags &
2574					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2575					    (io->io_hdr.flags &
2576					    CTL_FLAG_ABORT) ? " ABORT" : "",
2577			                    (io->io_hdr.flags &
2578		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2579				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2580				sbuf_finish(&sb);
2581				printf("%s\n", sbuf_data(&sb));
2582			}
2583			mtx_unlock(&lun->lun_lock);
2584		}
2585		printf("OOA queues dump done\n");
2586		mtx_unlock(&softc->ctl_lock);
2587		break;
2588	}
2589	case CTL_GET_OOA: {
2590		struct ctl_lun *lun;
2591		struct ctl_ooa *ooa_hdr;
2592		struct ctl_ooa_entry *entries;
2593		uint32_t cur_fill_num;
2594
2595		ooa_hdr = (struct ctl_ooa *)addr;
2596
2597		if ((ooa_hdr->alloc_len == 0)
2598		 || (ooa_hdr->alloc_num == 0)) {
2599			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2600			       "must be non-zero\n", __func__,
2601			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2602			retval = EINVAL;
2603			break;
2604		}
2605
2606		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2607		    sizeof(struct ctl_ooa_entry))) {
2608			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2609			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2610			       __func__, ooa_hdr->alloc_len,
2611			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2612			retval = EINVAL;
2613			break;
2614		}
2615
2616		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2617		if (entries == NULL) {
2618			printf("%s: could not allocate %d bytes for OOA "
2619			       "dump\n", __func__, ooa_hdr->alloc_len);
2620			retval = ENOMEM;
2621			break;
2622		}
2623
2624		mtx_lock(&softc->ctl_lock);
2625		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2626		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2627		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2628			mtx_unlock(&softc->ctl_lock);
2629			free(entries, M_CTL);
2630			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2631			       __func__, (uintmax_t)ooa_hdr->lun_num);
2632			retval = EINVAL;
2633			break;
2634		}
2635
2636		cur_fill_num = 0;
2637
2638		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2639			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2640				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2641					ooa_hdr, entries);
2642				if (retval != 0)
2643					break;
2644			}
2645			if (retval != 0) {
2646				mtx_unlock(&softc->ctl_lock);
2647				free(entries, M_CTL);
2648				break;
2649			}
2650		} else {
2651			lun = softc->ctl_luns[ooa_hdr->lun_num];
2652
2653			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2654						    entries);
2655		}
2656		mtx_unlock(&softc->ctl_lock);
2657
2658		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2659		ooa_hdr->fill_len = ooa_hdr->fill_num *
2660			sizeof(struct ctl_ooa_entry);
2661		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2662		if (retval != 0) {
2663			printf("%s: error copying out %d bytes for OOA dump\n",
2664			       __func__, ooa_hdr->fill_len);
2665		}
2666
2667		getbintime(&ooa_hdr->cur_bt);
2668
2669		if (cur_fill_num > ooa_hdr->alloc_num) {
2670			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2671			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2672		} else {
2673			ooa_hdr->dropped_num = 0;
2674			ooa_hdr->status = CTL_OOA_OK;
2675		}
2676
2677		free(entries, M_CTL);
2678		break;
2679	}
2680	case CTL_CHECK_OOA: {
2681		union ctl_io *io;
2682		struct ctl_lun *lun;
2683		struct ctl_ooa_info *ooa_info;
2684
2685
2686		ooa_info = (struct ctl_ooa_info *)addr;
2687
2688		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2689			ooa_info->status = CTL_OOA_INVALID_LUN;
2690			break;
2691		}
2692		mtx_lock(&softc->ctl_lock);
2693		lun = softc->ctl_luns[ooa_info->lun_id];
2694		if (lun == NULL) {
2695			mtx_unlock(&softc->ctl_lock);
2696			ooa_info->status = CTL_OOA_INVALID_LUN;
2697			break;
2698		}
2699		mtx_lock(&lun->lun_lock);
2700		mtx_unlock(&softc->ctl_lock);
2701		ooa_info->num_entries = 0;
2702		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2703		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2704		     &io->io_hdr, ooa_links)) {
2705			ooa_info->num_entries++;
2706		}
2707		mtx_unlock(&lun->lun_lock);
2708
2709		ooa_info->status = CTL_OOA_SUCCESS;
2710
2711		break;
2712	}
2713	case CTL_HARD_START:
2714	case CTL_HARD_STOP: {
2715		struct ctl_fe_ioctl_startstop_info ss_info;
2716		struct cfi_metatask *metatask;
2717		struct mtx hs_mtx;
2718
2719		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2720
2721		cv_init(&ss_info.sem, "hard start/stop cv" );
2722
2723		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2724		if (metatask == NULL) {
2725			retval = ENOMEM;
2726			mtx_destroy(&hs_mtx);
2727			break;
2728		}
2729
2730		if (cmd == CTL_HARD_START)
2731			metatask->tasktype = CFI_TASK_STARTUP;
2732		else
2733			metatask->tasktype = CFI_TASK_SHUTDOWN;
2734
2735		metatask->callback = ctl_ioctl_hard_startstop_callback;
2736		metatask->callback_arg = &ss_info;
2737
2738		cfi_action(metatask);
2739
2740		/* Wait for the callback */
2741		mtx_lock(&hs_mtx);
2742		cv_wait_sig(&ss_info.sem, &hs_mtx);
2743		mtx_unlock(&hs_mtx);
2744
2745		/*
2746		 * All information has been copied from the metatask by the
2747		 * time cv_broadcast() is called, so we free the metatask here.
2748		 */
2749		cfi_free_metatask(metatask);
2750
2751		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2752
2753		mtx_destroy(&hs_mtx);
2754		break;
2755	}
2756	case CTL_BBRREAD: {
2757		struct ctl_bbrread_info *bbr_info;
2758		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2759		struct mtx bbr_mtx;
2760		struct cfi_metatask *metatask;
2761
2762		bbr_info = (struct ctl_bbrread_info *)addr;
2763
2764		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2765
2766		bzero(&bbr_mtx, sizeof(bbr_mtx));
2767		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2768
2769		fe_bbr_info.bbr_info = bbr_info;
2770		fe_bbr_info.lock = &bbr_mtx;
2771
2772		cv_init(&fe_bbr_info.sem, "BBR read cv");
2773		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2774
2775		if (metatask == NULL) {
2776			mtx_destroy(&bbr_mtx);
2777			cv_destroy(&fe_bbr_info.sem);
2778			retval = ENOMEM;
2779			break;
2780		}
2781		metatask->tasktype = CFI_TASK_BBRREAD;
2782		metatask->callback = ctl_ioctl_bbrread_callback;
2783		metatask->callback_arg = &fe_bbr_info;
2784		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2785		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2786		metatask->taskinfo.bbrread.len = bbr_info->len;
2787
2788		cfi_action(metatask);
2789
2790		mtx_lock(&bbr_mtx);
2791		while (fe_bbr_info.wakeup_done == 0)
2792			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2793		mtx_unlock(&bbr_mtx);
2794
2795		bbr_info->status = metatask->status;
2796		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2797		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2798		memcpy(&bbr_info->sense_data,
2799		       &metatask->taskinfo.bbrread.sense_data,
2800		       ctl_min(sizeof(bbr_info->sense_data),
2801			       sizeof(metatask->taskinfo.bbrread.sense_data)));
2802
2803		cfi_free_metatask(metatask);
2804
2805		mtx_destroy(&bbr_mtx);
2806		cv_destroy(&fe_bbr_info.sem);
2807
2808		break;
2809	}
2810	case CTL_DELAY_IO: {
2811		struct ctl_io_delay_info *delay_info;
2812#ifdef CTL_IO_DELAY
2813		struct ctl_lun *lun;
2814#endif /* CTL_IO_DELAY */
2815
2816		delay_info = (struct ctl_io_delay_info *)addr;
2817
2818#ifdef CTL_IO_DELAY
2819		mtx_lock(&softc->ctl_lock);
2820
2821		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2822		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2823			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2824		} else {
2825			lun = softc->ctl_luns[delay_info->lun_id];
2826			mtx_lock(&lun->lun_lock);
2827
2828			delay_info->status = CTL_DELAY_STATUS_OK;
2829
2830			switch (delay_info->delay_type) {
2831			case CTL_DELAY_TYPE_CONT:
2832				break;
2833			case CTL_DELAY_TYPE_ONESHOT:
2834				break;
2835			default:
2836				delay_info->status =
2837					CTL_DELAY_STATUS_INVALID_TYPE;
2838				break;
2839			}
2840
2841			switch (delay_info->delay_loc) {
2842			case CTL_DELAY_LOC_DATAMOVE:
2843				lun->delay_info.datamove_type =
2844					delay_info->delay_type;
2845				lun->delay_info.datamove_delay =
2846					delay_info->delay_secs;
2847				break;
2848			case CTL_DELAY_LOC_DONE:
2849				lun->delay_info.done_type =
2850					delay_info->delay_type;
2851				lun->delay_info.done_delay =
2852					delay_info->delay_secs;
2853				break;
2854			default:
2855				delay_info->status =
2856					CTL_DELAY_STATUS_INVALID_LOC;
2857				break;
2858			}
2859			mtx_unlock(&lun->lun_lock);
2860		}
2861
2862		mtx_unlock(&softc->ctl_lock);
2863#else
2864		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2865#endif /* CTL_IO_DELAY */
2866		break;
2867	}
2868	case CTL_REALSYNC_SET: {
2869		int *syncstate;
2870
2871		syncstate = (int *)addr;
2872
2873		mtx_lock(&softc->ctl_lock);
2874		switch (*syncstate) {
2875		case 0:
2876			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2877			break;
2878		case 1:
2879			softc->flags |= CTL_FLAG_REAL_SYNC;
2880			break;
2881		default:
2882			retval = EINVAL;
2883			break;
2884		}
2885		mtx_unlock(&softc->ctl_lock);
2886		break;
2887	}
2888	case CTL_REALSYNC_GET: {
2889		int *syncstate;
2890
2891		syncstate = (int*)addr;
2892
2893		mtx_lock(&softc->ctl_lock);
2894		if (softc->flags & CTL_FLAG_REAL_SYNC)
2895			*syncstate = 1;
2896		else
2897			*syncstate = 0;
2898		mtx_unlock(&softc->ctl_lock);
2899
2900		break;
2901	}
2902	case CTL_SETSYNC:
2903	case CTL_GETSYNC: {
2904		struct ctl_sync_info *sync_info;
2905		struct ctl_lun *lun;
2906
2907		sync_info = (struct ctl_sync_info *)addr;
2908
2909		mtx_lock(&softc->ctl_lock);
2910		lun = softc->ctl_luns[sync_info->lun_id];
2911		if (lun == NULL) {
2912			mtx_unlock(&softc->ctl_lock);
2913			sync_info->status = CTL_GS_SYNC_NO_LUN;
2914		}
2915		/*
2916		 * Get or set the sync interval.  We're not bounds checking
2917		 * in the set case, hopefully the user won't do something
2918		 * silly.
2919		 */
2920		mtx_lock(&lun->lun_lock);
2921		mtx_unlock(&softc->ctl_lock);
2922		if (cmd == CTL_GETSYNC)
2923			sync_info->sync_interval = lun->sync_interval;
2924		else
2925			lun->sync_interval = sync_info->sync_interval;
2926		mtx_unlock(&lun->lun_lock);
2927
2928		sync_info->status = CTL_GS_SYNC_OK;
2929
2930		break;
2931	}
2932	case CTL_GETSTATS: {
2933		struct ctl_stats *stats;
2934		struct ctl_lun *lun;
2935		int i;
2936
2937		stats = (struct ctl_stats *)addr;
2938
2939		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2940		     stats->alloc_len) {
2941			stats->status = CTL_SS_NEED_MORE_SPACE;
2942			stats->num_luns = softc->num_luns;
2943			break;
2944		}
2945		/*
2946		 * XXX KDM no locking here.  If the LUN list changes,
2947		 * things can blow up.
2948		 */
2949		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2950		     i++, lun = STAILQ_NEXT(lun, links)) {
2951			retval = copyout(&lun->stats, &stats->lun_stats[i],
2952					 sizeof(lun->stats));
2953			if (retval != 0)
2954				break;
2955		}
2956		stats->num_luns = softc->num_luns;
2957		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2958				 softc->num_luns;
2959		stats->status = CTL_SS_OK;
2960#ifdef CTL_TIME_IO
2961		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2962#else
2963		stats->flags = CTL_STATS_FLAG_NONE;
2964#endif
2965		getnanouptime(&stats->timestamp);
2966		break;
2967	}
2968	case CTL_ERROR_INJECT: {
2969		struct ctl_error_desc *err_desc, *new_err_desc;
2970		struct ctl_lun *lun;
2971
2972		err_desc = (struct ctl_error_desc *)addr;
2973
2974		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2975				      M_WAITOK | M_ZERO);
2976		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2977
2978		mtx_lock(&softc->ctl_lock);
2979		lun = softc->ctl_luns[err_desc->lun_id];
2980		if (lun == NULL) {
2981			mtx_unlock(&softc->ctl_lock);
2982			free(new_err_desc, M_CTL);
2983			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2984			       __func__, (uintmax_t)err_desc->lun_id);
2985			retval = EINVAL;
2986			break;
2987		}
2988		mtx_lock(&lun->lun_lock);
2989		mtx_unlock(&softc->ctl_lock);
2990
2991		/*
2992		 * We could do some checking here to verify the validity
2993		 * of the request, but given the complexity of error
2994		 * injection requests, the checking logic would be fairly
2995		 * complex.
2996		 *
2997		 * For now, if the request is invalid, it just won't get
2998		 * executed and might get deleted.
2999		 */
3000		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
3001
3002		/*
3003		 * XXX KDM check to make sure the serial number is unique,
3004		 * in case we somehow manage to wrap.  That shouldn't
3005		 * happen for a very long time, but it's the right thing to
3006		 * do.
3007		 */
3008		new_err_desc->serial = lun->error_serial;
3009		err_desc->serial = lun->error_serial;
3010		lun->error_serial++;
3011
3012		mtx_unlock(&lun->lun_lock);
3013		break;
3014	}
3015	case CTL_ERROR_INJECT_DELETE: {
3016		struct ctl_error_desc *delete_desc, *desc, *desc2;
3017		struct ctl_lun *lun;
3018		int delete_done;
3019
3020		delete_desc = (struct ctl_error_desc *)addr;
3021		delete_done = 0;
3022
3023		mtx_lock(&softc->ctl_lock);
3024		lun = softc->ctl_luns[delete_desc->lun_id];
3025		if (lun == NULL) {
3026			mtx_unlock(&softc->ctl_lock);
3027			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
3028			       __func__, (uintmax_t)delete_desc->lun_id);
3029			retval = EINVAL;
3030			break;
3031		}
3032		mtx_lock(&lun->lun_lock);
3033		mtx_unlock(&softc->ctl_lock);
3034		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
3035			if (desc->serial != delete_desc->serial)
3036				continue;
3037
3038			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
3039				      links);
3040			free(desc, M_CTL);
3041			delete_done = 1;
3042		}
3043		mtx_unlock(&lun->lun_lock);
3044		if (delete_done == 0) {
3045			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
3046			       "error serial %ju on LUN %u\n", __func__,
3047			       delete_desc->serial, delete_desc->lun_id);
3048			retval = EINVAL;
3049			break;
3050		}
3051		break;
3052	}
3053	case CTL_DUMP_STRUCTS: {
3054		int i, j, k, idx;
3055		struct ctl_port *port;
3056		struct ctl_frontend *fe;
3057
3058		mtx_lock(&softc->ctl_lock);
3059		printf("CTL Persistent Reservation information start:\n");
3060		for (i = 0; i < CTL_MAX_LUNS; i++) {
3061			struct ctl_lun *lun;
3062
3063			lun = softc->ctl_luns[i];
3064
3065			if ((lun == NULL)
3066			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
3067				continue;
3068
3069			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
3070				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
3071					idx = j * CTL_MAX_INIT_PER_PORT + k;
3072					if (lun->pr_keys[idx] == 0)
3073						continue;
3074					printf("  LUN %d port %d iid %d key "
3075					       "%#jx\n", i, j, k,
3076					       (uintmax_t)lun->pr_keys[idx]);
3077				}
3078			}
3079		}
3080		printf("CTL Persistent Reservation information end\n");
3081		printf("CTL Ports:\n");
3082		STAILQ_FOREACH(port, &softc->port_list, links) {
3083			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3084			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3085			       port->frontend->name, port->port_type,
3086			       port->physical_port, port->virtual_port,
3087			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3088			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3089				if (port->wwpn_iid[j].in_use == 0 &&
3090				    port->wwpn_iid[j].wwpn == 0 &&
3091				    port->wwpn_iid[j].name == NULL)
3092					continue;
3093
3094				printf("    iid %u use %d WWPN %#jx '%s'\n",
3095				    j, port->wwpn_iid[j].in_use,
3096				    (uintmax_t)port->wwpn_iid[j].wwpn,
3097				    port->wwpn_iid[j].name);
3098			}
3099		}
3100		printf("CTL Port information end\n");
3101		mtx_unlock(&softc->ctl_lock);
3102		/*
3103		 * XXX KDM calling this without a lock.  We'd likely want
3104		 * to drop the lock before calling the frontend's dump
3105		 * routine anyway.
3106		 */
3107		printf("CTL Frontends:\n");
3108		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3109			printf("  Frontend '%s'\n", fe->name);
3110			if (fe->fe_dump != NULL)
3111				fe->fe_dump();
3112		}
3113		printf("CTL Frontend information end\n");
3114		break;
3115	}
3116	case CTL_LUN_REQ: {
3117		struct ctl_lun_req *lun_req;
3118		struct ctl_backend_driver *backend;
3119
3120		lun_req = (struct ctl_lun_req *)addr;
3121
3122		backend = ctl_backend_find(lun_req->backend);
3123		if (backend == NULL) {
3124			lun_req->status = CTL_LUN_ERROR;
3125			snprintf(lun_req->error_str,
3126				 sizeof(lun_req->error_str),
3127				 "Backend \"%s\" not found.",
3128				 lun_req->backend);
3129			break;
3130		}
3131		if (lun_req->num_be_args > 0) {
3132			lun_req->kern_be_args = ctl_copyin_args(
3133				lun_req->num_be_args,
3134				lun_req->be_args,
3135				lun_req->error_str,
3136				sizeof(lun_req->error_str));
3137			if (lun_req->kern_be_args == NULL) {
3138				lun_req->status = CTL_LUN_ERROR;
3139				break;
3140			}
3141		}
3142
3143		retval = backend->ioctl(dev, cmd, addr, flag, td);
3144
3145		if (lun_req->num_be_args > 0) {
3146			ctl_copyout_args(lun_req->num_be_args,
3147				      lun_req->kern_be_args);
3148			ctl_free_args(lun_req->num_be_args,
3149				      lun_req->kern_be_args);
3150		}
3151		break;
3152	}
3153	case CTL_LUN_LIST: {
3154		struct sbuf *sb;
3155		struct ctl_lun *lun;
3156		struct ctl_lun_list *list;
3157		struct ctl_option *opt;
3158
3159		list = (struct ctl_lun_list *)addr;
3160
3161		/*
3162		 * Allocate a fixed length sbuf here, based on the length
3163		 * of the user's buffer.  We could allocate an auto-extending
3164		 * buffer, and then tell the user how much larger our
3165		 * amount of data is than his buffer, but that presents
3166		 * some problems:
3167		 *
3168		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3169		 *     we can't hold a lock while calling them with an
3170		 *     auto-extending buffer.
3171 		 *
3172		 * 2.  There is not currently a LUN reference counting
3173		 *     mechanism, outside of outstanding transactions on
3174		 *     the LUN's OOA queue.  So a LUN could go away on us
3175		 *     while we're getting the LUN number, backend-specific
3176		 *     information, etc.  Thus, given the way things
3177		 *     currently work, we need to hold the CTL lock while
3178		 *     grabbing LUN information.
3179		 *
3180		 * So, from the user's standpoint, the best thing to do is
3181		 * allocate what he thinks is a reasonable buffer length,
3182		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3183		 * double the buffer length and try again.  (And repeat
3184		 * that until he succeeds.)
3185		 */
3186		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3187		if (sb == NULL) {
3188			list->status = CTL_LUN_LIST_ERROR;
3189			snprintf(list->error_str, sizeof(list->error_str),
3190				 "Unable to allocate %d bytes for LUN list",
3191				 list->alloc_len);
3192			break;
3193		}
3194
3195		sbuf_printf(sb, "<ctllunlist>\n");
3196
3197		mtx_lock(&softc->ctl_lock);
3198		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3199			mtx_lock(&lun->lun_lock);
3200			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3201					     (uintmax_t)lun->lun);
3202
3203			/*
3204			 * Bail out as soon as we see that we've overfilled
3205			 * the buffer.
3206			 */
3207			if (retval != 0)
3208				break;
3209
3210			retval = sbuf_printf(sb, "\t<backend_type>%s"
3211					     "</backend_type>\n",
3212					     (lun->backend == NULL) ?  "none" :
3213					     lun->backend->name);
3214
3215			if (retval != 0)
3216				break;
3217
3218			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3219					     lun->be_lun->lun_type);
3220
3221			if (retval != 0)
3222				break;
3223
3224			if (lun->backend == NULL) {
3225				retval = sbuf_printf(sb, "</lun>\n");
3226				if (retval != 0)
3227					break;
3228				continue;
3229			}
3230
3231			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3232					     (lun->be_lun->maxlba > 0) ?
3233					     lun->be_lun->maxlba + 1 : 0);
3234
3235			if (retval != 0)
3236				break;
3237
3238			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3239					     lun->be_lun->blocksize);
3240
3241			if (retval != 0)
3242				break;
3243
3244			retval = sbuf_printf(sb, "\t<serial_number>");
3245
3246			if (retval != 0)
3247				break;
3248
3249			retval = ctl_sbuf_printf_esc(sb,
3250			    lun->be_lun->serial_num,
3251			    sizeof(lun->be_lun->serial_num));
3252
3253			if (retval != 0)
3254				break;
3255
3256			retval = sbuf_printf(sb, "</serial_number>\n");
3257
3258			if (retval != 0)
3259				break;
3260
3261			retval = sbuf_printf(sb, "\t<device_id>");
3262
3263			if (retval != 0)
3264				break;
3265
3266			retval = ctl_sbuf_printf_esc(sb,
3267			    lun->be_lun->device_id,
3268			    sizeof(lun->be_lun->device_id));
3269
3270			if (retval != 0)
3271				break;
3272
3273			retval = sbuf_printf(sb, "</device_id>\n");
3274
3275			if (retval != 0)
3276				break;
3277
3278			if (lun->backend->lun_info != NULL) {
3279				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3280				if (retval != 0)
3281					break;
3282			}
3283			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3284				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3285				    opt->name, opt->value, opt->name);
3286				if (retval != 0)
3287					break;
3288			}
3289
3290			retval = sbuf_printf(sb, "</lun>\n");
3291
3292			if (retval != 0)
3293				break;
3294			mtx_unlock(&lun->lun_lock);
3295		}
3296		if (lun != NULL)
3297			mtx_unlock(&lun->lun_lock);
3298		mtx_unlock(&softc->ctl_lock);
3299
3300		if ((retval != 0)
3301		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3302			retval = 0;
3303			sbuf_delete(sb);
3304			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3305			snprintf(list->error_str, sizeof(list->error_str),
3306				 "Out of space, %d bytes is too small",
3307				 list->alloc_len);
3308			break;
3309		}
3310
3311		sbuf_finish(sb);
3312
3313		retval = copyout(sbuf_data(sb), list->lun_xml,
3314				 sbuf_len(sb) + 1);
3315
3316		list->fill_len = sbuf_len(sb) + 1;
3317		list->status = CTL_LUN_LIST_OK;
3318		sbuf_delete(sb);
3319		break;
3320	}
3321	case CTL_ISCSI: {
3322		struct ctl_iscsi *ci;
3323		struct ctl_frontend *fe;
3324
3325		ci = (struct ctl_iscsi *)addr;
3326
3327		fe = ctl_frontend_find("iscsi");
3328		if (fe == NULL) {
3329			ci->status = CTL_ISCSI_ERROR;
3330			snprintf(ci->error_str, sizeof(ci->error_str),
3331			    "Frontend \"iscsi\" not found.");
3332			break;
3333		}
3334
3335		retval = fe->ioctl(dev, cmd, addr, flag, td);
3336		break;
3337	}
3338	case CTL_PORT_REQ: {
3339		struct ctl_req *req;
3340		struct ctl_frontend *fe;
3341
3342		req = (struct ctl_req *)addr;
3343
3344		fe = ctl_frontend_find(req->driver);
3345		if (fe == NULL) {
3346			req->status = CTL_LUN_ERROR;
3347			snprintf(req->error_str, sizeof(req->error_str),
3348			    "Frontend \"%s\" not found.", req->driver);
3349			break;
3350		}
3351		if (req->num_args > 0) {
3352			req->kern_args = ctl_copyin_args(req->num_args,
3353			    req->args, req->error_str, sizeof(req->error_str));
3354			if (req->kern_args == NULL) {
3355				req->status = CTL_LUN_ERROR;
3356				break;
3357			}
3358		}
3359
3360		retval = fe->ioctl(dev, cmd, addr, flag, td);
3361
3362		if (req->num_args > 0) {
3363			ctl_copyout_args(req->num_args, req->kern_args);
3364			ctl_free_args(req->num_args, req->kern_args);
3365		}
3366		break;
3367	}
3368	case CTL_PORT_LIST: {
3369		struct sbuf *sb;
3370		struct ctl_port *port;
3371		struct ctl_lun_list *list;
3372		struct ctl_option *opt;
3373		int j;
3374
3375		list = (struct ctl_lun_list *)addr;
3376
3377		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3378		if (sb == NULL) {
3379			list->status = CTL_LUN_LIST_ERROR;
3380			snprintf(list->error_str, sizeof(list->error_str),
3381				 "Unable to allocate %d bytes for LUN list",
3382				 list->alloc_len);
3383			break;
3384		}
3385
3386		sbuf_printf(sb, "<ctlportlist>\n");
3387
3388		mtx_lock(&softc->ctl_lock);
3389		STAILQ_FOREACH(port, &softc->port_list, links) {
3390			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3391					     (uintmax_t)port->targ_port);
3392
3393			/*
3394			 * Bail out as soon as we see that we've overfilled
3395			 * the buffer.
3396			 */
3397			if (retval != 0)
3398				break;
3399
3400			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3401			    "</frontend_type>\n", port->frontend->name);
3402			if (retval != 0)
3403				break;
3404
3405			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3406					     port->port_type);
3407			if (retval != 0)
3408				break;
3409
3410			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3411			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3412			if (retval != 0)
3413				break;
3414
3415			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3416			    port->port_name);
3417			if (retval != 0)
3418				break;
3419
3420			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3421			    port->physical_port);
3422			if (retval != 0)
3423				break;
3424
3425			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3426			    port->virtual_port);
3427			if (retval != 0)
3428				break;
3429
3430			if (port->target_devid != NULL) {
3431				sbuf_printf(sb, "\t<target>");
3432				ctl_id_sbuf(port->target_devid, sb);
3433				sbuf_printf(sb, "</target>\n");
3434			}
3435
3436			if (port->port_devid != NULL) {
3437				sbuf_printf(sb, "\t<port>");
3438				ctl_id_sbuf(port->port_devid, sb);
3439				sbuf_printf(sb, "</port>\n");
3440			}
3441
3442			if (port->port_info != NULL) {
3443				retval = port->port_info(port->onoff_arg, sb);
3444				if (retval != 0)
3445					break;
3446			}
3447			STAILQ_FOREACH(opt, &port->options, links) {
3448				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3449				    opt->name, opt->value, opt->name);
3450				if (retval != 0)
3451					break;
3452			}
3453
3454			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3455				if (port->wwpn_iid[j].in_use == 0 ||
3456				    (port->wwpn_iid[j].wwpn == 0 &&
3457				     port->wwpn_iid[j].name == NULL))
3458					continue;
3459
3460				if (port->wwpn_iid[j].name != NULL)
3461					retval = sbuf_printf(sb,
3462					    "\t<initiator>%u %s</initiator>\n",
3463					    j, port->wwpn_iid[j].name);
3464				else
3465					retval = sbuf_printf(sb,
3466					    "\t<initiator>%u naa.%08jx</initiator>\n",
3467					    j, port->wwpn_iid[j].wwpn);
3468				if (retval != 0)
3469					break;
3470			}
3471			if (retval != 0)
3472				break;
3473
3474			retval = sbuf_printf(sb, "</targ_port>\n");
3475			if (retval != 0)
3476				break;
3477		}
3478		mtx_unlock(&softc->ctl_lock);
3479
3480		if ((retval != 0)
3481		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3482			retval = 0;
3483			sbuf_delete(sb);
3484			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3485			snprintf(list->error_str, sizeof(list->error_str),
3486				 "Out of space, %d bytes is too small",
3487				 list->alloc_len);
3488			break;
3489		}
3490
3491		sbuf_finish(sb);
3492
3493		retval = copyout(sbuf_data(sb), list->lun_xml,
3494				 sbuf_len(sb) + 1);
3495
3496		list->fill_len = sbuf_len(sb) + 1;
3497		list->status = CTL_LUN_LIST_OK;
3498		sbuf_delete(sb);
3499		break;
3500	}
3501	default: {
3502		/* XXX KDM should we fix this? */
3503#if 0
3504		struct ctl_backend_driver *backend;
3505		unsigned int type;
3506		int found;
3507
3508		found = 0;
3509
3510		/*
3511		 * We encode the backend type as the ioctl type for backend
3512		 * ioctls.  So parse it out here, and then search for a
3513		 * backend of this type.
3514		 */
3515		type = _IOC_TYPE(cmd);
3516
3517		STAILQ_FOREACH(backend, &softc->be_list, links) {
3518			if (backend->type == type) {
3519				found = 1;
3520				break;
3521			}
3522		}
3523		if (found == 0) {
3524			printf("ctl: unknown ioctl command %#lx or backend "
3525			       "%d\n", cmd, type);
3526			retval = EINVAL;
3527			break;
3528		}
3529		retval = backend->ioctl(dev, cmd, addr, flag, td);
3530#endif
3531		retval = ENOTTY;
3532		break;
3533	}
3534	}
3535	return (retval);
3536}
3537
3538uint32_t
3539ctl_get_initindex(struct ctl_nexus *nexus)
3540{
3541	if (nexus->targ_port < CTL_MAX_PORTS)
3542		return (nexus->initid.id +
3543			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3544	else
3545		return (nexus->initid.id +
3546		       ((nexus->targ_port - CTL_MAX_PORTS) *
3547			CTL_MAX_INIT_PER_PORT));
3548}
3549
3550uint32_t
3551ctl_get_resindex(struct ctl_nexus *nexus)
3552{
3553	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3554}
3555
3556uint32_t
3557ctl_port_idx(int port_num)
3558{
3559	if (port_num < CTL_MAX_PORTS)
3560		return(port_num);
3561	else
3562		return(port_num - CTL_MAX_PORTS);
3563}
3564
3565static uint32_t
3566ctl_map_lun(int port_num, uint32_t lun_id)
3567{
3568	struct ctl_port *port;
3569
3570	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3571	if (port == NULL)
3572		return (UINT32_MAX);
3573	if (port->lun_map == NULL)
3574		return (lun_id);
3575	return (port->lun_map(port->targ_lun_arg, lun_id));
3576}
3577
3578static uint32_t
3579ctl_map_lun_back(int port_num, uint32_t lun_id)
3580{
3581	struct ctl_port *port;
3582	uint32_t i;
3583
3584	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3585	if (port->lun_map == NULL)
3586		return (lun_id);
3587	for (i = 0; i < CTL_MAX_LUNS; i++) {
3588		if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3589			return (i);
3590	}
3591	return (UINT32_MAX);
3592}
3593
3594/*
3595 * Note:  This only works for bitmask sizes that are at least 32 bits, and
3596 * that are a power of 2.
3597 */
3598int
3599ctl_ffz(uint32_t *mask, uint32_t size)
3600{
3601	uint32_t num_chunks, num_pieces;
3602	int i, j;
3603
3604	num_chunks = (size >> 5);
3605	if (num_chunks == 0)
3606		num_chunks++;
3607	num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3608
3609	for (i = 0; i < num_chunks; i++) {
3610		for (j = 0; j < num_pieces; j++) {
3611			if ((mask[i] & (1 << j)) == 0)
3612				return ((i << 5) + j);
3613		}
3614	}
3615
3616	return (-1);
3617}
3618
3619int
3620ctl_set_mask(uint32_t *mask, uint32_t bit)
3621{
3622	uint32_t chunk, piece;
3623
3624	chunk = bit >> 5;
3625	piece = bit % (sizeof(uint32_t) * 8);
3626
3627	if ((mask[chunk] & (1 << piece)) != 0)
3628		return (-1);
3629	else
3630		mask[chunk] |= (1 << piece);
3631
3632	return (0);
3633}
3634
3635int
3636ctl_clear_mask(uint32_t *mask, uint32_t bit)
3637{
3638	uint32_t chunk, piece;
3639
3640	chunk = bit >> 5;
3641	piece = bit % (sizeof(uint32_t) * 8);
3642
3643	if ((mask[chunk] & (1 << piece)) == 0)
3644		return (-1);
3645	else
3646		mask[chunk] &= ~(1 << piece);
3647
3648	return (0);
3649}
3650
3651int
3652ctl_is_set(uint32_t *mask, uint32_t bit)
3653{
3654	uint32_t chunk, piece;
3655
3656	chunk = bit >> 5;
3657	piece = bit % (sizeof(uint32_t) * 8);
3658
3659	if ((mask[chunk] & (1 << piece)) == 0)
3660		return (0);
3661	else
3662		return (1);
3663}
3664
3665#ifdef unused
3666/*
3667 * The bus, target and lun are optional, they can be filled in later.
3668 * can_wait is used to determine whether we can wait on the malloc or not.
3669 */
3670union ctl_io*
3671ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3672	      uint32_t targ_lun, int can_wait)
3673{
3674	union ctl_io *io;
3675
3676	if (can_wait)
3677		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3678	else
3679		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3680
3681	if (io != NULL) {
3682		io->io_hdr.io_type = io_type;
3683		io->io_hdr.targ_port = targ_port;
3684		/*
3685		 * XXX KDM this needs to change/go away.  We need to move
3686		 * to a preallocated pool of ctl_scsiio structures.
3687		 */
3688		io->io_hdr.nexus.targ_target.id = targ_target;
3689		io->io_hdr.nexus.targ_lun = targ_lun;
3690	}
3691
3692	return (io);
3693}
3694
3695void
3696ctl_kfree_io(union ctl_io *io)
3697{
3698	free(io, M_CTL);
3699}
3700#endif /* unused */
3701
3702/*
3703 * ctl_softc, pool_type, total_ctl_io are passed in.
3704 * npool is passed out.
3705 */
3706int
3707ctl_pool_create(struct ctl_softc *ctl_softc, ctl_pool_type pool_type,
3708		uint32_t total_ctl_io, struct ctl_io_pool **npool)
3709{
3710	uint32_t i;
3711	union ctl_io *cur_io, *next_io;
3712	struct ctl_io_pool *pool;
3713	int retval;
3714
3715	retval = 0;
3716
3717	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3718					    M_NOWAIT | M_ZERO);
3719	if (pool == NULL) {
3720		retval = ENOMEM;
3721		goto bailout;
3722	}
3723
3724	pool->type = pool_type;
3725	pool->ctl_softc = ctl_softc;
3726
3727	mtx_lock(&ctl_softc->pool_lock);
3728	pool->id = ctl_softc->cur_pool_id++;
3729	mtx_unlock(&ctl_softc->pool_lock);
3730
3731	pool->flags = CTL_POOL_FLAG_NONE;
3732	pool->refcount = 1;		/* Reference for validity. */
3733	STAILQ_INIT(&pool->free_queue);
3734
3735	/*
3736	 * XXX KDM other options here:
3737	 * - allocate a page at a time
3738	 * - allocate one big chunk of memory.
3739	 * Page allocation might work well, but would take a little more
3740	 * tracking.
3741	 */
3742	for (i = 0; i < total_ctl_io; i++) {
3743		cur_io = (union ctl_io *)malloc(sizeof(*cur_io), M_CTLIO,
3744						M_NOWAIT);
3745		if (cur_io == NULL) {
3746			retval = ENOMEM;
3747			break;
3748		}
3749		cur_io->io_hdr.pool = pool;
3750		STAILQ_INSERT_TAIL(&pool->free_queue, &cur_io->io_hdr, links);
3751		pool->total_ctl_io++;
3752		pool->free_ctl_io++;
3753	}
3754
3755	if (retval != 0) {
3756		for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3757		     cur_io != NULL; cur_io = next_io) {
3758			next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3759							      links);
3760			STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr,
3761				      ctl_io_hdr, links);
3762			free(cur_io, M_CTLIO);
3763		}
3764
3765		free(pool, M_CTL);
3766		goto bailout;
3767	}
3768	mtx_lock(&ctl_softc->pool_lock);
3769	ctl_softc->num_pools++;
3770	STAILQ_INSERT_TAIL(&ctl_softc->io_pools, pool, links);
3771	/*
3772	 * Increment our usage count if this is an external consumer, so we
3773	 * can't get unloaded until the external consumer (most likely a
3774	 * FETD) unloads and frees his pool.
3775	 *
3776	 * XXX KDM will this increment the caller's module use count, or
3777	 * mine?
3778	 */
3779#if 0
3780	if ((pool_type != CTL_POOL_EMERGENCY)
3781	 && (pool_type != CTL_POOL_INTERNAL)
3782	 && (pool_type != CTL_POOL_4OTHERSC))
3783		MOD_INC_USE_COUNT;
3784#endif
3785
3786	mtx_unlock(&ctl_softc->pool_lock);
3787
3788	*npool = pool;
3789
3790bailout:
3791
3792	return (retval);
3793}
3794
3795static int
3796ctl_pool_acquire(struct ctl_io_pool *pool)
3797{
3798
3799	mtx_assert(&pool->ctl_softc->pool_lock, MA_OWNED);
3800
3801	if (pool->flags & CTL_POOL_FLAG_INVALID)
3802		return (EINVAL);
3803
3804	pool->refcount++;
3805
3806	return (0);
3807}
3808
3809static void
3810ctl_pool_release(struct ctl_io_pool *pool)
3811{
3812	struct ctl_softc *ctl_softc = pool->ctl_softc;
3813	union ctl_io *io;
3814
3815	mtx_assert(&ctl_softc->pool_lock, MA_OWNED);
3816
3817	if (--pool->refcount != 0)
3818		return;
3819
3820	while ((io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue)) != NULL) {
3821		STAILQ_REMOVE(&pool->free_queue, &io->io_hdr, ctl_io_hdr,
3822			      links);
3823		free(io, M_CTLIO);
3824	}
3825
3826	STAILQ_REMOVE(&ctl_softc->io_pools, pool, ctl_io_pool, links);
3827	ctl_softc->num_pools--;
3828
3829	/*
3830	 * XXX KDM will this decrement the caller's usage count or mine?
3831	 */
3832#if 0
3833	if ((pool->type != CTL_POOL_EMERGENCY)
3834	 && (pool->type != CTL_POOL_INTERNAL)
3835	 && (pool->type != CTL_POOL_4OTHERSC))
3836		MOD_DEC_USE_COUNT;
3837#endif
3838
3839	free(pool, M_CTL);
3840}
3841
3842void
3843ctl_pool_free(struct ctl_io_pool *pool)
3844{
3845	struct ctl_softc *ctl_softc;
3846
3847	if (pool == NULL)
3848		return;
3849
3850	ctl_softc = pool->ctl_softc;
3851	mtx_lock(&ctl_softc->pool_lock);
3852	pool->flags |= CTL_POOL_FLAG_INVALID;
3853	ctl_pool_release(pool);
3854	mtx_unlock(&ctl_softc->pool_lock);
3855}
3856
3857/*
3858 * This routine does not block (except for spinlocks of course).
3859 * It tries to allocate a ctl_io union from the caller's pool as quickly as
3860 * possible.
3861 */
3862union ctl_io *
3863ctl_alloc_io(void *pool_ref)
3864{
3865	union ctl_io *io;
3866	struct ctl_softc *ctl_softc;
3867	struct ctl_io_pool *pool, *npool;
3868	struct ctl_io_pool *emergency_pool;
3869
3870	pool = (struct ctl_io_pool *)pool_ref;
3871
3872	if (pool == NULL) {
3873		printf("%s: pool is NULL\n", __func__);
3874		return (NULL);
3875	}
3876
3877	emergency_pool = NULL;
3878
3879	ctl_softc = pool->ctl_softc;
3880
3881	mtx_lock(&ctl_softc->pool_lock);
3882	/*
3883	 * First, try to get the io structure from the user's pool.
3884	 */
3885	if (ctl_pool_acquire(pool) == 0) {
3886		io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3887		if (io != NULL) {
3888			STAILQ_REMOVE_HEAD(&pool->free_queue, links);
3889			pool->total_allocated++;
3890			pool->free_ctl_io--;
3891			mtx_unlock(&ctl_softc->pool_lock);
3892			return (io);
3893		} else
3894			ctl_pool_release(pool);
3895	}
3896	/*
3897	 * If he doesn't have any io structures left, search for an
3898	 * emergency pool and grab one from there.
3899	 */
3900	STAILQ_FOREACH(npool, &ctl_softc->io_pools, links) {
3901		if (npool->type != CTL_POOL_EMERGENCY)
3902			continue;
3903
3904		if (ctl_pool_acquire(npool) != 0)
3905			continue;
3906
3907		emergency_pool = npool;
3908
3909		io = (union ctl_io *)STAILQ_FIRST(&npool->free_queue);
3910		if (io != NULL) {
3911			STAILQ_REMOVE_HEAD(&npool->free_queue, links);
3912			npool->total_allocated++;
3913			npool->free_ctl_io--;
3914			mtx_unlock(&ctl_softc->pool_lock);
3915			return (io);
3916		} else
3917			ctl_pool_release(npool);
3918	}
3919
3920	/* Drop the spinlock before we malloc */
3921	mtx_unlock(&ctl_softc->pool_lock);
3922
3923	/*
3924	 * The emergency pool (if it exists) didn't have one, so try an
3925	 * atomic (i.e. nonblocking) malloc and see if we get lucky.
3926	 */
3927	io = (union ctl_io *)malloc(sizeof(*io), M_CTLIO, M_NOWAIT);
3928	if (io != NULL) {
3929		/*
3930		 * If the emergency pool exists but is empty, add this
3931		 * ctl_io to its list when it gets freed.
3932		 */
3933		if (emergency_pool != NULL) {
3934			mtx_lock(&ctl_softc->pool_lock);
3935			if (ctl_pool_acquire(emergency_pool) == 0) {
3936				io->io_hdr.pool = emergency_pool;
3937				emergency_pool->total_ctl_io++;
3938				/*
3939				 * Need to bump this, otherwise
3940				 * total_allocated and total_freed won't
3941				 * match when we no longer have anything
3942				 * outstanding.
3943				 */
3944				emergency_pool->total_allocated++;
3945			}
3946			mtx_unlock(&ctl_softc->pool_lock);
3947		} else
3948			io->io_hdr.pool = NULL;
3949	}
3950
3951	return (io);
3952}
3953
3954void
3955ctl_free_io(union ctl_io *io)
3956{
3957	if (io == NULL)
3958		return;
3959
3960	/*
3961	 * If this ctl_io has a pool, return it to that pool.
3962	 */
3963	if (io->io_hdr.pool != NULL) {
3964		struct ctl_io_pool *pool;
3965
3966		pool = (struct ctl_io_pool *)io->io_hdr.pool;
3967		mtx_lock(&pool->ctl_softc->pool_lock);
3968		io->io_hdr.io_type = 0xff;
3969		STAILQ_INSERT_TAIL(&pool->free_queue, &io->io_hdr, links);
3970		pool->total_freed++;
3971		pool->free_ctl_io++;
3972		ctl_pool_release(pool);
3973		mtx_unlock(&pool->ctl_softc->pool_lock);
3974	} else {
3975		/*
3976		 * Otherwise, just free it.  We probably malloced it and
3977		 * the emergency pool wasn't available.
3978		 */
3979		free(io, M_CTLIO);
3980	}
3981
3982}
3983
3984void
3985ctl_zero_io(union ctl_io *io)
3986{
3987	void *pool_ref;
3988
3989	if (io == NULL)
3990		return;
3991
3992	/*
3993	 * May need to preserve linked list pointers at some point too.
3994	 */
3995	pool_ref = io->io_hdr.pool;
3996
3997	memset(io, 0, sizeof(*io));
3998
3999	io->io_hdr.pool = pool_ref;
4000}
4001
4002/*
4003 * This routine is currently used for internal copies of ctl_ios that need
4004 * to persist for some reason after we've already returned status to the
4005 * FETD.  (Thus the flag set.)
4006 *
4007 * XXX XXX
4008 * Note that this makes a blind copy of all fields in the ctl_io, except
4009 * for the pool reference.  This includes any memory that has been
4010 * allocated!  That memory will no longer be valid after done has been
4011 * called, so this would be VERY DANGEROUS for command that actually does
4012 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
4013 * start and stop commands, which don't transfer any data, so this is not a
4014 * problem.  If it is used for anything else, the caller would also need to
4015 * allocate data buffer space and this routine would need to be modified to
4016 * copy the data buffer(s) as well.
4017 */
4018void
4019ctl_copy_io(union ctl_io *src, union ctl_io *dest)
4020{
4021	void *pool_ref;
4022
4023	if ((src == NULL)
4024	 || (dest == NULL))
4025		return;
4026
4027	/*
4028	 * May need to preserve linked list pointers at some point too.
4029	 */
4030	pool_ref = dest->io_hdr.pool;
4031
4032	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
4033
4034	dest->io_hdr.pool = pool_ref;
4035	/*
4036	 * We need to know that this is an internal copy, and doesn't need
4037	 * to get passed back to the FETD that allocated it.
4038	 */
4039	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
4040}
4041
4042static int
4043ctl_expand_number(const char *buf, uint64_t *num)
4044{
4045	char *endptr;
4046	uint64_t number;
4047	unsigned shift;
4048
4049	number = strtoq(buf, &endptr, 0);
4050
4051	switch (tolower((unsigned char)*endptr)) {
4052	case 'e':
4053		shift = 60;
4054		break;
4055	case 'p':
4056		shift = 50;
4057		break;
4058	case 't':
4059		shift = 40;
4060		break;
4061	case 'g':
4062		shift = 30;
4063		break;
4064	case 'm':
4065		shift = 20;
4066		break;
4067	case 'k':
4068		shift = 10;
4069		break;
4070	case 'b':
4071	case '\0': /* No unit. */
4072		*num = number;
4073		return (0);
4074	default:
4075		/* Unrecognized unit. */
4076		return (-1);
4077	}
4078
4079	if ((number << shift) >> shift != number) {
4080		/* Overflow */
4081		return (-1);
4082	}
4083	*num = number << shift;
4084	return (0);
4085}
4086
4087
4088/*
4089 * This routine could be used in the future to load default and/or saved
4090 * mode page parameters for a particuar lun.
4091 */
4092static int
4093ctl_init_page_index(struct ctl_lun *lun)
4094{
4095	int i;
4096	struct ctl_page_index *page_index;
4097	const char *value;
4098	uint64_t ival;
4099
4100	memcpy(&lun->mode_pages.index, page_index_template,
4101	       sizeof(page_index_template));
4102
4103	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4104
4105		page_index = &lun->mode_pages.index[i];
4106		/*
4107		 * If this is a disk-only mode page, there's no point in
4108		 * setting it up.  For some pages, we have to have some
4109		 * basic information about the disk in order to calculate the
4110		 * mode page data.
4111		 */
4112		if ((lun->be_lun->lun_type != T_DIRECT)
4113		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4114			continue;
4115
4116		switch (page_index->page_code & SMPH_PC_MASK) {
4117		case SMS_RW_ERROR_RECOVERY_PAGE: {
4118			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4119				panic("subpage is incorrect!");
4120			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
4121			       &rw_er_page_default,
4122			       sizeof(rw_er_page_default));
4123			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
4124			       &rw_er_page_changeable,
4125			       sizeof(rw_er_page_changeable));
4126			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
4127			       &rw_er_page_default,
4128			       sizeof(rw_er_page_default));
4129			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
4130			       &rw_er_page_default,
4131			       sizeof(rw_er_page_default));
4132			page_index->page_data =
4133				(uint8_t *)lun->mode_pages.rw_er_page;
4134			break;
4135		}
4136		case SMS_FORMAT_DEVICE_PAGE: {
4137			struct scsi_format_page *format_page;
4138
4139			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4140				panic("subpage is incorrect!");
4141
4142			/*
4143			 * Sectors per track are set above.  Bytes per
4144			 * sector need to be set here on a per-LUN basis.
4145			 */
4146			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4147			       &format_page_default,
4148			       sizeof(format_page_default));
4149			memcpy(&lun->mode_pages.format_page[
4150			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4151			       sizeof(format_page_changeable));
4152			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4153			       &format_page_default,
4154			       sizeof(format_page_default));
4155			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4156			       &format_page_default,
4157			       sizeof(format_page_default));
4158
4159			format_page = &lun->mode_pages.format_page[
4160				CTL_PAGE_CURRENT];
4161			scsi_ulto2b(lun->be_lun->blocksize,
4162				    format_page->bytes_per_sector);
4163
4164			format_page = &lun->mode_pages.format_page[
4165				CTL_PAGE_DEFAULT];
4166			scsi_ulto2b(lun->be_lun->blocksize,
4167				    format_page->bytes_per_sector);
4168
4169			format_page = &lun->mode_pages.format_page[
4170				CTL_PAGE_SAVED];
4171			scsi_ulto2b(lun->be_lun->blocksize,
4172				    format_page->bytes_per_sector);
4173
4174			page_index->page_data =
4175				(uint8_t *)lun->mode_pages.format_page;
4176			break;
4177		}
4178		case SMS_RIGID_DISK_PAGE: {
4179			struct scsi_rigid_disk_page *rigid_disk_page;
4180			uint32_t sectors_per_cylinder;
4181			uint64_t cylinders;
4182#ifndef	__XSCALE__
4183			int shift;
4184#endif /* !__XSCALE__ */
4185
4186			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4187				panic("invalid subpage value %d",
4188				      page_index->subpage);
4189
4190			/*
4191			 * Rotation rate and sectors per track are set
4192			 * above.  We calculate the cylinders here based on
4193			 * capacity.  Due to the number of heads and
4194			 * sectors per track we're using, smaller arrays
4195			 * may turn out to have 0 cylinders.  Linux and
4196			 * FreeBSD don't pay attention to these mode pages
4197			 * to figure out capacity, but Solaris does.  It
4198			 * seems to deal with 0 cylinders just fine, and
4199			 * works out a fake geometry based on the capacity.
4200			 */
4201			memcpy(&lun->mode_pages.rigid_disk_page[
4202			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4203			       sizeof(rigid_disk_page_default));
4204			memcpy(&lun->mode_pages.rigid_disk_page[
4205			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4206			       sizeof(rigid_disk_page_changeable));
4207
4208			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4209				CTL_DEFAULT_HEADS;
4210
4211			/*
4212			 * The divide method here will be more accurate,
4213			 * probably, but results in floating point being
4214			 * used in the kernel on i386 (__udivdi3()).  On the
4215			 * XScale, though, __udivdi3() is implemented in
4216			 * software.
4217			 *
4218			 * The shift method for cylinder calculation is
4219			 * accurate if sectors_per_cylinder is a power of
4220			 * 2.  Otherwise it might be slightly off -- you
4221			 * might have a bit of a truncation problem.
4222			 */
4223#ifdef	__XSCALE__
4224			cylinders = (lun->be_lun->maxlba + 1) /
4225				sectors_per_cylinder;
4226#else
4227			for (shift = 31; shift > 0; shift--) {
4228				if (sectors_per_cylinder & (1 << shift))
4229					break;
4230			}
4231			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4232#endif
4233
4234			/*
4235			 * We've basically got 3 bytes, or 24 bits for the
4236			 * cylinder size in the mode page.  If we're over,
4237			 * just round down to 2^24.
4238			 */
4239			if (cylinders > 0xffffff)
4240				cylinders = 0xffffff;
4241
4242			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4243				CTL_PAGE_DEFAULT];
4244			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4245
4246			if ((value = ctl_get_opt(&lun->be_lun->options,
4247			    "rpm")) != NULL) {
4248				scsi_ulto2b(strtol(value, NULL, 0),
4249				     rigid_disk_page->rotation_rate);
4250			}
4251
4252			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4253			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4254			       sizeof(rigid_disk_page_default));
4255			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4256			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4257			       sizeof(rigid_disk_page_default));
4258
4259			page_index->page_data =
4260				(uint8_t *)lun->mode_pages.rigid_disk_page;
4261			break;
4262		}
4263		case SMS_CACHING_PAGE: {
4264			struct scsi_caching_page *caching_page;
4265
4266			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4267				panic("invalid subpage value %d",
4268				      page_index->subpage);
4269			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4270			       &caching_page_default,
4271			       sizeof(caching_page_default));
4272			memcpy(&lun->mode_pages.caching_page[
4273			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4274			       sizeof(caching_page_changeable));
4275			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4276			       &caching_page_default,
4277			       sizeof(caching_page_default));
4278			caching_page = &lun->mode_pages.caching_page[
4279			    CTL_PAGE_SAVED];
4280			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4281			if (value != NULL && strcmp(value, "off") == 0)
4282				caching_page->flags1 &= ~SCP_WCE;
4283			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4284			if (value != NULL && strcmp(value, "off") == 0)
4285				caching_page->flags1 |= SCP_RCD;
4286			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4287			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4288			       sizeof(caching_page_default));
4289			page_index->page_data =
4290				(uint8_t *)lun->mode_pages.caching_page;
4291			break;
4292		}
4293		case SMS_CONTROL_MODE_PAGE: {
4294			struct scsi_control_page *control_page;
4295
4296			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4297				panic("invalid subpage value %d",
4298				      page_index->subpage);
4299
4300			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4301			       &control_page_default,
4302			       sizeof(control_page_default));
4303			memcpy(&lun->mode_pages.control_page[
4304			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4305			       sizeof(control_page_changeable));
4306			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4307			       &control_page_default,
4308			       sizeof(control_page_default));
4309			control_page = &lun->mode_pages.control_page[
4310			    CTL_PAGE_SAVED];
4311			value = ctl_get_opt(&lun->be_lun->options, "reordering");
4312			if (value != NULL && strcmp(value, "unrestricted") == 0) {
4313				control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4314				control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4315			}
4316			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4317			       &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4318			       sizeof(control_page_default));
4319			page_index->page_data =
4320				(uint8_t *)lun->mode_pages.control_page;
4321			break;
4322
4323		}
4324		case SMS_INFO_EXCEPTIONS_PAGE: {
4325			switch (page_index->subpage) {
4326			case SMS_SUBPAGE_PAGE_0:
4327				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4328				       &ie_page_default,
4329				       sizeof(ie_page_default));
4330				memcpy(&lun->mode_pages.ie_page[
4331				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4332				       sizeof(ie_page_changeable));
4333				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4334				       &ie_page_default,
4335				       sizeof(ie_page_default));
4336				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4337				       &ie_page_default,
4338				       sizeof(ie_page_default));
4339				page_index->page_data =
4340					(uint8_t *)lun->mode_pages.ie_page;
4341				break;
4342			case 0x02: {
4343				struct ctl_logical_block_provisioning_page *page;
4344
4345				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4346				       &lbp_page_default,
4347				       sizeof(lbp_page_default));
4348				memcpy(&lun->mode_pages.lbp_page[
4349				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4350				       sizeof(lbp_page_changeable));
4351				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4352				       &lbp_page_default,
4353				       sizeof(lbp_page_default));
4354				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4355				value = ctl_get_opt(&lun->be_lun->options,
4356				    "avail-threshold");
4357				if (value != NULL &&
4358				    ctl_expand_number(value, &ival) == 0) {
4359					page->descr[0].flags |= SLBPPD_ENABLED |
4360					    SLBPPD_ARMING_DEC;
4361					if (lun->be_lun->blocksize)
4362						ival /= lun->be_lun->blocksize;
4363					else
4364						ival /= 512;
4365					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4366					    page->descr[0].count);
4367				}
4368				value = ctl_get_opt(&lun->be_lun->options,
4369				    "used-threshold");
4370				if (value != NULL &&
4371				    ctl_expand_number(value, &ival) == 0) {
4372					page->descr[1].flags |= SLBPPD_ENABLED |
4373					    SLBPPD_ARMING_INC;
4374					if (lun->be_lun->blocksize)
4375						ival /= lun->be_lun->blocksize;
4376					else
4377						ival /= 512;
4378					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4379					    page->descr[1].count);
4380				}
4381				value = ctl_get_opt(&lun->be_lun->options,
4382				    "pool-avail-threshold");
4383				if (value != NULL &&
4384				    ctl_expand_number(value, &ival) == 0) {
4385					page->descr[2].flags |= SLBPPD_ENABLED |
4386					    SLBPPD_ARMING_DEC;
4387					if (lun->be_lun->blocksize)
4388						ival /= lun->be_lun->blocksize;
4389					else
4390						ival /= 512;
4391					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4392					    page->descr[2].count);
4393				}
4394				value = ctl_get_opt(&lun->be_lun->options,
4395				    "pool-used-threshold");
4396				if (value != NULL &&
4397				    ctl_expand_number(value, &ival) == 0) {
4398					page->descr[3].flags |= SLBPPD_ENABLED |
4399					    SLBPPD_ARMING_INC;
4400					if (lun->be_lun->blocksize)
4401						ival /= lun->be_lun->blocksize;
4402					else
4403						ival /= 512;
4404					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4405					    page->descr[3].count);
4406				}
4407				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4408				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4409				       sizeof(lbp_page_default));
4410				page_index->page_data =
4411					(uint8_t *)lun->mode_pages.lbp_page;
4412			}}
4413			break;
4414		}
4415		case SMS_VENDOR_SPECIFIC_PAGE:{
4416			switch (page_index->subpage) {
4417			case DBGCNF_SUBPAGE_CODE: {
4418				struct copan_debugconf_subpage *current_page,
4419							       *saved_page;
4420
4421				memcpy(&lun->mode_pages.debugconf_subpage[
4422				       CTL_PAGE_CURRENT],
4423				       &debugconf_page_default,
4424				       sizeof(debugconf_page_default));
4425				memcpy(&lun->mode_pages.debugconf_subpage[
4426				       CTL_PAGE_CHANGEABLE],
4427				       &debugconf_page_changeable,
4428				       sizeof(debugconf_page_changeable));
4429				memcpy(&lun->mode_pages.debugconf_subpage[
4430				       CTL_PAGE_DEFAULT],
4431				       &debugconf_page_default,
4432				       sizeof(debugconf_page_default));
4433				memcpy(&lun->mode_pages.debugconf_subpage[
4434				       CTL_PAGE_SAVED],
4435				       &debugconf_page_default,
4436				       sizeof(debugconf_page_default));
4437				page_index->page_data =
4438					(uint8_t *)lun->mode_pages.debugconf_subpage;
4439
4440				current_page = (struct copan_debugconf_subpage *)
4441					(page_index->page_data +
4442					 (page_index->page_len *
4443					  CTL_PAGE_CURRENT));
4444				saved_page = (struct copan_debugconf_subpage *)
4445					(page_index->page_data +
4446					 (page_index->page_len *
4447					  CTL_PAGE_SAVED));
4448				break;
4449			}
4450			default:
4451				panic("invalid subpage value %d",
4452				      page_index->subpage);
4453				break;
4454			}
4455   			break;
4456		}
4457		default:
4458			panic("invalid page value %d",
4459			      page_index->page_code & SMPH_PC_MASK);
4460			break;
4461    	}
4462	}
4463
4464	return (CTL_RETVAL_COMPLETE);
4465}
4466
4467static int
4468ctl_init_log_page_index(struct ctl_lun *lun)
4469{
4470	struct ctl_page_index *page_index;
4471	int i, j, k, prev;
4472
4473	memcpy(&lun->log_pages.index, log_page_index_template,
4474	       sizeof(log_page_index_template));
4475
4476	prev = -1;
4477	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4478
4479		page_index = &lun->log_pages.index[i];
4480		/*
4481		 * If this is a disk-only mode page, there's no point in
4482		 * setting it up.  For some pages, we have to have some
4483		 * basic information about the disk in order to calculate the
4484		 * mode page data.
4485		 */
4486		if ((lun->be_lun->lun_type != T_DIRECT)
4487		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4488			continue;
4489
4490		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4491		    ((lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) == 0 ||
4492		     lun->backend->lun_attr == NULL))
4493			continue;
4494
4495		if (page_index->page_code != prev) {
4496			lun->log_pages.pages_page[j] = page_index->page_code;
4497			prev = page_index->page_code;
4498			j++;
4499		}
4500		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4501		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4502		k++;
4503	}
4504	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4505	lun->log_pages.index[0].page_len = j;
4506	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4507	lun->log_pages.index[1].page_len = k * 2;
4508	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4509	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4510
4511	return (CTL_RETVAL_COMPLETE);
4512}
4513
4514static int
4515hex2bin(const char *str, uint8_t *buf, int buf_size)
4516{
4517	int i;
4518	u_char c;
4519
4520	memset(buf, 0, buf_size);
4521	while (isspace(str[0]))
4522		str++;
4523	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4524		str += 2;
4525	buf_size *= 2;
4526	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4527		c = str[i];
4528		if (isdigit(c))
4529			c -= '0';
4530		else if (isalpha(c))
4531			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4532		else
4533			break;
4534		if (c >= 16)
4535			break;
4536		if ((i & 1) == 0)
4537			buf[i / 2] |= (c << 4);
4538		else
4539			buf[i / 2] |= c;
4540	}
4541	return ((i + 1) / 2);
4542}
4543
4544/*
4545 * LUN allocation.
4546 *
4547 * Requirements:
4548 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4549 *   wants us to allocate the LUN and he can block.
4550 * - ctl_softc is always set
4551 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4552 *
4553 * Returns 0 for success, non-zero (errno) for failure.
4554 */
4555static int
4556ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4557	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4558{
4559	struct ctl_lun *nlun, *lun;
4560	struct ctl_port *port;
4561	struct scsi_vpd_id_descriptor *desc;
4562	struct scsi_vpd_id_t10 *t10id;
4563	const char *eui, *naa, *scsiname, *vendor, *value;
4564	int lun_number, i, lun_malloced;
4565	int devidlen, idlen1, idlen2 = 0, len;
4566
4567	if (be_lun == NULL)
4568		return (EINVAL);
4569
4570	/*
4571	 * We currently only support Direct Access or Processor LUN types.
4572	 */
4573	switch (be_lun->lun_type) {
4574	case T_DIRECT:
4575		break;
4576	case T_PROCESSOR:
4577		break;
4578	case T_SEQUENTIAL:
4579	case T_CHANGER:
4580	default:
4581		be_lun->lun_config_status(be_lun->be_lun,
4582					  CTL_LUN_CONFIG_FAILURE);
4583		break;
4584	}
4585	if (ctl_lun == NULL) {
4586		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4587		lun_malloced = 1;
4588	} else {
4589		lun_malloced = 0;
4590		lun = ctl_lun;
4591	}
4592
4593	memset(lun, 0, sizeof(*lun));
4594	if (lun_malloced)
4595		lun->flags = CTL_LUN_MALLOCED;
4596
4597	/* Generate LUN ID. */
4598	devidlen = max(CTL_DEVID_MIN_LEN,
4599	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4600	idlen1 = sizeof(*t10id) + devidlen;
4601	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4602	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4603	if (scsiname != NULL) {
4604		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4605		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4606	}
4607	eui = ctl_get_opt(&be_lun->options, "eui");
4608	if (eui != NULL) {
4609		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4610	}
4611	naa = ctl_get_opt(&be_lun->options, "naa");
4612	if (naa != NULL) {
4613		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4614	}
4615	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4616	    M_CTL, M_WAITOK | M_ZERO);
4617	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4618	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4619	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4620	desc->length = idlen1;
4621	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4622	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4623	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4624		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4625	} else {
4626		strncpy(t10id->vendor, vendor,
4627		    min(sizeof(t10id->vendor), strlen(vendor)));
4628	}
4629	strncpy((char *)t10id->vendor_spec_id,
4630	    (char *)be_lun->device_id, devidlen);
4631	if (scsiname != NULL) {
4632		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4633		    desc->length);
4634		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4635		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4636		    SVPD_ID_TYPE_SCSI_NAME;
4637		desc->length = idlen2;
4638		strlcpy(desc->identifier, scsiname, idlen2);
4639	}
4640	if (eui != NULL) {
4641		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4642		    desc->length);
4643		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4644		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4645		    SVPD_ID_TYPE_EUI64;
4646		desc->length = hex2bin(eui, desc->identifier, 16);
4647		desc->length = desc->length > 12 ? 16 :
4648		    (desc->length > 8 ? 12 : 8);
4649		len -= 16 - desc->length;
4650	}
4651	if (naa != NULL) {
4652		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4653		    desc->length);
4654		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4655		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4656		    SVPD_ID_TYPE_NAA;
4657		desc->length = hex2bin(naa, desc->identifier, 16);
4658		desc->length = desc->length > 8 ? 16 : 8;
4659		len -= 16 - desc->length;
4660	}
4661	lun->lun_devid->len = len;
4662
4663	mtx_lock(&ctl_softc->ctl_lock);
4664	/*
4665	 * See if the caller requested a particular LUN number.  If so, see
4666	 * if it is available.  Otherwise, allocate the first available LUN.
4667	 */
4668	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4669		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4670		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4671			mtx_unlock(&ctl_softc->ctl_lock);
4672			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4673				printf("ctl: requested LUN ID %d is higher "
4674				       "than CTL_MAX_LUNS - 1 (%d)\n",
4675				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4676			} else {
4677				/*
4678				 * XXX KDM return an error, or just assign
4679				 * another LUN ID in this case??
4680				 */
4681				printf("ctl: requested LUN ID %d is already "
4682				       "in use\n", be_lun->req_lun_id);
4683			}
4684			if (lun->flags & CTL_LUN_MALLOCED)
4685				free(lun, M_CTL);
4686			be_lun->lun_config_status(be_lun->be_lun,
4687						  CTL_LUN_CONFIG_FAILURE);
4688			return (ENOSPC);
4689		}
4690		lun_number = be_lun->req_lun_id;
4691	} else {
4692		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4693		if (lun_number == -1) {
4694			mtx_unlock(&ctl_softc->ctl_lock);
4695			printf("ctl: can't allocate LUN on target %ju, out of "
4696			       "LUNs\n", (uintmax_t)target_id.id);
4697			if (lun->flags & CTL_LUN_MALLOCED)
4698				free(lun, M_CTL);
4699			be_lun->lun_config_status(be_lun->be_lun,
4700						  CTL_LUN_CONFIG_FAILURE);
4701			return (ENOSPC);
4702		}
4703	}
4704	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4705
4706	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4707	lun->target = target_id;
4708	lun->lun = lun_number;
4709	lun->be_lun = be_lun;
4710	/*
4711	 * The processor LUN is always enabled.  Disk LUNs come on line
4712	 * disabled, and must be enabled by the backend.
4713	 */
4714	lun->flags |= CTL_LUN_DISABLED;
4715	lun->backend = be_lun->be;
4716	be_lun->ctl_lun = lun;
4717	be_lun->lun_id = lun_number;
4718	atomic_add_int(&be_lun->be->num_luns, 1);
4719	if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4720		lun->flags |= CTL_LUN_OFFLINE;
4721
4722	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4723		lun->flags |= CTL_LUN_STOPPED;
4724
4725	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4726		lun->flags |= CTL_LUN_INOPERABLE;
4727
4728	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4729		lun->flags |= CTL_LUN_PRIMARY_SC;
4730
4731	value = ctl_get_opt(&be_lun->options, "readonly");
4732	if (value != NULL && strcmp(value, "on") == 0)
4733		lun->flags |= CTL_LUN_READONLY;
4734
4735	lun->ctl_softc = ctl_softc;
4736	TAILQ_INIT(&lun->ooa_queue);
4737	TAILQ_INIT(&lun->blocked_queue);
4738	STAILQ_INIT(&lun->error_list);
4739	ctl_tpc_lun_init(lun);
4740
4741	/*
4742	 * Initialize the mode and log page index.
4743	 */
4744	ctl_init_page_index(lun);
4745	ctl_init_log_page_index(lun);
4746
4747	/*
4748	 * Set the poweron UA for all initiators on this LUN only.
4749	 */
4750	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4751		lun->pending_ua[i] = CTL_UA_POWERON;
4752
4753	/*
4754	 * Now, before we insert this lun on the lun list, set the lun
4755	 * inventory changed UA for all other luns.
4756	 */
4757	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4758		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4759			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4760		}
4761	}
4762
4763	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4764
4765	ctl_softc->ctl_luns[lun_number] = lun;
4766
4767	ctl_softc->num_luns++;
4768
4769	/* Setup statistics gathering */
4770	lun->stats.device_type = be_lun->lun_type;
4771	lun->stats.lun_number = lun_number;
4772	if (lun->stats.device_type == T_DIRECT)
4773		lun->stats.blocksize = be_lun->blocksize;
4774	else
4775		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4776	for (i = 0;i < CTL_MAX_PORTS;i++)
4777		lun->stats.ports[i].targ_port = i;
4778
4779	mtx_unlock(&ctl_softc->ctl_lock);
4780
4781	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4782
4783	/*
4784	 * Run through each registered FETD and bring it online if it isn't
4785	 * already.  Enable the target ID if it hasn't been enabled, and
4786	 * enable this particular LUN.
4787	 */
4788	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4789		int retval;
4790
4791		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4792		if (retval != 0) {
4793			printf("ctl_alloc_lun: FETD %s port %d returned error "
4794			       "%d for lun_enable on target %ju lun %d\n",
4795			       port->port_name, port->targ_port, retval,
4796			       (uintmax_t)target_id.id, lun_number);
4797		} else
4798			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4799	}
4800	return (0);
4801}
4802
4803/*
4804 * Delete a LUN.
4805 * Assumptions:
4806 * - LUN has already been marked invalid and any pending I/O has been taken
4807 *   care of.
4808 */
4809static int
4810ctl_free_lun(struct ctl_lun *lun)
4811{
4812	struct ctl_softc *softc;
4813#if 0
4814	struct ctl_port *port;
4815#endif
4816	struct ctl_lun *nlun;
4817	int i;
4818
4819	softc = lun->ctl_softc;
4820
4821	mtx_assert(&softc->ctl_lock, MA_OWNED);
4822
4823	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4824
4825	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4826
4827	softc->ctl_luns[lun->lun] = NULL;
4828
4829	if (!TAILQ_EMPTY(&lun->ooa_queue))
4830		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4831
4832	softc->num_luns--;
4833
4834	/*
4835	 * XXX KDM this scheme only works for a single target/multiple LUN
4836	 * setup.  It needs to be revamped for a multiple target scheme.
4837	 *
4838	 * XXX KDM this results in port->lun_disable() getting called twice,
4839	 * once when ctl_disable_lun() is called, and a second time here.
4840	 * We really need to re-think the LUN disable semantics.  There
4841	 * should probably be several steps/levels to LUN removal:
4842	 *  - disable
4843	 *  - invalidate
4844	 *  - free
4845 	 *
4846	 * Right now we only have a disable method when communicating to
4847	 * the front end ports, at least for individual LUNs.
4848	 */
4849#if 0
4850	STAILQ_FOREACH(port, &softc->port_list, links) {
4851		int retval;
4852
4853		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4854					 lun->lun);
4855		if (retval != 0) {
4856			printf("ctl_free_lun: FETD %s port %d returned error "
4857			       "%d for lun_disable on target %ju lun %jd\n",
4858			       port->port_name, port->targ_port, retval,
4859			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4860		}
4861
4862		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4863			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4864
4865			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4866			if (retval != 0) {
4867				printf("ctl_free_lun: FETD %s port %d "
4868				       "returned error %d for targ_disable on "
4869				       "target %ju\n", port->port_name,
4870				       port->targ_port, retval,
4871				       (uintmax_t)lun->target.id);
4872			} else
4873				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4874
4875			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4876				continue;
4877
4878#if 0
4879			port->port_offline(port->onoff_arg);
4880			port->status &= ~CTL_PORT_STATUS_ONLINE;
4881#endif
4882		}
4883	}
4884#endif
4885
4886	/*
4887	 * Tell the backend to free resources, if this LUN has a backend.
4888	 */
4889	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4890	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4891
4892	ctl_tpc_lun_shutdown(lun);
4893	mtx_destroy(&lun->lun_lock);
4894	free(lun->lun_devid, M_CTL);
4895	free(lun->write_buffer, M_CTL);
4896	if (lun->flags & CTL_LUN_MALLOCED)
4897		free(lun, M_CTL);
4898
4899	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4900		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4901			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4902		}
4903	}
4904
4905	return (0);
4906}
4907
4908static void
4909ctl_create_lun(struct ctl_be_lun *be_lun)
4910{
4911	struct ctl_softc *ctl_softc;
4912
4913	ctl_softc = control_softc;
4914
4915	/*
4916	 * ctl_alloc_lun() should handle all potential failure cases.
4917	 */
4918	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4919}
4920
4921int
4922ctl_add_lun(struct ctl_be_lun *be_lun)
4923{
4924	struct ctl_softc *ctl_softc = control_softc;
4925
4926	mtx_lock(&ctl_softc->ctl_lock);
4927	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4928	mtx_unlock(&ctl_softc->ctl_lock);
4929	wakeup(&ctl_softc->pending_lun_queue);
4930
4931	return (0);
4932}
4933
4934int
4935ctl_enable_lun(struct ctl_be_lun *be_lun)
4936{
4937	struct ctl_softc *ctl_softc;
4938	struct ctl_port *port, *nport;
4939	struct ctl_lun *lun;
4940	int retval;
4941
4942	ctl_softc = control_softc;
4943
4944	lun = (struct ctl_lun *)be_lun->ctl_lun;
4945
4946	mtx_lock(&ctl_softc->ctl_lock);
4947	mtx_lock(&lun->lun_lock);
4948	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4949		/*
4950		 * eh?  Why did we get called if the LUN is already
4951		 * enabled?
4952		 */
4953		mtx_unlock(&lun->lun_lock);
4954		mtx_unlock(&ctl_softc->ctl_lock);
4955		return (0);
4956	}
4957	lun->flags &= ~CTL_LUN_DISABLED;
4958	mtx_unlock(&lun->lun_lock);
4959
4960	for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4961		nport = STAILQ_NEXT(port, links);
4962
4963		/*
4964		 * Drop the lock while we call the FETD's enable routine.
4965		 * This can lead to a callback into CTL (at least in the
4966		 * case of the internal initiator frontend.
4967		 */
4968		mtx_unlock(&ctl_softc->ctl_lock);
4969		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4970		mtx_lock(&ctl_softc->ctl_lock);
4971		if (retval != 0) {
4972			printf("%s: FETD %s port %d returned error "
4973			       "%d for lun_enable on target %ju lun %jd\n",
4974			       __func__, port->port_name, port->targ_port, retval,
4975			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4976		}
4977#if 0
4978		 else {
4979            /* NOTE:  TODO:  why does lun enable affect port status? */
4980			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4981		}
4982#endif
4983	}
4984
4985	mtx_unlock(&ctl_softc->ctl_lock);
4986
4987	return (0);
4988}
4989
4990int
4991ctl_disable_lun(struct ctl_be_lun *be_lun)
4992{
4993	struct ctl_softc *ctl_softc;
4994	struct ctl_port *port;
4995	struct ctl_lun *lun;
4996	int retval;
4997
4998	ctl_softc = control_softc;
4999
5000	lun = (struct ctl_lun *)be_lun->ctl_lun;
5001
5002	mtx_lock(&ctl_softc->ctl_lock);
5003	mtx_lock(&lun->lun_lock);
5004	if (lun->flags & CTL_LUN_DISABLED) {
5005		mtx_unlock(&lun->lun_lock);
5006		mtx_unlock(&ctl_softc->ctl_lock);
5007		return (0);
5008	}
5009	lun->flags |= CTL_LUN_DISABLED;
5010	mtx_unlock(&lun->lun_lock);
5011
5012	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
5013		mtx_unlock(&ctl_softc->ctl_lock);
5014		/*
5015		 * Drop the lock before we call the frontend's disable
5016		 * routine, to avoid lock order reversals.
5017		 *
5018		 * XXX KDM what happens if the frontend list changes while
5019		 * we're traversing it?  It's unlikely, but should be handled.
5020		 */
5021		retval = port->lun_disable(port->targ_lun_arg, lun->target,
5022					 lun->lun);
5023		mtx_lock(&ctl_softc->ctl_lock);
5024		if (retval != 0) {
5025			printf("ctl_alloc_lun: FETD %s port %d returned error "
5026			       "%d for lun_disable on target %ju lun %jd\n",
5027			       port->port_name, port->targ_port, retval,
5028			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
5029		}
5030	}
5031
5032	mtx_unlock(&ctl_softc->ctl_lock);
5033
5034	return (0);
5035}
5036
5037int
5038ctl_start_lun(struct ctl_be_lun *be_lun)
5039{
5040	struct ctl_softc *ctl_softc;
5041	struct ctl_lun *lun;
5042
5043	ctl_softc = control_softc;
5044
5045	lun = (struct ctl_lun *)be_lun->ctl_lun;
5046
5047	mtx_lock(&lun->lun_lock);
5048	lun->flags &= ~CTL_LUN_STOPPED;
5049	mtx_unlock(&lun->lun_lock);
5050
5051	return (0);
5052}
5053
5054int
5055ctl_stop_lun(struct ctl_be_lun *be_lun)
5056{
5057	struct ctl_softc *ctl_softc;
5058	struct ctl_lun *lun;
5059
5060	ctl_softc = control_softc;
5061
5062	lun = (struct ctl_lun *)be_lun->ctl_lun;
5063
5064	mtx_lock(&lun->lun_lock);
5065	lun->flags |= CTL_LUN_STOPPED;
5066	mtx_unlock(&lun->lun_lock);
5067
5068	return (0);
5069}
5070
5071int
5072ctl_lun_offline(struct ctl_be_lun *be_lun)
5073{
5074	struct ctl_softc *ctl_softc;
5075	struct ctl_lun *lun;
5076
5077	ctl_softc = control_softc;
5078
5079	lun = (struct ctl_lun *)be_lun->ctl_lun;
5080
5081	mtx_lock(&lun->lun_lock);
5082	lun->flags |= CTL_LUN_OFFLINE;
5083	mtx_unlock(&lun->lun_lock);
5084
5085	return (0);
5086}
5087
5088int
5089ctl_lun_online(struct ctl_be_lun *be_lun)
5090{
5091	struct ctl_softc *ctl_softc;
5092	struct ctl_lun *lun;
5093
5094	ctl_softc = control_softc;
5095
5096	lun = (struct ctl_lun *)be_lun->ctl_lun;
5097
5098	mtx_lock(&lun->lun_lock);
5099	lun->flags &= ~CTL_LUN_OFFLINE;
5100	mtx_unlock(&lun->lun_lock);
5101
5102	return (0);
5103}
5104
5105int
5106ctl_invalidate_lun(struct ctl_be_lun *be_lun)
5107{
5108	struct ctl_softc *ctl_softc;
5109	struct ctl_lun *lun;
5110
5111	ctl_softc = control_softc;
5112
5113	lun = (struct ctl_lun *)be_lun->ctl_lun;
5114
5115	mtx_lock(&lun->lun_lock);
5116
5117	/*
5118	 * The LUN needs to be disabled before it can be marked invalid.
5119	 */
5120	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
5121		mtx_unlock(&lun->lun_lock);
5122		return (-1);
5123	}
5124	/*
5125	 * Mark the LUN invalid.
5126	 */
5127	lun->flags |= CTL_LUN_INVALID;
5128
5129	/*
5130	 * If there is nothing in the OOA queue, go ahead and free the LUN.
5131	 * If we have something in the OOA queue, we'll free it when the
5132	 * last I/O completes.
5133	 */
5134	if (TAILQ_EMPTY(&lun->ooa_queue)) {
5135		mtx_unlock(&lun->lun_lock);
5136		mtx_lock(&ctl_softc->ctl_lock);
5137		ctl_free_lun(lun);
5138		mtx_unlock(&ctl_softc->ctl_lock);
5139	} else
5140		mtx_unlock(&lun->lun_lock);
5141
5142	return (0);
5143}
5144
5145int
5146ctl_lun_inoperable(struct ctl_be_lun *be_lun)
5147{
5148	struct ctl_softc *ctl_softc;
5149	struct ctl_lun *lun;
5150
5151	ctl_softc = control_softc;
5152	lun = (struct ctl_lun *)be_lun->ctl_lun;
5153
5154	mtx_lock(&lun->lun_lock);
5155	lun->flags |= CTL_LUN_INOPERABLE;
5156	mtx_unlock(&lun->lun_lock);
5157
5158	return (0);
5159}
5160
5161int
5162ctl_lun_operable(struct ctl_be_lun *be_lun)
5163{
5164	struct ctl_softc *ctl_softc;
5165	struct ctl_lun *lun;
5166
5167	ctl_softc = control_softc;
5168	lun = (struct ctl_lun *)be_lun->ctl_lun;
5169
5170	mtx_lock(&lun->lun_lock);
5171	lun->flags &= ~CTL_LUN_INOPERABLE;
5172	mtx_unlock(&lun->lun_lock);
5173
5174	return (0);
5175}
5176
5177void
5178ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5179{
5180	struct ctl_lun *lun;
5181	struct ctl_softc *softc;
5182	int i;
5183
5184	softc = control_softc;
5185
5186	lun = (struct ctl_lun *)be_lun->ctl_lun;
5187
5188	mtx_lock(&lun->lun_lock);
5189
5190	for (i = 0; i < CTL_MAX_INITIATORS; i++)
5191		lun->pending_ua[i] |= CTL_UA_CAPACITY_CHANGED;
5192
5193	mtx_unlock(&lun->lun_lock);
5194}
5195
5196/*
5197 * Backend "memory move is complete" callback for requests that never
5198 * make it down to say RAIDCore's configuration code.
5199 */
5200int
5201ctl_config_move_done(union ctl_io *io)
5202{
5203	int retval;
5204
5205	retval = CTL_RETVAL_COMPLETE;
5206
5207
5208	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5209	/*
5210	 * XXX KDM this shouldn't happen, but what if it does?
5211	 */
5212	if (io->io_hdr.io_type != CTL_IO_SCSI)
5213		panic("I/O type isn't CTL_IO_SCSI!");
5214
5215	if ((io->io_hdr.port_status == 0)
5216	 && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5217	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
5218		io->io_hdr.status = CTL_SUCCESS;
5219	else if ((io->io_hdr.port_status != 0)
5220	      && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5221	      && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
5222		/*
5223		 * For hardware error sense keys, the sense key
5224		 * specific value is defined to be a retry count,
5225		 * but we use it to pass back an internal FETD
5226		 * error code.  XXX KDM  Hopefully the FETD is only
5227		 * using 16 bits for an error code, since that's
5228		 * all the space we have in the sks field.
5229		 */
5230		ctl_set_internal_failure(&io->scsiio,
5231					 /*sks_valid*/ 1,
5232					 /*retry_count*/
5233					 io->io_hdr.port_status);
5234		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5235			free(io->scsiio.kern_data_ptr, M_CTL);
5236		ctl_done(io);
5237		goto bailout;
5238	}
5239
5240	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
5241	 || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
5242	 || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5243		/*
5244		 * XXX KDM just assuming a single pointer here, and not a
5245		 * S/G list.  If we start using S/G lists for config data,
5246		 * we'll need to know how to clean them up here as well.
5247		 */
5248		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5249			free(io->scsiio.kern_data_ptr, M_CTL);
5250		/* Hopefully the user has already set the status... */
5251		ctl_done(io);
5252	} else {
5253		/*
5254		 * XXX KDM now we need to continue data movement.  Some
5255		 * options:
5256		 * - call ctl_scsiio() again?  We don't do this for data
5257		 *   writes, because for those at least we know ahead of
5258		 *   time where the write will go and how long it is.  For
5259		 *   config writes, though, that information is largely
5260		 *   contained within the write itself, thus we need to
5261		 *   parse out the data again.
5262		 *
5263		 * - Call some other function once the data is in?
5264		 */
5265		if (ctl_debug & CTL_DEBUG_CDB_DATA)
5266			ctl_data_print(io);
5267
5268		/*
5269		 * XXX KDM call ctl_scsiio() again for now, and check flag
5270		 * bits to see whether we're allocated or not.
5271		 */
5272		retval = ctl_scsiio(&io->scsiio);
5273	}
5274bailout:
5275	return (retval);
5276}
5277
5278/*
5279 * This gets called by a backend driver when it is done with a
5280 * data_submit method.
5281 */
5282void
5283ctl_data_submit_done(union ctl_io *io)
5284{
5285	/*
5286	 * If the IO_CONT flag is set, we need to call the supplied
5287	 * function to continue processing the I/O, instead of completing
5288	 * the I/O just yet.
5289	 *
5290	 * If there is an error, though, we don't want to keep processing.
5291	 * Instead, just send status back to the initiator.
5292	 */
5293	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5294	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5295	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5296	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5297		io->scsiio.io_cont(io);
5298		return;
5299	}
5300	ctl_done(io);
5301}
5302
5303/*
5304 * This gets called by a backend driver when it is done with a
5305 * configuration write.
5306 */
5307void
5308ctl_config_write_done(union ctl_io *io)
5309{
5310	uint8_t *buf;
5311
5312	/*
5313	 * If the IO_CONT flag is set, we need to call the supplied
5314	 * function to continue processing the I/O, instead of completing
5315	 * the I/O just yet.
5316	 *
5317	 * If there is an error, though, we don't want to keep processing.
5318	 * Instead, just send status back to the initiator.
5319	 */
5320	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5321	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5322	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5323	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5324		io->scsiio.io_cont(io);
5325		return;
5326	}
5327	/*
5328	 * Since a configuration write can be done for commands that actually
5329	 * have data allocated, like write buffer, and commands that have
5330	 * no data, like start/stop unit, we need to check here.
5331	 */
5332	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5333		buf = io->scsiio.kern_data_ptr;
5334	else
5335		buf = NULL;
5336	ctl_done(io);
5337	if (buf)
5338		free(buf, M_CTL);
5339}
5340
5341/*
5342 * SCSI release command.
5343 */
5344int
5345ctl_scsi_release(struct ctl_scsiio *ctsio)
5346{
5347	int length, longid, thirdparty_id, resv_id;
5348	struct ctl_softc *ctl_softc;
5349	struct ctl_lun *lun;
5350	uint32_t residx;
5351
5352	length = 0;
5353	resv_id = 0;
5354
5355	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5356
5357	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5358	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5359	ctl_softc = control_softc;
5360
5361	switch (ctsio->cdb[0]) {
5362	case RELEASE_10: {
5363		struct scsi_release_10 *cdb;
5364
5365		cdb = (struct scsi_release_10 *)ctsio->cdb;
5366
5367		if (cdb->byte2 & SR10_LONGID)
5368			longid = 1;
5369		else
5370			thirdparty_id = cdb->thirdparty_id;
5371
5372		resv_id = cdb->resv_id;
5373		length = scsi_2btoul(cdb->length);
5374		break;
5375	}
5376	}
5377
5378
5379	/*
5380	 * XXX KDM right now, we only support LUN reservation.  We don't
5381	 * support 3rd party reservations, or extent reservations, which
5382	 * might actually need the parameter list.  If we've gotten this
5383	 * far, we've got a LUN reservation.  Anything else got kicked out
5384	 * above.  So, according to SPC, ignore the length.
5385	 */
5386	length = 0;
5387
5388	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5389	 && (length > 0)) {
5390		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5391		ctsio->kern_data_len = length;
5392		ctsio->kern_total_len = length;
5393		ctsio->kern_data_resid = 0;
5394		ctsio->kern_rel_offset = 0;
5395		ctsio->kern_sg_entries = 0;
5396		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5397		ctsio->be_move_done = ctl_config_move_done;
5398		ctl_datamove((union ctl_io *)ctsio);
5399
5400		return (CTL_RETVAL_COMPLETE);
5401	}
5402
5403	if (length > 0)
5404		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5405
5406	mtx_lock(&lun->lun_lock);
5407
5408	/*
5409	 * According to SPC, it is not an error for an intiator to attempt
5410	 * to release a reservation on a LUN that isn't reserved, or that
5411	 * is reserved by another initiator.  The reservation can only be
5412	 * released, though, by the initiator who made it or by one of
5413	 * several reset type events.
5414	 */
5415	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5416			lun->flags &= ~CTL_LUN_RESERVED;
5417
5418	mtx_unlock(&lun->lun_lock);
5419
5420	ctsio->scsi_status = SCSI_STATUS_OK;
5421	ctsio->io_hdr.status = CTL_SUCCESS;
5422
5423	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5424		free(ctsio->kern_data_ptr, M_CTL);
5425		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5426	}
5427
5428	ctl_done((union ctl_io *)ctsio);
5429	return (CTL_RETVAL_COMPLETE);
5430}
5431
5432int
5433ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5434{
5435	int extent, thirdparty, longid;
5436	int resv_id, length;
5437	uint64_t thirdparty_id;
5438	struct ctl_softc *ctl_softc;
5439	struct ctl_lun *lun;
5440	uint32_t residx;
5441
5442	extent = 0;
5443	thirdparty = 0;
5444	longid = 0;
5445	resv_id = 0;
5446	length = 0;
5447	thirdparty_id = 0;
5448
5449	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5450
5451	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5452	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5453	ctl_softc = control_softc;
5454
5455	switch (ctsio->cdb[0]) {
5456	case RESERVE_10: {
5457		struct scsi_reserve_10 *cdb;
5458
5459		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5460
5461		if (cdb->byte2 & SR10_LONGID)
5462			longid = 1;
5463		else
5464			thirdparty_id = cdb->thirdparty_id;
5465
5466		resv_id = cdb->resv_id;
5467		length = scsi_2btoul(cdb->length);
5468		break;
5469	}
5470	}
5471
5472	/*
5473	 * XXX KDM right now, we only support LUN reservation.  We don't
5474	 * support 3rd party reservations, or extent reservations, which
5475	 * might actually need the parameter list.  If we've gotten this
5476	 * far, we've got a LUN reservation.  Anything else got kicked out
5477	 * above.  So, according to SPC, ignore the length.
5478	 */
5479	length = 0;
5480
5481	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5482	 && (length > 0)) {
5483		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5484		ctsio->kern_data_len = length;
5485		ctsio->kern_total_len = length;
5486		ctsio->kern_data_resid = 0;
5487		ctsio->kern_rel_offset = 0;
5488		ctsio->kern_sg_entries = 0;
5489		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5490		ctsio->be_move_done = ctl_config_move_done;
5491		ctl_datamove((union ctl_io *)ctsio);
5492
5493		return (CTL_RETVAL_COMPLETE);
5494	}
5495
5496	if (length > 0)
5497		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5498
5499	mtx_lock(&lun->lun_lock);
5500	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5501		ctl_set_reservation_conflict(ctsio);
5502		goto bailout;
5503	}
5504
5505	lun->flags |= CTL_LUN_RESERVED;
5506	lun->res_idx = residx;
5507
5508	ctsio->scsi_status = SCSI_STATUS_OK;
5509	ctsio->io_hdr.status = CTL_SUCCESS;
5510
5511bailout:
5512	mtx_unlock(&lun->lun_lock);
5513
5514	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5515		free(ctsio->kern_data_ptr, M_CTL);
5516		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5517	}
5518
5519	ctl_done((union ctl_io *)ctsio);
5520	return (CTL_RETVAL_COMPLETE);
5521}
5522
5523int
5524ctl_start_stop(struct ctl_scsiio *ctsio)
5525{
5526	struct scsi_start_stop_unit *cdb;
5527	struct ctl_lun *lun;
5528	struct ctl_softc *ctl_softc;
5529	int retval;
5530
5531	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5532
5533	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5534	ctl_softc = control_softc;
5535	retval = 0;
5536
5537	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5538
5539	/*
5540	 * XXX KDM
5541	 * We don't support the immediate bit on a stop unit.  In order to
5542	 * do that, we would need to code up a way to know that a stop is
5543	 * pending, and hold off any new commands until it completes, one
5544	 * way or another.  Then we could accept or reject those commands
5545	 * depending on its status.  We would almost need to do the reverse
5546	 * of what we do below for an immediate start -- return the copy of
5547	 * the ctl_io to the FETD with status to send to the host (and to
5548	 * free the copy!) and then free the original I/O once the stop
5549	 * actually completes.  That way, the OOA queue mechanism can work
5550	 * to block commands that shouldn't proceed.  Another alternative
5551	 * would be to put the copy in the queue in place of the original,
5552	 * and return the original back to the caller.  That could be
5553	 * slightly safer..
5554	 */
5555	if ((cdb->byte2 & SSS_IMMED)
5556	 && ((cdb->how & SSS_START) == 0)) {
5557		ctl_set_invalid_field(ctsio,
5558				      /*sks_valid*/ 1,
5559				      /*command*/ 1,
5560				      /*field*/ 1,
5561				      /*bit_valid*/ 1,
5562				      /*bit*/ 0);
5563		ctl_done((union ctl_io *)ctsio);
5564		return (CTL_RETVAL_COMPLETE);
5565	}
5566
5567	if ((lun->flags & CTL_LUN_PR_RESERVED)
5568	 && ((cdb->how & SSS_START)==0)) {
5569		uint32_t residx;
5570
5571		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5572		if (lun->pr_keys[residx] == 0
5573		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5574
5575			ctl_set_reservation_conflict(ctsio);
5576			ctl_done((union ctl_io *)ctsio);
5577			return (CTL_RETVAL_COMPLETE);
5578		}
5579	}
5580
5581	/*
5582	 * If there is no backend on this device, we can't start or stop
5583	 * it.  In theory we shouldn't get any start/stop commands in the
5584	 * first place at this level if the LUN doesn't have a backend.
5585	 * That should get stopped by the command decode code.
5586	 */
5587	if (lun->backend == NULL) {
5588		ctl_set_invalid_opcode(ctsio);
5589		ctl_done((union ctl_io *)ctsio);
5590		return (CTL_RETVAL_COMPLETE);
5591	}
5592
5593	/*
5594	 * XXX KDM Copan-specific offline behavior.
5595	 * Figure out a reasonable way to port this?
5596	 */
5597#ifdef NEEDTOPORT
5598	mtx_lock(&lun->lun_lock);
5599
5600	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5601	 && (lun->flags & CTL_LUN_OFFLINE)) {
5602		/*
5603		 * If the LUN is offline, and the on/offline bit isn't set,
5604		 * reject the start or stop.  Otherwise, let it through.
5605		 */
5606		mtx_unlock(&lun->lun_lock);
5607		ctl_set_lun_not_ready(ctsio);
5608		ctl_done((union ctl_io *)ctsio);
5609	} else {
5610		mtx_unlock(&lun->lun_lock);
5611#endif /* NEEDTOPORT */
5612		/*
5613		 * This could be a start or a stop when we're online,
5614		 * or a stop/offline or start/online.  A start or stop when
5615		 * we're offline is covered in the case above.
5616		 */
5617		/*
5618		 * In the non-immediate case, we send the request to
5619		 * the backend and return status to the user when
5620		 * it is done.
5621		 *
5622		 * In the immediate case, we allocate a new ctl_io
5623		 * to hold a copy of the request, and send that to
5624		 * the backend.  We then set good status on the
5625		 * user's request and return it immediately.
5626		 */
5627		if (cdb->byte2 & SSS_IMMED) {
5628			union ctl_io *new_io;
5629
5630			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5631			if (new_io == NULL) {
5632				ctl_set_busy(ctsio);
5633				ctl_done((union ctl_io *)ctsio);
5634			} else {
5635				ctl_copy_io((union ctl_io *)ctsio,
5636					    new_io);
5637				retval = lun->backend->config_write(new_io);
5638				ctl_set_success(ctsio);
5639				ctl_done((union ctl_io *)ctsio);
5640			}
5641		} else {
5642			retval = lun->backend->config_write(
5643				(union ctl_io *)ctsio);
5644		}
5645#ifdef NEEDTOPORT
5646	}
5647#endif
5648	return (retval);
5649}
5650
5651/*
5652 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5653 * we don't really do anything with the LBA and length fields if the user
5654 * passes them in.  Instead we'll just flush out the cache for the entire
5655 * LUN.
5656 */
5657int
5658ctl_sync_cache(struct ctl_scsiio *ctsio)
5659{
5660	struct ctl_lun *lun;
5661	struct ctl_softc *ctl_softc;
5662	uint64_t starting_lba;
5663	uint32_t block_count;
5664	int retval;
5665
5666	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5667
5668	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5669	ctl_softc = control_softc;
5670	retval = 0;
5671
5672	switch (ctsio->cdb[0]) {
5673	case SYNCHRONIZE_CACHE: {
5674		struct scsi_sync_cache *cdb;
5675		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5676
5677		starting_lba = scsi_4btoul(cdb->begin_lba);
5678		block_count = scsi_2btoul(cdb->lb_count);
5679		break;
5680	}
5681	case SYNCHRONIZE_CACHE_16: {
5682		struct scsi_sync_cache_16 *cdb;
5683		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5684
5685		starting_lba = scsi_8btou64(cdb->begin_lba);
5686		block_count = scsi_4btoul(cdb->lb_count);
5687		break;
5688	}
5689	default:
5690		ctl_set_invalid_opcode(ctsio);
5691		ctl_done((union ctl_io *)ctsio);
5692		goto bailout;
5693		break; /* NOTREACHED */
5694	}
5695
5696	/*
5697	 * We check the LBA and length, but don't do anything with them.
5698	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5699	 * get flushed.  This check will just help satisfy anyone who wants
5700	 * to see an error for an out of range LBA.
5701	 */
5702	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5703		ctl_set_lba_out_of_range(ctsio);
5704		ctl_done((union ctl_io *)ctsio);
5705		goto bailout;
5706	}
5707
5708	/*
5709	 * If this LUN has no backend, we can't flush the cache anyway.
5710	 */
5711	if (lun->backend == NULL) {
5712		ctl_set_invalid_opcode(ctsio);
5713		ctl_done((union ctl_io *)ctsio);
5714		goto bailout;
5715	}
5716
5717	/*
5718	 * Check to see whether we're configured to send the SYNCHRONIZE
5719	 * CACHE command directly to the back end.
5720	 */
5721	mtx_lock(&lun->lun_lock);
5722	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5723	 && (++(lun->sync_count) >= lun->sync_interval)) {
5724		lun->sync_count = 0;
5725		mtx_unlock(&lun->lun_lock);
5726		retval = lun->backend->config_write((union ctl_io *)ctsio);
5727	} else {
5728		mtx_unlock(&lun->lun_lock);
5729		ctl_set_success(ctsio);
5730		ctl_done((union ctl_io *)ctsio);
5731	}
5732
5733bailout:
5734
5735	return (retval);
5736}
5737
5738int
5739ctl_format(struct ctl_scsiio *ctsio)
5740{
5741	struct scsi_format *cdb;
5742	struct ctl_lun *lun;
5743	struct ctl_softc *ctl_softc;
5744	int length, defect_list_len;
5745
5746	CTL_DEBUG_PRINT(("ctl_format\n"));
5747
5748	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5749	ctl_softc = control_softc;
5750
5751	cdb = (struct scsi_format *)ctsio->cdb;
5752
5753	length = 0;
5754	if (cdb->byte2 & SF_FMTDATA) {
5755		if (cdb->byte2 & SF_LONGLIST)
5756			length = sizeof(struct scsi_format_header_long);
5757		else
5758			length = sizeof(struct scsi_format_header_short);
5759	}
5760
5761	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5762	 && (length > 0)) {
5763		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5764		ctsio->kern_data_len = length;
5765		ctsio->kern_total_len = length;
5766		ctsio->kern_data_resid = 0;
5767		ctsio->kern_rel_offset = 0;
5768		ctsio->kern_sg_entries = 0;
5769		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5770		ctsio->be_move_done = ctl_config_move_done;
5771		ctl_datamove((union ctl_io *)ctsio);
5772
5773		return (CTL_RETVAL_COMPLETE);
5774	}
5775
5776	defect_list_len = 0;
5777
5778	if (cdb->byte2 & SF_FMTDATA) {
5779		if (cdb->byte2 & SF_LONGLIST) {
5780			struct scsi_format_header_long *header;
5781
5782			header = (struct scsi_format_header_long *)
5783				ctsio->kern_data_ptr;
5784
5785			defect_list_len = scsi_4btoul(header->defect_list_len);
5786			if (defect_list_len != 0) {
5787				ctl_set_invalid_field(ctsio,
5788						      /*sks_valid*/ 1,
5789						      /*command*/ 0,
5790						      /*field*/ 2,
5791						      /*bit_valid*/ 0,
5792						      /*bit*/ 0);
5793				goto bailout;
5794			}
5795		} else {
5796			struct scsi_format_header_short *header;
5797
5798			header = (struct scsi_format_header_short *)
5799				ctsio->kern_data_ptr;
5800
5801			defect_list_len = scsi_2btoul(header->defect_list_len);
5802			if (defect_list_len != 0) {
5803				ctl_set_invalid_field(ctsio,
5804						      /*sks_valid*/ 1,
5805						      /*command*/ 0,
5806						      /*field*/ 2,
5807						      /*bit_valid*/ 0,
5808						      /*bit*/ 0);
5809				goto bailout;
5810			}
5811		}
5812	}
5813
5814	/*
5815	 * The format command will clear out the "Medium format corrupted"
5816	 * status if set by the configuration code.  That status is really
5817	 * just a way to notify the host that we have lost the media, and
5818	 * get them to issue a command that will basically make them think
5819	 * they're blowing away the media.
5820	 */
5821	mtx_lock(&lun->lun_lock);
5822	lun->flags &= ~CTL_LUN_INOPERABLE;
5823	mtx_unlock(&lun->lun_lock);
5824
5825	ctsio->scsi_status = SCSI_STATUS_OK;
5826	ctsio->io_hdr.status = CTL_SUCCESS;
5827bailout:
5828
5829	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5830		free(ctsio->kern_data_ptr, M_CTL);
5831		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5832	}
5833
5834	ctl_done((union ctl_io *)ctsio);
5835	return (CTL_RETVAL_COMPLETE);
5836}
5837
5838int
5839ctl_read_buffer(struct ctl_scsiio *ctsio)
5840{
5841	struct scsi_read_buffer *cdb;
5842	struct ctl_lun *lun;
5843	int buffer_offset, len;
5844	static uint8_t descr[4];
5845	static uint8_t echo_descr[4] = { 0 };
5846
5847	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5848
5849	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5850	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5851
5852	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5853	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5854	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5855		ctl_set_invalid_field(ctsio,
5856				      /*sks_valid*/ 1,
5857				      /*command*/ 1,
5858				      /*field*/ 1,
5859				      /*bit_valid*/ 1,
5860				      /*bit*/ 4);
5861		ctl_done((union ctl_io *)ctsio);
5862		return (CTL_RETVAL_COMPLETE);
5863	}
5864
5865	len = scsi_3btoul(cdb->length);
5866	buffer_offset = scsi_3btoul(cdb->offset);
5867
5868	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5869		ctl_set_invalid_field(ctsio,
5870				      /*sks_valid*/ 1,
5871				      /*command*/ 1,
5872				      /*field*/ 6,
5873				      /*bit_valid*/ 0,
5874				      /*bit*/ 0);
5875		ctl_done((union ctl_io *)ctsio);
5876		return (CTL_RETVAL_COMPLETE);
5877	}
5878
5879	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5880		descr[0] = 0;
5881		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5882		ctsio->kern_data_ptr = descr;
5883		len = min(len, sizeof(descr));
5884	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5885		ctsio->kern_data_ptr = echo_descr;
5886		len = min(len, sizeof(echo_descr));
5887	} else {
5888		if (lun->write_buffer == NULL) {
5889			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5890			    M_CTL, M_WAITOK);
5891		}
5892		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5893	}
5894	ctsio->kern_data_len = len;
5895	ctsio->kern_total_len = len;
5896	ctsio->kern_data_resid = 0;
5897	ctsio->kern_rel_offset = 0;
5898	ctsio->kern_sg_entries = 0;
5899	ctsio->be_move_done = ctl_config_move_done;
5900	ctl_datamove((union ctl_io *)ctsio);
5901
5902	return (CTL_RETVAL_COMPLETE);
5903}
5904
5905int
5906ctl_write_buffer(struct ctl_scsiio *ctsio)
5907{
5908	struct scsi_write_buffer *cdb;
5909	struct ctl_lun *lun;
5910	int buffer_offset, len;
5911
5912	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5913
5914	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5915	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5916
5917	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5918		ctl_set_invalid_field(ctsio,
5919				      /*sks_valid*/ 1,
5920				      /*command*/ 1,
5921				      /*field*/ 1,
5922				      /*bit_valid*/ 1,
5923				      /*bit*/ 4);
5924		ctl_done((union ctl_io *)ctsio);
5925		return (CTL_RETVAL_COMPLETE);
5926	}
5927
5928	len = scsi_3btoul(cdb->length);
5929	buffer_offset = scsi_3btoul(cdb->offset);
5930
5931	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5932		ctl_set_invalid_field(ctsio,
5933				      /*sks_valid*/ 1,
5934				      /*command*/ 1,
5935				      /*field*/ 6,
5936				      /*bit_valid*/ 0,
5937				      /*bit*/ 0);
5938		ctl_done((union ctl_io *)ctsio);
5939		return (CTL_RETVAL_COMPLETE);
5940	}
5941
5942	/*
5943	 * If we've got a kernel request that hasn't been malloced yet,
5944	 * malloc it and tell the caller the data buffer is here.
5945	 */
5946	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5947		if (lun->write_buffer == NULL) {
5948			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5949			    M_CTL, M_WAITOK);
5950		}
5951		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5952		ctsio->kern_data_len = len;
5953		ctsio->kern_total_len = len;
5954		ctsio->kern_data_resid = 0;
5955		ctsio->kern_rel_offset = 0;
5956		ctsio->kern_sg_entries = 0;
5957		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5958		ctsio->be_move_done = ctl_config_move_done;
5959		ctl_datamove((union ctl_io *)ctsio);
5960
5961		return (CTL_RETVAL_COMPLETE);
5962	}
5963
5964	ctl_done((union ctl_io *)ctsio);
5965
5966	return (CTL_RETVAL_COMPLETE);
5967}
5968
5969int
5970ctl_write_same(struct ctl_scsiio *ctsio)
5971{
5972	struct ctl_lun *lun;
5973	struct ctl_lba_len_flags *lbalen;
5974	uint64_t lba;
5975	uint32_t num_blocks;
5976	int len, retval;
5977	uint8_t byte2;
5978
5979	retval = CTL_RETVAL_COMPLETE;
5980
5981	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5982
5983	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5984
5985	switch (ctsio->cdb[0]) {
5986	case WRITE_SAME_10: {
5987		struct scsi_write_same_10 *cdb;
5988
5989		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5990
5991		lba = scsi_4btoul(cdb->addr);
5992		num_blocks = scsi_2btoul(cdb->length);
5993		byte2 = cdb->byte2;
5994		break;
5995	}
5996	case WRITE_SAME_16: {
5997		struct scsi_write_same_16 *cdb;
5998
5999		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
6000
6001		lba = scsi_8btou64(cdb->addr);
6002		num_blocks = scsi_4btoul(cdb->length);
6003		byte2 = cdb->byte2;
6004		break;
6005	}
6006	default:
6007		/*
6008		 * We got a command we don't support.  This shouldn't
6009		 * happen, commands should be filtered out above us.
6010		 */
6011		ctl_set_invalid_opcode(ctsio);
6012		ctl_done((union ctl_io *)ctsio);
6013
6014		return (CTL_RETVAL_COMPLETE);
6015		break; /* NOTREACHED */
6016	}
6017
6018	/* NDOB and ANCHOR flags can be used only together with UNMAP */
6019	if ((byte2 & SWS_UNMAP) == 0 &&
6020	    (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
6021		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
6022		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
6023		ctl_done((union ctl_io *)ctsio);
6024		return (CTL_RETVAL_COMPLETE);
6025	}
6026
6027	/*
6028	 * The first check is to make sure we're in bounds, the second
6029	 * check is to catch wrap-around problems.  If the lba + num blocks
6030	 * is less than the lba, then we've wrapped around and the block
6031	 * range is invalid anyway.
6032	 */
6033	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6034	 || ((lba + num_blocks) < lba)) {
6035		ctl_set_lba_out_of_range(ctsio);
6036		ctl_done((union ctl_io *)ctsio);
6037		return (CTL_RETVAL_COMPLETE);
6038	}
6039
6040	/* Zero number of blocks means "to the last logical block" */
6041	if (num_blocks == 0) {
6042		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
6043			ctl_set_invalid_field(ctsio,
6044					      /*sks_valid*/ 0,
6045					      /*command*/ 1,
6046					      /*field*/ 0,
6047					      /*bit_valid*/ 0,
6048					      /*bit*/ 0);
6049			ctl_done((union ctl_io *)ctsio);
6050			return (CTL_RETVAL_COMPLETE);
6051		}
6052		num_blocks = (lun->be_lun->maxlba + 1) - lba;
6053	}
6054
6055	len = lun->be_lun->blocksize;
6056
6057	/*
6058	 * If we've got a kernel request that hasn't been malloced yet,
6059	 * malloc it and tell the caller the data buffer is here.
6060	 */
6061	if ((byte2 & SWS_NDOB) == 0 &&
6062	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6063		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6064		ctsio->kern_data_len = len;
6065		ctsio->kern_total_len = len;
6066		ctsio->kern_data_resid = 0;
6067		ctsio->kern_rel_offset = 0;
6068		ctsio->kern_sg_entries = 0;
6069		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6070		ctsio->be_move_done = ctl_config_move_done;
6071		ctl_datamove((union ctl_io *)ctsio);
6072
6073		return (CTL_RETVAL_COMPLETE);
6074	}
6075
6076	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6077	lbalen->lba = lba;
6078	lbalen->len = num_blocks;
6079	lbalen->flags = byte2;
6080	retval = lun->backend->config_write((union ctl_io *)ctsio);
6081
6082	return (retval);
6083}
6084
6085int
6086ctl_unmap(struct ctl_scsiio *ctsio)
6087{
6088	struct ctl_lun *lun;
6089	struct scsi_unmap *cdb;
6090	struct ctl_ptr_len_flags *ptrlen;
6091	struct scsi_unmap_header *hdr;
6092	struct scsi_unmap_desc *buf, *end, *endnz, *range;
6093	uint64_t lba;
6094	uint32_t num_blocks;
6095	int len, retval;
6096	uint8_t byte2;
6097
6098	retval = CTL_RETVAL_COMPLETE;
6099
6100	CTL_DEBUG_PRINT(("ctl_unmap\n"));
6101
6102	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6103	cdb = (struct scsi_unmap *)ctsio->cdb;
6104
6105	len = scsi_2btoul(cdb->length);
6106	byte2 = cdb->byte2;
6107
6108	/*
6109	 * If we've got a kernel request that hasn't been malloced yet,
6110	 * malloc it and tell the caller the data buffer is here.
6111	 */
6112	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6113		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6114		ctsio->kern_data_len = len;
6115		ctsio->kern_total_len = len;
6116		ctsio->kern_data_resid = 0;
6117		ctsio->kern_rel_offset = 0;
6118		ctsio->kern_sg_entries = 0;
6119		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6120		ctsio->be_move_done = ctl_config_move_done;
6121		ctl_datamove((union ctl_io *)ctsio);
6122
6123		return (CTL_RETVAL_COMPLETE);
6124	}
6125
6126	len = ctsio->kern_total_len - ctsio->kern_data_resid;
6127	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
6128	if (len < sizeof (*hdr) ||
6129	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
6130	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
6131	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
6132		ctl_set_invalid_field(ctsio,
6133				      /*sks_valid*/ 0,
6134				      /*command*/ 0,
6135				      /*field*/ 0,
6136				      /*bit_valid*/ 0,
6137				      /*bit*/ 0);
6138		ctl_done((union ctl_io *)ctsio);
6139		return (CTL_RETVAL_COMPLETE);
6140	}
6141	len = scsi_2btoul(hdr->desc_length);
6142	buf = (struct scsi_unmap_desc *)(hdr + 1);
6143	end = buf + len / sizeof(*buf);
6144
6145	endnz = buf;
6146	for (range = buf; range < end; range++) {
6147		lba = scsi_8btou64(range->lba);
6148		num_blocks = scsi_4btoul(range->length);
6149		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6150		 || ((lba + num_blocks) < lba)) {
6151			ctl_set_lba_out_of_range(ctsio);
6152			ctl_done((union ctl_io *)ctsio);
6153			return (CTL_RETVAL_COMPLETE);
6154		}
6155		if (num_blocks != 0)
6156			endnz = range + 1;
6157	}
6158
6159	/*
6160	 * Block backend can not handle zero last range.
6161	 * Filter it out and return if there is nothing left.
6162	 */
6163	len = (uint8_t *)endnz - (uint8_t *)buf;
6164	if (len == 0) {
6165		ctl_set_success(ctsio);
6166		ctl_done((union ctl_io *)ctsio);
6167		return (CTL_RETVAL_COMPLETE);
6168	}
6169
6170	mtx_lock(&lun->lun_lock);
6171	ptrlen = (struct ctl_ptr_len_flags *)
6172	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6173	ptrlen->ptr = (void *)buf;
6174	ptrlen->len = len;
6175	ptrlen->flags = byte2;
6176	ctl_check_blocked(lun);
6177	mtx_unlock(&lun->lun_lock);
6178
6179	retval = lun->backend->config_write((union ctl_io *)ctsio);
6180	return (retval);
6181}
6182
6183/*
6184 * Note that this function currently doesn't actually do anything inside
6185 * CTL to enforce things if the DQue bit is turned on.
6186 *
6187 * Also note that this function can't be used in the default case, because
6188 * the DQue bit isn't set in the changeable mask for the control mode page
6189 * anyway.  This is just here as an example for how to implement a page
6190 * handler, and a placeholder in case we want to allow the user to turn
6191 * tagged queueing on and off.
6192 *
6193 * The D_SENSE bit handling is functional, however, and will turn
6194 * descriptor sense on and off for a given LUN.
6195 */
6196int
6197ctl_control_page_handler(struct ctl_scsiio *ctsio,
6198			 struct ctl_page_index *page_index, uint8_t *page_ptr)
6199{
6200	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6201	struct ctl_lun *lun;
6202	struct ctl_softc *softc;
6203	int set_ua;
6204	uint32_t initidx;
6205
6206	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6207	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6208	set_ua = 0;
6209
6210	user_cp = (struct scsi_control_page *)page_ptr;
6211	current_cp = (struct scsi_control_page *)
6212		(page_index->page_data + (page_index->page_len *
6213		CTL_PAGE_CURRENT));
6214	saved_cp = (struct scsi_control_page *)
6215		(page_index->page_data + (page_index->page_len *
6216		CTL_PAGE_SAVED));
6217
6218	softc = control_softc;
6219
6220	mtx_lock(&lun->lun_lock);
6221	if (((current_cp->rlec & SCP_DSENSE) == 0)
6222	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6223		/*
6224		 * Descriptor sense is currently turned off and the user
6225		 * wants to turn it on.
6226		 */
6227		current_cp->rlec |= SCP_DSENSE;
6228		saved_cp->rlec |= SCP_DSENSE;
6229		lun->flags |= CTL_LUN_SENSE_DESC;
6230		set_ua = 1;
6231	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6232		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6233		/*
6234		 * Descriptor sense is currently turned on, and the user
6235		 * wants to turn it off.
6236		 */
6237		current_cp->rlec &= ~SCP_DSENSE;
6238		saved_cp->rlec &= ~SCP_DSENSE;
6239		lun->flags &= ~CTL_LUN_SENSE_DESC;
6240		set_ua = 1;
6241	}
6242	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6243	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6244		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6245		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6246		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6247		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6248		set_ua = 1;
6249	}
6250	if ((current_cp->eca_and_aen & SCP_SWP) !=
6251	    (user_cp->eca_and_aen & SCP_SWP)) {
6252		current_cp->eca_and_aen &= ~SCP_SWP;
6253		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6254		saved_cp->eca_and_aen &= ~SCP_SWP;
6255		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6256		set_ua = 1;
6257	}
6258	if (set_ua != 0) {
6259		int i;
6260		/*
6261		 * Let other initiators know that the mode
6262		 * parameters for this LUN have changed.
6263		 */
6264		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6265			if (i == initidx)
6266				continue;
6267
6268			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6269		}
6270	}
6271	mtx_unlock(&lun->lun_lock);
6272
6273	return (0);
6274}
6275
6276int
6277ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6278		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6279{
6280	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6281	struct ctl_lun *lun;
6282	int set_ua;
6283	uint32_t initidx;
6284
6285	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6286	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6287	set_ua = 0;
6288
6289	user_cp = (struct scsi_caching_page *)page_ptr;
6290	current_cp = (struct scsi_caching_page *)
6291		(page_index->page_data + (page_index->page_len *
6292		CTL_PAGE_CURRENT));
6293	saved_cp = (struct scsi_caching_page *)
6294		(page_index->page_data + (page_index->page_len *
6295		CTL_PAGE_SAVED));
6296
6297	mtx_lock(&lun->lun_lock);
6298	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6299	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6300		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6301		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6302		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6303		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6304		set_ua = 1;
6305	}
6306	if (set_ua != 0) {
6307		int i;
6308		/*
6309		 * Let other initiators know that the mode
6310		 * parameters for this LUN have changed.
6311		 */
6312		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6313			if (i == initidx)
6314				continue;
6315
6316			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6317		}
6318	}
6319	mtx_unlock(&lun->lun_lock);
6320
6321	return (0);
6322}
6323
6324int
6325ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6326				struct ctl_page_index *page_index,
6327				uint8_t *page_ptr)
6328{
6329	uint8_t *c;
6330	int i;
6331
6332	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6333	ctl_time_io_secs =
6334		(c[0] << 8) |
6335		(c[1] << 0) |
6336		0;
6337	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6338	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6339	printf("page data:");
6340	for (i=0; i<8; i++)
6341		printf(" %.2x",page_ptr[i]);
6342	printf("\n");
6343	return (0);
6344}
6345
6346int
6347ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6348			       struct ctl_page_index *page_index,
6349			       int pc)
6350{
6351	struct copan_debugconf_subpage *page;
6352
6353	page = (struct copan_debugconf_subpage *)page_index->page_data +
6354		(page_index->page_len * pc);
6355
6356	switch (pc) {
6357	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6358	case SMS_PAGE_CTRL_DEFAULT >> 6:
6359	case SMS_PAGE_CTRL_SAVED >> 6:
6360		/*
6361		 * We don't update the changable or default bits for this page.
6362		 */
6363		break;
6364	case SMS_PAGE_CTRL_CURRENT >> 6:
6365		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6366		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6367		break;
6368	default:
6369#ifdef NEEDTOPORT
6370		EPRINT(0, "Invalid PC %d!!", pc);
6371#endif /* NEEDTOPORT */
6372		break;
6373	}
6374	return (0);
6375}
6376
6377
6378static int
6379ctl_do_mode_select(union ctl_io *io)
6380{
6381	struct scsi_mode_page_header *page_header;
6382	struct ctl_page_index *page_index;
6383	struct ctl_scsiio *ctsio;
6384	int control_dev, page_len;
6385	int page_len_offset, page_len_size;
6386	union ctl_modepage_info *modepage_info;
6387	struct ctl_lun *lun;
6388	int *len_left, *len_used;
6389	int retval, i;
6390
6391	ctsio = &io->scsiio;
6392	page_index = NULL;
6393	page_len = 0;
6394	retval = CTL_RETVAL_COMPLETE;
6395
6396	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6397
6398	if (lun->be_lun->lun_type != T_DIRECT)
6399		control_dev = 1;
6400	else
6401		control_dev = 0;
6402
6403	modepage_info = (union ctl_modepage_info *)
6404		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6405	len_left = &modepage_info->header.len_left;
6406	len_used = &modepage_info->header.len_used;
6407
6408do_next_page:
6409
6410	page_header = (struct scsi_mode_page_header *)
6411		(ctsio->kern_data_ptr + *len_used);
6412
6413	if (*len_left == 0) {
6414		free(ctsio->kern_data_ptr, M_CTL);
6415		ctl_set_success(ctsio);
6416		ctl_done((union ctl_io *)ctsio);
6417		return (CTL_RETVAL_COMPLETE);
6418	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6419
6420		free(ctsio->kern_data_ptr, M_CTL);
6421		ctl_set_param_len_error(ctsio);
6422		ctl_done((union ctl_io *)ctsio);
6423		return (CTL_RETVAL_COMPLETE);
6424
6425	} else if ((page_header->page_code & SMPH_SPF)
6426		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6427
6428		free(ctsio->kern_data_ptr, M_CTL);
6429		ctl_set_param_len_error(ctsio);
6430		ctl_done((union ctl_io *)ctsio);
6431		return (CTL_RETVAL_COMPLETE);
6432	}
6433
6434
6435	/*
6436	 * XXX KDM should we do something with the block descriptor?
6437	 */
6438	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6439
6440		if ((control_dev != 0)
6441		 && (lun->mode_pages.index[i].page_flags &
6442		     CTL_PAGE_FLAG_DISK_ONLY))
6443			continue;
6444
6445		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6446		    (page_header->page_code & SMPH_PC_MASK))
6447			continue;
6448
6449		/*
6450		 * If neither page has a subpage code, then we've got a
6451		 * match.
6452		 */
6453		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6454		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6455			page_index = &lun->mode_pages.index[i];
6456			page_len = page_header->page_length;
6457			break;
6458		}
6459
6460		/*
6461		 * If both pages have subpages, then the subpage numbers
6462		 * have to match.
6463		 */
6464		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6465		  && (page_header->page_code & SMPH_SPF)) {
6466			struct scsi_mode_page_header_sp *sph;
6467
6468			sph = (struct scsi_mode_page_header_sp *)page_header;
6469
6470			if (lun->mode_pages.index[i].subpage ==
6471			    sph->subpage) {
6472				page_index = &lun->mode_pages.index[i];
6473				page_len = scsi_2btoul(sph->page_length);
6474				break;
6475			}
6476		}
6477	}
6478
6479	/*
6480	 * If we couldn't find the page, or if we don't have a mode select
6481	 * handler for it, send back an error to the user.
6482	 */
6483	if ((page_index == NULL)
6484	 || (page_index->select_handler == NULL)) {
6485		ctl_set_invalid_field(ctsio,
6486				      /*sks_valid*/ 1,
6487				      /*command*/ 0,
6488				      /*field*/ *len_used,
6489				      /*bit_valid*/ 0,
6490				      /*bit*/ 0);
6491		free(ctsio->kern_data_ptr, M_CTL);
6492		ctl_done((union ctl_io *)ctsio);
6493		return (CTL_RETVAL_COMPLETE);
6494	}
6495
6496	if (page_index->page_code & SMPH_SPF) {
6497		page_len_offset = 2;
6498		page_len_size = 2;
6499	} else {
6500		page_len_size = 1;
6501		page_len_offset = 1;
6502	}
6503
6504	/*
6505	 * If the length the initiator gives us isn't the one we specify in
6506	 * the mode page header, or if they didn't specify enough data in
6507	 * the CDB to avoid truncating this page, kick out the request.
6508	 */
6509	if ((page_len != (page_index->page_len - page_len_offset -
6510			  page_len_size))
6511	 || (*len_left < page_index->page_len)) {
6512
6513
6514		ctl_set_invalid_field(ctsio,
6515				      /*sks_valid*/ 1,
6516				      /*command*/ 0,
6517				      /*field*/ *len_used + page_len_offset,
6518				      /*bit_valid*/ 0,
6519				      /*bit*/ 0);
6520		free(ctsio->kern_data_ptr, M_CTL);
6521		ctl_done((union ctl_io *)ctsio);
6522		return (CTL_RETVAL_COMPLETE);
6523	}
6524
6525	/*
6526	 * Run through the mode page, checking to make sure that the bits
6527	 * the user changed are actually legal for him to change.
6528	 */
6529	for (i = 0; i < page_index->page_len; i++) {
6530		uint8_t *user_byte, *change_mask, *current_byte;
6531		int bad_bit;
6532		int j;
6533
6534		user_byte = (uint8_t *)page_header + i;
6535		change_mask = page_index->page_data +
6536			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6537		current_byte = page_index->page_data +
6538			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6539
6540		/*
6541		 * Check to see whether the user set any bits in this byte
6542		 * that he is not allowed to set.
6543		 */
6544		if ((*user_byte & ~(*change_mask)) ==
6545		    (*current_byte & ~(*change_mask)))
6546			continue;
6547
6548		/*
6549		 * Go through bit by bit to determine which one is illegal.
6550		 */
6551		bad_bit = 0;
6552		for (j = 7; j >= 0; j--) {
6553			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6554			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6555				bad_bit = i;
6556				break;
6557			}
6558		}
6559		ctl_set_invalid_field(ctsio,
6560				      /*sks_valid*/ 1,
6561				      /*command*/ 0,
6562				      /*field*/ *len_used + i,
6563				      /*bit_valid*/ 1,
6564				      /*bit*/ bad_bit);
6565		free(ctsio->kern_data_ptr, M_CTL);
6566		ctl_done((union ctl_io *)ctsio);
6567		return (CTL_RETVAL_COMPLETE);
6568	}
6569
6570	/*
6571	 * Decrement these before we call the page handler, since we may
6572	 * end up getting called back one way or another before the handler
6573	 * returns to this context.
6574	 */
6575	*len_left -= page_index->page_len;
6576	*len_used += page_index->page_len;
6577
6578	retval = page_index->select_handler(ctsio, page_index,
6579					    (uint8_t *)page_header);
6580
6581	/*
6582	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6583	 * wait until this queued command completes to finish processing
6584	 * the mode page.  If it returns anything other than
6585	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6586	 * already set the sense information, freed the data pointer, and
6587	 * completed the io for us.
6588	 */
6589	if (retval != CTL_RETVAL_COMPLETE)
6590		goto bailout_no_done;
6591
6592	/*
6593	 * If the initiator sent us more than one page, parse the next one.
6594	 */
6595	if (*len_left > 0)
6596		goto do_next_page;
6597
6598	ctl_set_success(ctsio);
6599	free(ctsio->kern_data_ptr, M_CTL);
6600	ctl_done((union ctl_io *)ctsio);
6601
6602bailout_no_done:
6603
6604	return (CTL_RETVAL_COMPLETE);
6605
6606}
6607
6608int
6609ctl_mode_select(struct ctl_scsiio *ctsio)
6610{
6611	int param_len, pf, sp;
6612	int header_size, bd_len;
6613	int len_left, len_used;
6614	struct ctl_page_index *page_index;
6615	struct ctl_lun *lun;
6616	int control_dev, page_len;
6617	union ctl_modepage_info *modepage_info;
6618	int retval;
6619
6620	pf = 0;
6621	sp = 0;
6622	page_len = 0;
6623	len_used = 0;
6624	len_left = 0;
6625	retval = 0;
6626	bd_len = 0;
6627	page_index = NULL;
6628
6629	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6630
6631	if (lun->be_lun->lun_type != T_DIRECT)
6632		control_dev = 1;
6633	else
6634		control_dev = 0;
6635
6636	switch (ctsio->cdb[0]) {
6637	case MODE_SELECT_6: {
6638		struct scsi_mode_select_6 *cdb;
6639
6640		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6641
6642		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6643		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6644
6645		param_len = cdb->length;
6646		header_size = sizeof(struct scsi_mode_header_6);
6647		break;
6648	}
6649	case MODE_SELECT_10: {
6650		struct scsi_mode_select_10 *cdb;
6651
6652		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6653
6654		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6655		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6656
6657		param_len = scsi_2btoul(cdb->length);
6658		header_size = sizeof(struct scsi_mode_header_10);
6659		break;
6660	}
6661	default:
6662		ctl_set_invalid_opcode(ctsio);
6663		ctl_done((union ctl_io *)ctsio);
6664		return (CTL_RETVAL_COMPLETE);
6665		break; /* NOTREACHED */
6666	}
6667
6668	/*
6669	 * From SPC-3:
6670	 * "A parameter list length of zero indicates that the Data-Out Buffer
6671	 * shall be empty. This condition shall not be considered as an error."
6672	 */
6673	if (param_len == 0) {
6674		ctl_set_success(ctsio);
6675		ctl_done((union ctl_io *)ctsio);
6676		return (CTL_RETVAL_COMPLETE);
6677	}
6678
6679	/*
6680	 * Since we'll hit this the first time through, prior to
6681	 * allocation, we don't need to free a data buffer here.
6682	 */
6683	if (param_len < header_size) {
6684		ctl_set_param_len_error(ctsio);
6685		ctl_done((union ctl_io *)ctsio);
6686		return (CTL_RETVAL_COMPLETE);
6687	}
6688
6689	/*
6690	 * Allocate the data buffer and grab the user's data.  In theory,
6691	 * we shouldn't have to sanity check the parameter list length here
6692	 * because the maximum size is 64K.  We should be able to malloc
6693	 * that much without too many problems.
6694	 */
6695	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6696		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6697		ctsio->kern_data_len = param_len;
6698		ctsio->kern_total_len = param_len;
6699		ctsio->kern_data_resid = 0;
6700		ctsio->kern_rel_offset = 0;
6701		ctsio->kern_sg_entries = 0;
6702		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6703		ctsio->be_move_done = ctl_config_move_done;
6704		ctl_datamove((union ctl_io *)ctsio);
6705
6706		return (CTL_RETVAL_COMPLETE);
6707	}
6708
6709	switch (ctsio->cdb[0]) {
6710	case MODE_SELECT_6: {
6711		struct scsi_mode_header_6 *mh6;
6712
6713		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6714		bd_len = mh6->blk_desc_len;
6715		break;
6716	}
6717	case MODE_SELECT_10: {
6718		struct scsi_mode_header_10 *mh10;
6719
6720		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6721		bd_len = scsi_2btoul(mh10->blk_desc_len);
6722		break;
6723	}
6724	default:
6725		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6726		break;
6727	}
6728
6729	if (param_len < (header_size + bd_len)) {
6730		free(ctsio->kern_data_ptr, M_CTL);
6731		ctl_set_param_len_error(ctsio);
6732		ctl_done((union ctl_io *)ctsio);
6733		return (CTL_RETVAL_COMPLETE);
6734	}
6735
6736	/*
6737	 * Set the IO_CONT flag, so that if this I/O gets passed to
6738	 * ctl_config_write_done(), it'll get passed back to
6739	 * ctl_do_mode_select() for further processing, or completion if
6740	 * we're all done.
6741	 */
6742	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6743	ctsio->io_cont = ctl_do_mode_select;
6744
6745	modepage_info = (union ctl_modepage_info *)
6746		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6747
6748	memset(modepage_info, 0, sizeof(*modepage_info));
6749
6750	len_left = param_len - header_size - bd_len;
6751	len_used = header_size + bd_len;
6752
6753	modepage_info->header.len_left = len_left;
6754	modepage_info->header.len_used = len_used;
6755
6756	return (ctl_do_mode_select((union ctl_io *)ctsio));
6757}
6758
6759int
6760ctl_mode_sense(struct ctl_scsiio *ctsio)
6761{
6762	struct ctl_lun *lun;
6763	int pc, page_code, dbd, llba, subpage;
6764	int alloc_len, page_len, header_len, total_len;
6765	struct scsi_mode_block_descr *block_desc;
6766	struct ctl_page_index *page_index;
6767	int control_dev;
6768
6769	dbd = 0;
6770	llba = 0;
6771	block_desc = NULL;
6772	page_index = NULL;
6773
6774	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6775
6776	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6777
6778	if (lun->be_lun->lun_type != T_DIRECT)
6779		control_dev = 1;
6780	else
6781		control_dev = 0;
6782
6783	switch (ctsio->cdb[0]) {
6784	case MODE_SENSE_6: {
6785		struct scsi_mode_sense_6 *cdb;
6786
6787		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6788
6789		header_len = sizeof(struct scsi_mode_hdr_6);
6790		if (cdb->byte2 & SMS_DBD)
6791			dbd = 1;
6792		else
6793			header_len += sizeof(struct scsi_mode_block_descr);
6794
6795		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6796		page_code = cdb->page & SMS_PAGE_CODE;
6797		subpage = cdb->subpage;
6798		alloc_len = cdb->length;
6799		break;
6800	}
6801	case MODE_SENSE_10: {
6802		struct scsi_mode_sense_10 *cdb;
6803
6804		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6805
6806		header_len = sizeof(struct scsi_mode_hdr_10);
6807
6808		if (cdb->byte2 & SMS_DBD)
6809			dbd = 1;
6810		else
6811			header_len += sizeof(struct scsi_mode_block_descr);
6812		if (cdb->byte2 & SMS10_LLBAA)
6813			llba = 1;
6814		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6815		page_code = cdb->page & SMS_PAGE_CODE;
6816		subpage = cdb->subpage;
6817		alloc_len = scsi_2btoul(cdb->length);
6818		break;
6819	}
6820	default:
6821		ctl_set_invalid_opcode(ctsio);
6822		ctl_done((union ctl_io *)ctsio);
6823		return (CTL_RETVAL_COMPLETE);
6824		break; /* NOTREACHED */
6825	}
6826
6827	/*
6828	 * We have to make a first pass through to calculate the size of
6829	 * the pages that match the user's query.  Then we allocate enough
6830	 * memory to hold it, and actually copy the data into the buffer.
6831	 */
6832	switch (page_code) {
6833	case SMS_ALL_PAGES_PAGE: {
6834		int i;
6835
6836		page_len = 0;
6837
6838		/*
6839		 * At the moment, values other than 0 and 0xff here are
6840		 * reserved according to SPC-3.
6841		 */
6842		if ((subpage != SMS_SUBPAGE_PAGE_0)
6843		 && (subpage != SMS_SUBPAGE_ALL)) {
6844			ctl_set_invalid_field(ctsio,
6845					      /*sks_valid*/ 1,
6846					      /*command*/ 1,
6847					      /*field*/ 3,
6848					      /*bit_valid*/ 0,
6849					      /*bit*/ 0);
6850			ctl_done((union ctl_io *)ctsio);
6851			return (CTL_RETVAL_COMPLETE);
6852		}
6853
6854		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6855			if ((control_dev != 0)
6856			 && (lun->mode_pages.index[i].page_flags &
6857			     CTL_PAGE_FLAG_DISK_ONLY))
6858				continue;
6859
6860			/*
6861			 * We don't use this subpage if the user didn't
6862			 * request all subpages.
6863			 */
6864			if ((lun->mode_pages.index[i].subpage != 0)
6865			 && (subpage == SMS_SUBPAGE_PAGE_0))
6866				continue;
6867
6868#if 0
6869			printf("found page %#x len %d\n",
6870			       lun->mode_pages.index[i].page_code &
6871			       SMPH_PC_MASK,
6872			       lun->mode_pages.index[i].page_len);
6873#endif
6874			page_len += lun->mode_pages.index[i].page_len;
6875		}
6876		break;
6877	}
6878	default: {
6879		int i;
6880
6881		page_len = 0;
6882
6883		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6884			/* Look for the right page code */
6885			if ((lun->mode_pages.index[i].page_code &
6886			     SMPH_PC_MASK) != page_code)
6887				continue;
6888
6889			/* Look for the right subpage or the subpage wildcard*/
6890			if ((lun->mode_pages.index[i].subpage != subpage)
6891			 && (subpage != SMS_SUBPAGE_ALL))
6892				continue;
6893
6894			/* Make sure the page is supported for this dev type */
6895			if ((control_dev != 0)
6896			 && (lun->mode_pages.index[i].page_flags &
6897			     CTL_PAGE_FLAG_DISK_ONLY))
6898				continue;
6899
6900#if 0
6901			printf("found page %#x len %d\n",
6902			       lun->mode_pages.index[i].page_code &
6903			       SMPH_PC_MASK,
6904			       lun->mode_pages.index[i].page_len);
6905#endif
6906
6907			page_len += lun->mode_pages.index[i].page_len;
6908		}
6909
6910		if (page_len == 0) {
6911			ctl_set_invalid_field(ctsio,
6912					      /*sks_valid*/ 1,
6913					      /*command*/ 1,
6914					      /*field*/ 2,
6915					      /*bit_valid*/ 1,
6916					      /*bit*/ 5);
6917			ctl_done((union ctl_io *)ctsio);
6918			return (CTL_RETVAL_COMPLETE);
6919		}
6920		break;
6921	}
6922	}
6923
6924	total_len = header_len + page_len;
6925#if 0
6926	printf("header_len = %d, page_len = %d, total_len = %d\n",
6927	       header_len, page_len, total_len);
6928#endif
6929
6930	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6931	ctsio->kern_sg_entries = 0;
6932	ctsio->kern_data_resid = 0;
6933	ctsio->kern_rel_offset = 0;
6934	if (total_len < alloc_len) {
6935		ctsio->residual = alloc_len - total_len;
6936		ctsio->kern_data_len = total_len;
6937		ctsio->kern_total_len = total_len;
6938	} else {
6939		ctsio->residual = 0;
6940		ctsio->kern_data_len = alloc_len;
6941		ctsio->kern_total_len = alloc_len;
6942	}
6943
6944	switch (ctsio->cdb[0]) {
6945	case MODE_SENSE_6: {
6946		struct scsi_mode_hdr_6 *header;
6947
6948		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6949
6950		header->datalen = ctl_min(total_len - 1, 254);
6951		if (control_dev == 0) {
6952			header->dev_specific = 0x10; /* DPOFUA */
6953			if ((lun->flags & CTL_LUN_READONLY) ||
6954			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6955			    .eca_and_aen & SCP_SWP) != 0)
6956				    header->dev_specific |= 0x80; /* WP */
6957		}
6958		if (dbd)
6959			header->block_descr_len = 0;
6960		else
6961			header->block_descr_len =
6962				sizeof(struct scsi_mode_block_descr);
6963		block_desc = (struct scsi_mode_block_descr *)&header[1];
6964		break;
6965	}
6966	case MODE_SENSE_10: {
6967		struct scsi_mode_hdr_10 *header;
6968		int datalen;
6969
6970		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6971
6972		datalen = ctl_min(total_len - 2, 65533);
6973		scsi_ulto2b(datalen, header->datalen);
6974		if (control_dev == 0) {
6975			header->dev_specific = 0x10; /* DPOFUA */
6976			if ((lun->flags & CTL_LUN_READONLY) ||
6977			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6978			    .eca_and_aen & SCP_SWP) != 0)
6979				    header->dev_specific |= 0x80; /* WP */
6980		}
6981		if (dbd)
6982			scsi_ulto2b(0, header->block_descr_len);
6983		else
6984			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6985				    header->block_descr_len);
6986		block_desc = (struct scsi_mode_block_descr *)&header[1];
6987		break;
6988	}
6989	default:
6990		panic("invalid CDB type %#x", ctsio->cdb[0]);
6991		break; /* NOTREACHED */
6992	}
6993
6994	/*
6995	 * If we've got a disk, use its blocksize in the block
6996	 * descriptor.  Otherwise, just set it to 0.
6997	 */
6998	if (dbd == 0) {
6999		if (control_dev == 0)
7000			scsi_ulto3b(lun->be_lun->blocksize,
7001				    block_desc->block_len);
7002		else
7003			scsi_ulto3b(0, block_desc->block_len);
7004	}
7005
7006	switch (page_code) {
7007	case SMS_ALL_PAGES_PAGE: {
7008		int i, data_used;
7009
7010		data_used = header_len;
7011		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7012			struct ctl_page_index *page_index;
7013
7014			page_index = &lun->mode_pages.index[i];
7015
7016			if ((control_dev != 0)
7017			 && (page_index->page_flags &
7018			    CTL_PAGE_FLAG_DISK_ONLY))
7019				continue;
7020
7021			/*
7022			 * We don't use this subpage if the user didn't
7023			 * request all subpages.  We already checked (above)
7024			 * to make sure the user only specified a subpage
7025			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
7026			 */
7027			if ((page_index->subpage != 0)
7028			 && (subpage == SMS_SUBPAGE_PAGE_0))
7029				continue;
7030
7031			/*
7032			 * Call the handler, if it exists, to update the
7033			 * page to the latest values.
7034			 */
7035			if (page_index->sense_handler != NULL)
7036				page_index->sense_handler(ctsio, page_index,pc);
7037
7038			memcpy(ctsio->kern_data_ptr + data_used,
7039			       page_index->page_data +
7040			       (page_index->page_len * pc),
7041			       page_index->page_len);
7042			data_used += page_index->page_len;
7043		}
7044		break;
7045	}
7046	default: {
7047		int i, data_used;
7048
7049		data_used = header_len;
7050
7051		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7052			struct ctl_page_index *page_index;
7053
7054			page_index = &lun->mode_pages.index[i];
7055
7056			/* Look for the right page code */
7057			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
7058				continue;
7059
7060			/* Look for the right subpage or the subpage wildcard*/
7061			if ((page_index->subpage != subpage)
7062			 && (subpage != SMS_SUBPAGE_ALL))
7063				continue;
7064
7065			/* Make sure the page is supported for this dev type */
7066			if ((control_dev != 0)
7067			 && (page_index->page_flags &
7068			     CTL_PAGE_FLAG_DISK_ONLY))
7069				continue;
7070
7071			/*
7072			 * Call the handler, if it exists, to update the
7073			 * page to the latest values.
7074			 */
7075			if (page_index->sense_handler != NULL)
7076				page_index->sense_handler(ctsio, page_index,pc);
7077
7078			memcpy(ctsio->kern_data_ptr + data_used,
7079			       page_index->page_data +
7080			       (page_index->page_len * pc),
7081			       page_index->page_len);
7082			data_used += page_index->page_len;
7083		}
7084		break;
7085	}
7086	}
7087
7088	ctsio->scsi_status = SCSI_STATUS_OK;
7089
7090	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7091	ctsio->be_move_done = ctl_config_move_done;
7092	ctl_datamove((union ctl_io *)ctsio);
7093
7094	return (CTL_RETVAL_COMPLETE);
7095}
7096
7097int
7098ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
7099			       struct ctl_page_index *page_index,
7100			       int pc)
7101{
7102	struct ctl_lun *lun;
7103	struct scsi_log_param_header *phdr;
7104	uint8_t *data;
7105	uint64_t val;
7106
7107	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7108	data = page_index->page_data;
7109
7110	if (lun->backend->lun_attr != NULL &&
7111	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
7112	     != UINT64_MAX) {
7113		phdr = (struct scsi_log_param_header *)data;
7114		scsi_ulto2b(0x0001, phdr->param_code);
7115		phdr->param_control = SLP_LBIN | SLP_LP;
7116		phdr->param_len = 8;
7117		data = (uint8_t *)(phdr + 1);
7118		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
7119		data[4] = 0x01; /* per-LUN */
7120		data += phdr->param_len;
7121	}
7122
7123	if (lun->backend->lun_attr != NULL &&
7124	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
7125	     != UINT64_MAX) {
7126		phdr = (struct scsi_log_param_header *)data;
7127		scsi_ulto2b(0x0002, phdr->param_code);
7128		phdr->param_control = SLP_LBIN | SLP_LP;
7129		phdr->param_len = 8;
7130		data = (uint8_t *)(phdr + 1);
7131		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
7132		data[4] = 0x02; /* per-pool */
7133		data += phdr->param_len;
7134	}
7135
7136	if (lun->backend->lun_attr != NULL &&
7137	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
7138	     != UINT64_MAX) {
7139		phdr = (struct scsi_log_param_header *)data;
7140		scsi_ulto2b(0x00f1, phdr->param_code);
7141		phdr->param_control = SLP_LBIN | SLP_LP;
7142		phdr->param_len = 8;
7143		data = (uint8_t *)(phdr + 1);
7144		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
7145		data[4] = 0x02; /* per-pool */
7146		data += phdr->param_len;
7147	}
7148
7149	if (lun->backend->lun_attr != NULL &&
7150	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
7151	     != UINT64_MAX) {
7152		phdr = (struct scsi_log_param_header *)data;
7153		scsi_ulto2b(0x00f2, phdr->param_code);
7154		phdr->param_control = SLP_LBIN | SLP_LP;
7155		phdr->param_len = 8;
7156		data = (uint8_t *)(phdr + 1);
7157		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
7158		data[4] = 0x02; /* per-pool */
7159		data += phdr->param_len;
7160	}
7161
7162	page_index->page_len = data - page_index->page_data;
7163	return (0);
7164}
7165
7166int
7167ctl_log_sense(struct ctl_scsiio *ctsio)
7168{
7169	struct ctl_lun *lun;
7170	int i, pc, page_code, subpage;
7171	int alloc_len, total_len;
7172	struct ctl_page_index *page_index;
7173	struct scsi_log_sense *cdb;
7174	struct scsi_log_header *header;
7175
7176	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
7177
7178	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7179	cdb = (struct scsi_log_sense *)ctsio->cdb;
7180	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
7181	page_code = cdb->page & SLS_PAGE_CODE;
7182	subpage = cdb->subpage;
7183	alloc_len = scsi_2btoul(cdb->length);
7184
7185	page_index = NULL;
7186	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
7187		page_index = &lun->log_pages.index[i];
7188
7189		/* Look for the right page code */
7190		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
7191			continue;
7192
7193		/* Look for the right subpage or the subpage wildcard*/
7194		if (page_index->subpage != subpage)
7195			continue;
7196
7197		break;
7198	}
7199	if (i >= CTL_NUM_LOG_PAGES) {
7200		ctl_set_invalid_field(ctsio,
7201				      /*sks_valid*/ 1,
7202				      /*command*/ 1,
7203				      /*field*/ 2,
7204				      /*bit_valid*/ 0,
7205				      /*bit*/ 0);
7206		ctl_done((union ctl_io *)ctsio);
7207		return (CTL_RETVAL_COMPLETE);
7208	}
7209
7210	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
7211
7212	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7213	ctsio->kern_sg_entries = 0;
7214	ctsio->kern_data_resid = 0;
7215	ctsio->kern_rel_offset = 0;
7216	if (total_len < alloc_len) {
7217		ctsio->residual = alloc_len - total_len;
7218		ctsio->kern_data_len = total_len;
7219		ctsio->kern_total_len = total_len;
7220	} else {
7221		ctsio->residual = 0;
7222		ctsio->kern_data_len = alloc_len;
7223		ctsio->kern_total_len = alloc_len;
7224	}
7225
7226	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7227	header->page = page_index->page_code;
7228	if (page_index->subpage) {
7229		header->page |= SL_SPF;
7230		header->subpage = page_index->subpage;
7231	}
7232	scsi_ulto2b(page_index->page_len, header->datalen);
7233
7234	/*
7235	 * Call the handler, if it exists, to update the
7236	 * page to the latest values.
7237	 */
7238	if (page_index->sense_handler != NULL)
7239		page_index->sense_handler(ctsio, page_index, pc);
7240
7241	memcpy(header + 1, page_index->page_data, page_index->page_len);
7242
7243	ctsio->scsi_status = SCSI_STATUS_OK;
7244	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7245	ctsio->be_move_done = ctl_config_move_done;
7246	ctl_datamove((union ctl_io *)ctsio);
7247
7248	return (CTL_RETVAL_COMPLETE);
7249}
7250
7251int
7252ctl_read_capacity(struct ctl_scsiio *ctsio)
7253{
7254	struct scsi_read_capacity *cdb;
7255	struct scsi_read_capacity_data *data;
7256	struct ctl_lun *lun;
7257	uint32_t lba;
7258
7259	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7260
7261	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7262
7263	lba = scsi_4btoul(cdb->addr);
7264	if (((cdb->pmi & SRC_PMI) == 0)
7265	 && (lba != 0)) {
7266		ctl_set_invalid_field(/*ctsio*/ ctsio,
7267				      /*sks_valid*/ 1,
7268				      /*command*/ 1,
7269				      /*field*/ 2,
7270				      /*bit_valid*/ 0,
7271				      /*bit*/ 0);
7272		ctl_done((union ctl_io *)ctsio);
7273		return (CTL_RETVAL_COMPLETE);
7274	}
7275
7276	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7277
7278	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7279	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7280	ctsio->residual = 0;
7281	ctsio->kern_data_len = sizeof(*data);
7282	ctsio->kern_total_len = sizeof(*data);
7283	ctsio->kern_data_resid = 0;
7284	ctsio->kern_rel_offset = 0;
7285	ctsio->kern_sg_entries = 0;
7286
7287	/*
7288	 * If the maximum LBA is greater than 0xfffffffe, the user must
7289	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7290	 * serivce action set.
7291	 */
7292	if (lun->be_lun->maxlba > 0xfffffffe)
7293		scsi_ulto4b(0xffffffff, data->addr);
7294	else
7295		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7296
7297	/*
7298	 * XXX KDM this may not be 512 bytes...
7299	 */
7300	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7301
7302	ctsio->scsi_status = SCSI_STATUS_OK;
7303
7304	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7305	ctsio->be_move_done = ctl_config_move_done;
7306	ctl_datamove((union ctl_io *)ctsio);
7307
7308	return (CTL_RETVAL_COMPLETE);
7309}
7310
7311int
7312ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7313{
7314	struct scsi_read_capacity_16 *cdb;
7315	struct scsi_read_capacity_data_long *data;
7316	struct ctl_lun *lun;
7317	uint64_t lba;
7318	uint32_t alloc_len;
7319
7320	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7321
7322	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7323
7324	alloc_len = scsi_4btoul(cdb->alloc_len);
7325	lba = scsi_8btou64(cdb->addr);
7326
7327	if ((cdb->reladr & SRC16_PMI)
7328	 && (lba != 0)) {
7329		ctl_set_invalid_field(/*ctsio*/ ctsio,
7330				      /*sks_valid*/ 1,
7331				      /*command*/ 1,
7332				      /*field*/ 2,
7333				      /*bit_valid*/ 0,
7334				      /*bit*/ 0);
7335		ctl_done((union ctl_io *)ctsio);
7336		return (CTL_RETVAL_COMPLETE);
7337	}
7338
7339	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7340
7341	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7342	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7343
7344	if (sizeof(*data) < alloc_len) {
7345		ctsio->residual = alloc_len - sizeof(*data);
7346		ctsio->kern_data_len = sizeof(*data);
7347		ctsio->kern_total_len = sizeof(*data);
7348	} else {
7349		ctsio->residual = 0;
7350		ctsio->kern_data_len = alloc_len;
7351		ctsio->kern_total_len = alloc_len;
7352	}
7353	ctsio->kern_data_resid = 0;
7354	ctsio->kern_rel_offset = 0;
7355	ctsio->kern_sg_entries = 0;
7356
7357	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7358	/* XXX KDM this may not be 512 bytes... */
7359	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7360	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7361	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7362	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7363		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7364
7365	ctsio->scsi_status = SCSI_STATUS_OK;
7366
7367	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7368	ctsio->be_move_done = ctl_config_move_done;
7369	ctl_datamove((union ctl_io *)ctsio);
7370
7371	return (CTL_RETVAL_COMPLETE);
7372}
7373
7374int
7375ctl_read_defect(struct ctl_scsiio *ctsio)
7376{
7377	struct scsi_read_defect_data_10 *ccb10;
7378	struct scsi_read_defect_data_12 *ccb12;
7379	struct scsi_read_defect_data_hdr_10 *data10;
7380	struct scsi_read_defect_data_hdr_12 *data12;
7381	struct ctl_lun *lun;
7382	uint32_t alloc_len, data_len;
7383	uint8_t format;
7384
7385	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7386
7387	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7388
7389	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7390		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7391		format = ccb10->format;
7392		alloc_len = scsi_2btoul(ccb10->alloc_length);
7393		data_len = sizeof(*data10);
7394	} else {
7395		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7396		format = ccb12->format;
7397		alloc_len = scsi_4btoul(ccb12->alloc_length);
7398		data_len = sizeof(*data12);
7399	}
7400	if (alloc_len == 0) {
7401		ctl_set_success(ctsio);
7402		ctl_done((union ctl_io *)ctsio);
7403		return (CTL_RETVAL_COMPLETE);
7404	}
7405
7406	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7407	if (data_len < alloc_len) {
7408		ctsio->residual = alloc_len - data_len;
7409		ctsio->kern_data_len = data_len;
7410		ctsio->kern_total_len = data_len;
7411	} else {
7412		ctsio->residual = 0;
7413		ctsio->kern_data_len = alloc_len;
7414		ctsio->kern_total_len = alloc_len;
7415	}
7416	ctsio->kern_data_resid = 0;
7417	ctsio->kern_rel_offset = 0;
7418	ctsio->kern_sg_entries = 0;
7419
7420	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7421		data10 = (struct scsi_read_defect_data_hdr_10 *)
7422		    ctsio->kern_data_ptr;
7423		data10->format = format;
7424		scsi_ulto2b(0, data10->length);
7425	} else {
7426		data12 = (struct scsi_read_defect_data_hdr_12 *)
7427		    ctsio->kern_data_ptr;
7428		data12->format = format;
7429		scsi_ulto2b(0, data12->generation);
7430		scsi_ulto4b(0, data12->length);
7431	}
7432
7433	ctsio->scsi_status = SCSI_STATUS_OK;
7434	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7435	ctsio->be_move_done = ctl_config_move_done;
7436	ctl_datamove((union ctl_io *)ctsio);
7437	return (CTL_RETVAL_COMPLETE);
7438}
7439
7440int
7441ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7442{
7443	struct scsi_maintenance_in *cdb;
7444	int retval;
7445	int alloc_len, ext, total_len = 0, g, p, pc, pg;
7446	int num_target_port_groups, num_target_ports, single;
7447	struct ctl_lun *lun;
7448	struct ctl_softc *softc;
7449	struct ctl_port *port;
7450	struct scsi_target_group_data *rtg_ptr;
7451	struct scsi_target_group_data_extended *rtg_ext_ptr;
7452	struct scsi_target_port_group_descriptor *tpg_desc;
7453
7454	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7455
7456	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7457	softc = control_softc;
7458	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7459
7460	retval = CTL_RETVAL_COMPLETE;
7461
7462	switch (cdb->byte2 & STG_PDF_MASK) {
7463	case STG_PDF_LENGTH:
7464		ext = 0;
7465		break;
7466	case STG_PDF_EXTENDED:
7467		ext = 1;
7468		break;
7469	default:
7470		ctl_set_invalid_field(/*ctsio*/ ctsio,
7471				      /*sks_valid*/ 1,
7472				      /*command*/ 1,
7473				      /*field*/ 2,
7474				      /*bit_valid*/ 1,
7475				      /*bit*/ 5);
7476		ctl_done((union ctl_io *)ctsio);
7477		return(retval);
7478	}
7479
7480	single = ctl_is_single;
7481	if (single)
7482		num_target_port_groups = 1;
7483	else
7484		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7485	num_target_ports = 0;
7486	mtx_lock(&softc->ctl_lock);
7487	STAILQ_FOREACH(port, &softc->port_list, links) {
7488		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7489			continue;
7490		if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7491			continue;
7492		num_target_ports++;
7493	}
7494	mtx_unlock(&softc->ctl_lock);
7495
7496	if (ext)
7497		total_len = sizeof(struct scsi_target_group_data_extended);
7498	else
7499		total_len = sizeof(struct scsi_target_group_data);
7500	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7501		num_target_port_groups +
7502	    sizeof(struct scsi_target_port_descriptor) *
7503		num_target_ports * num_target_port_groups;
7504
7505	alloc_len = scsi_4btoul(cdb->length);
7506
7507	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7508
7509	ctsio->kern_sg_entries = 0;
7510
7511	if (total_len < alloc_len) {
7512		ctsio->residual = alloc_len - total_len;
7513		ctsio->kern_data_len = total_len;
7514		ctsio->kern_total_len = total_len;
7515	} else {
7516		ctsio->residual = 0;
7517		ctsio->kern_data_len = alloc_len;
7518		ctsio->kern_total_len = alloc_len;
7519	}
7520	ctsio->kern_data_resid = 0;
7521	ctsio->kern_rel_offset = 0;
7522
7523	if (ext) {
7524		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7525		    ctsio->kern_data_ptr;
7526		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7527		rtg_ext_ptr->format_type = 0x10;
7528		rtg_ext_ptr->implicit_transition_time = 0;
7529		tpg_desc = &rtg_ext_ptr->groups[0];
7530	} else {
7531		rtg_ptr = (struct scsi_target_group_data *)
7532		    ctsio->kern_data_ptr;
7533		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7534		tpg_desc = &rtg_ptr->groups[0];
7535	}
7536
7537	pg = ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS;
7538	mtx_lock(&softc->ctl_lock);
7539	for (g = 0; g < num_target_port_groups; g++) {
7540		if (g == pg)
7541			tpg_desc->pref_state = TPG_PRIMARY |
7542			    TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7543		else
7544			tpg_desc->pref_state =
7545			    TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7546		tpg_desc->support = TPG_AO_SUP;
7547		if (!single)
7548			tpg_desc->support |= TPG_AN_SUP;
7549		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7550		tpg_desc->status = TPG_IMPLICIT;
7551		pc = 0;
7552		STAILQ_FOREACH(port, &softc->port_list, links) {
7553			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7554				continue;
7555			if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7556			    CTL_MAX_LUNS)
7557				continue;
7558			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7559			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7560			    relative_target_port_identifier);
7561			pc++;
7562		}
7563		tpg_desc->target_port_count = pc;
7564		tpg_desc = (struct scsi_target_port_group_descriptor *)
7565		    &tpg_desc->descriptors[pc];
7566	}
7567	mtx_unlock(&softc->ctl_lock);
7568
7569	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7570	ctsio->be_move_done = ctl_config_move_done;
7571
7572	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7573			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7574			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7575			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7576			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7577
7578	ctl_datamove((union ctl_io *)ctsio);
7579	return(retval);
7580}
7581
7582int
7583ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7584{
7585	struct ctl_lun *lun;
7586	struct scsi_report_supported_opcodes *cdb;
7587	const struct ctl_cmd_entry *entry, *sentry;
7588	struct scsi_report_supported_opcodes_all *all;
7589	struct scsi_report_supported_opcodes_descr *descr;
7590	struct scsi_report_supported_opcodes_one *one;
7591	int retval;
7592	int alloc_len, total_len;
7593	int opcode, service_action, i, j, num;
7594
7595	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7596
7597	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7598	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7599
7600	retval = CTL_RETVAL_COMPLETE;
7601
7602	opcode = cdb->requested_opcode;
7603	service_action = scsi_2btoul(cdb->requested_service_action);
7604	switch (cdb->options & RSO_OPTIONS_MASK) {
7605	case RSO_OPTIONS_ALL:
7606		num = 0;
7607		for (i = 0; i < 256; i++) {
7608			entry = &ctl_cmd_table[i];
7609			if (entry->flags & CTL_CMD_FLAG_SA5) {
7610				for (j = 0; j < 32; j++) {
7611					sentry = &((const struct ctl_cmd_entry *)
7612					    entry->execute)[j];
7613					if (ctl_cmd_applicable(
7614					    lun->be_lun->lun_type, sentry))
7615						num++;
7616				}
7617			} else {
7618				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7619				    entry))
7620					num++;
7621			}
7622		}
7623		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7624		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7625		break;
7626	case RSO_OPTIONS_OC:
7627		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7628			ctl_set_invalid_field(/*ctsio*/ ctsio,
7629					      /*sks_valid*/ 1,
7630					      /*command*/ 1,
7631					      /*field*/ 2,
7632					      /*bit_valid*/ 1,
7633					      /*bit*/ 2);
7634			ctl_done((union ctl_io *)ctsio);
7635			return (CTL_RETVAL_COMPLETE);
7636		}
7637		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7638		break;
7639	case RSO_OPTIONS_OC_SA:
7640		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7641		    service_action >= 32) {
7642			ctl_set_invalid_field(/*ctsio*/ ctsio,
7643					      /*sks_valid*/ 1,
7644					      /*command*/ 1,
7645					      /*field*/ 2,
7646					      /*bit_valid*/ 1,
7647					      /*bit*/ 2);
7648			ctl_done((union ctl_io *)ctsio);
7649			return (CTL_RETVAL_COMPLETE);
7650		}
7651		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7652		break;
7653	default:
7654		ctl_set_invalid_field(/*ctsio*/ ctsio,
7655				      /*sks_valid*/ 1,
7656				      /*command*/ 1,
7657				      /*field*/ 2,
7658				      /*bit_valid*/ 1,
7659				      /*bit*/ 2);
7660		ctl_done((union ctl_io *)ctsio);
7661		return (CTL_RETVAL_COMPLETE);
7662	}
7663
7664	alloc_len = scsi_4btoul(cdb->length);
7665
7666	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7667
7668	ctsio->kern_sg_entries = 0;
7669
7670	if (total_len < alloc_len) {
7671		ctsio->residual = alloc_len - total_len;
7672		ctsio->kern_data_len = total_len;
7673		ctsio->kern_total_len = total_len;
7674	} else {
7675		ctsio->residual = 0;
7676		ctsio->kern_data_len = alloc_len;
7677		ctsio->kern_total_len = alloc_len;
7678	}
7679	ctsio->kern_data_resid = 0;
7680	ctsio->kern_rel_offset = 0;
7681
7682	switch (cdb->options & RSO_OPTIONS_MASK) {
7683	case RSO_OPTIONS_ALL:
7684		all = (struct scsi_report_supported_opcodes_all *)
7685		    ctsio->kern_data_ptr;
7686		num = 0;
7687		for (i = 0; i < 256; i++) {
7688			entry = &ctl_cmd_table[i];
7689			if (entry->flags & CTL_CMD_FLAG_SA5) {
7690				for (j = 0; j < 32; j++) {
7691					sentry = &((const struct ctl_cmd_entry *)
7692					    entry->execute)[j];
7693					if (!ctl_cmd_applicable(
7694					    lun->be_lun->lun_type, sentry))
7695						continue;
7696					descr = &all->descr[num++];
7697					descr->opcode = i;
7698					scsi_ulto2b(j, descr->service_action);
7699					descr->flags = RSO_SERVACTV;
7700					scsi_ulto2b(sentry->length,
7701					    descr->cdb_length);
7702				}
7703			} else {
7704				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7705				    entry))
7706					continue;
7707				descr = &all->descr[num++];
7708				descr->opcode = i;
7709				scsi_ulto2b(0, descr->service_action);
7710				descr->flags = 0;
7711				scsi_ulto2b(entry->length, descr->cdb_length);
7712			}
7713		}
7714		scsi_ulto4b(
7715		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7716		    all->length);
7717		break;
7718	case RSO_OPTIONS_OC:
7719		one = (struct scsi_report_supported_opcodes_one *)
7720		    ctsio->kern_data_ptr;
7721		entry = &ctl_cmd_table[opcode];
7722		goto fill_one;
7723	case RSO_OPTIONS_OC_SA:
7724		one = (struct scsi_report_supported_opcodes_one *)
7725		    ctsio->kern_data_ptr;
7726		entry = &ctl_cmd_table[opcode];
7727		entry = &((const struct ctl_cmd_entry *)
7728		    entry->execute)[service_action];
7729fill_one:
7730		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7731			one->support = 3;
7732			scsi_ulto2b(entry->length, one->cdb_length);
7733			one->cdb_usage[0] = opcode;
7734			memcpy(&one->cdb_usage[1], entry->usage,
7735			    entry->length - 1);
7736		} else
7737			one->support = 1;
7738		break;
7739	}
7740
7741	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7742	ctsio->be_move_done = ctl_config_move_done;
7743
7744	ctl_datamove((union ctl_io *)ctsio);
7745	return(retval);
7746}
7747
7748int
7749ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7750{
7751	struct ctl_lun *lun;
7752	struct scsi_report_supported_tmf *cdb;
7753	struct scsi_report_supported_tmf_data *data;
7754	int retval;
7755	int alloc_len, total_len;
7756
7757	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7758
7759	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7760	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7761
7762	retval = CTL_RETVAL_COMPLETE;
7763
7764	total_len = sizeof(struct scsi_report_supported_tmf_data);
7765	alloc_len = scsi_4btoul(cdb->length);
7766
7767	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7768
7769	ctsio->kern_sg_entries = 0;
7770
7771	if (total_len < alloc_len) {
7772		ctsio->residual = alloc_len - total_len;
7773		ctsio->kern_data_len = total_len;
7774		ctsio->kern_total_len = total_len;
7775	} else {
7776		ctsio->residual = 0;
7777		ctsio->kern_data_len = alloc_len;
7778		ctsio->kern_total_len = alloc_len;
7779	}
7780	ctsio->kern_data_resid = 0;
7781	ctsio->kern_rel_offset = 0;
7782
7783	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7784	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7785	data->byte2 |= RST_ITNRS;
7786
7787	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7788	ctsio->be_move_done = ctl_config_move_done;
7789
7790	ctl_datamove((union ctl_io *)ctsio);
7791	return (retval);
7792}
7793
7794int
7795ctl_report_timestamp(struct ctl_scsiio *ctsio)
7796{
7797	struct ctl_lun *lun;
7798	struct scsi_report_timestamp *cdb;
7799	struct scsi_report_timestamp_data *data;
7800	struct timeval tv;
7801	int64_t timestamp;
7802	int retval;
7803	int alloc_len, total_len;
7804
7805	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7806
7807	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7808	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7809
7810	retval = CTL_RETVAL_COMPLETE;
7811
7812	total_len = sizeof(struct scsi_report_timestamp_data);
7813	alloc_len = scsi_4btoul(cdb->length);
7814
7815	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7816
7817	ctsio->kern_sg_entries = 0;
7818
7819	if (total_len < alloc_len) {
7820		ctsio->residual = alloc_len - total_len;
7821		ctsio->kern_data_len = total_len;
7822		ctsio->kern_total_len = total_len;
7823	} else {
7824		ctsio->residual = 0;
7825		ctsio->kern_data_len = alloc_len;
7826		ctsio->kern_total_len = alloc_len;
7827	}
7828	ctsio->kern_data_resid = 0;
7829	ctsio->kern_rel_offset = 0;
7830
7831	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7832	scsi_ulto2b(sizeof(*data) - 2, data->length);
7833	data->origin = RTS_ORIG_OUTSIDE;
7834	getmicrotime(&tv);
7835	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7836	scsi_ulto4b(timestamp >> 16, data->timestamp);
7837	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7838
7839	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7840	ctsio->be_move_done = ctl_config_move_done;
7841
7842	ctl_datamove((union ctl_io *)ctsio);
7843	return (retval);
7844}
7845
7846int
7847ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7848{
7849	struct scsi_per_res_in *cdb;
7850	int alloc_len, total_len = 0;
7851	/* struct scsi_per_res_in_rsrv in_data; */
7852	struct ctl_lun *lun;
7853	struct ctl_softc *softc;
7854
7855	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7856
7857	softc = control_softc;
7858
7859	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7860
7861	alloc_len = scsi_2btoul(cdb->length);
7862
7863	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7864
7865retry:
7866	mtx_lock(&lun->lun_lock);
7867	switch (cdb->action) {
7868	case SPRI_RK: /* read keys */
7869		total_len = sizeof(struct scsi_per_res_in_keys) +
7870			lun->pr_key_count *
7871			sizeof(struct scsi_per_res_key);
7872		break;
7873	case SPRI_RR: /* read reservation */
7874		if (lun->flags & CTL_LUN_PR_RESERVED)
7875			total_len = sizeof(struct scsi_per_res_in_rsrv);
7876		else
7877			total_len = sizeof(struct scsi_per_res_in_header);
7878		break;
7879	case SPRI_RC: /* report capabilities */
7880		total_len = sizeof(struct scsi_per_res_cap);
7881		break;
7882	case SPRI_RS: /* read full status */
7883		total_len = sizeof(struct scsi_per_res_in_header) +
7884		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7885		    lun->pr_key_count;
7886		break;
7887	default:
7888		panic("Invalid PR type %x", cdb->action);
7889	}
7890	mtx_unlock(&lun->lun_lock);
7891
7892	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7893
7894	if (total_len < alloc_len) {
7895		ctsio->residual = alloc_len - total_len;
7896		ctsio->kern_data_len = total_len;
7897		ctsio->kern_total_len = total_len;
7898	} else {
7899		ctsio->residual = 0;
7900		ctsio->kern_data_len = alloc_len;
7901		ctsio->kern_total_len = alloc_len;
7902	}
7903
7904	ctsio->kern_data_resid = 0;
7905	ctsio->kern_rel_offset = 0;
7906	ctsio->kern_sg_entries = 0;
7907
7908	mtx_lock(&lun->lun_lock);
7909	switch (cdb->action) {
7910	case SPRI_RK: { // read keys
7911        struct scsi_per_res_in_keys *res_keys;
7912		int i, key_count;
7913
7914		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7915
7916		/*
7917		 * We had to drop the lock to allocate our buffer, which
7918		 * leaves time for someone to come in with another
7919		 * persistent reservation.  (That is unlikely, though,
7920		 * since this should be the only persistent reservation
7921		 * command active right now.)
7922		 */
7923		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7924		    (lun->pr_key_count *
7925		     sizeof(struct scsi_per_res_key)))){
7926			mtx_unlock(&lun->lun_lock);
7927			free(ctsio->kern_data_ptr, M_CTL);
7928			printf("%s: reservation length changed, retrying\n",
7929			       __func__);
7930			goto retry;
7931		}
7932
7933		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7934
7935		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7936			     lun->pr_key_count, res_keys->header.length);
7937
7938		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7939			if (lun->pr_keys[i] == 0)
7940				continue;
7941
7942			/*
7943			 * We used lun->pr_key_count to calculate the
7944			 * size to allocate.  If it turns out the number of
7945			 * initiators with the registered flag set is
7946			 * larger than that (i.e. they haven't been kept in
7947			 * sync), we've got a problem.
7948			 */
7949			if (key_count >= lun->pr_key_count) {
7950#ifdef NEEDTOPORT
7951				csevent_log(CSC_CTL | CSC_SHELF_SW |
7952					    CTL_PR_ERROR,
7953					    csevent_LogType_Fault,
7954					    csevent_AlertLevel_Yellow,
7955					    csevent_FRU_ShelfController,
7956					    csevent_FRU_Firmware,
7957				        csevent_FRU_Unknown,
7958					    "registered keys %d >= key "
7959					    "count %d", key_count,
7960					    lun->pr_key_count);
7961#endif
7962				key_count++;
7963				continue;
7964			}
7965			scsi_u64to8b(lun->pr_keys[i],
7966			    res_keys->keys[key_count].key);
7967			key_count++;
7968		}
7969		break;
7970	}
7971	case SPRI_RR: { // read reservation
7972		struct scsi_per_res_in_rsrv *res;
7973		int tmp_len, header_only;
7974
7975		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7976
7977		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7978
7979		if (lun->flags & CTL_LUN_PR_RESERVED)
7980		{
7981			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7982			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7983				    res->header.length);
7984			header_only = 0;
7985		} else {
7986			tmp_len = sizeof(struct scsi_per_res_in_header);
7987			scsi_ulto4b(0, res->header.length);
7988			header_only = 1;
7989		}
7990
7991		/*
7992		 * We had to drop the lock to allocate our buffer, which
7993		 * leaves time for someone to come in with another
7994		 * persistent reservation.  (That is unlikely, though,
7995		 * since this should be the only persistent reservation
7996		 * command active right now.)
7997		 */
7998		if (tmp_len != total_len) {
7999			mtx_unlock(&lun->lun_lock);
8000			free(ctsio->kern_data_ptr, M_CTL);
8001			printf("%s: reservation status changed, retrying\n",
8002			       __func__);
8003			goto retry;
8004		}
8005
8006		/*
8007		 * No reservation held, so we're done.
8008		 */
8009		if (header_only != 0)
8010			break;
8011
8012		/*
8013		 * If the registration is an All Registrants type, the key
8014		 * is 0, since it doesn't really matter.
8015		 */
8016		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8017			scsi_u64to8b(lun->pr_keys[lun->pr_res_idx],
8018			    res->data.reservation);
8019		}
8020		res->data.scopetype = lun->res_type;
8021		break;
8022	}
8023	case SPRI_RC:     //report capabilities
8024	{
8025		struct scsi_per_res_cap *res_cap;
8026		uint16_t type_mask;
8027
8028		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
8029		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
8030		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
8031		type_mask = SPRI_TM_WR_EX_AR |
8032			    SPRI_TM_EX_AC_RO |
8033			    SPRI_TM_WR_EX_RO |
8034			    SPRI_TM_EX_AC |
8035			    SPRI_TM_WR_EX |
8036			    SPRI_TM_EX_AC_AR;
8037		scsi_ulto2b(type_mask, res_cap->type_mask);
8038		break;
8039	}
8040	case SPRI_RS: { // read full status
8041		struct scsi_per_res_in_full *res_status;
8042		struct scsi_per_res_in_full_desc *res_desc;
8043		struct ctl_port *port;
8044		int i, len;
8045
8046		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
8047
8048		/*
8049		 * We had to drop the lock to allocate our buffer, which
8050		 * leaves time for someone to come in with another
8051		 * persistent reservation.  (That is unlikely, though,
8052		 * since this should be the only persistent reservation
8053		 * command active right now.)
8054		 */
8055		if (total_len < (sizeof(struct scsi_per_res_in_header) +
8056		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
8057		     lun->pr_key_count)){
8058			mtx_unlock(&lun->lun_lock);
8059			free(ctsio->kern_data_ptr, M_CTL);
8060			printf("%s: reservation length changed, retrying\n",
8061			       __func__);
8062			goto retry;
8063		}
8064
8065		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
8066
8067		res_desc = &res_status->desc[0];
8068		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
8069			if (lun->pr_keys[i] == 0)
8070				continue;
8071
8072			scsi_u64to8b(lun->pr_keys[i], res_desc->res_key.key);
8073			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
8074			    (lun->pr_res_idx == i ||
8075			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
8076				res_desc->flags = SPRI_FULL_R_HOLDER;
8077				res_desc->scopetype = lun->res_type;
8078			}
8079			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
8080			    res_desc->rel_trgt_port_id);
8081			len = 0;
8082			port = softc->ctl_ports[
8083			    ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
8084			if (port != NULL)
8085				len = ctl_create_iid(port,
8086				    i % CTL_MAX_INIT_PER_PORT,
8087				    res_desc->transport_id);
8088			scsi_ulto4b(len, res_desc->additional_length);
8089			res_desc = (struct scsi_per_res_in_full_desc *)
8090			    &res_desc->transport_id[len];
8091		}
8092		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
8093		    res_status->header.length);
8094		break;
8095	}
8096	default:
8097		/*
8098		 * This is a bug, because we just checked for this above,
8099		 * and should have returned an error.
8100		 */
8101		panic("Invalid PR type %x", cdb->action);
8102		break; /* NOTREACHED */
8103	}
8104	mtx_unlock(&lun->lun_lock);
8105
8106	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8107	ctsio->be_move_done = ctl_config_move_done;
8108
8109	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
8110			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
8111			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
8112			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
8113			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
8114
8115	ctl_datamove((union ctl_io *)ctsio);
8116
8117	return (CTL_RETVAL_COMPLETE);
8118}
8119
8120/*
8121 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
8122 * it should return.
8123 */
8124static int
8125ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
8126		uint64_t sa_res_key, uint8_t type, uint32_t residx,
8127		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
8128		struct scsi_per_res_out_parms* param)
8129{
8130	union ctl_ha_msg persis_io;
8131	int retval, i;
8132	int isc_retval;
8133
8134	retval = 0;
8135
8136	mtx_lock(&lun->lun_lock);
8137	if (sa_res_key == 0) {
8138		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8139			/* validate scope and type */
8140			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8141			     SPR_LU_SCOPE) {
8142				mtx_unlock(&lun->lun_lock);
8143				ctl_set_invalid_field(/*ctsio*/ ctsio,
8144						      /*sks_valid*/ 1,
8145						      /*command*/ 1,
8146						      /*field*/ 2,
8147						      /*bit_valid*/ 1,
8148						      /*bit*/ 4);
8149				ctl_done((union ctl_io *)ctsio);
8150				return (1);
8151			}
8152
8153		        if (type>8 || type==2 || type==4 || type==0) {
8154				mtx_unlock(&lun->lun_lock);
8155				ctl_set_invalid_field(/*ctsio*/ ctsio,
8156       	           				      /*sks_valid*/ 1,
8157						      /*command*/ 1,
8158						      /*field*/ 2,
8159						      /*bit_valid*/ 1,
8160						      /*bit*/ 0);
8161				ctl_done((union ctl_io *)ctsio);
8162				return (1);
8163		        }
8164
8165			/*
8166			 * Unregister everybody else and build UA for
8167			 * them
8168			 */
8169			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8170				if (i == residx || lun->pr_keys[i] == 0)
8171					continue;
8172
8173				if (!persis_offset
8174				 && i <CTL_MAX_INITIATORS)
8175					lun->pending_ua[i] |=
8176						CTL_UA_REG_PREEMPT;
8177				else if (persis_offset
8178				      && i >= persis_offset)
8179					lun->pending_ua[i-persis_offset] |=
8180						CTL_UA_REG_PREEMPT;
8181				lun->pr_keys[i] = 0;
8182			}
8183			lun->pr_key_count = 1;
8184			lun->res_type = type;
8185			if (lun->res_type != SPR_TYPE_WR_EX_AR
8186			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8187				lun->pr_res_idx = residx;
8188
8189			/* send msg to other side */
8190			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8191			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8192			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8193			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8194			persis_io.pr.pr_info.res_type = type;
8195			memcpy(persis_io.pr.pr_info.sa_res_key,
8196			       param->serv_act_res_key,
8197			       sizeof(param->serv_act_res_key));
8198			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8199			     &persis_io, sizeof(persis_io), 0)) >
8200			     CTL_HA_STATUS_SUCCESS) {
8201				printf("CTL:Persis Out error returned "
8202				       "from ctl_ha_msg_send %d\n",
8203				       isc_retval);
8204			}
8205		} else {
8206			/* not all registrants */
8207			mtx_unlock(&lun->lun_lock);
8208			free(ctsio->kern_data_ptr, M_CTL);
8209			ctl_set_invalid_field(ctsio,
8210					      /*sks_valid*/ 1,
8211					      /*command*/ 0,
8212					      /*field*/ 8,
8213					      /*bit_valid*/ 0,
8214					      /*bit*/ 0);
8215			ctl_done((union ctl_io *)ctsio);
8216			return (1);
8217		}
8218	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8219		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8220		int found = 0;
8221
8222		if (res_key == sa_res_key) {
8223			/* special case */
8224			/*
8225			 * The spec implies this is not good but doesn't
8226			 * say what to do. There are two choices either
8227			 * generate a res conflict or check condition
8228			 * with illegal field in parameter data. Since
8229			 * that is what is done when the sa_res_key is
8230			 * zero I'll take that approach since this has
8231			 * to do with the sa_res_key.
8232			 */
8233			mtx_unlock(&lun->lun_lock);
8234			free(ctsio->kern_data_ptr, M_CTL);
8235			ctl_set_invalid_field(ctsio,
8236					      /*sks_valid*/ 1,
8237					      /*command*/ 0,
8238					      /*field*/ 8,
8239					      /*bit_valid*/ 0,
8240					      /*bit*/ 0);
8241			ctl_done((union ctl_io *)ctsio);
8242			return (1);
8243		}
8244
8245		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8246			if (lun->pr_keys[i] != sa_res_key)
8247				continue;
8248
8249			found = 1;
8250			lun->pr_keys[i] = 0;
8251			lun->pr_key_count--;
8252
8253			if (!persis_offset && i < CTL_MAX_INITIATORS)
8254				lun->pending_ua[i] |= CTL_UA_REG_PREEMPT;
8255			else if (persis_offset && i >= persis_offset)
8256				lun->pending_ua[i-persis_offset] |=
8257					CTL_UA_REG_PREEMPT;
8258		}
8259		if (!found) {
8260			mtx_unlock(&lun->lun_lock);
8261			free(ctsio->kern_data_ptr, M_CTL);
8262			ctl_set_reservation_conflict(ctsio);
8263			ctl_done((union ctl_io *)ctsio);
8264			return (CTL_RETVAL_COMPLETE);
8265		}
8266		/* send msg to other side */
8267		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8268		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8269		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8270		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8271		persis_io.pr.pr_info.res_type = type;
8272		memcpy(persis_io.pr.pr_info.sa_res_key,
8273		       param->serv_act_res_key,
8274		       sizeof(param->serv_act_res_key));
8275		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8276		     &persis_io, sizeof(persis_io), 0)) >
8277		     CTL_HA_STATUS_SUCCESS) {
8278			printf("CTL:Persis Out error returned from "
8279			       "ctl_ha_msg_send %d\n", isc_retval);
8280		}
8281	} else {
8282		/* Reserved but not all registrants */
8283		/* sa_res_key is res holder */
8284		if (sa_res_key == lun->pr_keys[lun->pr_res_idx]) {
8285			/* validate scope and type */
8286			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8287			     SPR_LU_SCOPE) {
8288				mtx_unlock(&lun->lun_lock);
8289				ctl_set_invalid_field(/*ctsio*/ ctsio,
8290						      /*sks_valid*/ 1,
8291						      /*command*/ 1,
8292						      /*field*/ 2,
8293						      /*bit_valid*/ 1,
8294						      /*bit*/ 4);
8295				ctl_done((union ctl_io *)ctsio);
8296				return (1);
8297			}
8298
8299			if (type>8 || type==2 || type==4 || type==0) {
8300				mtx_unlock(&lun->lun_lock);
8301				ctl_set_invalid_field(/*ctsio*/ ctsio,
8302						      /*sks_valid*/ 1,
8303						      /*command*/ 1,
8304						      /*field*/ 2,
8305						      /*bit_valid*/ 1,
8306						      /*bit*/ 0);
8307				ctl_done((union ctl_io *)ctsio);
8308				return (1);
8309			}
8310
8311			/*
8312			 * Do the following:
8313			 * if sa_res_key != res_key remove all
8314			 * registrants w/sa_res_key and generate UA
8315			 * for these registrants(Registrations
8316			 * Preempted) if it wasn't an exclusive
8317			 * reservation generate UA(Reservations
8318			 * Preempted) for all other registered nexuses
8319			 * if the type has changed. Establish the new
8320			 * reservation and holder. If res_key and
8321			 * sa_res_key are the same do the above
8322			 * except don't unregister the res holder.
8323			 */
8324
8325			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8326				if (i == residx || lun->pr_keys[i] == 0)
8327					continue;
8328
8329				if (sa_res_key == lun->pr_keys[i]) {
8330					lun->pr_keys[i] = 0;
8331					lun->pr_key_count--;
8332
8333					if (!persis_offset
8334					 && i < CTL_MAX_INITIATORS)
8335						lun->pending_ua[i] |=
8336							CTL_UA_REG_PREEMPT;
8337					else if (persis_offset
8338					      && i >= persis_offset)
8339						lun->pending_ua[i-persis_offset] |=
8340						  CTL_UA_REG_PREEMPT;
8341				} else if (type != lun->res_type
8342					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8343					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8344						if (!persis_offset
8345						 && i < CTL_MAX_INITIATORS)
8346							lun->pending_ua[i] |=
8347							CTL_UA_RES_RELEASE;
8348						else if (persis_offset
8349						      && i >= persis_offset)
8350							lun->pending_ua[
8351							i-persis_offset] |=
8352							CTL_UA_RES_RELEASE;
8353				}
8354			}
8355			lun->res_type = type;
8356			if (lun->res_type != SPR_TYPE_WR_EX_AR
8357			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8358				lun->pr_res_idx = residx;
8359			else
8360				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8361
8362			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8363			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8364			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8365			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8366			persis_io.pr.pr_info.res_type = type;
8367			memcpy(persis_io.pr.pr_info.sa_res_key,
8368			       param->serv_act_res_key,
8369			       sizeof(param->serv_act_res_key));
8370			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8371			     &persis_io, sizeof(persis_io), 0)) >
8372			     CTL_HA_STATUS_SUCCESS) {
8373				printf("CTL:Persis Out error returned "
8374				       "from ctl_ha_msg_send %d\n",
8375				       isc_retval);
8376			}
8377		} else {
8378			/*
8379			 * sa_res_key is not the res holder just
8380			 * remove registrants
8381			 */
8382			int found=0;
8383
8384			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8385				if (sa_res_key != lun->pr_keys[i])
8386					continue;
8387
8388				found = 1;
8389				lun->pr_keys[i] = 0;
8390				lun->pr_key_count--;
8391
8392				if (!persis_offset
8393				 && i < CTL_MAX_INITIATORS)
8394					lun->pending_ua[i] |=
8395						CTL_UA_REG_PREEMPT;
8396				else if (persis_offset
8397				      && i >= persis_offset)
8398					lun->pending_ua[i-persis_offset] |=
8399						CTL_UA_REG_PREEMPT;
8400			}
8401
8402			if (!found) {
8403				mtx_unlock(&lun->lun_lock);
8404				free(ctsio->kern_data_ptr, M_CTL);
8405				ctl_set_reservation_conflict(ctsio);
8406				ctl_done((union ctl_io *)ctsio);
8407		        	return (1);
8408			}
8409			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8410			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8411			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8412			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8413			persis_io.pr.pr_info.res_type = type;
8414			memcpy(persis_io.pr.pr_info.sa_res_key,
8415			       param->serv_act_res_key,
8416			       sizeof(param->serv_act_res_key));
8417			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8418			     &persis_io, sizeof(persis_io), 0)) >
8419			     CTL_HA_STATUS_SUCCESS) {
8420				printf("CTL:Persis Out error returned "
8421				       "from ctl_ha_msg_send %d\n",
8422				isc_retval);
8423			}
8424		}
8425	}
8426
8427	lun->PRGeneration++;
8428	mtx_unlock(&lun->lun_lock);
8429
8430	return (retval);
8431}
8432
8433static void
8434ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8435{
8436	uint64_t sa_res_key;
8437	int i;
8438
8439	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8440
8441	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8442	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8443	 || sa_res_key != lun->pr_keys[lun->pr_res_idx]) {
8444		if (sa_res_key == 0) {
8445			/*
8446			 * Unregister everybody else and build UA for
8447			 * them
8448			 */
8449			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8450				if (i == msg->pr.pr_info.residx ||
8451				    lun->pr_keys[i] == 0)
8452					continue;
8453
8454				if (!persis_offset
8455				 && i < CTL_MAX_INITIATORS)
8456					lun->pending_ua[i] |=
8457						CTL_UA_REG_PREEMPT;
8458				else if (persis_offset && i >= persis_offset)
8459					lun->pending_ua[i - persis_offset] |=
8460						CTL_UA_REG_PREEMPT;
8461				lun->pr_keys[i] = 0;
8462			}
8463
8464			lun->pr_key_count = 1;
8465			lun->res_type = msg->pr.pr_info.res_type;
8466			if (lun->res_type != SPR_TYPE_WR_EX_AR
8467			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8468				lun->pr_res_idx = msg->pr.pr_info.residx;
8469		} else {
8470		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8471				if (sa_res_key == lun->pr_keys[i])
8472					continue;
8473
8474				lun->pr_keys[i] = 0;
8475				lun->pr_key_count--;
8476
8477				if (!persis_offset
8478				 && i < persis_offset)
8479					lun->pending_ua[i] |=
8480						CTL_UA_REG_PREEMPT;
8481				else if (persis_offset
8482				      && i >= persis_offset)
8483					lun->pending_ua[i - persis_offset] |=
8484						CTL_UA_REG_PREEMPT;
8485			}
8486		}
8487	} else {
8488		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8489			if (i == msg->pr.pr_info.residx ||
8490			    lun->pr_keys[i] == 0)
8491				continue;
8492
8493			if (sa_res_key == lun->pr_keys[i]) {
8494				lun->pr_keys[i] = 0;
8495				lun->pr_key_count--;
8496				if (!persis_offset
8497				 && i < CTL_MAX_INITIATORS)
8498					lun->pending_ua[i] |=
8499						CTL_UA_REG_PREEMPT;
8500				else if (persis_offset
8501				      && i >= persis_offset)
8502					lun->pending_ua[i - persis_offset] |=
8503						CTL_UA_REG_PREEMPT;
8504			} else if (msg->pr.pr_info.res_type != lun->res_type
8505				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8506				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8507					if (!persis_offset
8508					 && i < persis_offset)
8509						lun->pending_ua[i] |=
8510							CTL_UA_RES_RELEASE;
8511					else if (persis_offset
8512					      && i >= persis_offset)
8513					lun->pending_ua[i - persis_offset] |=
8514						CTL_UA_RES_RELEASE;
8515			}
8516		}
8517		lun->res_type = msg->pr.pr_info.res_type;
8518		if (lun->res_type != SPR_TYPE_WR_EX_AR
8519		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8520			lun->pr_res_idx = msg->pr.pr_info.residx;
8521		else
8522			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8523	}
8524	lun->PRGeneration++;
8525
8526}
8527
8528
8529int
8530ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8531{
8532	int retval;
8533	int isc_retval;
8534	u_int32_t param_len;
8535	struct scsi_per_res_out *cdb;
8536	struct ctl_lun *lun;
8537	struct scsi_per_res_out_parms* param;
8538	struct ctl_softc *softc;
8539	uint32_t residx;
8540	uint64_t res_key, sa_res_key;
8541	uint8_t type;
8542	union ctl_ha_msg persis_io;
8543	int    i;
8544
8545	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8546
8547	retval = CTL_RETVAL_COMPLETE;
8548
8549	softc = control_softc;
8550
8551	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8552	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8553
8554	/*
8555	 * We only support whole-LUN scope.  The scope & type are ignored for
8556	 * register, register and ignore existing key and clear.
8557	 * We sometimes ignore scope and type on preempts too!!
8558	 * Verify reservation type here as well.
8559	 */
8560	type = cdb->scope_type & SPR_TYPE_MASK;
8561	if ((cdb->action == SPRO_RESERVE)
8562	 || (cdb->action == SPRO_RELEASE)) {
8563		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8564			ctl_set_invalid_field(/*ctsio*/ ctsio,
8565					      /*sks_valid*/ 1,
8566					      /*command*/ 1,
8567					      /*field*/ 2,
8568					      /*bit_valid*/ 1,
8569					      /*bit*/ 4);
8570			ctl_done((union ctl_io *)ctsio);
8571			return (CTL_RETVAL_COMPLETE);
8572		}
8573
8574		if (type>8 || type==2 || type==4 || type==0) {
8575			ctl_set_invalid_field(/*ctsio*/ ctsio,
8576					      /*sks_valid*/ 1,
8577					      /*command*/ 1,
8578					      /*field*/ 2,
8579					      /*bit_valid*/ 1,
8580					      /*bit*/ 0);
8581			ctl_done((union ctl_io *)ctsio);
8582			return (CTL_RETVAL_COMPLETE);
8583		}
8584	}
8585
8586	param_len = scsi_4btoul(cdb->length);
8587
8588	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8589		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8590		ctsio->kern_data_len = param_len;
8591		ctsio->kern_total_len = param_len;
8592		ctsio->kern_data_resid = 0;
8593		ctsio->kern_rel_offset = 0;
8594		ctsio->kern_sg_entries = 0;
8595		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8596		ctsio->be_move_done = ctl_config_move_done;
8597		ctl_datamove((union ctl_io *)ctsio);
8598
8599		return (CTL_RETVAL_COMPLETE);
8600	}
8601
8602	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8603
8604	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8605	res_key = scsi_8btou64(param->res_key.key);
8606	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8607
8608	/*
8609	 * Validate the reservation key here except for SPRO_REG_IGNO
8610	 * This must be done for all other service actions
8611	 */
8612	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8613		mtx_lock(&lun->lun_lock);
8614		if (lun->pr_keys[residx] != 0) {
8615		    if (res_key != lun->pr_keys[residx]) {
8616				/*
8617				 * The current key passed in doesn't match
8618				 * the one the initiator previously
8619				 * registered.
8620				 */
8621				mtx_unlock(&lun->lun_lock);
8622				free(ctsio->kern_data_ptr, M_CTL);
8623				ctl_set_reservation_conflict(ctsio);
8624				ctl_done((union ctl_io *)ctsio);
8625				return (CTL_RETVAL_COMPLETE);
8626			}
8627		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8628			/*
8629			 * We are not registered
8630			 */
8631			mtx_unlock(&lun->lun_lock);
8632			free(ctsio->kern_data_ptr, M_CTL);
8633			ctl_set_reservation_conflict(ctsio);
8634			ctl_done((union ctl_io *)ctsio);
8635			return (CTL_RETVAL_COMPLETE);
8636		} else if (res_key != 0) {
8637			/*
8638			 * We are not registered and trying to register but
8639			 * the register key isn't zero.
8640			 */
8641			mtx_unlock(&lun->lun_lock);
8642			free(ctsio->kern_data_ptr, M_CTL);
8643			ctl_set_reservation_conflict(ctsio);
8644			ctl_done((union ctl_io *)ctsio);
8645			return (CTL_RETVAL_COMPLETE);
8646		}
8647		mtx_unlock(&lun->lun_lock);
8648	}
8649
8650	switch (cdb->action & SPRO_ACTION_MASK) {
8651	case SPRO_REGISTER:
8652	case SPRO_REG_IGNO: {
8653
8654#if 0
8655		printf("Registration received\n");
8656#endif
8657
8658		/*
8659		 * We don't support any of these options, as we report in
8660		 * the read capabilities request (see
8661		 * ctl_persistent_reserve_in(), above).
8662		 */
8663		if ((param->flags & SPR_SPEC_I_PT)
8664		 || (param->flags & SPR_ALL_TG_PT)
8665		 || (param->flags & SPR_APTPL)) {
8666			int bit_ptr;
8667
8668			if (param->flags & SPR_APTPL)
8669				bit_ptr = 0;
8670			else if (param->flags & SPR_ALL_TG_PT)
8671				bit_ptr = 2;
8672			else /* SPR_SPEC_I_PT */
8673				bit_ptr = 3;
8674
8675			free(ctsio->kern_data_ptr, M_CTL);
8676			ctl_set_invalid_field(ctsio,
8677					      /*sks_valid*/ 1,
8678					      /*command*/ 0,
8679					      /*field*/ 20,
8680					      /*bit_valid*/ 1,
8681					      /*bit*/ bit_ptr);
8682			ctl_done((union ctl_io *)ctsio);
8683			return (CTL_RETVAL_COMPLETE);
8684		}
8685
8686		mtx_lock(&lun->lun_lock);
8687
8688		/*
8689		 * The initiator wants to clear the
8690		 * key/unregister.
8691		 */
8692		if (sa_res_key == 0) {
8693			if ((res_key == 0
8694			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8695			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8696			  && lun->pr_keys[residx] == 0)) {
8697				mtx_unlock(&lun->lun_lock);
8698				goto done;
8699			}
8700
8701			lun->pr_keys[residx] = 0;
8702			lun->pr_key_count--;
8703
8704			if (residx == lun->pr_res_idx) {
8705				lun->flags &= ~CTL_LUN_PR_RESERVED;
8706				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8707
8708				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8709				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8710				 && lun->pr_key_count) {
8711					/*
8712					 * If the reservation is a registrants
8713					 * only type we need to generate a UA
8714					 * for other registered inits.  The
8715					 * sense code should be RESERVATIONS
8716					 * RELEASED
8717					 */
8718
8719					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8720						if (lun->pr_keys[
8721						    i + persis_offset] == 0)
8722							continue;
8723						lun->pending_ua[i] |=
8724							CTL_UA_RES_RELEASE;
8725					}
8726				}
8727				lun->res_type = 0;
8728			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8729				if (lun->pr_key_count==0) {
8730					lun->flags &= ~CTL_LUN_PR_RESERVED;
8731					lun->res_type = 0;
8732					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8733				}
8734			}
8735			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8736			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8737			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8738			persis_io.pr.pr_info.residx = residx;
8739			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8740			     &persis_io, sizeof(persis_io), 0 )) >
8741			     CTL_HA_STATUS_SUCCESS) {
8742				printf("CTL:Persis Out error returned from "
8743				       "ctl_ha_msg_send %d\n", isc_retval);
8744			}
8745		} else /* sa_res_key != 0 */ {
8746
8747			/*
8748			 * If we aren't registered currently then increment
8749			 * the key count and set the registered flag.
8750			 */
8751			if (lun->pr_keys[residx] == 0)
8752				lun->pr_key_count++;
8753			lun->pr_keys[residx] = sa_res_key;
8754
8755			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8756			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8757			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8758			persis_io.pr.pr_info.residx = residx;
8759			memcpy(persis_io.pr.pr_info.sa_res_key,
8760			       param->serv_act_res_key,
8761			       sizeof(param->serv_act_res_key));
8762			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8763			     &persis_io, sizeof(persis_io), 0)) >
8764			     CTL_HA_STATUS_SUCCESS) {
8765				printf("CTL:Persis Out error returned from "
8766				       "ctl_ha_msg_send %d\n", isc_retval);
8767			}
8768		}
8769		lun->PRGeneration++;
8770		mtx_unlock(&lun->lun_lock);
8771
8772		break;
8773	}
8774	case SPRO_RESERVE:
8775#if 0
8776                printf("Reserve executed type %d\n", type);
8777#endif
8778		mtx_lock(&lun->lun_lock);
8779		if (lun->flags & CTL_LUN_PR_RESERVED) {
8780			/*
8781			 * if this isn't the reservation holder and it's
8782			 * not a "all registrants" type or if the type is
8783			 * different then we have a conflict
8784			 */
8785			if ((lun->pr_res_idx != residx
8786			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8787			 || lun->res_type != type) {
8788				mtx_unlock(&lun->lun_lock);
8789				free(ctsio->kern_data_ptr, M_CTL);
8790				ctl_set_reservation_conflict(ctsio);
8791				ctl_done((union ctl_io *)ctsio);
8792				return (CTL_RETVAL_COMPLETE);
8793			}
8794			mtx_unlock(&lun->lun_lock);
8795		} else /* create a reservation */ {
8796			/*
8797			 * If it's not an "all registrants" type record
8798			 * reservation holder
8799			 */
8800			if (type != SPR_TYPE_WR_EX_AR
8801			 && type != SPR_TYPE_EX_AC_AR)
8802				lun->pr_res_idx = residx; /* Res holder */
8803			else
8804				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8805
8806			lun->flags |= CTL_LUN_PR_RESERVED;
8807			lun->res_type = type;
8808
8809			mtx_unlock(&lun->lun_lock);
8810
8811			/* send msg to other side */
8812			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8813			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8814			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8815			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8816			persis_io.pr.pr_info.res_type = type;
8817			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8818			     &persis_io, sizeof(persis_io), 0)) >
8819			     CTL_HA_STATUS_SUCCESS) {
8820				printf("CTL:Persis Out error returned from "
8821				       "ctl_ha_msg_send %d\n", isc_retval);
8822			}
8823		}
8824		break;
8825
8826	case SPRO_RELEASE:
8827		mtx_lock(&lun->lun_lock);
8828		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8829			/* No reservation exists return good status */
8830			mtx_unlock(&lun->lun_lock);
8831			goto done;
8832		}
8833		/*
8834		 * Is this nexus a reservation holder?
8835		 */
8836		if (lun->pr_res_idx != residx
8837		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8838			/*
8839			 * not a res holder return good status but
8840			 * do nothing
8841			 */
8842			mtx_unlock(&lun->lun_lock);
8843			goto done;
8844		}
8845
8846		if (lun->res_type != type) {
8847			mtx_unlock(&lun->lun_lock);
8848			free(ctsio->kern_data_ptr, M_CTL);
8849			ctl_set_illegal_pr_release(ctsio);
8850			ctl_done((union ctl_io *)ctsio);
8851			return (CTL_RETVAL_COMPLETE);
8852		}
8853
8854		/* okay to release */
8855		lun->flags &= ~CTL_LUN_PR_RESERVED;
8856		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8857		lun->res_type = 0;
8858
8859		/*
8860		 * if this isn't an exclusive access
8861		 * res generate UA for all other
8862		 * registrants.
8863		 */
8864		if (type != SPR_TYPE_EX_AC
8865		 && type != SPR_TYPE_WR_EX) {
8866			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8867				if (i == residx ||
8868				    lun->pr_keys[i + persis_offset] == 0)
8869					continue;
8870				lun->pending_ua[i] |= CTL_UA_RES_RELEASE;
8871			}
8872		}
8873		mtx_unlock(&lun->lun_lock);
8874		/* Send msg to other side */
8875		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8876		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8877		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8878		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8879		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8880			printf("CTL:Persis Out error returned from "
8881			       "ctl_ha_msg_send %d\n", isc_retval);
8882		}
8883		break;
8884
8885	case SPRO_CLEAR:
8886		/* send msg to other side */
8887
8888		mtx_lock(&lun->lun_lock);
8889		lun->flags &= ~CTL_LUN_PR_RESERVED;
8890		lun->res_type = 0;
8891		lun->pr_key_count = 0;
8892		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8893
8894		lun->pr_keys[residx] = 0;
8895
8896		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8897			if (lun->pr_keys[i] != 0) {
8898				if (!persis_offset && i < CTL_MAX_INITIATORS)
8899					lun->pending_ua[i] |=
8900						CTL_UA_RES_PREEMPT;
8901				else if (persis_offset && i >= persis_offset)
8902					lun->pending_ua[i-persis_offset] |=
8903					    CTL_UA_RES_PREEMPT;
8904
8905				lun->pr_keys[i] = 0;
8906			}
8907		lun->PRGeneration++;
8908		mtx_unlock(&lun->lun_lock);
8909		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8910		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8911		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8912		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8913		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8914			printf("CTL:Persis Out error returned from "
8915			       "ctl_ha_msg_send %d\n", isc_retval);
8916		}
8917		break;
8918
8919	case SPRO_PREEMPT:
8920	case SPRO_PRE_ABO: {
8921		int nretval;
8922
8923		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8924					  residx, ctsio, cdb, param);
8925		if (nretval != 0)
8926			return (CTL_RETVAL_COMPLETE);
8927		break;
8928	}
8929	default:
8930		panic("Invalid PR type %x", cdb->action);
8931	}
8932
8933done:
8934	free(ctsio->kern_data_ptr, M_CTL);
8935	ctl_set_success(ctsio);
8936	ctl_done((union ctl_io *)ctsio);
8937
8938	return (retval);
8939}
8940
8941/*
8942 * This routine is for handling a message from the other SC pertaining to
8943 * persistent reserve out. All the error checking will have been done
8944 * so only perorming the action need be done here to keep the two
8945 * in sync.
8946 */
8947static void
8948ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8949{
8950	struct ctl_lun *lun;
8951	struct ctl_softc *softc;
8952	int i;
8953	uint32_t targ_lun;
8954
8955	softc = control_softc;
8956
8957	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8958	lun = softc->ctl_luns[targ_lun];
8959	mtx_lock(&lun->lun_lock);
8960	switch(msg->pr.pr_info.action) {
8961	case CTL_PR_REG_KEY:
8962		if (lun->pr_keys[msg->pr.pr_info.residx] == 0)
8963			lun->pr_key_count++;
8964		lun->pr_keys[msg->pr.pr_info.residx] =
8965		    scsi_8btou64(msg->pr.pr_info.sa_res_key);
8966		lun->PRGeneration++;
8967		break;
8968
8969	case CTL_PR_UNREG_KEY:
8970		lun->pr_keys[msg->pr.pr_info.residx] = 0;
8971		lun->pr_key_count--;
8972
8973		/* XXX Need to see if the reservation has been released */
8974		/* if so do we need to generate UA? */
8975		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8976			lun->flags &= ~CTL_LUN_PR_RESERVED;
8977			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8978
8979			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8980			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8981			 && lun->pr_key_count) {
8982				/*
8983				 * If the reservation is a registrants
8984				 * only type we need to generate a UA
8985				 * for other registered inits.  The
8986				 * sense code should be RESERVATIONS
8987				 * RELEASED
8988				 */
8989
8990				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8991					if (lun->pr_keys[i+
8992					    persis_offset] == 0)
8993						continue;
8994
8995					lun->pending_ua[i] |=
8996						CTL_UA_RES_RELEASE;
8997				}
8998			}
8999			lun->res_type = 0;
9000		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
9001			if (lun->pr_key_count==0) {
9002				lun->flags &= ~CTL_LUN_PR_RESERVED;
9003				lun->res_type = 0;
9004				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
9005			}
9006		}
9007		lun->PRGeneration++;
9008		break;
9009
9010	case CTL_PR_RESERVE:
9011		lun->flags |= CTL_LUN_PR_RESERVED;
9012		lun->res_type = msg->pr.pr_info.res_type;
9013		lun->pr_res_idx = msg->pr.pr_info.residx;
9014
9015		break;
9016
9017	case CTL_PR_RELEASE:
9018		/*
9019		 * if this isn't an exclusive access res generate UA for all
9020		 * other registrants.
9021		 */
9022		if (lun->res_type != SPR_TYPE_EX_AC
9023		 && lun->res_type != SPR_TYPE_WR_EX) {
9024			for (i = 0; i < CTL_MAX_INITIATORS; i++)
9025				if (lun->pr_keys[i+persis_offset] != 0)
9026					lun->pending_ua[i] |=
9027						CTL_UA_RES_RELEASE;
9028		}
9029
9030		lun->flags &= ~CTL_LUN_PR_RESERVED;
9031		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
9032		lun->res_type = 0;
9033		break;
9034
9035	case CTL_PR_PREEMPT:
9036		ctl_pro_preempt_other(lun, msg);
9037		break;
9038	case CTL_PR_CLEAR:
9039		lun->flags &= ~CTL_LUN_PR_RESERVED;
9040		lun->res_type = 0;
9041		lun->pr_key_count = 0;
9042		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
9043
9044		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
9045			if (lun->pr_keys[i] == 0)
9046				continue;
9047			if (!persis_offset
9048			 && i < CTL_MAX_INITIATORS)
9049				lun->pending_ua[i] |= CTL_UA_RES_PREEMPT;
9050			else if (persis_offset
9051			      && i >= persis_offset)
9052				lun->pending_ua[i-persis_offset] |=
9053					CTL_UA_RES_PREEMPT;
9054			lun->pr_keys[i] = 0;
9055		}
9056		lun->PRGeneration++;
9057		break;
9058	}
9059
9060	mtx_unlock(&lun->lun_lock);
9061}
9062
9063int
9064ctl_read_write(struct ctl_scsiio *ctsio)
9065{
9066	struct ctl_lun *lun;
9067	struct ctl_lba_len_flags *lbalen;
9068	uint64_t lba;
9069	uint32_t num_blocks;
9070	int flags, retval;
9071	int isread;
9072
9073	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9074
9075	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
9076
9077	flags = 0;
9078	retval = CTL_RETVAL_COMPLETE;
9079
9080	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
9081	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
9082	switch (ctsio->cdb[0]) {
9083	case READ_6:
9084	case WRITE_6: {
9085		struct scsi_rw_6 *cdb;
9086
9087		cdb = (struct scsi_rw_6 *)ctsio->cdb;
9088
9089		lba = scsi_3btoul(cdb->addr);
9090		/* only 5 bits are valid in the most significant address byte */
9091		lba &= 0x1fffff;
9092		num_blocks = cdb->length;
9093		/*
9094		 * This is correct according to SBC-2.
9095		 */
9096		if (num_blocks == 0)
9097			num_blocks = 256;
9098		break;
9099	}
9100	case READ_10:
9101	case WRITE_10: {
9102		struct scsi_rw_10 *cdb;
9103
9104		cdb = (struct scsi_rw_10 *)ctsio->cdb;
9105		if (cdb->byte2 & SRW10_FUA)
9106			flags |= CTL_LLF_FUA;
9107		if (cdb->byte2 & SRW10_DPO)
9108			flags |= CTL_LLF_DPO;
9109		lba = scsi_4btoul(cdb->addr);
9110		num_blocks = scsi_2btoul(cdb->length);
9111		break;
9112	}
9113	case WRITE_VERIFY_10: {
9114		struct scsi_write_verify_10 *cdb;
9115
9116		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
9117		flags |= CTL_LLF_FUA;
9118		if (cdb->byte2 & SWV_DPO)
9119			flags |= CTL_LLF_DPO;
9120		lba = scsi_4btoul(cdb->addr);
9121		num_blocks = scsi_2btoul(cdb->length);
9122		break;
9123	}
9124	case READ_12:
9125	case WRITE_12: {
9126		struct scsi_rw_12 *cdb;
9127
9128		cdb = (struct scsi_rw_12 *)ctsio->cdb;
9129		if (cdb->byte2 & SRW12_FUA)
9130			flags |= CTL_LLF_FUA;
9131		if (cdb->byte2 & SRW12_DPO)
9132			flags |= CTL_LLF_DPO;
9133		lba = scsi_4btoul(cdb->addr);
9134		num_blocks = scsi_4btoul(cdb->length);
9135		break;
9136	}
9137	case WRITE_VERIFY_12: {
9138		struct scsi_write_verify_12 *cdb;
9139
9140		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
9141		flags |= CTL_LLF_FUA;
9142		if (cdb->byte2 & SWV_DPO)
9143			flags |= CTL_LLF_DPO;
9144		lba = scsi_4btoul(cdb->addr);
9145		num_blocks = scsi_4btoul(cdb->length);
9146		break;
9147	}
9148	case READ_16:
9149	case WRITE_16: {
9150		struct scsi_rw_16 *cdb;
9151
9152		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9153		if (cdb->byte2 & SRW12_FUA)
9154			flags |= CTL_LLF_FUA;
9155		if (cdb->byte2 & SRW12_DPO)
9156			flags |= CTL_LLF_DPO;
9157		lba = scsi_8btou64(cdb->addr);
9158		num_blocks = scsi_4btoul(cdb->length);
9159		break;
9160	}
9161	case WRITE_ATOMIC_16: {
9162		struct scsi_rw_16 *cdb;
9163
9164		if (lun->be_lun->atomicblock == 0) {
9165			ctl_set_invalid_opcode(ctsio);
9166			ctl_done((union ctl_io *)ctsio);
9167			return (CTL_RETVAL_COMPLETE);
9168		}
9169
9170		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9171		if (cdb->byte2 & SRW12_FUA)
9172			flags |= CTL_LLF_FUA;
9173		if (cdb->byte2 & SRW12_DPO)
9174			flags |= CTL_LLF_DPO;
9175		lba = scsi_8btou64(cdb->addr);
9176		num_blocks = scsi_4btoul(cdb->length);
9177		if (num_blocks > lun->be_lun->atomicblock) {
9178			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
9179			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
9180			    /*bit*/ 0);
9181			ctl_done((union ctl_io *)ctsio);
9182			return (CTL_RETVAL_COMPLETE);
9183		}
9184		break;
9185	}
9186	case WRITE_VERIFY_16: {
9187		struct scsi_write_verify_16 *cdb;
9188
9189		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9190		flags |= CTL_LLF_FUA;
9191		if (cdb->byte2 & SWV_DPO)
9192			flags |= CTL_LLF_DPO;
9193		lba = scsi_8btou64(cdb->addr);
9194		num_blocks = scsi_4btoul(cdb->length);
9195		break;
9196	}
9197	default:
9198		/*
9199		 * We got a command we don't support.  This shouldn't
9200		 * happen, commands should be filtered out above us.
9201		 */
9202		ctl_set_invalid_opcode(ctsio);
9203		ctl_done((union ctl_io *)ctsio);
9204
9205		return (CTL_RETVAL_COMPLETE);
9206		break; /* NOTREACHED */
9207	}
9208
9209	/*
9210	 * The first check is to make sure we're in bounds, the second
9211	 * check is to catch wrap-around problems.  If the lba + num blocks
9212	 * is less than the lba, then we've wrapped around and the block
9213	 * range is invalid anyway.
9214	 */
9215	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9216	 || ((lba + num_blocks) < lba)) {
9217		ctl_set_lba_out_of_range(ctsio);
9218		ctl_done((union ctl_io *)ctsio);
9219		return (CTL_RETVAL_COMPLETE);
9220	}
9221
9222	/*
9223	 * According to SBC-3, a transfer length of 0 is not an error.
9224	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
9225	 * translates to 256 blocks for those commands.
9226	 */
9227	if (num_blocks == 0) {
9228		ctl_set_success(ctsio);
9229		ctl_done((union ctl_io *)ctsio);
9230		return (CTL_RETVAL_COMPLETE);
9231	}
9232
9233	/* Set FUA and/or DPO if caches are disabled. */
9234	if (isread) {
9235		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9236		    SCP_RCD) != 0)
9237			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9238	} else {
9239		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9240		    SCP_WCE) == 0)
9241			flags |= CTL_LLF_FUA;
9242	}
9243
9244	lbalen = (struct ctl_lba_len_flags *)
9245	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9246	lbalen->lba = lba;
9247	lbalen->len = num_blocks;
9248	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9249
9250	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9251	ctsio->kern_rel_offset = 0;
9252
9253	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9254
9255	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9256
9257	return (retval);
9258}
9259
9260static int
9261ctl_cnw_cont(union ctl_io *io)
9262{
9263	struct ctl_scsiio *ctsio;
9264	struct ctl_lun *lun;
9265	struct ctl_lba_len_flags *lbalen;
9266	int retval;
9267
9268	ctsio = &io->scsiio;
9269	ctsio->io_hdr.status = CTL_STATUS_NONE;
9270	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9271	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9272	lbalen = (struct ctl_lba_len_flags *)
9273	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9274	lbalen->flags &= ~CTL_LLF_COMPARE;
9275	lbalen->flags |= CTL_LLF_WRITE;
9276
9277	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9278	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9279	return (retval);
9280}
9281
9282int
9283ctl_cnw(struct ctl_scsiio *ctsio)
9284{
9285	struct ctl_lun *lun;
9286	struct ctl_lba_len_flags *lbalen;
9287	uint64_t lba;
9288	uint32_t num_blocks;
9289	int flags, retval;
9290
9291	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9292
9293	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9294
9295	flags = 0;
9296	retval = CTL_RETVAL_COMPLETE;
9297
9298	switch (ctsio->cdb[0]) {
9299	case COMPARE_AND_WRITE: {
9300		struct scsi_compare_and_write *cdb;
9301
9302		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9303		if (cdb->byte2 & SRW10_FUA)
9304			flags |= CTL_LLF_FUA;
9305		if (cdb->byte2 & SRW10_DPO)
9306			flags |= CTL_LLF_DPO;
9307		lba = scsi_8btou64(cdb->addr);
9308		num_blocks = cdb->length;
9309		break;
9310	}
9311	default:
9312		/*
9313		 * We got a command we don't support.  This shouldn't
9314		 * happen, commands should be filtered out above us.
9315		 */
9316		ctl_set_invalid_opcode(ctsio);
9317		ctl_done((union ctl_io *)ctsio);
9318
9319		return (CTL_RETVAL_COMPLETE);
9320		break; /* NOTREACHED */
9321	}
9322
9323	/*
9324	 * The first check is to make sure we're in bounds, the second
9325	 * check is to catch wrap-around problems.  If the lba + num blocks
9326	 * is less than the lba, then we've wrapped around and the block
9327	 * range is invalid anyway.
9328	 */
9329	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9330	 || ((lba + num_blocks) < lba)) {
9331		ctl_set_lba_out_of_range(ctsio);
9332		ctl_done((union ctl_io *)ctsio);
9333		return (CTL_RETVAL_COMPLETE);
9334	}
9335
9336	/*
9337	 * According to SBC-3, a transfer length of 0 is not an error.
9338	 */
9339	if (num_blocks == 0) {
9340		ctl_set_success(ctsio);
9341		ctl_done((union ctl_io *)ctsio);
9342		return (CTL_RETVAL_COMPLETE);
9343	}
9344
9345	/* Set FUA if write cache is disabled. */
9346	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9347	    SCP_WCE) == 0)
9348		flags |= CTL_LLF_FUA;
9349
9350	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9351	ctsio->kern_rel_offset = 0;
9352
9353	/*
9354	 * Set the IO_CONT flag, so that if this I/O gets passed to
9355	 * ctl_data_submit_done(), it'll get passed back to
9356	 * ctl_ctl_cnw_cont() for further processing.
9357	 */
9358	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9359	ctsio->io_cont = ctl_cnw_cont;
9360
9361	lbalen = (struct ctl_lba_len_flags *)
9362	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9363	lbalen->lba = lba;
9364	lbalen->len = num_blocks;
9365	lbalen->flags = CTL_LLF_COMPARE | flags;
9366
9367	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9368	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9369	return (retval);
9370}
9371
9372int
9373ctl_verify(struct ctl_scsiio *ctsio)
9374{
9375	struct ctl_lun *lun;
9376	struct ctl_lba_len_flags *lbalen;
9377	uint64_t lba;
9378	uint32_t num_blocks;
9379	int bytchk, flags;
9380	int retval;
9381
9382	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9383
9384	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9385
9386	bytchk = 0;
9387	flags = CTL_LLF_FUA;
9388	retval = CTL_RETVAL_COMPLETE;
9389
9390	switch (ctsio->cdb[0]) {
9391	case VERIFY_10: {
9392		struct scsi_verify_10 *cdb;
9393
9394		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9395		if (cdb->byte2 & SVFY_BYTCHK)
9396			bytchk = 1;
9397		if (cdb->byte2 & SVFY_DPO)
9398			flags |= CTL_LLF_DPO;
9399		lba = scsi_4btoul(cdb->addr);
9400		num_blocks = scsi_2btoul(cdb->length);
9401		break;
9402	}
9403	case VERIFY_12: {
9404		struct scsi_verify_12 *cdb;
9405
9406		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9407		if (cdb->byte2 & SVFY_BYTCHK)
9408			bytchk = 1;
9409		if (cdb->byte2 & SVFY_DPO)
9410			flags |= CTL_LLF_DPO;
9411		lba = scsi_4btoul(cdb->addr);
9412		num_blocks = scsi_4btoul(cdb->length);
9413		break;
9414	}
9415	case VERIFY_16: {
9416		struct scsi_rw_16 *cdb;
9417
9418		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9419		if (cdb->byte2 & SVFY_BYTCHK)
9420			bytchk = 1;
9421		if (cdb->byte2 & SVFY_DPO)
9422			flags |= CTL_LLF_DPO;
9423		lba = scsi_8btou64(cdb->addr);
9424		num_blocks = scsi_4btoul(cdb->length);
9425		break;
9426	}
9427	default:
9428		/*
9429		 * We got a command we don't support.  This shouldn't
9430		 * happen, commands should be filtered out above us.
9431		 */
9432		ctl_set_invalid_opcode(ctsio);
9433		ctl_done((union ctl_io *)ctsio);
9434		return (CTL_RETVAL_COMPLETE);
9435	}
9436
9437	/*
9438	 * The first check is to make sure we're in bounds, the second
9439	 * check is to catch wrap-around problems.  If the lba + num blocks
9440	 * is less than the lba, then we've wrapped around and the block
9441	 * range is invalid anyway.
9442	 */
9443	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9444	 || ((lba + num_blocks) < lba)) {
9445		ctl_set_lba_out_of_range(ctsio);
9446		ctl_done((union ctl_io *)ctsio);
9447		return (CTL_RETVAL_COMPLETE);
9448	}
9449
9450	/*
9451	 * According to SBC-3, a transfer length of 0 is not an error.
9452	 */
9453	if (num_blocks == 0) {
9454		ctl_set_success(ctsio);
9455		ctl_done((union ctl_io *)ctsio);
9456		return (CTL_RETVAL_COMPLETE);
9457	}
9458
9459	lbalen = (struct ctl_lba_len_flags *)
9460	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9461	lbalen->lba = lba;
9462	lbalen->len = num_blocks;
9463	if (bytchk) {
9464		lbalen->flags = CTL_LLF_COMPARE | flags;
9465		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9466	} else {
9467		lbalen->flags = CTL_LLF_VERIFY | flags;
9468		ctsio->kern_total_len = 0;
9469	}
9470	ctsio->kern_rel_offset = 0;
9471
9472	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9473	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9474	return (retval);
9475}
9476
9477int
9478ctl_report_luns(struct ctl_scsiio *ctsio)
9479{
9480	struct scsi_report_luns *cdb;
9481	struct scsi_report_luns_data *lun_data;
9482	struct ctl_lun *lun, *request_lun;
9483	int num_luns, retval;
9484	uint32_t alloc_len, lun_datalen;
9485	int num_filled, well_known;
9486	uint32_t initidx, targ_lun_id, lun_id;
9487
9488	retval = CTL_RETVAL_COMPLETE;
9489	well_known = 0;
9490
9491	cdb = (struct scsi_report_luns *)ctsio->cdb;
9492
9493	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9494
9495	mtx_lock(&control_softc->ctl_lock);
9496	num_luns = control_softc->num_luns;
9497	mtx_unlock(&control_softc->ctl_lock);
9498
9499	switch (cdb->select_report) {
9500	case RPL_REPORT_DEFAULT:
9501	case RPL_REPORT_ALL:
9502		break;
9503	case RPL_REPORT_WELLKNOWN:
9504		well_known = 1;
9505		num_luns = 0;
9506		break;
9507	default:
9508		ctl_set_invalid_field(ctsio,
9509				      /*sks_valid*/ 1,
9510				      /*command*/ 1,
9511				      /*field*/ 2,
9512				      /*bit_valid*/ 0,
9513				      /*bit*/ 0);
9514		ctl_done((union ctl_io *)ctsio);
9515		return (retval);
9516		break; /* NOTREACHED */
9517	}
9518
9519	alloc_len = scsi_4btoul(cdb->length);
9520	/*
9521	 * The initiator has to allocate at least 16 bytes for this request,
9522	 * so he can at least get the header and the first LUN.  Otherwise
9523	 * we reject the request (per SPC-3 rev 14, section 6.21).
9524	 */
9525	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9526	    sizeof(struct scsi_report_luns_lundata))) {
9527		ctl_set_invalid_field(ctsio,
9528				      /*sks_valid*/ 1,
9529				      /*command*/ 1,
9530				      /*field*/ 6,
9531				      /*bit_valid*/ 0,
9532				      /*bit*/ 0);
9533		ctl_done((union ctl_io *)ctsio);
9534		return (retval);
9535	}
9536
9537	request_lun = (struct ctl_lun *)
9538		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9539
9540	lun_datalen = sizeof(*lun_data) +
9541		(num_luns * sizeof(struct scsi_report_luns_lundata));
9542
9543	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9544	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9545	ctsio->kern_sg_entries = 0;
9546
9547	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9548
9549	mtx_lock(&control_softc->ctl_lock);
9550	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9551		lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9552		if (lun_id >= CTL_MAX_LUNS)
9553			continue;
9554		lun = control_softc->ctl_luns[lun_id];
9555		if (lun == NULL)
9556			continue;
9557
9558		if (targ_lun_id <= 0xff) {
9559			/*
9560			 * Peripheral addressing method, bus number 0.
9561			 */
9562			lun_data->luns[num_filled].lundata[0] =
9563				RPL_LUNDATA_ATYP_PERIPH;
9564			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9565			num_filled++;
9566		} else if (targ_lun_id <= 0x3fff) {
9567			/*
9568			 * Flat addressing method.
9569			 */
9570			lun_data->luns[num_filled].lundata[0] =
9571				RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9572			lun_data->luns[num_filled].lundata[1] =
9573				(targ_lun_id & 0xff);
9574			num_filled++;
9575		} else if (targ_lun_id <= 0xffffff) {
9576			/*
9577			 * Extended flat addressing method.
9578			 */
9579			lun_data->luns[num_filled].lundata[0] =
9580			    RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9581			scsi_ulto3b(targ_lun_id,
9582			    &lun_data->luns[num_filled].lundata[1]);
9583			num_filled++;
9584		} else {
9585			printf("ctl_report_luns: bogus LUN number %jd, "
9586			       "skipping\n", (intmax_t)targ_lun_id);
9587		}
9588		/*
9589		 * According to SPC-3, rev 14 section 6.21:
9590		 *
9591		 * "The execution of a REPORT LUNS command to any valid and
9592		 * installed logical unit shall clear the REPORTED LUNS DATA
9593		 * HAS CHANGED unit attention condition for all logical
9594		 * units of that target with respect to the requesting
9595		 * initiator. A valid and installed logical unit is one
9596		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9597		 * INQUIRY data (see 6.4.2)."
9598		 *
9599		 * If request_lun is NULL, the LUN this report luns command
9600		 * was issued to is either disabled or doesn't exist. In that
9601		 * case, we shouldn't clear any pending lun change unit
9602		 * attention.
9603		 */
9604		if (request_lun != NULL) {
9605			mtx_lock(&lun->lun_lock);
9606			lun->pending_ua[initidx] &= ~CTL_UA_LUN_CHANGE;
9607			mtx_unlock(&lun->lun_lock);
9608		}
9609	}
9610	mtx_unlock(&control_softc->ctl_lock);
9611
9612	/*
9613	 * It's quite possible that we've returned fewer LUNs than we allocated
9614	 * space for.  Trim it.
9615	 */
9616	lun_datalen = sizeof(*lun_data) +
9617		(num_filled * sizeof(struct scsi_report_luns_lundata));
9618
9619	if (lun_datalen < alloc_len) {
9620		ctsio->residual = alloc_len - lun_datalen;
9621		ctsio->kern_data_len = lun_datalen;
9622		ctsio->kern_total_len = lun_datalen;
9623	} else {
9624		ctsio->residual = 0;
9625		ctsio->kern_data_len = alloc_len;
9626		ctsio->kern_total_len = alloc_len;
9627	}
9628	ctsio->kern_data_resid = 0;
9629	ctsio->kern_rel_offset = 0;
9630	ctsio->kern_sg_entries = 0;
9631
9632	/*
9633	 * We set this to the actual data length, regardless of how much
9634	 * space we actually have to return results.  If the user looks at
9635	 * this value, he'll know whether or not he allocated enough space
9636	 * and reissue the command if necessary.  We don't support well
9637	 * known logical units, so if the user asks for that, return none.
9638	 */
9639	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9640
9641	/*
9642	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9643	 * this request.
9644	 */
9645	ctsio->scsi_status = SCSI_STATUS_OK;
9646
9647	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9648	ctsio->be_move_done = ctl_config_move_done;
9649	ctl_datamove((union ctl_io *)ctsio);
9650
9651	return (retval);
9652}
9653
9654int
9655ctl_request_sense(struct ctl_scsiio *ctsio)
9656{
9657	struct scsi_request_sense *cdb;
9658	struct scsi_sense_data *sense_ptr;
9659	struct ctl_lun *lun;
9660	uint32_t initidx;
9661	int have_error;
9662	scsi_sense_data_type sense_format;
9663
9664	cdb = (struct scsi_request_sense *)ctsio->cdb;
9665
9666	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9667
9668	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9669
9670	/*
9671	 * Determine which sense format the user wants.
9672	 */
9673	if (cdb->byte2 & SRS_DESC)
9674		sense_format = SSD_TYPE_DESC;
9675	else
9676		sense_format = SSD_TYPE_FIXED;
9677
9678	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9679	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9680	ctsio->kern_sg_entries = 0;
9681
9682	/*
9683	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9684	 * larger than the largest allowed value for the length field in the
9685	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9686	 */
9687	ctsio->residual = 0;
9688	ctsio->kern_data_len = cdb->length;
9689	ctsio->kern_total_len = cdb->length;
9690
9691	ctsio->kern_data_resid = 0;
9692	ctsio->kern_rel_offset = 0;
9693	ctsio->kern_sg_entries = 0;
9694
9695	/*
9696	 * If we don't have a LUN, we don't have any pending sense.
9697	 */
9698	if (lun == NULL)
9699		goto no_sense;
9700
9701	have_error = 0;
9702	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9703	/*
9704	 * Check for pending sense, and then for pending unit attentions.
9705	 * Pending sense gets returned first, then pending unit attentions.
9706	 */
9707	mtx_lock(&lun->lun_lock);
9708#ifdef CTL_WITH_CA
9709	if (ctl_is_set(lun->have_ca, initidx)) {
9710		scsi_sense_data_type stored_format;
9711
9712		/*
9713		 * Check to see which sense format was used for the stored
9714		 * sense data.
9715		 */
9716		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9717
9718		/*
9719		 * If the user requested a different sense format than the
9720		 * one we stored, then we need to convert it to the other
9721		 * format.  If we're going from descriptor to fixed format
9722		 * sense data, we may lose things in translation, depending
9723		 * on what options were used.
9724		 *
9725		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9726		 * for some reason we'll just copy it out as-is.
9727		 */
9728		if ((stored_format == SSD_TYPE_FIXED)
9729		 && (sense_format == SSD_TYPE_DESC))
9730			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9731			    &lun->pending_sense[initidx],
9732			    (struct scsi_sense_data_desc *)sense_ptr);
9733		else if ((stored_format == SSD_TYPE_DESC)
9734		      && (sense_format == SSD_TYPE_FIXED))
9735			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9736			    &lun->pending_sense[initidx],
9737			    (struct scsi_sense_data_fixed *)sense_ptr);
9738		else
9739			memcpy(sense_ptr, &lun->pending_sense[initidx],
9740			       ctl_min(sizeof(*sense_ptr),
9741			       sizeof(lun->pending_sense[initidx])));
9742
9743		ctl_clear_mask(lun->have_ca, initidx);
9744		have_error = 1;
9745	} else
9746#endif
9747	if (lun->pending_ua[initidx] != CTL_UA_NONE) {
9748		ctl_ua_type ua_type;
9749
9750		ua_type = ctl_build_ua(&lun->pending_ua[initidx],
9751				       sense_ptr, sense_format);
9752		if (ua_type != CTL_UA_NONE)
9753			have_error = 1;
9754	}
9755	mtx_unlock(&lun->lun_lock);
9756
9757	/*
9758	 * We already have a pending error, return it.
9759	 */
9760	if (have_error != 0) {
9761		/*
9762		 * We report the SCSI status as OK, since the status of the
9763		 * request sense command itself is OK.
9764		 */
9765		ctsio->scsi_status = SCSI_STATUS_OK;
9766
9767		/*
9768		 * We report 0 for the sense length, because we aren't doing
9769		 * autosense in this case.  We're reporting sense as
9770		 * parameter data.
9771		 */
9772		ctsio->sense_len = 0;
9773		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9774		ctsio->be_move_done = ctl_config_move_done;
9775		ctl_datamove((union ctl_io *)ctsio);
9776
9777		return (CTL_RETVAL_COMPLETE);
9778	}
9779
9780no_sense:
9781
9782	/*
9783	 * No sense information to report, so we report that everything is
9784	 * okay.
9785	 */
9786	ctl_set_sense_data(sense_ptr,
9787			   lun,
9788			   sense_format,
9789			   /*current_error*/ 1,
9790			   /*sense_key*/ SSD_KEY_NO_SENSE,
9791			   /*asc*/ 0x00,
9792			   /*ascq*/ 0x00,
9793			   SSD_ELEM_NONE);
9794
9795	ctsio->scsi_status = SCSI_STATUS_OK;
9796
9797	/*
9798	 * We report 0 for the sense length, because we aren't doing
9799	 * autosense in this case.  We're reporting sense as parameter data.
9800	 */
9801	ctsio->sense_len = 0;
9802	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9803	ctsio->be_move_done = ctl_config_move_done;
9804	ctl_datamove((union ctl_io *)ctsio);
9805
9806	return (CTL_RETVAL_COMPLETE);
9807}
9808
9809int
9810ctl_tur(struct ctl_scsiio *ctsio)
9811{
9812	struct ctl_lun *lun;
9813
9814	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9815
9816	CTL_DEBUG_PRINT(("ctl_tur\n"));
9817
9818	if (lun == NULL)
9819		return (EINVAL);
9820
9821	ctsio->scsi_status = SCSI_STATUS_OK;
9822	ctsio->io_hdr.status = CTL_SUCCESS;
9823
9824	ctl_done((union ctl_io *)ctsio);
9825
9826	return (CTL_RETVAL_COMPLETE);
9827}
9828
9829#ifdef notyet
9830static int
9831ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9832{
9833
9834}
9835#endif
9836
9837static int
9838ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9839{
9840	struct scsi_vpd_supported_pages *pages;
9841	int sup_page_size;
9842	struct ctl_lun *lun;
9843
9844	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9845
9846	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9847	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9848	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9849	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9850	ctsio->kern_sg_entries = 0;
9851
9852	if (sup_page_size < alloc_len) {
9853		ctsio->residual = alloc_len - sup_page_size;
9854		ctsio->kern_data_len = sup_page_size;
9855		ctsio->kern_total_len = sup_page_size;
9856	} else {
9857		ctsio->residual = 0;
9858		ctsio->kern_data_len = alloc_len;
9859		ctsio->kern_total_len = alloc_len;
9860	}
9861	ctsio->kern_data_resid = 0;
9862	ctsio->kern_rel_offset = 0;
9863	ctsio->kern_sg_entries = 0;
9864
9865	/*
9866	 * The control device is always connected.  The disk device, on the
9867	 * other hand, may not be online all the time.  Need to change this
9868	 * to figure out whether the disk device is actually online or not.
9869	 */
9870	if (lun != NULL)
9871		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9872				lun->be_lun->lun_type;
9873	else
9874		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9875
9876	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9877	/* Supported VPD pages */
9878	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9879	/* Serial Number */
9880	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9881	/* Device Identification */
9882	pages->page_list[2] = SVPD_DEVICE_ID;
9883	/* Extended INQUIRY Data */
9884	pages->page_list[3] = SVPD_EXTENDED_INQUIRY_DATA;
9885	/* Mode Page Policy */
9886	pages->page_list[4] = SVPD_MODE_PAGE_POLICY;
9887	/* SCSI Ports */
9888	pages->page_list[5] = SVPD_SCSI_PORTS;
9889	/* Third-party Copy */
9890	pages->page_list[6] = SVPD_SCSI_TPC;
9891	/* Block limits */
9892	pages->page_list[7] = SVPD_BLOCK_LIMITS;
9893	/* Block Device Characteristics */
9894	pages->page_list[8] = SVPD_BDC;
9895	/* Logical Block Provisioning */
9896	pages->page_list[9] = SVPD_LBP;
9897
9898	ctsio->scsi_status = SCSI_STATUS_OK;
9899
9900	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9901	ctsio->be_move_done = ctl_config_move_done;
9902	ctl_datamove((union ctl_io *)ctsio);
9903
9904	return (CTL_RETVAL_COMPLETE);
9905}
9906
9907static int
9908ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9909{
9910	struct scsi_vpd_unit_serial_number *sn_ptr;
9911	struct ctl_lun *lun;
9912	int data_len;
9913
9914	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9915
9916	data_len = 4 + CTL_SN_LEN;
9917	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9918	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9919	if (data_len < alloc_len) {
9920		ctsio->residual = alloc_len - data_len;
9921		ctsio->kern_data_len = data_len;
9922		ctsio->kern_total_len = data_len;
9923	} else {
9924		ctsio->residual = 0;
9925		ctsio->kern_data_len = alloc_len;
9926		ctsio->kern_total_len = alloc_len;
9927	}
9928	ctsio->kern_data_resid = 0;
9929	ctsio->kern_rel_offset = 0;
9930	ctsio->kern_sg_entries = 0;
9931
9932	/*
9933	 * The control device is always connected.  The disk device, on the
9934	 * other hand, may not be online all the time.  Need to change this
9935	 * to figure out whether the disk device is actually online or not.
9936	 */
9937	if (lun != NULL)
9938		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9939				  lun->be_lun->lun_type;
9940	else
9941		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9942
9943	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9944	sn_ptr->length = CTL_SN_LEN;
9945	/*
9946	 * If we don't have a LUN, we just leave the serial number as
9947	 * all spaces.
9948	 */
9949	if (lun != NULL) {
9950		strncpy((char *)sn_ptr->serial_num,
9951			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9952	} else
9953		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9954	ctsio->scsi_status = SCSI_STATUS_OK;
9955
9956	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9957	ctsio->be_move_done = ctl_config_move_done;
9958	ctl_datamove((union ctl_io *)ctsio);
9959
9960	return (CTL_RETVAL_COMPLETE);
9961}
9962
9963
9964static int
9965ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9966{
9967	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9968	struct ctl_lun *lun;
9969	int data_len;
9970
9971	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9972
9973	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9974	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9975	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9976	ctsio->kern_sg_entries = 0;
9977
9978	if (data_len < alloc_len) {
9979		ctsio->residual = alloc_len - data_len;
9980		ctsio->kern_data_len = data_len;
9981		ctsio->kern_total_len = data_len;
9982	} else {
9983		ctsio->residual = 0;
9984		ctsio->kern_data_len = alloc_len;
9985		ctsio->kern_total_len = alloc_len;
9986	}
9987	ctsio->kern_data_resid = 0;
9988	ctsio->kern_rel_offset = 0;
9989	ctsio->kern_sg_entries = 0;
9990
9991	/*
9992	 * The control device is always connected.  The disk device, on the
9993	 * other hand, may not be online all the time.
9994	 */
9995	if (lun != NULL)
9996		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9997				     lun->be_lun->lun_type;
9998	else
9999		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10000	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
10001	eid_ptr->page_length = data_len - 4;
10002	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
10003	eid_ptr->flags3 = SVPD_EID_V_SUP;
10004
10005	ctsio->scsi_status = SCSI_STATUS_OK;
10006	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10007	ctsio->be_move_done = ctl_config_move_done;
10008	ctl_datamove((union ctl_io *)ctsio);
10009
10010	return (CTL_RETVAL_COMPLETE);
10011}
10012
10013static int
10014ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
10015{
10016	struct scsi_vpd_mode_page_policy *mpp_ptr;
10017	struct ctl_lun *lun;
10018	int data_len;
10019
10020	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10021
10022	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
10023	    sizeof(struct scsi_vpd_mode_page_policy_descr);
10024
10025	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10026	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
10027	ctsio->kern_sg_entries = 0;
10028
10029	if (data_len < alloc_len) {
10030		ctsio->residual = alloc_len - data_len;
10031		ctsio->kern_data_len = data_len;
10032		ctsio->kern_total_len = data_len;
10033	} else {
10034		ctsio->residual = 0;
10035		ctsio->kern_data_len = alloc_len;
10036		ctsio->kern_total_len = alloc_len;
10037	}
10038	ctsio->kern_data_resid = 0;
10039	ctsio->kern_rel_offset = 0;
10040	ctsio->kern_sg_entries = 0;
10041
10042	/*
10043	 * The control device is always connected.  The disk device, on the
10044	 * other hand, may not be online all the time.
10045	 */
10046	if (lun != NULL)
10047		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10048				     lun->be_lun->lun_type;
10049	else
10050		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10051	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
10052	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
10053	mpp_ptr->descr[0].page_code = 0x3f;
10054	mpp_ptr->descr[0].subpage_code = 0xff;
10055	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
10056
10057	ctsio->scsi_status = SCSI_STATUS_OK;
10058	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10059	ctsio->be_move_done = ctl_config_move_done;
10060	ctl_datamove((union ctl_io *)ctsio);
10061
10062	return (CTL_RETVAL_COMPLETE);
10063}
10064
10065static int
10066ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
10067{
10068	struct scsi_vpd_device_id *devid_ptr;
10069	struct scsi_vpd_id_descriptor *desc;
10070	struct ctl_softc *ctl_softc;
10071	struct ctl_lun *lun;
10072	struct ctl_port *port;
10073	int data_len;
10074	uint8_t proto;
10075
10076	ctl_softc = control_softc;
10077
10078	port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
10079	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10080
10081	data_len = sizeof(struct scsi_vpd_device_id) +
10082	    sizeof(struct scsi_vpd_id_descriptor) +
10083		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
10084	    sizeof(struct scsi_vpd_id_descriptor) +
10085		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
10086	if (lun && lun->lun_devid)
10087		data_len += lun->lun_devid->len;
10088	if (port->port_devid)
10089		data_len += port->port_devid->len;
10090	if (port->target_devid)
10091		data_len += port->target_devid->len;
10092
10093	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10094	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
10095	ctsio->kern_sg_entries = 0;
10096
10097	if (data_len < alloc_len) {
10098		ctsio->residual = alloc_len - data_len;
10099		ctsio->kern_data_len = data_len;
10100		ctsio->kern_total_len = data_len;
10101	} else {
10102		ctsio->residual = 0;
10103		ctsio->kern_data_len = alloc_len;
10104		ctsio->kern_total_len = alloc_len;
10105	}
10106	ctsio->kern_data_resid = 0;
10107	ctsio->kern_rel_offset = 0;
10108	ctsio->kern_sg_entries = 0;
10109
10110	/*
10111	 * The control device is always connected.  The disk device, on the
10112	 * other hand, may not be online all the time.
10113	 */
10114	if (lun != NULL)
10115		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10116				     lun->be_lun->lun_type;
10117	else
10118		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10119	devid_ptr->page_code = SVPD_DEVICE_ID;
10120	scsi_ulto2b(data_len - 4, devid_ptr->length);
10121
10122	if (port->port_type == CTL_PORT_FC)
10123		proto = SCSI_PROTO_FC << 4;
10124	else if (port->port_type == CTL_PORT_ISCSI)
10125		proto = SCSI_PROTO_ISCSI << 4;
10126	else
10127		proto = SCSI_PROTO_SPI << 4;
10128	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
10129
10130	/*
10131	 * We're using a LUN association here.  i.e., this device ID is a
10132	 * per-LUN identifier.
10133	 */
10134	if (lun && lun->lun_devid) {
10135		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
10136		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10137		    lun->lun_devid->len);
10138	}
10139
10140	/*
10141	 * This is for the WWPN which is a port association.
10142	 */
10143	if (port->port_devid) {
10144		memcpy(desc, port->port_devid->data, port->port_devid->len);
10145		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10146		    port->port_devid->len);
10147	}
10148
10149	/*
10150	 * This is for the Relative Target Port(type 4h) identifier
10151	 */
10152	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10153	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10154	    SVPD_ID_TYPE_RELTARG;
10155	desc->length = 4;
10156	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
10157	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10158	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
10159
10160	/*
10161	 * This is for the Target Port Group(type 5h) identifier
10162	 */
10163	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10164	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10165	    SVPD_ID_TYPE_TPORTGRP;
10166	desc->length = 4;
10167	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
10168	    &desc->identifier[2]);
10169	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10170	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
10171
10172	/*
10173	 * This is for the Target identifier
10174	 */
10175	if (port->target_devid) {
10176		memcpy(desc, port->target_devid->data, port->target_devid->len);
10177	}
10178
10179	ctsio->scsi_status = SCSI_STATUS_OK;
10180	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10181	ctsio->be_move_done = ctl_config_move_done;
10182	ctl_datamove((union ctl_io *)ctsio);
10183
10184	return (CTL_RETVAL_COMPLETE);
10185}
10186
10187static int
10188ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
10189{
10190	struct ctl_softc *softc = control_softc;
10191	struct scsi_vpd_scsi_ports *sp;
10192	struct scsi_vpd_port_designation *pd;
10193	struct scsi_vpd_port_designation_cont *pdc;
10194	struct ctl_lun *lun;
10195	struct ctl_port *port;
10196	int data_len, num_target_ports, iid_len, id_len, g, pg, p;
10197	int num_target_port_groups, single;
10198
10199	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10200
10201	single = ctl_is_single;
10202	if (single)
10203		num_target_port_groups = 1;
10204	else
10205		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10206	num_target_ports = 0;
10207	iid_len = 0;
10208	id_len = 0;
10209	mtx_lock(&softc->ctl_lock);
10210	STAILQ_FOREACH(port, &softc->port_list, links) {
10211		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10212			continue;
10213		if (lun != NULL &&
10214		    ctl_map_lun_back(port->targ_port, lun->lun) >=
10215		    CTL_MAX_LUNS)
10216			continue;
10217		num_target_ports++;
10218		if (port->init_devid)
10219			iid_len += port->init_devid->len;
10220		if (port->port_devid)
10221			id_len += port->port_devid->len;
10222	}
10223	mtx_unlock(&softc->ctl_lock);
10224
10225	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10226	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10227	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10228	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10229	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10230	ctsio->kern_sg_entries = 0;
10231
10232	if (data_len < alloc_len) {
10233		ctsio->residual = alloc_len - data_len;
10234		ctsio->kern_data_len = data_len;
10235		ctsio->kern_total_len = data_len;
10236	} else {
10237		ctsio->residual = 0;
10238		ctsio->kern_data_len = alloc_len;
10239		ctsio->kern_total_len = alloc_len;
10240	}
10241	ctsio->kern_data_resid = 0;
10242	ctsio->kern_rel_offset = 0;
10243	ctsio->kern_sg_entries = 0;
10244
10245	/*
10246	 * The control device is always connected.  The disk device, on the
10247	 * other hand, may not be online all the time.  Need to change this
10248	 * to figure out whether the disk device is actually online or not.
10249	 */
10250	if (lun != NULL)
10251		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10252				  lun->be_lun->lun_type;
10253	else
10254		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10255
10256	sp->page_code = SVPD_SCSI_PORTS;
10257	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10258	    sp->page_length);
10259	pd = &sp->design[0];
10260
10261	mtx_lock(&softc->ctl_lock);
10262	if (softc->flags & CTL_FLAG_MASTER_SHELF)
10263		pg = 0;
10264	else
10265		pg = 1;
10266	for (g = 0; g < num_target_port_groups; g++) {
10267		STAILQ_FOREACH(port, &softc->port_list, links) {
10268			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10269				continue;
10270			if (lun != NULL &&
10271			    ctl_map_lun_back(port->targ_port, lun->lun) >=
10272			    CTL_MAX_LUNS)
10273				continue;
10274			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10275			scsi_ulto2b(p, pd->relative_port_id);
10276			if (port->init_devid && g == pg) {
10277				iid_len = port->init_devid->len;
10278				memcpy(pd->initiator_transportid,
10279				    port->init_devid->data, port->init_devid->len);
10280			} else
10281				iid_len = 0;
10282			scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10283			pdc = (struct scsi_vpd_port_designation_cont *)
10284			    (&pd->initiator_transportid[iid_len]);
10285			if (port->port_devid && g == pg) {
10286				id_len = port->port_devid->len;
10287				memcpy(pdc->target_port_descriptors,
10288				    port->port_devid->data, port->port_devid->len);
10289			} else
10290				id_len = 0;
10291			scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10292			pd = (struct scsi_vpd_port_designation *)
10293			    ((uint8_t *)pdc->target_port_descriptors + id_len);
10294		}
10295	}
10296	mtx_unlock(&softc->ctl_lock);
10297
10298	ctsio->scsi_status = SCSI_STATUS_OK;
10299	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10300	ctsio->be_move_done = ctl_config_move_done;
10301	ctl_datamove((union ctl_io *)ctsio);
10302
10303	return (CTL_RETVAL_COMPLETE);
10304}
10305
10306static int
10307ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10308{
10309	struct scsi_vpd_block_limits *bl_ptr;
10310	struct ctl_lun *lun;
10311	int bs;
10312
10313	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10314
10315	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10316	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10317	ctsio->kern_sg_entries = 0;
10318
10319	if (sizeof(*bl_ptr) < alloc_len) {
10320		ctsio->residual = alloc_len - sizeof(*bl_ptr);
10321		ctsio->kern_data_len = sizeof(*bl_ptr);
10322		ctsio->kern_total_len = sizeof(*bl_ptr);
10323	} else {
10324		ctsio->residual = 0;
10325		ctsio->kern_data_len = alloc_len;
10326		ctsio->kern_total_len = alloc_len;
10327	}
10328	ctsio->kern_data_resid = 0;
10329	ctsio->kern_rel_offset = 0;
10330	ctsio->kern_sg_entries = 0;
10331
10332	/*
10333	 * The control device is always connected.  The disk device, on the
10334	 * other hand, may not be online all the time.  Need to change this
10335	 * to figure out whether the disk device is actually online or not.
10336	 */
10337	if (lun != NULL)
10338		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10339				  lun->be_lun->lun_type;
10340	else
10341		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10342
10343	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10344	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10345	bl_ptr->max_cmp_write_len = 0xff;
10346	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10347	if (lun != NULL) {
10348		bs = lun->be_lun->blocksize;
10349		scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10350		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10351			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10352			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10353			if (lun->be_lun->pblockexp != 0) {
10354				scsi_ulto4b((1 << lun->be_lun->pblockexp),
10355				    bl_ptr->opt_unmap_grain);
10356				scsi_ulto4b(0x80000000 | lun->be_lun->pblockoff,
10357				    bl_ptr->unmap_grain_align);
10358			}
10359		}
10360		scsi_ulto4b(lun->be_lun->atomicblock,
10361		    bl_ptr->max_atomic_transfer_length);
10362		scsi_ulto4b(0, bl_ptr->atomic_alignment);
10363		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10364	}
10365	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10366
10367	ctsio->scsi_status = SCSI_STATUS_OK;
10368	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10369	ctsio->be_move_done = ctl_config_move_done;
10370	ctl_datamove((union ctl_io *)ctsio);
10371
10372	return (CTL_RETVAL_COMPLETE);
10373}
10374
10375static int
10376ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10377{
10378	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10379	struct ctl_lun *lun;
10380	const char *value;
10381	u_int i;
10382
10383	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10384
10385	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10386	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10387	ctsio->kern_sg_entries = 0;
10388
10389	if (sizeof(*bdc_ptr) < alloc_len) {
10390		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10391		ctsio->kern_data_len = sizeof(*bdc_ptr);
10392		ctsio->kern_total_len = sizeof(*bdc_ptr);
10393	} else {
10394		ctsio->residual = 0;
10395		ctsio->kern_data_len = alloc_len;
10396		ctsio->kern_total_len = alloc_len;
10397	}
10398	ctsio->kern_data_resid = 0;
10399	ctsio->kern_rel_offset = 0;
10400	ctsio->kern_sg_entries = 0;
10401
10402	/*
10403	 * The control device is always connected.  The disk device, on the
10404	 * other hand, may not be online all the time.  Need to change this
10405	 * to figure out whether the disk device is actually online or not.
10406	 */
10407	if (lun != NULL)
10408		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10409				  lun->be_lun->lun_type;
10410	else
10411		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10412	bdc_ptr->page_code = SVPD_BDC;
10413	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10414	if (lun != NULL &&
10415	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10416		i = strtol(value, NULL, 0);
10417	else
10418		i = CTL_DEFAULT_ROTATION_RATE;
10419	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10420	if (lun != NULL &&
10421	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10422		i = strtol(value, NULL, 0);
10423	else
10424		i = 0;
10425	bdc_ptr->wab_wac_ff = (i & 0x0f);
10426	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10427
10428	ctsio->scsi_status = SCSI_STATUS_OK;
10429	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10430	ctsio->be_move_done = ctl_config_move_done;
10431	ctl_datamove((union ctl_io *)ctsio);
10432
10433	return (CTL_RETVAL_COMPLETE);
10434}
10435
10436static int
10437ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10438{
10439	struct scsi_vpd_logical_block_prov *lbp_ptr;
10440	struct ctl_lun *lun;
10441
10442	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10443
10444	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10445	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10446	ctsio->kern_sg_entries = 0;
10447
10448	if (sizeof(*lbp_ptr) < alloc_len) {
10449		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10450		ctsio->kern_data_len = sizeof(*lbp_ptr);
10451		ctsio->kern_total_len = sizeof(*lbp_ptr);
10452	} else {
10453		ctsio->residual = 0;
10454		ctsio->kern_data_len = alloc_len;
10455		ctsio->kern_total_len = alloc_len;
10456	}
10457	ctsio->kern_data_resid = 0;
10458	ctsio->kern_rel_offset = 0;
10459	ctsio->kern_sg_entries = 0;
10460
10461	/*
10462	 * The control device is always connected.  The disk device, on the
10463	 * other hand, may not be online all the time.  Need to change this
10464	 * to figure out whether the disk device is actually online or not.
10465	 */
10466	if (lun != NULL)
10467		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10468				  lun->be_lun->lun_type;
10469	else
10470		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10471
10472	lbp_ptr->page_code = SVPD_LBP;
10473	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10474	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10475		lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10476		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10477		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10478		lbp_ptr->prov_type = SVPD_LBP_THIN;
10479	}
10480
10481	ctsio->scsi_status = SCSI_STATUS_OK;
10482	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10483	ctsio->be_move_done = ctl_config_move_done;
10484	ctl_datamove((union ctl_io *)ctsio);
10485
10486	return (CTL_RETVAL_COMPLETE);
10487}
10488
10489static int
10490ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10491{
10492	struct scsi_inquiry *cdb;
10493	struct ctl_lun *lun;
10494	int alloc_len, retval;
10495
10496	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10497	cdb = (struct scsi_inquiry *)ctsio->cdb;
10498
10499	retval = CTL_RETVAL_COMPLETE;
10500
10501	alloc_len = scsi_2btoul(cdb->length);
10502
10503	switch (cdb->page_code) {
10504	case SVPD_SUPPORTED_PAGES:
10505		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10506		break;
10507	case SVPD_UNIT_SERIAL_NUMBER:
10508		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10509		break;
10510	case SVPD_DEVICE_ID:
10511		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10512		break;
10513	case SVPD_EXTENDED_INQUIRY_DATA:
10514		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10515		break;
10516	case SVPD_MODE_PAGE_POLICY:
10517		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10518		break;
10519	case SVPD_SCSI_PORTS:
10520		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10521		break;
10522	case SVPD_SCSI_TPC:
10523		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10524		break;
10525	case SVPD_BLOCK_LIMITS:
10526		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10527		break;
10528	case SVPD_BDC:
10529		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10530		break;
10531	case SVPD_LBP:
10532		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10533		break;
10534	default:
10535		ctl_set_invalid_field(ctsio,
10536				      /*sks_valid*/ 1,
10537				      /*command*/ 1,
10538				      /*field*/ 2,
10539				      /*bit_valid*/ 0,
10540				      /*bit*/ 0);
10541		ctl_done((union ctl_io *)ctsio);
10542		retval = CTL_RETVAL_COMPLETE;
10543		break;
10544	}
10545
10546	return (retval);
10547}
10548
10549static int
10550ctl_inquiry_std(struct ctl_scsiio *ctsio)
10551{
10552	struct scsi_inquiry_data *inq_ptr;
10553	struct scsi_inquiry *cdb;
10554	struct ctl_softc *ctl_softc;
10555	struct ctl_lun *lun;
10556	char *val;
10557	uint32_t alloc_len, data_len;
10558	ctl_port_type port_type;
10559
10560	ctl_softc = control_softc;
10561
10562	/*
10563	 * Figure out whether we're talking to a Fibre Channel port or not.
10564	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10565	 * SCSI front ends.
10566	 */
10567	port_type = ctl_softc->ctl_ports[
10568	    ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10569	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10570		port_type = CTL_PORT_SCSI;
10571
10572	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10573	cdb = (struct scsi_inquiry *)ctsio->cdb;
10574	alloc_len = scsi_2btoul(cdb->length);
10575
10576	/*
10577	 * We malloc the full inquiry data size here and fill it
10578	 * in.  If the user only asks for less, we'll give him
10579	 * that much.
10580	 */
10581	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10582	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10583	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10584	ctsio->kern_sg_entries = 0;
10585	ctsio->kern_data_resid = 0;
10586	ctsio->kern_rel_offset = 0;
10587
10588	if (data_len < alloc_len) {
10589		ctsio->residual = alloc_len - data_len;
10590		ctsio->kern_data_len = data_len;
10591		ctsio->kern_total_len = data_len;
10592	} else {
10593		ctsio->residual = 0;
10594		ctsio->kern_data_len = alloc_len;
10595		ctsio->kern_total_len = alloc_len;
10596	}
10597
10598	/*
10599	 * If we have a LUN configured, report it as connected.  Otherwise,
10600	 * report that it is offline or no device is supported, depending
10601	 * on the value of inquiry_pq_no_lun.
10602	 *
10603	 * According to the spec (SPC-4 r34), the peripheral qualifier
10604	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10605	 *
10606	 * "A peripheral device having the specified peripheral device type
10607	 * is not connected to this logical unit. However, the device
10608	 * server is capable of supporting the specified peripheral device
10609	 * type on this logical unit."
10610	 *
10611	 * According to the same spec, the peripheral qualifier
10612	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10613	 *
10614	 * "The device server is not capable of supporting a peripheral
10615	 * device on this logical unit. For this peripheral qualifier the
10616	 * peripheral device type shall be set to 1Fh. All other peripheral
10617	 * device type values are reserved for this peripheral qualifier."
10618	 *
10619	 * Given the text, it would seem that we probably want to report that
10620	 * the LUN is offline here.  There is no LUN connected, but we can
10621	 * support a LUN at the given LUN number.
10622	 *
10623	 * In the real world, though, it sounds like things are a little
10624	 * different:
10625	 *
10626	 * - Linux, when presented with a LUN with the offline peripheral
10627	 *   qualifier, will create an sg driver instance for it.  So when
10628	 *   you attach it to CTL, you wind up with a ton of sg driver
10629	 *   instances.  (One for every LUN that Linux bothered to probe.)
10630	 *   Linux does this despite the fact that it issues a REPORT LUNs
10631	 *   to LUN 0 to get the inventory of supported LUNs.
10632	 *
10633	 * - There is other anecdotal evidence (from Emulex folks) about
10634	 *   arrays that use the offline peripheral qualifier for LUNs that
10635	 *   are on the "passive" path in an active/passive array.
10636	 *
10637	 * So the solution is provide a hopefully reasonable default
10638	 * (return bad/no LUN) and allow the user to change the behavior
10639	 * with a tunable/sysctl variable.
10640	 */
10641	if (lun != NULL)
10642		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10643				  lun->be_lun->lun_type;
10644	else if (ctl_softc->inquiry_pq_no_lun == 0)
10645		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10646	else
10647		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10648
10649	/* RMB in byte 2 is 0 */
10650	inq_ptr->version = SCSI_REV_SPC4;
10651
10652	/*
10653	 * According to SAM-3, even if a device only supports a single
10654	 * level of LUN addressing, it should still set the HISUP bit:
10655	 *
10656	 * 4.9.1 Logical unit numbers overview
10657	 *
10658	 * All logical unit number formats described in this standard are
10659	 * hierarchical in structure even when only a single level in that
10660	 * hierarchy is used. The HISUP bit shall be set to one in the
10661	 * standard INQUIRY data (see SPC-2) when any logical unit number
10662	 * format described in this standard is used.  Non-hierarchical
10663	 * formats are outside the scope of this standard.
10664	 *
10665	 * Therefore we set the HiSup bit here.
10666	 *
10667	 * The reponse format is 2, per SPC-3.
10668	 */
10669	inq_ptr->response_format = SID_HiSup | 2;
10670
10671	inq_ptr->additional_length = data_len -
10672	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10673	CTL_DEBUG_PRINT(("additional_length = %d\n",
10674			 inq_ptr->additional_length));
10675
10676	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10677	/* 16 bit addressing */
10678	if (port_type == CTL_PORT_SCSI)
10679		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10680	/* XXX set the SID_MultiP bit here if we're actually going to
10681	   respond on multiple ports */
10682	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10683
10684	/* 16 bit data bus, synchronous transfers */
10685	if (port_type == CTL_PORT_SCSI)
10686		inq_ptr->flags = SID_WBus16 | SID_Sync;
10687	/*
10688	 * XXX KDM do we want to support tagged queueing on the control
10689	 * device at all?
10690	 */
10691	if ((lun == NULL)
10692	 || (lun->be_lun->lun_type != T_PROCESSOR))
10693		inq_ptr->flags |= SID_CmdQue;
10694	/*
10695	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10696	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10697	 * name and 4 bytes for the revision.
10698	 */
10699	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10700	    "vendor")) == NULL) {
10701		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10702	} else {
10703		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10704		strncpy(inq_ptr->vendor, val,
10705		    min(sizeof(inq_ptr->vendor), strlen(val)));
10706	}
10707	if (lun == NULL) {
10708		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10709		    sizeof(inq_ptr->product));
10710	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10711		switch (lun->be_lun->lun_type) {
10712		case T_DIRECT:
10713			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10714			    sizeof(inq_ptr->product));
10715			break;
10716		case T_PROCESSOR:
10717			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10718			    sizeof(inq_ptr->product));
10719			break;
10720		default:
10721			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10722			    sizeof(inq_ptr->product));
10723			break;
10724		}
10725	} else {
10726		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10727		strncpy(inq_ptr->product, val,
10728		    min(sizeof(inq_ptr->product), strlen(val)));
10729	}
10730
10731	/*
10732	 * XXX make this a macro somewhere so it automatically gets
10733	 * incremented when we make changes.
10734	 */
10735	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10736	    "revision")) == NULL) {
10737		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10738	} else {
10739		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10740		strncpy(inq_ptr->revision, val,
10741		    min(sizeof(inq_ptr->revision), strlen(val)));
10742	}
10743
10744	/*
10745	 * For parallel SCSI, we support double transition and single
10746	 * transition clocking.  We also support QAS (Quick Arbitration
10747	 * and Selection) and Information Unit transfers on both the
10748	 * control and array devices.
10749	 */
10750	if (port_type == CTL_PORT_SCSI)
10751		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10752				    SID_SPI_IUS;
10753
10754	/* SAM-5 (no version claimed) */
10755	scsi_ulto2b(0x00A0, inq_ptr->version1);
10756	/* SPC-4 (no version claimed) */
10757	scsi_ulto2b(0x0460, inq_ptr->version2);
10758	if (port_type == CTL_PORT_FC) {
10759		/* FCP-2 ANSI INCITS.350:2003 */
10760		scsi_ulto2b(0x0917, inq_ptr->version3);
10761	} else if (port_type == CTL_PORT_SCSI) {
10762		/* SPI-4 ANSI INCITS.362:200x */
10763		scsi_ulto2b(0x0B56, inq_ptr->version3);
10764	} else if (port_type == CTL_PORT_ISCSI) {
10765		/* iSCSI (no version claimed) */
10766		scsi_ulto2b(0x0960, inq_ptr->version3);
10767	} else if (port_type == CTL_PORT_SAS) {
10768		/* SAS (no version claimed) */
10769		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10770	}
10771
10772	if (lun == NULL) {
10773		/* SBC-4 (no version claimed) */
10774		scsi_ulto2b(0x0600, inq_ptr->version4);
10775	} else {
10776		switch (lun->be_lun->lun_type) {
10777		case T_DIRECT:
10778			/* SBC-4 (no version claimed) */
10779			scsi_ulto2b(0x0600, inq_ptr->version4);
10780			break;
10781		case T_PROCESSOR:
10782		default:
10783			break;
10784		}
10785	}
10786
10787	ctsio->scsi_status = SCSI_STATUS_OK;
10788	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10789	ctsio->be_move_done = ctl_config_move_done;
10790	ctl_datamove((union ctl_io *)ctsio);
10791	return (CTL_RETVAL_COMPLETE);
10792}
10793
10794int
10795ctl_inquiry(struct ctl_scsiio *ctsio)
10796{
10797	struct scsi_inquiry *cdb;
10798	int retval;
10799
10800	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10801
10802	cdb = (struct scsi_inquiry *)ctsio->cdb;
10803	if (cdb->byte2 & SI_EVPD)
10804		retval = ctl_inquiry_evpd(ctsio);
10805	else if (cdb->page_code == 0)
10806		retval = ctl_inquiry_std(ctsio);
10807	else {
10808		ctl_set_invalid_field(ctsio,
10809				      /*sks_valid*/ 1,
10810				      /*command*/ 1,
10811				      /*field*/ 2,
10812				      /*bit_valid*/ 0,
10813				      /*bit*/ 0);
10814		ctl_done((union ctl_io *)ctsio);
10815		return (CTL_RETVAL_COMPLETE);
10816	}
10817
10818	return (retval);
10819}
10820
10821/*
10822 * For known CDB types, parse the LBA and length.
10823 */
10824static int
10825ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10826{
10827	if (io->io_hdr.io_type != CTL_IO_SCSI)
10828		return (1);
10829
10830	switch (io->scsiio.cdb[0]) {
10831	case COMPARE_AND_WRITE: {
10832		struct scsi_compare_and_write *cdb;
10833
10834		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10835
10836		*lba = scsi_8btou64(cdb->addr);
10837		*len = cdb->length;
10838		break;
10839	}
10840	case READ_6:
10841	case WRITE_6: {
10842		struct scsi_rw_6 *cdb;
10843
10844		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10845
10846		*lba = scsi_3btoul(cdb->addr);
10847		/* only 5 bits are valid in the most significant address byte */
10848		*lba &= 0x1fffff;
10849		*len = cdb->length;
10850		break;
10851	}
10852	case READ_10:
10853	case WRITE_10: {
10854		struct scsi_rw_10 *cdb;
10855
10856		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10857
10858		*lba = scsi_4btoul(cdb->addr);
10859		*len = scsi_2btoul(cdb->length);
10860		break;
10861	}
10862	case WRITE_VERIFY_10: {
10863		struct scsi_write_verify_10 *cdb;
10864
10865		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10866
10867		*lba = scsi_4btoul(cdb->addr);
10868		*len = scsi_2btoul(cdb->length);
10869		break;
10870	}
10871	case READ_12:
10872	case WRITE_12: {
10873		struct scsi_rw_12 *cdb;
10874
10875		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10876
10877		*lba = scsi_4btoul(cdb->addr);
10878		*len = scsi_4btoul(cdb->length);
10879		break;
10880	}
10881	case WRITE_VERIFY_12: {
10882		struct scsi_write_verify_12 *cdb;
10883
10884		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10885
10886		*lba = scsi_4btoul(cdb->addr);
10887		*len = scsi_4btoul(cdb->length);
10888		break;
10889	}
10890	case READ_16:
10891	case WRITE_16:
10892	case WRITE_ATOMIC_16: {
10893		struct scsi_rw_16 *cdb;
10894
10895		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10896
10897		*lba = scsi_8btou64(cdb->addr);
10898		*len = scsi_4btoul(cdb->length);
10899		break;
10900	}
10901	case WRITE_VERIFY_16: {
10902		struct scsi_write_verify_16 *cdb;
10903
10904		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10905
10906		*lba = scsi_8btou64(cdb->addr);
10907		*len = scsi_4btoul(cdb->length);
10908		break;
10909	}
10910	case WRITE_SAME_10: {
10911		struct scsi_write_same_10 *cdb;
10912
10913		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10914
10915		*lba = scsi_4btoul(cdb->addr);
10916		*len = scsi_2btoul(cdb->length);
10917		break;
10918	}
10919	case WRITE_SAME_16: {
10920		struct scsi_write_same_16 *cdb;
10921
10922		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10923
10924		*lba = scsi_8btou64(cdb->addr);
10925		*len = scsi_4btoul(cdb->length);
10926		break;
10927	}
10928	case VERIFY_10: {
10929		struct scsi_verify_10 *cdb;
10930
10931		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10932
10933		*lba = scsi_4btoul(cdb->addr);
10934		*len = scsi_2btoul(cdb->length);
10935		break;
10936	}
10937	case VERIFY_12: {
10938		struct scsi_verify_12 *cdb;
10939
10940		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10941
10942		*lba = scsi_4btoul(cdb->addr);
10943		*len = scsi_4btoul(cdb->length);
10944		break;
10945	}
10946	case VERIFY_16: {
10947		struct scsi_verify_16 *cdb;
10948
10949		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10950
10951		*lba = scsi_8btou64(cdb->addr);
10952		*len = scsi_4btoul(cdb->length);
10953		break;
10954	}
10955	case UNMAP: {
10956		*lba = 0;
10957		*len = UINT64_MAX;
10958		break;
10959	}
10960	default:
10961		return (1);
10962		break; /* NOTREACHED */
10963	}
10964
10965	return (0);
10966}
10967
10968static ctl_action
10969ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2)
10970{
10971	uint64_t endlba1, endlba2;
10972
10973	endlba1 = lba1 + len1 - 1;
10974	endlba2 = lba2 + len2 - 1;
10975
10976	if ((endlba1 < lba2)
10977	 || (endlba2 < lba1))
10978		return (CTL_ACTION_PASS);
10979	else
10980		return (CTL_ACTION_BLOCK);
10981}
10982
10983static int
10984ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10985{
10986	struct ctl_ptr_len_flags *ptrlen;
10987	struct scsi_unmap_desc *buf, *end, *range;
10988	uint64_t lba;
10989	uint32_t len;
10990
10991	/* If not UNMAP -- go other way. */
10992	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10993	    io->scsiio.cdb[0] != UNMAP)
10994		return (CTL_ACTION_ERROR);
10995
10996	/* If UNMAP without data -- block and wait for data. */
10997	ptrlen = (struct ctl_ptr_len_flags *)
10998	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10999	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
11000	    ptrlen->ptr == NULL)
11001		return (CTL_ACTION_BLOCK);
11002
11003	/* UNMAP with data -- check for collision. */
11004	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
11005	end = buf + ptrlen->len / sizeof(*buf);
11006	for (range = buf; range < end; range++) {
11007		lba = scsi_8btou64(range->lba);
11008		len = scsi_4btoul(range->length);
11009		if ((lba < lba2 + len2) && (lba + len > lba2))
11010			return (CTL_ACTION_BLOCK);
11011	}
11012	return (CTL_ACTION_PASS);
11013}
11014
11015static ctl_action
11016ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
11017{
11018	uint64_t lba1, lba2;
11019	uint64_t len1, len2;
11020	int retval;
11021
11022	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
11023		return (CTL_ACTION_ERROR);
11024
11025	retval = ctl_extent_check_unmap(io2, lba1, len1);
11026	if (retval != CTL_ACTION_ERROR)
11027		return (retval);
11028
11029	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
11030		return (CTL_ACTION_ERROR);
11031
11032	return (ctl_extent_check_lba(lba1, len1, lba2, len2));
11033}
11034
11035static ctl_action
11036ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
11037    union ctl_io *ooa_io)
11038{
11039	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
11040	ctl_serialize_action *serialize_row;
11041
11042	/*
11043	 * The initiator attempted multiple untagged commands at the same
11044	 * time.  Can't do that.
11045	 */
11046	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11047	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11048	 && ((pending_io->io_hdr.nexus.targ_port ==
11049	      ooa_io->io_hdr.nexus.targ_port)
11050	  && (pending_io->io_hdr.nexus.initid.id ==
11051	      ooa_io->io_hdr.nexus.initid.id))
11052	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
11053		return (CTL_ACTION_OVERLAP);
11054
11055	/*
11056	 * The initiator attempted to send multiple tagged commands with
11057	 * the same ID.  (It's fine if different initiators have the same
11058	 * tag ID.)
11059	 *
11060	 * Even if all of those conditions are true, we don't kill the I/O
11061	 * if the command ahead of us has been aborted.  We won't end up
11062	 * sending it to the FETD, and it's perfectly legal to resend a
11063	 * command with the same tag number as long as the previous
11064	 * instance of this tag number has been aborted somehow.
11065	 */
11066	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11067	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11068	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11069	 && ((pending_io->io_hdr.nexus.targ_port ==
11070	      ooa_io->io_hdr.nexus.targ_port)
11071	  && (pending_io->io_hdr.nexus.initid.id ==
11072	      ooa_io->io_hdr.nexus.initid.id))
11073	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
11074		return (CTL_ACTION_OVERLAP_TAG);
11075
11076	/*
11077	 * If we get a head of queue tag, SAM-3 says that we should
11078	 * immediately execute it.
11079	 *
11080	 * What happens if this command would normally block for some other
11081	 * reason?  e.g. a request sense with a head of queue tag
11082	 * immediately after a write.  Normally that would block, but this
11083	 * will result in its getting executed immediately...
11084	 *
11085	 * We currently return "pass" instead of "skip", so we'll end up
11086	 * going through the rest of the queue to check for overlapped tags.
11087	 *
11088	 * XXX KDM check for other types of blockage first??
11089	 */
11090	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11091		return (CTL_ACTION_PASS);
11092
11093	/*
11094	 * Ordered tags have to block until all items ahead of them
11095	 * have completed.  If we get called with an ordered tag, we always
11096	 * block, if something else is ahead of us in the queue.
11097	 */
11098	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11099		return (CTL_ACTION_BLOCK);
11100
11101	/*
11102	 * Simple tags get blocked until all head of queue and ordered tags
11103	 * ahead of them have completed.  I'm lumping untagged commands in
11104	 * with simple tags here.  XXX KDM is that the right thing to do?
11105	 */
11106	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11107	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11108	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11109	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11110		return (CTL_ACTION_BLOCK);
11111
11112	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11113	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11114
11115	serialize_row = ctl_serialize_table[ooa_entry->seridx];
11116
11117	switch (serialize_row[pending_entry->seridx]) {
11118	case CTL_SER_BLOCK:
11119		return (CTL_ACTION_BLOCK);
11120	case CTL_SER_EXTENT:
11121		return (ctl_extent_check(pending_io, ooa_io));
11122	case CTL_SER_EXTENTOPT:
11123		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11124		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11125			return (ctl_extent_check(pending_io, ooa_io));
11126		/* FALLTHROUGH */
11127	case CTL_SER_PASS:
11128		return (CTL_ACTION_PASS);
11129	case CTL_SER_BLOCKOPT:
11130		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11131		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11132			return (CTL_ACTION_BLOCK);
11133		return (CTL_ACTION_PASS);
11134	case CTL_SER_SKIP:
11135		return (CTL_ACTION_SKIP);
11136	default:
11137		panic("invalid serialization value %d",
11138		      serialize_row[pending_entry->seridx]);
11139	}
11140
11141	return (CTL_ACTION_ERROR);
11142}
11143
11144/*
11145 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11146 * Assumptions:
11147 * - pending_io is generally either incoming, or on the blocked queue
11148 * - starting I/O is the I/O we want to start the check with.
11149 */
11150static ctl_action
11151ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11152	      union ctl_io *starting_io)
11153{
11154	union ctl_io *ooa_io;
11155	ctl_action action;
11156
11157	mtx_assert(&lun->lun_lock, MA_OWNED);
11158
11159	/*
11160	 * Run back along the OOA queue, starting with the current
11161	 * blocked I/O and going through every I/O before it on the
11162	 * queue.  If starting_io is NULL, we'll just end up returning
11163	 * CTL_ACTION_PASS.
11164	 */
11165	for (ooa_io = starting_io; ooa_io != NULL;
11166	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11167	     ooa_links)){
11168
11169		/*
11170		 * This routine just checks to see whether
11171		 * cur_blocked is blocked by ooa_io, which is ahead
11172		 * of it in the queue.  It doesn't queue/dequeue
11173		 * cur_blocked.
11174		 */
11175		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11176		switch (action) {
11177		case CTL_ACTION_BLOCK:
11178		case CTL_ACTION_OVERLAP:
11179		case CTL_ACTION_OVERLAP_TAG:
11180		case CTL_ACTION_SKIP:
11181		case CTL_ACTION_ERROR:
11182			return (action);
11183			break; /* NOTREACHED */
11184		case CTL_ACTION_PASS:
11185			break;
11186		default:
11187			panic("invalid action %d", action);
11188			break;  /* NOTREACHED */
11189		}
11190	}
11191
11192	return (CTL_ACTION_PASS);
11193}
11194
11195/*
11196 * Assumptions:
11197 * - An I/O has just completed, and has been removed from the per-LUN OOA
11198 *   queue, so some items on the blocked queue may now be unblocked.
11199 */
11200static int
11201ctl_check_blocked(struct ctl_lun *lun)
11202{
11203	union ctl_io *cur_blocked, *next_blocked;
11204
11205	mtx_assert(&lun->lun_lock, MA_OWNED);
11206
11207	/*
11208	 * Run forward from the head of the blocked queue, checking each
11209	 * entry against the I/Os prior to it on the OOA queue to see if
11210	 * there is still any blockage.
11211	 *
11212	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11213	 * with our removing a variable on it while it is traversing the
11214	 * list.
11215	 */
11216	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11217	     cur_blocked != NULL; cur_blocked = next_blocked) {
11218		union ctl_io *prev_ooa;
11219		ctl_action action;
11220
11221		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11222							  blocked_links);
11223
11224		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11225						      ctl_ooaq, ooa_links);
11226
11227		/*
11228		 * If cur_blocked happens to be the first item in the OOA
11229		 * queue now, prev_ooa will be NULL, and the action
11230		 * returned will just be CTL_ACTION_PASS.
11231		 */
11232		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11233
11234		switch (action) {
11235		case CTL_ACTION_BLOCK:
11236			/* Nothing to do here, still blocked */
11237			break;
11238		case CTL_ACTION_OVERLAP:
11239		case CTL_ACTION_OVERLAP_TAG:
11240			/*
11241			 * This shouldn't happen!  In theory we've already
11242			 * checked this command for overlap...
11243			 */
11244			break;
11245		case CTL_ACTION_PASS:
11246		case CTL_ACTION_SKIP: {
11247			struct ctl_softc *softc;
11248			const struct ctl_cmd_entry *entry;
11249			uint32_t initidx;
11250			int isc_retval;
11251
11252			/*
11253			 * The skip case shouldn't happen, this transaction
11254			 * should have never made it onto the blocked queue.
11255			 */
11256			/*
11257			 * This I/O is no longer blocked, we can remove it
11258			 * from the blocked queue.  Since this is a TAILQ
11259			 * (doubly linked list), we can do O(1) removals
11260			 * from any place on the list.
11261			 */
11262			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11263				     blocked_links);
11264			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11265
11266			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11267				/*
11268				 * Need to send IO back to original side to
11269				 * run
11270				 */
11271				union ctl_ha_msg msg_info;
11272
11273				msg_info.hdr.original_sc =
11274					cur_blocked->io_hdr.original_sc;
11275				msg_info.hdr.serializing_sc = cur_blocked;
11276				msg_info.hdr.msg_type = CTL_MSG_R2R;
11277				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11278				     &msg_info, sizeof(msg_info), 0)) >
11279				     CTL_HA_STATUS_SUCCESS) {
11280					printf("CTL:Check Blocked error from "
11281					       "ctl_ha_msg_send %d\n",
11282					       isc_retval);
11283				}
11284				break;
11285			}
11286			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11287			softc = control_softc;
11288
11289			initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
11290
11291			/*
11292			 * Check this I/O for LUN state changes that may
11293			 * have happened while this command was blocked.
11294			 * The LUN state may have been changed by a command
11295			 * ahead of us in the queue, so we need to re-check
11296			 * for any states that can be caused by SCSI
11297			 * commands.
11298			 */
11299			if (ctl_scsiio_lun_check(softc, lun, entry,
11300						 &cur_blocked->scsiio) == 0) {
11301				cur_blocked->io_hdr.flags |=
11302				                      CTL_FLAG_IS_WAS_ON_RTR;
11303				ctl_enqueue_rtr(cur_blocked);
11304			} else
11305				ctl_done(cur_blocked);
11306			break;
11307		}
11308		default:
11309			/*
11310			 * This probably shouldn't happen -- we shouldn't
11311			 * get CTL_ACTION_ERROR, or anything else.
11312			 */
11313			break;
11314		}
11315	}
11316
11317	return (CTL_RETVAL_COMPLETE);
11318}
11319
11320/*
11321 * This routine (with one exception) checks LUN flags that can be set by
11322 * commands ahead of us in the OOA queue.  These flags have to be checked
11323 * when a command initially comes in, and when we pull a command off the
11324 * blocked queue and are preparing to execute it.  The reason we have to
11325 * check these flags for commands on the blocked queue is that the LUN
11326 * state may have been changed by a command ahead of us while we're on the
11327 * blocked queue.
11328 *
11329 * Ordering is somewhat important with these checks, so please pay
11330 * careful attention to the placement of any new checks.
11331 */
11332static int
11333ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11334    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11335{
11336	int retval;
11337	uint32_t residx;
11338
11339	retval = 0;
11340
11341	mtx_assert(&lun->lun_lock, MA_OWNED);
11342
11343	/*
11344	 * If this shelf is a secondary shelf controller, we have to reject
11345	 * any media access commands.
11346	 */
11347#if 0
11348	/* No longer needed for HA */
11349	if (((ctl_softc->flags & CTL_FLAG_MASTER_SHELF) == 0)
11350	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0)) {
11351		ctl_set_lun_standby(ctsio);
11352		retval = 1;
11353		goto bailout;
11354	}
11355#endif
11356
11357	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11358		if (lun->flags & CTL_LUN_READONLY) {
11359			ctl_set_sense(ctsio, /*current_error*/ 1,
11360			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11361			    /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11362			retval = 1;
11363			goto bailout;
11364		}
11365		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11366		    .eca_and_aen & SCP_SWP) != 0) {
11367			ctl_set_sense(ctsio, /*current_error*/ 1,
11368			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11369			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11370			retval = 1;
11371			goto bailout;
11372		}
11373	}
11374
11375	/*
11376	 * Check for a reservation conflict.  If this command isn't allowed
11377	 * even on reserved LUNs, and if this initiator isn't the one who
11378	 * reserved us, reject the command with a reservation conflict.
11379	 */
11380	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11381	if ((lun->flags & CTL_LUN_RESERVED)
11382	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11383		if (lun->res_idx != residx) {
11384			ctl_set_reservation_conflict(ctsio);
11385			retval = 1;
11386			goto bailout;
11387		}
11388	}
11389
11390	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11391	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11392		/* No reservation or command is allowed. */;
11393	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11394	    (lun->res_type == SPR_TYPE_WR_EX ||
11395	     lun->res_type == SPR_TYPE_WR_EX_RO ||
11396	     lun->res_type == SPR_TYPE_WR_EX_AR)) {
11397		/* The command is allowed for Write Exclusive resv. */;
11398	} else {
11399		/*
11400		 * if we aren't registered or it's a res holder type
11401		 * reservation and this isn't the res holder then set a
11402		 * conflict.
11403		 */
11404		if (lun->pr_keys[residx] == 0
11405		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11406			ctl_set_reservation_conflict(ctsio);
11407			retval = 1;
11408			goto bailout;
11409		}
11410
11411	}
11412
11413	if ((lun->flags & CTL_LUN_OFFLINE)
11414	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11415		ctl_set_lun_not_ready(ctsio);
11416		retval = 1;
11417		goto bailout;
11418	}
11419
11420	/*
11421	 * If the LUN is stopped, see if this particular command is allowed
11422	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11423	 */
11424	if ((lun->flags & CTL_LUN_STOPPED)
11425	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11426		/* "Logical unit not ready, initializing cmd. required" */
11427		ctl_set_lun_stopped(ctsio);
11428		retval = 1;
11429		goto bailout;
11430	}
11431
11432	if ((lun->flags & CTL_LUN_INOPERABLE)
11433	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11434		/* "Medium format corrupted" */
11435		ctl_set_medium_format_corrupted(ctsio);
11436		retval = 1;
11437		goto bailout;
11438	}
11439
11440bailout:
11441	return (retval);
11442
11443}
11444
11445static void
11446ctl_failover_io(union ctl_io *io, int have_lock)
11447{
11448	ctl_set_busy(&io->scsiio);
11449	ctl_done(io);
11450}
11451
11452static void
11453ctl_failover(void)
11454{
11455	struct ctl_lun *lun;
11456	struct ctl_softc *ctl_softc;
11457	union ctl_io *next_io, *pending_io;
11458	union ctl_io *io;
11459	int lun_idx;
11460	int i;
11461
11462	ctl_softc = control_softc;
11463
11464	mtx_lock(&ctl_softc->ctl_lock);
11465	/*
11466	 * Remove any cmds from the other SC from the rtr queue.  These
11467	 * will obviously only be for LUNs for which we're the primary.
11468	 * We can't send status or get/send data for these commands.
11469	 * Since they haven't been executed yet, we can just remove them.
11470	 * We'll either abort them or delete them below, depending on
11471	 * which HA mode we're in.
11472	 */
11473#ifdef notyet
11474	mtx_lock(&ctl_softc->queue_lock);
11475	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11476	     io != NULL; io = next_io) {
11477		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11478		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11479			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11480				      ctl_io_hdr, links);
11481	}
11482	mtx_unlock(&ctl_softc->queue_lock);
11483#endif
11484
11485	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11486		lun = ctl_softc->ctl_luns[lun_idx];
11487		if (lun==NULL)
11488			continue;
11489
11490		/*
11491		 * Processor LUNs are primary on both sides.
11492		 * XXX will this always be true?
11493		 */
11494		if (lun->be_lun->lun_type == T_PROCESSOR)
11495			continue;
11496
11497		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11498		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11499			printf("FAILOVER: primary lun %d\n", lun_idx);
11500		        /*
11501			 * Remove all commands from the other SC. First from the
11502			 * blocked queue then from the ooa queue. Once we have
11503			 * removed them. Call ctl_check_blocked to see if there
11504			 * is anything that can run.
11505			 */
11506			for (io = (union ctl_io *)TAILQ_FIRST(
11507			     &lun->blocked_queue); io != NULL; io = next_io) {
11508
11509		        	next_io = (union ctl_io *)TAILQ_NEXT(
11510				    &io->io_hdr, blocked_links);
11511
11512				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11513					TAILQ_REMOVE(&lun->blocked_queue,
11514						     &io->io_hdr,blocked_links);
11515					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11516					TAILQ_REMOVE(&lun->ooa_queue,
11517						     &io->io_hdr, ooa_links);
11518
11519					ctl_free_io(io);
11520				}
11521			}
11522
11523			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11524	     		     io != NULL; io = next_io) {
11525
11526		        	next_io = (union ctl_io *)TAILQ_NEXT(
11527				    &io->io_hdr, ooa_links);
11528
11529				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11530
11531					TAILQ_REMOVE(&lun->ooa_queue,
11532						&io->io_hdr,
11533					     	ooa_links);
11534
11535					ctl_free_io(io);
11536				}
11537			}
11538			ctl_check_blocked(lun);
11539		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11540			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11541
11542			printf("FAILOVER: primary lun %d\n", lun_idx);
11543			/*
11544			 * Abort all commands from the other SC.  We can't
11545			 * send status back for them now.  These should get
11546			 * cleaned up when they are completed or come out
11547			 * for a datamove operation.
11548			 */
11549			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11550	     		     io != NULL; io = next_io) {
11551		        	next_io = (union ctl_io *)TAILQ_NEXT(
11552					&io->io_hdr, ooa_links);
11553
11554				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11555					io->io_hdr.flags |= CTL_FLAG_ABORT;
11556			}
11557		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11558			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11559
11560			printf("FAILOVER: secondary lun %d\n", lun_idx);
11561
11562			lun->flags |= CTL_LUN_PRIMARY_SC;
11563
11564			/*
11565			 * We send all I/O that was sent to this controller
11566			 * and redirected to the other side back with
11567			 * busy status, and have the initiator retry it.
11568			 * Figuring out how much data has been transferred,
11569			 * etc. and picking up where we left off would be
11570			 * very tricky.
11571			 *
11572			 * XXX KDM need to remove I/O from the blocked
11573			 * queue as well!
11574			 */
11575			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11576			     &lun->ooa_queue); pending_io != NULL;
11577			     pending_io = next_io) {
11578
11579				next_io =  (union ctl_io *)TAILQ_NEXT(
11580					&pending_io->io_hdr, ooa_links);
11581
11582				pending_io->io_hdr.flags &=
11583					~CTL_FLAG_SENT_2OTHER_SC;
11584
11585				if (pending_io->io_hdr.flags &
11586				    CTL_FLAG_IO_ACTIVE) {
11587					pending_io->io_hdr.flags |=
11588						CTL_FLAG_FAILOVER;
11589				} else {
11590					ctl_set_busy(&pending_io->scsiio);
11591					ctl_done(pending_io);
11592				}
11593			}
11594
11595			/*
11596			 * Build Unit Attention
11597			 */
11598			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11599				lun->pending_ua[i] |=
11600				                     CTL_UA_ASYM_ACC_CHANGE;
11601			}
11602		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11603			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11604			printf("FAILOVER: secondary lun %d\n", lun_idx);
11605			/*
11606			 * if the first io on the OOA is not on the RtR queue
11607			 * add it.
11608			 */
11609			lun->flags |= CTL_LUN_PRIMARY_SC;
11610
11611			pending_io = (union ctl_io *)TAILQ_FIRST(
11612			    &lun->ooa_queue);
11613			if (pending_io==NULL) {
11614				printf("Nothing on OOA queue\n");
11615				continue;
11616			}
11617
11618			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11619			if ((pending_io->io_hdr.flags &
11620			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11621				pending_io->io_hdr.flags |=
11622				    CTL_FLAG_IS_WAS_ON_RTR;
11623				ctl_enqueue_rtr(pending_io);
11624			}
11625#if 0
11626			else
11627			{
11628				printf("Tag 0x%04x is running\n",
11629				      pending_io->scsiio.tag_num);
11630			}
11631#endif
11632
11633			next_io = (union ctl_io *)TAILQ_NEXT(
11634			    &pending_io->io_hdr, ooa_links);
11635			for (pending_io=next_io; pending_io != NULL;
11636			     pending_io = next_io) {
11637				pending_io->io_hdr.flags &=
11638				    ~CTL_FLAG_SENT_2OTHER_SC;
11639				next_io = (union ctl_io *)TAILQ_NEXT(
11640					&pending_io->io_hdr, ooa_links);
11641				if (pending_io->io_hdr.flags &
11642				    CTL_FLAG_IS_WAS_ON_RTR) {
11643#if 0
11644				        printf("Tag 0x%04x is running\n",
11645				      		pending_io->scsiio.tag_num);
11646#endif
11647					continue;
11648				}
11649
11650				switch (ctl_check_ooa(lun, pending_io,
11651			            (union ctl_io *)TAILQ_PREV(
11652				    &pending_io->io_hdr, ctl_ooaq,
11653				    ooa_links))) {
11654
11655				case CTL_ACTION_BLOCK:
11656					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11657							  &pending_io->io_hdr,
11658							  blocked_links);
11659					pending_io->io_hdr.flags |=
11660					    CTL_FLAG_BLOCKED;
11661					break;
11662				case CTL_ACTION_PASS:
11663				case CTL_ACTION_SKIP:
11664					pending_io->io_hdr.flags |=
11665					    CTL_FLAG_IS_WAS_ON_RTR;
11666					ctl_enqueue_rtr(pending_io);
11667					break;
11668				case CTL_ACTION_OVERLAP:
11669					ctl_set_overlapped_cmd(
11670					    (struct ctl_scsiio *)pending_io);
11671					ctl_done(pending_io);
11672					break;
11673				case CTL_ACTION_OVERLAP_TAG:
11674					ctl_set_overlapped_tag(
11675					    (struct ctl_scsiio *)pending_io,
11676					    pending_io->scsiio.tag_num & 0xff);
11677					ctl_done(pending_io);
11678					break;
11679				case CTL_ACTION_ERROR:
11680				default:
11681					ctl_set_internal_failure(
11682						(struct ctl_scsiio *)pending_io,
11683						0,  // sks_valid
11684						0); //retry count
11685					ctl_done(pending_io);
11686					break;
11687				}
11688			}
11689
11690			/*
11691			 * Build Unit Attention
11692			 */
11693			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11694				lun->pending_ua[i] |=
11695				                     CTL_UA_ASYM_ACC_CHANGE;
11696			}
11697		} else {
11698			panic("Unhandled HA mode failover, LUN flags = %#x, "
11699			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11700		}
11701	}
11702	ctl_pause_rtr = 0;
11703	mtx_unlock(&ctl_softc->ctl_lock);
11704}
11705
11706static int
11707ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11708{
11709	struct ctl_lun *lun;
11710	const struct ctl_cmd_entry *entry;
11711	uint32_t initidx, targ_lun;
11712	int retval;
11713
11714	retval = 0;
11715
11716	lun = NULL;
11717
11718	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11719	if ((targ_lun < CTL_MAX_LUNS)
11720	 && (ctl_softc->ctl_luns[targ_lun] != NULL)) {
11721		lun = ctl_softc->ctl_luns[targ_lun];
11722		/*
11723		 * If the LUN is invalid, pretend that it doesn't exist.
11724		 * It will go away as soon as all pending I/O has been
11725		 * completed.
11726		 */
11727		if (lun->flags & CTL_LUN_DISABLED) {
11728			lun = NULL;
11729		} else {
11730			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11731			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11732				lun->be_lun;
11733			if (lun->be_lun->lun_type == T_PROCESSOR) {
11734				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11735			}
11736
11737			/*
11738			 * Every I/O goes into the OOA queue for a
11739			 * particular LUN, and stays there until completion.
11740			 */
11741			mtx_lock(&lun->lun_lock);
11742			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11743			    ooa_links);
11744		}
11745	} else {
11746		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11747		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11748	}
11749
11750	/* Get command entry and return error if it is unsuppotyed. */
11751	entry = ctl_validate_command(ctsio);
11752	if (entry == NULL) {
11753		if (lun)
11754			mtx_unlock(&lun->lun_lock);
11755		return (retval);
11756	}
11757
11758	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11759	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11760
11761	/*
11762	 * Check to see whether we can send this command to LUNs that don't
11763	 * exist.  This should pretty much only be the case for inquiry
11764	 * and request sense.  Further checks, below, really require having
11765	 * a LUN, so we can't really check the command anymore.  Just put
11766	 * it on the rtr queue.
11767	 */
11768	if (lun == NULL) {
11769		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11770			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11771			ctl_enqueue_rtr((union ctl_io *)ctsio);
11772			return (retval);
11773		}
11774
11775		ctl_set_unsupported_lun(ctsio);
11776		ctl_done((union ctl_io *)ctsio);
11777		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11778		return (retval);
11779	} else {
11780		/*
11781		 * Make sure we support this particular command on this LUN.
11782		 * e.g., we don't support writes to the control LUN.
11783		 */
11784		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11785			mtx_unlock(&lun->lun_lock);
11786			ctl_set_invalid_opcode(ctsio);
11787			ctl_done((union ctl_io *)ctsio);
11788			return (retval);
11789		}
11790	}
11791
11792	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11793
11794#ifdef CTL_WITH_CA
11795	/*
11796	 * If we've got a request sense, it'll clear the contingent
11797	 * allegiance condition.  Otherwise, if we have a CA condition for
11798	 * this initiator, clear it, because it sent down a command other
11799	 * than request sense.
11800	 */
11801	if ((ctsio->cdb[0] != REQUEST_SENSE)
11802	 && (ctl_is_set(lun->have_ca, initidx)))
11803		ctl_clear_mask(lun->have_ca, initidx);
11804#endif
11805
11806	/*
11807	 * If the command has this flag set, it handles its own unit
11808	 * attention reporting, we shouldn't do anything.  Otherwise we
11809	 * check for any pending unit attentions, and send them back to the
11810	 * initiator.  We only do this when a command initially comes in,
11811	 * not when we pull it off the blocked queue.
11812	 *
11813	 * According to SAM-3, section 5.3.2, the order that things get
11814	 * presented back to the host is basically unit attentions caused
11815	 * by some sort of reset event, busy status, reservation conflicts
11816	 * or task set full, and finally any other status.
11817	 *
11818	 * One issue here is that some of the unit attentions we report
11819	 * don't fall into the "reset" category (e.g. "reported luns data
11820	 * has changed").  So reporting it here, before the reservation
11821	 * check, may be technically wrong.  I guess the only thing to do
11822	 * would be to check for and report the reset events here, and then
11823	 * check for the other unit attention types after we check for a
11824	 * reservation conflict.
11825	 *
11826	 * XXX KDM need to fix this
11827	 */
11828	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11829		ctl_ua_type ua_type;
11830
11831		if (lun->pending_ua[initidx] != CTL_UA_NONE) {
11832			scsi_sense_data_type sense_format;
11833
11834			if (lun != NULL)
11835				sense_format = (lun->flags &
11836				    CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11837				    SSD_TYPE_FIXED;
11838			else
11839				sense_format = SSD_TYPE_FIXED;
11840
11841			ua_type = ctl_build_ua(&lun->pending_ua[initidx],
11842			    &ctsio->sense_data, sense_format);
11843			if (ua_type != CTL_UA_NONE) {
11844				ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11845				ctsio->io_hdr.status = CTL_SCSI_ERROR |
11846						       CTL_AUTOSENSE;
11847				ctsio->sense_len = SSD_FULL_SIZE;
11848				mtx_unlock(&lun->lun_lock);
11849				ctl_done((union ctl_io *)ctsio);
11850				return (retval);
11851			}
11852		}
11853	}
11854
11855
11856	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11857		mtx_unlock(&lun->lun_lock);
11858		ctl_done((union ctl_io *)ctsio);
11859		return (retval);
11860	}
11861
11862	/*
11863	 * XXX CHD this is where we want to send IO to other side if
11864	 * this LUN is secondary on this SC. We will need to make a copy
11865	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11866	 * the copy we send as FROM_OTHER.
11867	 * We also need to stuff the address of the original IO so we can
11868	 * find it easily. Something similar will need be done on the other
11869	 * side so when we are done we can find the copy.
11870	 */
11871	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11872		union ctl_ha_msg msg_info;
11873		int isc_retval;
11874
11875		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11876
11877		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11878		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11879#if 0
11880		printf("1. ctsio %p\n", ctsio);
11881#endif
11882		msg_info.hdr.serializing_sc = NULL;
11883		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11884		msg_info.scsi.tag_num = ctsio->tag_num;
11885		msg_info.scsi.tag_type = ctsio->tag_type;
11886		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11887
11888		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11889
11890		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11891		    (void *)&msg_info, sizeof(msg_info), 0)) >
11892		    CTL_HA_STATUS_SUCCESS) {
11893			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11894			       isc_retval);
11895			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11896		} else {
11897#if 0
11898			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11899#endif
11900		}
11901
11902		/*
11903		 * XXX KDM this I/O is off the incoming queue, but hasn't
11904		 * been inserted on any other queue.  We may need to come
11905		 * up with a holding queue while we wait for serialization
11906		 * so that we have an idea of what we're waiting for from
11907		 * the other side.
11908		 */
11909		mtx_unlock(&lun->lun_lock);
11910		return (retval);
11911	}
11912
11913	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11914			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11915			      ctl_ooaq, ooa_links))) {
11916	case CTL_ACTION_BLOCK:
11917		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11918		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11919				  blocked_links);
11920		mtx_unlock(&lun->lun_lock);
11921		return (retval);
11922	case CTL_ACTION_PASS:
11923	case CTL_ACTION_SKIP:
11924		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11925		mtx_unlock(&lun->lun_lock);
11926		ctl_enqueue_rtr((union ctl_io *)ctsio);
11927		break;
11928	case CTL_ACTION_OVERLAP:
11929		mtx_unlock(&lun->lun_lock);
11930		ctl_set_overlapped_cmd(ctsio);
11931		ctl_done((union ctl_io *)ctsio);
11932		break;
11933	case CTL_ACTION_OVERLAP_TAG:
11934		mtx_unlock(&lun->lun_lock);
11935		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11936		ctl_done((union ctl_io *)ctsio);
11937		break;
11938	case CTL_ACTION_ERROR:
11939	default:
11940		mtx_unlock(&lun->lun_lock);
11941		ctl_set_internal_failure(ctsio,
11942					 /*sks_valid*/ 0,
11943					 /*retry_count*/ 0);
11944		ctl_done((union ctl_io *)ctsio);
11945		break;
11946	}
11947	return (retval);
11948}
11949
11950const struct ctl_cmd_entry *
11951ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11952{
11953	const struct ctl_cmd_entry *entry;
11954	int service_action;
11955
11956	entry = &ctl_cmd_table[ctsio->cdb[0]];
11957	if (sa)
11958		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11959	if (entry->flags & CTL_CMD_FLAG_SA5) {
11960		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11961		entry = &((const struct ctl_cmd_entry *)
11962		    entry->execute)[service_action];
11963	}
11964	return (entry);
11965}
11966
11967const struct ctl_cmd_entry *
11968ctl_validate_command(struct ctl_scsiio *ctsio)
11969{
11970	const struct ctl_cmd_entry *entry;
11971	int i, sa;
11972	uint8_t diff;
11973
11974	entry = ctl_get_cmd_entry(ctsio, &sa);
11975	if (entry->execute == NULL) {
11976		if (sa)
11977			ctl_set_invalid_field(ctsio,
11978					      /*sks_valid*/ 1,
11979					      /*command*/ 1,
11980					      /*field*/ 1,
11981					      /*bit_valid*/ 1,
11982					      /*bit*/ 4);
11983		else
11984			ctl_set_invalid_opcode(ctsio);
11985		ctl_done((union ctl_io *)ctsio);
11986		return (NULL);
11987	}
11988	KASSERT(entry->length > 0,
11989	    ("Not defined length for command 0x%02x/0x%02x",
11990	     ctsio->cdb[0], ctsio->cdb[1]));
11991	for (i = 1; i < entry->length; i++) {
11992		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11993		if (diff == 0)
11994			continue;
11995		ctl_set_invalid_field(ctsio,
11996				      /*sks_valid*/ 1,
11997				      /*command*/ 1,
11998				      /*field*/ i,
11999				      /*bit_valid*/ 1,
12000				      /*bit*/ fls(diff) - 1);
12001		ctl_done((union ctl_io *)ctsio);
12002		return (NULL);
12003	}
12004	return (entry);
12005}
12006
12007static int
12008ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
12009{
12010
12011	switch (lun_type) {
12012	case T_PROCESSOR:
12013		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
12014		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
12015			return (0);
12016		break;
12017	case T_DIRECT:
12018		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
12019		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
12020			return (0);
12021		break;
12022	default:
12023		return (0);
12024	}
12025	return (1);
12026}
12027
12028static int
12029ctl_scsiio(struct ctl_scsiio *ctsio)
12030{
12031	int retval;
12032	const struct ctl_cmd_entry *entry;
12033
12034	retval = CTL_RETVAL_COMPLETE;
12035
12036	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
12037
12038	entry = ctl_get_cmd_entry(ctsio, NULL);
12039
12040	/*
12041	 * If this I/O has been aborted, just send it straight to
12042	 * ctl_done() without executing it.
12043	 */
12044	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
12045		ctl_done((union ctl_io *)ctsio);
12046		goto bailout;
12047	}
12048
12049	/*
12050	 * All the checks should have been handled by ctl_scsiio_precheck().
12051	 * We should be clear now to just execute the I/O.
12052	 */
12053	retval = entry->execute(ctsio);
12054
12055bailout:
12056	return (retval);
12057}
12058
12059/*
12060 * Since we only implement one target right now, a bus reset simply resets
12061 * our single target.
12062 */
12063static int
12064ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
12065{
12066	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
12067}
12068
12069static int
12070ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
12071		 ctl_ua_type ua_type)
12072{
12073	struct ctl_lun *lun;
12074	int retval;
12075
12076	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12077		union ctl_ha_msg msg_info;
12078
12079		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
12080		msg_info.hdr.nexus = io->io_hdr.nexus;
12081		if (ua_type==CTL_UA_TARG_RESET)
12082			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
12083		else
12084			msg_info.task.task_action = CTL_TASK_BUS_RESET;
12085		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12086		msg_info.hdr.original_sc = NULL;
12087		msg_info.hdr.serializing_sc = NULL;
12088		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12089		    (void *)&msg_info, sizeof(msg_info), 0)) {
12090		}
12091	}
12092	retval = 0;
12093
12094	mtx_lock(&ctl_softc->ctl_lock);
12095	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
12096		retval += ctl_lun_reset(lun, io, ua_type);
12097	mtx_unlock(&ctl_softc->ctl_lock);
12098
12099	return (retval);
12100}
12101
12102/*
12103 * The LUN should always be set.  The I/O is optional, and is used to
12104 * distinguish between I/Os sent by this initiator, and by other
12105 * initiators.  We set unit attention for initiators other than this one.
12106 * SAM-3 is vague on this point.  It does say that a unit attention should
12107 * be established for other initiators when a LUN is reset (see section
12108 * 5.7.3), but it doesn't specifically say that the unit attention should
12109 * be established for this particular initiator when a LUN is reset.  Here
12110 * is the relevant text, from SAM-3 rev 8:
12111 *
12112 * 5.7.2 When a SCSI initiator port aborts its own tasks
12113 *
12114 * When a SCSI initiator port causes its own task(s) to be aborted, no
12115 * notification that the task(s) have been aborted shall be returned to
12116 * the SCSI initiator port other than the completion response for the
12117 * command or task management function action that caused the task(s) to
12118 * be aborted and notification(s) associated with related effects of the
12119 * action (e.g., a reset unit attention condition).
12120 *
12121 * XXX KDM for now, we're setting unit attention for all initiators.
12122 */
12123static int
12124ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
12125{
12126	union ctl_io *xio;
12127#if 0
12128	uint32_t initindex;
12129#endif
12130	int i;
12131
12132	mtx_lock(&lun->lun_lock);
12133	/*
12134	 * Run through the OOA queue and abort each I/O.
12135	 */
12136#if 0
12137	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12138#endif
12139	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12140	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12141		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
12142	}
12143
12144	/*
12145	 * This version sets unit attention for every
12146	 */
12147#if 0
12148	initindex = ctl_get_initindex(&io->io_hdr.nexus);
12149	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
12150		if (initindex == i)
12151			continue;
12152		lun->pending_ua[i] |= ua_type;
12153	}
12154#endif
12155
12156	/*
12157	 * A reset (any kind, really) clears reservations established with
12158	 * RESERVE/RELEASE.  It does not clear reservations established
12159	 * with PERSISTENT RESERVE OUT, but we don't support that at the
12160	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
12161	 * reservations made with the RESERVE/RELEASE commands, because
12162	 * those commands are obsolete in SPC-3.
12163	 */
12164	lun->flags &= ~CTL_LUN_RESERVED;
12165
12166	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
12167#ifdef CTL_WITH_CA
12168		ctl_clear_mask(lun->have_ca, i);
12169#endif
12170		lun->pending_ua[i] |= ua_type;
12171	}
12172	mtx_unlock(&lun->lun_lock);
12173
12174	return (0);
12175}
12176
12177static void
12178ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
12179    int other_sc)
12180{
12181	union ctl_io *xio;
12182
12183	mtx_assert(&lun->lun_lock, MA_OWNED);
12184
12185	/*
12186	 * Run through the OOA queue and attempt to find the given I/O.
12187	 * The target port, initiator ID, tag type and tag number have to
12188	 * match the values that we got from the initiator.  If we have an
12189	 * untagged command to abort, simply abort the first untagged command
12190	 * we come to.  We only allow one untagged command at a time of course.
12191	 */
12192	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12193	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12194
12195		if ((targ_port == UINT32_MAX ||
12196		     targ_port == xio->io_hdr.nexus.targ_port) &&
12197		    (init_id == UINT32_MAX ||
12198		     init_id == xio->io_hdr.nexus.initid.id)) {
12199			if (targ_port != xio->io_hdr.nexus.targ_port ||
12200			    init_id != xio->io_hdr.nexus.initid.id)
12201				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12202			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12203			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12204				union ctl_ha_msg msg_info;
12205
12206				msg_info.hdr.nexus = xio->io_hdr.nexus;
12207				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12208				msg_info.task.tag_num = xio->scsiio.tag_num;
12209				msg_info.task.tag_type = xio->scsiio.tag_type;
12210				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12211				msg_info.hdr.original_sc = NULL;
12212				msg_info.hdr.serializing_sc = NULL;
12213				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12214				    (void *)&msg_info, sizeof(msg_info), 0);
12215			}
12216		}
12217	}
12218}
12219
12220static int
12221ctl_abort_task_set(union ctl_io *io)
12222{
12223	struct ctl_softc *softc = control_softc;
12224	struct ctl_lun *lun;
12225	uint32_t targ_lun;
12226
12227	/*
12228	 * Look up the LUN.
12229	 */
12230	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12231	mtx_lock(&softc->ctl_lock);
12232	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
12233		lun = softc->ctl_luns[targ_lun];
12234	else {
12235		mtx_unlock(&softc->ctl_lock);
12236		return (1);
12237	}
12238
12239	mtx_lock(&lun->lun_lock);
12240	mtx_unlock(&softc->ctl_lock);
12241	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12242		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12243		    io->io_hdr.nexus.initid.id,
12244		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12245	} else { /* CTL_TASK_CLEAR_TASK_SET */
12246		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12247		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12248	}
12249	mtx_unlock(&lun->lun_lock);
12250	return (0);
12251}
12252
12253static int
12254ctl_i_t_nexus_reset(union ctl_io *io)
12255{
12256	struct ctl_softc *softc = control_softc;
12257	struct ctl_lun *lun;
12258	uint32_t initindex, residx;
12259
12260	initindex = ctl_get_initindex(&io->io_hdr.nexus);
12261	residx = ctl_get_resindex(&io->io_hdr.nexus);
12262	mtx_lock(&softc->ctl_lock);
12263	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12264		mtx_lock(&lun->lun_lock);
12265		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12266		    io->io_hdr.nexus.initid.id,
12267		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12268#ifdef CTL_WITH_CA
12269		ctl_clear_mask(lun->have_ca, initindex);
12270#endif
12271		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
12272			lun->flags &= ~CTL_LUN_RESERVED;
12273		lun->pending_ua[initindex] |= CTL_UA_I_T_NEXUS_LOSS;
12274		mtx_unlock(&lun->lun_lock);
12275	}
12276	mtx_unlock(&softc->ctl_lock);
12277	return (0);
12278}
12279
12280static int
12281ctl_abort_task(union ctl_io *io)
12282{
12283	union ctl_io *xio;
12284	struct ctl_lun *lun;
12285	struct ctl_softc *ctl_softc;
12286#if 0
12287	struct sbuf sb;
12288	char printbuf[128];
12289#endif
12290	int found;
12291	uint32_t targ_lun;
12292
12293	ctl_softc = control_softc;
12294	found = 0;
12295
12296	/*
12297	 * Look up the LUN.
12298	 */
12299	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12300	mtx_lock(&ctl_softc->ctl_lock);
12301	if ((targ_lun < CTL_MAX_LUNS)
12302	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12303		lun = ctl_softc->ctl_luns[targ_lun];
12304	else {
12305		mtx_unlock(&ctl_softc->ctl_lock);
12306		return (1);
12307	}
12308
12309#if 0
12310	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12311	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12312#endif
12313
12314	mtx_lock(&lun->lun_lock);
12315	mtx_unlock(&ctl_softc->ctl_lock);
12316	/*
12317	 * Run through the OOA queue and attempt to find the given I/O.
12318	 * The target port, initiator ID, tag type and tag number have to
12319	 * match the values that we got from the initiator.  If we have an
12320	 * untagged command to abort, simply abort the first untagged command
12321	 * we come to.  We only allow one untagged command at a time of course.
12322	 */
12323#if 0
12324	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12325#endif
12326	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12327	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12328#if 0
12329		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12330
12331		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12332			    lun->lun, xio->scsiio.tag_num,
12333			    xio->scsiio.tag_type,
12334			    (xio->io_hdr.blocked_links.tqe_prev
12335			    == NULL) ? "" : " BLOCKED",
12336			    (xio->io_hdr.flags &
12337			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12338			    (xio->io_hdr.flags &
12339			    CTL_FLAG_ABORT) ? " ABORT" : "",
12340			    (xio->io_hdr.flags &
12341			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12342		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12343		sbuf_finish(&sb);
12344		printf("%s\n", sbuf_data(&sb));
12345#endif
12346
12347		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12348		 && (xio->io_hdr.nexus.initid.id ==
12349		     io->io_hdr.nexus.initid.id)) {
12350			/*
12351			 * If the abort says that the task is untagged, the
12352			 * task in the queue must be untagged.  Otherwise,
12353			 * we just check to see whether the tag numbers
12354			 * match.  This is because the QLogic firmware
12355			 * doesn't pass back the tag type in an abort
12356			 * request.
12357			 */
12358#if 0
12359			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12360			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12361			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12362#endif
12363			/*
12364			 * XXX KDM we've got problems with FC, because it
12365			 * doesn't send down a tag type with aborts.  So we
12366			 * can only really go by the tag number...
12367			 * This may cause problems with parallel SCSI.
12368			 * Need to figure that out!!
12369			 */
12370			if (xio->scsiio.tag_num == io->taskio.tag_num) {
12371				xio->io_hdr.flags |= CTL_FLAG_ABORT;
12372				found = 1;
12373				if ((io->io_hdr.flags &
12374				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
12375				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12376					union ctl_ha_msg msg_info;
12377
12378					io->io_hdr.flags |=
12379					                CTL_FLAG_SENT_2OTHER_SC;
12380					msg_info.hdr.nexus = io->io_hdr.nexus;
12381					msg_info.task.task_action =
12382						CTL_TASK_ABORT_TASK;
12383					msg_info.task.tag_num =
12384						io->taskio.tag_num;
12385					msg_info.task.tag_type =
12386						io->taskio.tag_type;
12387					msg_info.hdr.msg_type =
12388						CTL_MSG_MANAGE_TASKS;
12389					msg_info.hdr.original_sc = NULL;
12390					msg_info.hdr.serializing_sc = NULL;
12391#if 0
12392					printf("Sent Abort to other side\n");
12393#endif
12394					if (CTL_HA_STATUS_SUCCESS !=
12395					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12396		    				(void *)&msg_info,
12397						sizeof(msg_info), 0)) {
12398					}
12399				}
12400#if 0
12401				printf("ctl_abort_task: found I/O to abort\n");
12402#endif
12403				break;
12404			}
12405		}
12406	}
12407	mtx_unlock(&lun->lun_lock);
12408
12409	if (found == 0) {
12410		/*
12411		 * This isn't really an error.  It's entirely possible for
12412		 * the abort and command completion to cross on the wire.
12413		 * This is more of an informative/diagnostic error.
12414		 */
12415#if 0
12416		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12417		       "%d:%d:%d:%d tag %d type %d\n",
12418		       io->io_hdr.nexus.initid.id,
12419		       io->io_hdr.nexus.targ_port,
12420		       io->io_hdr.nexus.targ_target.id,
12421		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12422		       io->taskio.tag_type);
12423#endif
12424	}
12425	return (0);
12426}
12427
12428static void
12429ctl_run_task(union ctl_io *io)
12430{
12431	struct ctl_softc *ctl_softc = control_softc;
12432	int retval = 1;
12433	const char *task_desc;
12434
12435	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12436
12437	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12438	    ("ctl_run_task: Unextected io_type %d\n",
12439	     io->io_hdr.io_type));
12440
12441	task_desc = ctl_scsi_task_string(&io->taskio);
12442	if (task_desc != NULL) {
12443#ifdef NEEDTOPORT
12444		csevent_log(CSC_CTL | CSC_SHELF_SW |
12445			    CTL_TASK_REPORT,
12446			    csevent_LogType_Trace,
12447			    csevent_Severity_Information,
12448			    csevent_AlertLevel_Green,
12449			    csevent_FRU_Firmware,
12450			    csevent_FRU_Unknown,
12451			    "CTL: received task: %s",task_desc);
12452#endif
12453	} else {
12454#ifdef NEEDTOPORT
12455		csevent_log(CSC_CTL | CSC_SHELF_SW |
12456			    CTL_TASK_REPORT,
12457			    csevent_LogType_Trace,
12458			    csevent_Severity_Information,
12459			    csevent_AlertLevel_Green,
12460			    csevent_FRU_Firmware,
12461			    csevent_FRU_Unknown,
12462			    "CTL: received unknown task "
12463			    "type: %d (%#x)",
12464			    io->taskio.task_action,
12465			    io->taskio.task_action);
12466#endif
12467	}
12468	switch (io->taskio.task_action) {
12469	case CTL_TASK_ABORT_TASK:
12470		retval = ctl_abort_task(io);
12471		break;
12472	case CTL_TASK_ABORT_TASK_SET:
12473	case CTL_TASK_CLEAR_TASK_SET:
12474		retval = ctl_abort_task_set(io);
12475		break;
12476	case CTL_TASK_CLEAR_ACA:
12477		break;
12478	case CTL_TASK_I_T_NEXUS_RESET:
12479		retval = ctl_i_t_nexus_reset(io);
12480		break;
12481	case CTL_TASK_LUN_RESET: {
12482		struct ctl_lun *lun;
12483		uint32_t targ_lun;
12484
12485		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12486		mtx_lock(&ctl_softc->ctl_lock);
12487		if ((targ_lun < CTL_MAX_LUNS)
12488		 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12489			lun = ctl_softc->ctl_luns[targ_lun];
12490		else {
12491			mtx_unlock(&ctl_softc->ctl_lock);
12492			retval = 1;
12493			break;
12494		}
12495
12496		if (!(io->io_hdr.flags &
12497		    CTL_FLAG_FROM_OTHER_SC)) {
12498			union ctl_ha_msg msg_info;
12499
12500			io->io_hdr.flags |=
12501				CTL_FLAG_SENT_2OTHER_SC;
12502			msg_info.hdr.msg_type =
12503				CTL_MSG_MANAGE_TASKS;
12504			msg_info.hdr.nexus = io->io_hdr.nexus;
12505			msg_info.task.task_action =
12506				CTL_TASK_LUN_RESET;
12507			msg_info.hdr.original_sc = NULL;
12508			msg_info.hdr.serializing_sc = NULL;
12509			if (CTL_HA_STATUS_SUCCESS !=
12510			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12511			    (void *)&msg_info,
12512			    sizeof(msg_info), 0)) {
12513			}
12514		}
12515
12516		retval = ctl_lun_reset(lun, io,
12517				       CTL_UA_LUN_RESET);
12518		mtx_unlock(&ctl_softc->ctl_lock);
12519		break;
12520	}
12521	case CTL_TASK_TARGET_RESET:
12522		retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12523		break;
12524	case CTL_TASK_BUS_RESET:
12525		retval = ctl_bus_reset(ctl_softc, io);
12526		break;
12527	case CTL_TASK_PORT_LOGIN:
12528		break;
12529	case CTL_TASK_PORT_LOGOUT:
12530		break;
12531	default:
12532		printf("ctl_run_task: got unknown task management event %d\n",
12533		       io->taskio.task_action);
12534		break;
12535	}
12536	if (retval == 0)
12537		io->io_hdr.status = CTL_SUCCESS;
12538	else
12539		io->io_hdr.status = CTL_ERROR;
12540	ctl_done(io);
12541}
12542
12543/*
12544 * For HA operation.  Handle commands that come in from the other
12545 * controller.
12546 */
12547static void
12548ctl_handle_isc(union ctl_io *io)
12549{
12550	int free_io;
12551	struct ctl_lun *lun;
12552	struct ctl_softc *ctl_softc;
12553	uint32_t targ_lun;
12554
12555	ctl_softc = control_softc;
12556
12557	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12558	lun = ctl_softc->ctl_luns[targ_lun];
12559
12560	switch (io->io_hdr.msg_type) {
12561	case CTL_MSG_SERIALIZE:
12562		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12563		break;
12564	case CTL_MSG_R2R: {
12565		const struct ctl_cmd_entry *entry;
12566
12567		/*
12568		 * This is only used in SER_ONLY mode.
12569		 */
12570		free_io = 0;
12571		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12572		mtx_lock(&lun->lun_lock);
12573		if (ctl_scsiio_lun_check(ctl_softc, lun,
12574		    entry, (struct ctl_scsiio *)io) != 0) {
12575			mtx_unlock(&lun->lun_lock);
12576			ctl_done(io);
12577			break;
12578		}
12579		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12580		mtx_unlock(&lun->lun_lock);
12581		ctl_enqueue_rtr(io);
12582		break;
12583	}
12584	case CTL_MSG_FINISH_IO:
12585		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12586			free_io = 0;
12587			ctl_done(io);
12588		} else {
12589			free_io = 1;
12590			mtx_lock(&lun->lun_lock);
12591			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12592				     ooa_links);
12593			ctl_check_blocked(lun);
12594			mtx_unlock(&lun->lun_lock);
12595		}
12596		break;
12597	case CTL_MSG_PERS_ACTION:
12598		ctl_hndl_per_res_out_on_other_sc(
12599			(union ctl_ha_msg *)&io->presio.pr_msg);
12600		free_io = 1;
12601		break;
12602	case CTL_MSG_BAD_JUJU:
12603		free_io = 0;
12604		ctl_done(io);
12605		break;
12606	case CTL_MSG_DATAMOVE:
12607		/* Only used in XFER mode */
12608		free_io = 0;
12609		ctl_datamove_remote(io);
12610		break;
12611	case CTL_MSG_DATAMOVE_DONE:
12612		/* Only used in XFER mode */
12613		free_io = 0;
12614		io->scsiio.be_move_done(io);
12615		break;
12616	default:
12617		free_io = 1;
12618		printf("%s: Invalid message type %d\n",
12619		       __func__, io->io_hdr.msg_type);
12620		break;
12621	}
12622	if (free_io)
12623		ctl_free_io(io);
12624
12625}
12626
12627
12628/*
12629 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12630 * there is no match.
12631 */
12632static ctl_lun_error_pattern
12633ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12634{
12635	const struct ctl_cmd_entry *entry;
12636	ctl_lun_error_pattern filtered_pattern, pattern;
12637
12638	pattern = desc->error_pattern;
12639
12640	/*
12641	 * XXX KDM we need more data passed into this function to match a
12642	 * custom pattern, and we actually need to implement custom pattern
12643	 * matching.
12644	 */
12645	if (pattern & CTL_LUN_PAT_CMD)
12646		return (CTL_LUN_PAT_CMD);
12647
12648	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12649		return (CTL_LUN_PAT_ANY);
12650
12651	entry = ctl_get_cmd_entry(ctsio, NULL);
12652
12653	filtered_pattern = entry->pattern & pattern;
12654
12655	/*
12656	 * If the user requested specific flags in the pattern (e.g.
12657	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12658	 * flags.
12659	 *
12660	 * If the user did not specify any flags, it doesn't matter whether
12661	 * or not the command supports the flags.
12662	 */
12663	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12664	     (pattern & ~CTL_LUN_PAT_MASK))
12665		return (CTL_LUN_PAT_NONE);
12666
12667	/*
12668	 * If the user asked for a range check, see if the requested LBA
12669	 * range overlaps with this command's LBA range.
12670	 */
12671	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12672		uint64_t lba1;
12673		uint64_t len1;
12674		ctl_action action;
12675		int retval;
12676
12677		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12678		if (retval != 0)
12679			return (CTL_LUN_PAT_NONE);
12680
12681		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12682					      desc->lba_range.len);
12683		/*
12684		 * A "pass" means that the LBA ranges don't overlap, so
12685		 * this doesn't match the user's range criteria.
12686		 */
12687		if (action == CTL_ACTION_PASS)
12688			return (CTL_LUN_PAT_NONE);
12689	}
12690
12691	return (filtered_pattern);
12692}
12693
12694static void
12695ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12696{
12697	struct ctl_error_desc *desc, *desc2;
12698
12699	mtx_assert(&lun->lun_lock, MA_OWNED);
12700
12701	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12702		ctl_lun_error_pattern pattern;
12703		/*
12704		 * Check to see whether this particular command matches
12705		 * the pattern in the descriptor.
12706		 */
12707		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12708		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12709			continue;
12710
12711		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12712		case CTL_LUN_INJ_ABORTED:
12713			ctl_set_aborted(&io->scsiio);
12714			break;
12715		case CTL_LUN_INJ_MEDIUM_ERR:
12716			ctl_set_medium_error(&io->scsiio);
12717			break;
12718		case CTL_LUN_INJ_UA:
12719			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12720			 * OCCURRED */
12721			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12722			break;
12723		case CTL_LUN_INJ_CUSTOM:
12724			/*
12725			 * We're assuming the user knows what he is doing.
12726			 * Just copy the sense information without doing
12727			 * checks.
12728			 */
12729			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12730			      ctl_min(sizeof(desc->custom_sense),
12731				      sizeof(io->scsiio.sense_data)));
12732			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12733			io->scsiio.sense_len = SSD_FULL_SIZE;
12734			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12735			break;
12736		case CTL_LUN_INJ_NONE:
12737		default:
12738			/*
12739			 * If this is an error injection type we don't know
12740			 * about, clear the continuous flag (if it is set)
12741			 * so it will get deleted below.
12742			 */
12743			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12744			break;
12745		}
12746		/*
12747		 * By default, each error injection action is a one-shot
12748		 */
12749		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12750			continue;
12751
12752		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12753
12754		free(desc, M_CTL);
12755	}
12756}
12757
12758#ifdef CTL_IO_DELAY
12759static void
12760ctl_datamove_timer_wakeup(void *arg)
12761{
12762	union ctl_io *io;
12763
12764	io = (union ctl_io *)arg;
12765
12766	ctl_datamove(io);
12767}
12768#endif /* CTL_IO_DELAY */
12769
12770void
12771ctl_datamove(union ctl_io *io)
12772{
12773	void (*fe_datamove)(union ctl_io *io);
12774
12775	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12776
12777	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12778
12779#ifdef CTL_TIME_IO
12780	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12781		char str[256];
12782		char path_str[64];
12783		struct sbuf sb;
12784
12785		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12786		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12787
12788		sbuf_cat(&sb, path_str);
12789		switch (io->io_hdr.io_type) {
12790		case CTL_IO_SCSI:
12791			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12792			sbuf_printf(&sb, "\n");
12793			sbuf_cat(&sb, path_str);
12794			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12795				    io->scsiio.tag_num, io->scsiio.tag_type);
12796			break;
12797		case CTL_IO_TASK:
12798			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12799				    "Tag Type: %d\n", io->taskio.task_action,
12800				    io->taskio.tag_num, io->taskio.tag_type);
12801			break;
12802		default:
12803			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12804			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12805			break;
12806		}
12807		sbuf_cat(&sb, path_str);
12808		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12809			    (intmax_t)time_uptime - io->io_hdr.start_time);
12810		sbuf_finish(&sb);
12811		printf("%s", sbuf_data(&sb));
12812	}
12813#endif /* CTL_TIME_IO */
12814
12815#ifdef CTL_IO_DELAY
12816	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12817		struct ctl_lun *lun;
12818
12819		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12820
12821		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12822	} else {
12823		struct ctl_lun *lun;
12824
12825		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12826		if ((lun != NULL)
12827		 && (lun->delay_info.datamove_delay > 0)) {
12828			struct callout *callout;
12829
12830			callout = (struct callout *)&io->io_hdr.timer_bytes;
12831			callout_init(callout, /*mpsafe*/ 1);
12832			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12833			callout_reset(callout,
12834				      lun->delay_info.datamove_delay * hz,
12835				      ctl_datamove_timer_wakeup, io);
12836			if (lun->delay_info.datamove_type ==
12837			    CTL_DELAY_TYPE_ONESHOT)
12838				lun->delay_info.datamove_delay = 0;
12839			return;
12840		}
12841	}
12842#endif
12843
12844	/*
12845	 * This command has been aborted.  Set the port status, so we fail
12846	 * the data move.
12847	 */
12848	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12849		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12850		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12851		       io->io_hdr.nexus.targ_port,
12852		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12853		       io->io_hdr.nexus.targ_lun);
12854		io->io_hdr.port_status = 31337;
12855		/*
12856		 * Note that the backend, in this case, will get the
12857		 * callback in its context.  In other cases it may get
12858		 * called in the frontend's interrupt thread context.
12859		 */
12860		io->scsiio.be_move_done(io);
12861		return;
12862	}
12863
12864	/* Don't confuse frontend with zero length data move. */
12865	if (io->scsiio.kern_data_len == 0) {
12866		io->scsiio.be_move_done(io);
12867		return;
12868	}
12869
12870	/*
12871	 * If we're in XFER mode and this I/O is from the other shelf
12872	 * controller, we need to send the DMA to the other side to
12873	 * actually transfer the data to/from the host.  In serialize only
12874	 * mode the transfer happens below CTL and ctl_datamove() is only
12875	 * called on the machine that originally received the I/O.
12876	 */
12877	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12878	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12879		union ctl_ha_msg msg;
12880		uint32_t sg_entries_sent;
12881		int do_sg_copy;
12882		int i;
12883
12884		memset(&msg, 0, sizeof(msg));
12885		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12886		msg.hdr.original_sc = io->io_hdr.original_sc;
12887		msg.hdr.serializing_sc = io;
12888		msg.hdr.nexus = io->io_hdr.nexus;
12889		msg.dt.flags = io->io_hdr.flags;
12890		/*
12891		 * We convert everything into a S/G list here.  We can't
12892		 * pass by reference, only by value between controllers.
12893		 * So we can't pass a pointer to the S/G list, only as many
12894		 * S/G entries as we can fit in here.  If it's possible for
12895		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12896		 * then we need to break this up into multiple transfers.
12897		 */
12898		if (io->scsiio.kern_sg_entries == 0) {
12899			msg.dt.kern_sg_entries = 1;
12900			/*
12901			 * If this is in cached memory, flush the cache
12902			 * before we send the DMA request to the other
12903			 * controller.  We want to do this in either the
12904			 * read or the write case.  The read case is
12905			 * straightforward.  In the write case, we want to
12906			 * make sure nothing is in the local cache that
12907			 * could overwrite the DMAed data.
12908			 */
12909			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12910				/*
12911				 * XXX KDM use bus_dmamap_sync() here.
12912				 */
12913			}
12914
12915			/*
12916			 * Convert to a physical address if this is a
12917			 * virtual address.
12918			 */
12919			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12920				msg.dt.sg_list[0].addr =
12921					io->scsiio.kern_data_ptr;
12922			} else {
12923				/*
12924				 * XXX KDM use busdma here!
12925				 */
12926#if 0
12927				msg.dt.sg_list[0].addr = (void *)
12928					vtophys(io->scsiio.kern_data_ptr);
12929#endif
12930			}
12931
12932			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12933			do_sg_copy = 0;
12934		} else {
12935			struct ctl_sg_entry *sgl;
12936
12937			do_sg_copy = 1;
12938			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12939			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12940			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12941				/*
12942				 * XXX KDM use bus_dmamap_sync() here.
12943				 */
12944			}
12945		}
12946
12947		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12948		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12949		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12950		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12951		msg.dt.sg_sequence = 0;
12952
12953		/*
12954		 * Loop until we've sent all of the S/G entries.  On the
12955		 * other end, we'll recompose these S/G entries into one
12956		 * contiguous list before passing it to the
12957		 */
12958		for (sg_entries_sent = 0; sg_entries_sent <
12959		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12960			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12961				sizeof(msg.dt.sg_list[0])),
12962				msg.dt.kern_sg_entries - sg_entries_sent);
12963
12964			if (do_sg_copy != 0) {
12965				struct ctl_sg_entry *sgl;
12966				int j;
12967
12968				sgl = (struct ctl_sg_entry *)
12969					io->scsiio.kern_data_ptr;
12970				/*
12971				 * If this is in cached memory, flush the cache
12972				 * before we send the DMA request to the other
12973				 * controller.  We want to do this in either
12974				 * the * read or the write case.  The read
12975				 * case is straightforward.  In the write
12976				 * case, we want to make sure nothing is
12977				 * in the local cache that could overwrite
12978				 * the DMAed data.
12979				 */
12980
12981				for (i = sg_entries_sent, j = 0;
12982				     i < msg.dt.cur_sg_entries; i++, j++) {
12983					if ((io->io_hdr.flags &
12984					     CTL_FLAG_NO_DATASYNC) == 0) {
12985						/*
12986						 * XXX KDM use bus_dmamap_sync()
12987						 */
12988					}
12989					if ((io->io_hdr.flags &
12990					     CTL_FLAG_BUS_ADDR) == 0) {
12991						/*
12992						 * XXX KDM use busdma.
12993						 */
12994#if 0
12995						msg.dt.sg_list[j].addr =(void *)
12996						       vtophys(sgl[i].addr);
12997#endif
12998					} else {
12999						msg.dt.sg_list[j].addr =
13000							sgl[i].addr;
13001					}
13002					msg.dt.sg_list[j].len = sgl[i].len;
13003				}
13004			}
13005
13006			sg_entries_sent += msg.dt.cur_sg_entries;
13007			if (sg_entries_sent >= msg.dt.kern_sg_entries)
13008				msg.dt.sg_last = 1;
13009			else
13010				msg.dt.sg_last = 0;
13011
13012			/*
13013			 * XXX KDM drop and reacquire the lock here?
13014			 */
13015			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13016			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13017				/*
13018				 * XXX do something here.
13019				 */
13020			}
13021
13022			msg.dt.sent_sg_entries = sg_entries_sent;
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*/ 0);
13027
13028	} else {
13029
13030		/*
13031		 * Lookup the fe_datamove() function for this particular
13032		 * front end.
13033		 */
13034		fe_datamove =
13035		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13036
13037		fe_datamove(io);
13038	}
13039}
13040
13041static void
13042ctl_send_datamove_done(union ctl_io *io, int have_lock)
13043{
13044	union ctl_ha_msg msg;
13045	int isc_status;
13046
13047	memset(&msg, 0, sizeof(msg));
13048
13049	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
13050	msg.hdr.original_sc = io;
13051	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13052	msg.hdr.nexus = io->io_hdr.nexus;
13053	msg.hdr.status = io->io_hdr.status;
13054	msg.scsi.tag_num = io->scsiio.tag_num;
13055	msg.scsi.tag_type = io->scsiio.tag_type;
13056	msg.scsi.scsi_status = io->scsiio.scsi_status;
13057	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13058	       sizeof(io->scsiio.sense_data));
13059	msg.scsi.sense_len = io->scsiio.sense_len;
13060	msg.scsi.sense_residual = io->scsiio.sense_residual;
13061	msg.scsi.fetd_status = io->io_hdr.port_status;
13062	msg.scsi.residual = io->scsiio.residual;
13063	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13064
13065	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13066		ctl_failover_io(io, /*have_lock*/ have_lock);
13067		return;
13068	}
13069
13070	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
13071	if (isc_status > CTL_HA_STATUS_SUCCESS) {
13072		/* XXX do something if this fails */
13073	}
13074
13075}
13076
13077/*
13078 * The DMA to the remote side is done, now we need to tell the other side
13079 * we're done so it can continue with its data movement.
13080 */
13081static void
13082ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
13083{
13084	union ctl_io *io;
13085
13086	io = rq->context;
13087
13088	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13089		printf("%s: ISC DMA write failed with error %d", __func__,
13090		       rq->ret);
13091		ctl_set_internal_failure(&io->scsiio,
13092					 /*sks_valid*/ 1,
13093					 /*retry_count*/ rq->ret);
13094	}
13095
13096	ctl_dt_req_free(rq);
13097
13098	/*
13099	 * In this case, we had to malloc the memory locally.  Free it.
13100	 */
13101	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13102		int i;
13103		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13104			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13105	}
13106	/*
13107	 * The data is in local and remote memory, so now we need to send
13108	 * status (good or back) back to the other side.
13109	 */
13110	ctl_send_datamove_done(io, /*have_lock*/ 0);
13111}
13112
13113/*
13114 * We've moved the data from the host/controller into local memory.  Now we
13115 * need to push it over to the remote controller's memory.
13116 */
13117static int
13118ctl_datamove_remote_dm_write_cb(union ctl_io *io)
13119{
13120	int retval;
13121
13122	retval = 0;
13123
13124	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
13125					  ctl_datamove_remote_write_cb);
13126
13127	return (retval);
13128}
13129
13130static void
13131ctl_datamove_remote_write(union ctl_io *io)
13132{
13133	int retval;
13134	void (*fe_datamove)(union ctl_io *io);
13135
13136	/*
13137	 * - Get the data from the host/HBA into local memory.
13138	 * - DMA memory from the local controller to the remote controller.
13139	 * - Send status back to the remote controller.
13140	 */
13141
13142	retval = ctl_datamove_remote_sgl_setup(io);
13143	if (retval != 0)
13144		return;
13145
13146	/* Switch the pointer over so the FETD knows what to do */
13147	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13148
13149	/*
13150	 * Use a custom move done callback, since we need to send completion
13151	 * back to the other controller, not to the backend on this side.
13152	 */
13153	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
13154
13155	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13156
13157	fe_datamove(io);
13158
13159	return;
13160
13161}
13162
13163static int
13164ctl_datamove_remote_dm_read_cb(union ctl_io *io)
13165{
13166#if 0
13167	char str[256];
13168	char path_str[64];
13169	struct sbuf sb;
13170#endif
13171
13172	/*
13173	 * In this case, we had to malloc the memory locally.  Free it.
13174	 */
13175	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13176		int i;
13177		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13178			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13179	}
13180
13181#if 0
13182	scsi_path_string(io, path_str, sizeof(path_str));
13183	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13184	sbuf_cat(&sb, path_str);
13185	scsi_command_string(&io->scsiio, NULL, &sb);
13186	sbuf_printf(&sb, "\n");
13187	sbuf_cat(&sb, path_str);
13188	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13189		    io->scsiio.tag_num, io->scsiio.tag_type);
13190	sbuf_cat(&sb, path_str);
13191	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
13192		    io->io_hdr.flags, io->io_hdr.status);
13193	sbuf_finish(&sb);
13194	printk("%s", sbuf_data(&sb));
13195#endif
13196
13197
13198	/*
13199	 * The read is done, now we need to send status (good or bad) back
13200	 * to the other side.
13201	 */
13202	ctl_send_datamove_done(io, /*have_lock*/ 0);
13203
13204	return (0);
13205}
13206
13207static void
13208ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
13209{
13210	union ctl_io *io;
13211	void (*fe_datamove)(union ctl_io *io);
13212
13213	io = rq->context;
13214
13215	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13216		printf("%s: ISC DMA read failed with error %d", __func__,
13217		       rq->ret);
13218		ctl_set_internal_failure(&io->scsiio,
13219					 /*sks_valid*/ 1,
13220					 /*retry_count*/ rq->ret);
13221	}
13222
13223	ctl_dt_req_free(rq);
13224
13225	/* Switch the pointer over so the FETD knows what to do */
13226	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13227
13228	/*
13229	 * Use a custom move done callback, since we need to send completion
13230	 * back to the other controller, not to the backend on this side.
13231	 */
13232	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
13233
13234	/* XXX KDM add checks like the ones in ctl_datamove? */
13235
13236	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13237
13238	fe_datamove(io);
13239}
13240
13241static int
13242ctl_datamove_remote_sgl_setup(union ctl_io *io)
13243{
13244	struct ctl_sg_entry *local_sglist, *remote_sglist;
13245	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13246	struct ctl_softc *softc;
13247	int retval;
13248	int i;
13249
13250	retval = 0;
13251	softc = control_softc;
13252
13253	local_sglist = io->io_hdr.local_sglist;
13254	local_dma_sglist = io->io_hdr.local_dma_sglist;
13255	remote_sglist = io->io_hdr.remote_sglist;
13256	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13257
13258	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13259		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13260			local_sglist[i].len = remote_sglist[i].len;
13261
13262			/*
13263			 * XXX Detect the situation where the RS-level I/O
13264			 * redirector on the other side has already read the
13265			 * data off of the AOR RS on this side, and
13266			 * transferred it to remote (mirror) memory on the
13267			 * other side.  Since we already have the data in
13268			 * memory here, we just need to use it.
13269			 *
13270			 * XXX KDM this can probably be removed once we
13271			 * get the cache device code in and take the
13272			 * current AOR implementation out.
13273			 */
13274#ifdef NEEDTOPORT
13275			if ((remote_sglist[i].addr >=
13276			     (void *)vtophys(softc->mirr->addr))
13277			 && (remote_sglist[i].addr <
13278			     ((void *)vtophys(softc->mirr->addr) +
13279			     CacheMirrorOffset))) {
13280				local_sglist[i].addr = remote_sglist[i].addr -
13281					CacheMirrorOffset;
13282				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13283				     CTL_FLAG_DATA_IN)
13284					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13285			} else {
13286				local_sglist[i].addr = remote_sglist[i].addr +
13287					CacheMirrorOffset;
13288			}
13289#endif
13290#if 0
13291			printf("%s: local %p, remote %p, len %d\n",
13292			       __func__, local_sglist[i].addr,
13293			       remote_sglist[i].addr, local_sglist[i].len);
13294#endif
13295		}
13296	} else {
13297		uint32_t len_to_go;
13298
13299		/*
13300		 * In this case, we don't have automatically allocated
13301		 * memory for this I/O on this controller.  This typically
13302		 * happens with internal CTL I/O -- e.g. inquiry, mode
13303		 * sense, etc.  Anything coming from RAIDCore will have
13304		 * a mirror area available.
13305		 */
13306		len_to_go = io->scsiio.kern_data_len;
13307
13308		/*
13309		 * Clear the no datasync flag, we have to use malloced
13310		 * buffers.
13311		 */
13312		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13313
13314		/*
13315		 * The difficult thing here is that the size of the various
13316		 * S/G segments may be different than the size from the
13317		 * remote controller.  That'll make it harder when DMAing
13318		 * the data back to the other side.
13319		 */
13320		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13321		     sizeof(io->io_hdr.remote_sglist[0])) &&
13322		     (len_to_go > 0); i++) {
13323			local_sglist[i].len = ctl_min(len_to_go, 131072);
13324			CTL_SIZE_8B(local_dma_sglist[i].len,
13325				    local_sglist[i].len);
13326			local_sglist[i].addr =
13327				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13328
13329			local_dma_sglist[i].addr = local_sglist[i].addr;
13330
13331			if (local_sglist[i].addr == NULL) {
13332				int j;
13333
13334				printf("malloc failed for %zd bytes!",
13335				       local_dma_sglist[i].len);
13336				for (j = 0; j < i; j++) {
13337					free(local_sglist[j].addr, M_CTL);
13338				}
13339				ctl_set_internal_failure(&io->scsiio,
13340							 /*sks_valid*/ 1,
13341							 /*retry_count*/ 4857);
13342				retval = 1;
13343				goto bailout_error;
13344
13345			}
13346			/* XXX KDM do we need a sync here? */
13347
13348			len_to_go -= local_sglist[i].len;
13349		}
13350		/*
13351		 * Reset the number of S/G entries accordingly.  The
13352		 * original number of S/G entries is available in
13353		 * rem_sg_entries.
13354		 */
13355		io->scsiio.kern_sg_entries = i;
13356
13357#if 0
13358		printf("%s: kern_sg_entries = %d\n", __func__,
13359		       io->scsiio.kern_sg_entries);
13360		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13361			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13362			       local_sglist[i].addr, local_sglist[i].len,
13363			       local_dma_sglist[i].len);
13364#endif
13365	}
13366
13367
13368	return (retval);
13369
13370bailout_error:
13371
13372	ctl_send_datamove_done(io, /*have_lock*/ 0);
13373
13374	return (retval);
13375}
13376
13377static int
13378ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13379			 ctl_ha_dt_cb callback)
13380{
13381	struct ctl_ha_dt_req *rq;
13382	struct ctl_sg_entry *remote_sglist, *local_sglist;
13383	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13384	uint32_t local_used, remote_used, total_used;
13385	int retval;
13386	int i, j;
13387
13388	retval = 0;
13389
13390	rq = ctl_dt_req_alloc();
13391
13392	/*
13393	 * If we failed to allocate the request, and if the DMA didn't fail
13394	 * anyway, set busy status.  This is just a resource allocation
13395	 * failure.
13396	 */
13397	if ((rq == NULL)
13398	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13399		ctl_set_busy(&io->scsiio);
13400
13401	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13402
13403		if (rq != NULL)
13404			ctl_dt_req_free(rq);
13405
13406		/*
13407		 * The data move failed.  We need to return status back
13408		 * to the other controller.  No point in trying to DMA
13409		 * data to the remote controller.
13410		 */
13411
13412		ctl_send_datamove_done(io, /*have_lock*/ 0);
13413
13414		retval = 1;
13415
13416		goto bailout;
13417	}
13418
13419	local_sglist = io->io_hdr.local_sglist;
13420	local_dma_sglist = io->io_hdr.local_dma_sglist;
13421	remote_sglist = io->io_hdr.remote_sglist;
13422	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13423	local_used = 0;
13424	remote_used = 0;
13425	total_used = 0;
13426
13427	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13428		rq->ret = CTL_HA_STATUS_SUCCESS;
13429		rq->context = io;
13430		callback(rq);
13431		goto bailout;
13432	}
13433
13434	/*
13435	 * Pull/push the data over the wire from/to the other controller.
13436	 * This takes into account the possibility that the local and
13437	 * remote sglists may not be identical in terms of the size of
13438	 * the elements and the number of elements.
13439	 *
13440	 * One fundamental assumption here is that the length allocated for
13441	 * both the local and remote sglists is identical.  Otherwise, we've
13442	 * essentially got a coding error of some sort.
13443	 */
13444	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13445		int isc_ret;
13446		uint32_t cur_len, dma_length;
13447		uint8_t *tmp_ptr;
13448
13449		rq->id = CTL_HA_DATA_CTL;
13450		rq->command = command;
13451		rq->context = io;
13452
13453		/*
13454		 * Both pointers should be aligned.  But it is possible
13455		 * that the allocation length is not.  They should both
13456		 * also have enough slack left over at the end, though,
13457		 * to round up to the next 8 byte boundary.
13458		 */
13459		cur_len = ctl_min(local_sglist[i].len - local_used,
13460				  remote_sglist[j].len - remote_used);
13461
13462		/*
13463		 * In this case, we have a size issue and need to decrease
13464		 * the size, except in the case where we actually have less
13465		 * than 8 bytes left.  In that case, we need to increase
13466		 * the DMA length to get the last bit.
13467		 */
13468		if ((cur_len & 0x7) != 0) {
13469			if (cur_len > 0x7) {
13470				cur_len = cur_len - (cur_len & 0x7);
13471				dma_length = cur_len;
13472			} else {
13473				CTL_SIZE_8B(dma_length, cur_len);
13474			}
13475
13476		} else
13477			dma_length = cur_len;
13478
13479		/*
13480		 * If we had to allocate memory for this I/O, instead of using
13481		 * the non-cached mirror memory, we'll need to flush the cache
13482		 * before trying to DMA to the other controller.
13483		 *
13484		 * We could end up doing this multiple times for the same
13485		 * segment if we have a larger local segment than remote
13486		 * segment.  That shouldn't be an issue.
13487		 */
13488		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13489			/*
13490			 * XXX KDM use bus_dmamap_sync() here.
13491			 */
13492		}
13493
13494		rq->size = dma_length;
13495
13496		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13497		tmp_ptr += local_used;
13498
13499		/* Use physical addresses when talking to ISC hardware */
13500		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13501			/* XXX KDM use busdma */
13502#if 0
13503			rq->local = vtophys(tmp_ptr);
13504#endif
13505		} else
13506			rq->local = tmp_ptr;
13507
13508		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13509		tmp_ptr += remote_used;
13510		rq->remote = tmp_ptr;
13511
13512		rq->callback = NULL;
13513
13514		local_used += cur_len;
13515		if (local_used >= local_sglist[i].len) {
13516			i++;
13517			local_used = 0;
13518		}
13519
13520		remote_used += cur_len;
13521		if (remote_used >= remote_sglist[j].len) {
13522			j++;
13523			remote_used = 0;
13524		}
13525		total_used += cur_len;
13526
13527		if (total_used >= io->scsiio.kern_data_len)
13528			rq->callback = callback;
13529
13530		if ((rq->size & 0x7) != 0) {
13531			printf("%s: warning: size %d is not on 8b boundary\n",
13532			       __func__, rq->size);
13533		}
13534		if (((uintptr_t)rq->local & 0x7) != 0) {
13535			printf("%s: warning: local %p not on 8b boundary\n",
13536			       __func__, rq->local);
13537		}
13538		if (((uintptr_t)rq->remote & 0x7) != 0) {
13539			printf("%s: warning: remote %p not on 8b boundary\n",
13540			       __func__, rq->local);
13541		}
13542#if 0
13543		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13544		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13545		       rq->local, rq->remote, rq->size);
13546#endif
13547
13548		isc_ret = ctl_dt_single(rq);
13549		if (isc_ret == CTL_HA_STATUS_WAIT)
13550			continue;
13551
13552		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13553			rq->ret = CTL_HA_STATUS_SUCCESS;
13554		} else {
13555			rq->ret = isc_ret;
13556		}
13557		callback(rq);
13558		goto bailout;
13559	}
13560
13561bailout:
13562	return (retval);
13563
13564}
13565
13566static void
13567ctl_datamove_remote_read(union ctl_io *io)
13568{
13569	int retval;
13570	int i;
13571
13572	/*
13573	 * This will send an error to the other controller in the case of a
13574	 * failure.
13575	 */
13576	retval = ctl_datamove_remote_sgl_setup(io);
13577	if (retval != 0)
13578		return;
13579
13580	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13581					  ctl_datamove_remote_read_cb);
13582	if ((retval != 0)
13583	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13584		/*
13585		 * Make sure we free memory if there was an error..  The
13586		 * ctl_datamove_remote_xfer() function will send the
13587		 * datamove done message, or call the callback with an
13588		 * error if there is a problem.
13589		 */
13590		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13591			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13592	}
13593
13594	return;
13595}
13596
13597/*
13598 * Process a datamove request from the other controller.  This is used for
13599 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13600 * first.  Once that is complete, the data gets DMAed into the remote
13601 * controller's memory.  For reads, we DMA from the remote controller's
13602 * memory into our memory first, and then move it out to the FETD.
13603 */
13604static void
13605ctl_datamove_remote(union ctl_io *io)
13606{
13607	struct ctl_softc *softc;
13608
13609	softc = control_softc;
13610
13611	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13612
13613	/*
13614	 * Note that we look for an aborted I/O here, but don't do some of
13615	 * the other checks that ctl_datamove() normally does.
13616	 * We don't need to run the datamove delay code, since that should
13617	 * have been done if need be on the other controller.
13618	 */
13619	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13620		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13621		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13622		       io->io_hdr.nexus.targ_port,
13623		       io->io_hdr.nexus.targ_target.id,
13624		       io->io_hdr.nexus.targ_lun);
13625		io->io_hdr.port_status = 31338;
13626		ctl_send_datamove_done(io, /*have_lock*/ 0);
13627		return;
13628	}
13629
13630	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13631		ctl_datamove_remote_write(io);
13632	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13633		ctl_datamove_remote_read(io);
13634	} else {
13635		union ctl_ha_msg msg;
13636		struct scsi_sense_data *sense;
13637		uint8_t sks[3];
13638		int retry_count;
13639
13640		memset(&msg, 0, sizeof(msg));
13641
13642		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13643		msg.hdr.status = CTL_SCSI_ERROR;
13644		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13645
13646		retry_count = 4243;
13647
13648		sense = &msg.scsi.sense_data;
13649		sks[0] = SSD_SCS_VALID;
13650		sks[1] = (retry_count >> 8) & 0xff;
13651		sks[2] = retry_count & 0xff;
13652
13653		/* "Internal target failure" */
13654		scsi_set_sense_data(sense,
13655				    /*sense_format*/ SSD_TYPE_NONE,
13656				    /*current_error*/ 1,
13657				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13658				    /*asc*/ 0x44,
13659				    /*ascq*/ 0x00,
13660				    /*type*/ SSD_ELEM_SKS,
13661				    /*size*/ sizeof(sks),
13662				    /*data*/ sks,
13663				    SSD_ELEM_NONE);
13664
13665		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13666		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13667			ctl_failover_io(io, /*have_lock*/ 1);
13668			return;
13669		}
13670
13671		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13672		    CTL_HA_STATUS_SUCCESS) {
13673			/* XXX KDM what to do if this fails? */
13674		}
13675		return;
13676	}
13677
13678}
13679
13680static int
13681ctl_process_done(union ctl_io *io)
13682{
13683	struct ctl_lun *lun;
13684	struct ctl_softc *ctl_softc;
13685	void (*fe_done)(union ctl_io *io);
13686	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13687
13688	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13689
13690	fe_done =
13691	    control_softc->ctl_ports[targ_port]->fe_done;
13692
13693#ifdef CTL_TIME_IO
13694	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13695		char str[256];
13696		char path_str[64];
13697		struct sbuf sb;
13698
13699		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13700		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13701
13702		sbuf_cat(&sb, path_str);
13703		switch (io->io_hdr.io_type) {
13704		case CTL_IO_SCSI:
13705			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13706			sbuf_printf(&sb, "\n");
13707			sbuf_cat(&sb, path_str);
13708			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13709				    io->scsiio.tag_num, io->scsiio.tag_type);
13710			break;
13711		case CTL_IO_TASK:
13712			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13713				    "Tag Type: %d\n", io->taskio.task_action,
13714				    io->taskio.tag_num, io->taskio.tag_type);
13715			break;
13716		default:
13717			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13718			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13719			break;
13720		}
13721		sbuf_cat(&sb, path_str);
13722		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13723			    (intmax_t)time_uptime - io->io_hdr.start_time);
13724		sbuf_finish(&sb);
13725		printf("%s", sbuf_data(&sb));
13726	}
13727#endif /* CTL_TIME_IO */
13728
13729	switch (io->io_hdr.io_type) {
13730	case CTL_IO_SCSI:
13731		break;
13732	case CTL_IO_TASK:
13733		if (bootverbose || (ctl_debug & CTL_DEBUG_INFO))
13734			ctl_io_error_print(io, NULL);
13735		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13736			ctl_free_io(io);
13737		else
13738			fe_done(io);
13739		return (CTL_RETVAL_COMPLETE);
13740	default:
13741		panic("ctl_process_done: invalid io type %d\n",
13742		      io->io_hdr.io_type);
13743		break; /* NOTREACHED */
13744	}
13745
13746	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13747	if (lun == NULL) {
13748		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13749				 io->io_hdr.nexus.targ_mapped_lun));
13750		fe_done(io);
13751		goto bailout;
13752	}
13753	ctl_softc = lun->ctl_softc;
13754
13755	mtx_lock(&lun->lun_lock);
13756
13757	/*
13758	 * Check to see if we have any errors to inject here.  We only
13759	 * inject errors for commands that don't already have errors set.
13760	 */
13761	if ((STAILQ_FIRST(&lun->error_list) != NULL)
13762	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
13763		ctl_inject_error(lun, io);
13764
13765	/*
13766	 * XXX KDM how do we treat commands that aren't completed
13767	 * successfully?
13768	 *
13769	 * XXX KDM should we also track I/O latency?
13770	 */
13771	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13772	    io->io_hdr.io_type == CTL_IO_SCSI) {
13773#ifdef CTL_TIME_IO
13774		struct bintime cur_bt;
13775#endif
13776		int type;
13777
13778		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13779		    CTL_FLAG_DATA_IN)
13780			type = CTL_STATS_READ;
13781		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13782		    CTL_FLAG_DATA_OUT)
13783			type = CTL_STATS_WRITE;
13784		else
13785			type = CTL_STATS_NO_IO;
13786
13787		lun->stats.ports[targ_port].bytes[type] +=
13788		    io->scsiio.kern_total_len;
13789		lun->stats.ports[targ_port].operations[type]++;
13790#ifdef CTL_TIME_IO
13791		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13792		   &io->io_hdr.dma_bt);
13793		lun->stats.ports[targ_port].num_dmas[type] +=
13794		    io->io_hdr.num_dmas;
13795		getbintime(&cur_bt);
13796		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13797		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13798#endif
13799	}
13800
13801	/*
13802	 * Remove this from the OOA queue.
13803	 */
13804	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13805
13806	/*
13807	 * Run through the blocked queue on this LUN and see if anything
13808	 * has become unblocked, now that this transaction is done.
13809	 */
13810	ctl_check_blocked(lun);
13811
13812	/*
13813	 * If the LUN has been invalidated, free it if there is nothing
13814	 * left on its OOA queue.
13815	 */
13816	if ((lun->flags & CTL_LUN_INVALID)
13817	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13818		mtx_unlock(&lun->lun_lock);
13819		mtx_lock(&ctl_softc->ctl_lock);
13820		ctl_free_lun(lun);
13821		mtx_unlock(&ctl_softc->ctl_lock);
13822	} else
13823		mtx_unlock(&lun->lun_lock);
13824
13825	/*
13826	 * If this command has been aborted, make sure we set the status
13827	 * properly.  The FETD is responsible for freeing the I/O and doing
13828	 * whatever it needs to do to clean up its state.
13829	 */
13830	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13831		ctl_set_task_aborted(&io->scsiio);
13832
13833	/*
13834	 * If enabled, print command error status.
13835	 * We don't print UAs unless debugging was enabled explicitly.
13836	 */
13837	do {
13838		if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)
13839			break;
13840		if (!bootverbose && (ctl_debug & CTL_DEBUG_INFO) == 0)
13841			break;
13842		if ((ctl_debug & CTL_DEBUG_INFO) == 0 &&
13843		    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR) &&
13844		     (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13845			int error_code, sense_key, asc, ascq;
13846
13847			scsi_extract_sense_len(&io->scsiio.sense_data,
13848			    io->scsiio.sense_len, &error_code, &sense_key,
13849			    &asc, &ascq, /*show_errors*/ 0);
13850			if (sense_key == SSD_KEY_UNIT_ATTENTION)
13851				break;
13852		}
13853
13854		ctl_io_error_print(io, NULL);
13855	} while (0);
13856
13857	/*
13858	 * Tell the FETD or the other shelf controller we're done with this
13859	 * command.  Note that only SCSI commands get to this point.  Task
13860	 * management commands are completed above.
13861	 *
13862	 * We only send status to the other controller if we're in XFER
13863	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13864	 * received the I/O (from CTL's perspective), and so the status is
13865	 * generated there.
13866	 *
13867	 * XXX KDM if we hold the lock here, we could cause a deadlock
13868	 * if the frontend comes back in in this context to queue
13869	 * something.
13870	 */
13871	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13872	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13873		union ctl_ha_msg msg;
13874
13875		memset(&msg, 0, sizeof(msg));
13876		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13877		msg.hdr.original_sc = io->io_hdr.original_sc;
13878		msg.hdr.nexus = io->io_hdr.nexus;
13879		msg.hdr.status = io->io_hdr.status;
13880		msg.scsi.scsi_status = io->scsiio.scsi_status;
13881		msg.scsi.tag_num = io->scsiio.tag_num;
13882		msg.scsi.tag_type = io->scsiio.tag_type;
13883		msg.scsi.sense_len = io->scsiio.sense_len;
13884		msg.scsi.sense_residual = io->scsiio.sense_residual;
13885		msg.scsi.residual = io->scsiio.residual;
13886		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13887		       sizeof(io->scsiio.sense_data));
13888		/*
13889		 * We copy this whether or not this is an I/O-related
13890		 * command.  Otherwise, we'd have to go and check to see
13891		 * whether it's a read/write command, and it really isn't
13892		 * worth it.
13893		 */
13894		memcpy(&msg.scsi.lbalen,
13895		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13896		       sizeof(msg.scsi.lbalen));
13897
13898		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13899				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13900			/* XXX do something here */
13901		}
13902
13903		ctl_free_io(io);
13904	} else
13905		fe_done(io);
13906
13907bailout:
13908
13909	return (CTL_RETVAL_COMPLETE);
13910}
13911
13912#ifdef CTL_WITH_CA
13913/*
13914 * Front end should call this if it doesn't do autosense.  When the request
13915 * sense comes back in from the initiator, we'll dequeue this and send it.
13916 */
13917int
13918ctl_queue_sense(union ctl_io *io)
13919{
13920	struct ctl_lun *lun;
13921	struct ctl_softc *ctl_softc;
13922	uint32_t initidx, targ_lun;
13923
13924	ctl_softc = control_softc;
13925
13926	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13927
13928	/*
13929	 * LUN lookup will likely move to the ctl_work_thread() once we
13930	 * have our new queueing infrastructure (that doesn't put things on
13931	 * a per-LUN queue initially).  That is so that we can handle
13932	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13933	 * can't deal with that right now.
13934	 */
13935	mtx_lock(&ctl_softc->ctl_lock);
13936
13937	/*
13938	 * If we don't have a LUN for this, just toss the sense
13939	 * information.
13940	 */
13941	targ_lun = io->io_hdr.nexus.targ_lun;
13942	targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13943	if ((targ_lun < CTL_MAX_LUNS)
13944	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
13945		lun = ctl_softc->ctl_luns[targ_lun];
13946	else
13947		goto bailout;
13948
13949	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13950
13951	mtx_lock(&lun->lun_lock);
13952	/*
13953	 * Already have CA set for this LUN...toss the sense information.
13954	 */
13955	if (ctl_is_set(lun->have_ca, initidx)) {
13956		mtx_unlock(&lun->lun_lock);
13957		goto bailout;
13958	}
13959
13960	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13961	       ctl_min(sizeof(lun->pending_sense[initidx]),
13962	       sizeof(io->scsiio.sense_data)));
13963	ctl_set_mask(lun->have_ca, initidx);
13964	mtx_unlock(&lun->lun_lock);
13965
13966bailout:
13967	mtx_unlock(&ctl_softc->ctl_lock);
13968
13969	ctl_free_io(io);
13970
13971	return (CTL_RETVAL_COMPLETE);
13972}
13973#endif
13974
13975/*
13976 * Primary command inlet from frontend ports.  All SCSI and task I/O
13977 * requests must go through this function.
13978 */
13979int
13980ctl_queue(union ctl_io *io)
13981{
13982	struct ctl_softc *ctl_softc;
13983
13984	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13985
13986	ctl_softc = control_softc;
13987
13988#ifdef CTL_TIME_IO
13989	io->io_hdr.start_time = time_uptime;
13990	getbintime(&io->io_hdr.start_bt);
13991#endif /* CTL_TIME_IO */
13992
13993	/* Map FE-specific LUN ID into global one. */
13994	io->io_hdr.nexus.targ_mapped_lun =
13995	    ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13996
13997	switch (io->io_hdr.io_type) {
13998	case CTL_IO_SCSI:
13999	case CTL_IO_TASK:
14000		if (ctl_debug & CTL_DEBUG_CDB)
14001			ctl_io_print(io);
14002		ctl_enqueue_incoming(io);
14003		break;
14004	default:
14005		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
14006		return (EINVAL);
14007	}
14008
14009	return (CTL_RETVAL_COMPLETE);
14010}
14011
14012#ifdef CTL_IO_DELAY
14013static void
14014ctl_done_timer_wakeup(void *arg)
14015{
14016	union ctl_io *io;
14017
14018	io = (union ctl_io *)arg;
14019	ctl_done(io);
14020}
14021#endif /* CTL_IO_DELAY */
14022
14023void
14024ctl_done(union ctl_io *io)
14025{
14026	struct ctl_softc *ctl_softc;
14027
14028	ctl_softc = control_softc;
14029
14030	/*
14031	 * Enable this to catch duplicate completion issues.
14032	 */
14033#if 0
14034	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
14035		printf("%s: type %d msg %d cdb %x iptl: "
14036		       "%d:%d:%d:%d tag 0x%04x "
14037		       "flag %#x status %x\n",
14038			__func__,
14039			io->io_hdr.io_type,
14040			io->io_hdr.msg_type,
14041			io->scsiio.cdb[0],
14042			io->io_hdr.nexus.initid.id,
14043			io->io_hdr.nexus.targ_port,
14044			io->io_hdr.nexus.targ_target.id,
14045			io->io_hdr.nexus.targ_lun,
14046			(io->io_hdr.io_type ==
14047			CTL_IO_TASK) ?
14048			io->taskio.tag_num :
14049			io->scsiio.tag_num,
14050		        io->io_hdr.flags,
14051			io->io_hdr.status);
14052	} else
14053		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
14054#endif
14055
14056	/*
14057	 * This is an internal copy of an I/O, and should not go through
14058	 * the normal done processing logic.
14059	 */
14060	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
14061		return;
14062
14063	/*
14064	 * We need to send a msg to the serializing shelf to finish the IO
14065	 * as well.  We don't send a finish message to the other shelf if
14066	 * this is a task management command.  Task management commands
14067	 * aren't serialized in the OOA queue, but rather just executed on
14068	 * both shelf controllers for commands that originated on that
14069	 * controller.
14070	 */
14071	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
14072	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
14073		union ctl_ha_msg msg_io;
14074
14075		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
14076		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
14077		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
14078		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
14079		}
14080		/* continue on to finish IO */
14081	}
14082#ifdef CTL_IO_DELAY
14083	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
14084		struct ctl_lun *lun;
14085
14086		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14087
14088		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
14089	} else {
14090		struct ctl_lun *lun;
14091
14092		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14093
14094		if ((lun != NULL)
14095		 && (lun->delay_info.done_delay > 0)) {
14096			struct callout *callout;
14097
14098			callout = (struct callout *)&io->io_hdr.timer_bytes;
14099			callout_init(callout, /*mpsafe*/ 1);
14100			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
14101			callout_reset(callout,
14102				      lun->delay_info.done_delay * hz,
14103				      ctl_done_timer_wakeup, io);
14104			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
14105				lun->delay_info.done_delay = 0;
14106			return;
14107		}
14108	}
14109#endif /* CTL_IO_DELAY */
14110
14111	ctl_enqueue_done(io);
14112}
14113
14114int
14115ctl_isc(struct ctl_scsiio *ctsio)
14116{
14117	struct ctl_lun *lun;
14118	int retval;
14119
14120	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14121
14122	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
14123
14124	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
14125
14126	retval = lun->backend->data_submit((union ctl_io *)ctsio);
14127
14128	return (retval);
14129}
14130
14131
14132static void
14133ctl_work_thread(void *arg)
14134{
14135	struct ctl_thread *thr = (struct ctl_thread *)arg;
14136	struct ctl_softc *softc = thr->ctl_softc;
14137	union ctl_io *io;
14138	int retval;
14139
14140	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
14141
14142	for (;;) {
14143		retval = 0;
14144
14145		/*
14146		 * We handle the queues in this order:
14147		 * - ISC
14148		 * - done queue (to free up resources, unblock other commands)
14149		 * - RtR queue
14150		 * - incoming queue
14151		 *
14152		 * If those queues are empty, we break out of the loop and
14153		 * go to sleep.
14154		 */
14155		mtx_lock(&thr->queue_lock);
14156		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
14157		if (io != NULL) {
14158			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
14159			mtx_unlock(&thr->queue_lock);
14160			ctl_handle_isc(io);
14161			continue;
14162		}
14163		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
14164		if (io != NULL) {
14165			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
14166			/* clear any blocked commands, call fe_done */
14167			mtx_unlock(&thr->queue_lock);
14168			retval = ctl_process_done(io);
14169			continue;
14170		}
14171		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
14172		if (io != NULL) {
14173			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
14174			mtx_unlock(&thr->queue_lock);
14175			if (io->io_hdr.io_type == CTL_IO_TASK)
14176				ctl_run_task(io);
14177			else
14178				ctl_scsiio_precheck(softc, &io->scsiio);
14179			continue;
14180		}
14181		if (!ctl_pause_rtr) {
14182			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
14183			if (io != NULL) {
14184				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
14185				mtx_unlock(&thr->queue_lock);
14186				retval = ctl_scsiio(&io->scsiio);
14187				if (retval != CTL_RETVAL_COMPLETE)
14188					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
14189				continue;
14190			}
14191		}
14192
14193		/* Sleep until we have something to do. */
14194		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
14195	}
14196}
14197
14198static void
14199ctl_lun_thread(void *arg)
14200{
14201	struct ctl_softc *softc = (struct ctl_softc *)arg;
14202	struct ctl_be_lun *be_lun;
14203	int retval;
14204
14205	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
14206
14207	for (;;) {
14208		retval = 0;
14209		mtx_lock(&softc->ctl_lock);
14210		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
14211		if (be_lun != NULL) {
14212			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
14213			mtx_unlock(&softc->ctl_lock);
14214			ctl_create_lun(be_lun);
14215			continue;
14216		}
14217
14218		/* Sleep until we have something to do. */
14219		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
14220		    PDROP | PRIBIO, "-", 0);
14221	}
14222}
14223
14224static void
14225ctl_thresh_thread(void *arg)
14226{
14227	struct ctl_softc *softc = (struct ctl_softc *)arg;
14228	struct ctl_lun *lun;
14229	struct ctl_be_lun *be_lun;
14230	struct scsi_da_rw_recovery_page *rwpage;
14231	struct ctl_logical_block_provisioning_page *page;
14232	const char *attr;
14233	uint64_t thres, val;
14234	int i, e;
14235
14236	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
14237
14238	for (;;) {
14239		mtx_lock(&softc->ctl_lock);
14240		STAILQ_FOREACH(lun, &softc->lun_list, links) {
14241			be_lun = lun->be_lun;
14242			if ((lun->flags & CTL_LUN_DISABLED) ||
14243			    (lun->flags & CTL_LUN_OFFLINE) ||
14244			    (be_lun->flags & CTL_LUN_FLAG_UNMAP) == 0 ||
14245			    lun->backend->lun_attr == NULL)
14246				continue;
14247			rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
14248			if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
14249				continue;
14250			e = 0;
14251			page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
14252			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
14253				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
14254					continue;
14255				thres = scsi_4btoul(page->descr[i].count);
14256				thres <<= CTL_LBP_EXPONENT;
14257				switch (page->descr[i].resource) {
14258				case 0x01:
14259					attr = "blocksavail";
14260					break;
14261				case 0x02:
14262					attr = "blocksused";
14263					break;
14264				case 0xf1:
14265					attr = "poolblocksavail";
14266					break;
14267				case 0xf2:
14268					attr = "poolblocksused";
14269					break;
14270				default:
14271					continue;
14272				}
14273				mtx_unlock(&softc->ctl_lock); // XXX
14274				val = lun->backend->lun_attr(
14275				    lun->be_lun->be_lun, attr);
14276				mtx_lock(&softc->ctl_lock);
14277				if (val == UINT64_MAX)
14278					continue;
14279				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
14280				    == SLBPPD_ARMING_INC)
14281					e |= (val >= thres);
14282				else
14283					e |= (val <= thres);
14284			}
14285			mtx_lock(&lun->lun_lock);
14286			if (e) {
14287				if (lun->lasttpt == 0 ||
14288				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
14289					lun->lasttpt = time_uptime;
14290					for (i = 0; i < CTL_MAX_INITIATORS; i++)
14291						lun->pending_ua[i] |=
14292						    CTL_UA_THIN_PROV_THRES;
14293				}
14294			} else {
14295				lun->lasttpt = 0;
14296				for (i = 0; i < CTL_MAX_INITIATORS; i++)
14297					lun->pending_ua[i] &= ~CTL_UA_THIN_PROV_THRES;
14298			}
14299			mtx_unlock(&lun->lun_lock);
14300		}
14301		mtx_unlock(&softc->ctl_lock);
14302		pause("-", CTL_LBP_PERIOD * hz);
14303	}
14304}
14305
14306static void
14307ctl_enqueue_incoming(union ctl_io *io)
14308{
14309	struct ctl_softc *softc = control_softc;
14310	struct ctl_thread *thr;
14311	u_int idx;
14312
14313	idx = (io->io_hdr.nexus.targ_port * 127 +
14314	       io->io_hdr.nexus.initid.id) % worker_threads;
14315	thr = &softc->threads[idx];
14316	mtx_lock(&thr->queue_lock);
14317	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14318	mtx_unlock(&thr->queue_lock);
14319	wakeup(thr);
14320}
14321
14322static void
14323ctl_enqueue_rtr(union ctl_io *io)
14324{
14325	struct ctl_softc *softc = control_softc;
14326	struct ctl_thread *thr;
14327
14328	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14329	mtx_lock(&thr->queue_lock);
14330	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14331	mtx_unlock(&thr->queue_lock);
14332	wakeup(thr);
14333}
14334
14335static void
14336ctl_enqueue_done(union ctl_io *io)
14337{
14338	struct ctl_softc *softc = control_softc;
14339	struct ctl_thread *thr;
14340
14341	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14342	mtx_lock(&thr->queue_lock);
14343	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14344	mtx_unlock(&thr->queue_lock);
14345	wakeup(thr);
14346}
14347
14348static void
14349ctl_enqueue_isc(union ctl_io *io)
14350{
14351	struct ctl_softc *softc = control_softc;
14352	struct ctl_thread *thr;
14353
14354	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14355	mtx_lock(&thr->queue_lock);
14356	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14357	mtx_unlock(&thr->queue_lock);
14358	wakeup(thr);
14359}
14360
14361/* Initialization and failover */
14362
14363void
14364ctl_init_isc_msg(void)
14365{
14366	printf("CTL: Still calling this thing\n");
14367}
14368
14369/*
14370 * Init component
14371 * 	Initializes component into configuration defined by bootMode
14372 *	(see hasc-sv.c)
14373 *  	returns hasc_Status:
14374 * 		OK
14375 *		ERROR - fatal error
14376 */
14377static ctl_ha_comp_status
14378ctl_isc_init(struct ctl_ha_component *c)
14379{
14380	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14381
14382	c->status = ret;
14383	return ret;
14384}
14385
14386/* Start component
14387 * 	Starts component in state requested. If component starts successfully,
14388 *	it must set its own state to the requestrd state
14389 *	When requested state is HASC_STATE_HA, the component may refine it
14390 * 	by adding _SLAVE or _MASTER flags.
14391 *	Currently allowed state transitions are:
14392 *	UNKNOWN->HA		- initial startup
14393 *	UNKNOWN->SINGLE - initial startup when no parter detected
14394 *	HA->SINGLE		- failover
14395 * returns ctl_ha_comp_status:
14396 * 		OK	- component successfully started in requested state
14397 *		FAILED  - could not start the requested state, failover may
14398 * 			  be possible
14399 *		ERROR	- fatal error detected, no future startup possible
14400 */
14401static ctl_ha_comp_status
14402ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14403{
14404	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14405
14406	printf("%s: go\n", __func__);
14407
14408	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14409	if (c->state == CTL_HA_STATE_UNKNOWN ) {
14410		ctl_is_single = 0;
14411		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14412		    != CTL_HA_STATUS_SUCCESS) {
14413			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14414			ret = CTL_HA_COMP_STATUS_ERROR;
14415		}
14416	} else if (CTL_HA_STATE_IS_HA(c->state)
14417		&& CTL_HA_STATE_IS_SINGLE(state)){
14418		// HA->SINGLE transition
14419	        ctl_failover();
14420		ctl_is_single = 1;
14421	} else {
14422		printf("ctl_isc_start:Invalid state transition %X->%X\n",
14423		       c->state, state);
14424		ret = CTL_HA_COMP_STATUS_ERROR;
14425	}
14426	if (CTL_HA_STATE_IS_SINGLE(state))
14427		ctl_is_single = 1;
14428
14429	c->state = state;
14430	c->status = ret;
14431	return ret;
14432}
14433
14434/*
14435 * Quiesce component
14436 * The component must clear any error conditions (set status to OK) and
14437 * prepare itself to another Start call
14438 * returns ctl_ha_comp_status:
14439 * 	OK
14440 *	ERROR
14441 */
14442static ctl_ha_comp_status
14443ctl_isc_quiesce(struct ctl_ha_component *c)
14444{
14445	int ret = CTL_HA_COMP_STATUS_OK;
14446
14447	ctl_pause_rtr = 1;
14448	c->status = ret;
14449	return ret;
14450}
14451
14452struct ctl_ha_component ctl_ha_component_ctlisc =
14453{
14454	.name = "CTL ISC",
14455	.state = CTL_HA_STATE_UNKNOWN,
14456	.init = ctl_isc_init,
14457	.start = ctl_isc_start,
14458	.quiesce = ctl_isc_quiesce
14459};
14460
14461/*
14462 *  vim: ts=8
14463 */
14464