ctl.c revision 274785
1/*-
2 * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3 * Copyright (c) 2012 The FreeBSD Foundation
4 * All rights reserved.
5 *
6 * Portions of this software were developed by Edward Tomasz Napierala
7 * under sponsorship from the FreeBSD Foundation.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions, and the following disclaimer,
14 *    without modification.
15 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
16 *    substantially similar to the "NO WARRANTY" disclaimer below
17 *    ("Disclaimer") and any redistribution must be conditioned upon
18 *    including a substantially similar Disclaimer requirement for further
19 *    binary redistribution.
20 *
21 * NO WARRANTY
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
25 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
31 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGES.
33 *
34 * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/ctl.c#8 $
35 */
36/*
37 * CAM Target Layer, a SCSI device emulation subsystem.
38 *
39 * Author: Ken Merry <ken@FreeBSD.org>
40 */
41
42#define _CTL_C
43
44#include <sys/cdefs.h>
45__FBSDID("$FreeBSD: head/sys/cam/ctl/ctl.c 274785 2014-11-21 06:27:37Z 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;
360
361SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
362static int worker_threads = -1;
363SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
364    &worker_threads, 1, "Number of worker threads");
365static int ctl_debug = CTL_DEBUG_NONE;
366SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
367    &ctl_debug, 0, "Enabled debug flags");
368
369/*
370 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
371 * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
372 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
373 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
374 */
375#define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
376
377static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
378				  int param);
379static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
380static int ctl_init(void);
381void ctl_shutdown(void);
382static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
383static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
384static void ctl_ioctl_online(void *arg);
385static void ctl_ioctl_offline(void *arg);
386static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
387static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
388static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
389static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
390static int ctl_ioctl_submit_wait(union ctl_io *io);
391static void ctl_ioctl_datamove(union ctl_io *io);
392static void ctl_ioctl_done(union ctl_io *io);
393static void ctl_ioctl_hard_startstop_callback(void *arg,
394					      struct cfi_metatask *metatask);
395static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
396static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
397			      struct ctl_ooa *ooa_hdr,
398			      struct ctl_ooa_entry *kern_entries);
399static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
400		     struct thread *td);
401static uint32_t ctl_map_lun(int port_num, uint32_t lun);
402static uint32_t ctl_map_lun_back(int port_num, uint32_t lun);
403#ifdef unused
404static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
405				   uint32_t targ_target, uint32_t targ_lun,
406				   int can_wait);
407static void ctl_kfree_io(union ctl_io *io);
408#endif /* unused */
409static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
410			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
411static int ctl_free_lun(struct ctl_lun *lun);
412static void ctl_create_lun(struct ctl_be_lun *be_lun);
413/**
414static void ctl_failover_change_pages(struct ctl_softc *softc,
415				      struct ctl_scsiio *ctsio, int master);
416**/
417
418static int ctl_do_mode_select(union ctl_io *io);
419static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
420			   uint64_t res_key, uint64_t sa_res_key,
421			   uint8_t type, uint32_t residx,
422			   struct ctl_scsiio *ctsio,
423			   struct scsi_per_res_out *cdb,
424			   struct scsi_per_res_out_parms* param);
425static void ctl_pro_preempt_other(struct ctl_lun *lun,
426				  union ctl_ha_msg *msg);
427static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
428static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
429static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
430static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
431static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
432static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
433static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
434					 int alloc_len);
435static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
436					 int alloc_len);
437static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
438static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
439static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
440static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
441static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
442static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
443static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
444    union ctl_io *pending_io, union ctl_io *ooa_io);
445static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
446				union ctl_io *starting_io);
447static int ctl_check_blocked(struct ctl_lun *lun);
448static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
449				struct ctl_lun *lun,
450				const struct ctl_cmd_entry *entry,
451				struct ctl_scsiio *ctsio);
452//static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
453static void ctl_failover(void);
454static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
455			       struct ctl_scsiio *ctsio);
456static int ctl_scsiio(struct ctl_scsiio *ctsio);
457
458static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
459static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
460			    ctl_ua_type ua_type);
461static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
462			 ctl_ua_type ua_type);
463static int ctl_abort_task(union ctl_io *io);
464static int ctl_abort_task_set(union ctl_io *io);
465static int ctl_i_t_nexus_reset(union ctl_io *io);
466static void ctl_run_task(union ctl_io *io);
467#ifdef CTL_IO_DELAY
468static void ctl_datamove_timer_wakeup(void *arg);
469static void ctl_done_timer_wakeup(void *arg);
470#endif /* CTL_IO_DELAY */
471
472static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
473static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
474static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
475static void ctl_datamove_remote_write(union ctl_io *io);
476static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
477static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
478static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
479static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
480				    ctl_ha_dt_cb callback);
481static void ctl_datamove_remote_read(union ctl_io *io);
482static void ctl_datamove_remote(union ctl_io *io);
483static int ctl_process_done(union ctl_io *io);
484static void ctl_lun_thread(void *arg);
485static void ctl_thresh_thread(void *arg);
486static void ctl_work_thread(void *arg);
487static void ctl_enqueue_incoming(union ctl_io *io);
488static void ctl_enqueue_rtr(union ctl_io *io);
489static void ctl_enqueue_done(union ctl_io *io);
490static void ctl_enqueue_isc(union ctl_io *io);
491static const struct ctl_cmd_entry *
492    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
493static const struct ctl_cmd_entry *
494    ctl_validate_command(struct ctl_scsiio *ctsio);
495static int ctl_cmd_applicable(uint8_t lun_type,
496    const struct ctl_cmd_entry *entry);
497
498/*
499 * Load the serialization table.  This isn't very pretty, but is probably
500 * the easiest way to do it.
501 */
502#include "ctl_ser_table.c"
503
504/*
505 * We only need to define open, close and ioctl routines for this driver.
506 */
507static struct cdevsw ctl_cdevsw = {
508	.d_version =	D_VERSION,
509	.d_flags =	0,
510	.d_open =	ctl_open,
511	.d_close =	ctl_close,
512	.d_ioctl =	ctl_ioctl,
513	.d_name =	"ctl",
514};
515
516
517MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
518MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
519
520static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
521
522static moduledata_t ctl_moduledata = {
523	"ctl",
524	ctl_module_event_handler,
525	NULL
526};
527
528DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
529MODULE_VERSION(ctl, 1);
530
531static struct ctl_frontend ioctl_frontend =
532{
533	.name = "ioctl",
534};
535
536static void
537ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
538			    union ctl_ha_msg *msg_info)
539{
540	struct ctl_scsiio *ctsio;
541
542	if (msg_info->hdr.original_sc == NULL) {
543		printf("%s: original_sc == NULL!\n", __func__);
544		/* XXX KDM now what? */
545		return;
546	}
547
548	ctsio = &msg_info->hdr.original_sc->scsiio;
549	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
550	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
551	ctsio->io_hdr.status = msg_info->hdr.status;
552	ctsio->scsi_status = msg_info->scsi.scsi_status;
553	ctsio->sense_len = msg_info->scsi.sense_len;
554	ctsio->sense_residual = msg_info->scsi.sense_residual;
555	ctsio->residual = msg_info->scsi.residual;
556	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
557	       sizeof(ctsio->sense_data));
558	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
559	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
560	ctl_enqueue_isc((union ctl_io *)ctsio);
561}
562
563static void
564ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
565				union ctl_ha_msg *msg_info)
566{
567	struct ctl_scsiio *ctsio;
568
569	if (msg_info->hdr.serializing_sc == NULL) {
570		printf("%s: serializing_sc == NULL!\n", __func__);
571		/* XXX KDM now what? */
572		return;
573	}
574
575	ctsio = &msg_info->hdr.serializing_sc->scsiio;
576#if 0
577	/*
578	 * Attempt to catch the situation where an I/O has
579	 * been freed, and we're using it again.
580	 */
581	if (ctsio->io_hdr.io_type == 0xff) {
582		union ctl_io *tmp_io;
583		tmp_io = (union ctl_io *)ctsio;
584		printf("%s: %p use after free!\n", __func__,
585		       ctsio);
586		printf("%s: type %d msg %d cdb %x iptl: "
587		       "%d:%d:%d:%d tag 0x%04x "
588		       "flag %#x status %x\n",
589			__func__,
590			tmp_io->io_hdr.io_type,
591			tmp_io->io_hdr.msg_type,
592			tmp_io->scsiio.cdb[0],
593			tmp_io->io_hdr.nexus.initid.id,
594			tmp_io->io_hdr.nexus.targ_port,
595			tmp_io->io_hdr.nexus.targ_target.id,
596			tmp_io->io_hdr.nexus.targ_lun,
597			(tmp_io->io_hdr.io_type ==
598			CTL_IO_TASK) ?
599			tmp_io->taskio.tag_num :
600			tmp_io->scsiio.tag_num,
601		        tmp_io->io_hdr.flags,
602			tmp_io->io_hdr.status);
603	}
604#endif
605	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
606	ctl_enqueue_isc((union ctl_io *)ctsio);
607}
608
609/*
610 * ISC (Inter Shelf Communication) event handler.  Events from the HA
611 * subsystem come in here.
612 */
613static void
614ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
615{
616	struct ctl_softc *ctl_softc;
617	union ctl_io *io;
618	struct ctl_prio *presio;
619	ctl_ha_status isc_status;
620
621	ctl_softc = control_softc;
622	io = NULL;
623
624
625#if 0
626	printf("CTL: Isc Msg event %d\n", event);
627#endif
628	if (event == CTL_HA_EVT_MSG_RECV) {
629		union ctl_ha_msg msg_info;
630
631		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
632					     sizeof(msg_info), /*wait*/ 0);
633#if 0
634		printf("CTL: msg_type %d\n", msg_info.msg_type);
635#endif
636		if (isc_status != 0) {
637			printf("Error receiving message, status = %d\n",
638			       isc_status);
639			return;
640		}
641
642		switch (msg_info.hdr.msg_type) {
643		case CTL_MSG_SERIALIZE:
644#if 0
645			printf("Serialize\n");
646#endif
647			io = ctl_alloc_io((void *)ctl_softc->othersc_pool);
648			if (io == NULL) {
649				printf("ctl_isc_event_handler: can't allocate "
650				       "ctl_io!\n");
651				/* Bad Juju */
652				/* Need to set busy and send msg back */
653				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
654				msg_info.hdr.status = CTL_SCSI_ERROR;
655				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
656				msg_info.scsi.sense_len = 0;
657			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
658				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
659				}
660				goto bailout;
661			}
662			ctl_zero_io(io);
663			// populate ctsio from msg_info
664			io->io_hdr.io_type = CTL_IO_SCSI;
665			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
666			io->io_hdr.original_sc = msg_info.hdr.original_sc;
667#if 0
668			printf("pOrig %x\n", (int)msg_info.original_sc);
669#endif
670			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
671					    CTL_FLAG_IO_ACTIVE;
672			/*
673			 * If we're in serialization-only mode, we don't
674			 * want to go through full done processing.  Thus
675			 * the COPY flag.
676			 *
677			 * XXX KDM add another flag that is more specific.
678			 */
679			if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
680				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
681			io->io_hdr.nexus = msg_info.hdr.nexus;
682#if 0
683			printf("targ %d, port %d, iid %d, lun %d\n",
684			       io->io_hdr.nexus.targ_target.id,
685			       io->io_hdr.nexus.targ_port,
686			       io->io_hdr.nexus.initid.id,
687			       io->io_hdr.nexus.targ_lun);
688#endif
689			io->scsiio.tag_num = msg_info.scsi.tag_num;
690			io->scsiio.tag_type = msg_info.scsi.tag_type;
691			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
692			       CTL_MAX_CDBLEN);
693			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
694				const struct ctl_cmd_entry *entry;
695
696				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
697				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
698				io->io_hdr.flags |=
699					entry->flags & CTL_FLAG_DATA_MASK;
700			}
701			ctl_enqueue_isc(io);
702			break;
703
704		/* Performed on the Originating SC, XFER mode only */
705		case CTL_MSG_DATAMOVE: {
706			struct ctl_sg_entry *sgl;
707			int i, j;
708
709			io = msg_info.hdr.original_sc;
710			if (io == NULL) {
711				printf("%s: original_sc == NULL!\n", __func__);
712				/* XXX KDM do something here */
713				break;
714			}
715			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
716			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
717			/*
718			 * Keep track of this, we need to send it back over
719			 * when the datamove is complete.
720			 */
721			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
722
723			if (msg_info.dt.sg_sequence == 0) {
724				/*
725				 * XXX KDM we use the preallocated S/G list
726				 * here, but we'll need to change this to
727				 * dynamic allocation if we need larger S/G
728				 * lists.
729				 */
730				if (msg_info.dt.kern_sg_entries >
731				    sizeof(io->io_hdr.remote_sglist) /
732				    sizeof(io->io_hdr.remote_sglist[0])) {
733					printf("%s: number of S/G entries "
734					    "needed %u > allocated num %zd\n",
735					    __func__,
736					    msg_info.dt.kern_sg_entries,
737					    sizeof(io->io_hdr.remote_sglist)/
738					    sizeof(io->io_hdr.remote_sglist[0]));
739
740					/*
741					 * XXX KDM send a message back to
742					 * the other side to shut down the
743					 * DMA.  The error will come back
744					 * through via the normal channel.
745					 */
746					break;
747				}
748				sgl = io->io_hdr.remote_sglist;
749				memset(sgl, 0,
750				       sizeof(io->io_hdr.remote_sglist));
751
752				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
753
754				io->scsiio.kern_sg_entries =
755					msg_info.dt.kern_sg_entries;
756				io->scsiio.rem_sg_entries =
757					msg_info.dt.kern_sg_entries;
758				io->scsiio.kern_data_len =
759					msg_info.dt.kern_data_len;
760				io->scsiio.kern_total_len =
761					msg_info.dt.kern_total_len;
762				io->scsiio.kern_data_resid =
763					msg_info.dt.kern_data_resid;
764				io->scsiio.kern_rel_offset =
765					msg_info.dt.kern_rel_offset;
766				/*
767				 * Clear out per-DMA flags.
768				 */
769				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
770				/*
771				 * Add per-DMA flags that are set for this
772				 * particular DMA request.
773				 */
774				io->io_hdr.flags |= msg_info.dt.flags &
775						    CTL_FLAG_RDMA_MASK;
776			} else
777				sgl = (struct ctl_sg_entry *)
778					io->scsiio.kern_data_ptr;
779
780			for (i = msg_info.dt.sent_sg_entries, j = 0;
781			     i < (msg_info.dt.sent_sg_entries +
782			     msg_info.dt.cur_sg_entries); i++, j++) {
783				sgl[i].addr = msg_info.dt.sg_list[j].addr;
784				sgl[i].len = msg_info.dt.sg_list[j].len;
785
786#if 0
787				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
788				       __func__,
789				       msg_info.dt.sg_list[j].addr,
790				       msg_info.dt.sg_list[j].len,
791				       sgl[i].addr, sgl[i].len, j, i);
792#endif
793			}
794#if 0
795			memcpy(&sgl[msg_info.dt.sent_sg_entries],
796			       msg_info.dt.sg_list,
797			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
798#endif
799
800			/*
801			 * If this is the last piece of the I/O, we've got
802			 * the full S/G list.  Queue processing in the thread.
803			 * Otherwise wait for the next piece.
804			 */
805			if (msg_info.dt.sg_last != 0)
806				ctl_enqueue_isc(io);
807			break;
808		}
809		/* Performed on the Serializing (primary) SC, XFER mode only */
810		case CTL_MSG_DATAMOVE_DONE: {
811			if (msg_info.hdr.serializing_sc == NULL) {
812				printf("%s: serializing_sc == NULL!\n",
813				       __func__);
814				/* XXX KDM now what? */
815				break;
816			}
817			/*
818			 * We grab the sense information here in case
819			 * there was a failure, so we can return status
820			 * back to the initiator.
821			 */
822			io = msg_info.hdr.serializing_sc;
823			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
824			io->io_hdr.status = msg_info.hdr.status;
825			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
826			io->scsiio.sense_len = msg_info.scsi.sense_len;
827			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
828			io->io_hdr.port_status = msg_info.scsi.fetd_status;
829			io->scsiio.residual = msg_info.scsi.residual;
830			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
831			       sizeof(io->scsiio.sense_data));
832			ctl_enqueue_isc(io);
833			break;
834		}
835
836		/* Preformed on Originating SC, SER_ONLY mode */
837		case CTL_MSG_R2R:
838			io = msg_info.hdr.original_sc;
839			if (io == NULL) {
840				printf("%s: Major Bummer\n", __func__);
841				return;
842			} else {
843#if 0
844				printf("pOrig %x\n",(int) ctsio);
845#endif
846			}
847			io->io_hdr.msg_type = CTL_MSG_R2R;
848			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
849			ctl_enqueue_isc(io);
850			break;
851
852		/*
853		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
854		 * mode.
855		 * Performed on the Originating (i.e. secondary) SC in XFER
856		 * mode
857		 */
858		case CTL_MSG_FINISH_IO:
859			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
860				ctl_isc_handler_finish_xfer(ctl_softc,
861							    &msg_info);
862			else
863				ctl_isc_handler_finish_ser_only(ctl_softc,
864								&msg_info);
865			break;
866
867		/* Preformed on Originating SC */
868		case CTL_MSG_BAD_JUJU:
869			io = msg_info.hdr.original_sc;
870			if (io == NULL) {
871				printf("%s: Bad JUJU!, original_sc is NULL!\n",
872				       __func__);
873				break;
874			}
875			ctl_copy_sense_data(&msg_info, io);
876			/*
877			 * IO should have already been cleaned up on other
878			 * SC so clear this flag so we won't send a message
879			 * back to finish the IO there.
880			 */
881			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
882			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
883
884			/* io = msg_info.hdr.serializing_sc; */
885			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
886			ctl_enqueue_isc(io);
887			break;
888
889		/* Handle resets sent from the other side */
890		case CTL_MSG_MANAGE_TASKS: {
891			struct ctl_taskio *taskio;
892			taskio = (struct ctl_taskio *)ctl_alloc_io(
893				(void *)ctl_softc->othersc_pool);
894			if (taskio == NULL) {
895				printf("ctl_isc_event_handler: can't allocate "
896				       "ctl_io!\n");
897				/* Bad Juju */
898				/* should I just call the proper reset func
899				   here??? */
900				goto bailout;
901			}
902			ctl_zero_io((union ctl_io *)taskio);
903			taskio->io_hdr.io_type = CTL_IO_TASK;
904			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
905			taskio->io_hdr.nexus = msg_info.hdr.nexus;
906			taskio->task_action = msg_info.task.task_action;
907			taskio->tag_num = msg_info.task.tag_num;
908			taskio->tag_type = msg_info.task.tag_type;
909#ifdef CTL_TIME_IO
910			taskio->io_hdr.start_time = time_uptime;
911			getbintime(&taskio->io_hdr.start_bt);
912#if 0
913			cs_prof_gettime(&taskio->io_hdr.start_ticks);
914#endif
915#endif /* CTL_TIME_IO */
916			ctl_run_task((union ctl_io *)taskio);
917			break;
918		}
919		/* Persistent Reserve action which needs attention */
920		case CTL_MSG_PERS_ACTION:
921			presio = (struct ctl_prio *)ctl_alloc_io(
922				(void *)ctl_softc->othersc_pool);
923			if (presio == NULL) {
924				printf("ctl_isc_event_handler: can't allocate "
925				       "ctl_io!\n");
926				/* Bad Juju */
927				/* Need to set busy and send msg back */
928				goto bailout;
929			}
930			ctl_zero_io((union ctl_io *)presio);
931			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
932			presio->pr_msg = msg_info.pr;
933			ctl_enqueue_isc((union ctl_io *)presio);
934			break;
935		case CTL_MSG_SYNC_FE:
936			rcv_sync_msg = 1;
937			break;
938		default:
939		        printf("How did I get here?\n");
940		}
941	} else if (event == CTL_HA_EVT_MSG_SENT) {
942		if (param != CTL_HA_STATUS_SUCCESS) {
943			printf("Bad status from ctl_ha_msg_send status %d\n",
944			       param);
945		}
946		return;
947	} else if (event == CTL_HA_EVT_DISCONNECT) {
948		printf("CTL: Got a disconnect from Isc\n");
949		return;
950	} else {
951		printf("ctl_isc_event_handler: Unknown event %d\n", event);
952		return;
953	}
954
955bailout:
956	return;
957}
958
959static void
960ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
961{
962	struct scsi_sense_data *sense;
963
964	sense = &dest->scsiio.sense_data;
965	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
966	dest->scsiio.scsi_status = src->scsi.scsi_status;
967	dest->scsiio.sense_len = src->scsi.sense_len;
968	dest->io_hdr.status = src->hdr.status;
969}
970
971static int
972ctl_ha_state_sysctl(SYSCTL_HANDLER_ARGS)
973{
974	struct ctl_softc *softc = (struct ctl_softc *)arg1;
975	struct ctl_lun *lun;
976	int error, value, i;
977
978	if (softc->flags & CTL_FLAG_ACTIVE_SHELF)
979		value = 0;
980	else
981		value = 1;
982
983	error = sysctl_handle_int(oidp, &value, 0, req);
984	if ((error != 0) || (req->newptr == NULL))
985		return (error);
986
987	mtx_lock(&softc->ctl_lock);
988	if (value == 0)
989		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
990	else
991		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
992	STAILQ_FOREACH(lun, &softc->lun_list, links) {
993		mtx_lock(&lun->lun_lock);
994		for (i = 0; i < CTL_MAX_INITIATORS; i++)
995			lun->pending_ua[i] |= CTL_UA_ASYM_ACC_CHANGE;
996		mtx_unlock(&lun->lun_lock);
997	}
998	mtx_unlock(&softc->ctl_lock);
999	return (0);
1000}
1001
1002static int
1003ctl_init(void)
1004{
1005	struct ctl_softc *softc;
1006	struct ctl_io_pool *internal_pool, *emergency_pool, *other_pool;
1007	struct ctl_port *port;
1008	int i, error, retval;
1009	//int isc_retval;
1010
1011	retval = 0;
1012	ctl_pause_rtr = 0;
1013        rcv_sync_msg = 0;
1014
1015	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1016			       M_WAITOK | M_ZERO);
1017	softc = control_softc;
1018
1019	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1020			      "cam/ctl");
1021
1022	softc->dev->si_drv1 = softc;
1023
1024	/*
1025	 * By default, return a "bad LUN" peripheral qualifier for unknown
1026	 * LUNs.  The user can override this default using the tunable or
1027	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
1028	 */
1029	softc->inquiry_pq_no_lun = 1;
1030	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
1031			  &softc->inquiry_pq_no_lun);
1032	sysctl_ctx_init(&softc->sysctl_ctx);
1033	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1034		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1035		CTLFLAG_RD, 0, "CAM Target Layer");
1036
1037	if (softc->sysctl_tree == NULL) {
1038		printf("%s: unable to allocate sysctl tree\n", __func__);
1039		destroy_dev(softc->dev);
1040		free(control_softc, M_DEVBUF);
1041		control_softc = NULL;
1042		return (ENOMEM);
1043	}
1044
1045	SYSCTL_ADD_INT(&softc->sysctl_ctx,
1046		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1047		       "inquiry_pq_no_lun", CTLFLAG_RW,
1048		       &softc->inquiry_pq_no_lun, 0,
1049		       "Report no lun possible for invalid LUNs");
1050
1051	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1052	mtx_init(&softc->pool_lock, "CTL pool mutex", NULL, MTX_DEF);
1053	softc->open_count = 0;
1054
1055	/*
1056	 * Default to actually sending a SYNCHRONIZE CACHE command down to
1057	 * the drive.
1058	 */
1059	softc->flags = CTL_FLAG_REAL_SYNC;
1060
1061	/*
1062	 * In Copan's HA scheme, the "master" and "slave" roles are
1063	 * figured out through the slot the controller is in.  Although it
1064	 * is an active/active system, someone has to be in charge.
1065	 */
1066	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1067	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1068	    "HA head ID (0 - no HA)");
1069	if (softc->ha_id == 0) {
1070		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1071		softc->is_single = 1;
1072		softc->port_offset = 0;
1073	} else
1074		softc->port_offset = (softc->ha_id - 1) * CTL_MAX_PORTS;
1075	persis_offset = softc->port_offset * CTL_MAX_INIT_PER_PORT;
1076
1077	/*
1078	 * XXX KDM need to figure out where we want to get our target ID
1079	 * and WWID.  Is it different on each port?
1080	 */
1081	softc->target.id = 0;
1082	softc->target.wwid[0] = 0x12345678;
1083	softc->target.wwid[1] = 0x87654321;
1084	STAILQ_INIT(&softc->lun_list);
1085	STAILQ_INIT(&softc->pending_lun_queue);
1086	STAILQ_INIT(&softc->fe_list);
1087	STAILQ_INIT(&softc->port_list);
1088	STAILQ_INIT(&softc->be_list);
1089	STAILQ_INIT(&softc->io_pools);
1090	ctl_tpc_init(softc);
1091
1092	if (ctl_pool_create(softc, CTL_POOL_INTERNAL, CTL_POOL_ENTRIES_INTERNAL,
1093			    &internal_pool)!= 0){
1094		printf("ctl: can't allocate %d entry internal pool, "
1095		       "exiting\n", CTL_POOL_ENTRIES_INTERNAL);
1096		return (ENOMEM);
1097	}
1098
1099	if (ctl_pool_create(softc, CTL_POOL_EMERGENCY,
1100			    CTL_POOL_ENTRIES_EMERGENCY, &emergency_pool) != 0) {
1101		printf("ctl: can't allocate %d entry emergency pool, "
1102		       "exiting\n", CTL_POOL_ENTRIES_EMERGENCY);
1103		ctl_pool_free(internal_pool);
1104		return (ENOMEM);
1105	}
1106
1107	if (ctl_pool_create(softc, CTL_POOL_4OTHERSC, CTL_POOL_ENTRIES_OTHER_SC,
1108	                    &other_pool) != 0)
1109	{
1110		printf("ctl: can't allocate %d entry other SC pool, "
1111		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1112		ctl_pool_free(internal_pool);
1113		ctl_pool_free(emergency_pool);
1114		return (ENOMEM);
1115	}
1116
1117	softc->internal_pool = internal_pool;
1118	softc->emergency_pool = emergency_pool;
1119	softc->othersc_pool = other_pool;
1120
1121	if (worker_threads <= 0)
1122		worker_threads = max(1, mp_ncpus / 4);
1123	if (worker_threads > CTL_MAX_THREADS)
1124		worker_threads = CTL_MAX_THREADS;
1125
1126	for (i = 0; i < worker_threads; i++) {
1127		struct ctl_thread *thr = &softc->threads[i];
1128
1129		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1130		thr->ctl_softc = softc;
1131		STAILQ_INIT(&thr->incoming_queue);
1132		STAILQ_INIT(&thr->rtr_queue);
1133		STAILQ_INIT(&thr->done_queue);
1134		STAILQ_INIT(&thr->isc_queue);
1135
1136		error = kproc_kthread_add(ctl_work_thread, thr,
1137		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1138		if (error != 0) {
1139			printf("error creating CTL work thread!\n");
1140			ctl_pool_free(internal_pool);
1141			ctl_pool_free(emergency_pool);
1142			ctl_pool_free(other_pool);
1143			return (error);
1144		}
1145	}
1146	error = kproc_kthread_add(ctl_lun_thread, softc,
1147	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1148	if (error != 0) {
1149		printf("error creating CTL lun thread!\n");
1150		ctl_pool_free(internal_pool);
1151		ctl_pool_free(emergency_pool);
1152		ctl_pool_free(other_pool);
1153		return (error);
1154	}
1155	error = kproc_kthread_add(ctl_thresh_thread, softc,
1156	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1157	if (error != 0) {
1158		printf("error creating CTL threshold thread!\n");
1159		ctl_pool_free(internal_pool);
1160		ctl_pool_free(emergency_pool);
1161		ctl_pool_free(other_pool);
1162		return (error);
1163	}
1164	if (bootverbose)
1165		printf("ctl: CAM Target Layer loaded\n");
1166
1167	/*
1168	 * Initialize the ioctl front end.
1169	 */
1170	ctl_frontend_register(&ioctl_frontend);
1171	port = &softc->ioctl_info.port;
1172	port->frontend = &ioctl_frontend;
1173	sprintf(softc->ioctl_info.port_name, "ioctl");
1174	port->port_type = CTL_PORT_IOCTL;
1175	port->num_requested_ctl_io = 100;
1176	port->port_name = softc->ioctl_info.port_name;
1177	port->port_online = ctl_ioctl_online;
1178	port->port_offline = ctl_ioctl_offline;
1179	port->onoff_arg = &softc->ioctl_info;
1180	port->lun_enable = ctl_ioctl_lun_enable;
1181	port->lun_disable = ctl_ioctl_lun_disable;
1182	port->targ_lun_arg = &softc->ioctl_info;
1183	port->fe_datamove = ctl_ioctl_datamove;
1184	port->fe_done = ctl_ioctl_done;
1185	port->max_targets = 15;
1186	port->max_target_id = 15;
1187
1188	if (ctl_port_register(&softc->ioctl_info.port) != 0) {
1189		printf("ctl: ioctl front end registration failed, will "
1190		       "continue anyway\n");
1191	}
1192
1193	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1194	    OID_AUTO, "ha_state", CTLTYPE_INT | CTLFLAG_RWTUN,
1195	    softc, 0, ctl_ha_state_sysctl, "I", "HA state for this head");
1196
1197#ifdef CTL_IO_DELAY
1198	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1199		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1200		       sizeof(struct callout), CTL_TIMER_BYTES);
1201		return (EINVAL);
1202	}
1203#endif /* CTL_IO_DELAY */
1204
1205	return (0);
1206}
1207
1208void
1209ctl_shutdown(void)
1210{
1211	struct ctl_softc *softc;
1212	struct ctl_lun *lun, *next_lun;
1213	struct ctl_io_pool *pool;
1214
1215	softc = (struct ctl_softc *)control_softc;
1216
1217	if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1218		printf("ctl: ioctl front end deregistration failed\n");
1219
1220	mtx_lock(&softc->ctl_lock);
1221
1222	/*
1223	 * Free up each LUN.
1224	 */
1225	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1226		next_lun = STAILQ_NEXT(lun, links);
1227		ctl_free_lun(lun);
1228	}
1229
1230	mtx_unlock(&softc->ctl_lock);
1231
1232	ctl_frontend_deregister(&ioctl_frontend);
1233
1234	/*
1235	 * This will rip the rug out from under any FETDs or anyone else
1236	 * that has a pool allocated.  Since we increment our module
1237	 * refcount any time someone outside the main CTL module allocates
1238	 * a pool, we shouldn't have any problems here.  The user won't be
1239	 * able to unload the CTL module until client modules have
1240	 * successfully unloaded.
1241	 */
1242	while ((pool = STAILQ_FIRST(&softc->io_pools)) != NULL)
1243		ctl_pool_free(pool);
1244
1245#if 0
1246	ctl_shutdown_thread(softc->work_thread);
1247	mtx_destroy(&softc->queue_lock);
1248#endif
1249
1250	ctl_tpc_shutdown(softc);
1251	mtx_destroy(&softc->pool_lock);
1252	mtx_destroy(&softc->ctl_lock);
1253
1254	destroy_dev(softc->dev);
1255
1256	sysctl_ctx_free(&softc->sysctl_ctx);
1257
1258	free(control_softc, M_DEVBUF);
1259	control_softc = NULL;
1260
1261	if (bootverbose)
1262		printf("ctl: CAM Target Layer unloaded\n");
1263}
1264
1265static int
1266ctl_module_event_handler(module_t mod, int what, void *arg)
1267{
1268
1269	switch (what) {
1270	case MOD_LOAD:
1271		return (ctl_init());
1272	case MOD_UNLOAD:
1273		return (EBUSY);
1274	default:
1275		return (EOPNOTSUPP);
1276	}
1277}
1278
1279/*
1280 * XXX KDM should we do some access checks here?  Bump a reference count to
1281 * prevent a CTL module from being unloaded while someone has it open?
1282 */
1283static int
1284ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1285{
1286	return (0);
1287}
1288
1289static int
1290ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1291{
1292	return (0);
1293}
1294
1295int
1296ctl_port_enable(ctl_port_type port_type)
1297{
1298	struct ctl_softc *softc = control_softc;
1299	struct ctl_port *port;
1300
1301	if (softc->is_single == 0) {
1302		union ctl_ha_msg msg_info;
1303		int isc_retval;
1304
1305#if 0
1306		printf("%s: HA mode, synchronizing frontend enable\n",
1307		        __func__);
1308#endif
1309		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1310	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1311		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1312			printf("Sync msg send error retval %d\n", isc_retval);
1313		}
1314		if (!rcv_sync_msg) {
1315			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1316			        sizeof(msg_info), 1);
1317		}
1318#if 0
1319        	printf("CTL:Frontend Enable\n");
1320	} else {
1321		printf("%s: single mode, skipping frontend synchronization\n",
1322		        __func__);
1323#endif
1324	}
1325
1326	STAILQ_FOREACH(port, &softc->port_list, links) {
1327		if (port_type & port->port_type)
1328		{
1329#if 0
1330			printf("port %d\n", port->targ_port);
1331#endif
1332			ctl_port_online(port);
1333		}
1334	}
1335
1336	return (0);
1337}
1338
1339int
1340ctl_port_disable(ctl_port_type port_type)
1341{
1342	struct ctl_softc *softc;
1343	struct ctl_port *port;
1344
1345	softc = control_softc;
1346
1347	STAILQ_FOREACH(port, &softc->port_list, links) {
1348		if (port_type & port->port_type)
1349			ctl_port_offline(port);
1350	}
1351
1352	return (0);
1353}
1354
1355/*
1356 * Returns 0 for success, 1 for failure.
1357 * Currently the only failure mode is if there aren't enough entries
1358 * allocated.  So, in case of a failure, look at num_entries_dropped,
1359 * reallocate and try again.
1360 */
1361int
1362ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1363	      int *num_entries_filled, int *num_entries_dropped,
1364	      ctl_port_type port_type, int no_virtual)
1365{
1366	struct ctl_softc *softc;
1367	struct ctl_port *port;
1368	int entries_dropped, entries_filled;
1369	int retval;
1370	int i;
1371
1372	softc = control_softc;
1373
1374	retval = 0;
1375	entries_filled = 0;
1376	entries_dropped = 0;
1377
1378	i = 0;
1379	mtx_lock(&softc->ctl_lock);
1380	STAILQ_FOREACH(port, &softc->port_list, links) {
1381		struct ctl_port_entry *entry;
1382
1383		if ((port->port_type & port_type) == 0)
1384			continue;
1385
1386		if ((no_virtual != 0)
1387		 && (port->virtual_port != 0))
1388			continue;
1389
1390		if (entries_filled >= num_entries_alloced) {
1391			entries_dropped++;
1392			continue;
1393		}
1394		entry = &entries[i];
1395
1396		entry->port_type = port->port_type;
1397		strlcpy(entry->port_name, port->port_name,
1398			sizeof(entry->port_name));
1399		entry->physical_port = port->physical_port;
1400		entry->virtual_port = port->virtual_port;
1401		entry->wwnn = port->wwnn;
1402		entry->wwpn = port->wwpn;
1403
1404		i++;
1405		entries_filled++;
1406	}
1407
1408	mtx_unlock(&softc->ctl_lock);
1409
1410	if (entries_dropped > 0)
1411		retval = 1;
1412
1413	*num_entries_dropped = entries_dropped;
1414	*num_entries_filled = entries_filled;
1415
1416	return (retval);
1417}
1418
1419static void
1420ctl_ioctl_online(void *arg)
1421{
1422	struct ctl_ioctl_info *ioctl_info;
1423
1424	ioctl_info = (struct ctl_ioctl_info *)arg;
1425
1426	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1427}
1428
1429static void
1430ctl_ioctl_offline(void *arg)
1431{
1432	struct ctl_ioctl_info *ioctl_info;
1433
1434	ioctl_info = (struct ctl_ioctl_info *)arg;
1435
1436	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1437}
1438
1439/*
1440 * Remove an initiator by port number and initiator ID.
1441 * Returns 0 for success, -1 for failure.
1442 */
1443int
1444ctl_remove_initiator(struct ctl_port *port, int iid)
1445{
1446	struct ctl_softc *softc = control_softc;
1447
1448	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1449
1450	if (iid > CTL_MAX_INIT_PER_PORT) {
1451		printf("%s: initiator ID %u > maximun %u!\n",
1452		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1453		return (-1);
1454	}
1455
1456	mtx_lock(&softc->ctl_lock);
1457	port->wwpn_iid[iid].in_use--;
1458	port->wwpn_iid[iid].last_use = time_uptime;
1459	mtx_unlock(&softc->ctl_lock);
1460
1461	return (0);
1462}
1463
1464/*
1465 * Add an initiator to the initiator map.
1466 * Returns iid for success, < 0 for failure.
1467 */
1468int
1469ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1470{
1471	struct ctl_softc *softc = control_softc;
1472	time_t best_time;
1473	int i, best;
1474
1475	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1476
1477	if (iid >= CTL_MAX_INIT_PER_PORT) {
1478		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1479		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1480		free(name, M_CTL);
1481		return (-1);
1482	}
1483
1484	mtx_lock(&softc->ctl_lock);
1485
1486	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1487		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1488			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1489				iid = i;
1490				break;
1491			}
1492			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1493			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1494				iid = i;
1495				break;
1496			}
1497		}
1498	}
1499
1500	if (iid < 0) {
1501		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1502			if (port->wwpn_iid[i].in_use == 0 &&
1503			    port->wwpn_iid[i].wwpn == 0 &&
1504			    port->wwpn_iid[i].name == NULL) {
1505				iid = i;
1506				break;
1507			}
1508		}
1509	}
1510
1511	if (iid < 0) {
1512		best = -1;
1513		best_time = INT32_MAX;
1514		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1515			if (port->wwpn_iid[i].in_use == 0) {
1516				if (port->wwpn_iid[i].last_use < best_time) {
1517					best = i;
1518					best_time = port->wwpn_iid[i].last_use;
1519				}
1520			}
1521		}
1522		iid = best;
1523	}
1524
1525	if (iid < 0) {
1526		mtx_unlock(&softc->ctl_lock);
1527		free(name, M_CTL);
1528		return (-2);
1529	}
1530
1531	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1532		/*
1533		 * This is not an error yet.
1534		 */
1535		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1536#if 0
1537			printf("%s: port %d iid %u WWPN %#jx arrived"
1538			    " again\n", __func__, port->targ_port,
1539			    iid, (uintmax_t)wwpn);
1540#endif
1541			goto take;
1542		}
1543		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1544		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1545#if 0
1546			printf("%s: port %d iid %u name '%s' arrived"
1547			    " again\n", __func__, port->targ_port,
1548			    iid, name);
1549#endif
1550			goto take;
1551		}
1552
1553		/*
1554		 * This is an error, but what do we do about it?  The
1555		 * driver is telling us we have a new WWPN for this
1556		 * initiator ID, so we pretty much need to use it.
1557		 */
1558		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1559		    " but WWPN %#jx '%s' is still at that address\n",
1560		    __func__, port->targ_port, iid, wwpn, name,
1561		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1562		    port->wwpn_iid[iid].name);
1563
1564		/*
1565		 * XXX KDM clear have_ca and ua_pending on each LUN for
1566		 * this initiator.
1567		 */
1568	}
1569take:
1570	free(port->wwpn_iid[iid].name, M_CTL);
1571	port->wwpn_iid[iid].name = name;
1572	port->wwpn_iid[iid].wwpn = wwpn;
1573	port->wwpn_iid[iid].in_use++;
1574	mtx_unlock(&softc->ctl_lock);
1575
1576	return (iid);
1577}
1578
1579static int
1580ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1581{
1582	int len;
1583
1584	switch (port->port_type) {
1585	case CTL_PORT_FC:
1586	{
1587		struct scsi_transportid_fcp *id =
1588		    (struct scsi_transportid_fcp *)buf;
1589		if (port->wwpn_iid[iid].wwpn == 0)
1590			return (0);
1591		memset(id, 0, sizeof(*id));
1592		id->format_protocol = SCSI_PROTO_FC;
1593		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1594		return (sizeof(*id));
1595	}
1596	case CTL_PORT_ISCSI:
1597	{
1598		struct scsi_transportid_iscsi_port *id =
1599		    (struct scsi_transportid_iscsi_port *)buf;
1600		if (port->wwpn_iid[iid].name == NULL)
1601			return (0);
1602		memset(id, 0, 256);
1603		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1604		    SCSI_PROTO_ISCSI;
1605		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1606		len = roundup2(min(len, 252), 4);
1607		scsi_ulto2b(len, id->additional_length);
1608		return (sizeof(*id) + len);
1609	}
1610	case CTL_PORT_SAS:
1611	{
1612		struct scsi_transportid_sas *id =
1613		    (struct scsi_transportid_sas *)buf;
1614		if (port->wwpn_iid[iid].wwpn == 0)
1615			return (0);
1616		memset(id, 0, sizeof(*id));
1617		id->format_protocol = SCSI_PROTO_SAS;
1618		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1619		return (sizeof(*id));
1620	}
1621	default:
1622	{
1623		struct scsi_transportid_spi *id =
1624		    (struct scsi_transportid_spi *)buf;
1625		memset(id, 0, sizeof(*id));
1626		id->format_protocol = SCSI_PROTO_SPI;
1627		scsi_ulto2b(iid, id->scsi_addr);
1628		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1629		return (sizeof(*id));
1630	}
1631	}
1632}
1633
1634static int
1635ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1636{
1637	return (0);
1638}
1639
1640static int
1641ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1642{
1643	return (0);
1644}
1645
1646/*
1647 * Data movement routine for the CTL ioctl frontend port.
1648 */
1649static int
1650ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1651{
1652	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1653	struct ctl_sg_entry ext_entry, kern_entry;
1654	int ext_sglen, ext_sg_entries, kern_sg_entries;
1655	int ext_sg_start, ext_offset;
1656	int len_to_copy, len_copied;
1657	int kern_watermark, ext_watermark;
1658	int ext_sglist_malloced;
1659	int i, j;
1660
1661	ext_sglist_malloced = 0;
1662	ext_sg_start = 0;
1663	ext_offset = 0;
1664
1665	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1666
1667	/*
1668	 * If this flag is set, fake the data transfer.
1669	 */
1670	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1671		ctsio->ext_data_filled = ctsio->ext_data_len;
1672		goto bailout;
1673	}
1674
1675	/*
1676	 * To simplify things here, if we have a single buffer, stick it in
1677	 * a S/G entry and just make it a single entry S/G list.
1678	 */
1679	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1680		int len_seen;
1681
1682		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1683
1684		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1685							   M_WAITOK);
1686		ext_sglist_malloced = 1;
1687		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1688				   ext_sglen) != 0) {
1689			ctl_set_internal_failure(ctsio,
1690						 /*sks_valid*/ 0,
1691						 /*retry_count*/ 0);
1692			goto bailout;
1693		}
1694		ext_sg_entries = ctsio->ext_sg_entries;
1695		len_seen = 0;
1696		for (i = 0; i < ext_sg_entries; i++) {
1697			if ((len_seen + ext_sglist[i].len) >=
1698			     ctsio->ext_data_filled) {
1699				ext_sg_start = i;
1700				ext_offset = ctsio->ext_data_filled - len_seen;
1701				break;
1702			}
1703			len_seen += ext_sglist[i].len;
1704		}
1705	} else {
1706		ext_sglist = &ext_entry;
1707		ext_sglist->addr = ctsio->ext_data_ptr;
1708		ext_sglist->len = ctsio->ext_data_len;
1709		ext_sg_entries = 1;
1710		ext_sg_start = 0;
1711		ext_offset = ctsio->ext_data_filled;
1712	}
1713
1714	if (ctsio->kern_sg_entries > 0) {
1715		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1716		kern_sg_entries = ctsio->kern_sg_entries;
1717	} else {
1718		kern_sglist = &kern_entry;
1719		kern_sglist->addr = ctsio->kern_data_ptr;
1720		kern_sglist->len = ctsio->kern_data_len;
1721		kern_sg_entries = 1;
1722	}
1723
1724
1725	kern_watermark = 0;
1726	ext_watermark = ext_offset;
1727	len_copied = 0;
1728	for (i = ext_sg_start, j = 0;
1729	     i < ext_sg_entries && j < kern_sg_entries;) {
1730		uint8_t *ext_ptr, *kern_ptr;
1731
1732		len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1733				      kern_sglist[j].len - kern_watermark);
1734
1735		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1736		ext_ptr = ext_ptr + ext_watermark;
1737		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1738			/*
1739			 * XXX KDM fix this!
1740			 */
1741			panic("need to implement bus address support");
1742#if 0
1743			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1744#endif
1745		} else
1746			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1747		kern_ptr = kern_ptr + kern_watermark;
1748
1749		kern_watermark += len_to_copy;
1750		ext_watermark += len_to_copy;
1751
1752		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1753		     CTL_FLAG_DATA_IN) {
1754			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1755					 "bytes to user\n", len_to_copy));
1756			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1757					 "to %p\n", kern_ptr, ext_ptr));
1758			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1759				ctl_set_internal_failure(ctsio,
1760							 /*sks_valid*/ 0,
1761							 /*retry_count*/ 0);
1762				goto bailout;
1763			}
1764		} else {
1765			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1766					 "bytes from user\n", len_to_copy));
1767			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1768					 "to %p\n", ext_ptr, kern_ptr));
1769			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1770				ctl_set_internal_failure(ctsio,
1771							 /*sks_valid*/ 0,
1772							 /*retry_count*/0);
1773				goto bailout;
1774			}
1775		}
1776
1777		len_copied += len_to_copy;
1778
1779		if (ext_sglist[i].len == ext_watermark) {
1780			i++;
1781			ext_watermark = 0;
1782		}
1783
1784		if (kern_sglist[j].len == kern_watermark) {
1785			j++;
1786			kern_watermark = 0;
1787		}
1788	}
1789
1790	ctsio->ext_data_filled += len_copied;
1791
1792	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1793			 "kern_sg_entries: %d\n", ext_sg_entries,
1794			 kern_sg_entries));
1795	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1796			 "kern_data_len = %d\n", ctsio->ext_data_len,
1797			 ctsio->kern_data_len));
1798
1799
1800	/* XXX KDM set residual?? */
1801bailout:
1802
1803	if (ext_sglist_malloced != 0)
1804		free(ext_sglist, M_CTL);
1805
1806	return (CTL_RETVAL_COMPLETE);
1807}
1808
1809/*
1810 * Serialize a command that went down the "wrong" side, and so was sent to
1811 * this controller for execution.  The logic is a little different than the
1812 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1813 * sent back to the other side, but in the success case, we execute the
1814 * command on this side (XFER mode) or tell the other side to execute it
1815 * (SER_ONLY mode).
1816 */
1817static int
1818ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1819{
1820	struct ctl_softc *ctl_softc;
1821	union ctl_ha_msg msg_info;
1822	struct ctl_lun *lun;
1823	int retval = 0;
1824	uint32_t targ_lun;
1825
1826	ctl_softc = control_softc;
1827
1828	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1829	lun = ctl_softc->ctl_luns[targ_lun];
1830	if (lun==NULL)
1831	{
1832		/*
1833		 * Why isn't LUN defined? The other side wouldn't
1834		 * send a cmd if the LUN is undefined.
1835		 */
1836		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1837
1838		/* "Logical unit not supported" */
1839		ctl_set_sense_data(&msg_info.scsi.sense_data,
1840				   lun,
1841				   /*sense_format*/SSD_TYPE_NONE,
1842				   /*current_error*/ 1,
1843				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1844				   /*asc*/ 0x25,
1845				   /*ascq*/ 0x00,
1846				   SSD_ELEM_NONE);
1847
1848		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1849		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1850		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1851		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1852		msg_info.hdr.serializing_sc = NULL;
1853		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1854	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1855				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1856		}
1857		return(1);
1858
1859	}
1860
1861	mtx_lock(&lun->lun_lock);
1862    	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1863
1864	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1865		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1866		 ooa_links))) {
1867	case CTL_ACTION_BLOCK:
1868		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1869		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1870				  blocked_links);
1871		break;
1872	case CTL_ACTION_PASS:
1873	case CTL_ACTION_SKIP:
1874		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1875			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1876			ctl_enqueue_rtr((union ctl_io *)ctsio);
1877		} else {
1878
1879			/* send msg back to other side */
1880			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1881			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1882			msg_info.hdr.msg_type = CTL_MSG_R2R;
1883#if 0
1884			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1885#endif
1886		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1887			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1888			}
1889		}
1890		break;
1891	case CTL_ACTION_OVERLAP:
1892		/* OVERLAPPED COMMANDS ATTEMPTED */
1893		ctl_set_sense_data(&msg_info.scsi.sense_data,
1894				   lun,
1895				   /*sense_format*/SSD_TYPE_NONE,
1896				   /*current_error*/ 1,
1897				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1898				   /*asc*/ 0x4E,
1899				   /*ascq*/ 0x00,
1900				   SSD_ELEM_NONE);
1901
1902		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1903		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1904		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1905		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1906		msg_info.hdr.serializing_sc = NULL;
1907		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1908#if 0
1909		printf("BAD JUJU:Major Bummer Overlap\n");
1910#endif
1911		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1912		retval = 1;
1913		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1914		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1915		}
1916		break;
1917	case CTL_ACTION_OVERLAP_TAG:
1918		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1919		ctl_set_sense_data(&msg_info.scsi.sense_data,
1920				   lun,
1921				   /*sense_format*/SSD_TYPE_NONE,
1922				   /*current_error*/ 1,
1923				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1924				   /*asc*/ 0x4D,
1925				   /*ascq*/ ctsio->tag_num & 0xff,
1926				   SSD_ELEM_NONE);
1927
1928		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1929		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1930		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1931		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1932		msg_info.hdr.serializing_sc = NULL;
1933		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1934#if 0
1935		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1936#endif
1937		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1938		retval = 1;
1939		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1940		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1941		}
1942		break;
1943	case CTL_ACTION_ERROR:
1944	default:
1945		/* "Internal target failure" */
1946		ctl_set_sense_data(&msg_info.scsi.sense_data,
1947				   lun,
1948				   /*sense_format*/SSD_TYPE_NONE,
1949				   /*current_error*/ 1,
1950				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1951				   /*asc*/ 0x44,
1952				   /*ascq*/ 0x00,
1953				   SSD_ELEM_NONE);
1954
1955		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1956		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1957		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1958		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1959		msg_info.hdr.serializing_sc = NULL;
1960		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1961#if 0
1962		printf("BAD JUJU:Major Bummer HW Error\n");
1963#endif
1964		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1965		retval = 1;
1966		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1967		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1968		}
1969		break;
1970	}
1971	mtx_unlock(&lun->lun_lock);
1972	return (retval);
1973}
1974
1975static int
1976ctl_ioctl_submit_wait(union ctl_io *io)
1977{
1978	struct ctl_fe_ioctl_params params;
1979	ctl_fe_ioctl_state last_state;
1980	int done, retval;
1981
1982	retval = 0;
1983
1984	bzero(&params, sizeof(params));
1985
1986	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1987	cv_init(&params.sem, "ctlioccv");
1988	params.state = CTL_IOCTL_INPROG;
1989	last_state = params.state;
1990
1991	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1992
1993	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1994
1995	/* This shouldn't happen */
1996	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1997		return (retval);
1998
1999	done = 0;
2000
2001	do {
2002		mtx_lock(&params.ioctl_mtx);
2003		/*
2004		 * Check the state here, and don't sleep if the state has
2005		 * already changed (i.e. wakeup has already occured, but we
2006		 * weren't waiting yet).
2007		 */
2008		if (params.state == last_state) {
2009			/* XXX KDM cv_wait_sig instead? */
2010			cv_wait(&params.sem, &params.ioctl_mtx);
2011		}
2012		last_state = params.state;
2013
2014		switch (params.state) {
2015		case CTL_IOCTL_INPROG:
2016			/* Why did we wake up? */
2017			/* XXX KDM error here? */
2018			mtx_unlock(&params.ioctl_mtx);
2019			break;
2020		case CTL_IOCTL_DATAMOVE:
2021			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
2022
2023			/*
2024			 * change last_state back to INPROG to avoid
2025			 * deadlock on subsequent data moves.
2026			 */
2027			params.state = last_state = CTL_IOCTL_INPROG;
2028
2029			mtx_unlock(&params.ioctl_mtx);
2030			ctl_ioctl_do_datamove(&io->scsiio);
2031			/*
2032			 * Note that in some cases, most notably writes,
2033			 * this will queue the I/O and call us back later.
2034			 * In other cases, generally reads, this routine
2035			 * will immediately call back and wake us up,
2036			 * probably using our own context.
2037			 */
2038			io->scsiio.be_move_done(io);
2039			break;
2040		case CTL_IOCTL_DONE:
2041			mtx_unlock(&params.ioctl_mtx);
2042			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
2043			done = 1;
2044			break;
2045		default:
2046			mtx_unlock(&params.ioctl_mtx);
2047			/* XXX KDM error here? */
2048			break;
2049		}
2050	} while (done == 0);
2051
2052	mtx_destroy(&params.ioctl_mtx);
2053	cv_destroy(&params.sem);
2054
2055	return (CTL_RETVAL_COMPLETE);
2056}
2057
2058static void
2059ctl_ioctl_datamove(union ctl_io *io)
2060{
2061	struct ctl_fe_ioctl_params *params;
2062
2063	params = (struct ctl_fe_ioctl_params *)
2064		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2065
2066	mtx_lock(&params->ioctl_mtx);
2067	params->state = CTL_IOCTL_DATAMOVE;
2068	cv_broadcast(&params->sem);
2069	mtx_unlock(&params->ioctl_mtx);
2070}
2071
2072static void
2073ctl_ioctl_done(union ctl_io *io)
2074{
2075	struct ctl_fe_ioctl_params *params;
2076
2077	params = (struct ctl_fe_ioctl_params *)
2078		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2079
2080	mtx_lock(&params->ioctl_mtx);
2081	params->state = CTL_IOCTL_DONE;
2082	cv_broadcast(&params->sem);
2083	mtx_unlock(&params->ioctl_mtx);
2084}
2085
2086static void
2087ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2088{
2089	struct ctl_fe_ioctl_startstop_info *sd_info;
2090
2091	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2092
2093	sd_info->hs_info.status = metatask->status;
2094	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2095	sd_info->hs_info.luns_complete =
2096		metatask->taskinfo.startstop.luns_complete;
2097	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2098
2099	cv_broadcast(&sd_info->sem);
2100}
2101
2102static void
2103ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2104{
2105	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2106
2107	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2108
2109	mtx_lock(fe_bbr_info->lock);
2110	fe_bbr_info->bbr_info->status = metatask->status;
2111	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2112	fe_bbr_info->wakeup_done = 1;
2113	mtx_unlock(fe_bbr_info->lock);
2114
2115	cv_broadcast(&fe_bbr_info->sem);
2116}
2117
2118/*
2119 * Returns 0 for success, errno for failure.
2120 */
2121static int
2122ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2123		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2124{
2125	union ctl_io *io;
2126	int retval;
2127
2128	retval = 0;
2129
2130	mtx_lock(&lun->lun_lock);
2131	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2132	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2133	     ooa_links)) {
2134		struct ctl_ooa_entry *entry;
2135
2136		/*
2137		 * If we've got more than we can fit, just count the
2138		 * remaining entries.
2139		 */
2140		if (*cur_fill_num >= ooa_hdr->alloc_num)
2141			continue;
2142
2143		entry = &kern_entries[*cur_fill_num];
2144
2145		entry->tag_num = io->scsiio.tag_num;
2146		entry->lun_num = lun->lun;
2147#ifdef CTL_TIME_IO
2148		entry->start_bt = io->io_hdr.start_bt;
2149#endif
2150		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2151		entry->cdb_len = io->scsiio.cdb_len;
2152		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2153			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2154
2155		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2156			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2157
2158		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2159			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2160
2161		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2162			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2163
2164		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2165			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2166	}
2167	mtx_unlock(&lun->lun_lock);
2168
2169	return (retval);
2170}
2171
2172static void *
2173ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2174		 size_t error_str_len)
2175{
2176	void *kptr;
2177
2178	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2179
2180	if (copyin(user_addr, kptr, len) != 0) {
2181		snprintf(error_str, error_str_len, "Error copying %d bytes "
2182			 "from user address %p to kernel address %p", len,
2183			 user_addr, kptr);
2184		free(kptr, M_CTL);
2185		return (NULL);
2186	}
2187
2188	return (kptr);
2189}
2190
2191static void
2192ctl_free_args(int num_args, struct ctl_be_arg *args)
2193{
2194	int i;
2195
2196	if (args == NULL)
2197		return;
2198
2199	for (i = 0; i < num_args; i++) {
2200		free(args[i].kname, M_CTL);
2201		free(args[i].kvalue, M_CTL);
2202	}
2203
2204	free(args, M_CTL);
2205}
2206
2207static struct ctl_be_arg *
2208ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2209		char *error_str, size_t error_str_len)
2210{
2211	struct ctl_be_arg *args;
2212	int i;
2213
2214	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2215				error_str, error_str_len);
2216
2217	if (args == NULL)
2218		goto bailout;
2219
2220	for (i = 0; i < num_args; i++) {
2221		args[i].kname = NULL;
2222		args[i].kvalue = NULL;
2223	}
2224
2225	for (i = 0; i < num_args; i++) {
2226		uint8_t *tmpptr;
2227
2228		args[i].kname = ctl_copyin_alloc(args[i].name,
2229			args[i].namelen, error_str, error_str_len);
2230		if (args[i].kname == NULL)
2231			goto bailout;
2232
2233		if (args[i].kname[args[i].namelen - 1] != '\0') {
2234			snprintf(error_str, error_str_len, "Argument %d "
2235				 "name is not NUL-terminated", i);
2236			goto bailout;
2237		}
2238
2239		if (args[i].flags & CTL_BEARG_RD) {
2240			tmpptr = ctl_copyin_alloc(args[i].value,
2241				args[i].vallen, error_str, error_str_len);
2242			if (tmpptr == NULL)
2243				goto bailout;
2244			if ((args[i].flags & CTL_BEARG_ASCII)
2245			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2246				snprintf(error_str, error_str_len, "Argument "
2247				    "%d value is not NUL-terminated", i);
2248				goto bailout;
2249			}
2250			args[i].kvalue = tmpptr;
2251		} else {
2252			args[i].kvalue = malloc(args[i].vallen,
2253			    M_CTL, M_WAITOK | M_ZERO);
2254		}
2255	}
2256
2257	return (args);
2258bailout:
2259
2260	ctl_free_args(num_args, args);
2261
2262	return (NULL);
2263}
2264
2265static void
2266ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2267{
2268	int i;
2269
2270	for (i = 0; i < num_args; i++) {
2271		if (args[i].flags & CTL_BEARG_WR)
2272			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2273	}
2274}
2275
2276/*
2277 * Escape characters that are illegal or not recommended in XML.
2278 */
2279int
2280ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2281{
2282	char *end = str + size;
2283	int retval;
2284
2285	retval = 0;
2286
2287	for (; *str && str < end; str++) {
2288		switch (*str) {
2289		case '&':
2290			retval = sbuf_printf(sb, "&amp;");
2291			break;
2292		case '>':
2293			retval = sbuf_printf(sb, "&gt;");
2294			break;
2295		case '<':
2296			retval = sbuf_printf(sb, "&lt;");
2297			break;
2298		default:
2299			retval = sbuf_putc(sb, *str);
2300			break;
2301		}
2302
2303		if (retval != 0)
2304			break;
2305
2306	}
2307
2308	return (retval);
2309}
2310
2311static void
2312ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2313{
2314	struct scsi_vpd_id_descriptor *desc;
2315	int i;
2316
2317	if (id == NULL || id->len < 4)
2318		return;
2319	desc = (struct scsi_vpd_id_descriptor *)id->data;
2320	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2321	case SVPD_ID_TYPE_T10:
2322		sbuf_printf(sb, "t10.");
2323		break;
2324	case SVPD_ID_TYPE_EUI64:
2325		sbuf_printf(sb, "eui.");
2326		break;
2327	case SVPD_ID_TYPE_NAA:
2328		sbuf_printf(sb, "naa.");
2329		break;
2330	case SVPD_ID_TYPE_SCSI_NAME:
2331		break;
2332	}
2333	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2334	case SVPD_ID_CODESET_BINARY:
2335		for (i = 0; i < desc->length; i++)
2336			sbuf_printf(sb, "%02x", desc->identifier[i]);
2337		break;
2338	case SVPD_ID_CODESET_ASCII:
2339		sbuf_printf(sb, "%.*s", (int)desc->length,
2340		    (char *)desc->identifier);
2341		break;
2342	case SVPD_ID_CODESET_UTF8:
2343		sbuf_printf(sb, "%s", (char *)desc->identifier);
2344		break;
2345	}
2346}
2347
2348static int
2349ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2350	  struct thread *td)
2351{
2352	struct ctl_softc *softc;
2353	int retval;
2354
2355	softc = control_softc;
2356
2357	retval = 0;
2358
2359	switch (cmd) {
2360	case CTL_IO: {
2361		union ctl_io *io;
2362		void *pool_tmp;
2363
2364		/*
2365		 * If we haven't been "enabled", don't allow any SCSI I/O
2366		 * to this FETD.
2367		 */
2368		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2369			retval = EPERM;
2370			break;
2371		}
2372
2373		io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2374		if (io == NULL) {
2375			printf("ctl_ioctl: can't allocate ctl_io!\n");
2376			retval = ENOSPC;
2377			break;
2378		}
2379
2380		/*
2381		 * Need to save the pool reference so it doesn't get
2382		 * spammed by the user's ctl_io.
2383		 */
2384		pool_tmp = io->io_hdr.pool;
2385
2386		memcpy(io, (void *)addr, sizeof(*io));
2387
2388		io->io_hdr.pool = pool_tmp;
2389		/*
2390		 * No status yet, so make sure the status is set properly.
2391		 */
2392		io->io_hdr.status = CTL_STATUS_NONE;
2393
2394		/*
2395		 * The user sets the initiator ID, target and LUN IDs.
2396		 */
2397		io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2398		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2399		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2400		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2401			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2402
2403		retval = ctl_ioctl_submit_wait(io);
2404
2405		if (retval != 0) {
2406			ctl_free_io(io);
2407			break;
2408		}
2409
2410		memcpy((void *)addr, io, sizeof(*io));
2411
2412		/* return this to our pool */
2413		ctl_free_io(io);
2414
2415		break;
2416	}
2417	case CTL_ENABLE_PORT:
2418	case CTL_DISABLE_PORT:
2419	case CTL_SET_PORT_WWNS: {
2420		struct ctl_port *port;
2421		struct ctl_port_entry *entry;
2422
2423		entry = (struct ctl_port_entry *)addr;
2424
2425		mtx_lock(&softc->ctl_lock);
2426		STAILQ_FOREACH(port, &softc->port_list, links) {
2427			int action, done;
2428
2429			action = 0;
2430			done = 0;
2431
2432			if ((entry->port_type == CTL_PORT_NONE)
2433			 && (entry->targ_port == port->targ_port)) {
2434				/*
2435				 * If the user only wants to enable or
2436				 * disable or set WWNs on a specific port,
2437				 * do the operation and we're done.
2438				 */
2439				action = 1;
2440				done = 1;
2441			} else if (entry->port_type & port->port_type) {
2442				/*
2443				 * Compare the user's type mask with the
2444				 * particular frontend type to see if we
2445				 * have a match.
2446				 */
2447				action = 1;
2448				done = 0;
2449
2450				/*
2451				 * Make sure the user isn't trying to set
2452				 * WWNs on multiple ports at the same time.
2453				 */
2454				if (cmd == CTL_SET_PORT_WWNS) {
2455					printf("%s: Can't set WWNs on "
2456					       "multiple ports\n", __func__);
2457					retval = EINVAL;
2458					break;
2459				}
2460			}
2461			if (action != 0) {
2462				/*
2463				 * XXX KDM we have to drop the lock here,
2464				 * because the online/offline operations
2465				 * can potentially block.  We need to
2466				 * reference count the frontends so they
2467				 * can't go away,
2468				 */
2469				mtx_unlock(&softc->ctl_lock);
2470
2471				if (cmd == CTL_ENABLE_PORT) {
2472					struct ctl_lun *lun;
2473
2474					STAILQ_FOREACH(lun, &softc->lun_list,
2475						       links) {
2476						port->lun_enable(port->targ_lun_arg,
2477						    lun->target,
2478						    lun->lun);
2479					}
2480
2481					ctl_port_online(port);
2482				} else if (cmd == CTL_DISABLE_PORT) {
2483					struct ctl_lun *lun;
2484
2485					ctl_port_offline(port);
2486
2487					STAILQ_FOREACH(lun, &softc->lun_list,
2488						       links) {
2489						port->lun_disable(
2490						    port->targ_lun_arg,
2491						    lun->target,
2492						    lun->lun);
2493					}
2494				}
2495
2496				mtx_lock(&softc->ctl_lock);
2497
2498				if (cmd == CTL_SET_PORT_WWNS)
2499					ctl_port_set_wwns(port,
2500					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2501					    1 : 0, entry->wwnn,
2502					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2503					    1 : 0, entry->wwpn);
2504			}
2505			if (done != 0)
2506				break;
2507		}
2508		mtx_unlock(&softc->ctl_lock);
2509		break;
2510	}
2511	case CTL_GET_PORT_LIST: {
2512		struct ctl_port *port;
2513		struct ctl_port_list *list;
2514		int i;
2515
2516		list = (struct ctl_port_list *)addr;
2517
2518		if (list->alloc_len != (list->alloc_num *
2519		    sizeof(struct ctl_port_entry))) {
2520			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2521			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2522			       "%zu\n", __func__, list->alloc_len,
2523			       list->alloc_num, sizeof(struct ctl_port_entry));
2524			retval = EINVAL;
2525			break;
2526		}
2527		list->fill_len = 0;
2528		list->fill_num = 0;
2529		list->dropped_num = 0;
2530		i = 0;
2531		mtx_lock(&softc->ctl_lock);
2532		STAILQ_FOREACH(port, &softc->port_list, links) {
2533			struct ctl_port_entry entry, *list_entry;
2534
2535			if (list->fill_num >= list->alloc_num) {
2536				list->dropped_num++;
2537				continue;
2538			}
2539
2540			entry.port_type = port->port_type;
2541			strlcpy(entry.port_name, port->port_name,
2542				sizeof(entry.port_name));
2543			entry.targ_port = port->targ_port;
2544			entry.physical_port = port->physical_port;
2545			entry.virtual_port = port->virtual_port;
2546			entry.wwnn = port->wwnn;
2547			entry.wwpn = port->wwpn;
2548			if (port->status & CTL_PORT_STATUS_ONLINE)
2549				entry.online = 1;
2550			else
2551				entry.online = 0;
2552
2553			list_entry = &list->entries[i];
2554
2555			retval = copyout(&entry, list_entry, sizeof(entry));
2556			if (retval != 0) {
2557				printf("%s: CTL_GET_PORT_LIST: copyout "
2558				       "returned %d\n", __func__, retval);
2559				break;
2560			}
2561			i++;
2562			list->fill_num++;
2563			list->fill_len += sizeof(entry);
2564		}
2565		mtx_unlock(&softc->ctl_lock);
2566
2567		/*
2568		 * If this is non-zero, we had a copyout fault, so there's
2569		 * probably no point in attempting to set the status inside
2570		 * the structure.
2571		 */
2572		if (retval != 0)
2573			break;
2574
2575		if (list->dropped_num > 0)
2576			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2577		else
2578			list->status = CTL_PORT_LIST_OK;
2579		break;
2580	}
2581	case CTL_DUMP_OOA: {
2582		struct ctl_lun *lun;
2583		union ctl_io *io;
2584		char printbuf[128];
2585		struct sbuf sb;
2586
2587		mtx_lock(&softc->ctl_lock);
2588		printf("Dumping OOA queues:\n");
2589		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2590			mtx_lock(&lun->lun_lock);
2591			for (io = (union ctl_io *)TAILQ_FIRST(
2592			     &lun->ooa_queue); io != NULL;
2593			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2594			     ooa_links)) {
2595				sbuf_new(&sb, printbuf, sizeof(printbuf),
2596					 SBUF_FIXEDLEN);
2597				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2598					    (intmax_t)lun->lun,
2599					    io->scsiio.tag_num,
2600					    (io->io_hdr.flags &
2601					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2602					    (io->io_hdr.flags &
2603					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2604					    (io->io_hdr.flags &
2605					    CTL_FLAG_ABORT) ? " ABORT" : "",
2606			                    (io->io_hdr.flags &
2607		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2608				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2609				sbuf_finish(&sb);
2610				printf("%s\n", sbuf_data(&sb));
2611			}
2612			mtx_unlock(&lun->lun_lock);
2613		}
2614		printf("OOA queues dump done\n");
2615		mtx_unlock(&softc->ctl_lock);
2616		break;
2617	}
2618	case CTL_GET_OOA: {
2619		struct ctl_lun *lun;
2620		struct ctl_ooa *ooa_hdr;
2621		struct ctl_ooa_entry *entries;
2622		uint32_t cur_fill_num;
2623
2624		ooa_hdr = (struct ctl_ooa *)addr;
2625
2626		if ((ooa_hdr->alloc_len == 0)
2627		 || (ooa_hdr->alloc_num == 0)) {
2628			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2629			       "must be non-zero\n", __func__,
2630			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2631			retval = EINVAL;
2632			break;
2633		}
2634
2635		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2636		    sizeof(struct ctl_ooa_entry))) {
2637			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2638			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2639			       __func__, ooa_hdr->alloc_len,
2640			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2641			retval = EINVAL;
2642			break;
2643		}
2644
2645		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2646		if (entries == NULL) {
2647			printf("%s: could not allocate %d bytes for OOA "
2648			       "dump\n", __func__, ooa_hdr->alloc_len);
2649			retval = ENOMEM;
2650			break;
2651		}
2652
2653		mtx_lock(&softc->ctl_lock);
2654		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2655		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2656		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2657			mtx_unlock(&softc->ctl_lock);
2658			free(entries, M_CTL);
2659			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2660			       __func__, (uintmax_t)ooa_hdr->lun_num);
2661			retval = EINVAL;
2662			break;
2663		}
2664
2665		cur_fill_num = 0;
2666
2667		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2668			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2669				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2670					ooa_hdr, entries);
2671				if (retval != 0)
2672					break;
2673			}
2674			if (retval != 0) {
2675				mtx_unlock(&softc->ctl_lock);
2676				free(entries, M_CTL);
2677				break;
2678			}
2679		} else {
2680			lun = softc->ctl_luns[ooa_hdr->lun_num];
2681
2682			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2683						    entries);
2684		}
2685		mtx_unlock(&softc->ctl_lock);
2686
2687		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2688		ooa_hdr->fill_len = ooa_hdr->fill_num *
2689			sizeof(struct ctl_ooa_entry);
2690		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2691		if (retval != 0) {
2692			printf("%s: error copying out %d bytes for OOA dump\n",
2693			       __func__, ooa_hdr->fill_len);
2694		}
2695
2696		getbintime(&ooa_hdr->cur_bt);
2697
2698		if (cur_fill_num > ooa_hdr->alloc_num) {
2699			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2700			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2701		} else {
2702			ooa_hdr->dropped_num = 0;
2703			ooa_hdr->status = CTL_OOA_OK;
2704		}
2705
2706		free(entries, M_CTL);
2707		break;
2708	}
2709	case CTL_CHECK_OOA: {
2710		union ctl_io *io;
2711		struct ctl_lun *lun;
2712		struct ctl_ooa_info *ooa_info;
2713
2714
2715		ooa_info = (struct ctl_ooa_info *)addr;
2716
2717		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2718			ooa_info->status = CTL_OOA_INVALID_LUN;
2719			break;
2720		}
2721		mtx_lock(&softc->ctl_lock);
2722		lun = softc->ctl_luns[ooa_info->lun_id];
2723		if (lun == NULL) {
2724			mtx_unlock(&softc->ctl_lock);
2725			ooa_info->status = CTL_OOA_INVALID_LUN;
2726			break;
2727		}
2728		mtx_lock(&lun->lun_lock);
2729		mtx_unlock(&softc->ctl_lock);
2730		ooa_info->num_entries = 0;
2731		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2732		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2733		     &io->io_hdr, ooa_links)) {
2734			ooa_info->num_entries++;
2735		}
2736		mtx_unlock(&lun->lun_lock);
2737
2738		ooa_info->status = CTL_OOA_SUCCESS;
2739
2740		break;
2741	}
2742	case CTL_HARD_START:
2743	case CTL_HARD_STOP: {
2744		struct ctl_fe_ioctl_startstop_info ss_info;
2745		struct cfi_metatask *metatask;
2746		struct mtx hs_mtx;
2747
2748		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2749
2750		cv_init(&ss_info.sem, "hard start/stop cv" );
2751
2752		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2753		if (metatask == NULL) {
2754			retval = ENOMEM;
2755			mtx_destroy(&hs_mtx);
2756			break;
2757		}
2758
2759		if (cmd == CTL_HARD_START)
2760			metatask->tasktype = CFI_TASK_STARTUP;
2761		else
2762			metatask->tasktype = CFI_TASK_SHUTDOWN;
2763
2764		metatask->callback = ctl_ioctl_hard_startstop_callback;
2765		metatask->callback_arg = &ss_info;
2766
2767		cfi_action(metatask);
2768
2769		/* Wait for the callback */
2770		mtx_lock(&hs_mtx);
2771		cv_wait_sig(&ss_info.sem, &hs_mtx);
2772		mtx_unlock(&hs_mtx);
2773
2774		/*
2775		 * All information has been copied from the metatask by the
2776		 * time cv_broadcast() is called, so we free the metatask here.
2777		 */
2778		cfi_free_metatask(metatask);
2779
2780		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2781
2782		mtx_destroy(&hs_mtx);
2783		break;
2784	}
2785	case CTL_BBRREAD: {
2786		struct ctl_bbrread_info *bbr_info;
2787		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2788		struct mtx bbr_mtx;
2789		struct cfi_metatask *metatask;
2790
2791		bbr_info = (struct ctl_bbrread_info *)addr;
2792
2793		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2794
2795		bzero(&bbr_mtx, sizeof(bbr_mtx));
2796		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2797
2798		fe_bbr_info.bbr_info = bbr_info;
2799		fe_bbr_info.lock = &bbr_mtx;
2800
2801		cv_init(&fe_bbr_info.sem, "BBR read cv");
2802		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2803
2804		if (metatask == NULL) {
2805			mtx_destroy(&bbr_mtx);
2806			cv_destroy(&fe_bbr_info.sem);
2807			retval = ENOMEM;
2808			break;
2809		}
2810		metatask->tasktype = CFI_TASK_BBRREAD;
2811		metatask->callback = ctl_ioctl_bbrread_callback;
2812		metatask->callback_arg = &fe_bbr_info;
2813		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2814		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2815		metatask->taskinfo.bbrread.len = bbr_info->len;
2816
2817		cfi_action(metatask);
2818
2819		mtx_lock(&bbr_mtx);
2820		while (fe_bbr_info.wakeup_done == 0)
2821			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2822		mtx_unlock(&bbr_mtx);
2823
2824		bbr_info->status = metatask->status;
2825		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2826		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2827		memcpy(&bbr_info->sense_data,
2828		       &metatask->taskinfo.bbrread.sense_data,
2829		       ctl_min(sizeof(bbr_info->sense_data),
2830			       sizeof(metatask->taskinfo.bbrread.sense_data)));
2831
2832		cfi_free_metatask(metatask);
2833
2834		mtx_destroy(&bbr_mtx);
2835		cv_destroy(&fe_bbr_info.sem);
2836
2837		break;
2838	}
2839	case CTL_DELAY_IO: {
2840		struct ctl_io_delay_info *delay_info;
2841#ifdef CTL_IO_DELAY
2842		struct ctl_lun *lun;
2843#endif /* CTL_IO_DELAY */
2844
2845		delay_info = (struct ctl_io_delay_info *)addr;
2846
2847#ifdef CTL_IO_DELAY
2848		mtx_lock(&softc->ctl_lock);
2849
2850		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2851		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2852			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2853		} else {
2854			lun = softc->ctl_luns[delay_info->lun_id];
2855			mtx_lock(&lun->lun_lock);
2856
2857			delay_info->status = CTL_DELAY_STATUS_OK;
2858
2859			switch (delay_info->delay_type) {
2860			case CTL_DELAY_TYPE_CONT:
2861				break;
2862			case CTL_DELAY_TYPE_ONESHOT:
2863				break;
2864			default:
2865				delay_info->status =
2866					CTL_DELAY_STATUS_INVALID_TYPE;
2867				break;
2868			}
2869
2870			switch (delay_info->delay_loc) {
2871			case CTL_DELAY_LOC_DATAMOVE:
2872				lun->delay_info.datamove_type =
2873					delay_info->delay_type;
2874				lun->delay_info.datamove_delay =
2875					delay_info->delay_secs;
2876				break;
2877			case CTL_DELAY_LOC_DONE:
2878				lun->delay_info.done_type =
2879					delay_info->delay_type;
2880				lun->delay_info.done_delay =
2881					delay_info->delay_secs;
2882				break;
2883			default:
2884				delay_info->status =
2885					CTL_DELAY_STATUS_INVALID_LOC;
2886				break;
2887			}
2888			mtx_unlock(&lun->lun_lock);
2889		}
2890
2891		mtx_unlock(&softc->ctl_lock);
2892#else
2893		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2894#endif /* CTL_IO_DELAY */
2895		break;
2896	}
2897	case CTL_REALSYNC_SET: {
2898		int *syncstate;
2899
2900		syncstate = (int *)addr;
2901
2902		mtx_lock(&softc->ctl_lock);
2903		switch (*syncstate) {
2904		case 0:
2905			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2906			break;
2907		case 1:
2908			softc->flags |= CTL_FLAG_REAL_SYNC;
2909			break;
2910		default:
2911			retval = EINVAL;
2912			break;
2913		}
2914		mtx_unlock(&softc->ctl_lock);
2915		break;
2916	}
2917	case CTL_REALSYNC_GET: {
2918		int *syncstate;
2919
2920		syncstate = (int*)addr;
2921
2922		mtx_lock(&softc->ctl_lock);
2923		if (softc->flags & CTL_FLAG_REAL_SYNC)
2924			*syncstate = 1;
2925		else
2926			*syncstate = 0;
2927		mtx_unlock(&softc->ctl_lock);
2928
2929		break;
2930	}
2931	case CTL_SETSYNC:
2932	case CTL_GETSYNC: {
2933		struct ctl_sync_info *sync_info;
2934		struct ctl_lun *lun;
2935
2936		sync_info = (struct ctl_sync_info *)addr;
2937
2938		mtx_lock(&softc->ctl_lock);
2939		lun = softc->ctl_luns[sync_info->lun_id];
2940		if (lun == NULL) {
2941			mtx_unlock(&softc->ctl_lock);
2942			sync_info->status = CTL_GS_SYNC_NO_LUN;
2943		}
2944		/*
2945		 * Get or set the sync interval.  We're not bounds checking
2946		 * in the set case, hopefully the user won't do something
2947		 * silly.
2948		 */
2949		mtx_lock(&lun->lun_lock);
2950		mtx_unlock(&softc->ctl_lock);
2951		if (cmd == CTL_GETSYNC)
2952			sync_info->sync_interval = lun->sync_interval;
2953		else
2954			lun->sync_interval = sync_info->sync_interval;
2955		mtx_unlock(&lun->lun_lock);
2956
2957		sync_info->status = CTL_GS_SYNC_OK;
2958
2959		break;
2960	}
2961	case CTL_GETSTATS: {
2962		struct ctl_stats *stats;
2963		struct ctl_lun *lun;
2964		int i;
2965
2966		stats = (struct ctl_stats *)addr;
2967
2968		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2969		     stats->alloc_len) {
2970			stats->status = CTL_SS_NEED_MORE_SPACE;
2971			stats->num_luns = softc->num_luns;
2972			break;
2973		}
2974		/*
2975		 * XXX KDM no locking here.  If the LUN list changes,
2976		 * things can blow up.
2977		 */
2978		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2979		     i++, lun = STAILQ_NEXT(lun, links)) {
2980			retval = copyout(&lun->stats, &stats->lun_stats[i],
2981					 sizeof(lun->stats));
2982			if (retval != 0)
2983				break;
2984		}
2985		stats->num_luns = softc->num_luns;
2986		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2987				 softc->num_luns;
2988		stats->status = CTL_SS_OK;
2989#ifdef CTL_TIME_IO
2990		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2991#else
2992		stats->flags = CTL_STATS_FLAG_NONE;
2993#endif
2994		getnanouptime(&stats->timestamp);
2995		break;
2996	}
2997	case CTL_ERROR_INJECT: {
2998		struct ctl_error_desc *err_desc, *new_err_desc;
2999		struct ctl_lun *lun;
3000
3001		err_desc = (struct ctl_error_desc *)addr;
3002
3003		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
3004				      M_WAITOK | M_ZERO);
3005		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
3006
3007		mtx_lock(&softc->ctl_lock);
3008		lun = softc->ctl_luns[err_desc->lun_id];
3009		if (lun == NULL) {
3010			mtx_unlock(&softc->ctl_lock);
3011			free(new_err_desc, M_CTL);
3012			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
3013			       __func__, (uintmax_t)err_desc->lun_id);
3014			retval = EINVAL;
3015			break;
3016		}
3017		mtx_lock(&lun->lun_lock);
3018		mtx_unlock(&softc->ctl_lock);
3019
3020		/*
3021		 * We could do some checking here to verify the validity
3022		 * of the request, but given the complexity of error
3023		 * injection requests, the checking logic would be fairly
3024		 * complex.
3025		 *
3026		 * For now, if the request is invalid, it just won't get
3027		 * executed and might get deleted.
3028		 */
3029		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
3030
3031		/*
3032		 * XXX KDM check to make sure the serial number is unique,
3033		 * in case we somehow manage to wrap.  That shouldn't
3034		 * happen for a very long time, but it's the right thing to
3035		 * do.
3036		 */
3037		new_err_desc->serial = lun->error_serial;
3038		err_desc->serial = lun->error_serial;
3039		lun->error_serial++;
3040
3041		mtx_unlock(&lun->lun_lock);
3042		break;
3043	}
3044	case CTL_ERROR_INJECT_DELETE: {
3045		struct ctl_error_desc *delete_desc, *desc, *desc2;
3046		struct ctl_lun *lun;
3047		int delete_done;
3048
3049		delete_desc = (struct ctl_error_desc *)addr;
3050		delete_done = 0;
3051
3052		mtx_lock(&softc->ctl_lock);
3053		lun = softc->ctl_luns[delete_desc->lun_id];
3054		if (lun == NULL) {
3055			mtx_unlock(&softc->ctl_lock);
3056			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
3057			       __func__, (uintmax_t)delete_desc->lun_id);
3058			retval = EINVAL;
3059			break;
3060		}
3061		mtx_lock(&lun->lun_lock);
3062		mtx_unlock(&softc->ctl_lock);
3063		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
3064			if (desc->serial != delete_desc->serial)
3065				continue;
3066
3067			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
3068				      links);
3069			free(desc, M_CTL);
3070			delete_done = 1;
3071		}
3072		mtx_unlock(&lun->lun_lock);
3073		if (delete_done == 0) {
3074			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
3075			       "error serial %ju on LUN %u\n", __func__,
3076			       delete_desc->serial, delete_desc->lun_id);
3077			retval = EINVAL;
3078			break;
3079		}
3080		break;
3081	}
3082	case CTL_DUMP_STRUCTS: {
3083		int i, j, k, idx;
3084		struct ctl_port *port;
3085		struct ctl_frontend *fe;
3086
3087		mtx_lock(&softc->ctl_lock);
3088		printf("CTL Persistent Reservation information start:\n");
3089		for (i = 0; i < CTL_MAX_LUNS; i++) {
3090			struct ctl_lun *lun;
3091
3092			lun = softc->ctl_luns[i];
3093
3094			if ((lun == NULL)
3095			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
3096				continue;
3097
3098			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
3099				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
3100					idx = j * CTL_MAX_INIT_PER_PORT + k;
3101					if (lun->pr_keys[idx] == 0)
3102						continue;
3103					printf("  LUN %d port %d iid %d key "
3104					       "%#jx\n", i, j, k,
3105					       (uintmax_t)lun->pr_keys[idx]);
3106				}
3107			}
3108		}
3109		printf("CTL Persistent Reservation information end\n");
3110		printf("CTL Ports:\n");
3111		STAILQ_FOREACH(port, &softc->port_list, links) {
3112			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3113			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3114			       port->frontend->name, port->port_type,
3115			       port->physical_port, port->virtual_port,
3116			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3117			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3118				if (port->wwpn_iid[j].in_use == 0 &&
3119				    port->wwpn_iid[j].wwpn == 0 &&
3120				    port->wwpn_iid[j].name == NULL)
3121					continue;
3122
3123				printf("    iid %u use %d WWPN %#jx '%s'\n",
3124				    j, port->wwpn_iid[j].in_use,
3125				    (uintmax_t)port->wwpn_iid[j].wwpn,
3126				    port->wwpn_iid[j].name);
3127			}
3128		}
3129		printf("CTL Port information end\n");
3130		mtx_unlock(&softc->ctl_lock);
3131		/*
3132		 * XXX KDM calling this without a lock.  We'd likely want
3133		 * to drop the lock before calling the frontend's dump
3134		 * routine anyway.
3135		 */
3136		printf("CTL Frontends:\n");
3137		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3138			printf("  Frontend '%s'\n", fe->name);
3139			if (fe->fe_dump != NULL)
3140				fe->fe_dump();
3141		}
3142		printf("CTL Frontend information end\n");
3143		break;
3144	}
3145	case CTL_LUN_REQ: {
3146		struct ctl_lun_req *lun_req;
3147		struct ctl_backend_driver *backend;
3148
3149		lun_req = (struct ctl_lun_req *)addr;
3150
3151		backend = ctl_backend_find(lun_req->backend);
3152		if (backend == NULL) {
3153			lun_req->status = CTL_LUN_ERROR;
3154			snprintf(lun_req->error_str,
3155				 sizeof(lun_req->error_str),
3156				 "Backend \"%s\" not found.",
3157				 lun_req->backend);
3158			break;
3159		}
3160		if (lun_req->num_be_args > 0) {
3161			lun_req->kern_be_args = ctl_copyin_args(
3162				lun_req->num_be_args,
3163				lun_req->be_args,
3164				lun_req->error_str,
3165				sizeof(lun_req->error_str));
3166			if (lun_req->kern_be_args == NULL) {
3167				lun_req->status = CTL_LUN_ERROR;
3168				break;
3169			}
3170		}
3171
3172		retval = backend->ioctl(dev, cmd, addr, flag, td);
3173
3174		if (lun_req->num_be_args > 0) {
3175			ctl_copyout_args(lun_req->num_be_args,
3176				      lun_req->kern_be_args);
3177			ctl_free_args(lun_req->num_be_args,
3178				      lun_req->kern_be_args);
3179		}
3180		break;
3181	}
3182	case CTL_LUN_LIST: {
3183		struct sbuf *sb;
3184		struct ctl_lun *lun;
3185		struct ctl_lun_list *list;
3186		struct ctl_option *opt;
3187
3188		list = (struct ctl_lun_list *)addr;
3189
3190		/*
3191		 * Allocate a fixed length sbuf here, based on the length
3192		 * of the user's buffer.  We could allocate an auto-extending
3193		 * buffer, and then tell the user how much larger our
3194		 * amount of data is than his buffer, but that presents
3195		 * some problems:
3196		 *
3197		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3198		 *     we can't hold a lock while calling them with an
3199		 *     auto-extending buffer.
3200 		 *
3201		 * 2.  There is not currently a LUN reference counting
3202		 *     mechanism, outside of outstanding transactions on
3203		 *     the LUN's OOA queue.  So a LUN could go away on us
3204		 *     while we're getting the LUN number, backend-specific
3205		 *     information, etc.  Thus, given the way things
3206		 *     currently work, we need to hold the CTL lock while
3207		 *     grabbing LUN information.
3208		 *
3209		 * So, from the user's standpoint, the best thing to do is
3210		 * allocate what he thinks is a reasonable buffer length,
3211		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3212		 * double the buffer length and try again.  (And repeat
3213		 * that until he succeeds.)
3214		 */
3215		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3216		if (sb == NULL) {
3217			list->status = CTL_LUN_LIST_ERROR;
3218			snprintf(list->error_str, sizeof(list->error_str),
3219				 "Unable to allocate %d bytes for LUN list",
3220				 list->alloc_len);
3221			break;
3222		}
3223
3224		sbuf_printf(sb, "<ctllunlist>\n");
3225
3226		mtx_lock(&softc->ctl_lock);
3227		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3228			mtx_lock(&lun->lun_lock);
3229			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3230					     (uintmax_t)lun->lun);
3231
3232			/*
3233			 * Bail out as soon as we see that we've overfilled
3234			 * the buffer.
3235			 */
3236			if (retval != 0)
3237				break;
3238
3239			retval = sbuf_printf(sb, "\t<backend_type>%s"
3240					     "</backend_type>\n",
3241					     (lun->backend == NULL) ?  "none" :
3242					     lun->backend->name);
3243
3244			if (retval != 0)
3245				break;
3246
3247			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3248					     lun->be_lun->lun_type);
3249
3250			if (retval != 0)
3251				break;
3252
3253			if (lun->backend == NULL) {
3254				retval = sbuf_printf(sb, "</lun>\n");
3255				if (retval != 0)
3256					break;
3257				continue;
3258			}
3259
3260			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3261					     (lun->be_lun->maxlba > 0) ?
3262					     lun->be_lun->maxlba + 1 : 0);
3263
3264			if (retval != 0)
3265				break;
3266
3267			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3268					     lun->be_lun->blocksize);
3269
3270			if (retval != 0)
3271				break;
3272
3273			retval = sbuf_printf(sb, "\t<serial_number>");
3274
3275			if (retval != 0)
3276				break;
3277
3278			retval = ctl_sbuf_printf_esc(sb,
3279			    lun->be_lun->serial_num,
3280			    sizeof(lun->be_lun->serial_num));
3281
3282			if (retval != 0)
3283				break;
3284
3285			retval = sbuf_printf(sb, "</serial_number>\n");
3286
3287			if (retval != 0)
3288				break;
3289
3290			retval = sbuf_printf(sb, "\t<device_id>");
3291
3292			if (retval != 0)
3293				break;
3294
3295			retval = ctl_sbuf_printf_esc(sb,
3296			    lun->be_lun->device_id,
3297			    sizeof(lun->be_lun->device_id));
3298
3299			if (retval != 0)
3300				break;
3301
3302			retval = sbuf_printf(sb, "</device_id>\n");
3303
3304			if (retval != 0)
3305				break;
3306
3307			if (lun->backend->lun_info != NULL) {
3308				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3309				if (retval != 0)
3310					break;
3311			}
3312			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3313				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3314				    opt->name, opt->value, opt->name);
3315				if (retval != 0)
3316					break;
3317			}
3318
3319			retval = sbuf_printf(sb, "</lun>\n");
3320
3321			if (retval != 0)
3322				break;
3323			mtx_unlock(&lun->lun_lock);
3324		}
3325		if (lun != NULL)
3326			mtx_unlock(&lun->lun_lock);
3327		mtx_unlock(&softc->ctl_lock);
3328
3329		if ((retval != 0)
3330		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3331			retval = 0;
3332			sbuf_delete(sb);
3333			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3334			snprintf(list->error_str, sizeof(list->error_str),
3335				 "Out of space, %d bytes is too small",
3336				 list->alloc_len);
3337			break;
3338		}
3339
3340		sbuf_finish(sb);
3341
3342		retval = copyout(sbuf_data(sb), list->lun_xml,
3343				 sbuf_len(sb) + 1);
3344
3345		list->fill_len = sbuf_len(sb) + 1;
3346		list->status = CTL_LUN_LIST_OK;
3347		sbuf_delete(sb);
3348		break;
3349	}
3350	case CTL_ISCSI: {
3351		struct ctl_iscsi *ci;
3352		struct ctl_frontend *fe;
3353
3354		ci = (struct ctl_iscsi *)addr;
3355
3356		fe = ctl_frontend_find("iscsi");
3357		if (fe == NULL) {
3358			ci->status = CTL_ISCSI_ERROR;
3359			snprintf(ci->error_str, sizeof(ci->error_str),
3360			    "Frontend \"iscsi\" not found.");
3361			break;
3362		}
3363
3364		retval = fe->ioctl(dev, cmd, addr, flag, td);
3365		break;
3366	}
3367	case CTL_PORT_REQ: {
3368		struct ctl_req *req;
3369		struct ctl_frontend *fe;
3370
3371		req = (struct ctl_req *)addr;
3372
3373		fe = ctl_frontend_find(req->driver);
3374		if (fe == NULL) {
3375			req->status = CTL_LUN_ERROR;
3376			snprintf(req->error_str, sizeof(req->error_str),
3377			    "Frontend \"%s\" not found.", req->driver);
3378			break;
3379		}
3380		if (req->num_args > 0) {
3381			req->kern_args = ctl_copyin_args(req->num_args,
3382			    req->args, req->error_str, sizeof(req->error_str));
3383			if (req->kern_args == NULL) {
3384				req->status = CTL_LUN_ERROR;
3385				break;
3386			}
3387		}
3388
3389		retval = fe->ioctl(dev, cmd, addr, flag, td);
3390
3391		if (req->num_args > 0) {
3392			ctl_copyout_args(req->num_args, req->kern_args);
3393			ctl_free_args(req->num_args, req->kern_args);
3394		}
3395		break;
3396	}
3397	case CTL_PORT_LIST: {
3398		struct sbuf *sb;
3399		struct ctl_port *port;
3400		struct ctl_lun_list *list;
3401		struct ctl_option *opt;
3402		int j;
3403
3404		list = (struct ctl_lun_list *)addr;
3405
3406		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3407		if (sb == NULL) {
3408			list->status = CTL_LUN_LIST_ERROR;
3409			snprintf(list->error_str, sizeof(list->error_str),
3410				 "Unable to allocate %d bytes for LUN list",
3411				 list->alloc_len);
3412			break;
3413		}
3414
3415		sbuf_printf(sb, "<ctlportlist>\n");
3416
3417		mtx_lock(&softc->ctl_lock);
3418		STAILQ_FOREACH(port, &softc->port_list, links) {
3419			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3420					     (uintmax_t)port->targ_port);
3421
3422			/*
3423			 * Bail out as soon as we see that we've overfilled
3424			 * the buffer.
3425			 */
3426			if (retval != 0)
3427				break;
3428
3429			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3430			    "</frontend_type>\n", port->frontend->name);
3431			if (retval != 0)
3432				break;
3433
3434			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3435					     port->port_type);
3436			if (retval != 0)
3437				break;
3438
3439			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3440			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3441			if (retval != 0)
3442				break;
3443
3444			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3445			    port->port_name);
3446			if (retval != 0)
3447				break;
3448
3449			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3450			    port->physical_port);
3451			if (retval != 0)
3452				break;
3453
3454			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3455			    port->virtual_port);
3456			if (retval != 0)
3457				break;
3458
3459			if (port->target_devid != NULL) {
3460				sbuf_printf(sb, "\t<target>");
3461				ctl_id_sbuf(port->target_devid, sb);
3462				sbuf_printf(sb, "</target>\n");
3463			}
3464
3465			if (port->port_devid != NULL) {
3466				sbuf_printf(sb, "\t<port>");
3467				ctl_id_sbuf(port->port_devid, sb);
3468				sbuf_printf(sb, "</port>\n");
3469			}
3470
3471			if (port->port_info != NULL) {
3472				retval = port->port_info(port->onoff_arg, sb);
3473				if (retval != 0)
3474					break;
3475			}
3476			STAILQ_FOREACH(opt, &port->options, links) {
3477				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3478				    opt->name, opt->value, opt->name);
3479				if (retval != 0)
3480					break;
3481			}
3482
3483			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3484				if (port->wwpn_iid[j].in_use == 0 ||
3485				    (port->wwpn_iid[j].wwpn == 0 &&
3486				     port->wwpn_iid[j].name == NULL))
3487					continue;
3488
3489				if (port->wwpn_iid[j].name != NULL)
3490					retval = sbuf_printf(sb,
3491					    "\t<initiator>%u %s</initiator>\n",
3492					    j, port->wwpn_iid[j].name);
3493				else
3494					retval = sbuf_printf(sb,
3495					    "\t<initiator>%u naa.%08jx</initiator>\n",
3496					    j, port->wwpn_iid[j].wwpn);
3497				if (retval != 0)
3498					break;
3499			}
3500			if (retval != 0)
3501				break;
3502
3503			retval = sbuf_printf(sb, "</targ_port>\n");
3504			if (retval != 0)
3505				break;
3506		}
3507		mtx_unlock(&softc->ctl_lock);
3508
3509		if ((retval != 0)
3510		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3511			retval = 0;
3512			sbuf_delete(sb);
3513			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3514			snprintf(list->error_str, sizeof(list->error_str),
3515				 "Out of space, %d bytes is too small",
3516				 list->alloc_len);
3517			break;
3518		}
3519
3520		sbuf_finish(sb);
3521
3522		retval = copyout(sbuf_data(sb), list->lun_xml,
3523				 sbuf_len(sb) + 1);
3524
3525		list->fill_len = sbuf_len(sb) + 1;
3526		list->status = CTL_LUN_LIST_OK;
3527		sbuf_delete(sb);
3528		break;
3529	}
3530	default: {
3531		/* XXX KDM should we fix this? */
3532#if 0
3533		struct ctl_backend_driver *backend;
3534		unsigned int type;
3535		int found;
3536
3537		found = 0;
3538
3539		/*
3540		 * We encode the backend type as the ioctl type for backend
3541		 * ioctls.  So parse it out here, and then search for a
3542		 * backend of this type.
3543		 */
3544		type = _IOC_TYPE(cmd);
3545
3546		STAILQ_FOREACH(backend, &softc->be_list, links) {
3547			if (backend->type == type) {
3548				found = 1;
3549				break;
3550			}
3551		}
3552		if (found == 0) {
3553			printf("ctl: unknown ioctl command %#lx or backend "
3554			       "%d\n", cmd, type);
3555			retval = EINVAL;
3556			break;
3557		}
3558		retval = backend->ioctl(dev, cmd, addr, flag, td);
3559#endif
3560		retval = ENOTTY;
3561		break;
3562	}
3563	}
3564	return (retval);
3565}
3566
3567uint32_t
3568ctl_get_initindex(struct ctl_nexus *nexus)
3569{
3570	if (nexus->targ_port < CTL_MAX_PORTS)
3571		return (nexus->initid.id +
3572			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3573	else
3574		return (nexus->initid.id +
3575		       ((nexus->targ_port - CTL_MAX_PORTS) *
3576			CTL_MAX_INIT_PER_PORT));
3577}
3578
3579uint32_t
3580ctl_get_resindex(struct ctl_nexus *nexus)
3581{
3582	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3583}
3584
3585uint32_t
3586ctl_port_idx(int port_num)
3587{
3588	if (port_num < CTL_MAX_PORTS)
3589		return(port_num);
3590	else
3591		return(port_num - CTL_MAX_PORTS);
3592}
3593
3594static uint32_t
3595ctl_map_lun(int port_num, uint32_t lun_id)
3596{
3597	struct ctl_port *port;
3598
3599	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3600	if (port == NULL)
3601		return (UINT32_MAX);
3602	if (port->lun_map == NULL)
3603		return (lun_id);
3604	return (port->lun_map(port->targ_lun_arg, lun_id));
3605}
3606
3607static uint32_t
3608ctl_map_lun_back(int port_num, uint32_t lun_id)
3609{
3610	struct ctl_port *port;
3611	uint32_t i;
3612
3613	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3614	if (port->lun_map == NULL)
3615		return (lun_id);
3616	for (i = 0; i < CTL_MAX_LUNS; i++) {
3617		if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3618			return (i);
3619	}
3620	return (UINT32_MAX);
3621}
3622
3623/*
3624 * Note:  This only works for bitmask sizes that are at least 32 bits, and
3625 * that are a power of 2.
3626 */
3627int
3628ctl_ffz(uint32_t *mask, uint32_t size)
3629{
3630	uint32_t num_chunks, num_pieces;
3631	int i, j;
3632
3633	num_chunks = (size >> 5);
3634	if (num_chunks == 0)
3635		num_chunks++;
3636	num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3637
3638	for (i = 0; i < num_chunks; i++) {
3639		for (j = 0; j < num_pieces; j++) {
3640			if ((mask[i] & (1 << j)) == 0)
3641				return ((i << 5) + j);
3642		}
3643	}
3644
3645	return (-1);
3646}
3647
3648int
3649ctl_set_mask(uint32_t *mask, uint32_t bit)
3650{
3651	uint32_t chunk, piece;
3652
3653	chunk = bit >> 5;
3654	piece = bit % (sizeof(uint32_t) * 8);
3655
3656	if ((mask[chunk] & (1 << piece)) != 0)
3657		return (-1);
3658	else
3659		mask[chunk] |= (1 << piece);
3660
3661	return (0);
3662}
3663
3664int
3665ctl_clear_mask(uint32_t *mask, uint32_t bit)
3666{
3667	uint32_t chunk, piece;
3668
3669	chunk = bit >> 5;
3670	piece = bit % (sizeof(uint32_t) * 8);
3671
3672	if ((mask[chunk] & (1 << piece)) == 0)
3673		return (-1);
3674	else
3675		mask[chunk] &= ~(1 << piece);
3676
3677	return (0);
3678}
3679
3680int
3681ctl_is_set(uint32_t *mask, uint32_t bit)
3682{
3683	uint32_t chunk, piece;
3684
3685	chunk = bit >> 5;
3686	piece = bit % (sizeof(uint32_t) * 8);
3687
3688	if ((mask[chunk] & (1 << piece)) == 0)
3689		return (0);
3690	else
3691		return (1);
3692}
3693
3694#ifdef unused
3695/*
3696 * The bus, target and lun are optional, they can be filled in later.
3697 * can_wait is used to determine whether we can wait on the malloc or not.
3698 */
3699union ctl_io*
3700ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3701	      uint32_t targ_lun, int can_wait)
3702{
3703	union ctl_io *io;
3704
3705	if (can_wait)
3706		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3707	else
3708		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3709
3710	if (io != NULL) {
3711		io->io_hdr.io_type = io_type;
3712		io->io_hdr.targ_port = targ_port;
3713		/*
3714		 * XXX KDM this needs to change/go away.  We need to move
3715		 * to a preallocated pool of ctl_scsiio structures.
3716		 */
3717		io->io_hdr.nexus.targ_target.id = targ_target;
3718		io->io_hdr.nexus.targ_lun = targ_lun;
3719	}
3720
3721	return (io);
3722}
3723
3724void
3725ctl_kfree_io(union ctl_io *io)
3726{
3727	free(io, M_CTL);
3728}
3729#endif /* unused */
3730
3731/*
3732 * ctl_softc, pool_type, total_ctl_io are passed in.
3733 * npool is passed out.
3734 */
3735int
3736ctl_pool_create(struct ctl_softc *ctl_softc, ctl_pool_type pool_type,
3737		uint32_t total_ctl_io, struct ctl_io_pool **npool)
3738{
3739	uint32_t i;
3740	union ctl_io *cur_io, *next_io;
3741	struct ctl_io_pool *pool;
3742	int retval;
3743
3744	retval = 0;
3745
3746	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3747					    M_NOWAIT | M_ZERO);
3748	if (pool == NULL) {
3749		retval = ENOMEM;
3750		goto bailout;
3751	}
3752
3753	pool->type = pool_type;
3754	pool->ctl_softc = ctl_softc;
3755
3756	mtx_lock(&ctl_softc->pool_lock);
3757	pool->id = ctl_softc->cur_pool_id++;
3758	mtx_unlock(&ctl_softc->pool_lock);
3759
3760	pool->flags = CTL_POOL_FLAG_NONE;
3761	pool->refcount = 1;		/* Reference for validity. */
3762	STAILQ_INIT(&pool->free_queue);
3763
3764	/*
3765	 * XXX KDM other options here:
3766	 * - allocate a page at a time
3767	 * - allocate one big chunk of memory.
3768	 * Page allocation might work well, but would take a little more
3769	 * tracking.
3770	 */
3771	for (i = 0; i < total_ctl_io; i++) {
3772		cur_io = (union ctl_io *)malloc(sizeof(*cur_io), M_CTLIO,
3773						M_NOWAIT);
3774		if (cur_io == NULL) {
3775			retval = ENOMEM;
3776			break;
3777		}
3778		cur_io->io_hdr.pool = pool;
3779		STAILQ_INSERT_TAIL(&pool->free_queue, &cur_io->io_hdr, links);
3780		pool->total_ctl_io++;
3781		pool->free_ctl_io++;
3782	}
3783
3784	if (retval != 0) {
3785		for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3786		     cur_io != NULL; cur_io = next_io) {
3787			next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3788							      links);
3789			STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr,
3790				      ctl_io_hdr, links);
3791			free(cur_io, M_CTLIO);
3792		}
3793
3794		free(pool, M_CTL);
3795		goto bailout;
3796	}
3797	mtx_lock(&ctl_softc->pool_lock);
3798	ctl_softc->num_pools++;
3799	STAILQ_INSERT_TAIL(&ctl_softc->io_pools, pool, links);
3800	/*
3801	 * Increment our usage count if this is an external consumer, so we
3802	 * can't get unloaded until the external consumer (most likely a
3803	 * FETD) unloads and frees his pool.
3804	 *
3805	 * XXX KDM will this increment the caller's module use count, or
3806	 * mine?
3807	 */
3808#if 0
3809	if ((pool_type != CTL_POOL_EMERGENCY)
3810	 && (pool_type != CTL_POOL_INTERNAL)
3811	 && (pool_type != CTL_POOL_4OTHERSC))
3812		MOD_INC_USE_COUNT;
3813#endif
3814
3815	mtx_unlock(&ctl_softc->pool_lock);
3816
3817	*npool = pool;
3818
3819bailout:
3820
3821	return (retval);
3822}
3823
3824static int
3825ctl_pool_acquire(struct ctl_io_pool *pool)
3826{
3827
3828	mtx_assert(&pool->ctl_softc->pool_lock, MA_OWNED);
3829
3830	if (pool->flags & CTL_POOL_FLAG_INVALID)
3831		return (EINVAL);
3832
3833	pool->refcount++;
3834
3835	return (0);
3836}
3837
3838static void
3839ctl_pool_release(struct ctl_io_pool *pool)
3840{
3841	struct ctl_softc *ctl_softc = pool->ctl_softc;
3842	union ctl_io *io;
3843
3844	mtx_assert(&ctl_softc->pool_lock, MA_OWNED);
3845
3846	if (--pool->refcount != 0)
3847		return;
3848
3849	while ((io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue)) != NULL) {
3850		STAILQ_REMOVE(&pool->free_queue, &io->io_hdr, ctl_io_hdr,
3851			      links);
3852		free(io, M_CTLIO);
3853	}
3854
3855	STAILQ_REMOVE(&ctl_softc->io_pools, pool, ctl_io_pool, links);
3856	ctl_softc->num_pools--;
3857
3858	/*
3859	 * XXX KDM will this decrement the caller's usage count or mine?
3860	 */
3861#if 0
3862	if ((pool->type != CTL_POOL_EMERGENCY)
3863	 && (pool->type != CTL_POOL_INTERNAL)
3864	 && (pool->type != CTL_POOL_4OTHERSC))
3865		MOD_DEC_USE_COUNT;
3866#endif
3867
3868	free(pool, M_CTL);
3869}
3870
3871void
3872ctl_pool_free(struct ctl_io_pool *pool)
3873{
3874	struct ctl_softc *ctl_softc;
3875
3876	if (pool == NULL)
3877		return;
3878
3879	ctl_softc = pool->ctl_softc;
3880	mtx_lock(&ctl_softc->pool_lock);
3881	pool->flags |= CTL_POOL_FLAG_INVALID;
3882	ctl_pool_release(pool);
3883	mtx_unlock(&ctl_softc->pool_lock);
3884}
3885
3886/*
3887 * This routine does not block (except for spinlocks of course).
3888 * It tries to allocate a ctl_io union from the caller's pool as quickly as
3889 * possible.
3890 */
3891union ctl_io *
3892ctl_alloc_io(void *pool_ref)
3893{
3894	union ctl_io *io;
3895	struct ctl_softc *ctl_softc;
3896	struct ctl_io_pool *pool, *npool;
3897	struct ctl_io_pool *emergency_pool;
3898
3899	pool = (struct ctl_io_pool *)pool_ref;
3900
3901	if (pool == NULL) {
3902		printf("%s: pool is NULL\n", __func__);
3903		return (NULL);
3904	}
3905
3906	emergency_pool = NULL;
3907
3908	ctl_softc = pool->ctl_softc;
3909
3910	mtx_lock(&ctl_softc->pool_lock);
3911	/*
3912	 * First, try to get the io structure from the user's pool.
3913	 */
3914	if (ctl_pool_acquire(pool) == 0) {
3915		io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3916		if (io != NULL) {
3917			STAILQ_REMOVE_HEAD(&pool->free_queue, links);
3918			pool->total_allocated++;
3919			pool->free_ctl_io--;
3920			mtx_unlock(&ctl_softc->pool_lock);
3921			return (io);
3922		} else
3923			ctl_pool_release(pool);
3924	}
3925	/*
3926	 * If he doesn't have any io structures left, search for an
3927	 * emergency pool and grab one from there.
3928	 */
3929	STAILQ_FOREACH(npool, &ctl_softc->io_pools, links) {
3930		if (npool->type != CTL_POOL_EMERGENCY)
3931			continue;
3932
3933		if (ctl_pool_acquire(npool) != 0)
3934			continue;
3935
3936		emergency_pool = npool;
3937
3938		io = (union ctl_io *)STAILQ_FIRST(&npool->free_queue);
3939		if (io != NULL) {
3940			STAILQ_REMOVE_HEAD(&npool->free_queue, links);
3941			npool->total_allocated++;
3942			npool->free_ctl_io--;
3943			mtx_unlock(&ctl_softc->pool_lock);
3944			return (io);
3945		} else
3946			ctl_pool_release(npool);
3947	}
3948
3949	/* Drop the spinlock before we malloc */
3950	mtx_unlock(&ctl_softc->pool_lock);
3951
3952	/*
3953	 * The emergency pool (if it exists) didn't have one, so try an
3954	 * atomic (i.e. nonblocking) malloc and see if we get lucky.
3955	 */
3956	io = (union ctl_io *)malloc(sizeof(*io), M_CTLIO, M_NOWAIT);
3957	if (io != NULL) {
3958		/*
3959		 * If the emergency pool exists but is empty, add this
3960		 * ctl_io to its list when it gets freed.
3961		 */
3962		if (emergency_pool != NULL) {
3963			mtx_lock(&ctl_softc->pool_lock);
3964			if (ctl_pool_acquire(emergency_pool) == 0) {
3965				io->io_hdr.pool = emergency_pool;
3966				emergency_pool->total_ctl_io++;
3967				/*
3968				 * Need to bump this, otherwise
3969				 * total_allocated and total_freed won't
3970				 * match when we no longer have anything
3971				 * outstanding.
3972				 */
3973				emergency_pool->total_allocated++;
3974			}
3975			mtx_unlock(&ctl_softc->pool_lock);
3976		} else
3977			io->io_hdr.pool = NULL;
3978	}
3979
3980	return (io);
3981}
3982
3983void
3984ctl_free_io(union ctl_io *io)
3985{
3986	if (io == NULL)
3987		return;
3988
3989	/*
3990	 * If this ctl_io has a pool, return it to that pool.
3991	 */
3992	if (io->io_hdr.pool != NULL) {
3993		struct ctl_io_pool *pool;
3994
3995		pool = (struct ctl_io_pool *)io->io_hdr.pool;
3996		mtx_lock(&pool->ctl_softc->pool_lock);
3997		io->io_hdr.io_type = 0xff;
3998		STAILQ_INSERT_TAIL(&pool->free_queue, &io->io_hdr, links);
3999		pool->total_freed++;
4000		pool->free_ctl_io++;
4001		ctl_pool_release(pool);
4002		mtx_unlock(&pool->ctl_softc->pool_lock);
4003	} else {
4004		/*
4005		 * Otherwise, just free it.  We probably malloced it and
4006		 * the emergency pool wasn't available.
4007		 */
4008		free(io, M_CTLIO);
4009	}
4010
4011}
4012
4013void
4014ctl_zero_io(union ctl_io *io)
4015{
4016	void *pool_ref;
4017
4018	if (io == NULL)
4019		return;
4020
4021	/*
4022	 * May need to preserve linked list pointers at some point too.
4023	 */
4024	pool_ref = io->io_hdr.pool;
4025
4026	memset(io, 0, sizeof(*io));
4027
4028	io->io_hdr.pool = pool_ref;
4029}
4030
4031/*
4032 * This routine is currently used for internal copies of ctl_ios that need
4033 * to persist for some reason after we've already returned status to the
4034 * FETD.  (Thus the flag set.)
4035 *
4036 * XXX XXX
4037 * Note that this makes a blind copy of all fields in the ctl_io, except
4038 * for the pool reference.  This includes any memory that has been
4039 * allocated!  That memory will no longer be valid after done has been
4040 * called, so this would be VERY DANGEROUS for command that actually does
4041 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
4042 * start and stop commands, which don't transfer any data, so this is not a
4043 * problem.  If it is used for anything else, the caller would also need to
4044 * allocate data buffer space and this routine would need to be modified to
4045 * copy the data buffer(s) as well.
4046 */
4047void
4048ctl_copy_io(union ctl_io *src, union ctl_io *dest)
4049{
4050	void *pool_ref;
4051
4052	if ((src == NULL)
4053	 || (dest == NULL))
4054		return;
4055
4056	/*
4057	 * May need to preserve linked list pointers at some point too.
4058	 */
4059	pool_ref = dest->io_hdr.pool;
4060
4061	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
4062
4063	dest->io_hdr.pool = pool_ref;
4064	/*
4065	 * We need to know that this is an internal copy, and doesn't need
4066	 * to get passed back to the FETD that allocated it.
4067	 */
4068	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
4069}
4070
4071static int
4072ctl_expand_number(const char *buf, uint64_t *num)
4073{
4074	char *endptr;
4075	uint64_t number;
4076	unsigned shift;
4077
4078	number = strtoq(buf, &endptr, 0);
4079
4080	switch (tolower((unsigned char)*endptr)) {
4081	case 'e':
4082		shift = 60;
4083		break;
4084	case 'p':
4085		shift = 50;
4086		break;
4087	case 't':
4088		shift = 40;
4089		break;
4090	case 'g':
4091		shift = 30;
4092		break;
4093	case 'm':
4094		shift = 20;
4095		break;
4096	case 'k':
4097		shift = 10;
4098		break;
4099	case 'b':
4100	case '\0': /* No unit. */
4101		*num = number;
4102		return (0);
4103	default:
4104		/* Unrecognized unit. */
4105		return (-1);
4106	}
4107
4108	if ((number << shift) >> shift != number) {
4109		/* Overflow */
4110		return (-1);
4111	}
4112	*num = number << shift;
4113	return (0);
4114}
4115
4116
4117/*
4118 * This routine could be used in the future to load default and/or saved
4119 * mode page parameters for a particuar lun.
4120 */
4121static int
4122ctl_init_page_index(struct ctl_lun *lun)
4123{
4124	int i;
4125	struct ctl_page_index *page_index;
4126	const char *value;
4127	uint64_t ival;
4128
4129	memcpy(&lun->mode_pages.index, page_index_template,
4130	       sizeof(page_index_template));
4131
4132	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4133
4134		page_index = &lun->mode_pages.index[i];
4135		/*
4136		 * If this is a disk-only mode page, there's no point in
4137		 * setting it up.  For some pages, we have to have some
4138		 * basic information about the disk in order to calculate the
4139		 * mode page data.
4140		 */
4141		if ((lun->be_lun->lun_type != T_DIRECT)
4142		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4143			continue;
4144
4145		switch (page_index->page_code & SMPH_PC_MASK) {
4146		case SMS_RW_ERROR_RECOVERY_PAGE: {
4147			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4148				panic("subpage is incorrect!");
4149			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
4150			       &rw_er_page_default,
4151			       sizeof(rw_er_page_default));
4152			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
4153			       &rw_er_page_changeable,
4154			       sizeof(rw_er_page_changeable));
4155			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
4156			       &rw_er_page_default,
4157			       sizeof(rw_er_page_default));
4158			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
4159			       &rw_er_page_default,
4160			       sizeof(rw_er_page_default));
4161			page_index->page_data =
4162				(uint8_t *)lun->mode_pages.rw_er_page;
4163			break;
4164		}
4165		case SMS_FORMAT_DEVICE_PAGE: {
4166			struct scsi_format_page *format_page;
4167
4168			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4169				panic("subpage is incorrect!");
4170
4171			/*
4172			 * Sectors per track are set above.  Bytes per
4173			 * sector need to be set here on a per-LUN basis.
4174			 */
4175			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4176			       &format_page_default,
4177			       sizeof(format_page_default));
4178			memcpy(&lun->mode_pages.format_page[
4179			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4180			       sizeof(format_page_changeable));
4181			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4182			       &format_page_default,
4183			       sizeof(format_page_default));
4184			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4185			       &format_page_default,
4186			       sizeof(format_page_default));
4187
4188			format_page = &lun->mode_pages.format_page[
4189				CTL_PAGE_CURRENT];
4190			scsi_ulto2b(lun->be_lun->blocksize,
4191				    format_page->bytes_per_sector);
4192
4193			format_page = &lun->mode_pages.format_page[
4194				CTL_PAGE_DEFAULT];
4195			scsi_ulto2b(lun->be_lun->blocksize,
4196				    format_page->bytes_per_sector);
4197
4198			format_page = &lun->mode_pages.format_page[
4199				CTL_PAGE_SAVED];
4200			scsi_ulto2b(lun->be_lun->blocksize,
4201				    format_page->bytes_per_sector);
4202
4203			page_index->page_data =
4204				(uint8_t *)lun->mode_pages.format_page;
4205			break;
4206		}
4207		case SMS_RIGID_DISK_PAGE: {
4208			struct scsi_rigid_disk_page *rigid_disk_page;
4209			uint32_t sectors_per_cylinder;
4210			uint64_t cylinders;
4211#ifndef	__XSCALE__
4212			int shift;
4213#endif /* !__XSCALE__ */
4214
4215			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4216				panic("invalid subpage value %d",
4217				      page_index->subpage);
4218
4219			/*
4220			 * Rotation rate and sectors per track are set
4221			 * above.  We calculate the cylinders here based on
4222			 * capacity.  Due to the number of heads and
4223			 * sectors per track we're using, smaller arrays
4224			 * may turn out to have 0 cylinders.  Linux and
4225			 * FreeBSD don't pay attention to these mode pages
4226			 * to figure out capacity, but Solaris does.  It
4227			 * seems to deal with 0 cylinders just fine, and
4228			 * works out a fake geometry based on the capacity.
4229			 */
4230			memcpy(&lun->mode_pages.rigid_disk_page[
4231			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4232			       sizeof(rigid_disk_page_default));
4233			memcpy(&lun->mode_pages.rigid_disk_page[
4234			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4235			       sizeof(rigid_disk_page_changeable));
4236
4237			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4238				CTL_DEFAULT_HEADS;
4239
4240			/*
4241			 * The divide method here will be more accurate,
4242			 * probably, but results in floating point being
4243			 * used in the kernel on i386 (__udivdi3()).  On the
4244			 * XScale, though, __udivdi3() is implemented in
4245			 * software.
4246			 *
4247			 * The shift method for cylinder calculation is
4248			 * accurate if sectors_per_cylinder is a power of
4249			 * 2.  Otherwise it might be slightly off -- you
4250			 * might have a bit of a truncation problem.
4251			 */
4252#ifdef	__XSCALE__
4253			cylinders = (lun->be_lun->maxlba + 1) /
4254				sectors_per_cylinder;
4255#else
4256			for (shift = 31; shift > 0; shift--) {
4257				if (sectors_per_cylinder & (1 << shift))
4258					break;
4259			}
4260			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4261#endif
4262
4263			/*
4264			 * We've basically got 3 bytes, or 24 bits for the
4265			 * cylinder size in the mode page.  If we're over,
4266			 * just round down to 2^24.
4267			 */
4268			if (cylinders > 0xffffff)
4269				cylinders = 0xffffff;
4270
4271			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4272				CTL_PAGE_DEFAULT];
4273			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4274
4275			if ((value = ctl_get_opt(&lun->be_lun->options,
4276			    "rpm")) != NULL) {
4277				scsi_ulto2b(strtol(value, NULL, 0),
4278				     rigid_disk_page->rotation_rate);
4279			}
4280
4281			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4282			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4283			       sizeof(rigid_disk_page_default));
4284			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4285			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4286			       sizeof(rigid_disk_page_default));
4287
4288			page_index->page_data =
4289				(uint8_t *)lun->mode_pages.rigid_disk_page;
4290			break;
4291		}
4292		case SMS_CACHING_PAGE: {
4293			struct scsi_caching_page *caching_page;
4294
4295			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4296				panic("invalid subpage value %d",
4297				      page_index->subpage);
4298			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4299			       &caching_page_default,
4300			       sizeof(caching_page_default));
4301			memcpy(&lun->mode_pages.caching_page[
4302			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4303			       sizeof(caching_page_changeable));
4304			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4305			       &caching_page_default,
4306			       sizeof(caching_page_default));
4307			caching_page = &lun->mode_pages.caching_page[
4308			    CTL_PAGE_SAVED];
4309			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4310			if (value != NULL && strcmp(value, "off") == 0)
4311				caching_page->flags1 &= ~SCP_WCE;
4312			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4313			if (value != NULL && strcmp(value, "off") == 0)
4314				caching_page->flags1 |= SCP_RCD;
4315			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4316			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4317			       sizeof(caching_page_default));
4318			page_index->page_data =
4319				(uint8_t *)lun->mode_pages.caching_page;
4320			break;
4321		}
4322		case SMS_CONTROL_MODE_PAGE: {
4323			struct scsi_control_page *control_page;
4324
4325			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4326				panic("invalid subpage value %d",
4327				      page_index->subpage);
4328
4329			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4330			       &control_page_default,
4331			       sizeof(control_page_default));
4332			memcpy(&lun->mode_pages.control_page[
4333			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4334			       sizeof(control_page_changeable));
4335			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4336			       &control_page_default,
4337			       sizeof(control_page_default));
4338			control_page = &lun->mode_pages.control_page[
4339			    CTL_PAGE_SAVED];
4340			value = ctl_get_opt(&lun->be_lun->options, "reordering");
4341			if (value != NULL && strcmp(value, "unrestricted") == 0) {
4342				control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4343				control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4344			}
4345			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4346			       &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4347			       sizeof(control_page_default));
4348			page_index->page_data =
4349				(uint8_t *)lun->mode_pages.control_page;
4350			break;
4351
4352		}
4353		case SMS_INFO_EXCEPTIONS_PAGE: {
4354			switch (page_index->subpage) {
4355			case SMS_SUBPAGE_PAGE_0:
4356				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4357				       &ie_page_default,
4358				       sizeof(ie_page_default));
4359				memcpy(&lun->mode_pages.ie_page[
4360				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4361				       sizeof(ie_page_changeable));
4362				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4363				       &ie_page_default,
4364				       sizeof(ie_page_default));
4365				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4366				       &ie_page_default,
4367				       sizeof(ie_page_default));
4368				page_index->page_data =
4369					(uint8_t *)lun->mode_pages.ie_page;
4370				break;
4371			case 0x02: {
4372				struct ctl_logical_block_provisioning_page *page;
4373
4374				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4375				       &lbp_page_default,
4376				       sizeof(lbp_page_default));
4377				memcpy(&lun->mode_pages.lbp_page[
4378				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4379				       sizeof(lbp_page_changeable));
4380				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4381				       &lbp_page_default,
4382				       sizeof(lbp_page_default));
4383				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4384				value = ctl_get_opt(&lun->be_lun->options,
4385				    "avail-threshold");
4386				if (value != NULL &&
4387				    ctl_expand_number(value, &ival) == 0) {
4388					page->descr[0].flags |= SLBPPD_ENABLED |
4389					    SLBPPD_ARMING_DEC;
4390					if (lun->be_lun->blocksize)
4391						ival /= lun->be_lun->blocksize;
4392					else
4393						ival /= 512;
4394					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4395					    page->descr[0].count);
4396				}
4397				value = ctl_get_opt(&lun->be_lun->options,
4398				    "used-threshold");
4399				if (value != NULL &&
4400				    ctl_expand_number(value, &ival) == 0) {
4401					page->descr[1].flags |= SLBPPD_ENABLED |
4402					    SLBPPD_ARMING_INC;
4403					if (lun->be_lun->blocksize)
4404						ival /= lun->be_lun->blocksize;
4405					else
4406						ival /= 512;
4407					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4408					    page->descr[1].count);
4409				}
4410				value = ctl_get_opt(&lun->be_lun->options,
4411				    "pool-avail-threshold");
4412				if (value != NULL &&
4413				    ctl_expand_number(value, &ival) == 0) {
4414					page->descr[2].flags |= SLBPPD_ENABLED |
4415					    SLBPPD_ARMING_DEC;
4416					if (lun->be_lun->blocksize)
4417						ival /= lun->be_lun->blocksize;
4418					else
4419						ival /= 512;
4420					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4421					    page->descr[2].count);
4422				}
4423				value = ctl_get_opt(&lun->be_lun->options,
4424				    "pool-used-threshold");
4425				if (value != NULL &&
4426				    ctl_expand_number(value, &ival) == 0) {
4427					page->descr[3].flags |= SLBPPD_ENABLED |
4428					    SLBPPD_ARMING_INC;
4429					if (lun->be_lun->blocksize)
4430						ival /= lun->be_lun->blocksize;
4431					else
4432						ival /= 512;
4433					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4434					    page->descr[3].count);
4435				}
4436				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4437				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4438				       sizeof(lbp_page_default));
4439				page_index->page_data =
4440					(uint8_t *)lun->mode_pages.lbp_page;
4441			}}
4442			break;
4443		}
4444		case SMS_VENDOR_SPECIFIC_PAGE:{
4445			switch (page_index->subpage) {
4446			case DBGCNF_SUBPAGE_CODE: {
4447				struct copan_debugconf_subpage *current_page,
4448							       *saved_page;
4449
4450				memcpy(&lun->mode_pages.debugconf_subpage[
4451				       CTL_PAGE_CURRENT],
4452				       &debugconf_page_default,
4453				       sizeof(debugconf_page_default));
4454				memcpy(&lun->mode_pages.debugconf_subpage[
4455				       CTL_PAGE_CHANGEABLE],
4456				       &debugconf_page_changeable,
4457				       sizeof(debugconf_page_changeable));
4458				memcpy(&lun->mode_pages.debugconf_subpage[
4459				       CTL_PAGE_DEFAULT],
4460				       &debugconf_page_default,
4461				       sizeof(debugconf_page_default));
4462				memcpy(&lun->mode_pages.debugconf_subpage[
4463				       CTL_PAGE_SAVED],
4464				       &debugconf_page_default,
4465				       sizeof(debugconf_page_default));
4466				page_index->page_data =
4467					(uint8_t *)lun->mode_pages.debugconf_subpage;
4468
4469				current_page = (struct copan_debugconf_subpage *)
4470					(page_index->page_data +
4471					 (page_index->page_len *
4472					  CTL_PAGE_CURRENT));
4473				saved_page = (struct copan_debugconf_subpage *)
4474					(page_index->page_data +
4475					 (page_index->page_len *
4476					  CTL_PAGE_SAVED));
4477				break;
4478			}
4479			default:
4480				panic("invalid subpage value %d",
4481				      page_index->subpage);
4482				break;
4483			}
4484   			break;
4485		}
4486		default:
4487			panic("invalid page value %d",
4488			      page_index->page_code & SMPH_PC_MASK);
4489			break;
4490    	}
4491	}
4492
4493	return (CTL_RETVAL_COMPLETE);
4494}
4495
4496static int
4497ctl_init_log_page_index(struct ctl_lun *lun)
4498{
4499	struct ctl_page_index *page_index;
4500	int i, j, k, prev;
4501
4502	memcpy(&lun->log_pages.index, log_page_index_template,
4503	       sizeof(log_page_index_template));
4504
4505	prev = -1;
4506	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4507
4508		page_index = &lun->log_pages.index[i];
4509		/*
4510		 * If this is a disk-only mode page, there's no point in
4511		 * setting it up.  For some pages, we have to have some
4512		 * basic information about the disk in order to calculate the
4513		 * mode page data.
4514		 */
4515		if ((lun->be_lun->lun_type != T_DIRECT)
4516		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4517			continue;
4518
4519		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4520		    ((lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) == 0 ||
4521		     lun->backend->lun_attr == NULL))
4522			continue;
4523
4524		if (page_index->page_code != prev) {
4525			lun->log_pages.pages_page[j] = page_index->page_code;
4526			prev = page_index->page_code;
4527			j++;
4528		}
4529		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4530		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4531		k++;
4532	}
4533	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4534	lun->log_pages.index[0].page_len = j;
4535	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4536	lun->log_pages.index[1].page_len = k * 2;
4537	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4538	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4539
4540	return (CTL_RETVAL_COMPLETE);
4541}
4542
4543static int
4544hex2bin(const char *str, uint8_t *buf, int buf_size)
4545{
4546	int i;
4547	u_char c;
4548
4549	memset(buf, 0, buf_size);
4550	while (isspace(str[0]))
4551		str++;
4552	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4553		str += 2;
4554	buf_size *= 2;
4555	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4556		c = str[i];
4557		if (isdigit(c))
4558			c -= '0';
4559		else if (isalpha(c))
4560			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4561		else
4562			break;
4563		if (c >= 16)
4564			break;
4565		if ((i & 1) == 0)
4566			buf[i / 2] |= (c << 4);
4567		else
4568			buf[i / 2] |= c;
4569	}
4570	return ((i + 1) / 2);
4571}
4572
4573/*
4574 * LUN allocation.
4575 *
4576 * Requirements:
4577 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4578 *   wants us to allocate the LUN and he can block.
4579 * - ctl_softc is always set
4580 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4581 *
4582 * Returns 0 for success, non-zero (errno) for failure.
4583 */
4584static int
4585ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4586	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4587{
4588	struct ctl_lun *nlun, *lun;
4589	struct ctl_port *port;
4590	struct scsi_vpd_id_descriptor *desc;
4591	struct scsi_vpd_id_t10 *t10id;
4592	const char *eui, *naa, *scsiname, *vendor, *value;
4593	int lun_number, i, lun_malloced;
4594	int devidlen, idlen1, idlen2 = 0, len;
4595
4596	if (be_lun == NULL)
4597		return (EINVAL);
4598
4599	/*
4600	 * We currently only support Direct Access or Processor LUN types.
4601	 */
4602	switch (be_lun->lun_type) {
4603	case T_DIRECT:
4604		break;
4605	case T_PROCESSOR:
4606		break;
4607	case T_SEQUENTIAL:
4608	case T_CHANGER:
4609	default:
4610		be_lun->lun_config_status(be_lun->be_lun,
4611					  CTL_LUN_CONFIG_FAILURE);
4612		break;
4613	}
4614	if (ctl_lun == NULL) {
4615		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4616		lun_malloced = 1;
4617	} else {
4618		lun_malloced = 0;
4619		lun = ctl_lun;
4620	}
4621
4622	memset(lun, 0, sizeof(*lun));
4623	if (lun_malloced)
4624		lun->flags = CTL_LUN_MALLOCED;
4625
4626	/* Generate LUN ID. */
4627	devidlen = max(CTL_DEVID_MIN_LEN,
4628	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4629	idlen1 = sizeof(*t10id) + devidlen;
4630	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4631	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4632	if (scsiname != NULL) {
4633		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4634		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4635	}
4636	eui = ctl_get_opt(&be_lun->options, "eui");
4637	if (eui != NULL) {
4638		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4639	}
4640	naa = ctl_get_opt(&be_lun->options, "naa");
4641	if (naa != NULL) {
4642		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4643	}
4644	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4645	    M_CTL, M_WAITOK | M_ZERO);
4646	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4647	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4648	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4649	desc->length = idlen1;
4650	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4651	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4652	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4653		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4654	} else {
4655		strncpy(t10id->vendor, vendor,
4656		    min(sizeof(t10id->vendor), strlen(vendor)));
4657	}
4658	strncpy((char *)t10id->vendor_spec_id,
4659	    (char *)be_lun->device_id, devidlen);
4660	if (scsiname != NULL) {
4661		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4662		    desc->length);
4663		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4664		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4665		    SVPD_ID_TYPE_SCSI_NAME;
4666		desc->length = idlen2;
4667		strlcpy(desc->identifier, scsiname, idlen2);
4668	}
4669	if (eui != NULL) {
4670		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4671		    desc->length);
4672		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4673		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4674		    SVPD_ID_TYPE_EUI64;
4675		desc->length = hex2bin(eui, desc->identifier, 16);
4676		desc->length = desc->length > 12 ? 16 :
4677		    (desc->length > 8 ? 12 : 8);
4678		len -= 16 - desc->length;
4679	}
4680	if (naa != NULL) {
4681		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4682		    desc->length);
4683		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4684		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4685		    SVPD_ID_TYPE_NAA;
4686		desc->length = hex2bin(naa, desc->identifier, 16);
4687		desc->length = desc->length > 8 ? 16 : 8;
4688		len -= 16 - desc->length;
4689	}
4690	lun->lun_devid->len = len;
4691
4692	mtx_lock(&ctl_softc->ctl_lock);
4693	/*
4694	 * See if the caller requested a particular LUN number.  If so, see
4695	 * if it is available.  Otherwise, allocate the first available LUN.
4696	 */
4697	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4698		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4699		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4700			mtx_unlock(&ctl_softc->ctl_lock);
4701			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4702				printf("ctl: requested LUN ID %d is higher "
4703				       "than CTL_MAX_LUNS - 1 (%d)\n",
4704				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4705			} else {
4706				/*
4707				 * XXX KDM return an error, or just assign
4708				 * another LUN ID in this case??
4709				 */
4710				printf("ctl: requested LUN ID %d is already "
4711				       "in use\n", be_lun->req_lun_id);
4712			}
4713			if (lun->flags & CTL_LUN_MALLOCED)
4714				free(lun, M_CTL);
4715			be_lun->lun_config_status(be_lun->be_lun,
4716						  CTL_LUN_CONFIG_FAILURE);
4717			return (ENOSPC);
4718		}
4719		lun_number = be_lun->req_lun_id;
4720	} else {
4721		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4722		if (lun_number == -1) {
4723			mtx_unlock(&ctl_softc->ctl_lock);
4724			printf("ctl: can't allocate LUN on target %ju, out of "
4725			       "LUNs\n", (uintmax_t)target_id.id);
4726			if (lun->flags & CTL_LUN_MALLOCED)
4727				free(lun, M_CTL);
4728			be_lun->lun_config_status(be_lun->be_lun,
4729						  CTL_LUN_CONFIG_FAILURE);
4730			return (ENOSPC);
4731		}
4732	}
4733	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4734
4735	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4736	lun->target = target_id;
4737	lun->lun = lun_number;
4738	lun->be_lun = be_lun;
4739	/*
4740	 * The processor LUN is always enabled.  Disk LUNs come on line
4741	 * disabled, and must be enabled by the backend.
4742	 */
4743	lun->flags |= CTL_LUN_DISABLED;
4744	lun->backend = be_lun->be;
4745	be_lun->ctl_lun = lun;
4746	be_lun->lun_id = lun_number;
4747	atomic_add_int(&be_lun->be->num_luns, 1);
4748	if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4749		lun->flags |= CTL_LUN_OFFLINE;
4750
4751	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4752		lun->flags |= CTL_LUN_STOPPED;
4753
4754	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4755		lun->flags |= CTL_LUN_INOPERABLE;
4756
4757	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4758		lun->flags |= CTL_LUN_PRIMARY_SC;
4759
4760	value = ctl_get_opt(&be_lun->options, "readonly");
4761	if (value != NULL && strcmp(value, "on") == 0)
4762		lun->flags |= CTL_LUN_READONLY;
4763
4764	lun->ctl_softc = ctl_softc;
4765	TAILQ_INIT(&lun->ooa_queue);
4766	TAILQ_INIT(&lun->blocked_queue);
4767	STAILQ_INIT(&lun->error_list);
4768	ctl_tpc_lun_init(lun);
4769
4770	/*
4771	 * Initialize the mode and log page index.
4772	 */
4773	ctl_init_page_index(lun);
4774	ctl_init_log_page_index(lun);
4775
4776	/*
4777	 * Set the poweron UA for all initiators on this LUN only.
4778	 */
4779	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4780		lun->pending_ua[i] = CTL_UA_POWERON;
4781
4782	/*
4783	 * Now, before we insert this lun on the lun list, set the lun
4784	 * inventory changed UA for all other luns.
4785	 */
4786	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4787		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4788			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4789		}
4790	}
4791
4792	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4793
4794	ctl_softc->ctl_luns[lun_number] = lun;
4795
4796	ctl_softc->num_luns++;
4797
4798	/* Setup statistics gathering */
4799	lun->stats.device_type = be_lun->lun_type;
4800	lun->stats.lun_number = lun_number;
4801	if (lun->stats.device_type == T_DIRECT)
4802		lun->stats.blocksize = be_lun->blocksize;
4803	else
4804		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4805	for (i = 0;i < CTL_MAX_PORTS;i++)
4806		lun->stats.ports[i].targ_port = i;
4807
4808	mtx_unlock(&ctl_softc->ctl_lock);
4809
4810	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4811
4812	/*
4813	 * Run through each registered FETD and bring it online if it isn't
4814	 * already.  Enable the target ID if it hasn't been enabled, and
4815	 * enable this particular LUN.
4816	 */
4817	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4818		int retval;
4819
4820		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4821		if (retval != 0) {
4822			printf("ctl_alloc_lun: FETD %s port %d returned error "
4823			       "%d for lun_enable on target %ju lun %d\n",
4824			       port->port_name, port->targ_port, retval,
4825			       (uintmax_t)target_id.id, lun_number);
4826		} else
4827			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4828	}
4829	return (0);
4830}
4831
4832/*
4833 * Delete a LUN.
4834 * Assumptions:
4835 * - LUN has already been marked invalid and any pending I/O has been taken
4836 *   care of.
4837 */
4838static int
4839ctl_free_lun(struct ctl_lun *lun)
4840{
4841	struct ctl_softc *softc;
4842#if 0
4843	struct ctl_port *port;
4844#endif
4845	struct ctl_lun *nlun;
4846	int i;
4847
4848	softc = lun->ctl_softc;
4849
4850	mtx_assert(&softc->ctl_lock, MA_OWNED);
4851
4852	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4853
4854	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4855
4856	softc->ctl_luns[lun->lun] = NULL;
4857
4858	if (!TAILQ_EMPTY(&lun->ooa_queue))
4859		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4860
4861	softc->num_luns--;
4862
4863	/*
4864	 * XXX KDM this scheme only works for a single target/multiple LUN
4865	 * setup.  It needs to be revamped for a multiple target scheme.
4866	 *
4867	 * XXX KDM this results in port->lun_disable() getting called twice,
4868	 * once when ctl_disable_lun() is called, and a second time here.
4869	 * We really need to re-think the LUN disable semantics.  There
4870	 * should probably be several steps/levels to LUN removal:
4871	 *  - disable
4872	 *  - invalidate
4873	 *  - free
4874 	 *
4875	 * Right now we only have a disable method when communicating to
4876	 * the front end ports, at least for individual LUNs.
4877	 */
4878#if 0
4879	STAILQ_FOREACH(port, &softc->port_list, links) {
4880		int retval;
4881
4882		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4883					 lun->lun);
4884		if (retval != 0) {
4885			printf("ctl_free_lun: FETD %s port %d returned error "
4886			       "%d for lun_disable on target %ju lun %jd\n",
4887			       port->port_name, port->targ_port, retval,
4888			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4889		}
4890
4891		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4892			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4893
4894			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4895			if (retval != 0) {
4896				printf("ctl_free_lun: FETD %s port %d "
4897				       "returned error %d for targ_disable on "
4898				       "target %ju\n", port->port_name,
4899				       port->targ_port, retval,
4900				       (uintmax_t)lun->target.id);
4901			} else
4902				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4903
4904			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4905				continue;
4906
4907#if 0
4908			port->port_offline(port->onoff_arg);
4909			port->status &= ~CTL_PORT_STATUS_ONLINE;
4910#endif
4911		}
4912	}
4913#endif
4914
4915	/*
4916	 * Tell the backend to free resources, if this LUN has a backend.
4917	 */
4918	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4919	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4920
4921	ctl_tpc_lun_shutdown(lun);
4922	mtx_destroy(&lun->lun_lock);
4923	free(lun->lun_devid, M_CTL);
4924	free(lun->write_buffer, M_CTL);
4925	if (lun->flags & CTL_LUN_MALLOCED)
4926		free(lun, M_CTL);
4927
4928	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4929		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4930			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4931		}
4932	}
4933
4934	return (0);
4935}
4936
4937static void
4938ctl_create_lun(struct ctl_be_lun *be_lun)
4939{
4940	struct ctl_softc *ctl_softc;
4941
4942	ctl_softc = control_softc;
4943
4944	/*
4945	 * ctl_alloc_lun() should handle all potential failure cases.
4946	 */
4947	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4948}
4949
4950int
4951ctl_add_lun(struct ctl_be_lun *be_lun)
4952{
4953	struct ctl_softc *ctl_softc = control_softc;
4954
4955	mtx_lock(&ctl_softc->ctl_lock);
4956	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4957	mtx_unlock(&ctl_softc->ctl_lock);
4958	wakeup(&ctl_softc->pending_lun_queue);
4959
4960	return (0);
4961}
4962
4963int
4964ctl_enable_lun(struct ctl_be_lun *be_lun)
4965{
4966	struct ctl_softc *ctl_softc;
4967	struct ctl_port *port, *nport;
4968	struct ctl_lun *lun;
4969	int retval;
4970
4971	ctl_softc = control_softc;
4972
4973	lun = (struct ctl_lun *)be_lun->ctl_lun;
4974
4975	mtx_lock(&ctl_softc->ctl_lock);
4976	mtx_lock(&lun->lun_lock);
4977	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4978		/*
4979		 * eh?  Why did we get called if the LUN is already
4980		 * enabled?
4981		 */
4982		mtx_unlock(&lun->lun_lock);
4983		mtx_unlock(&ctl_softc->ctl_lock);
4984		return (0);
4985	}
4986	lun->flags &= ~CTL_LUN_DISABLED;
4987	mtx_unlock(&lun->lun_lock);
4988
4989	for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4990		nport = STAILQ_NEXT(port, links);
4991
4992		/*
4993		 * Drop the lock while we call the FETD's enable routine.
4994		 * This can lead to a callback into CTL (at least in the
4995		 * case of the internal initiator frontend.
4996		 */
4997		mtx_unlock(&ctl_softc->ctl_lock);
4998		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4999		mtx_lock(&ctl_softc->ctl_lock);
5000		if (retval != 0) {
5001			printf("%s: FETD %s port %d returned error "
5002			       "%d for lun_enable on target %ju lun %jd\n",
5003			       __func__, port->port_name, port->targ_port, retval,
5004			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
5005		}
5006#if 0
5007		 else {
5008            /* NOTE:  TODO:  why does lun enable affect port status? */
5009			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
5010		}
5011#endif
5012	}
5013
5014	mtx_unlock(&ctl_softc->ctl_lock);
5015
5016	return (0);
5017}
5018
5019int
5020ctl_disable_lun(struct ctl_be_lun *be_lun)
5021{
5022	struct ctl_softc *ctl_softc;
5023	struct ctl_port *port;
5024	struct ctl_lun *lun;
5025	int retval;
5026
5027	ctl_softc = control_softc;
5028
5029	lun = (struct ctl_lun *)be_lun->ctl_lun;
5030
5031	mtx_lock(&ctl_softc->ctl_lock);
5032	mtx_lock(&lun->lun_lock);
5033	if (lun->flags & CTL_LUN_DISABLED) {
5034		mtx_unlock(&lun->lun_lock);
5035		mtx_unlock(&ctl_softc->ctl_lock);
5036		return (0);
5037	}
5038	lun->flags |= CTL_LUN_DISABLED;
5039	mtx_unlock(&lun->lun_lock);
5040
5041	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
5042		mtx_unlock(&ctl_softc->ctl_lock);
5043		/*
5044		 * Drop the lock before we call the frontend's disable
5045		 * routine, to avoid lock order reversals.
5046		 *
5047		 * XXX KDM what happens if the frontend list changes while
5048		 * we're traversing it?  It's unlikely, but should be handled.
5049		 */
5050		retval = port->lun_disable(port->targ_lun_arg, lun->target,
5051					 lun->lun);
5052		mtx_lock(&ctl_softc->ctl_lock);
5053		if (retval != 0) {
5054			printf("ctl_alloc_lun: FETD %s port %d returned error "
5055			       "%d for lun_disable on target %ju lun %jd\n",
5056			       port->port_name, port->targ_port, retval,
5057			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
5058		}
5059	}
5060
5061	mtx_unlock(&ctl_softc->ctl_lock);
5062
5063	return (0);
5064}
5065
5066int
5067ctl_start_lun(struct ctl_be_lun *be_lun)
5068{
5069	struct ctl_softc *ctl_softc;
5070	struct ctl_lun *lun;
5071
5072	ctl_softc = control_softc;
5073
5074	lun = (struct ctl_lun *)be_lun->ctl_lun;
5075
5076	mtx_lock(&lun->lun_lock);
5077	lun->flags &= ~CTL_LUN_STOPPED;
5078	mtx_unlock(&lun->lun_lock);
5079
5080	return (0);
5081}
5082
5083int
5084ctl_stop_lun(struct ctl_be_lun *be_lun)
5085{
5086	struct ctl_softc *ctl_softc;
5087	struct ctl_lun *lun;
5088
5089	ctl_softc = control_softc;
5090
5091	lun = (struct ctl_lun *)be_lun->ctl_lun;
5092
5093	mtx_lock(&lun->lun_lock);
5094	lun->flags |= CTL_LUN_STOPPED;
5095	mtx_unlock(&lun->lun_lock);
5096
5097	return (0);
5098}
5099
5100int
5101ctl_lun_offline(struct ctl_be_lun *be_lun)
5102{
5103	struct ctl_softc *ctl_softc;
5104	struct ctl_lun *lun;
5105
5106	ctl_softc = control_softc;
5107
5108	lun = (struct ctl_lun *)be_lun->ctl_lun;
5109
5110	mtx_lock(&lun->lun_lock);
5111	lun->flags |= CTL_LUN_OFFLINE;
5112	mtx_unlock(&lun->lun_lock);
5113
5114	return (0);
5115}
5116
5117int
5118ctl_lun_online(struct ctl_be_lun *be_lun)
5119{
5120	struct ctl_softc *ctl_softc;
5121	struct ctl_lun *lun;
5122
5123	ctl_softc = control_softc;
5124
5125	lun = (struct ctl_lun *)be_lun->ctl_lun;
5126
5127	mtx_lock(&lun->lun_lock);
5128	lun->flags &= ~CTL_LUN_OFFLINE;
5129	mtx_unlock(&lun->lun_lock);
5130
5131	return (0);
5132}
5133
5134int
5135ctl_invalidate_lun(struct ctl_be_lun *be_lun)
5136{
5137	struct ctl_softc *ctl_softc;
5138	struct ctl_lun *lun;
5139
5140	ctl_softc = control_softc;
5141
5142	lun = (struct ctl_lun *)be_lun->ctl_lun;
5143
5144	mtx_lock(&lun->lun_lock);
5145
5146	/*
5147	 * The LUN needs to be disabled before it can be marked invalid.
5148	 */
5149	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
5150		mtx_unlock(&lun->lun_lock);
5151		return (-1);
5152	}
5153	/*
5154	 * Mark the LUN invalid.
5155	 */
5156	lun->flags |= CTL_LUN_INVALID;
5157
5158	/*
5159	 * If there is nothing in the OOA queue, go ahead and free the LUN.
5160	 * If we have something in the OOA queue, we'll free it when the
5161	 * last I/O completes.
5162	 */
5163	if (TAILQ_EMPTY(&lun->ooa_queue)) {
5164		mtx_unlock(&lun->lun_lock);
5165		mtx_lock(&ctl_softc->ctl_lock);
5166		ctl_free_lun(lun);
5167		mtx_unlock(&ctl_softc->ctl_lock);
5168	} else
5169		mtx_unlock(&lun->lun_lock);
5170
5171	return (0);
5172}
5173
5174int
5175ctl_lun_inoperable(struct ctl_be_lun *be_lun)
5176{
5177	struct ctl_softc *ctl_softc;
5178	struct ctl_lun *lun;
5179
5180	ctl_softc = control_softc;
5181	lun = (struct ctl_lun *)be_lun->ctl_lun;
5182
5183	mtx_lock(&lun->lun_lock);
5184	lun->flags |= CTL_LUN_INOPERABLE;
5185	mtx_unlock(&lun->lun_lock);
5186
5187	return (0);
5188}
5189
5190int
5191ctl_lun_operable(struct ctl_be_lun *be_lun)
5192{
5193	struct ctl_softc *ctl_softc;
5194	struct ctl_lun *lun;
5195
5196	ctl_softc = control_softc;
5197	lun = (struct ctl_lun *)be_lun->ctl_lun;
5198
5199	mtx_lock(&lun->lun_lock);
5200	lun->flags &= ~CTL_LUN_INOPERABLE;
5201	mtx_unlock(&lun->lun_lock);
5202
5203	return (0);
5204}
5205
5206void
5207ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5208{
5209	struct ctl_lun *lun;
5210	struct ctl_softc *softc;
5211	int i;
5212
5213	softc = control_softc;
5214
5215	lun = (struct ctl_lun *)be_lun->ctl_lun;
5216
5217	mtx_lock(&lun->lun_lock);
5218
5219	for (i = 0; i < CTL_MAX_INITIATORS; i++)
5220		lun->pending_ua[i] |= CTL_UA_CAPACITY_CHANGED;
5221
5222	mtx_unlock(&lun->lun_lock);
5223}
5224
5225/*
5226 * Backend "memory move is complete" callback for requests that never
5227 * make it down to say RAIDCore's configuration code.
5228 */
5229int
5230ctl_config_move_done(union ctl_io *io)
5231{
5232	int retval;
5233
5234	retval = CTL_RETVAL_COMPLETE;
5235
5236
5237	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5238	/*
5239	 * XXX KDM this shouldn't happen, but what if it does?
5240	 */
5241	if (io->io_hdr.io_type != CTL_IO_SCSI)
5242		panic("I/O type isn't CTL_IO_SCSI!");
5243
5244	if ((io->io_hdr.port_status == 0)
5245	 && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5246	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
5247		io->io_hdr.status = CTL_SUCCESS;
5248	else if ((io->io_hdr.port_status != 0)
5249	      && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5250	      && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
5251		/*
5252		 * For hardware error sense keys, the sense key
5253		 * specific value is defined to be a retry count,
5254		 * but we use it to pass back an internal FETD
5255		 * error code.  XXX KDM  Hopefully the FETD is only
5256		 * using 16 bits for an error code, since that's
5257		 * all the space we have in the sks field.
5258		 */
5259		ctl_set_internal_failure(&io->scsiio,
5260					 /*sks_valid*/ 1,
5261					 /*retry_count*/
5262					 io->io_hdr.port_status);
5263		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5264			free(io->scsiio.kern_data_ptr, M_CTL);
5265		ctl_done(io);
5266		goto bailout;
5267	}
5268
5269	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
5270	 || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
5271	 || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5272		/*
5273		 * XXX KDM just assuming a single pointer here, and not a
5274		 * S/G list.  If we start using S/G lists for config data,
5275		 * we'll need to know how to clean them up here as well.
5276		 */
5277		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5278			free(io->scsiio.kern_data_ptr, M_CTL);
5279		/* Hopefully the user has already set the status... */
5280		ctl_done(io);
5281	} else {
5282		/*
5283		 * XXX KDM now we need to continue data movement.  Some
5284		 * options:
5285		 * - call ctl_scsiio() again?  We don't do this for data
5286		 *   writes, because for those at least we know ahead of
5287		 *   time where the write will go and how long it is.  For
5288		 *   config writes, though, that information is largely
5289		 *   contained within the write itself, thus we need to
5290		 *   parse out the data again.
5291		 *
5292		 * - Call some other function once the data is in?
5293		 */
5294		if (ctl_debug & CTL_DEBUG_CDB_DATA)
5295			ctl_data_print(io);
5296
5297		/*
5298		 * XXX KDM call ctl_scsiio() again for now, and check flag
5299		 * bits to see whether we're allocated or not.
5300		 */
5301		retval = ctl_scsiio(&io->scsiio);
5302	}
5303bailout:
5304	return (retval);
5305}
5306
5307/*
5308 * This gets called by a backend driver when it is done with a
5309 * data_submit method.
5310 */
5311void
5312ctl_data_submit_done(union ctl_io *io)
5313{
5314	/*
5315	 * If the IO_CONT flag is set, we need to call the supplied
5316	 * function to continue processing the I/O, instead of completing
5317	 * the I/O just yet.
5318	 *
5319	 * If there is an error, though, we don't want to keep processing.
5320	 * Instead, just send status back to the initiator.
5321	 */
5322	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5323	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5324	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5325	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5326		io->scsiio.io_cont(io);
5327		return;
5328	}
5329	ctl_done(io);
5330}
5331
5332/*
5333 * This gets called by a backend driver when it is done with a
5334 * configuration write.
5335 */
5336void
5337ctl_config_write_done(union ctl_io *io)
5338{
5339	uint8_t *buf;
5340
5341	/*
5342	 * If the IO_CONT flag is set, we need to call the supplied
5343	 * function to continue processing the I/O, instead of completing
5344	 * the I/O just yet.
5345	 *
5346	 * If there is an error, though, we don't want to keep processing.
5347	 * Instead, just send status back to the initiator.
5348	 */
5349	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5350	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5351	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5352	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5353		io->scsiio.io_cont(io);
5354		return;
5355	}
5356	/*
5357	 * Since a configuration write can be done for commands that actually
5358	 * have data allocated, like write buffer, and commands that have
5359	 * no data, like start/stop unit, we need to check here.
5360	 */
5361	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5362		buf = io->scsiio.kern_data_ptr;
5363	else
5364		buf = NULL;
5365	ctl_done(io);
5366	if (buf)
5367		free(buf, M_CTL);
5368}
5369
5370/*
5371 * SCSI release command.
5372 */
5373int
5374ctl_scsi_release(struct ctl_scsiio *ctsio)
5375{
5376	int length, longid, thirdparty_id, resv_id;
5377	struct ctl_softc *ctl_softc;
5378	struct ctl_lun *lun;
5379	uint32_t residx;
5380
5381	length = 0;
5382	resv_id = 0;
5383
5384	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5385
5386	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5387	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5388	ctl_softc = control_softc;
5389
5390	switch (ctsio->cdb[0]) {
5391	case RELEASE_10: {
5392		struct scsi_release_10 *cdb;
5393
5394		cdb = (struct scsi_release_10 *)ctsio->cdb;
5395
5396		if (cdb->byte2 & SR10_LONGID)
5397			longid = 1;
5398		else
5399			thirdparty_id = cdb->thirdparty_id;
5400
5401		resv_id = cdb->resv_id;
5402		length = scsi_2btoul(cdb->length);
5403		break;
5404	}
5405	}
5406
5407
5408	/*
5409	 * XXX KDM right now, we only support LUN reservation.  We don't
5410	 * support 3rd party reservations, or extent reservations, which
5411	 * might actually need the parameter list.  If we've gotten this
5412	 * far, we've got a LUN reservation.  Anything else got kicked out
5413	 * above.  So, according to SPC, ignore the length.
5414	 */
5415	length = 0;
5416
5417	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5418	 && (length > 0)) {
5419		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5420		ctsio->kern_data_len = length;
5421		ctsio->kern_total_len = length;
5422		ctsio->kern_data_resid = 0;
5423		ctsio->kern_rel_offset = 0;
5424		ctsio->kern_sg_entries = 0;
5425		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5426		ctsio->be_move_done = ctl_config_move_done;
5427		ctl_datamove((union ctl_io *)ctsio);
5428
5429		return (CTL_RETVAL_COMPLETE);
5430	}
5431
5432	if (length > 0)
5433		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5434
5435	mtx_lock(&lun->lun_lock);
5436
5437	/*
5438	 * According to SPC, it is not an error for an intiator to attempt
5439	 * to release a reservation on a LUN that isn't reserved, or that
5440	 * is reserved by another initiator.  The reservation can only be
5441	 * released, though, by the initiator who made it or by one of
5442	 * several reset type events.
5443	 */
5444	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5445			lun->flags &= ~CTL_LUN_RESERVED;
5446
5447	mtx_unlock(&lun->lun_lock);
5448
5449	ctsio->scsi_status = SCSI_STATUS_OK;
5450	ctsio->io_hdr.status = CTL_SUCCESS;
5451
5452	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5453		free(ctsio->kern_data_ptr, M_CTL);
5454		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5455	}
5456
5457	ctl_done((union ctl_io *)ctsio);
5458	return (CTL_RETVAL_COMPLETE);
5459}
5460
5461int
5462ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5463{
5464	int extent, thirdparty, longid;
5465	int resv_id, length;
5466	uint64_t thirdparty_id;
5467	struct ctl_softc *ctl_softc;
5468	struct ctl_lun *lun;
5469	uint32_t residx;
5470
5471	extent = 0;
5472	thirdparty = 0;
5473	longid = 0;
5474	resv_id = 0;
5475	length = 0;
5476	thirdparty_id = 0;
5477
5478	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5479
5480	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5481	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5482	ctl_softc = control_softc;
5483
5484	switch (ctsio->cdb[0]) {
5485	case RESERVE_10: {
5486		struct scsi_reserve_10 *cdb;
5487
5488		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5489
5490		if (cdb->byte2 & SR10_LONGID)
5491			longid = 1;
5492		else
5493			thirdparty_id = cdb->thirdparty_id;
5494
5495		resv_id = cdb->resv_id;
5496		length = scsi_2btoul(cdb->length);
5497		break;
5498	}
5499	}
5500
5501	/*
5502	 * XXX KDM right now, we only support LUN reservation.  We don't
5503	 * support 3rd party reservations, or extent reservations, which
5504	 * might actually need the parameter list.  If we've gotten this
5505	 * far, we've got a LUN reservation.  Anything else got kicked out
5506	 * above.  So, according to SPC, ignore the length.
5507	 */
5508	length = 0;
5509
5510	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5511	 && (length > 0)) {
5512		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5513		ctsio->kern_data_len = length;
5514		ctsio->kern_total_len = length;
5515		ctsio->kern_data_resid = 0;
5516		ctsio->kern_rel_offset = 0;
5517		ctsio->kern_sg_entries = 0;
5518		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5519		ctsio->be_move_done = ctl_config_move_done;
5520		ctl_datamove((union ctl_io *)ctsio);
5521
5522		return (CTL_RETVAL_COMPLETE);
5523	}
5524
5525	if (length > 0)
5526		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5527
5528	mtx_lock(&lun->lun_lock);
5529	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5530		ctl_set_reservation_conflict(ctsio);
5531		goto bailout;
5532	}
5533
5534	lun->flags |= CTL_LUN_RESERVED;
5535	lun->res_idx = residx;
5536
5537	ctsio->scsi_status = SCSI_STATUS_OK;
5538	ctsio->io_hdr.status = CTL_SUCCESS;
5539
5540bailout:
5541	mtx_unlock(&lun->lun_lock);
5542
5543	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5544		free(ctsio->kern_data_ptr, M_CTL);
5545		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5546	}
5547
5548	ctl_done((union ctl_io *)ctsio);
5549	return (CTL_RETVAL_COMPLETE);
5550}
5551
5552int
5553ctl_start_stop(struct ctl_scsiio *ctsio)
5554{
5555	struct scsi_start_stop_unit *cdb;
5556	struct ctl_lun *lun;
5557	struct ctl_softc *ctl_softc;
5558	int retval;
5559
5560	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5561
5562	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5563	ctl_softc = control_softc;
5564	retval = 0;
5565
5566	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5567
5568	/*
5569	 * XXX KDM
5570	 * We don't support the immediate bit on a stop unit.  In order to
5571	 * do that, we would need to code up a way to know that a stop is
5572	 * pending, and hold off any new commands until it completes, one
5573	 * way or another.  Then we could accept or reject those commands
5574	 * depending on its status.  We would almost need to do the reverse
5575	 * of what we do below for an immediate start -- return the copy of
5576	 * the ctl_io to the FETD with status to send to the host (and to
5577	 * free the copy!) and then free the original I/O once the stop
5578	 * actually completes.  That way, the OOA queue mechanism can work
5579	 * to block commands that shouldn't proceed.  Another alternative
5580	 * would be to put the copy in the queue in place of the original,
5581	 * and return the original back to the caller.  That could be
5582	 * slightly safer..
5583	 */
5584	if ((cdb->byte2 & SSS_IMMED)
5585	 && ((cdb->how & SSS_START) == 0)) {
5586		ctl_set_invalid_field(ctsio,
5587				      /*sks_valid*/ 1,
5588				      /*command*/ 1,
5589				      /*field*/ 1,
5590				      /*bit_valid*/ 1,
5591				      /*bit*/ 0);
5592		ctl_done((union ctl_io *)ctsio);
5593		return (CTL_RETVAL_COMPLETE);
5594	}
5595
5596	if ((lun->flags & CTL_LUN_PR_RESERVED)
5597	 && ((cdb->how & SSS_START)==0)) {
5598		uint32_t residx;
5599
5600		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5601		if (lun->pr_keys[residx] == 0
5602		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5603
5604			ctl_set_reservation_conflict(ctsio);
5605			ctl_done((union ctl_io *)ctsio);
5606			return (CTL_RETVAL_COMPLETE);
5607		}
5608	}
5609
5610	/*
5611	 * If there is no backend on this device, we can't start or stop
5612	 * it.  In theory we shouldn't get any start/stop commands in the
5613	 * first place at this level if the LUN doesn't have a backend.
5614	 * That should get stopped by the command decode code.
5615	 */
5616	if (lun->backend == NULL) {
5617		ctl_set_invalid_opcode(ctsio);
5618		ctl_done((union ctl_io *)ctsio);
5619		return (CTL_RETVAL_COMPLETE);
5620	}
5621
5622	/*
5623	 * XXX KDM Copan-specific offline behavior.
5624	 * Figure out a reasonable way to port this?
5625	 */
5626#ifdef NEEDTOPORT
5627	mtx_lock(&lun->lun_lock);
5628
5629	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5630	 && (lun->flags & CTL_LUN_OFFLINE)) {
5631		/*
5632		 * If the LUN is offline, and the on/offline bit isn't set,
5633		 * reject the start or stop.  Otherwise, let it through.
5634		 */
5635		mtx_unlock(&lun->lun_lock);
5636		ctl_set_lun_not_ready(ctsio);
5637		ctl_done((union ctl_io *)ctsio);
5638	} else {
5639		mtx_unlock(&lun->lun_lock);
5640#endif /* NEEDTOPORT */
5641		/*
5642		 * This could be a start or a stop when we're online,
5643		 * or a stop/offline or start/online.  A start or stop when
5644		 * we're offline is covered in the case above.
5645		 */
5646		/*
5647		 * In the non-immediate case, we send the request to
5648		 * the backend and return status to the user when
5649		 * it is done.
5650		 *
5651		 * In the immediate case, we allocate a new ctl_io
5652		 * to hold a copy of the request, and send that to
5653		 * the backend.  We then set good status on the
5654		 * user's request and return it immediately.
5655		 */
5656		if (cdb->byte2 & SSS_IMMED) {
5657			union ctl_io *new_io;
5658
5659			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5660			if (new_io == NULL) {
5661				ctl_set_busy(ctsio);
5662				ctl_done((union ctl_io *)ctsio);
5663			} else {
5664				ctl_copy_io((union ctl_io *)ctsio,
5665					    new_io);
5666				retval = lun->backend->config_write(new_io);
5667				ctl_set_success(ctsio);
5668				ctl_done((union ctl_io *)ctsio);
5669			}
5670		} else {
5671			retval = lun->backend->config_write(
5672				(union ctl_io *)ctsio);
5673		}
5674#ifdef NEEDTOPORT
5675	}
5676#endif
5677	return (retval);
5678}
5679
5680/*
5681 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5682 * we don't really do anything with the LBA and length fields if the user
5683 * passes them in.  Instead we'll just flush out the cache for the entire
5684 * LUN.
5685 */
5686int
5687ctl_sync_cache(struct ctl_scsiio *ctsio)
5688{
5689	struct ctl_lun *lun;
5690	struct ctl_softc *ctl_softc;
5691	uint64_t starting_lba;
5692	uint32_t block_count;
5693	int retval;
5694
5695	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5696
5697	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5698	ctl_softc = control_softc;
5699	retval = 0;
5700
5701	switch (ctsio->cdb[0]) {
5702	case SYNCHRONIZE_CACHE: {
5703		struct scsi_sync_cache *cdb;
5704		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5705
5706		starting_lba = scsi_4btoul(cdb->begin_lba);
5707		block_count = scsi_2btoul(cdb->lb_count);
5708		break;
5709	}
5710	case SYNCHRONIZE_CACHE_16: {
5711		struct scsi_sync_cache_16 *cdb;
5712		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5713
5714		starting_lba = scsi_8btou64(cdb->begin_lba);
5715		block_count = scsi_4btoul(cdb->lb_count);
5716		break;
5717	}
5718	default:
5719		ctl_set_invalid_opcode(ctsio);
5720		ctl_done((union ctl_io *)ctsio);
5721		goto bailout;
5722		break; /* NOTREACHED */
5723	}
5724
5725	/*
5726	 * We check the LBA and length, but don't do anything with them.
5727	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5728	 * get flushed.  This check will just help satisfy anyone who wants
5729	 * to see an error for an out of range LBA.
5730	 */
5731	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5732		ctl_set_lba_out_of_range(ctsio);
5733		ctl_done((union ctl_io *)ctsio);
5734		goto bailout;
5735	}
5736
5737	/*
5738	 * If this LUN has no backend, we can't flush the cache anyway.
5739	 */
5740	if (lun->backend == NULL) {
5741		ctl_set_invalid_opcode(ctsio);
5742		ctl_done((union ctl_io *)ctsio);
5743		goto bailout;
5744	}
5745
5746	/*
5747	 * Check to see whether we're configured to send the SYNCHRONIZE
5748	 * CACHE command directly to the back end.
5749	 */
5750	mtx_lock(&lun->lun_lock);
5751	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5752	 && (++(lun->sync_count) >= lun->sync_interval)) {
5753		lun->sync_count = 0;
5754		mtx_unlock(&lun->lun_lock);
5755		retval = lun->backend->config_write((union ctl_io *)ctsio);
5756	} else {
5757		mtx_unlock(&lun->lun_lock);
5758		ctl_set_success(ctsio);
5759		ctl_done((union ctl_io *)ctsio);
5760	}
5761
5762bailout:
5763
5764	return (retval);
5765}
5766
5767int
5768ctl_format(struct ctl_scsiio *ctsio)
5769{
5770	struct scsi_format *cdb;
5771	struct ctl_lun *lun;
5772	struct ctl_softc *ctl_softc;
5773	int length, defect_list_len;
5774
5775	CTL_DEBUG_PRINT(("ctl_format\n"));
5776
5777	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5778	ctl_softc = control_softc;
5779
5780	cdb = (struct scsi_format *)ctsio->cdb;
5781
5782	length = 0;
5783	if (cdb->byte2 & SF_FMTDATA) {
5784		if (cdb->byte2 & SF_LONGLIST)
5785			length = sizeof(struct scsi_format_header_long);
5786		else
5787			length = sizeof(struct scsi_format_header_short);
5788	}
5789
5790	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5791	 && (length > 0)) {
5792		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5793		ctsio->kern_data_len = length;
5794		ctsio->kern_total_len = length;
5795		ctsio->kern_data_resid = 0;
5796		ctsio->kern_rel_offset = 0;
5797		ctsio->kern_sg_entries = 0;
5798		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5799		ctsio->be_move_done = ctl_config_move_done;
5800		ctl_datamove((union ctl_io *)ctsio);
5801
5802		return (CTL_RETVAL_COMPLETE);
5803	}
5804
5805	defect_list_len = 0;
5806
5807	if (cdb->byte2 & SF_FMTDATA) {
5808		if (cdb->byte2 & SF_LONGLIST) {
5809			struct scsi_format_header_long *header;
5810
5811			header = (struct scsi_format_header_long *)
5812				ctsio->kern_data_ptr;
5813
5814			defect_list_len = scsi_4btoul(header->defect_list_len);
5815			if (defect_list_len != 0) {
5816				ctl_set_invalid_field(ctsio,
5817						      /*sks_valid*/ 1,
5818						      /*command*/ 0,
5819						      /*field*/ 2,
5820						      /*bit_valid*/ 0,
5821						      /*bit*/ 0);
5822				goto bailout;
5823			}
5824		} else {
5825			struct scsi_format_header_short *header;
5826
5827			header = (struct scsi_format_header_short *)
5828				ctsio->kern_data_ptr;
5829
5830			defect_list_len = scsi_2btoul(header->defect_list_len);
5831			if (defect_list_len != 0) {
5832				ctl_set_invalid_field(ctsio,
5833						      /*sks_valid*/ 1,
5834						      /*command*/ 0,
5835						      /*field*/ 2,
5836						      /*bit_valid*/ 0,
5837						      /*bit*/ 0);
5838				goto bailout;
5839			}
5840		}
5841	}
5842
5843	/*
5844	 * The format command will clear out the "Medium format corrupted"
5845	 * status if set by the configuration code.  That status is really
5846	 * just a way to notify the host that we have lost the media, and
5847	 * get them to issue a command that will basically make them think
5848	 * they're blowing away the media.
5849	 */
5850	mtx_lock(&lun->lun_lock);
5851	lun->flags &= ~CTL_LUN_INOPERABLE;
5852	mtx_unlock(&lun->lun_lock);
5853
5854	ctsio->scsi_status = SCSI_STATUS_OK;
5855	ctsio->io_hdr.status = CTL_SUCCESS;
5856bailout:
5857
5858	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5859		free(ctsio->kern_data_ptr, M_CTL);
5860		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5861	}
5862
5863	ctl_done((union ctl_io *)ctsio);
5864	return (CTL_RETVAL_COMPLETE);
5865}
5866
5867int
5868ctl_read_buffer(struct ctl_scsiio *ctsio)
5869{
5870	struct scsi_read_buffer *cdb;
5871	struct ctl_lun *lun;
5872	int buffer_offset, len;
5873	static uint8_t descr[4];
5874	static uint8_t echo_descr[4] = { 0 };
5875
5876	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5877
5878	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5879	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5880
5881	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5882	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5883	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5884		ctl_set_invalid_field(ctsio,
5885				      /*sks_valid*/ 1,
5886				      /*command*/ 1,
5887				      /*field*/ 1,
5888				      /*bit_valid*/ 1,
5889				      /*bit*/ 4);
5890		ctl_done((union ctl_io *)ctsio);
5891		return (CTL_RETVAL_COMPLETE);
5892	}
5893
5894	len = scsi_3btoul(cdb->length);
5895	buffer_offset = scsi_3btoul(cdb->offset);
5896
5897	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5898		ctl_set_invalid_field(ctsio,
5899				      /*sks_valid*/ 1,
5900				      /*command*/ 1,
5901				      /*field*/ 6,
5902				      /*bit_valid*/ 0,
5903				      /*bit*/ 0);
5904		ctl_done((union ctl_io *)ctsio);
5905		return (CTL_RETVAL_COMPLETE);
5906	}
5907
5908	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5909		descr[0] = 0;
5910		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5911		ctsio->kern_data_ptr = descr;
5912		len = min(len, sizeof(descr));
5913	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5914		ctsio->kern_data_ptr = echo_descr;
5915		len = min(len, sizeof(echo_descr));
5916	} else {
5917		if (lun->write_buffer == NULL) {
5918			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5919			    M_CTL, M_WAITOK);
5920		}
5921		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5922	}
5923	ctsio->kern_data_len = len;
5924	ctsio->kern_total_len = len;
5925	ctsio->kern_data_resid = 0;
5926	ctsio->kern_rel_offset = 0;
5927	ctsio->kern_sg_entries = 0;
5928	ctsio->be_move_done = ctl_config_move_done;
5929	ctl_datamove((union ctl_io *)ctsio);
5930
5931	return (CTL_RETVAL_COMPLETE);
5932}
5933
5934int
5935ctl_write_buffer(struct ctl_scsiio *ctsio)
5936{
5937	struct scsi_write_buffer *cdb;
5938	struct ctl_lun *lun;
5939	int buffer_offset, len;
5940
5941	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5942
5943	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5944	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5945
5946	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5947		ctl_set_invalid_field(ctsio,
5948				      /*sks_valid*/ 1,
5949				      /*command*/ 1,
5950				      /*field*/ 1,
5951				      /*bit_valid*/ 1,
5952				      /*bit*/ 4);
5953		ctl_done((union ctl_io *)ctsio);
5954		return (CTL_RETVAL_COMPLETE);
5955	}
5956
5957	len = scsi_3btoul(cdb->length);
5958	buffer_offset = scsi_3btoul(cdb->offset);
5959
5960	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5961		ctl_set_invalid_field(ctsio,
5962				      /*sks_valid*/ 1,
5963				      /*command*/ 1,
5964				      /*field*/ 6,
5965				      /*bit_valid*/ 0,
5966				      /*bit*/ 0);
5967		ctl_done((union ctl_io *)ctsio);
5968		return (CTL_RETVAL_COMPLETE);
5969	}
5970
5971	/*
5972	 * If we've got a kernel request that hasn't been malloced yet,
5973	 * malloc it and tell the caller the data buffer is here.
5974	 */
5975	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5976		if (lun->write_buffer == NULL) {
5977			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5978			    M_CTL, M_WAITOK);
5979		}
5980		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5981		ctsio->kern_data_len = len;
5982		ctsio->kern_total_len = len;
5983		ctsio->kern_data_resid = 0;
5984		ctsio->kern_rel_offset = 0;
5985		ctsio->kern_sg_entries = 0;
5986		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5987		ctsio->be_move_done = ctl_config_move_done;
5988		ctl_datamove((union ctl_io *)ctsio);
5989
5990		return (CTL_RETVAL_COMPLETE);
5991	}
5992
5993	ctl_done((union ctl_io *)ctsio);
5994
5995	return (CTL_RETVAL_COMPLETE);
5996}
5997
5998int
5999ctl_write_same(struct ctl_scsiio *ctsio)
6000{
6001	struct ctl_lun *lun;
6002	struct ctl_lba_len_flags *lbalen;
6003	uint64_t lba;
6004	uint32_t num_blocks;
6005	int len, retval;
6006	uint8_t byte2;
6007
6008	retval = CTL_RETVAL_COMPLETE;
6009
6010	CTL_DEBUG_PRINT(("ctl_write_same\n"));
6011
6012	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6013
6014	switch (ctsio->cdb[0]) {
6015	case WRITE_SAME_10: {
6016		struct scsi_write_same_10 *cdb;
6017
6018		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
6019
6020		lba = scsi_4btoul(cdb->addr);
6021		num_blocks = scsi_2btoul(cdb->length);
6022		byte2 = cdb->byte2;
6023		break;
6024	}
6025	case WRITE_SAME_16: {
6026		struct scsi_write_same_16 *cdb;
6027
6028		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
6029
6030		lba = scsi_8btou64(cdb->addr);
6031		num_blocks = scsi_4btoul(cdb->length);
6032		byte2 = cdb->byte2;
6033		break;
6034	}
6035	default:
6036		/*
6037		 * We got a command we don't support.  This shouldn't
6038		 * happen, commands should be filtered out above us.
6039		 */
6040		ctl_set_invalid_opcode(ctsio);
6041		ctl_done((union ctl_io *)ctsio);
6042
6043		return (CTL_RETVAL_COMPLETE);
6044		break; /* NOTREACHED */
6045	}
6046
6047	/* NDOB and ANCHOR flags can be used only together with UNMAP */
6048	if ((byte2 & SWS_UNMAP) == 0 &&
6049	    (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
6050		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
6051		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
6052		ctl_done((union ctl_io *)ctsio);
6053		return (CTL_RETVAL_COMPLETE);
6054	}
6055
6056	/*
6057	 * The first check is to make sure we're in bounds, the second
6058	 * check is to catch wrap-around problems.  If the lba + num blocks
6059	 * is less than the lba, then we've wrapped around and the block
6060	 * range is invalid anyway.
6061	 */
6062	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6063	 || ((lba + num_blocks) < lba)) {
6064		ctl_set_lba_out_of_range(ctsio);
6065		ctl_done((union ctl_io *)ctsio);
6066		return (CTL_RETVAL_COMPLETE);
6067	}
6068
6069	/* Zero number of blocks means "to the last logical block" */
6070	if (num_blocks == 0) {
6071		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
6072			ctl_set_invalid_field(ctsio,
6073					      /*sks_valid*/ 0,
6074					      /*command*/ 1,
6075					      /*field*/ 0,
6076					      /*bit_valid*/ 0,
6077					      /*bit*/ 0);
6078			ctl_done((union ctl_io *)ctsio);
6079			return (CTL_RETVAL_COMPLETE);
6080		}
6081		num_blocks = (lun->be_lun->maxlba + 1) - lba;
6082	}
6083
6084	len = lun->be_lun->blocksize;
6085
6086	/*
6087	 * If we've got a kernel request that hasn't been malloced yet,
6088	 * malloc it and tell the caller the data buffer is here.
6089	 */
6090	if ((byte2 & SWS_NDOB) == 0 &&
6091	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6092		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6093		ctsio->kern_data_len = len;
6094		ctsio->kern_total_len = len;
6095		ctsio->kern_data_resid = 0;
6096		ctsio->kern_rel_offset = 0;
6097		ctsio->kern_sg_entries = 0;
6098		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6099		ctsio->be_move_done = ctl_config_move_done;
6100		ctl_datamove((union ctl_io *)ctsio);
6101
6102		return (CTL_RETVAL_COMPLETE);
6103	}
6104
6105	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6106	lbalen->lba = lba;
6107	lbalen->len = num_blocks;
6108	lbalen->flags = byte2;
6109	retval = lun->backend->config_write((union ctl_io *)ctsio);
6110
6111	return (retval);
6112}
6113
6114int
6115ctl_unmap(struct ctl_scsiio *ctsio)
6116{
6117	struct ctl_lun *lun;
6118	struct scsi_unmap *cdb;
6119	struct ctl_ptr_len_flags *ptrlen;
6120	struct scsi_unmap_header *hdr;
6121	struct scsi_unmap_desc *buf, *end, *endnz, *range;
6122	uint64_t lba;
6123	uint32_t num_blocks;
6124	int len, retval;
6125	uint8_t byte2;
6126
6127	retval = CTL_RETVAL_COMPLETE;
6128
6129	CTL_DEBUG_PRINT(("ctl_unmap\n"));
6130
6131	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6132	cdb = (struct scsi_unmap *)ctsio->cdb;
6133
6134	len = scsi_2btoul(cdb->length);
6135	byte2 = cdb->byte2;
6136
6137	/*
6138	 * If we've got a kernel request that hasn't been malloced yet,
6139	 * malloc it and tell the caller the data buffer is here.
6140	 */
6141	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6142		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6143		ctsio->kern_data_len = len;
6144		ctsio->kern_total_len = len;
6145		ctsio->kern_data_resid = 0;
6146		ctsio->kern_rel_offset = 0;
6147		ctsio->kern_sg_entries = 0;
6148		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6149		ctsio->be_move_done = ctl_config_move_done;
6150		ctl_datamove((union ctl_io *)ctsio);
6151
6152		return (CTL_RETVAL_COMPLETE);
6153	}
6154
6155	len = ctsio->kern_total_len - ctsio->kern_data_resid;
6156	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
6157	if (len < sizeof (*hdr) ||
6158	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
6159	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
6160	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
6161		ctl_set_invalid_field(ctsio,
6162				      /*sks_valid*/ 0,
6163				      /*command*/ 0,
6164				      /*field*/ 0,
6165				      /*bit_valid*/ 0,
6166				      /*bit*/ 0);
6167		ctl_done((union ctl_io *)ctsio);
6168		return (CTL_RETVAL_COMPLETE);
6169	}
6170	len = scsi_2btoul(hdr->desc_length);
6171	buf = (struct scsi_unmap_desc *)(hdr + 1);
6172	end = buf + len / sizeof(*buf);
6173
6174	endnz = buf;
6175	for (range = buf; range < end; range++) {
6176		lba = scsi_8btou64(range->lba);
6177		num_blocks = scsi_4btoul(range->length);
6178		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6179		 || ((lba + num_blocks) < lba)) {
6180			ctl_set_lba_out_of_range(ctsio);
6181			ctl_done((union ctl_io *)ctsio);
6182			return (CTL_RETVAL_COMPLETE);
6183		}
6184		if (num_blocks != 0)
6185			endnz = range + 1;
6186	}
6187
6188	/*
6189	 * Block backend can not handle zero last range.
6190	 * Filter it out and return if there is nothing left.
6191	 */
6192	len = (uint8_t *)endnz - (uint8_t *)buf;
6193	if (len == 0) {
6194		ctl_set_success(ctsio);
6195		ctl_done((union ctl_io *)ctsio);
6196		return (CTL_RETVAL_COMPLETE);
6197	}
6198
6199	mtx_lock(&lun->lun_lock);
6200	ptrlen = (struct ctl_ptr_len_flags *)
6201	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6202	ptrlen->ptr = (void *)buf;
6203	ptrlen->len = len;
6204	ptrlen->flags = byte2;
6205	ctl_check_blocked(lun);
6206	mtx_unlock(&lun->lun_lock);
6207
6208	retval = lun->backend->config_write((union ctl_io *)ctsio);
6209	return (retval);
6210}
6211
6212/*
6213 * Note that this function currently doesn't actually do anything inside
6214 * CTL to enforce things if the DQue bit is turned on.
6215 *
6216 * Also note that this function can't be used in the default case, because
6217 * the DQue bit isn't set in the changeable mask for the control mode page
6218 * anyway.  This is just here as an example for how to implement a page
6219 * handler, and a placeholder in case we want to allow the user to turn
6220 * tagged queueing on and off.
6221 *
6222 * The D_SENSE bit handling is functional, however, and will turn
6223 * descriptor sense on and off for a given LUN.
6224 */
6225int
6226ctl_control_page_handler(struct ctl_scsiio *ctsio,
6227			 struct ctl_page_index *page_index, uint8_t *page_ptr)
6228{
6229	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6230	struct ctl_lun *lun;
6231	struct ctl_softc *softc;
6232	int set_ua;
6233	uint32_t initidx;
6234
6235	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6236	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6237	set_ua = 0;
6238
6239	user_cp = (struct scsi_control_page *)page_ptr;
6240	current_cp = (struct scsi_control_page *)
6241		(page_index->page_data + (page_index->page_len *
6242		CTL_PAGE_CURRENT));
6243	saved_cp = (struct scsi_control_page *)
6244		(page_index->page_data + (page_index->page_len *
6245		CTL_PAGE_SAVED));
6246
6247	softc = control_softc;
6248
6249	mtx_lock(&lun->lun_lock);
6250	if (((current_cp->rlec & SCP_DSENSE) == 0)
6251	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6252		/*
6253		 * Descriptor sense is currently turned off and the user
6254		 * wants to turn it on.
6255		 */
6256		current_cp->rlec |= SCP_DSENSE;
6257		saved_cp->rlec |= SCP_DSENSE;
6258		lun->flags |= CTL_LUN_SENSE_DESC;
6259		set_ua = 1;
6260	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6261		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6262		/*
6263		 * Descriptor sense is currently turned on, and the user
6264		 * wants to turn it off.
6265		 */
6266		current_cp->rlec &= ~SCP_DSENSE;
6267		saved_cp->rlec &= ~SCP_DSENSE;
6268		lun->flags &= ~CTL_LUN_SENSE_DESC;
6269		set_ua = 1;
6270	}
6271	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6272	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6273		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6274		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6275		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6276		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6277		set_ua = 1;
6278	}
6279	if ((current_cp->eca_and_aen & SCP_SWP) !=
6280	    (user_cp->eca_and_aen & SCP_SWP)) {
6281		current_cp->eca_and_aen &= ~SCP_SWP;
6282		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6283		saved_cp->eca_and_aen &= ~SCP_SWP;
6284		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6285		set_ua = 1;
6286	}
6287	if (set_ua != 0) {
6288		int i;
6289		/*
6290		 * Let other initiators know that the mode
6291		 * parameters for this LUN have changed.
6292		 */
6293		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6294			if (i == initidx)
6295				continue;
6296
6297			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6298		}
6299	}
6300	mtx_unlock(&lun->lun_lock);
6301
6302	return (0);
6303}
6304
6305int
6306ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6307		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6308{
6309	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6310	struct ctl_lun *lun;
6311	int set_ua;
6312	uint32_t initidx;
6313
6314	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6315	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6316	set_ua = 0;
6317
6318	user_cp = (struct scsi_caching_page *)page_ptr;
6319	current_cp = (struct scsi_caching_page *)
6320		(page_index->page_data + (page_index->page_len *
6321		CTL_PAGE_CURRENT));
6322	saved_cp = (struct scsi_caching_page *)
6323		(page_index->page_data + (page_index->page_len *
6324		CTL_PAGE_SAVED));
6325
6326	mtx_lock(&lun->lun_lock);
6327	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6328	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6329		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6330		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6331		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6332		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6333		set_ua = 1;
6334	}
6335	if (set_ua != 0) {
6336		int i;
6337		/*
6338		 * Let other initiators know that the mode
6339		 * parameters for this LUN have changed.
6340		 */
6341		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6342			if (i == initidx)
6343				continue;
6344
6345			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6346		}
6347	}
6348	mtx_unlock(&lun->lun_lock);
6349
6350	return (0);
6351}
6352
6353int
6354ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6355				struct ctl_page_index *page_index,
6356				uint8_t *page_ptr)
6357{
6358	uint8_t *c;
6359	int i;
6360
6361	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6362	ctl_time_io_secs =
6363		(c[0] << 8) |
6364		(c[1] << 0) |
6365		0;
6366	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6367	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6368	printf("page data:");
6369	for (i=0; i<8; i++)
6370		printf(" %.2x",page_ptr[i]);
6371	printf("\n");
6372	return (0);
6373}
6374
6375int
6376ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6377			       struct ctl_page_index *page_index,
6378			       int pc)
6379{
6380	struct copan_debugconf_subpage *page;
6381
6382	page = (struct copan_debugconf_subpage *)page_index->page_data +
6383		(page_index->page_len * pc);
6384
6385	switch (pc) {
6386	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6387	case SMS_PAGE_CTRL_DEFAULT >> 6:
6388	case SMS_PAGE_CTRL_SAVED >> 6:
6389		/*
6390		 * We don't update the changable or default bits for this page.
6391		 */
6392		break;
6393	case SMS_PAGE_CTRL_CURRENT >> 6:
6394		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6395		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6396		break;
6397	default:
6398#ifdef NEEDTOPORT
6399		EPRINT(0, "Invalid PC %d!!", pc);
6400#endif /* NEEDTOPORT */
6401		break;
6402	}
6403	return (0);
6404}
6405
6406
6407static int
6408ctl_do_mode_select(union ctl_io *io)
6409{
6410	struct scsi_mode_page_header *page_header;
6411	struct ctl_page_index *page_index;
6412	struct ctl_scsiio *ctsio;
6413	int control_dev, page_len;
6414	int page_len_offset, page_len_size;
6415	union ctl_modepage_info *modepage_info;
6416	struct ctl_lun *lun;
6417	int *len_left, *len_used;
6418	int retval, i;
6419
6420	ctsio = &io->scsiio;
6421	page_index = NULL;
6422	page_len = 0;
6423	retval = CTL_RETVAL_COMPLETE;
6424
6425	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6426
6427	if (lun->be_lun->lun_type != T_DIRECT)
6428		control_dev = 1;
6429	else
6430		control_dev = 0;
6431
6432	modepage_info = (union ctl_modepage_info *)
6433		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6434	len_left = &modepage_info->header.len_left;
6435	len_used = &modepage_info->header.len_used;
6436
6437do_next_page:
6438
6439	page_header = (struct scsi_mode_page_header *)
6440		(ctsio->kern_data_ptr + *len_used);
6441
6442	if (*len_left == 0) {
6443		free(ctsio->kern_data_ptr, M_CTL);
6444		ctl_set_success(ctsio);
6445		ctl_done((union ctl_io *)ctsio);
6446		return (CTL_RETVAL_COMPLETE);
6447	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6448
6449		free(ctsio->kern_data_ptr, M_CTL);
6450		ctl_set_param_len_error(ctsio);
6451		ctl_done((union ctl_io *)ctsio);
6452		return (CTL_RETVAL_COMPLETE);
6453
6454	} else if ((page_header->page_code & SMPH_SPF)
6455		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6456
6457		free(ctsio->kern_data_ptr, M_CTL);
6458		ctl_set_param_len_error(ctsio);
6459		ctl_done((union ctl_io *)ctsio);
6460		return (CTL_RETVAL_COMPLETE);
6461	}
6462
6463
6464	/*
6465	 * XXX KDM should we do something with the block descriptor?
6466	 */
6467	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6468
6469		if ((control_dev != 0)
6470		 && (lun->mode_pages.index[i].page_flags &
6471		     CTL_PAGE_FLAG_DISK_ONLY))
6472			continue;
6473
6474		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6475		    (page_header->page_code & SMPH_PC_MASK))
6476			continue;
6477
6478		/*
6479		 * If neither page has a subpage code, then we've got a
6480		 * match.
6481		 */
6482		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6483		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6484			page_index = &lun->mode_pages.index[i];
6485			page_len = page_header->page_length;
6486			break;
6487		}
6488
6489		/*
6490		 * If both pages have subpages, then the subpage numbers
6491		 * have to match.
6492		 */
6493		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6494		  && (page_header->page_code & SMPH_SPF)) {
6495			struct scsi_mode_page_header_sp *sph;
6496
6497			sph = (struct scsi_mode_page_header_sp *)page_header;
6498
6499			if (lun->mode_pages.index[i].subpage ==
6500			    sph->subpage) {
6501				page_index = &lun->mode_pages.index[i];
6502				page_len = scsi_2btoul(sph->page_length);
6503				break;
6504			}
6505		}
6506	}
6507
6508	/*
6509	 * If we couldn't find the page, or if we don't have a mode select
6510	 * handler for it, send back an error to the user.
6511	 */
6512	if ((page_index == NULL)
6513	 || (page_index->select_handler == NULL)) {
6514		ctl_set_invalid_field(ctsio,
6515				      /*sks_valid*/ 1,
6516				      /*command*/ 0,
6517				      /*field*/ *len_used,
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	if (page_index->page_code & SMPH_SPF) {
6526		page_len_offset = 2;
6527		page_len_size = 2;
6528	} else {
6529		page_len_size = 1;
6530		page_len_offset = 1;
6531	}
6532
6533	/*
6534	 * If the length the initiator gives us isn't the one we specify in
6535	 * the mode page header, or if they didn't specify enough data in
6536	 * the CDB to avoid truncating this page, kick out the request.
6537	 */
6538	if ((page_len != (page_index->page_len - page_len_offset -
6539			  page_len_size))
6540	 || (*len_left < page_index->page_len)) {
6541
6542
6543		ctl_set_invalid_field(ctsio,
6544				      /*sks_valid*/ 1,
6545				      /*command*/ 0,
6546				      /*field*/ *len_used + page_len_offset,
6547				      /*bit_valid*/ 0,
6548				      /*bit*/ 0);
6549		free(ctsio->kern_data_ptr, M_CTL);
6550		ctl_done((union ctl_io *)ctsio);
6551		return (CTL_RETVAL_COMPLETE);
6552	}
6553
6554	/*
6555	 * Run through the mode page, checking to make sure that the bits
6556	 * the user changed are actually legal for him to change.
6557	 */
6558	for (i = 0; i < page_index->page_len; i++) {
6559		uint8_t *user_byte, *change_mask, *current_byte;
6560		int bad_bit;
6561		int j;
6562
6563		user_byte = (uint8_t *)page_header + i;
6564		change_mask = page_index->page_data +
6565			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6566		current_byte = page_index->page_data +
6567			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6568
6569		/*
6570		 * Check to see whether the user set any bits in this byte
6571		 * that he is not allowed to set.
6572		 */
6573		if ((*user_byte & ~(*change_mask)) ==
6574		    (*current_byte & ~(*change_mask)))
6575			continue;
6576
6577		/*
6578		 * Go through bit by bit to determine which one is illegal.
6579		 */
6580		bad_bit = 0;
6581		for (j = 7; j >= 0; j--) {
6582			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6583			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6584				bad_bit = i;
6585				break;
6586			}
6587		}
6588		ctl_set_invalid_field(ctsio,
6589				      /*sks_valid*/ 1,
6590				      /*command*/ 0,
6591				      /*field*/ *len_used + i,
6592				      /*bit_valid*/ 1,
6593				      /*bit*/ bad_bit);
6594		free(ctsio->kern_data_ptr, M_CTL);
6595		ctl_done((union ctl_io *)ctsio);
6596		return (CTL_RETVAL_COMPLETE);
6597	}
6598
6599	/*
6600	 * Decrement these before we call the page handler, since we may
6601	 * end up getting called back one way or another before the handler
6602	 * returns to this context.
6603	 */
6604	*len_left -= page_index->page_len;
6605	*len_used += page_index->page_len;
6606
6607	retval = page_index->select_handler(ctsio, page_index,
6608					    (uint8_t *)page_header);
6609
6610	/*
6611	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6612	 * wait until this queued command completes to finish processing
6613	 * the mode page.  If it returns anything other than
6614	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6615	 * already set the sense information, freed the data pointer, and
6616	 * completed the io for us.
6617	 */
6618	if (retval != CTL_RETVAL_COMPLETE)
6619		goto bailout_no_done;
6620
6621	/*
6622	 * If the initiator sent us more than one page, parse the next one.
6623	 */
6624	if (*len_left > 0)
6625		goto do_next_page;
6626
6627	ctl_set_success(ctsio);
6628	free(ctsio->kern_data_ptr, M_CTL);
6629	ctl_done((union ctl_io *)ctsio);
6630
6631bailout_no_done:
6632
6633	return (CTL_RETVAL_COMPLETE);
6634
6635}
6636
6637int
6638ctl_mode_select(struct ctl_scsiio *ctsio)
6639{
6640	int param_len, pf, sp;
6641	int header_size, bd_len;
6642	int len_left, len_used;
6643	struct ctl_page_index *page_index;
6644	struct ctl_lun *lun;
6645	int control_dev, page_len;
6646	union ctl_modepage_info *modepage_info;
6647	int retval;
6648
6649	pf = 0;
6650	sp = 0;
6651	page_len = 0;
6652	len_used = 0;
6653	len_left = 0;
6654	retval = 0;
6655	bd_len = 0;
6656	page_index = NULL;
6657
6658	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6659
6660	if (lun->be_lun->lun_type != T_DIRECT)
6661		control_dev = 1;
6662	else
6663		control_dev = 0;
6664
6665	switch (ctsio->cdb[0]) {
6666	case MODE_SELECT_6: {
6667		struct scsi_mode_select_6 *cdb;
6668
6669		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6670
6671		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6672		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6673
6674		param_len = cdb->length;
6675		header_size = sizeof(struct scsi_mode_header_6);
6676		break;
6677	}
6678	case MODE_SELECT_10: {
6679		struct scsi_mode_select_10 *cdb;
6680
6681		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6682
6683		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6684		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6685
6686		param_len = scsi_2btoul(cdb->length);
6687		header_size = sizeof(struct scsi_mode_header_10);
6688		break;
6689	}
6690	default:
6691		ctl_set_invalid_opcode(ctsio);
6692		ctl_done((union ctl_io *)ctsio);
6693		return (CTL_RETVAL_COMPLETE);
6694		break; /* NOTREACHED */
6695	}
6696
6697	/*
6698	 * From SPC-3:
6699	 * "A parameter list length of zero indicates that the Data-Out Buffer
6700	 * shall be empty. This condition shall not be considered as an error."
6701	 */
6702	if (param_len == 0) {
6703		ctl_set_success(ctsio);
6704		ctl_done((union ctl_io *)ctsio);
6705		return (CTL_RETVAL_COMPLETE);
6706	}
6707
6708	/*
6709	 * Since we'll hit this the first time through, prior to
6710	 * allocation, we don't need to free a data buffer here.
6711	 */
6712	if (param_len < header_size) {
6713		ctl_set_param_len_error(ctsio);
6714		ctl_done((union ctl_io *)ctsio);
6715		return (CTL_RETVAL_COMPLETE);
6716	}
6717
6718	/*
6719	 * Allocate the data buffer and grab the user's data.  In theory,
6720	 * we shouldn't have to sanity check the parameter list length here
6721	 * because the maximum size is 64K.  We should be able to malloc
6722	 * that much without too many problems.
6723	 */
6724	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6725		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6726		ctsio->kern_data_len = param_len;
6727		ctsio->kern_total_len = param_len;
6728		ctsio->kern_data_resid = 0;
6729		ctsio->kern_rel_offset = 0;
6730		ctsio->kern_sg_entries = 0;
6731		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6732		ctsio->be_move_done = ctl_config_move_done;
6733		ctl_datamove((union ctl_io *)ctsio);
6734
6735		return (CTL_RETVAL_COMPLETE);
6736	}
6737
6738	switch (ctsio->cdb[0]) {
6739	case MODE_SELECT_6: {
6740		struct scsi_mode_header_6 *mh6;
6741
6742		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6743		bd_len = mh6->blk_desc_len;
6744		break;
6745	}
6746	case MODE_SELECT_10: {
6747		struct scsi_mode_header_10 *mh10;
6748
6749		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6750		bd_len = scsi_2btoul(mh10->blk_desc_len);
6751		break;
6752	}
6753	default:
6754		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6755		break;
6756	}
6757
6758	if (param_len < (header_size + bd_len)) {
6759		free(ctsio->kern_data_ptr, M_CTL);
6760		ctl_set_param_len_error(ctsio);
6761		ctl_done((union ctl_io *)ctsio);
6762		return (CTL_RETVAL_COMPLETE);
6763	}
6764
6765	/*
6766	 * Set the IO_CONT flag, so that if this I/O gets passed to
6767	 * ctl_config_write_done(), it'll get passed back to
6768	 * ctl_do_mode_select() for further processing, or completion if
6769	 * we're all done.
6770	 */
6771	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6772	ctsio->io_cont = ctl_do_mode_select;
6773
6774	modepage_info = (union ctl_modepage_info *)
6775		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6776
6777	memset(modepage_info, 0, sizeof(*modepage_info));
6778
6779	len_left = param_len - header_size - bd_len;
6780	len_used = header_size + bd_len;
6781
6782	modepage_info->header.len_left = len_left;
6783	modepage_info->header.len_used = len_used;
6784
6785	return (ctl_do_mode_select((union ctl_io *)ctsio));
6786}
6787
6788int
6789ctl_mode_sense(struct ctl_scsiio *ctsio)
6790{
6791	struct ctl_lun *lun;
6792	int pc, page_code, dbd, llba, subpage;
6793	int alloc_len, page_len, header_len, total_len;
6794	struct scsi_mode_block_descr *block_desc;
6795	struct ctl_page_index *page_index;
6796	int control_dev;
6797
6798	dbd = 0;
6799	llba = 0;
6800	block_desc = NULL;
6801	page_index = NULL;
6802
6803	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6804
6805	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6806
6807	if (lun->be_lun->lun_type != T_DIRECT)
6808		control_dev = 1;
6809	else
6810		control_dev = 0;
6811
6812	switch (ctsio->cdb[0]) {
6813	case MODE_SENSE_6: {
6814		struct scsi_mode_sense_6 *cdb;
6815
6816		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6817
6818		header_len = sizeof(struct scsi_mode_hdr_6);
6819		if (cdb->byte2 & SMS_DBD)
6820			dbd = 1;
6821		else
6822			header_len += sizeof(struct scsi_mode_block_descr);
6823
6824		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6825		page_code = cdb->page & SMS_PAGE_CODE;
6826		subpage = cdb->subpage;
6827		alloc_len = cdb->length;
6828		break;
6829	}
6830	case MODE_SENSE_10: {
6831		struct scsi_mode_sense_10 *cdb;
6832
6833		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6834
6835		header_len = sizeof(struct scsi_mode_hdr_10);
6836
6837		if (cdb->byte2 & SMS_DBD)
6838			dbd = 1;
6839		else
6840			header_len += sizeof(struct scsi_mode_block_descr);
6841		if (cdb->byte2 & SMS10_LLBAA)
6842			llba = 1;
6843		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6844		page_code = cdb->page & SMS_PAGE_CODE;
6845		subpage = cdb->subpage;
6846		alloc_len = scsi_2btoul(cdb->length);
6847		break;
6848	}
6849	default:
6850		ctl_set_invalid_opcode(ctsio);
6851		ctl_done((union ctl_io *)ctsio);
6852		return (CTL_RETVAL_COMPLETE);
6853		break; /* NOTREACHED */
6854	}
6855
6856	/*
6857	 * We have to make a first pass through to calculate the size of
6858	 * the pages that match the user's query.  Then we allocate enough
6859	 * memory to hold it, and actually copy the data into the buffer.
6860	 */
6861	switch (page_code) {
6862	case SMS_ALL_PAGES_PAGE: {
6863		int i;
6864
6865		page_len = 0;
6866
6867		/*
6868		 * At the moment, values other than 0 and 0xff here are
6869		 * reserved according to SPC-3.
6870		 */
6871		if ((subpage != SMS_SUBPAGE_PAGE_0)
6872		 && (subpage != SMS_SUBPAGE_ALL)) {
6873			ctl_set_invalid_field(ctsio,
6874					      /*sks_valid*/ 1,
6875					      /*command*/ 1,
6876					      /*field*/ 3,
6877					      /*bit_valid*/ 0,
6878					      /*bit*/ 0);
6879			ctl_done((union ctl_io *)ctsio);
6880			return (CTL_RETVAL_COMPLETE);
6881		}
6882
6883		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6884			if ((control_dev != 0)
6885			 && (lun->mode_pages.index[i].page_flags &
6886			     CTL_PAGE_FLAG_DISK_ONLY))
6887				continue;
6888
6889			/*
6890			 * We don't use this subpage if the user didn't
6891			 * request all subpages.
6892			 */
6893			if ((lun->mode_pages.index[i].subpage != 0)
6894			 && (subpage == SMS_SUBPAGE_PAGE_0))
6895				continue;
6896
6897#if 0
6898			printf("found page %#x len %d\n",
6899			       lun->mode_pages.index[i].page_code &
6900			       SMPH_PC_MASK,
6901			       lun->mode_pages.index[i].page_len);
6902#endif
6903			page_len += lun->mode_pages.index[i].page_len;
6904		}
6905		break;
6906	}
6907	default: {
6908		int i;
6909
6910		page_len = 0;
6911
6912		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6913			/* Look for the right page code */
6914			if ((lun->mode_pages.index[i].page_code &
6915			     SMPH_PC_MASK) != page_code)
6916				continue;
6917
6918			/* Look for the right subpage or the subpage wildcard*/
6919			if ((lun->mode_pages.index[i].subpage != subpage)
6920			 && (subpage != SMS_SUBPAGE_ALL))
6921				continue;
6922
6923			/* Make sure the page is supported for this dev type */
6924			if ((control_dev != 0)
6925			 && (lun->mode_pages.index[i].page_flags &
6926			     CTL_PAGE_FLAG_DISK_ONLY))
6927				continue;
6928
6929#if 0
6930			printf("found page %#x len %d\n",
6931			       lun->mode_pages.index[i].page_code &
6932			       SMPH_PC_MASK,
6933			       lun->mode_pages.index[i].page_len);
6934#endif
6935
6936			page_len += lun->mode_pages.index[i].page_len;
6937		}
6938
6939		if (page_len == 0) {
6940			ctl_set_invalid_field(ctsio,
6941					      /*sks_valid*/ 1,
6942					      /*command*/ 1,
6943					      /*field*/ 2,
6944					      /*bit_valid*/ 1,
6945					      /*bit*/ 5);
6946			ctl_done((union ctl_io *)ctsio);
6947			return (CTL_RETVAL_COMPLETE);
6948		}
6949		break;
6950	}
6951	}
6952
6953	total_len = header_len + page_len;
6954#if 0
6955	printf("header_len = %d, page_len = %d, total_len = %d\n",
6956	       header_len, page_len, total_len);
6957#endif
6958
6959	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6960	ctsio->kern_sg_entries = 0;
6961	ctsio->kern_data_resid = 0;
6962	ctsio->kern_rel_offset = 0;
6963	if (total_len < alloc_len) {
6964		ctsio->residual = alloc_len - total_len;
6965		ctsio->kern_data_len = total_len;
6966		ctsio->kern_total_len = total_len;
6967	} else {
6968		ctsio->residual = 0;
6969		ctsio->kern_data_len = alloc_len;
6970		ctsio->kern_total_len = alloc_len;
6971	}
6972
6973	switch (ctsio->cdb[0]) {
6974	case MODE_SENSE_6: {
6975		struct scsi_mode_hdr_6 *header;
6976
6977		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6978
6979		header->datalen = ctl_min(total_len - 1, 254);
6980		if (control_dev == 0) {
6981			header->dev_specific = 0x10; /* DPOFUA */
6982			if ((lun->flags & CTL_LUN_READONLY) ||
6983			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6984			    .eca_and_aen & SCP_SWP) != 0)
6985				    header->dev_specific |= 0x80; /* WP */
6986		}
6987		if (dbd)
6988			header->block_descr_len = 0;
6989		else
6990			header->block_descr_len =
6991				sizeof(struct scsi_mode_block_descr);
6992		block_desc = (struct scsi_mode_block_descr *)&header[1];
6993		break;
6994	}
6995	case MODE_SENSE_10: {
6996		struct scsi_mode_hdr_10 *header;
6997		int datalen;
6998
6999		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
7000
7001		datalen = ctl_min(total_len - 2, 65533);
7002		scsi_ulto2b(datalen, header->datalen);
7003		if (control_dev == 0) {
7004			header->dev_specific = 0x10; /* DPOFUA */
7005			if ((lun->flags & CTL_LUN_READONLY) ||
7006			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
7007			    .eca_and_aen & SCP_SWP) != 0)
7008				    header->dev_specific |= 0x80; /* WP */
7009		}
7010		if (dbd)
7011			scsi_ulto2b(0, header->block_descr_len);
7012		else
7013			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
7014				    header->block_descr_len);
7015		block_desc = (struct scsi_mode_block_descr *)&header[1];
7016		break;
7017	}
7018	default:
7019		panic("invalid CDB type %#x", ctsio->cdb[0]);
7020		break; /* NOTREACHED */
7021	}
7022
7023	/*
7024	 * If we've got a disk, use its blocksize in the block
7025	 * descriptor.  Otherwise, just set it to 0.
7026	 */
7027	if (dbd == 0) {
7028		if (control_dev == 0)
7029			scsi_ulto3b(lun->be_lun->blocksize,
7030				    block_desc->block_len);
7031		else
7032			scsi_ulto3b(0, block_desc->block_len);
7033	}
7034
7035	switch (page_code) {
7036	case SMS_ALL_PAGES_PAGE: {
7037		int i, data_used;
7038
7039		data_used = header_len;
7040		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7041			struct ctl_page_index *page_index;
7042
7043			page_index = &lun->mode_pages.index[i];
7044
7045			if ((control_dev != 0)
7046			 && (page_index->page_flags &
7047			    CTL_PAGE_FLAG_DISK_ONLY))
7048				continue;
7049
7050			/*
7051			 * We don't use this subpage if the user didn't
7052			 * request all subpages.  We already checked (above)
7053			 * to make sure the user only specified a subpage
7054			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
7055			 */
7056			if ((page_index->subpage != 0)
7057			 && (subpage == SMS_SUBPAGE_PAGE_0))
7058				continue;
7059
7060			/*
7061			 * Call the handler, if it exists, to update the
7062			 * page to the latest values.
7063			 */
7064			if (page_index->sense_handler != NULL)
7065				page_index->sense_handler(ctsio, page_index,pc);
7066
7067			memcpy(ctsio->kern_data_ptr + data_used,
7068			       page_index->page_data +
7069			       (page_index->page_len * pc),
7070			       page_index->page_len);
7071			data_used += page_index->page_len;
7072		}
7073		break;
7074	}
7075	default: {
7076		int i, data_used;
7077
7078		data_used = header_len;
7079
7080		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7081			struct ctl_page_index *page_index;
7082
7083			page_index = &lun->mode_pages.index[i];
7084
7085			/* Look for the right page code */
7086			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
7087				continue;
7088
7089			/* Look for the right subpage or the subpage wildcard*/
7090			if ((page_index->subpage != subpage)
7091			 && (subpage != SMS_SUBPAGE_ALL))
7092				continue;
7093
7094			/* Make sure the page is supported for this dev type */
7095			if ((control_dev != 0)
7096			 && (page_index->page_flags &
7097			     CTL_PAGE_FLAG_DISK_ONLY))
7098				continue;
7099
7100			/*
7101			 * Call the handler, if it exists, to update the
7102			 * page to the latest values.
7103			 */
7104			if (page_index->sense_handler != NULL)
7105				page_index->sense_handler(ctsio, page_index,pc);
7106
7107			memcpy(ctsio->kern_data_ptr + data_used,
7108			       page_index->page_data +
7109			       (page_index->page_len * pc),
7110			       page_index->page_len);
7111			data_used += page_index->page_len;
7112		}
7113		break;
7114	}
7115	}
7116
7117	ctsio->scsi_status = SCSI_STATUS_OK;
7118
7119	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7120	ctsio->be_move_done = ctl_config_move_done;
7121	ctl_datamove((union ctl_io *)ctsio);
7122
7123	return (CTL_RETVAL_COMPLETE);
7124}
7125
7126int
7127ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
7128			       struct ctl_page_index *page_index,
7129			       int pc)
7130{
7131	struct ctl_lun *lun;
7132	struct scsi_log_param_header *phdr;
7133	uint8_t *data;
7134	uint64_t val;
7135
7136	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7137	data = page_index->page_data;
7138
7139	if (lun->backend->lun_attr != NULL &&
7140	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
7141	     != UINT64_MAX) {
7142		phdr = (struct scsi_log_param_header *)data;
7143		scsi_ulto2b(0x0001, phdr->param_code);
7144		phdr->param_control = SLP_LBIN | SLP_LP;
7145		phdr->param_len = 8;
7146		data = (uint8_t *)(phdr + 1);
7147		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
7148		data[4] = 0x01; /* per-LUN */
7149		data += phdr->param_len;
7150	}
7151
7152	if (lun->backend->lun_attr != NULL &&
7153	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
7154	     != UINT64_MAX) {
7155		phdr = (struct scsi_log_param_header *)data;
7156		scsi_ulto2b(0x0002, phdr->param_code);
7157		phdr->param_control = SLP_LBIN | SLP_LP;
7158		phdr->param_len = 8;
7159		data = (uint8_t *)(phdr + 1);
7160		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
7161		data[4] = 0x02; /* per-pool */
7162		data += phdr->param_len;
7163	}
7164
7165	if (lun->backend->lun_attr != NULL &&
7166	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
7167	     != UINT64_MAX) {
7168		phdr = (struct scsi_log_param_header *)data;
7169		scsi_ulto2b(0x00f1, phdr->param_code);
7170		phdr->param_control = SLP_LBIN | SLP_LP;
7171		phdr->param_len = 8;
7172		data = (uint8_t *)(phdr + 1);
7173		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
7174		data[4] = 0x02; /* per-pool */
7175		data += phdr->param_len;
7176	}
7177
7178	if (lun->backend->lun_attr != NULL &&
7179	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
7180	     != UINT64_MAX) {
7181		phdr = (struct scsi_log_param_header *)data;
7182		scsi_ulto2b(0x00f2, phdr->param_code);
7183		phdr->param_control = SLP_LBIN | SLP_LP;
7184		phdr->param_len = 8;
7185		data = (uint8_t *)(phdr + 1);
7186		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
7187		data[4] = 0x02; /* per-pool */
7188		data += phdr->param_len;
7189	}
7190
7191	page_index->page_len = data - page_index->page_data;
7192	return (0);
7193}
7194
7195int
7196ctl_log_sense(struct ctl_scsiio *ctsio)
7197{
7198	struct ctl_lun *lun;
7199	int i, pc, page_code, subpage;
7200	int alloc_len, total_len;
7201	struct ctl_page_index *page_index;
7202	struct scsi_log_sense *cdb;
7203	struct scsi_log_header *header;
7204
7205	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
7206
7207	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7208	cdb = (struct scsi_log_sense *)ctsio->cdb;
7209	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
7210	page_code = cdb->page & SLS_PAGE_CODE;
7211	subpage = cdb->subpage;
7212	alloc_len = scsi_2btoul(cdb->length);
7213
7214	page_index = NULL;
7215	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
7216		page_index = &lun->log_pages.index[i];
7217
7218		/* Look for the right page code */
7219		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
7220			continue;
7221
7222		/* Look for the right subpage or the subpage wildcard*/
7223		if (page_index->subpage != subpage)
7224			continue;
7225
7226		break;
7227	}
7228	if (i >= CTL_NUM_LOG_PAGES) {
7229		ctl_set_invalid_field(ctsio,
7230				      /*sks_valid*/ 1,
7231				      /*command*/ 1,
7232				      /*field*/ 2,
7233				      /*bit_valid*/ 0,
7234				      /*bit*/ 0);
7235		ctl_done((union ctl_io *)ctsio);
7236		return (CTL_RETVAL_COMPLETE);
7237	}
7238
7239	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
7240
7241	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7242	ctsio->kern_sg_entries = 0;
7243	ctsio->kern_data_resid = 0;
7244	ctsio->kern_rel_offset = 0;
7245	if (total_len < alloc_len) {
7246		ctsio->residual = alloc_len - total_len;
7247		ctsio->kern_data_len = total_len;
7248		ctsio->kern_total_len = total_len;
7249	} else {
7250		ctsio->residual = 0;
7251		ctsio->kern_data_len = alloc_len;
7252		ctsio->kern_total_len = alloc_len;
7253	}
7254
7255	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7256	header->page = page_index->page_code;
7257	if (page_index->subpage) {
7258		header->page |= SL_SPF;
7259		header->subpage = page_index->subpage;
7260	}
7261	scsi_ulto2b(page_index->page_len, header->datalen);
7262
7263	/*
7264	 * Call the handler, if it exists, to update the
7265	 * page to the latest values.
7266	 */
7267	if (page_index->sense_handler != NULL)
7268		page_index->sense_handler(ctsio, page_index, pc);
7269
7270	memcpy(header + 1, page_index->page_data, page_index->page_len);
7271
7272	ctsio->scsi_status = SCSI_STATUS_OK;
7273	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7274	ctsio->be_move_done = ctl_config_move_done;
7275	ctl_datamove((union ctl_io *)ctsio);
7276
7277	return (CTL_RETVAL_COMPLETE);
7278}
7279
7280int
7281ctl_read_capacity(struct ctl_scsiio *ctsio)
7282{
7283	struct scsi_read_capacity *cdb;
7284	struct scsi_read_capacity_data *data;
7285	struct ctl_lun *lun;
7286	uint32_t lba;
7287
7288	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7289
7290	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7291
7292	lba = scsi_4btoul(cdb->addr);
7293	if (((cdb->pmi & SRC_PMI) == 0)
7294	 && (lba != 0)) {
7295		ctl_set_invalid_field(/*ctsio*/ ctsio,
7296				      /*sks_valid*/ 1,
7297				      /*command*/ 1,
7298				      /*field*/ 2,
7299				      /*bit_valid*/ 0,
7300				      /*bit*/ 0);
7301		ctl_done((union ctl_io *)ctsio);
7302		return (CTL_RETVAL_COMPLETE);
7303	}
7304
7305	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7306
7307	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7308	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7309	ctsio->residual = 0;
7310	ctsio->kern_data_len = sizeof(*data);
7311	ctsio->kern_total_len = sizeof(*data);
7312	ctsio->kern_data_resid = 0;
7313	ctsio->kern_rel_offset = 0;
7314	ctsio->kern_sg_entries = 0;
7315
7316	/*
7317	 * If the maximum LBA is greater than 0xfffffffe, the user must
7318	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7319	 * serivce action set.
7320	 */
7321	if (lun->be_lun->maxlba > 0xfffffffe)
7322		scsi_ulto4b(0xffffffff, data->addr);
7323	else
7324		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7325
7326	/*
7327	 * XXX KDM this may not be 512 bytes...
7328	 */
7329	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7330
7331	ctsio->scsi_status = SCSI_STATUS_OK;
7332
7333	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7334	ctsio->be_move_done = ctl_config_move_done;
7335	ctl_datamove((union ctl_io *)ctsio);
7336
7337	return (CTL_RETVAL_COMPLETE);
7338}
7339
7340int
7341ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7342{
7343	struct scsi_read_capacity_16 *cdb;
7344	struct scsi_read_capacity_data_long *data;
7345	struct ctl_lun *lun;
7346	uint64_t lba;
7347	uint32_t alloc_len;
7348
7349	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7350
7351	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7352
7353	alloc_len = scsi_4btoul(cdb->alloc_len);
7354	lba = scsi_8btou64(cdb->addr);
7355
7356	if ((cdb->reladr & SRC16_PMI)
7357	 && (lba != 0)) {
7358		ctl_set_invalid_field(/*ctsio*/ ctsio,
7359				      /*sks_valid*/ 1,
7360				      /*command*/ 1,
7361				      /*field*/ 2,
7362				      /*bit_valid*/ 0,
7363				      /*bit*/ 0);
7364		ctl_done((union ctl_io *)ctsio);
7365		return (CTL_RETVAL_COMPLETE);
7366	}
7367
7368	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7369
7370	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7371	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7372
7373	if (sizeof(*data) < alloc_len) {
7374		ctsio->residual = alloc_len - sizeof(*data);
7375		ctsio->kern_data_len = sizeof(*data);
7376		ctsio->kern_total_len = sizeof(*data);
7377	} else {
7378		ctsio->residual = 0;
7379		ctsio->kern_data_len = alloc_len;
7380		ctsio->kern_total_len = alloc_len;
7381	}
7382	ctsio->kern_data_resid = 0;
7383	ctsio->kern_rel_offset = 0;
7384	ctsio->kern_sg_entries = 0;
7385
7386	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7387	/* XXX KDM this may not be 512 bytes... */
7388	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7389	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7390	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7391	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7392		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7393
7394	ctsio->scsi_status = SCSI_STATUS_OK;
7395
7396	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7397	ctsio->be_move_done = ctl_config_move_done;
7398	ctl_datamove((union ctl_io *)ctsio);
7399
7400	return (CTL_RETVAL_COMPLETE);
7401}
7402
7403int
7404ctl_read_defect(struct ctl_scsiio *ctsio)
7405{
7406	struct scsi_read_defect_data_10 *ccb10;
7407	struct scsi_read_defect_data_12 *ccb12;
7408	struct scsi_read_defect_data_hdr_10 *data10;
7409	struct scsi_read_defect_data_hdr_12 *data12;
7410	struct ctl_lun *lun;
7411	uint32_t alloc_len, data_len;
7412	uint8_t format;
7413
7414	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7415
7416	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7417
7418	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7419		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7420		format = ccb10->format;
7421		alloc_len = scsi_2btoul(ccb10->alloc_length);
7422		data_len = sizeof(*data10);
7423	} else {
7424		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7425		format = ccb12->format;
7426		alloc_len = scsi_4btoul(ccb12->alloc_length);
7427		data_len = sizeof(*data12);
7428	}
7429	if (alloc_len == 0) {
7430		ctl_set_success(ctsio);
7431		ctl_done((union ctl_io *)ctsio);
7432		return (CTL_RETVAL_COMPLETE);
7433	}
7434
7435	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7436	if (data_len < alloc_len) {
7437		ctsio->residual = alloc_len - data_len;
7438		ctsio->kern_data_len = data_len;
7439		ctsio->kern_total_len = data_len;
7440	} else {
7441		ctsio->residual = 0;
7442		ctsio->kern_data_len = alloc_len;
7443		ctsio->kern_total_len = alloc_len;
7444	}
7445	ctsio->kern_data_resid = 0;
7446	ctsio->kern_rel_offset = 0;
7447	ctsio->kern_sg_entries = 0;
7448
7449	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7450		data10 = (struct scsi_read_defect_data_hdr_10 *)
7451		    ctsio->kern_data_ptr;
7452		data10->format = format;
7453		scsi_ulto2b(0, data10->length);
7454	} else {
7455		data12 = (struct scsi_read_defect_data_hdr_12 *)
7456		    ctsio->kern_data_ptr;
7457		data12->format = format;
7458		scsi_ulto2b(0, data12->generation);
7459		scsi_ulto4b(0, data12->length);
7460	}
7461
7462	ctsio->scsi_status = SCSI_STATUS_OK;
7463	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7464	ctsio->be_move_done = ctl_config_move_done;
7465	ctl_datamove((union ctl_io *)ctsio);
7466	return (CTL_RETVAL_COMPLETE);
7467}
7468
7469int
7470ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7471{
7472	struct scsi_maintenance_in *cdb;
7473	int retval;
7474	int alloc_len, ext, total_len = 0, g, p, pc, pg, gs, os;
7475	int num_target_port_groups, num_target_ports;
7476	struct ctl_lun *lun;
7477	struct ctl_softc *softc;
7478	struct ctl_port *port;
7479	struct scsi_target_group_data *rtg_ptr;
7480	struct scsi_target_group_data_extended *rtg_ext_ptr;
7481	struct scsi_target_port_group_descriptor *tpg_desc;
7482
7483	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7484
7485	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7486	softc = control_softc;
7487	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7488
7489	retval = CTL_RETVAL_COMPLETE;
7490
7491	switch (cdb->byte2 & STG_PDF_MASK) {
7492	case STG_PDF_LENGTH:
7493		ext = 0;
7494		break;
7495	case STG_PDF_EXTENDED:
7496		ext = 1;
7497		break;
7498	default:
7499		ctl_set_invalid_field(/*ctsio*/ ctsio,
7500				      /*sks_valid*/ 1,
7501				      /*command*/ 1,
7502				      /*field*/ 2,
7503				      /*bit_valid*/ 1,
7504				      /*bit*/ 5);
7505		ctl_done((union ctl_io *)ctsio);
7506		return(retval);
7507	}
7508
7509	if (softc->is_single)
7510		num_target_port_groups = 1;
7511	else
7512		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7513	num_target_ports = 0;
7514	mtx_lock(&softc->ctl_lock);
7515	STAILQ_FOREACH(port, &softc->port_list, links) {
7516		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7517			continue;
7518		if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7519			continue;
7520		num_target_ports++;
7521	}
7522	mtx_unlock(&softc->ctl_lock);
7523
7524	if (ext)
7525		total_len = sizeof(struct scsi_target_group_data_extended);
7526	else
7527		total_len = sizeof(struct scsi_target_group_data);
7528	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7529		num_target_port_groups +
7530	    sizeof(struct scsi_target_port_descriptor) *
7531		num_target_ports * num_target_port_groups;
7532
7533	alloc_len = scsi_4btoul(cdb->length);
7534
7535	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7536
7537	ctsio->kern_sg_entries = 0;
7538
7539	if (total_len < alloc_len) {
7540		ctsio->residual = alloc_len - total_len;
7541		ctsio->kern_data_len = total_len;
7542		ctsio->kern_total_len = total_len;
7543	} else {
7544		ctsio->residual = 0;
7545		ctsio->kern_data_len = alloc_len;
7546		ctsio->kern_total_len = alloc_len;
7547	}
7548	ctsio->kern_data_resid = 0;
7549	ctsio->kern_rel_offset = 0;
7550
7551	if (ext) {
7552		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7553		    ctsio->kern_data_ptr;
7554		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7555		rtg_ext_ptr->format_type = 0x10;
7556		rtg_ext_ptr->implicit_transition_time = 0;
7557		tpg_desc = &rtg_ext_ptr->groups[0];
7558	} else {
7559		rtg_ptr = (struct scsi_target_group_data *)
7560		    ctsio->kern_data_ptr;
7561		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7562		tpg_desc = &rtg_ptr->groups[0];
7563	}
7564
7565	mtx_lock(&softc->ctl_lock);
7566	pg = softc->port_offset / CTL_MAX_PORTS;
7567	if (softc->flags & CTL_FLAG_ACTIVE_SHELF) {
7568		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY) {
7569			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7570			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7571		} else if (lun->flags & CTL_LUN_PRIMARY_SC) {
7572			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7573			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7574		} else {
7575			gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7576			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7577		}
7578	} else {
7579		gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7580		os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7581	}
7582	for (g = 0; g < num_target_port_groups; g++) {
7583		tpg_desc->pref_state = (g == pg) ? gs : os;
7584		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP;
7585		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7586		tpg_desc->status = TPG_IMPLICIT;
7587		pc = 0;
7588		STAILQ_FOREACH(port, &softc->port_list, links) {
7589			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7590				continue;
7591			if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7592			    CTL_MAX_LUNS)
7593				continue;
7594			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7595			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7596			    relative_target_port_identifier);
7597			pc++;
7598		}
7599		tpg_desc->target_port_count = pc;
7600		tpg_desc = (struct scsi_target_port_group_descriptor *)
7601		    &tpg_desc->descriptors[pc];
7602	}
7603	mtx_unlock(&softc->ctl_lock);
7604
7605	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7606	ctsio->be_move_done = ctl_config_move_done;
7607
7608	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7609			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7610			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7611			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7612			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7613
7614	ctl_datamove((union ctl_io *)ctsio);
7615	return(retval);
7616}
7617
7618int
7619ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7620{
7621	struct ctl_lun *lun;
7622	struct scsi_report_supported_opcodes *cdb;
7623	const struct ctl_cmd_entry *entry, *sentry;
7624	struct scsi_report_supported_opcodes_all *all;
7625	struct scsi_report_supported_opcodes_descr *descr;
7626	struct scsi_report_supported_opcodes_one *one;
7627	int retval;
7628	int alloc_len, total_len;
7629	int opcode, service_action, i, j, num;
7630
7631	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7632
7633	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7634	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7635
7636	retval = CTL_RETVAL_COMPLETE;
7637
7638	opcode = cdb->requested_opcode;
7639	service_action = scsi_2btoul(cdb->requested_service_action);
7640	switch (cdb->options & RSO_OPTIONS_MASK) {
7641	case RSO_OPTIONS_ALL:
7642		num = 0;
7643		for (i = 0; i < 256; i++) {
7644			entry = &ctl_cmd_table[i];
7645			if (entry->flags & CTL_CMD_FLAG_SA5) {
7646				for (j = 0; j < 32; j++) {
7647					sentry = &((const struct ctl_cmd_entry *)
7648					    entry->execute)[j];
7649					if (ctl_cmd_applicable(
7650					    lun->be_lun->lun_type, sentry))
7651						num++;
7652				}
7653			} else {
7654				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7655				    entry))
7656					num++;
7657			}
7658		}
7659		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7660		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7661		break;
7662	case RSO_OPTIONS_OC:
7663		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7664			ctl_set_invalid_field(/*ctsio*/ ctsio,
7665					      /*sks_valid*/ 1,
7666					      /*command*/ 1,
7667					      /*field*/ 2,
7668					      /*bit_valid*/ 1,
7669					      /*bit*/ 2);
7670			ctl_done((union ctl_io *)ctsio);
7671			return (CTL_RETVAL_COMPLETE);
7672		}
7673		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7674		break;
7675	case RSO_OPTIONS_OC_SA:
7676		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7677		    service_action >= 32) {
7678			ctl_set_invalid_field(/*ctsio*/ ctsio,
7679					      /*sks_valid*/ 1,
7680					      /*command*/ 1,
7681					      /*field*/ 2,
7682					      /*bit_valid*/ 1,
7683					      /*bit*/ 2);
7684			ctl_done((union ctl_io *)ctsio);
7685			return (CTL_RETVAL_COMPLETE);
7686		}
7687		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7688		break;
7689	default:
7690		ctl_set_invalid_field(/*ctsio*/ ctsio,
7691				      /*sks_valid*/ 1,
7692				      /*command*/ 1,
7693				      /*field*/ 2,
7694				      /*bit_valid*/ 1,
7695				      /*bit*/ 2);
7696		ctl_done((union ctl_io *)ctsio);
7697		return (CTL_RETVAL_COMPLETE);
7698	}
7699
7700	alloc_len = scsi_4btoul(cdb->length);
7701
7702	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7703
7704	ctsio->kern_sg_entries = 0;
7705
7706	if (total_len < alloc_len) {
7707		ctsio->residual = alloc_len - total_len;
7708		ctsio->kern_data_len = total_len;
7709		ctsio->kern_total_len = total_len;
7710	} else {
7711		ctsio->residual = 0;
7712		ctsio->kern_data_len = alloc_len;
7713		ctsio->kern_total_len = alloc_len;
7714	}
7715	ctsio->kern_data_resid = 0;
7716	ctsio->kern_rel_offset = 0;
7717
7718	switch (cdb->options & RSO_OPTIONS_MASK) {
7719	case RSO_OPTIONS_ALL:
7720		all = (struct scsi_report_supported_opcodes_all *)
7721		    ctsio->kern_data_ptr;
7722		num = 0;
7723		for (i = 0; i < 256; i++) {
7724			entry = &ctl_cmd_table[i];
7725			if (entry->flags & CTL_CMD_FLAG_SA5) {
7726				for (j = 0; j < 32; j++) {
7727					sentry = &((const struct ctl_cmd_entry *)
7728					    entry->execute)[j];
7729					if (!ctl_cmd_applicable(
7730					    lun->be_lun->lun_type, sentry))
7731						continue;
7732					descr = &all->descr[num++];
7733					descr->opcode = i;
7734					scsi_ulto2b(j, descr->service_action);
7735					descr->flags = RSO_SERVACTV;
7736					scsi_ulto2b(sentry->length,
7737					    descr->cdb_length);
7738				}
7739			} else {
7740				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7741				    entry))
7742					continue;
7743				descr = &all->descr[num++];
7744				descr->opcode = i;
7745				scsi_ulto2b(0, descr->service_action);
7746				descr->flags = 0;
7747				scsi_ulto2b(entry->length, descr->cdb_length);
7748			}
7749		}
7750		scsi_ulto4b(
7751		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7752		    all->length);
7753		break;
7754	case RSO_OPTIONS_OC:
7755		one = (struct scsi_report_supported_opcodes_one *)
7756		    ctsio->kern_data_ptr;
7757		entry = &ctl_cmd_table[opcode];
7758		goto fill_one;
7759	case RSO_OPTIONS_OC_SA:
7760		one = (struct scsi_report_supported_opcodes_one *)
7761		    ctsio->kern_data_ptr;
7762		entry = &ctl_cmd_table[opcode];
7763		entry = &((const struct ctl_cmd_entry *)
7764		    entry->execute)[service_action];
7765fill_one:
7766		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7767			one->support = 3;
7768			scsi_ulto2b(entry->length, one->cdb_length);
7769			one->cdb_usage[0] = opcode;
7770			memcpy(&one->cdb_usage[1], entry->usage,
7771			    entry->length - 1);
7772		} else
7773			one->support = 1;
7774		break;
7775	}
7776
7777	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7778	ctsio->be_move_done = ctl_config_move_done;
7779
7780	ctl_datamove((union ctl_io *)ctsio);
7781	return(retval);
7782}
7783
7784int
7785ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7786{
7787	struct ctl_lun *lun;
7788	struct scsi_report_supported_tmf *cdb;
7789	struct scsi_report_supported_tmf_data *data;
7790	int retval;
7791	int alloc_len, total_len;
7792
7793	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7794
7795	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7796	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7797
7798	retval = CTL_RETVAL_COMPLETE;
7799
7800	total_len = sizeof(struct scsi_report_supported_tmf_data);
7801	alloc_len = scsi_4btoul(cdb->length);
7802
7803	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7804
7805	ctsio->kern_sg_entries = 0;
7806
7807	if (total_len < alloc_len) {
7808		ctsio->residual = alloc_len - total_len;
7809		ctsio->kern_data_len = total_len;
7810		ctsio->kern_total_len = total_len;
7811	} else {
7812		ctsio->residual = 0;
7813		ctsio->kern_data_len = alloc_len;
7814		ctsio->kern_total_len = alloc_len;
7815	}
7816	ctsio->kern_data_resid = 0;
7817	ctsio->kern_rel_offset = 0;
7818
7819	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7820	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7821	data->byte2 |= RST_ITNRS;
7822
7823	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7824	ctsio->be_move_done = ctl_config_move_done;
7825
7826	ctl_datamove((union ctl_io *)ctsio);
7827	return (retval);
7828}
7829
7830int
7831ctl_report_timestamp(struct ctl_scsiio *ctsio)
7832{
7833	struct ctl_lun *lun;
7834	struct scsi_report_timestamp *cdb;
7835	struct scsi_report_timestamp_data *data;
7836	struct timeval tv;
7837	int64_t timestamp;
7838	int retval;
7839	int alloc_len, total_len;
7840
7841	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7842
7843	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7844	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7845
7846	retval = CTL_RETVAL_COMPLETE;
7847
7848	total_len = sizeof(struct scsi_report_timestamp_data);
7849	alloc_len = scsi_4btoul(cdb->length);
7850
7851	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7852
7853	ctsio->kern_sg_entries = 0;
7854
7855	if (total_len < alloc_len) {
7856		ctsio->residual = alloc_len - total_len;
7857		ctsio->kern_data_len = total_len;
7858		ctsio->kern_total_len = total_len;
7859	} else {
7860		ctsio->residual = 0;
7861		ctsio->kern_data_len = alloc_len;
7862		ctsio->kern_total_len = alloc_len;
7863	}
7864	ctsio->kern_data_resid = 0;
7865	ctsio->kern_rel_offset = 0;
7866
7867	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7868	scsi_ulto2b(sizeof(*data) - 2, data->length);
7869	data->origin = RTS_ORIG_OUTSIDE;
7870	getmicrotime(&tv);
7871	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7872	scsi_ulto4b(timestamp >> 16, data->timestamp);
7873	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7874
7875	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7876	ctsio->be_move_done = ctl_config_move_done;
7877
7878	ctl_datamove((union ctl_io *)ctsio);
7879	return (retval);
7880}
7881
7882int
7883ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7884{
7885	struct scsi_per_res_in *cdb;
7886	int alloc_len, total_len = 0;
7887	/* struct scsi_per_res_in_rsrv in_data; */
7888	struct ctl_lun *lun;
7889	struct ctl_softc *softc;
7890
7891	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7892
7893	softc = control_softc;
7894
7895	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7896
7897	alloc_len = scsi_2btoul(cdb->length);
7898
7899	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7900
7901retry:
7902	mtx_lock(&lun->lun_lock);
7903	switch (cdb->action) {
7904	case SPRI_RK: /* read keys */
7905		total_len = sizeof(struct scsi_per_res_in_keys) +
7906			lun->pr_key_count *
7907			sizeof(struct scsi_per_res_key);
7908		break;
7909	case SPRI_RR: /* read reservation */
7910		if (lun->flags & CTL_LUN_PR_RESERVED)
7911			total_len = sizeof(struct scsi_per_res_in_rsrv);
7912		else
7913			total_len = sizeof(struct scsi_per_res_in_header);
7914		break;
7915	case SPRI_RC: /* report capabilities */
7916		total_len = sizeof(struct scsi_per_res_cap);
7917		break;
7918	case SPRI_RS: /* read full status */
7919		total_len = sizeof(struct scsi_per_res_in_header) +
7920		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7921		    lun->pr_key_count;
7922		break;
7923	default:
7924		panic("Invalid PR type %x", cdb->action);
7925	}
7926	mtx_unlock(&lun->lun_lock);
7927
7928	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7929
7930	if (total_len < alloc_len) {
7931		ctsio->residual = alloc_len - total_len;
7932		ctsio->kern_data_len = total_len;
7933		ctsio->kern_total_len = total_len;
7934	} else {
7935		ctsio->residual = 0;
7936		ctsio->kern_data_len = alloc_len;
7937		ctsio->kern_total_len = alloc_len;
7938	}
7939
7940	ctsio->kern_data_resid = 0;
7941	ctsio->kern_rel_offset = 0;
7942	ctsio->kern_sg_entries = 0;
7943
7944	mtx_lock(&lun->lun_lock);
7945	switch (cdb->action) {
7946	case SPRI_RK: { // read keys
7947        struct scsi_per_res_in_keys *res_keys;
7948		int i, key_count;
7949
7950		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7951
7952		/*
7953		 * We had to drop the lock to allocate our buffer, which
7954		 * leaves time for someone to come in with another
7955		 * persistent reservation.  (That is unlikely, though,
7956		 * since this should be the only persistent reservation
7957		 * command active right now.)
7958		 */
7959		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7960		    (lun->pr_key_count *
7961		     sizeof(struct scsi_per_res_key)))){
7962			mtx_unlock(&lun->lun_lock);
7963			free(ctsio->kern_data_ptr, M_CTL);
7964			printf("%s: reservation length changed, retrying\n",
7965			       __func__);
7966			goto retry;
7967		}
7968
7969		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7970
7971		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7972			     lun->pr_key_count, res_keys->header.length);
7973
7974		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7975			if (lun->pr_keys[i] == 0)
7976				continue;
7977
7978			/*
7979			 * We used lun->pr_key_count to calculate the
7980			 * size to allocate.  If it turns out the number of
7981			 * initiators with the registered flag set is
7982			 * larger than that (i.e. they haven't been kept in
7983			 * sync), we've got a problem.
7984			 */
7985			if (key_count >= lun->pr_key_count) {
7986#ifdef NEEDTOPORT
7987				csevent_log(CSC_CTL | CSC_SHELF_SW |
7988					    CTL_PR_ERROR,
7989					    csevent_LogType_Fault,
7990					    csevent_AlertLevel_Yellow,
7991					    csevent_FRU_ShelfController,
7992					    csevent_FRU_Firmware,
7993				        csevent_FRU_Unknown,
7994					    "registered keys %d >= key "
7995					    "count %d", key_count,
7996					    lun->pr_key_count);
7997#endif
7998				key_count++;
7999				continue;
8000			}
8001			scsi_u64to8b(lun->pr_keys[i],
8002			    res_keys->keys[key_count].key);
8003			key_count++;
8004		}
8005		break;
8006	}
8007	case SPRI_RR: { // read reservation
8008		struct scsi_per_res_in_rsrv *res;
8009		int tmp_len, header_only;
8010
8011		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
8012
8013		scsi_ulto4b(lun->PRGeneration, res->header.generation);
8014
8015		if (lun->flags & CTL_LUN_PR_RESERVED)
8016		{
8017			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
8018			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
8019				    res->header.length);
8020			header_only = 0;
8021		} else {
8022			tmp_len = sizeof(struct scsi_per_res_in_header);
8023			scsi_ulto4b(0, res->header.length);
8024			header_only = 1;
8025		}
8026
8027		/*
8028		 * We had to drop the lock to allocate our buffer, which
8029		 * leaves time for someone to come in with another
8030		 * persistent reservation.  (That is unlikely, though,
8031		 * since this should be the only persistent reservation
8032		 * command active right now.)
8033		 */
8034		if (tmp_len != total_len) {
8035			mtx_unlock(&lun->lun_lock);
8036			free(ctsio->kern_data_ptr, M_CTL);
8037			printf("%s: reservation status changed, retrying\n",
8038			       __func__);
8039			goto retry;
8040		}
8041
8042		/*
8043		 * No reservation held, so we're done.
8044		 */
8045		if (header_only != 0)
8046			break;
8047
8048		/*
8049		 * If the registration is an All Registrants type, the key
8050		 * is 0, since it doesn't really matter.
8051		 */
8052		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8053			scsi_u64to8b(lun->pr_keys[lun->pr_res_idx],
8054			    res->data.reservation);
8055		}
8056		res->data.scopetype = lun->res_type;
8057		break;
8058	}
8059	case SPRI_RC:     //report capabilities
8060	{
8061		struct scsi_per_res_cap *res_cap;
8062		uint16_t type_mask;
8063
8064		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
8065		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
8066		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
8067		type_mask = SPRI_TM_WR_EX_AR |
8068			    SPRI_TM_EX_AC_RO |
8069			    SPRI_TM_WR_EX_RO |
8070			    SPRI_TM_EX_AC |
8071			    SPRI_TM_WR_EX |
8072			    SPRI_TM_EX_AC_AR;
8073		scsi_ulto2b(type_mask, res_cap->type_mask);
8074		break;
8075	}
8076	case SPRI_RS: { // read full status
8077		struct scsi_per_res_in_full *res_status;
8078		struct scsi_per_res_in_full_desc *res_desc;
8079		struct ctl_port *port;
8080		int i, len;
8081
8082		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
8083
8084		/*
8085		 * We had to drop the lock to allocate our buffer, which
8086		 * leaves time for someone to come in with another
8087		 * persistent reservation.  (That is unlikely, though,
8088		 * since this should be the only persistent reservation
8089		 * command active right now.)
8090		 */
8091		if (total_len < (sizeof(struct scsi_per_res_in_header) +
8092		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
8093		     lun->pr_key_count)){
8094			mtx_unlock(&lun->lun_lock);
8095			free(ctsio->kern_data_ptr, M_CTL);
8096			printf("%s: reservation length changed, retrying\n",
8097			       __func__);
8098			goto retry;
8099		}
8100
8101		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
8102
8103		res_desc = &res_status->desc[0];
8104		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
8105			if (lun->pr_keys[i] == 0)
8106				continue;
8107
8108			scsi_u64to8b(lun->pr_keys[i], res_desc->res_key.key);
8109			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
8110			    (lun->pr_res_idx == i ||
8111			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
8112				res_desc->flags = SPRI_FULL_R_HOLDER;
8113				res_desc->scopetype = lun->res_type;
8114			}
8115			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
8116			    res_desc->rel_trgt_port_id);
8117			len = 0;
8118			port = softc->ctl_ports[
8119			    ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
8120			if (port != NULL)
8121				len = ctl_create_iid(port,
8122				    i % CTL_MAX_INIT_PER_PORT,
8123				    res_desc->transport_id);
8124			scsi_ulto4b(len, res_desc->additional_length);
8125			res_desc = (struct scsi_per_res_in_full_desc *)
8126			    &res_desc->transport_id[len];
8127		}
8128		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
8129		    res_status->header.length);
8130		break;
8131	}
8132	default:
8133		/*
8134		 * This is a bug, because we just checked for this above,
8135		 * and should have returned an error.
8136		 */
8137		panic("Invalid PR type %x", cdb->action);
8138		break; /* NOTREACHED */
8139	}
8140	mtx_unlock(&lun->lun_lock);
8141
8142	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8143	ctsio->be_move_done = ctl_config_move_done;
8144
8145	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
8146			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
8147			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
8148			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
8149			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
8150
8151	ctl_datamove((union ctl_io *)ctsio);
8152
8153	return (CTL_RETVAL_COMPLETE);
8154}
8155
8156/*
8157 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
8158 * it should return.
8159 */
8160static int
8161ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
8162		uint64_t sa_res_key, uint8_t type, uint32_t residx,
8163		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
8164		struct scsi_per_res_out_parms* param)
8165{
8166	union ctl_ha_msg persis_io;
8167	int retval, i;
8168	int isc_retval;
8169
8170	retval = 0;
8171
8172	mtx_lock(&lun->lun_lock);
8173	if (sa_res_key == 0) {
8174		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8175			/* validate scope and type */
8176			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8177			     SPR_LU_SCOPE) {
8178				mtx_unlock(&lun->lun_lock);
8179				ctl_set_invalid_field(/*ctsio*/ ctsio,
8180						      /*sks_valid*/ 1,
8181						      /*command*/ 1,
8182						      /*field*/ 2,
8183						      /*bit_valid*/ 1,
8184						      /*bit*/ 4);
8185				ctl_done((union ctl_io *)ctsio);
8186				return (1);
8187			}
8188
8189		        if (type>8 || type==2 || type==4 || type==0) {
8190				mtx_unlock(&lun->lun_lock);
8191				ctl_set_invalid_field(/*ctsio*/ ctsio,
8192       	           				      /*sks_valid*/ 1,
8193						      /*command*/ 1,
8194						      /*field*/ 2,
8195						      /*bit_valid*/ 1,
8196						      /*bit*/ 0);
8197				ctl_done((union ctl_io *)ctsio);
8198				return (1);
8199		        }
8200
8201			/*
8202			 * Unregister everybody else and build UA for
8203			 * them
8204			 */
8205			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8206				if (i == residx || lun->pr_keys[i] == 0)
8207					continue;
8208
8209				if (!persis_offset
8210				 && i <CTL_MAX_INITIATORS)
8211					lun->pending_ua[i] |=
8212						CTL_UA_REG_PREEMPT;
8213				else if (persis_offset
8214				      && i >= persis_offset)
8215					lun->pending_ua[i-persis_offset] |=
8216						CTL_UA_REG_PREEMPT;
8217				lun->pr_keys[i] = 0;
8218			}
8219			lun->pr_key_count = 1;
8220			lun->res_type = type;
8221			if (lun->res_type != SPR_TYPE_WR_EX_AR
8222			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8223				lun->pr_res_idx = residx;
8224
8225			/* send msg to other side */
8226			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8227			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8228			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8229			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8230			persis_io.pr.pr_info.res_type = type;
8231			memcpy(persis_io.pr.pr_info.sa_res_key,
8232			       param->serv_act_res_key,
8233			       sizeof(param->serv_act_res_key));
8234			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8235			     &persis_io, sizeof(persis_io), 0)) >
8236			     CTL_HA_STATUS_SUCCESS) {
8237				printf("CTL:Persis Out error returned "
8238				       "from ctl_ha_msg_send %d\n",
8239				       isc_retval);
8240			}
8241		} else {
8242			/* not all registrants */
8243			mtx_unlock(&lun->lun_lock);
8244			free(ctsio->kern_data_ptr, M_CTL);
8245			ctl_set_invalid_field(ctsio,
8246					      /*sks_valid*/ 1,
8247					      /*command*/ 0,
8248					      /*field*/ 8,
8249					      /*bit_valid*/ 0,
8250					      /*bit*/ 0);
8251			ctl_done((union ctl_io *)ctsio);
8252			return (1);
8253		}
8254	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8255		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8256		int found = 0;
8257
8258		if (res_key == sa_res_key) {
8259			/* special case */
8260			/*
8261			 * The spec implies this is not good but doesn't
8262			 * say what to do. There are two choices either
8263			 * generate a res conflict or check condition
8264			 * with illegal field in parameter data. Since
8265			 * that is what is done when the sa_res_key is
8266			 * zero I'll take that approach since this has
8267			 * to do with the sa_res_key.
8268			 */
8269			mtx_unlock(&lun->lun_lock);
8270			free(ctsio->kern_data_ptr, M_CTL);
8271			ctl_set_invalid_field(ctsio,
8272					      /*sks_valid*/ 1,
8273					      /*command*/ 0,
8274					      /*field*/ 8,
8275					      /*bit_valid*/ 0,
8276					      /*bit*/ 0);
8277			ctl_done((union ctl_io *)ctsio);
8278			return (1);
8279		}
8280
8281		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8282			if (lun->pr_keys[i] != sa_res_key)
8283				continue;
8284
8285			found = 1;
8286			lun->pr_keys[i] = 0;
8287			lun->pr_key_count--;
8288
8289			if (!persis_offset && i < CTL_MAX_INITIATORS)
8290				lun->pending_ua[i] |= CTL_UA_REG_PREEMPT;
8291			else if (persis_offset && i >= persis_offset)
8292				lun->pending_ua[i-persis_offset] |=
8293					CTL_UA_REG_PREEMPT;
8294		}
8295		if (!found) {
8296			mtx_unlock(&lun->lun_lock);
8297			free(ctsio->kern_data_ptr, M_CTL);
8298			ctl_set_reservation_conflict(ctsio);
8299			ctl_done((union ctl_io *)ctsio);
8300			return (CTL_RETVAL_COMPLETE);
8301		}
8302		/* send msg to other side */
8303		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8304		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8305		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8306		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8307		persis_io.pr.pr_info.res_type = type;
8308		memcpy(persis_io.pr.pr_info.sa_res_key,
8309		       param->serv_act_res_key,
8310		       sizeof(param->serv_act_res_key));
8311		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8312		     &persis_io, sizeof(persis_io), 0)) >
8313		     CTL_HA_STATUS_SUCCESS) {
8314			printf("CTL:Persis Out error returned from "
8315			       "ctl_ha_msg_send %d\n", isc_retval);
8316		}
8317	} else {
8318		/* Reserved but not all registrants */
8319		/* sa_res_key is res holder */
8320		if (sa_res_key == lun->pr_keys[lun->pr_res_idx]) {
8321			/* validate scope and type */
8322			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8323			     SPR_LU_SCOPE) {
8324				mtx_unlock(&lun->lun_lock);
8325				ctl_set_invalid_field(/*ctsio*/ ctsio,
8326						      /*sks_valid*/ 1,
8327						      /*command*/ 1,
8328						      /*field*/ 2,
8329						      /*bit_valid*/ 1,
8330						      /*bit*/ 4);
8331				ctl_done((union ctl_io *)ctsio);
8332				return (1);
8333			}
8334
8335			if (type>8 || type==2 || type==4 || type==0) {
8336				mtx_unlock(&lun->lun_lock);
8337				ctl_set_invalid_field(/*ctsio*/ ctsio,
8338						      /*sks_valid*/ 1,
8339						      /*command*/ 1,
8340						      /*field*/ 2,
8341						      /*bit_valid*/ 1,
8342						      /*bit*/ 0);
8343				ctl_done((union ctl_io *)ctsio);
8344				return (1);
8345			}
8346
8347			/*
8348			 * Do the following:
8349			 * if sa_res_key != res_key remove all
8350			 * registrants w/sa_res_key and generate UA
8351			 * for these registrants(Registrations
8352			 * Preempted) if it wasn't an exclusive
8353			 * reservation generate UA(Reservations
8354			 * Preempted) for all other registered nexuses
8355			 * if the type has changed. Establish the new
8356			 * reservation and holder. If res_key and
8357			 * sa_res_key are the same do the above
8358			 * except don't unregister the res holder.
8359			 */
8360
8361			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8362				if (i == residx || lun->pr_keys[i] == 0)
8363					continue;
8364
8365				if (sa_res_key == lun->pr_keys[i]) {
8366					lun->pr_keys[i] = 0;
8367					lun->pr_key_count--;
8368
8369					if (!persis_offset
8370					 && i < CTL_MAX_INITIATORS)
8371						lun->pending_ua[i] |=
8372							CTL_UA_REG_PREEMPT;
8373					else if (persis_offset
8374					      && i >= persis_offset)
8375						lun->pending_ua[i-persis_offset] |=
8376						  CTL_UA_REG_PREEMPT;
8377				} else if (type != lun->res_type
8378					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8379					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8380						if (!persis_offset
8381						 && i < CTL_MAX_INITIATORS)
8382							lun->pending_ua[i] |=
8383							CTL_UA_RES_RELEASE;
8384						else if (persis_offset
8385						      && i >= persis_offset)
8386							lun->pending_ua[
8387							i-persis_offset] |=
8388							CTL_UA_RES_RELEASE;
8389				}
8390			}
8391			lun->res_type = type;
8392			if (lun->res_type != SPR_TYPE_WR_EX_AR
8393			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8394				lun->pr_res_idx = residx;
8395			else
8396				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8397
8398			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8399			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8400			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8401			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8402			persis_io.pr.pr_info.res_type = type;
8403			memcpy(persis_io.pr.pr_info.sa_res_key,
8404			       param->serv_act_res_key,
8405			       sizeof(param->serv_act_res_key));
8406			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8407			     &persis_io, sizeof(persis_io), 0)) >
8408			     CTL_HA_STATUS_SUCCESS) {
8409				printf("CTL:Persis Out error returned "
8410				       "from ctl_ha_msg_send %d\n",
8411				       isc_retval);
8412			}
8413		} else {
8414			/*
8415			 * sa_res_key is not the res holder just
8416			 * remove registrants
8417			 */
8418			int found=0;
8419
8420			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8421				if (sa_res_key != lun->pr_keys[i])
8422					continue;
8423
8424				found = 1;
8425				lun->pr_keys[i] = 0;
8426				lun->pr_key_count--;
8427
8428				if (!persis_offset
8429				 && i < CTL_MAX_INITIATORS)
8430					lun->pending_ua[i] |=
8431						CTL_UA_REG_PREEMPT;
8432				else if (persis_offset
8433				      && i >= persis_offset)
8434					lun->pending_ua[i-persis_offset] |=
8435						CTL_UA_REG_PREEMPT;
8436			}
8437
8438			if (!found) {
8439				mtx_unlock(&lun->lun_lock);
8440				free(ctsio->kern_data_ptr, M_CTL);
8441				ctl_set_reservation_conflict(ctsio);
8442				ctl_done((union ctl_io *)ctsio);
8443		        	return (1);
8444			}
8445			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8446			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8447			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8448			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8449			persis_io.pr.pr_info.res_type = type;
8450			memcpy(persis_io.pr.pr_info.sa_res_key,
8451			       param->serv_act_res_key,
8452			       sizeof(param->serv_act_res_key));
8453			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8454			     &persis_io, sizeof(persis_io), 0)) >
8455			     CTL_HA_STATUS_SUCCESS) {
8456				printf("CTL:Persis Out error returned "
8457				       "from ctl_ha_msg_send %d\n",
8458				isc_retval);
8459			}
8460		}
8461	}
8462
8463	lun->PRGeneration++;
8464	mtx_unlock(&lun->lun_lock);
8465
8466	return (retval);
8467}
8468
8469static void
8470ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8471{
8472	uint64_t sa_res_key;
8473	int i;
8474
8475	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8476
8477	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8478	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8479	 || sa_res_key != lun->pr_keys[lun->pr_res_idx]) {
8480		if (sa_res_key == 0) {
8481			/*
8482			 * Unregister everybody else and build UA for
8483			 * them
8484			 */
8485			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8486				if (i == msg->pr.pr_info.residx ||
8487				    lun->pr_keys[i] == 0)
8488					continue;
8489
8490				if (!persis_offset
8491				 && i < CTL_MAX_INITIATORS)
8492					lun->pending_ua[i] |=
8493						CTL_UA_REG_PREEMPT;
8494				else if (persis_offset && i >= persis_offset)
8495					lun->pending_ua[i - persis_offset] |=
8496						CTL_UA_REG_PREEMPT;
8497				lun->pr_keys[i] = 0;
8498			}
8499
8500			lun->pr_key_count = 1;
8501			lun->res_type = msg->pr.pr_info.res_type;
8502			if (lun->res_type != SPR_TYPE_WR_EX_AR
8503			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8504				lun->pr_res_idx = msg->pr.pr_info.residx;
8505		} else {
8506		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8507				if (sa_res_key == lun->pr_keys[i])
8508					continue;
8509
8510				lun->pr_keys[i] = 0;
8511				lun->pr_key_count--;
8512
8513				if (!persis_offset
8514				 && i < persis_offset)
8515					lun->pending_ua[i] |=
8516						CTL_UA_REG_PREEMPT;
8517				else if (persis_offset
8518				      && i >= persis_offset)
8519					lun->pending_ua[i - persis_offset] |=
8520						CTL_UA_REG_PREEMPT;
8521			}
8522		}
8523	} else {
8524		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8525			if (i == msg->pr.pr_info.residx ||
8526			    lun->pr_keys[i] == 0)
8527				continue;
8528
8529			if (sa_res_key == lun->pr_keys[i]) {
8530				lun->pr_keys[i] = 0;
8531				lun->pr_key_count--;
8532				if (!persis_offset
8533				 && i < CTL_MAX_INITIATORS)
8534					lun->pending_ua[i] |=
8535						CTL_UA_REG_PREEMPT;
8536				else if (persis_offset
8537				      && i >= persis_offset)
8538					lun->pending_ua[i - persis_offset] |=
8539						CTL_UA_REG_PREEMPT;
8540			} else if (msg->pr.pr_info.res_type != lun->res_type
8541				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8542				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8543					if (!persis_offset
8544					 && i < persis_offset)
8545						lun->pending_ua[i] |=
8546							CTL_UA_RES_RELEASE;
8547					else if (persis_offset
8548					      && i >= persis_offset)
8549					lun->pending_ua[i - persis_offset] |=
8550						CTL_UA_RES_RELEASE;
8551			}
8552		}
8553		lun->res_type = msg->pr.pr_info.res_type;
8554		if (lun->res_type != SPR_TYPE_WR_EX_AR
8555		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8556			lun->pr_res_idx = msg->pr.pr_info.residx;
8557		else
8558			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8559	}
8560	lun->PRGeneration++;
8561
8562}
8563
8564
8565int
8566ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8567{
8568	int retval;
8569	int isc_retval;
8570	u_int32_t param_len;
8571	struct scsi_per_res_out *cdb;
8572	struct ctl_lun *lun;
8573	struct scsi_per_res_out_parms* param;
8574	struct ctl_softc *softc;
8575	uint32_t residx;
8576	uint64_t res_key, sa_res_key;
8577	uint8_t type;
8578	union ctl_ha_msg persis_io;
8579	int    i;
8580
8581	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8582
8583	retval = CTL_RETVAL_COMPLETE;
8584
8585	softc = control_softc;
8586
8587	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8588	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8589
8590	/*
8591	 * We only support whole-LUN scope.  The scope & type are ignored for
8592	 * register, register and ignore existing key and clear.
8593	 * We sometimes ignore scope and type on preempts too!!
8594	 * Verify reservation type here as well.
8595	 */
8596	type = cdb->scope_type & SPR_TYPE_MASK;
8597	if ((cdb->action == SPRO_RESERVE)
8598	 || (cdb->action == SPRO_RELEASE)) {
8599		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8600			ctl_set_invalid_field(/*ctsio*/ ctsio,
8601					      /*sks_valid*/ 1,
8602					      /*command*/ 1,
8603					      /*field*/ 2,
8604					      /*bit_valid*/ 1,
8605					      /*bit*/ 4);
8606			ctl_done((union ctl_io *)ctsio);
8607			return (CTL_RETVAL_COMPLETE);
8608		}
8609
8610		if (type>8 || type==2 || type==4 || type==0) {
8611			ctl_set_invalid_field(/*ctsio*/ ctsio,
8612					      /*sks_valid*/ 1,
8613					      /*command*/ 1,
8614					      /*field*/ 2,
8615					      /*bit_valid*/ 1,
8616					      /*bit*/ 0);
8617			ctl_done((union ctl_io *)ctsio);
8618			return (CTL_RETVAL_COMPLETE);
8619		}
8620	}
8621
8622	param_len = scsi_4btoul(cdb->length);
8623
8624	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8625		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8626		ctsio->kern_data_len = param_len;
8627		ctsio->kern_total_len = param_len;
8628		ctsio->kern_data_resid = 0;
8629		ctsio->kern_rel_offset = 0;
8630		ctsio->kern_sg_entries = 0;
8631		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8632		ctsio->be_move_done = ctl_config_move_done;
8633		ctl_datamove((union ctl_io *)ctsio);
8634
8635		return (CTL_RETVAL_COMPLETE);
8636	}
8637
8638	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8639
8640	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8641	res_key = scsi_8btou64(param->res_key.key);
8642	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8643
8644	/*
8645	 * Validate the reservation key here except for SPRO_REG_IGNO
8646	 * This must be done for all other service actions
8647	 */
8648	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8649		mtx_lock(&lun->lun_lock);
8650		if (lun->pr_keys[residx] != 0) {
8651		    if (res_key != lun->pr_keys[residx]) {
8652				/*
8653				 * The current key passed in doesn't match
8654				 * the one the initiator previously
8655				 * registered.
8656				 */
8657				mtx_unlock(&lun->lun_lock);
8658				free(ctsio->kern_data_ptr, M_CTL);
8659				ctl_set_reservation_conflict(ctsio);
8660				ctl_done((union ctl_io *)ctsio);
8661				return (CTL_RETVAL_COMPLETE);
8662			}
8663		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8664			/*
8665			 * We are not registered
8666			 */
8667			mtx_unlock(&lun->lun_lock);
8668			free(ctsio->kern_data_ptr, M_CTL);
8669			ctl_set_reservation_conflict(ctsio);
8670			ctl_done((union ctl_io *)ctsio);
8671			return (CTL_RETVAL_COMPLETE);
8672		} else if (res_key != 0) {
8673			/*
8674			 * We are not registered and trying to register but
8675			 * the register key isn't zero.
8676			 */
8677			mtx_unlock(&lun->lun_lock);
8678			free(ctsio->kern_data_ptr, M_CTL);
8679			ctl_set_reservation_conflict(ctsio);
8680			ctl_done((union ctl_io *)ctsio);
8681			return (CTL_RETVAL_COMPLETE);
8682		}
8683		mtx_unlock(&lun->lun_lock);
8684	}
8685
8686	switch (cdb->action & SPRO_ACTION_MASK) {
8687	case SPRO_REGISTER:
8688	case SPRO_REG_IGNO: {
8689
8690#if 0
8691		printf("Registration received\n");
8692#endif
8693
8694		/*
8695		 * We don't support any of these options, as we report in
8696		 * the read capabilities request (see
8697		 * ctl_persistent_reserve_in(), above).
8698		 */
8699		if ((param->flags & SPR_SPEC_I_PT)
8700		 || (param->flags & SPR_ALL_TG_PT)
8701		 || (param->flags & SPR_APTPL)) {
8702			int bit_ptr;
8703
8704			if (param->flags & SPR_APTPL)
8705				bit_ptr = 0;
8706			else if (param->flags & SPR_ALL_TG_PT)
8707				bit_ptr = 2;
8708			else /* SPR_SPEC_I_PT */
8709				bit_ptr = 3;
8710
8711			free(ctsio->kern_data_ptr, M_CTL);
8712			ctl_set_invalid_field(ctsio,
8713					      /*sks_valid*/ 1,
8714					      /*command*/ 0,
8715					      /*field*/ 20,
8716					      /*bit_valid*/ 1,
8717					      /*bit*/ bit_ptr);
8718			ctl_done((union ctl_io *)ctsio);
8719			return (CTL_RETVAL_COMPLETE);
8720		}
8721
8722		mtx_lock(&lun->lun_lock);
8723
8724		/*
8725		 * The initiator wants to clear the
8726		 * key/unregister.
8727		 */
8728		if (sa_res_key == 0) {
8729			if ((res_key == 0
8730			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8731			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8732			  && lun->pr_keys[residx] == 0)) {
8733				mtx_unlock(&lun->lun_lock);
8734				goto done;
8735			}
8736
8737			lun->pr_keys[residx] = 0;
8738			lun->pr_key_count--;
8739
8740			if (residx == lun->pr_res_idx) {
8741				lun->flags &= ~CTL_LUN_PR_RESERVED;
8742				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8743
8744				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8745				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8746				 && lun->pr_key_count) {
8747					/*
8748					 * If the reservation is a registrants
8749					 * only type we need to generate a UA
8750					 * for other registered inits.  The
8751					 * sense code should be RESERVATIONS
8752					 * RELEASED
8753					 */
8754
8755					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8756						if (lun->pr_keys[
8757						    i + persis_offset] == 0)
8758							continue;
8759						lun->pending_ua[i] |=
8760							CTL_UA_RES_RELEASE;
8761					}
8762				}
8763				lun->res_type = 0;
8764			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8765				if (lun->pr_key_count==0) {
8766					lun->flags &= ~CTL_LUN_PR_RESERVED;
8767					lun->res_type = 0;
8768					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8769				}
8770			}
8771			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8772			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8773			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8774			persis_io.pr.pr_info.residx = residx;
8775			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8776			     &persis_io, sizeof(persis_io), 0 )) >
8777			     CTL_HA_STATUS_SUCCESS) {
8778				printf("CTL:Persis Out error returned from "
8779				       "ctl_ha_msg_send %d\n", isc_retval);
8780			}
8781		} else /* sa_res_key != 0 */ {
8782
8783			/*
8784			 * If we aren't registered currently then increment
8785			 * the key count and set the registered flag.
8786			 */
8787			if (lun->pr_keys[residx] == 0)
8788				lun->pr_key_count++;
8789			lun->pr_keys[residx] = sa_res_key;
8790
8791			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8792			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8793			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8794			persis_io.pr.pr_info.residx = residx;
8795			memcpy(persis_io.pr.pr_info.sa_res_key,
8796			       param->serv_act_res_key,
8797			       sizeof(param->serv_act_res_key));
8798			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8799			     &persis_io, sizeof(persis_io), 0)) >
8800			     CTL_HA_STATUS_SUCCESS) {
8801				printf("CTL:Persis Out error returned from "
8802				       "ctl_ha_msg_send %d\n", isc_retval);
8803			}
8804		}
8805		lun->PRGeneration++;
8806		mtx_unlock(&lun->lun_lock);
8807
8808		break;
8809	}
8810	case SPRO_RESERVE:
8811#if 0
8812                printf("Reserve executed type %d\n", type);
8813#endif
8814		mtx_lock(&lun->lun_lock);
8815		if (lun->flags & CTL_LUN_PR_RESERVED) {
8816			/*
8817			 * if this isn't the reservation holder and it's
8818			 * not a "all registrants" type or if the type is
8819			 * different then we have a conflict
8820			 */
8821			if ((lun->pr_res_idx != residx
8822			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8823			 || lun->res_type != type) {
8824				mtx_unlock(&lun->lun_lock);
8825				free(ctsio->kern_data_ptr, M_CTL);
8826				ctl_set_reservation_conflict(ctsio);
8827				ctl_done((union ctl_io *)ctsio);
8828				return (CTL_RETVAL_COMPLETE);
8829			}
8830			mtx_unlock(&lun->lun_lock);
8831		} else /* create a reservation */ {
8832			/*
8833			 * If it's not an "all registrants" type record
8834			 * reservation holder
8835			 */
8836			if (type != SPR_TYPE_WR_EX_AR
8837			 && type != SPR_TYPE_EX_AC_AR)
8838				lun->pr_res_idx = residx; /* Res holder */
8839			else
8840				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8841
8842			lun->flags |= CTL_LUN_PR_RESERVED;
8843			lun->res_type = type;
8844
8845			mtx_unlock(&lun->lun_lock);
8846
8847			/* send msg to other side */
8848			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8849			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8850			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8851			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8852			persis_io.pr.pr_info.res_type = type;
8853			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8854			     &persis_io, sizeof(persis_io), 0)) >
8855			     CTL_HA_STATUS_SUCCESS) {
8856				printf("CTL:Persis Out error returned from "
8857				       "ctl_ha_msg_send %d\n", isc_retval);
8858			}
8859		}
8860		break;
8861
8862	case SPRO_RELEASE:
8863		mtx_lock(&lun->lun_lock);
8864		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8865			/* No reservation exists return good status */
8866			mtx_unlock(&lun->lun_lock);
8867			goto done;
8868		}
8869		/*
8870		 * Is this nexus a reservation holder?
8871		 */
8872		if (lun->pr_res_idx != residx
8873		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8874			/*
8875			 * not a res holder return good status but
8876			 * do nothing
8877			 */
8878			mtx_unlock(&lun->lun_lock);
8879			goto done;
8880		}
8881
8882		if (lun->res_type != type) {
8883			mtx_unlock(&lun->lun_lock);
8884			free(ctsio->kern_data_ptr, M_CTL);
8885			ctl_set_illegal_pr_release(ctsio);
8886			ctl_done((union ctl_io *)ctsio);
8887			return (CTL_RETVAL_COMPLETE);
8888		}
8889
8890		/* okay to release */
8891		lun->flags &= ~CTL_LUN_PR_RESERVED;
8892		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8893		lun->res_type = 0;
8894
8895		/*
8896		 * if this isn't an exclusive access
8897		 * res generate UA for all other
8898		 * registrants.
8899		 */
8900		if (type != SPR_TYPE_EX_AC
8901		 && type != SPR_TYPE_WR_EX) {
8902			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8903				if (i == residx ||
8904				    lun->pr_keys[i + persis_offset] == 0)
8905					continue;
8906				lun->pending_ua[i] |= CTL_UA_RES_RELEASE;
8907			}
8908		}
8909		mtx_unlock(&lun->lun_lock);
8910		/* Send msg to other side */
8911		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8912		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8913		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8914		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8915		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8916			printf("CTL:Persis Out error returned from "
8917			       "ctl_ha_msg_send %d\n", isc_retval);
8918		}
8919		break;
8920
8921	case SPRO_CLEAR:
8922		/* send msg to other side */
8923
8924		mtx_lock(&lun->lun_lock);
8925		lun->flags &= ~CTL_LUN_PR_RESERVED;
8926		lun->res_type = 0;
8927		lun->pr_key_count = 0;
8928		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8929
8930		lun->pr_keys[residx] = 0;
8931
8932		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8933			if (lun->pr_keys[i] != 0) {
8934				if (!persis_offset && i < CTL_MAX_INITIATORS)
8935					lun->pending_ua[i] |=
8936						CTL_UA_RES_PREEMPT;
8937				else if (persis_offset && i >= persis_offset)
8938					lun->pending_ua[i-persis_offset] |=
8939					    CTL_UA_RES_PREEMPT;
8940
8941				lun->pr_keys[i] = 0;
8942			}
8943		lun->PRGeneration++;
8944		mtx_unlock(&lun->lun_lock);
8945		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8946		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8947		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8948		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8949		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8950			printf("CTL:Persis Out error returned from "
8951			       "ctl_ha_msg_send %d\n", isc_retval);
8952		}
8953		break;
8954
8955	case SPRO_PREEMPT:
8956	case SPRO_PRE_ABO: {
8957		int nretval;
8958
8959		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8960					  residx, ctsio, cdb, param);
8961		if (nretval != 0)
8962			return (CTL_RETVAL_COMPLETE);
8963		break;
8964	}
8965	default:
8966		panic("Invalid PR type %x", cdb->action);
8967	}
8968
8969done:
8970	free(ctsio->kern_data_ptr, M_CTL);
8971	ctl_set_success(ctsio);
8972	ctl_done((union ctl_io *)ctsio);
8973
8974	return (retval);
8975}
8976
8977/*
8978 * This routine is for handling a message from the other SC pertaining to
8979 * persistent reserve out. All the error checking will have been done
8980 * so only perorming the action need be done here to keep the two
8981 * in sync.
8982 */
8983static void
8984ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8985{
8986	struct ctl_lun *lun;
8987	struct ctl_softc *softc;
8988	int i;
8989	uint32_t targ_lun;
8990
8991	softc = control_softc;
8992
8993	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8994	lun = softc->ctl_luns[targ_lun];
8995	mtx_lock(&lun->lun_lock);
8996	switch(msg->pr.pr_info.action) {
8997	case CTL_PR_REG_KEY:
8998		if (lun->pr_keys[msg->pr.pr_info.residx] == 0)
8999			lun->pr_key_count++;
9000		lun->pr_keys[msg->pr.pr_info.residx] =
9001		    scsi_8btou64(msg->pr.pr_info.sa_res_key);
9002		lun->PRGeneration++;
9003		break;
9004
9005	case CTL_PR_UNREG_KEY:
9006		lun->pr_keys[msg->pr.pr_info.residx] = 0;
9007		lun->pr_key_count--;
9008
9009		/* XXX Need to see if the reservation has been released */
9010		/* if so do we need to generate UA? */
9011		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
9012			lun->flags &= ~CTL_LUN_PR_RESERVED;
9013			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
9014
9015			if ((lun->res_type == SPR_TYPE_WR_EX_RO
9016			  || lun->res_type == SPR_TYPE_EX_AC_RO)
9017			 && lun->pr_key_count) {
9018				/*
9019				 * If the reservation is a registrants
9020				 * only type we need to generate a UA
9021				 * for other registered inits.  The
9022				 * sense code should be RESERVATIONS
9023				 * RELEASED
9024				 */
9025
9026				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
9027					if (lun->pr_keys[i+
9028					    persis_offset] == 0)
9029						continue;
9030
9031					lun->pending_ua[i] |=
9032						CTL_UA_RES_RELEASE;
9033				}
9034			}
9035			lun->res_type = 0;
9036		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
9037			if (lun->pr_key_count==0) {
9038				lun->flags &= ~CTL_LUN_PR_RESERVED;
9039				lun->res_type = 0;
9040				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
9041			}
9042		}
9043		lun->PRGeneration++;
9044		break;
9045
9046	case CTL_PR_RESERVE:
9047		lun->flags |= CTL_LUN_PR_RESERVED;
9048		lun->res_type = msg->pr.pr_info.res_type;
9049		lun->pr_res_idx = msg->pr.pr_info.residx;
9050
9051		break;
9052
9053	case CTL_PR_RELEASE:
9054		/*
9055		 * if this isn't an exclusive access res generate UA for all
9056		 * other registrants.
9057		 */
9058		if (lun->res_type != SPR_TYPE_EX_AC
9059		 && lun->res_type != SPR_TYPE_WR_EX) {
9060			for (i = 0; i < CTL_MAX_INITIATORS; i++)
9061				if (lun->pr_keys[i+persis_offset] != 0)
9062					lun->pending_ua[i] |=
9063						CTL_UA_RES_RELEASE;
9064		}
9065
9066		lun->flags &= ~CTL_LUN_PR_RESERVED;
9067		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
9068		lun->res_type = 0;
9069		break;
9070
9071	case CTL_PR_PREEMPT:
9072		ctl_pro_preempt_other(lun, msg);
9073		break;
9074	case CTL_PR_CLEAR:
9075		lun->flags &= ~CTL_LUN_PR_RESERVED;
9076		lun->res_type = 0;
9077		lun->pr_key_count = 0;
9078		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
9079
9080		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
9081			if (lun->pr_keys[i] == 0)
9082				continue;
9083			if (!persis_offset
9084			 && i < CTL_MAX_INITIATORS)
9085				lun->pending_ua[i] |= CTL_UA_RES_PREEMPT;
9086			else if (persis_offset
9087			      && i >= persis_offset)
9088				lun->pending_ua[i-persis_offset] |=
9089					CTL_UA_RES_PREEMPT;
9090			lun->pr_keys[i] = 0;
9091		}
9092		lun->PRGeneration++;
9093		break;
9094	}
9095
9096	mtx_unlock(&lun->lun_lock);
9097}
9098
9099int
9100ctl_read_write(struct ctl_scsiio *ctsio)
9101{
9102	struct ctl_lun *lun;
9103	struct ctl_lba_len_flags *lbalen;
9104	uint64_t lba;
9105	uint32_t num_blocks;
9106	int flags, retval;
9107	int isread;
9108
9109	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9110
9111	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
9112
9113	flags = 0;
9114	retval = CTL_RETVAL_COMPLETE;
9115
9116	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
9117	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
9118	switch (ctsio->cdb[0]) {
9119	case READ_6:
9120	case WRITE_6: {
9121		struct scsi_rw_6 *cdb;
9122
9123		cdb = (struct scsi_rw_6 *)ctsio->cdb;
9124
9125		lba = scsi_3btoul(cdb->addr);
9126		/* only 5 bits are valid in the most significant address byte */
9127		lba &= 0x1fffff;
9128		num_blocks = cdb->length;
9129		/*
9130		 * This is correct according to SBC-2.
9131		 */
9132		if (num_blocks == 0)
9133			num_blocks = 256;
9134		break;
9135	}
9136	case READ_10:
9137	case WRITE_10: {
9138		struct scsi_rw_10 *cdb;
9139
9140		cdb = (struct scsi_rw_10 *)ctsio->cdb;
9141		if (cdb->byte2 & SRW10_FUA)
9142			flags |= CTL_LLF_FUA;
9143		if (cdb->byte2 & SRW10_DPO)
9144			flags |= CTL_LLF_DPO;
9145		lba = scsi_4btoul(cdb->addr);
9146		num_blocks = scsi_2btoul(cdb->length);
9147		break;
9148	}
9149	case WRITE_VERIFY_10: {
9150		struct scsi_write_verify_10 *cdb;
9151
9152		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
9153		flags |= CTL_LLF_FUA;
9154		if (cdb->byte2 & SWV_DPO)
9155			flags |= CTL_LLF_DPO;
9156		lba = scsi_4btoul(cdb->addr);
9157		num_blocks = scsi_2btoul(cdb->length);
9158		break;
9159	}
9160	case READ_12:
9161	case WRITE_12: {
9162		struct scsi_rw_12 *cdb;
9163
9164		cdb = (struct scsi_rw_12 *)ctsio->cdb;
9165		if (cdb->byte2 & SRW12_FUA)
9166			flags |= CTL_LLF_FUA;
9167		if (cdb->byte2 & SRW12_DPO)
9168			flags |= CTL_LLF_DPO;
9169		lba = scsi_4btoul(cdb->addr);
9170		num_blocks = scsi_4btoul(cdb->length);
9171		break;
9172	}
9173	case WRITE_VERIFY_12: {
9174		struct scsi_write_verify_12 *cdb;
9175
9176		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
9177		flags |= CTL_LLF_FUA;
9178		if (cdb->byte2 & SWV_DPO)
9179			flags |= CTL_LLF_DPO;
9180		lba = scsi_4btoul(cdb->addr);
9181		num_blocks = scsi_4btoul(cdb->length);
9182		break;
9183	}
9184	case READ_16:
9185	case WRITE_16: {
9186		struct scsi_rw_16 *cdb;
9187
9188		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9189		if (cdb->byte2 & SRW12_FUA)
9190			flags |= CTL_LLF_FUA;
9191		if (cdb->byte2 & SRW12_DPO)
9192			flags |= CTL_LLF_DPO;
9193		lba = scsi_8btou64(cdb->addr);
9194		num_blocks = scsi_4btoul(cdb->length);
9195		break;
9196	}
9197	case WRITE_ATOMIC_16: {
9198		struct scsi_rw_16 *cdb;
9199
9200		if (lun->be_lun->atomicblock == 0) {
9201			ctl_set_invalid_opcode(ctsio);
9202			ctl_done((union ctl_io *)ctsio);
9203			return (CTL_RETVAL_COMPLETE);
9204		}
9205
9206		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9207		if (cdb->byte2 & SRW12_FUA)
9208			flags |= CTL_LLF_FUA;
9209		if (cdb->byte2 & SRW12_DPO)
9210			flags |= CTL_LLF_DPO;
9211		lba = scsi_8btou64(cdb->addr);
9212		num_blocks = scsi_4btoul(cdb->length);
9213		if (num_blocks > lun->be_lun->atomicblock) {
9214			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
9215			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
9216			    /*bit*/ 0);
9217			ctl_done((union ctl_io *)ctsio);
9218			return (CTL_RETVAL_COMPLETE);
9219		}
9220		break;
9221	}
9222	case WRITE_VERIFY_16: {
9223		struct scsi_write_verify_16 *cdb;
9224
9225		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9226		flags |= CTL_LLF_FUA;
9227		if (cdb->byte2 & SWV_DPO)
9228			flags |= CTL_LLF_DPO;
9229		lba = scsi_8btou64(cdb->addr);
9230		num_blocks = scsi_4btoul(cdb->length);
9231		break;
9232	}
9233	default:
9234		/*
9235		 * We got a command we don't support.  This shouldn't
9236		 * happen, commands should be filtered out above us.
9237		 */
9238		ctl_set_invalid_opcode(ctsio);
9239		ctl_done((union ctl_io *)ctsio);
9240
9241		return (CTL_RETVAL_COMPLETE);
9242		break; /* NOTREACHED */
9243	}
9244
9245	/*
9246	 * The first check is to make sure we're in bounds, the second
9247	 * check is to catch wrap-around problems.  If the lba + num blocks
9248	 * is less than the lba, then we've wrapped around and the block
9249	 * range is invalid anyway.
9250	 */
9251	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9252	 || ((lba + num_blocks) < lba)) {
9253		ctl_set_lba_out_of_range(ctsio);
9254		ctl_done((union ctl_io *)ctsio);
9255		return (CTL_RETVAL_COMPLETE);
9256	}
9257
9258	/*
9259	 * According to SBC-3, a transfer length of 0 is not an error.
9260	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
9261	 * translates to 256 blocks for those commands.
9262	 */
9263	if (num_blocks == 0) {
9264		ctl_set_success(ctsio);
9265		ctl_done((union ctl_io *)ctsio);
9266		return (CTL_RETVAL_COMPLETE);
9267	}
9268
9269	/* Set FUA and/or DPO if caches are disabled. */
9270	if (isread) {
9271		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9272		    SCP_RCD) != 0)
9273			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9274	} else {
9275		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9276		    SCP_WCE) == 0)
9277			flags |= CTL_LLF_FUA;
9278	}
9279
9280	lbalen = (struct ctl_lba_len_flags *)
9281	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9282	lbalen->lba = lba;
9283	lbalen->len = num_blocks;
9284	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9285
9286	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9287	ctsio->kern_rel_offset = 0;
9288
9289	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9290
9291	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9292
9293	return (retval);
9294}
9295
9296static int
9297ctl_cnw_cont(union ctl_io *io)
9298{
9299	struct ctl_scsiio *ctsio;
9300	struct ctl_lun *lun;
9301	struct ctl_lba_len_flags *lbalen;
9302	int retval;
9303
9304	ctsio = &io->scsiio;
9305	ctsio->io_hdr.status = CTL_STATUS_NONE;
9306	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9307	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9308	lbalen = (struct ctl_lba_len_flags *)
9309	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9310	lbalen->flags &= ~CTL_LLF_COMPARE;
9311	lbalen->flags |= CTL_LLF_WRITE;
9312
9313	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9314	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9315	return (retval);
9316}
9317
9318int
9319ctl_cnw(struct ctl_scsiio *ctsio)
9320{
9321	struct ctl_lun *lun;
9322	struct ctl_lba_len_flags *lbalen;
9323	uint64_t lba;
9324	uint32_t num_blocks;
9325	int flags, retval;
9326
9327	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9328
9329	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9330
9331	flags = 0;
9332	retval = CTL_RETVAL_COMPLETE;
9333
9334	switch (ctsio->cdb[0]) {
9335	case COMPARE_AND_WRITE: {
9336		struct scsi_compare_and_write *cdb;
9337
9338		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9339		if (cdb->byte2 & SRW10_FUA)
9340			flags |= CTL_LLF_FUA;
9341		if (cdb->byte2 & SRW10_DPO)
9342			flags |= CTL_LLF_DPO;
9343		lba = scsi_8btou64(cdb->addr);
9344		num_blocks = cdb->length;
9345		break;
9346	}
9347	default:
9348		/*
9349		 * We got a command we don't support.  This shouldn't
9350		 * happen, commands should be filtered out above us.
9351		 */
9352		ctl_set_invalid_opcode(ctsio);
9353		ctl_done((union ctl_io *)ctsio);
9354
9355		return (CTL_RETVAL_COMPLETE);
9356		break; /* NOTREACHED */
9357	}
9358
9359	/*
9360	 * The first check is to make sure we're in bounds, the second
9361	 * check is to catch wrap-around problems.  If the lba + num blocks
9362	 * is less than the lba, then we've wrapped around and the block
9363	 * range is invalid anyway.
9364	 */
9365	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9366	 || ((lba + num_blocks) < lba)) {
9367		ctl_set_lba_out_of_range(ctsio);
9368		ctl_done((union ctl_io *)ctsio);
9369		return (CTL_RETVAL_COMPLETE);
9370	}
9371
9372	/*
9373	 * According to SBC-3, a transfer length of 0 is not an error.
9374	 */
9375	if (num_blocks == 0) {
9376		ctl_set_success(ctsio);
9377		ctl_done((union ctl_io *)ctsio);
9378		return (CTL_RETVAL_COMPLETE);
9379	}
9380
9381	/* Set FUA if write cache is disabled. */
9382	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9383	    SCP_WCE) == 0)
9384		flags |= CTL_LLF_FUA;
9385
9386	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9387	ctsio->kern_rel_offset = 0;
9388
9389	/*
9390	 * Set the IO_CONT flag, so that if this I/O gets passed to
9391	 * ctl_data_submit_done(), it'll get passed back to
9392	 * ctl_ctl_cnw_cont() for further processing.
9393	 */
9394	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9395	ctsio->io_cont = ctl_cnw_cont;
9396
9397	lbalen = (struct ctl_lba_len_flags *)
9398	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9399	lbalen->lba = lba;
9400	lbalen->len = num_blocks;
9401	lbalen->flags = CTL_LLF_COMPARE | flags;
9402
9403	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9404	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9405	return (retval);
9406}
9407
9408int
9409ctl_verify(struct ctl_scsiio *ctsio)
9410{
9411	struct ctl_lun *lun;
9412	struct ctl_lba_len_flags *lbalen;
9413	uint64_t lba;
9414	uint32_t num_blocks;
9415	int bytchk, flags;
9416	int retval;
9417
9418	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9419
9420	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9421
9422	bytchk = 0;
9423	flags = CTL_LLF_FUA;
9424	retval = CTL_RETVAL_COMPLETE;
9425
9426	switch (ctsio->cdb[0]) {
9427	case VERIFY_10: {
9428		struct scsi_verify_10 *cdb;
9429
9430		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9431		if (cdb->byte2 & SVFY_BYTCHK)
9432			bytchk = 1;
9433		if (cdb->byte2 & SVFY_DPO)
9434			flags |= CTL_LLF_DPO;
9435		lba = scsi_4btoul(cdb->addr);
9436		num_blocks = scsi_2btoul(cdb->length);
9437		break;
9438	}
9439	case VERIFY_12: {
9440		struct scsi_verify_12 *cdb;
9441
9442		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9443		if (cdb->byte2 & SVFY_BYTCHK)
9444			bytchk = 1;
9445		if (cdb->byte2 & SVFY_DPO)
9446			flags |= CTL_LLF_DPO;
9447		lba = scsi_4btoul(cdb->addr);
9448		num_blocks = scsi_4btoul(cdb->length);
9449		break;
9450	}
9451	case VERIFY_16: {
9452		struct scsi_rw_16 *cdb;
9453
9454		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9455		if (cdb->byte2 & SVFY_BYTCHK)
9456			bytchk = 1;
9457		if (cdb->byte2 & SVFY_DPO)
9458			flags |= CTL_LLF_DPO;
9459		lba = scsi_8btou64(cdb->addr);
9460		num_blocks = scsi_4btoul(cdb->length);
9461		break;
9462	}
9463	default:
9464		/*
9465		 * We got a command we don't support.  This shouldn't
9466		 * happen, commands should be filtered out above us.
9467		 */
9468		ctl_set_invalid_opcode(ctsio);
9469		ctl_done((union ctl_io *)ctsio);
9470		return (CTL_RETVAL_COMPLETE);
9471	}
9472
9473	/*
9474	 * The first check is to make sure we're in bounds, the second
9475	 * check is to catch wrap-around problems.  If the lba + num blocks
9476	 * is less than the lba, then we've wrapped around and the block
9477	 * range is invalid anyway.
9478	 */
9479	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9480	 || ((lba + num_blocks) < lba)) {
9481		ctl_set_lba_out_of_range(ctsio);
9482		ctl_done((union ctl_io *)ctsio);
9483		return (CTL_RETVAL_COMPLETE);
9484	}
9485
9486	/*
9487	 * According to SBC-3, a transfer length of 0 is not an error.
9488	 */
9489	if (num_blocks == 0) {
9490		ctl_set_success(ctsio);
9491		ctl_done((union ctl_io *)ctsio);
9492		return (CTL_RETVAL_COMPLETE);
9493	}
9494
9495	lbalen = (struct ctl_lba_len_flags *)
9496	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9497	lbalen->lba = lba;
9498	lbalen->len = num_blocks;
9499	if (bytchk) {
9500		lbalen->flags = CTL_LLF_COMPARE | flags;
9501		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9502	} else {
9503		lbalen->flags = CTL_LLF_VERIFY | flags;
9504		ctsio->kern_total_len = 0;
9505	}
9506	ctsio->kern_rel_offset = 0;
9507
9508	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9509	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9510	return (retval);
9511}
9512
9513int
9514ctl_report_luns(struct ctl_scsiio *ctsio)
9515{
9516	struct scsi_report_luns *cdb;
9517	struct scsi_report_luns_data *lun_data;
9518	struct ctl_lun *lun, *request_lun;
9519	int num_luns, retval;
9520	uint32_t alloc_len, lun_datalen;
9521	int num_filled, well_known;
9522	uint32_t initidx, targ_lun_id, lun_id;
9523
9524	retval = CTL_RETVAL_COMPLETE;
9525	well_known = 0;
9526
9527	cdb = (struct scsi_report_luns *)ctsio->cdb;
9528
9529	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9530
9531	mtx_lock(&control_softc->ctl_lock);
9532	num_luns = control_softc->num_luns;
9533	mtx_unlock(&control_softc->ctl_lock);
9534
9535	switch (cdb->select_report) {
9536	case RPL_REPORT_DEFAULT:
9537	case RPL_REPORT_ALL:
9538		break;
9539	case RPL_REPORT_WELLKNOWN:
9540		well_known = 1;
9541		num_luns = 0;
9542		break;
9543	default:
9544		ctl_set_invalid_field(ctsio,
9545				      /*sks_valid*/ 1,
9546				      /*command*/ 1,
9547				      /*field*/ 2,
9548				      /*bit_valid*/ 0,
9549				      /*bit*/ 0);
9550		ctl_done((union ctl_io *)ctsio);
9551		return (retval);
9552		break; /* NOTREACHED */
9553	}
9554
9555	alloc_len = scsi_4btoul(cdb->length);
9556	/*
9557	 * The initiator has to allocate at least 16 bytes for this request,
9558	 * so he can at least get the header and the first LUN.  Otherwise
9559	 * we reject the request (per SPC-3 rev 14, section 6.21).
9560	 */
9561	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9562	    sizeof(struct scsi_report_luns_lundata))) {
9563		ctl_set_invalid_field(ctsio,
9564				      /*sks_valid*/ 1,
9565				      /*command*/ 1,
9566				      /*field*/ 6,
9567				      /*bit_valid*/ 0,
9568				      /*bit*/ 0);
9569		ctl_done((union ctl_io *)ctsio);
9570		return (retval);
9571	}
9572
9573	request_lun = (struct ctl_lun *)
9574		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9575
9576	lun_datalen = sizeof(*lun_data) +
9577		(num_luns * sizeof(struct scsi_report_luns_lundata));
9578
9579	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9580	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9581	ctsio->kern_sg_entries = 0;
9582
9583	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9584
9585	mtx_lock(&control_softc->ctl_lock);
9586	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9587		lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9588		if (lun_id >= CTL_MAX_LUNS)
9589			continue;
9590		lun = control_softc->ctl_luns[lun_id];
9591		if (lun == NULL)
9592			continue;
9593
9594		if (targ_lun_id <= 0xff) {
9595			/*
9596			 * Peripheral addressing method, bus number 0.
9597			 */
9598			lun_data->luns[num_filled].lundata[0] =
9599				RPL_LUNDATA_ATYP_PERIPH;
9600			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9601			num_filled++;
9602		} else if (targ_lun_id <= 0x3fff) {
9603			/*
9604			 * Flat addressing method.
9605			 */
9606			lun_data->luns[num_filled].lundata[0] =
9607				RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9608			lun_data->luns[num_filled].lundata[1] =
9609				(targ_lun_id & 0xff);
9610			num_filled++;
9611		} else if (targ_lun_id <= 0xffffff) {
9612			/*
9613			 * Extended flat addressing method.
9614			 */
9615			lun_data->luns[num_filled].lundata[0] =
9616			    RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9617			scsi_ulto3b(targ_lun_id,
9618			    &lun_data->luns[num_filled].lundata[1]);
9619			num_filled++;
9620		} else {
9621			printf("ctl_report_luns: bogus LUN number %jd, "
9622			       "skipping\n", (intmax_t)targ_lun_id);
9623		}
9624		/*
9625		 * According to SPC-3, rev 14 section 6.21:
9626		 *
9627		 * "The execution of a REPORT LUNS command to any valid and
9628		 * installed logical unit shall clear the REPORTED LUNS DATA
9629		 * HAS CHANGED unit attention condition for all logical
9630		 * units of that target with respect to the requesting
9631		 * initiator. A valid and installed logical unit is one
9632		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9633		 * INQUIRY data (see 6.4.2)."
9634		 *
9635		 * If request_lun is NULL, the LUN this report luns command
9636		 * was issued to is either disabled or doesn't exist. In that
9637		 * case, we shouldn't clear any pending lun change unit
9638		 * attention.
9639		 */
9640		if (request_lun != NULL) {
9641			mtx_lock(&lun->lun_lock);
9642			lun->pending_ua[initidx] &= ~CTL_UA_LUN_CHANGE;
9643			mtx_unlock(&lun->lun_lock);
9644		}
9645	}
9646	mtx_unlock(&control_softc->ctl_lock);
9647
9648	/*
9649	 * It's quite possible that we've returned fewer LUNs than we allocated
9650	 * space for.  Trim it.
9651	 */
9652	lun_datalen = sizeof(*lun_data) +
9653		(num_filled * sizeof(struct scsi_report_luns_lundata));
9654
9655	if (lun_datalen < alloc_len) {
9656		ctsio->residual = alloc_len - lun_datalen;
9657		ctsio->kern_data_len = lun_datalen;
9658		ctsio->kern_total_len = lun_datalen;
9659	} else {
9660		ctsio->residual = 0;
9661		ctsio->kern_data_len = alloc_len;
9662		ctsio->kern_total_len = alloc_len;
9663	}
9664	ctsio->kern_data_resid = 0;
9665	ctsio->kern_rel_offset = 0;
9666	ctsio->kern_sg_entries = 0;
9667
9668	/*
9669	 * We set this to the actual data length, regardless of how much
9670	 * space we actually have to return results.  If the user looks at
9671	 * this value, he'll know whether or not he allocated enough space
9672	 * and reissue the command if necessary.  We don't support well
9673	 * known logical units, so if the user asks for that, return none.
9674	 */
9675	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9676
9677	/*
9678	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9679	 * this request.
9680	 */
9681	ctsio->scsi_status = SCSI_STATUS_OK;
9682
9683	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9684	ctsio->be_move_done = ctl_config_move_done;
9685	ctl_datamove((union ctl_io *)ctsio);
9686
9687	return (retval);
9688}
9689
9690int
9691ctl_request_sense(struct ctl_scsiio *ctsio)
9692{
9693	struct scsi_request_sense *cdb;
9694	struct scsi_sense_data *sense_ptr;
9695	struct ctl_lun *lun;
9696	uint32_t initidx;
9697	int have_error;
9698	scsi_sense_data_type sense_format;
9699
9700	cdb = (struct scsi_request_sense *)ctsio->cdb;
9701
9702	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9703
9704	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9705
9706	/*
9707	 * Determine which sense format the user wants.
9708	 */
9709	if (cdb->byte2 & SRS_DESC)
9710		sense_format = SSD_TYPE_DESC;
9711	else
9712		sense_format = SSD_TYPE_FIXED;
9713
9714	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9715	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9716	ctsio->kern_sg_entries = 0;
9717
9718	/*
9719	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9720	 * larger than the largest allowed value for the length field in the
9721	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9722	 */
9723	ctsio->residual = 0;
9724	ctsio->kern_data_len = cdb->length;
9725	ctsio->kern_total_len = cdb->length;
9726
9727	ctsio->kern_data_resid = 0;
9728	ctsio->kern_rel_offset = 0;
9729	ctsio->kern_sg_entries = 0;
9730
9731	/*
9732	 * If we don't have a LUN, we don't have any pending sense.
9733	 */
9734	if (lun == NULL)
9735		goto no_sense;
9736
9737	have_error = 0;
9738	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9739	/*
9740	 * Check for pending sense, and then for pending unit attentions.
9741	 * Pending sense gets returned first, then pending unit attentions.
9742	 */
9743	mtx_lock(&lun->lun_lock);
9744#ifdef CTL_WITH_CA
9745	if (ctl_is_set(lun->have_ca, initidx)) {
9746		scsi_sense_data_type stored_format;
9747
9748		/*
9749		 * Check to see which sense format was used for the stored
9750		 * sense data.
9751		 */
9752		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9753
9754		/*
9755		 * If the user requested a different sense format than the
9756		 * one we stored, then we need to convert it to the other
9757		 * format.  If we're going from descriptor to fixed format
9758		 * sense data, we may lose things in translation, depending
9759		 * on what options were used.
9760		 *
9761		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9762		 * for some reason we'll just copy it out as-is.
9763		 */
9764		if ((stored_format == SSD_TYPE_FIXED)
9765		 && (sense_format == SSD_TYPE_DESC))
9766			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9767			    &lun->pending_sense[initidx],
9768			    (struct scsi_sense_data_desc *)sense_ptr);
9769		else if ((stored_format == SSD_TYPE_DESC)
9770		      && (sense_format == SSD_TYPE_FIXED))
9771			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9772			    &lun->pending_sense[initidx],
9773			    (struct scsi_sense_data_fixed *)sense_ptr);
9774		else
9775			memcpy(sense_ptr, &lun->pending_sense[initidx],
9776			       ctl_min(sizeof(*sense_ptr),
9777			       sizeof(lun->pending_sense[initidx])));
9778
9779		ctl_clear_mask(lun->have_ca, initidx);
9780		have_error = 1;
9781	} else
9782#endif
9783	if (lun->pending_ua[initidx] != CTL_UA_NONE) {
9784		ctl_ua_type ua_type;
9785
9786		ua_type = ctl_build_ua(&lun->pending_ua[initidx],
9787				       sense_ptr, sense_format);
9788		if (ua_type != CTL_UA_NONE)
9789			have_error = 1;
9790	}
9791	mtx_unlock(&lun->lun_lock);
9792
9793	/*
9794	 * We already have a pending error, return it.
9795	 */
9796	if (have_error != 0) {
9797		/*
9798		 * We report the SCSI status as OK, since the status of the
9799		 * request sense command itself is OK.
9800		 */
9801		ctsio->scsi_status = SCSI_STATUS_OK;
9802
9803		/*
9804		 * We report 0 for the sense length, because we aren't doing
9805		 * autosense in this case.  We're reporting sense as
9806		 * parameter data.
9807		 */
9808		ctsio->sense_len = 0;
9809		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9810		ctsio->be_move_done = ctl_config_move_done;
9811		ctl_datamove((union ctl_io *)ctsio);
9812
9813		return (CTL_RETVAL_COMPLETE);
9814	}
9815
9816no_sense:
9817
9818	/*
9819	 * No sense information to report, so we report that everything is
9820	 * okay.
9821	 */
9822	ctl_set_sense_data(sense_ptr,
9823			   lun,
9824			   sense_format,
9825			   /*current_error*/ 1,
9826			   /*sense_key*/ SSD_KEY_NO_SENSE,
9827			   /*asc*/ 0x00,
9828			   /*ascq*/ 0x00,
9829			   SSD_ELEM_NONE);
9830
9831	ctsio->scsi_status = SCSI_STATUS_OK;
9832
9833	/*
9834	 * We report 0 for the sense length, because we aren't doing
9835	 * autosense in this case.  We're reporting sense as parameter data.
9836	 */
9837	ctsio->sense_len = 0;
9838	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9839	ctsio->be_move_done = ctl_config_move_done;
9840	ctl_datamove((union ctl_io *)ctsio);
9841
9842	return (CTL_RETVAL_COMPLETE);
9843}
9844
9845int
9846ctl_tur(struct ctl_scsiio *ctsio)
9847{
9848	struct ctl_lun *lun;
9849
9850	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9851
9852	CTL_DEBUG_PRINT(("ctl_tur\n"));
9853
9854	if (lun == NULL)
9855		return (EINVAL);
9856
9857	ctsio->scsi_status = SCSI_STATUS_OK;
9858	ctsio->io_hdr.status = CTL_SUCCESS;
9859
9860	ctl_done((union ctl_io *)ctsio);
9861
9862	return (CTL_RETVAL_COMPLETE);
9863}
9864
9865#ifdef notyet
9866static int
9867ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9868{
9869
9870}
9871#endif
9872
9873static int
9874ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9875{
9876	struct scsi_vpd_supported_pages *pages;
9877	int sup_page_size;
9878	struct ctl_lun *lun;
9879
9880	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9881
9882	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9883	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9884	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9885	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9886	ctsio->kern_sg_entries = 0;
9887
9888	if (sup_page_size < alloc_len) {
9889		ctsio->residual = alloc_len - sup_page_size;
9890		ctsio->kern_data_len = sup_page_size;
9891		ctsio->kern_total_len = sup_page_size;
9892	} else {
9893		ctsio->residual = 0;
9894		ctsio->kern_data_len = alloc_len;
9895		ctsio->kern_total_len = alloc_len;
9896	}
9897	ctsio->kern_data_resid = 0;
9898	ctsio->kern_rel_offset = 0;
9899	ctsio->kern_sg_entries = 0;
9900
9901	/*
9902	 * The control device is always connected.  The disk device, on the
9903	 * other hand, may not be online all the time.  Need to change this
9904	 * to figure out whether the disk device is actually online or not.
9905	 */
9906	if (lun != NULL)
9907		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9908				lun->be_lun->lun_type;
9909	else
9910		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9911
9912	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9913	/* Supported VPD pages */
9914	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9915	/* Serial Number */
9916	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9917	/* Device Identification */
9918	pages->page_list[2] = SVPD_DEVICE_ID;
9919	/* Extended INQUIRY Data */
9920	pages->page_list[3] = SVPD_EXTENDED_INQUIRY_DATA;
9921	/* Mode Page Policy */
9922	pages->page_list[4] = SVPD_MODE_PAGE_POLICY;
9923	/* SCSI Ports */
9924	pages->page_list[5] = SVPD_SCSI_PORTS;
9925	/* Third-party Copy */
9926	pages->page_list[6] = SVPD_SCSI_TPC;
9927	/* Block limits */
9928	pages->page_list[7] = SVPD_BLOCK_LIMITS;
9929	/* Block Device Characteristics */
9930	pages->page_list[8] = SVPD_BDC;
9931	/* Logical Block Provisioning */
9932	pages->page_list[9] = SVPD_LBP;
9933
9934	ctsio->scsi_status = SCSI_STATUS_OK;
9935
9936	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9937	ctsio->be_move_done = ctl_config_move_done;
9938	ctl_datamove((union ctl_io *)ctsio);
9939
9940	return (CTL_RETVAL_COMPLETE);
9941}
9942
9943static int
9944ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9945{
9946	struct scsi_vpd_unit_serial_number *sn_ptr;
9947	struct ctl_lun *lun;
9948	int data_len;
9949
9950	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9951
9952	data_len = 4 + CTL_SN_LEN;
9953	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9954	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9955	if (data_len < alloc_len) {
9956		ctsio->residual = alloc_len - data_len;
9957		ctsio->kern_data_len = data_len;
9958		ctsio->kern_total_len = data_len;
9959	} else {
9960		ctsio->residual = 0;
9961		ctsio->kern_data_len = alloc_len;
9962		ctsio->kern_total_len = alloc_len;
9963	}
9964	ctsio->kern_data_resid = 0;
9965	ctsio->kern_rel_offset = 0;
9966	ctsio->kern_sg_entries = 0;
9967
9968	/*
9969	 * The control device is always connected.  The disk device, on the
9970	 * other hand, may not be online all the time.  Need to change this
9971	 * to figure out whether the disk device is actually online or not.
9972	 */
9973	if (lun != NULL)
9974		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9975				  lun->be_lun->lun_type;
9976	else
9977		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9978
9979	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9980	sn_ptr->length = CTL_SN_LEN;
9981	/*
9982	 * If we don't have a LUN, we just leave the serial number as
9983	 * all spaces.
9984	 */
9985	if (lun != NULL) {
9986		strncpy((char *)sn_ptr->serial_num,
9987			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9988	} else
9989		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9990	ctsio->scsi_status = SCSI_STATUS_OK;
9991
9992	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9993	ctsio->be_move_done = ctl_config_move_done;
9994	ctl_datamove((union ctl_io *)ctsio);
9995
9996	return (CTL_RETVAL_COMPLETE);
9997}
9998
9999
10000static int
10001ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
10002{
10003	struct scsi_vpd_extended_inquiry_data *eid_ptr;
10004	struct ctl_lun *lun;
10005	int data_len;
10006
10007	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10008
10009	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
10010	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10011	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
10012	ctsio->kern_sg_entries = 0;
10013
10014	if (data_len < alloc_len) {
10015		ctsio->residual = alloc_len - data_len;
10016		ctsio->kern_data_len = data_len;
10017		ctsio->kern_total_len = data_len;
10018	} else {
10019		ctsio->residual = 0;
10020		ctsio->kern_data_len = alloc_len;
10021		ctsio->kern_total_len = alloc_len;
10022	}
10023	ctsio->kern_data_resid = 0;
10024	ctsio->kern_rel_offset = 0;
10025	ctsio->kern_sg_entries = 0;
10026
10027	/*
10028	 * The control device is always connected.  The disk device, on the
10029	 * other hand, may not be online all the time.
10030	 */
10031	if (lun != NULL)
10032		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10033				     lun->be_lun->lun_type;
10034	else
10035		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10036	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
10037	eid_ptr->page_length = data_len - 4;
10038	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
10039	eid_ptr->flags3 = SVPD_EID_V_SUP;
10040
10041	ctsio->scsi_status = SCSI_STATUS_OK;
10042	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10043	ctsio->be_move_done = ctl_config_move_done;
10044	ctl_datamove((union ctl_io *)ctsio);
10045
10046	return (CTL_RETVAL_COMPLETE);
10047}
10048
10049static int
10050ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
10051{
10052	struct scsi_vpd_mode_page_policy *mpp_ptr;
10053	struct ctl_lun *lun;
10054	int data_len;
10055
10056	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10057
10058	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
10059	    sizeof(struct scsi_vpd_mode_page_policy_descr);
10060
10061	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10062	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
10063	ctsio->kern_sg_entries = 0;
10064
10065	if (data_len < alloc_len) {
10066		ctsio->residual = alloc_len - data_len;
10067		ctsio->kern_data_len = data_len;
10068		ctsio->kern_total_len = data_len;
10069	} else {
10070		ctsio->residual = 0;
10071		ctsio->kern_data_len = alloc_len;
10072		ctsio->kern_total_len = alloc_len;
10073	}
10074	ctsio->kern_data_resid = 0;
10075	ctsio->kern_rel_offset = 0;
10076	ctsio->kern_sg_entries = 0;
10077
10078	/*
10079	 * The control device is always connected.  The disk device, on the
10080	 * other hand, may not be online all the time.
10081	 */
10082	if (lun != NULL)
10083		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10084				     lun->be_lun->lun_type;
10085	else
10086		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10087	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
10088	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
10089	mpp_ptr->descr[0].page_code = 0x3f;
10090	mpp_ptr->descr[0].subpage_code = 0xff;
10091	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
10092
10093	ctsio->scsi_status = SCSI_STATUS_OK;
10094	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10095	ctsio->be_move_done = ctl_config_move_done;
10096	ctl_datamove((union ctl_io *)ctsio);
10097
10098	return (CTL_RETVAL_COMPLETE);
10099}
10100
10101static int
10102ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
10103{
10104	struct scsi_vpd_device_id *devid_ptr;
10105	struct scsi_vpd_id_descriptor *desc;
10106	struct ctl_softc *ctl_softc;
10107	struct ctl_lun *lun;
10108	struct ctl_port *port;
10109	int data_len;
10110	uint8_t proto;
10111
10112	ctl_softc = control_softc;
10113
10114	port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
10115	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10116
10117	data_len = sizeof(struct scsi_vpd_device_id) +
10118	    sizeof(struct scsi_vpd_id_descriptor) +
10119		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
10120	    sizeof(struct scsi_vpd_id_descriptor) +
10121		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
10122	if (lun && lun->lun_devid)
10123		data_len += lun->lun_devid->len;
10124	if (port->port_devid)
10125		data_len += port->port_devid->len;
10126	if (port->target_devid)
10127		data_len += port->target_devid->len;
10128
10129	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10130	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
10131	ctsio->kern_sg_entries = 0;
10132
10133	if (data_len < alloc_len) {
10134		ctsio->residual = alloc_len - data_len;
10135		ctsio->kern_data_len = data_len;
10136		ctsio->kern_total_len = data_len;
10137	} else {
10138		ctsio->residual = 0;
10139		ctsio->kern_data_len = alloc_len;
10140		ctsio->kern_total_len = alloc_len;
10141	}
10142	ctsio->kern_data_resid = 0;
10143	ctsio->kern_rel_offset = 0;
10144	ctsio->kern_sg_entries = 0;
10145
10146	/*
10147	 * The control device is always connected.  The disk device, on the
10148	 * other hand, may not be online all the time.
10149	 */
10150	if (lun != NULL)
10151		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10152				     lun->be_lun->lun_type;
10153	else
10154		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10155	devid_ptr->page_code = SVPD_DEVICE_ID;
10156	scsi_ulto2b(data_len - 4, devid_ptr->length);
10157
10158	if (port->port_type == CTL_PORT_FC)
10159		proto = SCSI_PROTO_FC << 4;
10160	else if (port->port_type == CTL_PORT_ISCSI)
10161		proto = SCSI_PROTO_ISCSI << 4;
10162	else
10163		proto = SCSI_PROTO_SPI << 4;
10164	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
10165
10166	/*
10167	 * We're using a LUN association here.  i.e., this device ID is a
10168	 * per-LUN identifier.
10169	 */
10170	if (lun && lun->lun_devid) {
10171		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
10172		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10173		    lun->lun_devid->len);
10174	}
10175
10176	/*
10177	 * This is for the WWPN which is a port association.
10178	 */
10179	if (port->port_devid) {
10180		memcpy(desc, port->port_devid->data, port->port_devid->len);
10181		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10182		    port->port_devid->len);
10183	}
10184
10185	/*
10186	 * This is for the Relative Target Port(type 4h) identifier
10187	 */
10188	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10189	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10190	    SVPD_ID_TYPE_RELTARG;
10191	desc->length = 4;
10192	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
10193	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10194	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
10195
10196	/*
10197	 * This is for the Target Port Group(type 5h) identifier
10198	 */
10199	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10200	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10201	    SVPD_ID_TYPE_TPORTGRP;
10202	desc->length = 4;
10203	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
10204	    &desc->identifier[2]);
10205	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10206	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
10207
10208	/*
10209	 * This is for the Target identifier
10210	 */
10211	if (port->target_devid) {
10212		memcpy(desc, port->target_devid->data, port->target_devid->len);
10213	}
10214
10215	ctsio->scsi_status = SCSI_STATUS_OK;
10216	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10217	ctsio->be_move_done = ctl_config_move_done;
10218	ctl_datamove((union ctl_io *)ctsio);
10219
10220	return (CTL_RETVAL_COMPLETE);
10221}
10222
10223static int
10224ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
10225{
10226	struct ctl_softc *softc = control_softc;
10227	struct scsi_vpd_scsi_ports *sp;
10228	struct scsi_vpd_port_designation *pd;
10229	struct scsi_vpd_port_designation_cont *pdc;
10230	struct ctl_lun *lun;
10231	struct ctl_port *port;
10232	int data_len, num_target_ports, iid_len, id_len, g, pg, p;
10233	int num_target_port_groups;
10234
10235	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10236
10237	if (softc->is_single)
10238		num_target_port_groups = 1;
10239	else
10240		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10241	num_target_ports = 0;
10242	iid_len = 0;
10243	id_len = 0;
10244	mtx_lock(&softc->ctl_lock);
10245	STAILQ_FOREACH(port, &softc->port_list, links) {
10246		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10247			continue;
10248		if (lun != NULL &&
10249		    ctl_map_lun_back(port->targ_port, lun->lun) >=
10250		    CTL_MAX_LUNS)
10251			continue;
10252		num_target_ports++;
10253		if (port->init_devid)
10254			iid_len += port->init_devid->len;
10255		if (port->port_devid)
10256			id_len += port->port_devid->len;
10257	}
10258	mtx_unlock(&softc->ctl_lock);
10259
10260	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10261	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10262	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10263	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10264	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10265	ctsio->kern_sg_entries = 0;
10266
10267	if (data_len < alloc_len) {
10268		ctsio->residual = alloc_len - data_len;
10269		ctsio->kern_data_len = data_len;
10270		ctsio->kern_total_len = data_len;
10271	} else {
10272		ctsio->residual = 0;
10273		ctsio->kern_data_len = alloc_len;
10274		ctsio->kern_total_len = alloc_len;
10275	}
10276	ctsio->kern_data_resid = 0;
10277	ctsio->kern_rel_offset = 0;
10278	ctsio->kern_sg_entries = 0;
10279
10280	/*
10281	 * The control device is always connected.  The disk device, on the
10282	 * other hand, may not be online all the time.  Need to change this
10283	 * to figure out whether the disk device is actually online or not.
10284	 */
10285	if (lun != NULL)
10286		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10287				  lun->be_lun->lun_type;
10288	else
10289		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10290
10291	sp->page_code = SVPD_SCSI_PORTS;
10292	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10293	    sp->page_length);
10294	pd = &sp->design[0];
10295
10296	mtx_lock(&softc->ctl_lock);
10297	pg = softc->port_offset / CTL_MAX_PORTS;
10298	for (g = 0; g < num_target_port_groups; g++) {
10299		STAILQ_FOREACH(port, &softc->port_list, links) {
10300			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10301				continue;
10302			if (lun != NULL &&
10303			    ctl_map_lun_back(port->targ_port, lun->lun) >=
10304			    CTL_MAX_LUNS)
10305				continue;
10306			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10307			scsi_ulto2b(p, pd->relative_port_id);
10308			if (port->init_devid && g == pg) {
10309				iid_len = port->init_devid->len;
10310				memcpy(pd->initiator_transportid,
10311				    port->init_devid->data, port->init_devid->len);
10312			} else
10313				iid_len = 0;
10314			scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10315			pdc = (struct scsi_vpd_port_designation_cont *)
10316			    (&pd->initiator_transportid[iid_len]);
10317			if (port->port_devid && g == pg) {
10318				id_len = port->port_devid->len;
10319				memcpy(pdc->target_port_descriptors,
10320				    port->port_devid->data, port->port_devid->len);
10321			} else
10322				id_len = 0;
10323			scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10324			pd = (struct scsi_vpd_port_designation *)
10325			    ((uint8_t *)pdc->target_port_descriptors + id_len);
10326		}
10327	}
10328	mtx_unlock(&softc->ctl_lock);
10329
10330	ctsio->scsi_status = SCSI_STATUS_OK;
10331	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10332	ctsio->be_move_done = ctl_config_move_done;
10333	ctl_datamove((union ctl_io *)ctsio);
10334
10335	return (CTL_RETVAL_COMPLETE);
10336}
10337
10338static int
10339ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10340{
10341	struct scsi_vpd_block_limits *bl_ptr;
10342	struct ctl_lun *lun;
10343	int bs;
10344
10345	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10346
10347	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10348	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10349	ctsio->kern_sg_entries = 0;
10350
10351	if (sizeof(*bl_ptr) < alloc_len) {
10352		ctsio->residual = alloc_len - sizeof(*bl_ptr);
10353		ctsio->kern_data_len = sizeof(*bl_ptr);
10354		ctsio->kern_total_len = sizeof(*bl_ptr);
10355	} else {
10356		ctsio->residual = 0;
10357		ctsio->kern_data_len = alloc_len;
10358		ctsio->kern_total_len = alloc_len;
10359	}
10360	ctsio->kern_data_resid = 0;
10361	ctsio->kern_rel_offset = 0;
10362	ctsio->kern_sg_entries = 0;
10363
10364	/*
10365	 * The control device is always connected.  The disk device, on the
10366	 * other hand, may not be online all the time.  Need to change this
10367	 * to figure out whether the disk device is actually online or not.
10368	 */
10369	if (lun != NULL)
10370		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10371				  lun->be_lun->lun_type;
10372	else
10373		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10374
10375	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10376	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10377	bl_ptr->max_cmp_write_len = 0xff;
10378	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10379	if (lun != NULL) {
10380		bs = lun->be_lun->blocksize;
10381		scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10382		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10383			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10384			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10385			if (lun->be_lun->pblockexp != 0) {
10386				scsi_ulto4b((1 << lun->be_lun->pblockexp),
10387				    bl_ptr->opt_unmap_grain);
10388				scsi_ulto4b(0x80000000 | lun->be_lun->pblockoff,
10389				    bl_ptr->unmap_grain_align);
10390			}
10391		}
10392		scsi_ulto4b(lun->be_lun->atomicblock,
10393		    bl_ptr->max_atomic_transfer_length);
10394		scsi_ulto4b(0, bl_ptr->atomic_alignment);
10395		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10396	}
10397	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10398
10399	ctsio->scsi_status = SCSI_STATUS_OK;
10400	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10401	ctsio->be_move_done = ctl_config_move_done;
10402	ctl_datamove((union ctl_io *)ctsio);
10403
10404	return (CTL_RETVAL_COMPLETE);
10405}
10406
10407static int
10408ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10409{
10410	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10411	struct ctl_lun *lun;
10412	const char *value;
10413	u_int i;
10414
10415	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10416
10417	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10418	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10419	ctsio->kern_sg_entries = 0;
10420
10421	if (sizeof(*bdc_ptr) < alloc_len) {
10422		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10423		ctsio->kern_data_len = sizeof(*bdc_ptr);
10424		ctsio->kern_total_len = sizeof(*bdc_ptr);
10425	} else {
10426		ctsio->residual = 0;
10427		ctsio->kern_data_len = alloc_len;
10428		ctsio->kern_total_len = alloc_len;
10429	}
10430	ctsio->kern_data_resid = 0;
10431	ctsio->kern_rel_offset = 0;
10432	ctsio->kern_sg_entries = 0;
10433
10434	/*
10435	 * The control device is always connected.  The disk device, on the
10436	 * other hand, may not be online all the time.  Need to change this
10437	 * to figure out whether the disk device is actually online or not.
10438	 */
10439	if (lun != NULL)
10440		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10441				  lun->be_lun->lun_type;
10442	else
10443		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10444	bdc_ptr->page_code = SVPD_BDC;
10445	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10446	if (lun != NULL &&
10447	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10448		i = strtol(value, NULL, 0);
10449	else
10450		i = CTL_DEFAULT_ROTATION_RATE;
10451	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10452	if (lun != NULL &&
10453	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10454		i = strtol(value, NULL, 0);
10455	else
10456		i = 0;
10457	bdc_ptr->wab_wac_ff = (i & 0x0f);
10458	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10459
10460	ctsio->scsi_status = SCSI_STATUS_OK;
10461	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10462	ctsio->be_move_done = ctl_config_move_done;
10463	ctl_datamove((union ctl_io *)ctsio);
10464
10465	return (CTL_RETVAL_COMPLETE);
10466}
10467
10468static int
10469ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10470{
10471	struct scsi_vpd_logical_block_prov *lbp_ptr;
10472	struct ctl_lun *lun;
10473
10474	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10475
10476	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10477	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10478	ctsio->kern_sg_entries = 0;
10479
10480	if (sizeof(*lbp_ptr) < alloc_len) {
10481		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10482		ctsio->kern_data_len = sizeof(*lbp_ptr);
10483		ctsio->kern_total_len = sizeof(*lbp_ptr);
10484	} else {
10485		ctsio->residual = 0;
10486		ctsio->kern_data_len = alloc_len;
10487		ctsio->kern_total_len = alloc_len;
10488	}
10489	ctsio->kern_data_resid = 0;
10490	ctsio->kern_rel_offset = 0;
10491	ctsio->kern_sg_entries = 0;
10492
10493	/*
10494	 * The control device is always connected.  The disk device, on the
10495	 * other hand, may not be online all the time.  Need to change this
10496	 * to figure out whether the disk device is actually online or not.
10497	 */
10498	if (lun != NULL)
10499		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10500				  lun->be_lun->lun_type;
10501	else
10502		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10503
10504	lbp_ptr->page_code = SVPD_LBP;
10505	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10506	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10507		lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10508		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10509		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10510		lbp_ptr->prov_type = SVPD_LBP_THIN;
10511	}
10512
10513	ctsio->scsi_status = SCSI_STATUS_OK;
10514	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10515	ctsio->be_move_done = ctl_config_move_done;
10516	ctl_datamove((union ctl_io *)ctsio);
10517
10518	return (CTL_RETVAL_COMPLETE);
10519}
10520
10521static int
10522ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10523{
10524	struct scsi_inquiry *cdb;
10525	struct ctl_lun *lun;
10526	int alloc_len, retval;
10527
10528	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10529	cdb = (struct scsi_inquiry *)ctsio->cdb;
10530
10531	retval = CTL_RETVAL_COMPLETE;
10532
10533	alloc_len = scsi_2btoul(cdb->length);
10534
10535	switch (cdb->page_code) {
10536	case SVPD_SUPPORTED_PAGES:
10537		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10538		break;
10539	case SVPD_UNIT_SERIAL_NUMBER:
10540		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10541		break;
10542	case SVPD_DEVICE_ID:
10543		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10544		break;
10545	case SVPD_EXTENDED_INQUIRY_DATA:
10546		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10547		break;
10548	case SVPD_MODE_PAGE_POLICY:
10549		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10550		break;
10551	case SVPD_SCSI_PORTS:
10552		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10553		break;
10554	case SVPD_SCSI_TPC:
10555		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10556		break;
10557	case SVPD_BLOCK_LIMITS:
10558		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10559		break;
10560	case SVPD_BDC:
10561		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10562		break;
10563	case SVPD_LBP:
10564		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10565		break;
10566	default:
10567		ctl_set_invalid_field(ctsio,
10568				      /*sks_valid*/ 1,
10569				      /*command*/ 1,
10570				      /*field*/ 2,
10571				      /*bit_valid*/ 0,
10572				      /*bit*/ 0);
10573		ctl_done((union ctl_io *)ctsio);
10574		retval = CTL_RETVAL_COMPLETE;
10575		break;
10576	}
10577
10578	return (retval);
10579}
10580
10581static int
10582ctl_inquiry_std(struct ctl_scsiio *ctsio)
10583{
10584	struct scsi_inquiry_data *inq_ptr;
10585	struct scsi_inquiry *cdb;
10586	struct ctl_softc *ctl_softc;
10587	struct ctl_lun *lun;
10588	char *val;
10589	uint32_t alloc_len, data_len;
10590	ctl_port_type port_type;
10591
10592	ctl_softc = control_softc;
10593
10594	/*
10595	 * Figure out whether we're talking to a Fibre Channel port or not.
10596	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10597	 * SCSI front ends.
10598	 */
10599	port_type = ctl_softc->ctl_ports[
10600	    ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10601	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10602		port_type = CTL_PORT_SCSI;
10603
10604	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10605	cdb = (struct scsi_inquiry *)ctsio->cdb;
10606	alloc_len = scsi_2btoul(cdb->length);
10607
10608	/*
10609	 * We malloc the full inquiry data size here and fill it
10610	 * in.  If the user only asks for less, we'll give him
10611	 * that much.
10612	 */
10613	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10614	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10615	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10616	ctsio->kern_sg_entries = 0;
10617	ctsio->kern_data_resid = 0;
10618	ctsio->kern_rel_offset = 0;
10619
10620	if (data_len < alloc_len) {
10621		ctsio->residual = alloc_len - data_len;
10622		ctsio->kern_data_len = data_len;
10623		ctsio->kern_total_len = data_len;
10624	} else {
10625		ctsio->residual = 0;
10626		ctsio->kern_data_len = alloc_len;
10627		ctsio->kern_total_len = alloc_len;
10628	}
10629
10630	/*
10631	 * If we have a LUN configured, report it as connected.  Otherwise,
10632	 * report that it is offline or no device is supported, depending
10633	 * on the value of inquiry_pq_no_lun.
10634	 *
10635	 * According to the spec (SPC-4 r34), the peripheral qualifier
10636	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10637	 *
10638	 * "A peripheral device having the specified peripheral device type
10639	 * is not connected to this logical unit. However, the device
10640	 * server is capable of supporting the specified peripheral device
10641	 * type on this logical unit."
10642	 *
10643	 * According to the same spec, the peripheral qualifier
10644	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10645	 *
10646	 * "The device server is not capable of supporting a peripheral
10647	 * device on this logical unit. For this peripheral qualifier the
10648	 * peripheral device type shall be set to 1Fh. All other peripheral
10649	 * device type values are reserved for this peripheral qualifier."
10650	 *
10651	 * Given the text, it would seem that we probably want to report that
10652	 * the LUN is offline here.  There is no LUN connected, but we can
10653	 * support a LUN at the given LUN number.
10654	 *
10655	 * In the real world, though, it sounds like things are a little
10656	 * different:
10657	 *
10658	 * - Linux, when presented with a LUN with the offline peripheral
10659	 *   qualifier, will create an sg driver instance for it.  So when
10660	 *   you attach it to CTL, you wind up with a ton of sg driver
10661	 *   instances.  (One for every LUN that Linux bothered to probe.)
10662	 *   Linux does this despite the fact that it issues a REPORT LUNs
10663	 *   to LUN 0 to get the inventory of supported LUNs.
10664	 *
10665	 * - There is other anecdotal evidence (from Emulex folks) about
10666	 *   arrays that use the offline peripheral qualifier for LUNs that
10667	 *   are on the "passive" path in an active/passive array.
10668	 *
10669	 * So the solution is provide a hopefully reasonable default
10670	 * (return bad/no LUN) and allow the user to change the behavior
10671	 * with a tunable/sysctl variable.
10672	 */
10673	if (lun != NULL)
10674		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10675				  lun->be_lun->lun_type;
10676	else if (ctl_softc->inquiry_pq_no_lun == 0)
10677		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10678	else
10679		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10680
10681	/* RMB in byte 2 is 0 */
10682	inq_ptr->version = SCSI_REV_SPC4;
10683
10684	/*
10685	 * According to SAM-3, even if a device only supports a single
10686	 * level of LUN addressing, it should still set the HISUP bit:
10687	 *
10688	 * 4.9.1 Logical unit numbers overview
10689	 *
10690	 * All logical unit number formats described in this standard are
10691	 * hierarchical in structure even when only a single level in that
10692	 * hierarchy is used. The HISUP bit shall be set to one in the
10693	 * standard INQUIRY data (see SPC-2) when any logical unit number
10694	 * format described in this standard is used.  Non-hierarchical
10695	 * formats are outside the scope of this standard.
10696	 *
10697	 * Therefore we set the HiSup bit here.
10698	 *
10699	 * The reponse format is 2, per SPC-3.
10700	 */
10701	inq_ptr->response_format = SID_HiSup | 2;
10702
10703	inq_ptr->additional_length = data_len -
10704	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10705	CTL_DEBUG_PRINT(("additional_length = %d\n",
10706			 inq_ptr->additional_length));
10707
10708	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10709	/* 16 bit addressing */
10710	if (port_type == CTL_PORT_SCSI)
10711		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10712	/* XXX set the SID_MultiP bit here if we're actually going to
10713	   respond on multiple ports */
10714	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10715
10716	/* 16 bit data bus, synchronous transfers */
10717	if (port_type == CTL_PORT_SCSI)
10718		inq_ptr->flags = SID_WBus16 | SID_Sync;
10719	/*
10720	 * XXX KDM do we want to support tagged queueing on the control
10721	 * device at all?
10722	 */
10723	if ((lun == NULL)
10724	 || (lun->be_lun->lun_type != T_PROCESSOR))
10725		inq_ptr->flags |= SID_CmdQue;
10726	/*
10727	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10728	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10729	 * name and 4 bytes for the revision.
10730	 */
10731	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10732	    "vendor")) == NULL) {
10733		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10734	} else {
10735		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10736		strncpy(inq_ptr->vendor, val,
10737		    min(sizeof(inq_ptr->vendor), strlen(val)));
10738	}
10739	if (lun == NULL) {
10740		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10741		    sizeof(inq_ptr->product));
10742	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10743		switch (lun->be_lun->lun_type) {
10744		case T_DIRECT:
10745			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10746			    sizeof(inq_ptr->product));
10747			break;
10748		case T_PROCESSOR:
10749			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10750			    sizeof(inq_ptr->product));
10751			break;
10752		default:
10753			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10754			    sizeof(inq_ptr->product));
10755			break;
10756		}
10757	} else {
10758		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10759		strncpy(inq_ptr->product, val,
10760		    min(sizeof(inq_ptr->product), strlen(val)));
10761	}
10762
10763	/*
10764	 * XXX make this a macro somewhere so it automatically gets
10765	 * incremented when we make changes.
10766	 */
10767	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10768	    "revision")) == NULL) {
10769		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10770	} else {
10771		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10772		strncpy(inq_ptr->revision, val,
10773		    min(sizeof(inq_ptr->revision), strlen(val)));
10774	}
10775
10776	/*
10777	 * For parallel SCSI, we support double transition and single
10778	 * transition clocking.  We also support QAS (Quick Arbitration
10779	 * and Selection) and Information Unit transfers on both the
10780	 * control and array devices.
10781	 */
10782	if (port_type == CTL_PORT_SCSI)
10783		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10784				    SID_SPI_IUS;
10785
10786	/* SAM-5 (no version claimed) */
10787	scsi_ulto2b(0x00A0, inq_ptr->version1);
10788	/* SPC-4 (no version claimed) */
10789	scsi_ulto2b(0x0460, inq_ptr->version2);
10790	if (port_type == CTL_PORT_FC) {
10791		/* FCP-2 ANSI INCITS.350:2003 */
10792		scsi_ulto2b(0x0917, inq_ptr->version3);
10793	} else if (port_type == CTL_PORT_SCSI) {
10794		/* SPI-4 ANSI INCITS.362:200x */
10795		scsi_ulto2b(0x0B56, inq_ptr->version3);
10796	} else if (port_type == CTL_PORT_ISCSI) {
10797		/* iSCSI (no version claimed) */
10798		scsi_ulto2b(0x0960, inq_ptr->version3);
10799	} else if (port_type == CTL_PORT_SAS) {
10800		/* SAS (no version claimed) */
10801		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10802	}
10803
10804	if (lun == NULL) {
10805		/* SBC-4 (no version claimed) */
10806		scsi_ulto2b(0x0600, inq_ptr->version4);
10807	} else {
10808		switch (lun->be_lun->lun_type) {
10809		case T_DIRECT:
10810			/* SBC-4 (no version claimed) */
10811			scsi_ulto2b(0x0600, inq_ptr->version4);
10812			break;
10813		case T_PROCESSOR:
10814		default:
10815			break;
10816		}
10817	}
10818
10819	ctsio->scsi_status = SCSI_STATUS_OK;
10820	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10821	ctsio->be_move_done = ctl_config_move_done;
10822	ctl_datamove((union ctl_io *)ctsio);
10823	return (CTL_RETVAL_COMPLETE);
10824}
10825
10826int
10827ctl_inquiry(struct ctl_scsiio *ctsio)
10828{
10829	struct scsi_inquiry *cdb;
10830	int retval;
10831
10832	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10833
10834	cdb = (struct scsi_inquiry *)ctsio->cdb;
10835	if (cdb->byte2 & SI_EVPD)
10836		retval = ctl_inquiry_evpd(ctsio);
10837	else if (cdb->page_code == 0)
10838		retval = ctl_inquiry_std(ctsio);
10839	else {
10840		ctl_set_invalid_field(ctsio,
10841				      /*sks_valid*/ 1,
10842				      /*command*/ 1,
10843				      /*field*/ 2,
10844				      /*bit_valid*/ 0,
10845				      /*bit*/ 0);
10846		ctl_done((union ctl_io *)ctsio);
10847		return (CTL_RETVAL_COMPLETE);
10848	}
10849
10850	return (retval);
10851}
10852
10853/*
10854 * For known CDB types, parse the LBA and length.
10855 */
10856static int
10857ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10858{
10859	if (io->io_hdr.io_type != CTL_IO_SCSI)
10860		return (1);
10861
10862	switch (io->scsiio.cdb[0]) {
10863	case COMPARE_AND_WRITE: {
10864		struct scsi_compare_and_write *cdb;
10865
10866		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10867
10868		*lba = scsi_8btou64(cdb->addr);
10869		*len = cdb->length;
10870		break;
10871	}
10872	case READ_6:
10873	case WRITE_6: {
10874		struct scsi_rw_6 *cdb;
10875
10876		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10877
10878		*lba = scsi_3btoul(cdb->addr);
10879		/* only 5 bits are valid in the most significant address byte */
10880		*lba &= 0x1fffff;
10881		*len = cdb->length;
10882		break;
10883	}
10884	case READ_10:
10885	case WRITE_10: {
10886		struct scsi_rw_10 *cdb;
10887
10888		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10889
10890		*lba = scsi_4btoul(cdb->addr);
10891		*len = scsi_2btoul(cdb->length);
10892		break;
10893	}
10894	case WRITE_VERIFY_10: {
10895		struct scsi_write_verify_10 *cdb;
10896
10897		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10898
10899		*lba = scsi_4btoul(cdb->addr);
10900		*len = scsi_2btoul(cdb->length);
10901		break;
10902	}
10903	case READ_12:
10904	case WRITE_12: {
10905		struct scsi_rw_12 *cdb;
10906
10907		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10908
10909		*lba = scsi_4btoul(cdb->addr);
10910		*len = scsi_4btoul(cdb->length);
10911		break;
10912	}
10913	case WRITE_VERIFY_12: {
10914		struct scsi_write_verify_12 *cdb;
10915
10916		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10917
10918		*lba = scsi_4btoul(cdb->addr);
10919		*len = scsi_4btoul(cdb->length);
10920		break;
10921	}
10922	case READ_16:
10923	case WRITE_16:
10924	case WRITE_ATOMIC_16: {
10925		struct scsi_rw_16 *cdb;
10926
10927		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10928
10929		*lba = scsi_8btou64(cdb->addr);
10930		*len = scsi_4btoul(cdb->length);
10931		break;
10932	}
10933	case WRITE_VERIFY_16: {
10934		struct scsi_write_verify_16 *cdb;
10935
10936		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10937
10938		*lba = scsi_8btou64(cdb->addr);
10939		*len = scsi_4btoul(cdb->length);
10940		break;
10941	}
10942	case WRITE_SAME_10: {
10943		struct scsi_write_same_10 *cdb;
10944
10945		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10946
10947		*lba = scsi_4btoul(cdb->addr);
10948		*len = scsi_2btoul(cdb->length);
10949		break;
10950	}
10951	case WRITE_SAME_16: {
10952		struct scsi_write_same_16 *cdb;
10953
10954		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10955
10956		*lba = scsi_8btou64(cdb->addr);
10957		*len = scsi_4btoul(cdb->length);
10958		break;
10959	}
10960	case VERIFY_10: {
10961		struct scsi_verify_10 *cdb;
10962
10963		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10964
10965		*lba = scsi_4btoul(cdb->addr);
10966		*len = scsi_2btoul(cdb->length);
10967		break;
10968	}
10969	case VERIFY_12: {
10970		struct scsi_verify_12 *cdb;
10971
10972		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10973
10974		*lba = scsi_4btoul(cdb->addr);
10975		*len = scsi_4btoul(cdb->length);
10976		break;
10977	}
10978	case VERIFY_16: {
10979		struct scsi_verify_16 *cdb;
10980
10981		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10982
10983		*lba = scsi_8btou64(cdb->addr);
10984		*len = scsi_4btoul(cdb->length);
10985		break;
10986	}
10987	case UNMAP: {
10988		*lba = 0;
10989		*len = UINT64_MAX;
10990		break;
10991	}
10992	default:
10993		return (1);
10994		break; /* NOTREACHED */
10995	}
10996
10997	return (0);
10998}
10999
11000static ctl_action
11001ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2)
11002{
11003	uint64_t endlba1, endlba2;
11004
11005	endlba1 = lba1 + len1 - 1;
11006	endlba2 = lba2 + len2 - 1;
11007
11008	if ((endlba1 < lba2)
11009	 || (endlba2 < lba1))
11010		return (CTL_ACTION_PASS);
11011	else
11012		return (CTL_ACTION_BLOCK);
11013}
11014
11015static int
11016ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
11017{
11018	struct ctl_ptr_len_flags *ptrlen;
11019	struct scsi_unmap_desc *buf, *end, *range;
11020	uint64_t lba;
11021	uint32_t len;
11022
11023	/* If not UNMAP -- go other way. */
11024	if (io->io_hdr.io_type != CTL_IO_SCSI ||
11025	    io->scsiio.cdb[0] != UNMAP)
11026		return (CTL_ACTION_ERROR);
11027
11028	/* If UNMAP without data -- block and wait for data. */
11029	ptrlen = (struct ctl_ptr_len_flags *)
11030	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
11031	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
11032	    ptrlen->ptr == NULL)
11033		return (CTL_ACTION_BLOCK);
11034
11035	/* UNMAP with data -- check for collision. */
11036	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
11037	end = buf + ptrlen->len / sizeof(*buf);
11038	for (range = buf; range < end; range++) {
11039		lba = scsi_8btou64(range->lba);
11040		len = scsi_4btoul(range->length);
11041		if ((lba < lba2 + len2) && (lba + len > lba2))
11042			return (CTL_ACTION_BLOCK);
11043	}
11044	return (CTL_ACTION_PASS);
11045}
11046
11047static ctl_action
11048ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
11049{
11050	uint64_t lba1, lba2;
11051	uint64_t len1, len2;
11052	int retval;
11053
11054	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
11055		return (CTL_ACTION_ERROR);
11056
11057	retval = ctl_extent_check_unmap(io2, lba1, len1);
11058	if (retval != CTL_ACTION_ERROR)
11059		return (retval);
11060
11061	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
11062		return (CTL_ACTION_ERROR);
11063
11064	return (ctl_extent_check_lba(lba1, len1, lba2, len2));
11065}
11066
11067static ctl_action
11068ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
11069    union ctl_io *ooa_io)
11070{
11071	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
11072	ctl_serialize_action *serialize_row;
11073
11074	/*
11075	 * The initiator attempted multiple untagged commands at the same
11076	 * time.  Can't do that.
11077	 */
11078	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11079	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11080	 && ((pending_io->io_hdr.nexus.targ_port ==
11081	      ooa_io->io_hdr.nexus.targ_port)
11082	  && (pending_io->io_hdr.nexus.initid.id ==
11083	      ooa_io->io_hdr.nexus.initid.id))
11084	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
11085		return (CTL_ACTION_OVERLAP);
11086
11087	/*
11088	 * The initiator attempted to send multiple tagged commands with
11089	 * the same ID.  (It's fine if different initiators have the same
11090	 * tag ID.)
11091	 *
11092	 * Even if all of those conditions are true, we don't kill the I/O
11093	 * if the command ahead of us has been aborted.  We won't end up
11094	 * sending it to the FETD, and it's perfectly legal to resend a
11095	 * command with the same tag number as long as the previous
11096	 * instance of this tag number has been aborted somehow.
11097	 */
11098	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11099	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11100	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11101	 && ((pending_io->io_hdr.nexus.targ_port ==
11102	      ooa_io->io_hdr.nexus.targ_port)
11103	  && (pending_io->io_hdr.nexus.initid.id ==
11104	      ooa_io->io_hdr.nexus.initid.id))
11105	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
11106		return (CTL_ACTION_OVERLAP_TAG);
11107
11108	/*
11109	 * If we get a head of queue tag, SAM-3 says that we should
11110	 * immediately execute it.
11111	 *
11112	 * What happens if this command would normally block for some other
11113	 * reason?  e.g. a request sense with a head of queue tag
11114	 * immediately after a write.  Normally that would block, but this
11115	 * will result in its getting executed immediately...
11116	 *
11117	 * We currently return "pass" instead of "skip", so we'll end up
11118	 * going through the rest of the queue to check for overlapped tags.
11119	 *
11120	 * XXX KDM check for other types of blockage first??
11121	 */
11122	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11123		return (CTL_ACTION_PASS);
11124
11125	/*
11126	 * Ordered tags have to block until all items ahead of them
11127	 * have completed.  If we get called with an ordered tag, we always
11128	 * block, if something else is ahead of us in the queue.
11129	 */
11130	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11131		return (CTL_ACTION_BLOCK);
11132
11133	/*
11134	 * Simple tags get blocked until all head of queue and ordered tags
11135	 * ahead of them have completed.  I'm lumping untagged commands in
11136	 * with simple tags here.  XXX KDM is that the right thing to do?
11137	 */
11138	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11139	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11140	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11141	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11142		return (CTL_ACTION_BLOCK);
11143
11144	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11145	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11146
11147	serialize_row = ctl_serialize_table[ooa_entry->seridx];
11148
11149	switch (serialize_row[pending_entry->seridx]) {
11150	case CTL_SER_BLOCK:
11151		return (CTL_ACTION_BLOCK);
11152	case CTL_SER_EXTENT:
11153		return (ctl_extent_check(pending_io, ooa_io));
11154	case CTL_SER_EXTENTOPT:
11155		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11156		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11157			return (ctl_extent_check(pending_io, ooa_io));
11158		/* FALLTHROUGH */
11159	case CTL_SER_PASS:
11160		return (CTL_ACTION_PASS);
11161	case CTL_SER_BLOCKOPT:
11162		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11163		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11164			return (CTL_ACTION_BLOCK);
11165		return (CTL_ACTION_PASS);
11166	case CTL_SER_SKIP:
11167		return (CTL_ACTION_SKIP);
11168	default:
11169		panic("invalid serialization value %d",
11170		      serialize_row[pending_entry->seridx]);
11171	}
11172
11173	return (CTL_ACTION_ERROR);
11174}
11175
11176/*
11177 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11178 * Assumptions:
11179 * - pending_io is generally either incoming, or on the blocked queue
11180 * - starting I/O is the I/O we want to start the check with.
11181 */
11182static ctl_action
11183ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11184	      union ctl_io *starting_io)
11185{
11186	union ctl_io *ooa_io;
11187	ctl_action action;
11188
11189	mtx_assert(&lun->lun_lock, MA_OWNED);
11190
11191	/*
11192	 * Run back along the OOA queue, starting with the current
11193	 * blocked I/O and going through every I/O before it on the
11194	 * queue.  If starting_io is NULL, we'll just end up returning
11195	 * CTL_ACTION_PASS.
11196	 */
11197	for (ooa_io = starting_io; ooa_io != NULL;
11198	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11199	     ooa_links)){
11200
11201		/*
11202		 * This routine just checks to see whether
11203		 * cur_blocked is blocked by ooa_io, which is ahead
11204		 * of it in the queue.  It doesn't queue/dequeue
11205		 * cur_blocked.
11206		 */
11207		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11208		switch (action) {
11209		case CTL_ACTION_BLOCK:
11210		case CTL_ACTION_OVERLAP:
11211		case CTL_ACTION_OVERLAP_TAG:
11212		case CTL_ACTION_SKIP:
11213		case CTL_ACTION_ERROR:
11214			return (action);
11215			break; /* NOTREACHED */
11216		case CTL_ACTION_PASS:
11217			break;
11218		default:
11219			panic("invalid action %d", action);
11220			break;  /* NOTREACHED */
11221		}
11222	}
11223
11224	return (CTL_ACTION_PASS);
11225}
11226
11227/*
11228 * Assumptions:
11229 * - An I/O has just completed, and has been removed from the per-LUN OOA
11230 *   queue, so some items on the blocked queue may now be unblocked.
11231 */
11232static int
11233ctl_check_blocked(struct ctl_lun *lun)
11234{
11235	union ctl_io *cur_blocked, *next_blocked;
11236
11237	mtx_assert(&lun->lun_lock, MA_OWNED);
11238
11239	/*
11240	 * Run forward from the head of the blocked queue, checking each
11241	 * entry against the I/Os prior to it on the OOA queue to see if
11242	 * there is still any blockage.
11243	 *
11244	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11245	 * with our removing a variable on it while it is traversing the
11246	 * list.
11247	 */
11248	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11249	     cur_blocked != NULL; cur_blocked = next_blocked) {
11250		union ctl_io *prev_ooa;
11251		ctl_action action;
11252
11253		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11254							  blocked_links);
11255
11256		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11257						      ctl_ooaq, ooa_links);
11258
11259		/*
11260		 * If cur_blocked happens to be the first item in the OOA
11261		 * queue now, prev_ooa will be NULL, and the action
11262		 * returned will just be CTL_ACTION_PASS.
11263		 */
11264		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11265
11266		switch (action) {
11267		case CTL_ACTION_BLOCK:
11268			/* Nothing to do here, still blocked */
11269			break;
11270		case CTL_ACTION_OVERLAP:
11271		case CTL_ACTION_OVERLAP_TAG:
11272			/*
11273			 * This shouldn't happen!  In theory we've already
11274			 * checked this command for overlap...
11275			 */
11276			break;
11277		case CTL_ACTION_PASS:
11278		case CTL_ACTION_SKIP: {
11279			struct ctl_softc *softc;
11280			const struct ctl_cmd_entry *entry;
11281			uint32_t initidx;
11282			int isc_retval;
11283
11284			/*
11285			 * The skip case shouldn't happen, this transaction
11286			 * should have never made it onto the blocked queue.
11287			 */
11288			/*
11289			 * This I/O is no longer blocked, we can remove it
11290			 * from the blocked queue.  Since this is a TAILQ
11291			 * (doubly linked list), we can do O(1) removals
11292			 * from any place on the list.
11293			 */
11294			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11295				     blocked_links);
11296			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11297
11298			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11299				/*
11300				 * Need to send IO back to original side to
11301				 * run
11302				 */
11303				union ctl_ha_msg msg_info;
11304
11305				msg_info.hdr.original_sc =
11306					cur_blocked->io_hdr.original_sc;
11307				msg_info.hdr.serializing_sc = cur_blocked;
11308				msg_info.hdr.msg_type = CTL_MSG_R2R;
11309				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11310				     &msg_info, sizeof(msg_info), 0)) >
11311				     CTL_HA_STATUS_SUCCESS) {
11312					printf("CTL:Check Blocked error from "
11313					       "ctl_ha_msg_send %d\n",
11314					       isc_retval);
11315				}
11316				break;
11317			}
11318			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11319			softc = control_softc;
11320
11321			initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
11322
11323			/*
11324			 * Check this I/O for LUN state changes that may
11325			 * have happened while this command was blocked.
11326			 * The LUN state may have been changed by a command
11327			 * ahead of us in the queue, so we need to re-check
11328			 * for any states that can be caused by SCSI
11329			 * commands.
11330			 */
11331			if (ctl_scsiio_lun_check(softc, lun, entry,
11332						 &cur_blocked->scsiio) == 0) {
11333				cur_blocked->io_hdr.flags |=
11334				                      CTL_FLAG_IS_WAS_ON_RTR;
11335				ctl_enqueue_rtr(cur_blocked);
11336			} else
11337				ctl_done(cur_blocked);
11338			break;
11339		}
11340		default:
11341			/*
11342			 * This probably shouldn't happen -- we shouldn't
11343			 * get CTL_ACTION_ERROR, or anything else.
11344			 */
11345			break;
11346		}
11347	}
11348
11349	return (CTL_RETVAL_COMPLETE);
11350}
11351
11352/*
11353 * This routine (with one exception) checks LUN flags that can be set by
11354 * commands ahead of us in the OOA queue.  These flags have to be checked
11355 * when a command initially comes in, and when we pull a command off the
11356 * blocked queue and are preparing to execute it.  The reason we have to
11357 * check these flags for commands on the blocked queue is that the LUN
11358 * state may have been changed by a command ahead of us while we're on the
11359 * blocked queue.
11360 *
11361 * Ordering is somewhat important with these checks, so please pay
11362 * careful attention to the placement of any new checks.
11363 */
11364static int
11365ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11366    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11367{
11368	int retval;
11369	uint32_t residx;
11370
11371	retval = 0;
11372
11373	mtx_assert(&lun->lun_lock, MA_OWNED);
11374
11375	/*
11376	 * If this shelf is a secondary shelf controller, we have to reject
11377	 * any media access commands.
11378	 */
11379	if ((ctl_softc->flags & CTL_FLAG_ACTIVE_SHELF) == 0 &&
11380	    (entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0) {
11381		ctl_set_lun_standby(ctsio);
11382		retval = 1;
11383		goto bailout;
11384	}
11385
11386	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11387		if (lun->flags & CTL_LUN_READONLY) {
11388			ctl_set_sense(ctsio, /*current_error*/ 1,
11389			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11390			    /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11391			retval = 1;
11392			goto bailout;
11393		}
11394		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11395		    .eca_and_aen & SCP_SWP) != 0) {
11396			ctl_set_sense(ctsio, /*current_error*/ 1,
11397			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11398			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11399			retval = 1;
11400			goto bailout;
11401		}
11402	}
11403
11404	/*
11405	 * Check for a reservation conflict.  If this command isn't allowed
11406	 * even on reserved LUNs, and if this initiator isn't the one who
11407	 * reserved us, reject the command with a reservation conflict.
11408	 */
11409	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11410	if ((lun->flags & CTL_LUN_RESERVED)
11411	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11412		if (lun->res_idx != residx) {
11413			ctl_set_reservation_conflict(ctsio);
11414			retval = 1;
11415			goto bailout;
11416		}
11417	}
11418
11419	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11420	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11421		/* No reservation or command is allowed. */;
11422	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11423	    (lun->res_type == SPR_TYPE_WR_EX ||
11424	     lun->res_type == SPR_TYPE_WR_EX_RO ||
11425	     lun->res_type == SPR_TYPE_WR_EX_AR)) {
11426		/* The command is allowed for Write Exclusive resv. */;
11427	} else {
11428		/*
11429		 * if we aren't registered or it's a res holder type
11430		 * reservation and this isn't the res holder then set a
11431		 * conflict.
11432		 */
11433		if (lun->pr_keys[residx] == 0
11434		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11435			ctl_set_reservation_conflict(ctsio);
11436			retval = 1;
11437			goto bailout;
11438		}
11439
11440	}
11441
11442	if ((lun->flags & CTL_LUN_OFFLINE)
11443	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11444		ctl_set_lun_not_ready(ctsio);
11445		retval = 1;
11446		goto bailout;
11447	}
11448
11449	/*
11450	 * If the LUN is stopped, see if this particular command is allowed
11451	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11452	 */
11453	if ((lun->flags & CTL_LUN_STOPPED)
11454	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11455		/* "Logical unit not ready, initializing cmd. required" */
11456		ctl_set_lun_stopped(ctsio);
11457		retval = 1;
11458		goto bailout;
11459	}
11460
11461	if ((lun->flags & CTL_LUN_INOPERABLE)
11462	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11463		/* "Medium format corrupted" */
11464		ctl_set_medium_format_corrupted(ctsio);
11465		retval = 1;
11466		goto bailout;
11467	}
11468
11469bailout:
11470	return (retval);
11471
11472}
11473
11474static void
11475ctl_failover_io(union ctl_io *io, int have_lock)
11476{
11477	ctl_set_busy(&io->scsiio);
11478	ctl_done(io);
11479}
11480
11481static void
11482ctl_failover(void)
11483{
11484	struct ctl_lun *lun;
11485	struct ctl_softc *ctl_softc;
11486	union ctl_io *next_io, *pending_io;
11487	union ctl_io *io;
11488	int lun_idx;
11489	int i;
11490
11491	ctl_softc = control_softc;
11492
11493	mtx_lock(&ctl_softc->ctl_lock);
11494	/*
11495	 * Remove any cmds from the other SC from the rtr queue.  These
11496	 * will obviously only be for LUNs for which we're the primary.
11497	 * We can't send status or get/send data for these commands.
11498	 * Since they haven't been executed yet, we can just remove them.
11499	 * We'll either abort them or delete them below, depending on
11500	 * which HA mode we're in.
11501	 */
11502#ifdef notyet
11503	mtx_lock(&ctl_softc->queue_lock);
11504	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11505	     io != NULL; io = next_io) {
11506		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11507		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11508			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11509				      ctl_io_hdr, links);
11510	}
11511	mtx_unlock(&ctl_softc->queue_lock);
11512#endif
11513
11514	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11515		lun = ctl_softc->ctl_luns[lun_idx];
11516		if (lun==NULL)
11517			continue;
11518
11519		/*
11520		 * Processor LUNs are primary on both sides.
11521		 * XXX will this always be true?
11522		 */
11523		if (lun->be_lun->lun_type == T_PROCESSOR)
11524			continue;
11525
11526		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11527		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11528			printf("FAILOVER: primary lun %d\n", lun_idx);
11529		        /*
11530			 * Remove all commands from the other SC. First from the
11531			 * blocked queue then from the ooa queue. Once we have
11532			 * removed them. Call ctl_check_blocked to see if there
11533			 * is anything that can run.
11534			 */
11535			for (io = (union ctl_io *)TAILQ_FIRST(
11536			     &lun->blocked_queue); io != NULL; io = next_io) {
11537
11538		        	next_io = (union ctl_io *)TAILQ_NEXT(
11539				    &io->io_hdr, blocked_links);
11540
11541				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11542					TAILQ_REMOVE(&lun->blocked_queue,
11543						     &io->io_hdr,blocked_links);
11544					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11545					TAILQ_REMOVE(&lun->ooa_queue,
11546						     &io->io_hdr, ooa_links);
11547
11548					ctl_free_io(io);
11549				}
11550			}
11551
11552			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11553	     		     io != NULL; io = next_io) {
11554
11555		        	next_io = (union ctl_io *)TAILQ_NEXT(
11556				    &io->io_hdr, ooa_links);
11557
11558				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11559
11560					TAILQ_REMOVE(&lun->ooa_queue,
11561						&io->io_hdr,
11562					     	ooa_links);
11563
11564					ctl_free_io(io);
11565				}
11566			}
11567			ctl_check_blocked(lun);
11568		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11569			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11570
11571			printf("FAILOVER: primary lun %d\n", lun_idx);
11572			/*
11573			 * Abort all commands from the other SC.  We can't
11574			 * send status back for them now.  These should get
11575			 * cleaned up when they are completed or come out
11576			 * for a datamove operation.
11577			 */
11578			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11579	     		     io != NULL; io = next_io) {
11580		        	next_io = (union ctl_io *)TAILQ_NEXT(
11581					&io->io_hdr, ooa_links);
11582
11583				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11584					io->io_hdr.flags |= CTL_FLAG_ABORT;
11585			}
11586		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11587			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11588
11589			printf("FAILOVER: secondary lun %d\n", lun_idx);
11590
11591			lun->flags |= CTL_LUN_PRIMARY_SC;
11592
11593			/*
11594			 * We send all I/O that was sent to this controller
11595			 * and redirected to the other side back with
11596			 * busy status, and have the initiator retry it.
11597			 * Figuring out how much data has been transferred,
11598			 * etc. and picking up where we left off would be
11599			 * very tricky.
11600			 *
11601			 * XXX KDM need to remove I/O from the blocked
11602			 * queue as well!
11603			 */
11604			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11605			     &lun->ooa_queue); pending_io != NULL;
11606			     pending_io = next_io) {
11607
11608				next_io =  (union ctl_io *)TAILQ_NEXT(
11609					&pending_io->io_hdr, ooa_links);
11610
11611				pending_io->io_hdr.flags &=
11612					~CTL_FLAG_SENT_2OTHER_SC;
11613
11614				if (pending_io->io_hdr.flags &
11615				    CTL_FLAG_IO_ACTIVE) {
11616					pending_io->io_hdr.flags |=
11617						CTL_FLAG_FAILOVER;
11618				} else {
11619					ctl_set_busy(&pending_io->scsiio);
11620					ctl_done(pending_io);
11621				}
11622			}
11623
11624			/*
11625			 * Build Unit Attention
11626			 */
11627			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11628				lun->pending_ua[i] |=
11629				                     CTL_UA_ASYM_ACC_CHANGE;
11630			}
11631		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11632			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11633			printf("FAILOVER: secondary lun %d\n", lun_idx);
11634			/*
11635			 * if the first io on the OOA is not on the RtR queue
11636			 * add it.
11637			 */
11638			lun->flags |= CTL_LUN_PRIMARY_SC;
11639
11640			pending_io = (union ctl_io *)TAILQ_FIRST(
11641			    &lun->ooa_queue);
11642			if (pending_io==NULL) {
11643				printf("Nothing on OOA queue\n");
11644				continue;
11645			}
11646
11647			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11648			if ((pending_io->io_hdr.flags &
11649			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11650				pending_io->io_hdr.flags |=
11651				    CTL_FLAG_IS_WAS_ON_RTR;
11652				ctl_enqueue_rtr(pending_io);
11653			}
11654#if 0
11655			else
11656			{
11657				printf("Tag 0x%04x is running\n",
11658				      pending_io->scsiio.tag_num);
11659			}
11660#endif
11661
11662			next_io = (union ctl_io *)TAILQ_NEXT(
11663			    &pending_io->io_hdr, ooa_links);
11664			for (pending_io=next_io; pending_io != NULL;
11665			     pending_io = next_io) {
11666				pending_io->io_hdr.flags &=
11667				    ~CTL_FLAG_SENT_2OTHER_SC;
11668				next_io = (union ctl_io *)TAILQ_NEXT(
11669					&pending_io->io_hdr, ooa_links);
11670				if (pending_io->io_hdr.flags &
11671				    CTL_FLAG_IS_WAS_ON_RTR) {
11672#if 0
11673				        printf("Tag 0x%04x is running\n",
11674				      		pending_io->scsiio.tag_num);
11675#endif
11676					continue;
11677				}
11678
11679				switch (ctl_check_ooa(lun, pending_io,
11680			            (union ctl_io *)TAILQ_PREV(
11681				    &pending_io->io_hdr, ctl_ooaq,
11682				    ooa_links))) {
11683
11684				case CTL_ACTION_BLOCK:
11685					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11686							  &pending_io->io_hdr,
11687							  blocked_links);
11688					pending_io->io_hdr.flags |=
11689					    CTL_FLAG_BLOCKED;
11690					break;
11691				case CTL_ACTION_PASS:
11692				case CTL_ACTION_SKIP:
11693					pending_io->io_hdr.flags |=
11694					    CTL_FLAG_IS_WAS_ON_RTR;
11695					ctl_enqueue_rtr(pending_io);
11696					break;
11697				case CTL_ACTION_OVERLAP:
11698					ctl_set_overlapped_cmd(
11699					    (struct ctl_scsiio *)pending_io);
11700					ctl_done(pending_io);
11701					break;
11702				case CTL_ACTION_OVERLAP_TAG:
11703					ctl_set_overlapped_tag(
11704					    (struct ctl_scsiio *)pending_io,
11705					    pending_io->scsiio.tag_num & 0xff);
11706					ctl_done(pending_io);
11707					break;
11708				case CTL_ACTION_ERROR:
11709				default:
11710					ctl_set_internal_failure(
11711						(struct ctl_scsiio *)pending_io,
11712						0,  // sks_valid
11713						0); //retry count
11714					ctl_done(pending_io);
11715					break;
11716				}
11717			}
11718
11719			/*
11720			 * Build Unit Attention
11721			 */
11722			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11723				lun->pending_ua[i] |=
11724				                     CTL_UA_ASYM_ACC_CHANGE;
11725			}
11726		} else {
11727			panic("Unhandled HA mode failover, LUN flags = %#x, "
11728			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11729		}
11730	}
11731	ctl_pause_rtr = 0;
11732	mtx_unlock(&ctl_softc->ctl_lock);
11733}
11734
11735static int
11736ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11737{
11738	struct ctl_lun *lun;
11739	const struct ctl_cmd_entry *entry;
11740	uint32_t initidx, targ_lun;
11741	int retval;
11742
11743	retval = 0;
11744
11745	lun = NULL;
11746
11747	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11748	if ((targ_lun < CTL_MAX_LUNS)
11749	 && (ctl_softc->ctl_luns[targ_lun] != NULL)) {
11750		lun = ctl_softc->ctl_luns[targ_lun];
11751		/*
11752		 * If the LUN is invalid, pretend that it doesn't exist.
11753		 * It will go away as soon as all pending I/O has been
11754		 * completed.
11755		 */
11756		if (lun->flags & CTL_LUN_DISABLED) {
11757			lun = NULL;
11758		} else {
11759			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11760			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11761				lun->be_lun;
11762			if (lun->be_lun->lun_type == T_PROCESSOR) {
11763				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11764			}
11765
11766			/*
11767			 * Every I/O goes into the OOA queue for a
11768			 * particular LUN, and stays there until completion.
11769			 */
11770			mtx_lock(&lun->lun_lock);
11771			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11772			    ooa_links);
11773		}
11774	} else {
11775		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11776		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11777	}
11778
11779	/* Get command entry and return error if it is unsuppotyed. */
11780	entry = ctl_validate_command(ctsio);
11781	if (entry == NULL) {
11782		if (lun)
11783			mtx_unlock(&lun->lun_lock);
11784		return (retval);
11785	}
11786
11787	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11788	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11789
11790	/*
11791	 * Check to see whether we can send this command to LUNs that don't
11792	 * exist.  This should pretty much only be the case for inquiry
11793	 * and request sense.  Further checks, below, really require having
11794	 * a LUN, so we can't really check the command anymore.  Just put
11795	 * it on the rtr queue.
11796	 */
11797	if (lun == NULL) {
11798		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11799			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11800			ctl_enqueue_rtr((union ctl_io *)ctsio);
11801			return (retval);
11802		}
11803
11804		ctl_set_unsupported_lun(ctsio);
11805		ctl_done((union ctl_io *)ctsio);
11806		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11807		return (retval);
11808	} else {
11809		/*
11810		 * Make sure we support this particular command on this LUN.
11811		 * e.g., we don't support writes to the control LUN.
11812		 */
11813		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11814			mtx_unlock(&lun->lun_lock);
11815			ctl_set_invalid_opcode(ctsio);
11816			ctl_done((union ctl_io *)ctsio);
11817			return (retval);
11818		}
11819	}
11820
11821	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11822
11823#ifdef CTL_WITH_CA
11824	/*
11825	 * If we've got a request sense, it'll clear the contingent
11826	 * allegiance condition.  Otherwise, if we have a CA condition for
11827	 * this initiator, clear it, because it sent down a command other
11828	 * than request sense.
11829	 */
11830	if ((ctsio->cdb[0] != REQUEST_SENSE)
11831	 && (ctl_is_set(lun->have_ca, initidx)))
11832		ctl_clear_mask(lun->have_ca, initidx);
11833#endif
11834
11835	/*
11836	 * If the command has this flag set, it handles its own unit
11837	 * attention reporting, we shouldn't do anything.  Otherwise we
11838	 * check for any pending unit attentions, and send them back to the
11839	 * initiator.  We only do this when a command initially comes in,
11840	 * not when we pull it off the blocked queue.
11841	 *
11842	 * According to SAM-3, section 5.3.2, the order that things get
11843	 * presented back to the host is basically unit attentions caused
11844	 * by some sort of reset event, busy status, reservation conflicts
11845	 * or task set full, and finally any other status.
11846	 *
11847	 * One issue here is that some of the unit attentions we report
11848	 * don't fall into the "reset" category (e.g. "reported luns data
11849	 * has changed").  So reporting it here, before the reservation
11850	 * check, may be technically wrong.  I guess the only thing to do
11851	 * would be to check for and report the reset events here, and then
11852	 * check for the other unit attention types after we check for a
11853	 * reservation conflict.
11854	 *
11855	 * XXX KDM need to fix this
11856	 */
11857	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11858		ctl_ua_type ua_type;
11859
11860		if (lun->pending_ua[initidx] != CTL_UA_NONE) {
11861			scsi_sense_data_type sense_format;
11862
11863			if (lun != NULL)
11864				sense_format = (lun->flags &
11865				    CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11866				    SSD_TYPE_FIXED;
11867			else
11868				sense_format = SSD_TYPE_FIXED;
11869
11870			ua_type = ctl_build_ua(&lun->pending_ua[initidx],
11871			    &ctsio->sense_data, sense_format);
11872			if (ua_type != CTL_UA_NONE) {
11873				ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11874				ctsio->io_hdr.status = CTL_SCSI_ERROR |
11875						       CTL_AUTOSENSE;
11876				ctsio->sense_len = SSD_FULL_SIZE;
11877				mtx_unlock(&lun->lun_lock);
11878				ctl_done((union ctl_io *)ctsio);
11879				return (retval);
11880			}
11881		}
11882	}
11883
11884
11885	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11886		mtx_unlock(&lun->lun_lock);
11887		ctl_done((union ctl_io *)ctsio);
11888		return (retval);
11889	}
11890
11891	/*
11892	 * XXX CHD this is where we want to send IO to other side if
11893	 * this LUN is secondary on this SC. We will need to make a copy
11894	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11895	 * the copy we send as FROM_OTHER.
11896	 * We also need to stuff the address of the original IO so we can
11897	 * find it easily. Something similar will need be done on the other
11898	 * side so when we are done we can find the copy.
11899	 */
11900	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11901		union ctl_ha_msg msg_info;
11902		int isc_retval;
11903
11904		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11905
11906		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11907		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11908#if 0
11909		printf("1. ctsio %p\n", ctsio);
11910#endif
11911		msg_info.hdr.serializing_sc = NULL;
11912		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11913		msg_info.scsi.tag_num = ctsio->tag_num;
11914		msg_info.scsi.tag_type = ctsio->tag_type;
11915		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11916
11917		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11918
11919		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11920		    (void *)&msg_info, sizeof(msg_info), 0)) >
11921		    CTL_HA_STATUS_SUCCESS) {
11922			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11923			       isc_retval);
11924			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11925		} else {
11926#if 0
11927			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11928#endif
11929		}
11930
11931		/*
11932		 * XXX KDM this I/O is off the incoming queue, but hasn't
11933		 * been inserted on any other queue.  We may need to come
11934		 * up with a holding queue while we wait for serialization
11935		 * so that we have an idea of what we're waiting for from
11936		 * the other side.
11937		 */
11938		mtx_unlock(&lun->lun_lock);
11939		return (retval);
11940	}
11941
11942	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11943			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11944			      ctl_ooaq, ooa_links))) {
11945	case CTL_ACTION_BLOCK:
11946		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11947		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11948				  blocked_links);
11949		mtx_unlock(&lun->lun_lock);
11950		return (retval);
11951	case CTL_ACTION_PASS:
11952	case CTL_ACTION_SKIP:
11953		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11954		mtx_unlock(&lun->lun_lock);
11955		ctl_enqueue_rtr((union ctl_io *)ctsio);
11956		break;
11957	case CTL_ACTION_OVERLAP:
11958		mtx_unlock(&lun->lun_lock);
11959		ctl_set_overlapped_cmd(ctsio);
11960		ctl_done((union ctl_io *)ctsio);
11961		break;
11962	case CTL_ACTION_OVERLAP_TAG:
11963		mtx_unlock(&lun->lun_lock);
11964		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11965		ctl_done((union ctl_io *)ctsio);
11966		break;
11967	case CTL_ACTION_ERROR:
11968	default:
11969		mtx_unlock(&lun->lun_lock);
11970		ctl_set_internal_failure(ctsio,
11971					 /*sks_valid*/ 0,
11972					 /*retry_count*/ 0);
11973		ctl_done((union ctl_io *)ctsio);
11974		break;
11975	}
11976	return (retval);
11977}
11978
11979const struct ctl_cmd_entry *
11980ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11981{
11982	const struct ctl_cmd_entry *entry;
11983	int service_action;
11984
11985	entry = &ctl_cmd_table[ctsio->cdb[0]];
11986	if (sa)
11987		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11988	if (entry->flags & CTL_CMD_FLAG_SA5) {
11989		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11990		entry = &((const struct ctl_cmd_entry *)
11991		    entry->execute)[service_action];
11992	}
11993	return (entry);
11994}
11995
11996const struct ctl_cmd_entry *
11997ctl_validate_command(struct ctl_scsiio *ctsio)
11998{
11999	const struct ctl_cmd_entry *entry;
12000	int i, sa;
12001	uint8_t diff;
12002
12003	entry = ctl_get_cmd_entry(ctsio, &sa);
12004	if (entry->execute == NULL) {
12005		if (sa)
12006			ctl_set_invalid_field(ctsio,
12007					      /*sks_valid*/ 1,
12008					      /*command*/ 1,
12009					      /*field*/ 1,
12010					      /*bit_valid*/ 1,
12011					      /*bit*/ 4);
12012		else
12013			ctl_set_invalid_opcode(ctsio);
12014		ctl_done((union ctl_io *)ctsio);
12015		return (NULL);
12016	}
12017	KASSERT(entry->length > 0,
12018	    ("Not defined length for command 0x%02x/0x%02x",
12019	     ctsio->cdb[0], ctsio->cdb[1]));
12020	for (i = 1; i < entry->length; i++) {
12021		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
12022		if (diff == 0)
12023			continue;
12024		ctl_set_invalid_field(ctsio,
12025				      /*sks_valid*/ 1,
12026				      /*command*/ 1,
12027				      /*field*/ i,
12028				      /*bit_valid*/ 1,
12029				      /*bit*/ fls(diff) - 1);
12030		ctl_done((union ctl_io *)ctsio);
12031		return (NULL);
12032	}
12033	return (entry);
12034}
12035
12036static int
12037ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
12038{
12039
12040	switch (lun_type) {
12041	case T_PROCESSOR:
12042		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
12043		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
12044			return (0);
12045		break;
12046	case T_DIRECT:
12047		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
12048		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
12049			return (0);
12050		break;
12051	default:
12052		return (0);
12053	}
12054	return (1);
12055}
12056
12057static int
12058ctl_scsiio(struct ctl_scsiio *ctsio)
12059{
12060	int retval;
12061	const struct ctl_cmd_entry *entry;
12062
12063	retval = CTL_RETVAL_COMPLETE;
12064
12065	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
12066
12067	entry = ctl_get_cmd_entry(ctsio, NULL);
12068
12069	/*
12070	 * If this I/O has been aborted, just send it straight to
12071	 * ctl_done() without executing it.
12072	 */
12073	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
12074		ctl_done((union ctl_io *)ctsio);
12075		goto bailout;
12076	}
12077
12078	/*
12079	 * All the checks should have been handled by ctl_scsiio_precheck().
12080	 * We should be clear now to just execute the I/O.
12081	 */
12082	retval = entry->execute(ctsio);
12083
12084bailout:
12085	return (retval);
12086}
12087
12088/*
12089 * Since we only implement one target right now, a bus reset simply resets
12090 * our single target.
12091 */
12092static int
12093ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
12094{
12095	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
12096}
12097
12098static int
12099ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
12100		 ctl_ua_type ua_type)
12101{
12102	struct ctl_lun *lun;
12103	int retval;
12104
12105	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12106		union ctl_ha_msg msg_info;
12107
12108		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
12109		msg_info.hdr.nexus = io->io_hdr.nexus;
12110		if (ua_type==CTL_UA_TARG_RESET)
12111			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
12112		else
12113			msg_info.task.task_action = CTL_TASK_BUS_RESET;
12114		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12115		msg_info.hdr.original_sc = NULL;
12116		msg_info.hdr.serializing_sc = NULL;
12117		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12118		    (void *)&msg_info, sizeof(msg_info), 0)) {
12119		}
12120	}
12121	retval = 0;
12122
12123	mtx_lock(&ctl_softc->ctl_lock);
12124	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
12125		retval += ctl_lun_reset(lun, io, ua_type);
12126	mtx_unlock(&ctl_softc->ctl_lock);
12127
12128	return (retval);
12129}
12130
12131/*
12132 * The LUN should always be set.  The I/O is optional, and is used to
12133 * distinguish between I/Os sent by this initiator, and by other
12134 * initiators.  We set unit attention for initiators other than this one.
12135 * SAM-3 is vague on this point.  It does say that a unit attention should
12136 * be established for other initiators when a LUN is reset (see section
12137 * 5.7.3), but it doesn't specifically say that the unit attention should
12138 * be established for this particular initiator when a LUN is reset.  Here
12139 * is the relevant text, from SAM-3 rev 8:
12140 *
12141 * 5.7.2 When a SCSI initiator port aborts its own tasks
12142 *
12143 * When a SCSI initiator port causes its own task(s) to be aborted, no
12144 * notification that the task(s) have been aborted shall be returned to
12145 * the SCSI initiator port other than the completion response for the
12146 * command or task management function action that caused the task(s) to
12147 * be aborted and notification(s) associated with related effects of the
12148 * action (e.g., a reset unit attention condition).
12149 *
12150 * XXX KDM for now, we're setting unit attention for all initiators.
12151 */
12152static int
12153ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
12154{
12155	union ctl_io *xio;
12156#if 0
12157	uint32_t initindex;
12158#endif
12159	int i;
12160
12161	mtx_lock(&lun->lun_lock);
12162	/*
12163	 * Run through the OOA queue and abort each I/O.
12164	 */
12165#if 0
12166	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12167#endif
12168	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12169	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12170		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
12171	}
12172
12173	/*
12174	 * This version sets unit attention for every
12175	 */
12176#if 0
12177	initindex = ctl_get_initindex(&io->io_hdr.nexus);
12178	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
12179		if (initindex == i)
12180			continue;
12181		lun->pending_ua[i] |= ua_type;
12182	}
12183#endif
12184
12185	/*
12186	 * A reset (any kind, really) clears reservations established with
12187	 * RESERVE/RELEASE.  It does not clear reservations established
12188	 * with PERSISTENT RESERVE OUT, but we don't support that at the
12189	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
12190	 * reservations made with the RESERVE/RELEASE commands, because
12191	 * those commands are obsolete in SPC-3.
12192	 */
12193	lun->flags &= ~CTL_LUN_RESERVED;
12194
12195	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
12196#ifdef CTL_WITH_CA
12197		ctl_clear_mask(lun->have_ca, i);
12198#endif
12199		lun->pending_ua[i] |= ua_type;
12200	}
12201	mtx_unlock(&lun->lun_lock);
12202
12203	return (0);
12204}
12205
12206static void
12207ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
12208    int other_sc)
12209{
12210	union ctl_io *xio;
12211
12212	mtx_assert(&lun->lun_lock, MA_OWNED);
12213
12214	/*
12215	 * Run through the OOA queue and attempt to find the given I/O.
12216	 * The target port, initiator ID, tag type and tag number have to
12217	 * match the values that we got from the initiator.  If we have an
12218	 * untagged command to abort, simply abort the first untagged command
12219	 * we come to.  We only allow one untagged command at a time of course.
12220	 */
12221	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12222	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12223
12224		if ((targ_port == UINT32_MAX ||
12225		     targ_port == xio->io_hdr.nexus.targ_port) &&
12226		    (init_id == UINT32_MAX ||
12227		     init_id == xio->io_hdr.nexus.initid.id)) {
12228			if (targ_port != xio->io_hdr.nexus.targ_port ||
12229			    init_id != xio->io_hdr.nexus.initid.id)
12230				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12231			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12232			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12233				union ctl_ha_msg msg_info;
12234
12235				msg_info.hdr.nexus = xio->io_hdr.nexus;
12236				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12237				msg_info.task.tag_num = xio->scsiio.tag_num;
12238				msg_info.task.tag_type = xio->scsiio.tag_type;
12239				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12240				msg_info.hdr.original_sc = NULL;
12241				msg_info.hdr.serializing_sc = NULL;
12242				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12243				    (void *)&msg_info, sizeof(msg_info), 0);
12244			}
12245		}
12246	}
12247}
12248
12249static int
12250ctl_abort_task_set(union ctl_io *io)
12251{
12252	struct ctl_softc *softc = control_softc;
12253	struct ctl_lun *lun;
12254	uint32_t targ_lun;
12255
12256	/*
12257	 * Look up the LUN.
12258	 */
12259	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12260	mtx_lock(&softc->ctl_lock);
12261	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
12262		lun = softc->ctl_luns[targ_lun];
12263	else {
12264		mtx_unlock(&softc->ctl_lock);
12265		return (1);
12266	}
12267
12268	mtx_lock(&lun->lun_lock);
12269	mtx_unlock(&softc->ctl_lock);
12270	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12271		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12272		    io->io_hdr.nexus.initid.id,
12273		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12274	} else { /* CTL_TASK_CLEAR_TASK_SET */
12275		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12276		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12277	}
12278	mtx_unlock(&lun->lun_lock);
12279	return (0);
12280}
12281
12282static int
12283ctl_i_t_nexus_reset(union ctl_io *io)
12284{
12285	struct ctl_softc *softc = control_softc;
12286	struct ctl_lun *lun;
12287	uint32_t initindex, residx;
12288
12289	initindex = ctl_get_initindex(&io->io_hdr.nexus);
12290	residx = ctl_get_resindex(&io->io_hdr.nexus);
12291	mtx_lock(&softc->ctl_lock);
12292	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12293		mtx_lock(&lun->lun_lock);
12294		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12295		    io->io_hdr.nexus.initid.id,
12296		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12297#ifdef CTL_WITH_CA
12298		ctl_clear_mask(lun->have_ca, initindex);
12299#endif
12300		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
12301			lun->flags &= ~CTL_LUN_RESERVED;
12302		lun->pending_ua[initindex] |= CTL_UA_I_T_NEXUS_LOSS;
12303		mtx_unlock(&lun->lun_lock);
12304	}
12305	mtx_unlock(&softc->ctl_lock);
12306	return (0);
12307}
12308
12309static int
12310ctl_abort_task(union ctl_io *io)
12311{
12312	union ctl_io *xio;
12313	struct ctl_lun *lun;
12314	struct ctl_softc *ctl_softc;
12315#if 0
12316	struct sbuf sb;
12317	char printbuf[128];
12318#endif
12319	int found;
12320	uint32_t targ_lun;
12321
12322	ctl_softc = control_softc;
12323	found = 0;
12324
12325	/*
12326	 * Look up the LUN.
12327	 */
12328	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12329	mtx_lock(&ctl_softc->ctl_lock);
12330	if ((targ_lun < CTL_MAX_LUNS)
12331	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12332		lun = ctl_softc->ctl_luns[targ_lun];
12333	else {
12334		mtx_unlock(&ctl_softc->ctl_lock);
12335		return (1);
12336	}
12337
12338#if 0
12339	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12340	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12341#endif
12342
12343	mtx_lock(&lun->lun_lock);
12344	mtx_unlock(&ctl_softc->ctl_lock);
12345	/*
12346	 * Run through the OOA queue and attempt to find the given I/O.
12347	 * The target port, initiator ID, tag type and tag number have to
12348	 * match the values that we got from the initiator.  If we have an
12349	 * untagged command to abort, simply abort the first untagged command
12350	 * we come to.  We only allow one untagged command at a time of course.
12351	 */
12352#if 0
12353	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12354#endif
12355	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12356	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12357#if 0
12358		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12359
12360		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12361			    lun->lun, xio->scsiio.tag_num,
12362			    xio->scsiio.tag_type,
12363			    (xio->io_hdr.blocked_links.tqe_prev
12364			    == NULL) ? "" : " BLOCKED",
12365			    (xio->io_hdr.flags &
12366			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12367			    (xio->io_hdr.flags &
12368			    CTL_FLAG_ABORT) ? " ABORT" : "",
12369			    (xio->io_hdr.flags &
12370			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12371		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12372		sbuf_finish(&sb);
12373		printf("%s\n", sbuf_data(&sb));
12374#endif
12375
12376		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12377		 && (xio->io_hdr.nexus.initid.id ==
12378		     io->io_hdr.nexus.initid.id)) {
12379			/*
12380			 * If the abort says that the task is untagged, the
12381			 * task in the queue must be untagged.  Otherwise,
12382			 * we just check to see whether the tag numbers
12383			 * match.  This is because the QLogic firmware
12384			 * doesn't pass back the tag type in an abort
12385			 * request.
12386			 */
12387#if 0
12388			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12389			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12390			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12391#endif
12392			/*
12393			 * XXX KDM we've got problems with FC, because it
12394			 * doesn't send down a tag type with aborts.  So we
12395			 * can only really go by the tag number...
12396			 * This may cause problems with parallel SCSI.
12397			 * Need to figure that out!!
12398			 */
12399			if (xio->scsiio.tag_num == io->taskio.tag_num) {
12400				xio->io_hdr.flags |= CTL_FLAG_ABORT;
12401				found = 1;
12402				if ((io->io_hdr.flags &
12403				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
12404				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12405					union ctl_ha_msg msg_info;
12406
12407					io->io_hdr.flags |=
12408					                CTL_FLAG_SENT_2OTHER_SC;
12409					msg_info.hdr.nexus = io->io_hdr.nexus;
12410					msg_info.task.task_action =
12411						CTL_TASK_ABORT_TASK;
12412					msg_info.task.tag_num =
12413						io->taskio.tag_num;
12414					msg_info.task.tag_type =
12415						io->taskio.tag_type;
12416					msg_info.hdr.msg_type =
12417						CTL_MSG_MANAGE_TASKS;
12418					msg_info.hdr.original_sc = NULL;
12419					msg_info.hdr.serializing_sc = NULL;
12420#if 0
12421					printf("Sent Abort to other side\n");
12422#endif
12423					if (CTL_HA_STATUS_SUCCESS !=
12424					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12425		    				(void *)&msg_info,
12426						sizeof(msg_info), 0)) {
12427					}
12428				}
12429#if 0
12430				printf("ctl_abort_task: found I/O to abort\n");
12431#endif
12432				break;
12433			}
12434		}
12435	}
12436	mtx_unlock(&lun->lun_lock);
12437
12438	if (found == 0) {
12439		/*
12440		 * This isn't really an error.  It's entirely possible for
12441		 * the abort and command completion to cross on the wire.
12442		 * This is more of an informative/diagnostic error.
12443		 */
12444#if 0
12445		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12446		       "%d:%d:%d:%d tag %d type %d\n",
12447		       io->io_hdr.nexus.initid.id,
12448		       io->io_hdr.nexus.targ_port,
12449		       io->io_hdr.nexus.targ_target.id,
12450		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12451		       io->taskio.tag_type);
12452#endif
12453	}
12454	return (0);
12455}
12456
12457static void
12458ctl_run_task(union ctl_io *io)
12459{
12460	struct ctl_softc *ctl_softc = control_softc;
12461	int retval = 1;
12462	const char *task_desc;
12463
12464	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12465
12466	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12467	    ("ctl_run_task: Unextected io_type %d\n",
12468	     io->io_hdr.io_type));
12469
12470	task_desc = ctl_scsi_task_string(&io->taskio);
12471	if (task_desc != NULL) {
12472#ifdef NEEDTOPORT
12473		csevent_log(CSC_CTL | CSC_SHELF_SW |
12474			    CTL_TASK_REPORT,
12475			    csevent_LogType_Trace,
12476			    csevent_Severity_Information,
12477			    csevent_AlertLevel_Green,
12478			    csevent_FRU_Firmware,
12479			    csevent_FRU_Unknown,
12480			    "CTL: received task: %s",task_desc);
12481#endif
12482	} else {
12483#ifdef NEEDTOPORT
12484		csevent_log(CSC_CTL | CSC_SHELF_SW |
12485			    CTL_TASK_REPORT,
12486			    csevent_LogType_Trace,
12487			    csevent_Severity_Information,
12488			    csevent_AlertLevel_Green,
12489			    csevent_FRU_Firmware,
12490			    csevent_FRU_Unknown,
12491			    "CTL: received unknown task "
12492			    "type: %d (%#x)",
12493			    io->taskio.task_action,
12494			    io->taskio.task_action);
12495#endif
12496	}
12497	switch (io->taskio.task_action) {
12498	case CTL_TASK_ABORT_TASK:
12499		retval = ctl_abort_task(io);
12500		break;
12501	case CTL_TASK_ABORT_TASK_SET:
12502	case CTL_TASK_CLEAR_TASK_SET:
12503		retval = ctl_abort_task_set(io);
12504		break;
12505	case CTL_TASK_CLEAR_ACA:
12506		break;
12507	case CTL_TASK_I_T_NEXUS_RESET:
12508		retval = ctl_i_t_nexus_reset(io);
12509		break;
12510	case CTL_TASK_LUN_RESET: {
12511		struct ctl_lun *lun;
12512		uint32_t targ_lun;
12513
12514		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12515		mtx_lock(&ctl_softc->ctl_lock);
12516		if ((targ_lun < CTL_MAX_LUNS)
12517		 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12518			lun = ctl_softc->ctl_luns[targ_lun];
12519		else {
12520			mtx_unlock(&ctl_softc->ctl_lock);
12521			retval = 1;
12522			break;
12523		}
12524
12525		if (!(io->io_hdr.flags &
12526		    CTL_FLAG_FROM_OTHER_SC)) {
12527			union ctl_ha_msg msg_info;
12528
12529			io->io_hdr.flags |=
12530				CTL_FLAG_SENT_2OTHER_SC;
12531			msg_info.hdr.msg_type =
12532				CTL_MSG_MANAGE_TASKS;
12533			msg_info.hdr.nexus = io->io_hdr.nexus;
12534			msg_info.task.task_action =
12535				CTL_TASK_LUN_RESET;
12536			msg_info.hdr.original_sc = NULL;
12537			msg_info.hdr.serializing_sc = NULL;
12538			if (CTL_HA_STATUS_SUCCESS !=
12539			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12540			    (void *)&msg_info,
12541			    sizeof(msg_info), 0)) {
12542			}
12543		}
12544
12545		retval = ctl_lun_reset(lun, io,
12546				       CTL_UA_LUN_RESET);
12547		mtx_unlock(&ctl_softc->ctl_lock);
12548		break;
12549	}
12550	case CTL_TASK_TARGET_RESET:
12551		retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12552		break;
12553	case CTL_TASK_BUS_RESET:
12554		retval = ctl_bus_reset(ctl_softc, io);
12555		break;
12556	case CTL_TASK_PORT_LOGIN:
12557		break;
12558	case CTL_TASK_PORT_LOGOUT:
12559		break;
12560	default:
12561		printf("ctl_run_task: got unknown task management event %d\n",
12562		       io->taskio.task_action);
12563		break;
12564	}
12565	if (retval == 0)
12566		io->io_hdr.status = CTL_SUCCESS;
12567	else
12568		io->io_hdr.status = CTL_ERROR;
12569	ctl_done(io);
12570}
12571
12572/*
12573 * For HA operation.  Handle commands that come in from the other
12574 * controller.
12575 */
12576static void
12577ctl_handle_isc(union ctl_io *io)
12578{
12579	int free_io;
12580	struct ctl_lun *lun;
12581	struct ctl_softc *ctl_softc;
12582	uint32_t targ_lun;
12583
12584	ctl_softc = control_softc;
12585
12586	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12587	lun = ctl_softc->ctl_luns[targ_lun];
12588
12589	switch (io->io_hdr.msg_type) {
12590	case CTL_MSG_SERIALIZE:
12591		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12592		break;
12593	case CTL_MSG_R2R: {
12594		const struct ctl_cmd_entry *entry;
12595
12596		/*
12597		 * This is only used in SER_ONLY mode.
12598		 */
12599		free_io = 0;
12600		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12601		mtx_lock(&lun->lun_lock);
12602		if (ctl_scsiio_lun_check(ctl_softc, lun,
12603		    entry, (struct ctl_scsiio *)io) != 0) {
12604			mtx_unlock(&lun->lun_lock);
12605			ctl_done(io);
12606			break;
12607		}
12608		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12609		mtx_unlock(&lun->lun_lock);
12610		ctl_enqueue_rtr(io);
12611		break;
12612	}
12613	case CTL_MSG_FINISH_IO:
12614		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12615			free_io = 0;
12616			ctl_done(io);
12617		} else {
12618			free_io = 1;
12619			mtx_lock(&lun->lun_lock);
12620			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12621				     ooa_links);
12622			ctl_check_blocked(lun);
12623			mtx_unlock(&lun->lun_lock);
12624		}
12625		break;
12626	case CTL_MSG_PERS_ACTION:
12627		ctl_hndl_per_res_out_on_other_sc(
12628			(union ctl_ha_msg *)&io->presio.pr_msg);
12629		free_io = 1;
12630		break;
12631	case CTL_MSG_BAD_JUJU:
12632		free_io = 0;
12633		ctl_done(io);
12634		break;
12635	case CTL_MSG_DATAMOVE:
12636		/* Only used in XFER mode */
12637		free_io = 0;
12638		ctl_datamove_remote(io);
12639		break;
12640	case CTL_MSG_DATAMOVE_DONE:
12641		/* Only used in XFER mode */
12642		free_io = 0;
12643		io->scsiio.be_move_done(io);
12644		break;
12645	default:
12646		free_io = 1;
12647		printf("%s: Invalid message type %d\n",
12648		       __func__, io->io_hdr.msg_type);
12649		break;
12650	}
12651	if (free_io)
12652		ctl_free_io(io);
12653
12654}
12655
12656
12657/*
12658 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12659 * there is no match.
12660 */
12661static ctl_lun_error_pattern
12662ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12663{
12664	const struct ctl_cmd_entry *entry;
12665	ctl_lun_error_pattern filtered_pattern, pattern;
12666
12667	pattern = desc->error_pattern;
12668
12669	/*
12670	 * XXX KDM we need more data passed into this function to match a
12671	 * custom pattern, and we actually need to implement custom pattern
12672	 * matching.
12673	 */
12674	if (pattern & CTL_LUN_PAT_CMD)
12675		return (CTL_LUN_PAT_CMD);
12676
12677	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12678		return (CTL_LUN_PAT_ANY);
12679
12680	entry = ctl_get_cmd_entry(ctsio, NULL);
12681
12682	filtered_pattern = entry->pattern & pattern;
12683
12684	/*
12685	 * If the user requested specific flags in the pattern (e.g.
12686	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12687	 * flags.
12688	 *
12689	 * If the user did not specify any flags, it doesn't matter whether
12690	 * or not the command supports the flags.
12691	 */
12692	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12693	     (pattern & ~CTL_LUN_PAT_MASK))
12694		return (CTL_LUN_PAT_NONE);
12695
12696	/*
12697	 * If the user asked for a range check, see if the requested LBA
12698	 * range overlaps with this command's LBA range.
12699	 */
12700	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12701		uint64_t lba1;
12702		uint64_t len1;
12703		ctl_action action;
12704		int retval;
12705
12706		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12707		if (retval != 0)
12708			return (CTL_LUN_PAT_NONE);
12709
12710		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12711					      desc->lba_range.len);
12712		/*
12713		 * A "pass" means that the LBA ranges don't overlap, so
12714		 * this doesn't match the user's range criteria.
12715		 */
12716		if (action == CTL_ACTION_PASS)
12717			return (CTL_LUN_PAT_NONE);
12718	}
12719
12720	return (filtered_pattern);
12721}
12722
12723static void
12724ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12725{
12726	struct ctl_error_desc *desc, *desc2;
12727
12728	mtx_assert(&lun->lun_lock, MA_OWNED);
12729
12730	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12731		ctl_lun_error_pattern pattern;
12732		/*
12733		 * Check to see whether this particular command matches
12734		 * the pattern in the descriptor.
12735		 */
12736		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12737		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12738			continue;
12739
12740		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12741		case CTL_LUN_INJ_ABORTED:
12742			ctl_set_aborted(&io->scsiio);
12743			break;
12744		case CTL_LUN_INJ_MEDIUM_ERR:
12745			ctl_set_medium_error(&io->scsiio);
12746			break;
12747		case CTL_LUN_INJ_UA:
12748			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12749			 * OCCURRED */
12750			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12751			break;
12752		case CTL_LUN_INJ_CUSTOM:
12753			/*
12754			 * We're assuming the user knows what he is doing.
12755			 * Just copy the sense information without doing
12756			 * checks.
12757			 */
12758			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12759			      ctl_min(sizeof(desc->custom_sense),
12760				      sizeof(io->scsiio.sense_data)));
12761			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12762			io->scsiio.sense_len = SSD_FULL_SIZE;
12763			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12764			break;
12765		case CTL_LUN_INJ_NONE:
12766		default:
12767			/*
12768			 * If this is an error injection type we don't know
12769			 * about, clear the continuous flag (if it is set)
12770			 * so it will get deleted below.
12771			 */
12772			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12773			break;
12774		}
12775		/*
12776		 * By default, each error injection action is a one-shot
12777		 */
12778		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12779			continue;
12780
12781		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12782
12783		free(desc, M_CTL);
12784	}
12785}
12786
12787#ifdef CTL_IO_DELAY
12788static void
12789ctl_datamove_timer_wakeup(void *arg)
12790{
12791	union ctl_io *io;
12792
12793	io = (union ctl_io *)arg;
12794
12795	ctl_datamove(io);
12796}
12797#endif /* CTL_IO_DELAY */
12798
12799void
12800ctl_datamove(union ctl_io *io)
12801{
12802	void (*fe_datamove)(union ctl_io *io);
12803
12804	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12805
12806	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12807
12808#ifdef CTL_TIME_IO
12809	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12810		char str[256];
12811		char path_str[64];
12812		struct sbuf sb;
12813
12814		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12815		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12816
12817		sbuf_cat(&sb, path_str);
12818		switch (io->io_hdr.io_type) {
12819		case CTL_IO_SCSI:
12820			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12821			sbuf_printf(&sb, "\n");
12822			sbuf_cat(&sb, path_str);
12823			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12824				    io->scsiio.tag_num, io->scsiio.tag_type);
12825			break;
12826		case CTL_IO_TASK:
12827			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12828				    "Tag Type: %d\n", io->taskio.task_action,
12829				    io->taskio.tag_num, io->taskio.tag_type);
12830			break;
12831		default:
12832			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12833			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12834			break;
12835		}
12836		sbuf_cat(&sb, path_str);
12837		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12838			    (intmax_t)time_uptime - io->io_hdr.start_time);
12839		sbuf_finish(&sb);
12840		printf("%s", sbuf_data(&sb));
12841	}
12842#endif /* CTL_TIME_IO */
12843
12844#ifdef CTL_IO_DELAY
12845	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12846		struct ctl_lun *lun;
12847
12848		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12849
12850		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12851	} else {
12852		struct ctl_lun *lun;
12853
12854		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12855		if ((lun != NULL)
12856		 && (lun->delay_info.datamove_delay > 0)) {
12857			struct callout *callout;
12858
12859			callout = (struct callout *)&io->io_hdr.timer_bytes;
12860			callout_init(callout, /*mpsafe*/ 1);
12861			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12862			callout_reset(callout,
12863				      lun->delay_info.datamove_delay * hz,
12864				      ctl_datamove_timer_wakeup, io);
12865			if (lun->delay_info.datamove_type ==
12866			    CTL_DELAY_TYPE_ONESHOT)
12867				lun->delay_info.datamove_delay = 0;
12868			return;
12869		}
12870	}
12871#endif
12872
12873	/*
12874	 * This command has been aborted.  Set the port status, so we fail
12875	 * the data move.
12876	 */
12877	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12878		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12879		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12880		       io->io_hdr.nexus.targ_port,
12881		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12882		       io->io_hdr.nexus.targ_lun);
12883		io->io_hdr.port_status = 31337;
12884		/*
12885		 * Note that the backend, in this case, will get the
12886		 * callback in its context.  In other cases it may get
12887		 * called in the frontend's interrupt thread context.
12888		 */
12889		io->scsiio.be_move_done(io);
12890		return;
12891	}
12892
12893	/* Don't confuse frontend with zero length data move. */
12894	if (io->scsiio.kern_data_len == 0) {
12895		io->scsiio.be_move_done(io);
12896		return;
12897	}
12898
12899	/*
12900	 * If we're in XFER mode and this I/O is from the other shelf
12901	 * controller, we need to send the DMA to the other side to
12902	 * actually transfer the data to/from the host.  In serialize only
12903	 * mode the transfer happens below CTL and ctl_datamove() is only
12904	 * called on the machine that originally received the I/O.
12905	 */
12906	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12907	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12908		union ctl_ha_msg msg;
12909		uint32_t sg_entries_sent;
12910		int do_sg_copy;
12911		int i;
12912
12913		memset(&msg, 0, sizeof(msg));
12914		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12915		msg.hdr.original_sc = io->io_hdr.original_sc;
12916		msg.hdr.serializing_sc = io;
12917		msg.hdr.nexus = io->io_hdr.nexus;
12918		msg.dt.flags = io->io_hdr.flags;
12919		/*
12920		 * We convert everything into a S/G list here.  We can't
12921		 * pass by reference, only by value between controllers.
12922		 * So we can't pass a pointer to the S/G list, only as many
12923		 * S/G entries as we can fit in here.  If it's possible for
12924		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12925		 * then we need to break this up into multiple transfers.
12926		 */
12927		if (io->scsiio.kern_sg_entries == 0) {
12928			msg.dt.kern_sg_entries = 1;
12929			/*
12930			 * If this is in cached memory, flush the cache
12931			 * before we send the DMA request to the other
12932			 * controller.  We want to do this in either the
12933			 * read or the write case.  The read case is
12934			 * straightforward.  In the write case, we want to
12935			 * make sure nothing is in the local cache that
12936			 * could overwrite the DMAed data.
12937			 */
12938			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12939				/*
12940				 * XXX KDM use bus_dmamap_sync() here.
12941				 */
12942			}
12943
12944			/*
12945			 * Convert to a physical address if this is a
12946			 * virtual address.
12947			 */
12948			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12949				msg.dt.sg_list[0].addr =
12950					io->scsiio.kern_data_ptr;
12951			} else {
12952				/*
12953				 * XXX KDM use busdma here!
12954				 */
12955#if 0
12956				msg.dt.sg_list[0].addr = (void *)
12957					vtophys(io->scsiio.kern_data_ptr);
12958#endif
12959			}
12960
12961			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12962			do_sg_copy = 0;
12963		} else {
12964			struct ctl_sg_entry *sgl;
12965
12966			do_sg_copy = 1;
12967			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12968			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12969			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12970				/*
12971				 * XXX KDM use bus_dmamap_sync() here.
12972				 */
12973			}
12974		}
12975
12976		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12977		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12978		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12979		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12980		msg.dt.sg_sequence = 0;
12981
12982		/*
12983		 * Loop until we've sent all of the S/G entries.  On the
12984		 * other end, we'll recompose these S/G entries into one
12985		 * contiguous list before passing it to the
12986		 */
12987		for (sg_entries_sent = 0; sg_entries_sent <
12988		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12989			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12990				sizeof(msg.dt.sg_list[0])),
12991				msg.dt.kern_sg_entries - sg_entries_sent);
12992
12993			if (do_sg_copy != 0) {
12994				struct ctl_sg_entry *sgl;
12995				int j;
12996
12997				sgl = (struct ctl_sg_entry *)
12998					io->scsiio.kern_data_ptr;
12999				/*
13000				 * If this is in cached memory, flush the cache
13001				 * before we send the DMA request to the other
13002				 * controller.  We want to do this in either
13003				 * the * read or the write case.  The read
13004				 * case is straightforward.  In the write
13005				 * case, we want to make sure nothing is
13006				 * in the local cache that could overwrite
13007				 * the DMAed data.
13008				 */
13009
13010				for (i = sg_entries_sent, j = 0;
13011				     i < msg.dt.cur_sg_entries; i++, j++) {
13012					if ((io->io_hdr.flags &
13013					     CTL_FLAG_NO_DATASYNC) == 0) {
13014						/*
13015						 * XXX KDM use bus_dmamap_sync()
13016						 */
13017					}
13018					if ((io->io_hdr.flags &
13019					     CTL_FLAG_BUS_ADDR) == 0) {
13020						/*
13021						 * XXX KDM use busdma.
13022						 */
13023#if 0
13024						msg.dt.sg_list[j].addr =(void *)
13025						       vtophys(sgl[i].addr);
13026#endif
13027					} else {
13028						msg.dt.sg_list[j].addr =
13029							sgl[i].addr;
13030					}
13031					msg.dt.sg_list[j].len = sgl[i].len;
13032				}
13033			}
13034
13035			sg_entries_sent += msg.dt.cur_sg_entries;
13036			if (sg_entries_sent >= msg.dt.kern_sg_entries)
13037				msg.dt.sg_last = 1;
13038			else
13039				msg.dt.sg_last = 0;
13040
13041			/*
13042			 * XXX KDM drop and reacquire the lock here?
13043			 */
13044			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13045			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13046				/*
13047				 * XXX do something here.
13048				 */
13049			}
13050
13051			msg.dt.sent_sg_entries = sg_entries_sent;
13052		}
13053		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13054		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
13055			ctl_failover_io(io, /*have_lock*/ 0);
13056
13057	} else {
13058
13059		/*
13060		 * Lookup the fe_datamove() function for this particular
13061		 * front end.
13062		 */
13063		fe_datamove =
13064		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13065
13066		fe_datamove(io);
13067	}
13068}
13069
13070static void
13071ctl_send_datamove_done(union ctl_io *io, int have_lock)
13072{
13073	union ctl_ha_msg msg;
13074	int isc_status;
13075
13076	memset(&msg, 0, sizeof(msg));
13077
13078	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
13079	msg.hdr.original_sc = io;
13080	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13081	msg.hdr.nexus = io->io_hdr.nexus;
13082	msg.hdr.status = io->io_hdr.status;
13083	msg.scsi.tag_num = io->scsiio.tag_num;
13084	msg.scsi.tag_type = io->scsiio.tag_type;
13085	msg.scsi.scsi_status = io->scsiio.scsi_status;
13086	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13087	       sizeof(io->scsiio.sense_data));
13088	msg.scsi.sense_len = io->scsiio.sense_len;
13089	msg.scsi.sense_residual = io->scsiio.sense_residual;
13090	msg.scsi.fetd_status = io->io_hdr.port_status;
13091	msg.scsi.residual = io->scsiio.residual;
13092	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13093
13094	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13095		ctl_failover_io(io, /*have_lock*/ have_lock);
13096		return;
13097	}
13098
13099	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
13100	if (isc_status > CTL_HA_STATUS_SUCCESS) {
13101		/* XXX do something if this fails */
13102	}
13103
13104}
13105
13106/*
13107 * The DMA to the remote side is done, now we need to tell the other side
13108 * we're done so it can continue with its data movement.
13109 */
13110static void
13111ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
13112{
13113	union ctl_io *io;
13114
13115	io = rq->context;
13116
13117	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13118		printf("%s: ISC DMA write failed with error %d", __func__,
13119		       rq->ret);
13120		ctl_set_internal_failure(&io->scsiio,
13121					 /*sks_valid*/ 1,
13122					 /*retry_count*/ rq->ret);
13123	}
13124
13125	ctl_dt_req_free(rq);
13126
13127	/*
13128	 * In this case, we had to malloc the memory locally.  Free it.
13129	 */
13130	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13131		int i;
13132		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13133			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13134	}
13135	/*
13136	 * The data is in local and remote memory, so now we need to send
13137	 * status (good or back) back to the other side.
13138	 */
13139	ctl_send_datamove_done(io, /*have_lock*/ 0);
13140}
13141
13142/*
13143 * We've moved the data from the host/controller into local memory.  Now we
13144 * need to push it over to the remote controller's memory.
13145 */
13146static int
13147ctl_datamove_remote_dm_write_cb(union ctl_io *io)
13148{
13149	int retval;
13150
13151	retval = 0;
13152
13153	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
13154					  ctl_datamove_remote_write_cb);
13155
13156	return (retval);
13157}
13158
13159static void
13160ctl_datamove_remote_write(union ctl_io *io)
13161{
13162	int retval;
13163	void (*fe_datamove)(union ctl_io *io);
13164
13165	/*
13166	 * - Get the data from the host/HBA into local memory.
13167	 * - DMA memory from the local controller to the remote controller.
13168	 * - Send status back to the remote controller.
13169	 */
13170
13171	retval = ctl_datamove_remote_sgl_setup(io);
13172	if (retval != 0)
13173		return;
13174
13175	/* Switch the pointer over so the FETD knows what to do */
13176	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13177
13178	/*
13179	 * Use a custom move done callback, since we need to send completion
13180	 * back to the other controller, not to the backend on this side.
13181	 */
13182	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
13183
13184	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13185
13186	fe_datamove(io);
13187
13188	return;
13189
13190}
13191
13192static int
13193ctl_datamove_remote_dm_read_cb(union ctl_io *io)
13194{
13195#if 0
13196	char str[256];
13197	char path_str[64];
13198	struct sbuf sb;
13199#endif
13200
13201	/*
13202	 * In this case, we had to malloc the memory locally.  Free it.
13203	 */
13204	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13205		int i;
13206		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13207			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13208	}
13209
13210#if 0
13211	scsi_path_string(io, path_str, sizeof(path_str));
13212	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13213	sbuf_cat(&sb, path_str);
13214	scsi_command_string(&io->scsiio, NULL, &sb);
13215	sbuf_printf(&sb, "\n");
13216	sbuf_cat(&sb, path_str);
13217	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13218		    io->scsiio.tag_num, io->scsiio.tag_type);
13219	sbuf_cat(&sb, path_str);
13220	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
13221		    io->io_hdr.flags, io->io_hdr.status);
13222	sbuf_finish(&sb);
13223	printk("%s", sbuf_data(&sb));
13224#endif
13225
13226
13227	/*
13228	 * The read is done, now we need to send status (good or bad) back
13229	 * to the other side.
13230	 */
13231	ctl_send_datamove_done(io, /*have_lock*/ 0);
13232
13233	return (0);
13234}
13235
13236static void
13237ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
13238{
13239	union ctl_io *io;
13240	void (*fe_datamove)(union ctl_io *io);
13241
13242	io = rq->context;
13243
13244	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13245		printf("%s: ISC DMA read failed with error %d", __func__,
13246		       rq->ret);
13247		ctl_set_internal_failure(&io->scsiio,
13248					 /*sks_valid*/ 1,
13249					 /*retry_count*/ rq->ret);
13250	}
13251
13252	ctl_dt_req_free(rq);
13253
13254	/* Switch the pointer over so the FETD knows what to do */
13255	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13256
13257	/*
13258	 * Use a custom move done callback, since we need to send completion
13259	 * back to the other controller, not to the backend on this side.
13260	 */
13261	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
13262
13263	/* XXX KDM add checks like the ones in ctl_datamove? */
13264
13265	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13266
13267	fe_datamove(io);
13268}
13269
13270static int
13271ctl_datamove_remote_sgl_setup(union ctl_io *io)
13272{
13273	struct ctl_sg_entry *local_sglist, *remote_sglist;
13274	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13275	struct ctl_softc *softc;
13276	int retval;
13277	int i;
13278
13279	retval = 0;
13280	softc = control_softc;
13281
13282	local_sglist = io->io_hdr.local_sglist;
13283	local_dma_sglist = io->io_hdr.local_dma_sglist;
13284	remote_sglist = io->io_hdr.remote_sglist;
13285	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13286
13287	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13288		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13289			local_sglist[i].len = remote_sglist[i].len;
13290
13291			/*
13292			 * XXX Detect the situation where the RS-level I/O
13293			 * redirector on the other side has already read the
13294			 * data off of the AOR RS on this side, and
13295			 * transferred it to remote (mirror) memory on the
13296			 * other side.  Since we already have the data in
13297			 * memory here, we just need to use it.
13298			 *
13299			 * XXX KDM this can probably be removed once we
13300			 * get the cache device code in and take the
13301			 * current AOR implementation out.
13302			 */
13303#ifdef NEEDTOPORT
13304			if ((remote_sglist[i].addr >=
13305			     (void *)vtophys(softc->mirr->addr))
13306			 && (remote_sglist[i].addr <
13307			     ((void *)vtophys(softc->mirr->addr) +
13308			     CacheMirrorOffset))) {
13309				local_sglist[i].addr = remote_sglist[i].addr -
13310					CacheMirrorOffset;
13311				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13312				     CTL_FLAG_DATA_IN)
13313					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13314			} else {
13315				local_sglist[i].addr = remote_sglist[i].addr +
13316					CacheMirrorOffset;
13317			}
13318#endif
13319#if 0
13320			printf("%s: local %p, remote %p, len %d\n",
13321			       __func__, local_sglist[i].addr,
13322			       remote_sglist[i].addr, local_sglist[i].len);
13323#endif
13324		}
13325	} else {
13326		uint32_t len_to_go;
13327
13328		/*
13329		 * In this case, we don't have automatically allocated
13330		 * memory for this I/O on this controller.  This typically
13331		 * happens with internal CTL I/O -- e.g. inquiry, mode
13332		 * sense, etc.  Anything coming from RAIDCore will have
13333		 * a mirror area available.
13334		 */
13335		len_to_go = io->scsiio.kern_data_len;
13336
13337		/*
13338		 * Clear the no datasync flag, we have to use malloced
13339		 * buffers.
13340		 */
13341		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13342
13343		/*
13344		 * The difficult thing here is that the size of the various
13345		 * S/G segments may be different than the size from the
13346		 * remote controller.  That'll make it harder when DMAing
13347		 * the data back to the other side.
13348		 */
13349		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13350		     sizeof(io->io_hdr.remote_sglist[0])) &&
13351		     (len_to_go > 0); i++) {
13352			local_sglist[i].len = ctl_min(len_to_go, 131072);
13353			CTL_SIZE_8B(local_dma_sglist[i].len,
13354				    local_sglist[i].len);
13355			local_sglist[i].addr =
13356				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13357
13358			local_dma_sglist[i].addr = local_sglist[i].addr;
13359
13360			if (local_sglist[i].addr == NULL) {
13361				int j;
13362
13363				printf("malloc failed for %zd bytes!",
13364				       local_dma_sglist[i].len);
13365				for (j = 0; j < i; j++) {
13366					free(local_sglist[j].addr, M_CTL);
13367				}
13368				ctl_set_internal_failure(&io->scsiio,
13369							 /*sks_valid*/ 1,
13370							 /*retry_count*/ 4857);
13371				retval = 1;
13372				goto bailout_error;
13373
13374			}
13375			/* XXX KDM do we need a sync here? */
13376
13377			len_to_go -= local_sglist[i].len;
13378		}
13379		/*
13380		 * Reset the number of S/G entries accordingly.  The
13381		 * original number of S/G entries is available in
13382		 * rem_sg_entries.
13383		 */
13384		io->scsiio.kern_sg_entries = i;
13385
13386#if 0
13387		printf("%s: kern_sg_entries = %d\n", __func__,
13388		       io->scsiio.kern_sg_entries);
13389		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13390			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13391			       local_sglist[i].addr, local_sglist[i].len,
13392			       local_dma_sglist[i].len);
13393#endif
13394	}
13395
13396
13397	return (retval);
13398
13399bailout_error:
13400
13401	ctl_send_datamove_done(io, /*have_lock*/ 0);
13402
13403	return (retval);
13404}
13405
13406static int
13407ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13408			 ctl_ha_dt_cb callback)
13409{
13410	struct ctl_ha_dt_req *rq;
13411	struct ctl_sg_entry *remote_sglist, *local_sglist;
13412	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13413	uint32_t local_used, remote_used, total_used;
13414	int retval;
13415	int i, j;
13416
13417	retval = 0;
13418
13419	rq = ctl_dt_req_alloc();
13420
13421	/*
13422	 * If we failed to allocate the request, and if the DMA didn't fail
13423	 * anyway, set busy status.  This is just a resource allocation
13424	 * failure.
13425	 */
13426	if ((rq == NULL)
13427	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13428		ctl_set_busy(&io->scsiio);
13429
13430	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13431
13432		if (rq != NULL)
13433			ctl_dt_req_free(rq);
13434
13435		/*
13436		 * The data move failed.  We need to return status back
13437		 * to the other controller.  No point in trying to DMA
13438		 * data to the remote controller.
13439		 */
13440
13441		ctl_send_datamove_done(io, /*have_lock*/ 0);
13442
13443		retval = 1;
13444
13445		goto bailout;
13446	}
13447
13448	local_sglist = io->io_hdr.local_sglist;
13449	local_dma_sglist = io->io_hdr.local_dma_sglist;
13450	remote_sglist = io->io_hdr.remote_sglist;
13451	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13452	local_used = 0;
13453	remote_used = 0;
13454	total_used = 0;
13455
13456	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13457		rq->ret = CTL_HA_STATUS_SUCCESS;
13458		rq->context = io;
13459		callback(rq);
13460		goto bailout;
13461	}
13462
13463	/*
13464	 * Pull/push the data over the wire from/to the other controller.
13465	 * This takes into account the possibility that the local and
13466	 * remote sglists may not be identical in terms of the size of
13467	 * the elements and the number of elements.
13468	 *
13469	 * One fundamental assumption here is that the length allocated for
13470	 * both the local and remote sglists is identical.  Otherwise, we've
13471	 * essentially got a coding error of some sort.
13472	 */
13473	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13474		int isc_ret;
13475		uint32_t cur_len, dma_length;
13476		uint8_t *tmp_ptr;
13477
13478		rq->id = CTL_HA_DATA_CTL;
13479		rq->command = command;
13480		rq->context = io;
13481
13482		/*
13483		 * Both pointers should be aligned.  But it is possible
13484		 * that the allocation length is not.  They should both
13485		 * also have enough slack left over at the end, though,
13486		 * to round up to the next 8 byte boundary.
13487		 */
13488		cur_len = ctl_min(local_sglist[i].len - local_used,
13489				  remote_sglist[j].len - remote_used);
13490
13491		/*
13492		 * In this case, we have a size issue and need to decrease
13493		 * the size, except in the case where we actually have less
13494		 * than 8 bytes left.  In that case, we need to increase
13495		 * the DMA length to get the last bit.
13496		 */
13497		if ((cur_len & 0x7) != 0) {
13498			if (cur_len > 0x7) {
13499				cur_len = cur_len - (cur_len & 0x7);
13500				dma_length = cur_len;
13501			} else {
13502				CTL_SIZE_8B(dma_length, cur_len);
13503			}
13504
13505		} else
13506			dma_length = cur_len;
13507
13508		/*
13509		 * If we had to allocate memory for this I/O, instead of using
13510		 * the non-cached mirror memory, we'll need to flush the cache
13511		 * before trying to DMA to the other controller.
13512		 *
13513		 * We could end up doing this multiple times for the same
13514		 * segment if we have a larger local segment than remote
13515		 * segment.  That shouldn't be an issue.
13516		 */
13517		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13518			/*
13519			 * XXX KDM use bus_dmamap_sync() here.
13520			 */
13521		}
13522
13523		rq->size = dma_length;
13524
13525		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13526		tmp_ptr += local_used;
13527
13528		/* Use physical addresses when talking to ISC hardware */
13529		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13530			/* XXX KDM use busdma */
13531#if 0
13532			rq->local = vtophys(tmp_ptr);
13533#endif
13534		} else
13535			rq->local = tmp_ptr;
13536
13537		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13538		tmp_ptr += remote_used;
13539		rq->remote = tmp_ptr;
13540
13541		rq->callback = NULL;
13542
13543		local_used += cur_len;
13544		if (local_used >= local_sglist[i].len) {
13545			i++;
13546			local_used = 0;
13547		}
13548
13549		remote_used += cur_len;
13550		if (remote_used >= remote_sglist[j].len) {
13551			j++;
13552			remote_used = 0;
13553		}
13554		total_used += cur_len;
13555
13556		if (total_used >= io->scsiio.kern_data_len)
13557			rq->callback = callback;
13558
13559		if ((rq->size & 0x7) != 0) {
13560			printf("%s: warning: size %d is not on 8b boundary\n",
13561			       __func__, rq->size);
13562		}
13563		if (((uintptr_t)rq->local & 0x7) != 0) {
13564			printf("%s: warning: local %p not on 8b boundary\n",
13565			       __func__, rq->local);
13566		}
13567		if (((uintptr_t)rq->remote & 0x7) != 0) {
13568			printf("%s: warning: remote %p not on 8b boundary\n",
13569			       __func__, rq->local);
13570		}
13571#if 0
13572		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13573		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13574		       rq->local, rq->remote, rq->size);
13575#endif
13576
13577		isc_ret = ctl_dt_single(rq);
13578		if (isc_ret == CTL_HA_STATUS_WAIT)
13579			continue;
13580
13581		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13582			rq->ret = CTL_HA_STATUS_SUCCESS;
13583		} else {
13584			rq->ret = isc_ret;
13585		}
13586		callback(rq);
13587		goto bailout;
13588	}
13589
13590bailout:
13591	return (retval);
13592
13593}
13594
13595static void
13596ctl_datamove_remote_read(union ctl_io *io)
13597{
13598	int retval;
13599	int i;
13600
13601	/*
13602	 * This will send an error to the other controller in the case of a
13603	 * failure.
13604	 */
13605	retval = ctl_datamove_remote_sgl_setup(io);
13606	if (retval != 0)
13607		return;
13608
13609	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13610					  ctl_datamove_remote_read_cb);
13611	if ((retval != 0)
13612	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13613		/*
13614		 * Make sure we free memory if there was an error..  The
13615		 * ctl_datamove_remote_xfer() function will send the
13616		 * datamove done message, or call the callback with an
13617		 * error if there is a problem.
13618		 */
13619		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13620			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13621	}
13622
13623	return;
13624}
13625
13626/*
13627 * Process a datamove request from the other controller.  This is used for
13628 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13629 * first.  Once that is complete, the data gets DMAed into the remote
13630 * controller's memory.  For reads, we DMA from the remote controller's
13631 * memory into our memory first, and then move it out to the FETD.
13632 */
13633static void
13634ctl_datamove_remote(union ctl_io *io)
13635{
13636	struct ctl_softc *softc;
13637
13638	softc = control_softc;
13639
13640	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13641
13642	/*
13643	 * Note that we look for an aborted I/O here, but don't do some of
13644	 * the other checks that ctl_datamove() normally does.
13645	 * We don't need to run the datamove delay code, since that should
13646	 * have been done if need be on the other controller.
13647	 */
13648	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13649		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13650		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13651		       io->io_hdr.nexus.targ_port,
13652		       io->io_hdr.nexus.targ_target.id,
13653		       io->io_hdr.nexus.targ_lun);
13654		io->io_hdr.port_status = 31338;
13655		ctl_send_datamove_done(io, /*have_lock*/ 0);
13656		return;
13657	}
13658
13659	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13660		ctl_datamove_remote_write(io);
13661	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13662		ctl_datamove_remote_read(io);
13663	} else {
13664		union ctl_ha_msg msg;
13665		struct scsi_sense_data *sense;
13666		uint8_t sks[3];
13667		int retry_count;
13668
13669		memset(&msg, 0, sizeof(msg));
13670
13671		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13672		msg.hdr.status = CTL_SCSI_ERROR;
13673		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13674
13675		retry_count = 4243;
13676
13677		sense = &msg.scsi.sense_data;
13678		sks[0] = SSD_SCS_VALID;
13679		sks[1] = (retry_count >> 8) & 0xff;
13680		sks[2] = retry_count & 0xff;
13681
13682		/* "Internal target failure" */
13683		scsi_set_sense_data(sense,
13684				    /*sense_format*/ SSD_TYPE_NONE,
13685				    /*current_error*/ 1,
13686				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13687				    /*asc*/ 0x44,
13688				    /*ascq*/ 0x00,
13689				    /*type*/ SSD_ELEM_SKS,
13690				    /*size*/ sizeof(sks),
13691				    /*data*/ sks,
13692				    SSD_ELEM_NONE);
13693
13694		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13695		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13696			ctl_failover_io(io, /*have_lock*/ 1);
13697			return;
13698		}
13699
13700		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13701		    CTL_HA_STATUS_SUCCESS) {
13702			/* XXX KDM what to do if this fails? */
13703		}
13704		return;
13705	}
13706
13707}
13708
13709static int
13710ctl_process_done(union ctl_io *io)
13711{
13712	struct ctl_lun *lun;
13713	struct ctl_softc *ctl_softc;
13714	void (*fe_done)(union ctl_io *io);
13715	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13716
13717	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13718
13719	fe_done =
13720	    control_softc->ctl_ports[targ_port]->fe_done;
13721
13722#ifdef CTL_TIME_IO
13723	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13724		char str[256];
13725		char path_str[64];
13726		struct sbuf sb;
13727
13728		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13729		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13730
13731		sbuf_cat(&sb, path_str);
13732		switch (io->io_hdr.io_type) {
13733		case CTL_IO_SCSI:
13734			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13735			sbuf_printf(&sb, "\n");
13736			sbuf_cat(&sb, path_str);
13737			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13738				    io->scsiio.tag_num, io->scsiio.tag_type);
13739			break;
13740		case CTL_IO_TASK:
13741			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13742				    "Tag Type: %d\n", io->taskio.task_action,
13743				    io->taskio.tag_num, io->taskio.tag_type);
13744			break;
13745		default:
13746			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13747			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13748			break;
13749		}
13750		sbuf_cat(&sb, path_str);
13751		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13752			    (intmax_t)time_uptime - io->io_hdr.start_time);
13753		sbuf_finish(&sb);
13754		printf("%s", sbuf_data(&sb));
13755	}
13756#endif /* CTL_TIME_IO */
13757
13758	switch (io->io_hdr.io_type) {
13759	case CTL_IO_SCSI:
13760		break;
13761	case CTL_IO_TASK:
13762		if (bootverbose || (ctl_debug & CTL_DEBUG_INFO))
13763			ctl_io_error_print(io, NULL);
13764		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13765			ctl_free_io(io);
13766		else
13767			fe_done(io);
13768		return (CTL_RETVAL_COMPLETE);
13769	default:
13770		panic("ctl_process_done: invalid io type %d\n",
13771		      io->io_hdr.io_type);
13772		break; /* NOTREACHED */
13773	}
13774
13775	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13776	if (lun == NULL) {
13777		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13778				 io->io_hdr.nexus.targ_mapped_lun));
13779		fe_done(io);
13780		goto bailout;
13781	}
13782	ctl_softc = lun->ctl_softc;
13783
13784	mtx_lock(&lun->lun_lock);
13785
13786	/*
13787	 * Check to see if we have any errors to inject here.  We only
13788	 * inject errors for commands that don't already have errors set.
13789	 */
13790	if ((STAILQ_FIRST(&lun->error_list) != NULL)
13791	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
13792		ctl_inject_error(lun, io);
13793
13794	/*
13795	 * XXX KDM how do we treat commands that aren't completed
13796	 * successfully?
13797	 *
13798	 * XXX KDM should we also track I/O latency?
13799	 */
13800	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13801	    io->io_hdr.io_type == CTL_IO_SCSI) {
13802#ifdef CTL_TIME_IO
13803		struct bintime cur_bt;
13804#endif
13805		int type;
13806
13807		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13808		    CTL_FLAG_DATA_IN)
13809			type = CTL_STATS_READ;
13810		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13811		    CTL_FLAG_DATA_OUT)
13812			type = CTL_STATS_WRITE;
13813		else
13814			type = CTL_STATS_NO_IO;
13815
13816		lun->stats.ports[targ_port].bytes[type] +=
13817		    io->scsiio.kern_total_len;
13818		lun->stats.ports[targ_port].operations[type]++;
13819#ifdef CTL_TIME_IO
13820		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13821		   &io->io_hdr.dma_bt);
13822		lun->stats.ports[targ_port].num_dmas[type] +=
13823		    io->io_hdr.num_dmas;
13824		getbintime(&cur_bt);
13825		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13826		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13827#endif
13828	}
13829
13830	/*
13831	 * Remove this from the OOA queue.
13832	 */
13833	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13834
13835	/*
13836	 * Run through the blocked queue on this LUN and see if anything
13837	 * has become unblocked, now that this transaction is done.
13838	 */
13839	ctl_check_blocked(lun);
13840
13841	/*
13842	 * If the LUN has been invalidated, free it if there is nothing
13843	 * left on its OOA queue.
13844	 */
13845	if ((lun->flags & CTL_LUN_INVALID)
13846	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13847		mtx_unlock(&lun->lun_lock);
13848		mtx_lock(&ctl_softc->ctl_lock);
13849		ctl_free_lun(lun);
13850		mtx_unlock(&ctl_softc->ctl_lock);
13851	} else
13852		mtx_unlock(&lun->lun_lock);
13853
13854	/*
13855	 * If this command has been aborted, make sure we set the status
13856	 * properly.  The FETD is responsible for freeing the I/O and doing
13857	 * whatever it needs to do to clean up its state.
13858	 */
13859	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13860		ctl_set_task_aborted(&io->scsiio);
13861
13862	/*
13863	 * If enabled, print command error status.
13864	 * We don't print UAs unless debugging was enabled explicitly.
13865	 */
13866	do {
13867		if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)
13868			break;
13869		if (!bootverbose && (ctl_debug & CTL_DEBUG_INFO) == 0)
13870			break;
13871		if ((ctl_debug & CTL_DEBUG_INFO) == 0 &&
13872		    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR) &&
13873		     (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13874			int error_code, sense_key, asc, ascq;
13875
13876			scsi_extract_sense_len(&io->scsiio.sense_data,
13877			    io->scsiio.sense_len, &error_code, &sense_key,
13878			    &asc, &ascq, /*show_errors*/ 0);
13879			if (sense_key == SSD_KEY_UNIT_ATTENTION)
13880				break;
13881		}
13882
13883		ctl_io_error_print(io, NULL);
13884	} while (0);
13885
13886	/*
13887	 * Tell the FETD or the other shelf controller we're done with this
13888	 * command.  Note that only SCSI commands get to this point.  Task
13889	 * management commands are completed above.
13890	 *
13891	 * We only send status to the other controller if we're in XFER
13892	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13893	 * received the I/O (from CTL's perspective), and so the status is
13894	 * generated there.
13895	 *
13896	 * XXX KDM if we hold the lock here, we could cause a deadlock
13897	 * if the frontend comes back in in this context to queue
13898	 * something.
13899	 */
13900	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13901	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13902		union ctl_ha_msg msg;
13903
13904		memset(&msg, 0, sizeof(msg));
13905		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13906		msg.hdr.original_sc = io->io_hdr.original_sc;
13907		msg.hdr.nexus = io->io_hdr.nexus;
13908		msg.hdr.status = io->io_hdr.status;
13909		msg.scsi.scsi_status = io->scsiio.scsi_status;
13910		msg.scsi.tag_num = io->scsiio.tag_num;
13911		msg.scsi.tag_type = io->scsiio.tag_type;
13912		msg.scsi.sense_len = io->scsiio.sense_len;
13913		msg.scsi.sense_residual = io->scsiio.sense_residual;
13914		msg.scsi.residual = io->scsiio.residual;
13915		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13916		       sizeof(io->scsiio.sense_data));
13917		/*
13918		 * We copy this whether or not this is an I/O-related
13919		 * command.  Otherwise, we'd have to go and check to see
13920		 * whether it's a read/write command, and it really isn't
13921		 * worth it.
13922		 */
13923		memcpy(&msg.scsi.lbalen,
13924		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13925		       sizeof(msg.scsi.lbalen));
13926
13927		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13928				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13929			/* XXX do something here */
13930		}
13931
13932		ctl_free_io(io);
13933	} else
13934		fe_done(io);
13935
13936bailout:
13937
13938	return (CTL_RETVAL_COMPLETE);
13939}
13940
13941#ifdef CTL_WITH_CA
13942/*
13943 * Front end should call this if it doesn't do autosense.  When the request
13944 * sense comes back in from the initiator, we'll dequeue this and send it.
13945 */
13946int
13947ctl_queue_sense(union ctl_io *io)
13948{
13949	struct ctl_lun *lun;
13950	struct ctl_softc *ctl_softc;
13951	uint32_t initidx, targ_lun;
13952
13953	ctl_softc = control_softc;
13954
13955	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13956
13957	/*
13958	 * LUN lookup will likely move to the ctl_work_thread() once we
13959	 * have our new queueing infrastructure (that doesn't put things on
13960	 * a per-LUN queue initially).  That is so that we can handle
13961	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13962	 * can't deal with that right now.
13963	 */
13964	mtx_lock(&ctl_softc->ctl_lock);
13965
13966	/*
13967	 * If we don't have a LUN for this, just toss the sense
13968	 * information.
13969	 */
13970	targ_lun = io->io_hdr.nexus.targ_lun;
13971	targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13972	if ((targ_lun < CTL_MAX_LUNS)
13973	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
13974		lun = ctl_softc->ctl_luns[targ_lun];
13975	else
13976		goto bailout;
13977
13978	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13979
13980	mtx_lock(&lun->lun_lock);
13981	/*
13982	 * Already have CA set for this LUN...toss the sense information.
13983	 */
13984	if (ctl_is_set(lun->have_ca, initidx)) {
13985		mtx_unlock(&lun->lun_lock);
13986		goto bailout;
13987	}
13988
13989	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13990	       ctl_min(sizeof(lun->pending_sense[initidx]),
13991	       sizeof(io->scsiio.sense_data)));
13992	ctl_set_mask(lun->have_ca, initidx);
13993	mtx_unlock(&lun->lun_lock);
13994
13995bailout:
13996	mtx_unlock(&ctl_softc->ctl_lock);
13997
13998	ctl_free_io(io);
13999
14000	return (CTL_RETVAL_COMPLETE);
14001}
14002#endif
14003
14004/*
14005 * Primary command inlet from frontend ports.  All SCSI and task I/O
14006 * requests must go through this function.
14007 */
14008int
14009ctl_queue(union ctl_io *io)
14010{
14011	struct ctl_softc *ctl_softc;
14012
14013	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
14014
14015	ctl_softc = control_softc;
14016
14017#ifdef CTL_TIME_IO
14018	io->io_hdr.start_time = time_uptime;
14019	getbintime(&io->io_hdr.start_bt);
14020#endif /* CTL_TIME_IO */
14021
14022	/* Map FE-specific LUN ID into global one. */
14023	io->io_hdr.nexus.targ_mapped_lun =
14024	    ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
14025
14026	switch (io->io_hdr.io_type) {
14027	case CTL_IO_SCSI:
14028	case CTL_IO_TASK:
14029		if (ctl_debug & CTL_DEBUG_CDB)
14030			ctl_io_print(io);
14031		ctl_enqueue_incoming(io);
14032		break;
14033	default:
14034		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
14035		return (EINVAL);
14036	}
14037
14038	return (CTL_RETVAL_COMPLETE);
14039}
14040
14041#ifdef CTL_IO_DELAY
14042static void
14043ctl_done_timer_wakeup(void *arg)
14044{
14045	union ctl_io *io;
14046
14047	io = (union ctl_io *)arg;
14048	ctl_done(io);
14049}
14050#endif /* CTL_IO_DELAY */
14051
14052void
14053ctl_done(union ctl_io *io)
14054{
14055	struct ctl_softc *ctl_softc;
14056
14057	ctl_softc = control_softc;
14058
14059	/*
14060	 * Enable this to catch duplicate completion issues.
14061	 */
14062#if 0
14063	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
14064		printf("%s: type %d msg %d cdb %x iptl: "
14065		       "%d:%d:%d:%d tag 0x%04x "
14066		       "flag %#x status %x\n",
14067			__func__,
14068			io->io_hdr.io_type,
14069			io->io_hdr.msg_type,
14070			io->scsiio.cdb[0],
14071			io->io_hdr.nexus.initid.id,
14072			io->io_hdr.nexus.targ_port,
14073			io->io_hdr.nexus.targ_target.id,
14074			io->io_hdr.nexus.targ_lun,
14075			(io->io_hdr.io_type ==
14076			CTL_IO_TASK) ?
14077			io->taskio.tag_num :
14078			io->scsiio.tag_num,
14079		        io->io_hdr.flags,
14080			io->io_hdr.status);
14081	} else
14082		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
14083#endif
14084
14085	/*
14086	 * This is an internal copy of an I/O, and should not go through
14087	 * the normal done processing logic.
14088	 */
14089	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
14090		return;
14091
14092	/*
14093	 * We need to send a msg to the serializing shelf to finish the IO
14094	 * as well.  We don't send a finish message to the other shelf if
14095	 * this is a task management command.  Task management commands
14096	 * aren't serialized in the OOA queue, but rather just executed on
14097	 * both shelf controllers for commands that originated on that
14098	 * controller.
14099	 */
14100	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
14101	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
14102		union ctl_ha_msg msg_io;
14103
14104		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
14105		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
14106		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
14107		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
14108		}
14109		/* continue on to finish IO */
14110	}
14111#ifdef CTL_IO_DELAY
14112	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
14113		struct ctl_lun *lun;
14114
14115		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14116
14117		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
14118	} else {
14119		struct ctl_lun *lun;
14120
14121		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14122
14123		if ((lun != NULL)
14124		 && (lun->delay_info.done_delay > 0)) {
14125			struct callout *callout;
14126
14127			callout = (struct callout *)&io->io_hdr.timer_bytes;
14128			callout_init(callout, /*mpsafe*/ 1);
14129			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
14130			callout_reset(callout,
14131				      lun->delay_info.done_delay * hz,
14132				      ctl_done_timer_wakeup, io);
14133			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
14134				lun->delay_info.done_delay = 0;
14135			return;
14136		}
14137	}
14138#endif /* CTL_IO_DELAY */
14139
14140	ctl_enqueue_done(io);
14141}
14142
14143int
14144ctl_isc(struct ctl_scsiio *ctsio)
14145{
14146	struct ctl_lun *lun;
14147	int retval;
14148
14149	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14150
14151	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
14152
14153	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
14154
14155	retval = lun->backend->data_submit((union ctl_io *)ctsio);
14156
14157	return (retval);
14158}
14159
14160
14161static void
14162ctl_work_thread(void *arg)
14163{
14164	struct ctl_thread *thr = (struct ctl_thread *)arg;
14165	struct ctl_softc *softc = thr->ctl_softc;
14166	union ctl_io *io;
14167	int retval;
14168
14169	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
14170
14171	for (;;) {
14172		retval = 0;
14173
14174		/*
14175		 * We handle the queues in this order:
14176		 * - ISC
14177		 * - done queue (to free up resources, unblock other commands)
14178		 * - RtR queue
14179		 * - incoming queue
14180		 *
14181		 * If those queues are empty, we break out of the loop and
14182		 * go to sleep.
14183		 */
14184		mtx_lock(&thr->queue_lock);
14185		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
14186		if (io != NULL) {
14187			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
14188			mtx_unlock(&thr->queue_lock);
14189			ctl_handle_isc(io);
14190			continue;
14191		}
14192		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
14193		if (io != NULL) {
14194			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
14195			/* clear any blocked commands, call fe_done */
14196			mtx_unlock(&thr->queue_lock);
14197			retval = ctl_process_done(io);
14198			continue;
14199		}
14200		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
14201		if (io != NULL) {
14202			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
14203			mtx_unlock(&thr->queue_lock);
14204			if (io->io_hdr.io_type == CTL_IO_TASK)
14205				ctl_run_task(io);
14206			else
14207				ctl_scsiio_precheck(softc, &io->scsiio);
14208			continue;
14209		}
14210		if (!ctl_pause_rtr) {
14211			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
14212			if (io != NULL) {
14213				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
14214				mtx_unlock(&thr->queue_lock);
14215				retval = ctl_scsiio(&io->scsiio);
14216				if (retval != CTL_RETVAL_COMPLETE)
14217					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
14218				continue;
14219			}
14220		}
14221
14222		/* Sleep until we have something to do. */
14223		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
14224	}
14225}
14226
14227static void
14228ctl_lun_thread(void *arg)
14229{
14230	struct ctl_softc *softc = (struct ctl_softc *)arg;
14231	struct ctl_be_lun *be_lun;
14232	int retval;
14233
14234	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
14235
14236	for (;;) {
14237		retval = 0;
14238		mtx_lock(&softc->ctl_lock);
14239		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
14240		if (be_lun != NULL) {
14241			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
14242			mtx_unlock(&softc->ctl_lock);
14243			ctl_create_lun(be_lun);
14244			continue;
14245		}
14246
14247		/* Sleep until we have something to do. */
14248		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
14249		    PDROP | PRIBIO, "-", 0);
14250	}
14251}
14252
14253static void
14254ctl_thresh_thread(void *arg)
14255{
14256	struct ctl_softc *softc = (struct ctl_softc *)arg;
14257	struct ctl_lun *lun;
14258	struct ctl_be_lun *be_lun;
14259	struct scsi_da_rw_recovery_page *rwpage;
14260	struct ctl_logical_block_provisioning_page *page;
14261	const char *attr;
14262	uint64_t thres, val;
14263	int i, e;
14264
14265	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
14266
14267	for (;;) {
14268		mtx_lock(&softc->ctl_lock);
14269		STAILQ_FOREACH(lun, &softc->lun_list, links) {
14270			be_lun = lun->be_lun;
14271			if ((lun->flags & CTL_LUN_DISABLED) ||
14272			    (lun->flags & CTL_LUN_OFFLINE) ||
14273			    (be_lun->flags & CTL_LUN_FLAG_UNMAP) == 0 ||
14274			    lun->backend->lun_attr == NULL)
14275				continue;
14276			rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
14277			if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
14278				continue;
14279			e = 0;
14280			page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
14281			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
14282				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
14283					continue;
14284				thres = scsi_4btoul(page->descr[i].count);
14285				thres <<= CTL_LBP_EXPONENT;
14286				switch (page->descr[i].resource) {
14287				case 0x01:
14288					attr = "blocksavail";
14289					break;
14290				case 0x02:
14291					attr = "blocksused";
14292					break;
14293				case 0xf1:
14294					attr = "poolblocksavail";
14295					break;
14296				case 0xf2:
14297					attr = "poolblocksused";
14298					break;
14299				default:
14300					continue;
14301				}
14302				mtx_unlock(&softc->ctl_lock); // XXX
14303				val = lun->backend->lun_attr(
14304				    lun->be_lun->be_lun, attr);
14305				mtx_lock(&softc->ctl_lock);
14306				if (val == UINT64_MAX)
14307					continue;
14308				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
14309				    == SLBPPD_ARMING_INC)
14310					e |= (val >= thres);
14311				else
14312					e |= (val <= thres);
14313			}
14314			mtx_lock(&lun->lun_lock);
14315			if (e) {
14316				if (lun->lasttpt == 0 ||
14317				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
14318					lun->lasttpt = time_uptime;
14319					for (i = 0; i < CTL_MAX_INITIATORS; i++)
14320						lun->pending_ua[i] |=
14321						    CTL_UA_THIN_PROV_THRES;
14322				}
14323			} else {
14324				lun->lasttpt = 0;
14325				for (i = 0; i < CTL_MAX_INITIATORS; i++)
14326					lun->pending_ua[i] &= ~CTL_UA_THIN_PROV_THRES;
14327			}
14328			mtx_unlock(&lun->lun_lock);
14329		}
14330		mtx_unlock(&softc->ctl_lock);
14331		pause("-", CTL_LBP_PERIOD * hz);
14332	}
14333}
14334
14335static void
14336ctl_enqueue_incoming(union ctl_io *io)
14337{
14338	struct ctl_softc *softc = control_softc;
14339	struct ctl_thread *thr;
14340	u_int idx;
14341
14342	idx = (io->io_hdr.nexus.targ_port * 127 +
14343	       io->io_hdr.nexus.initid.id) % worker_threads;
14344	thr = &softc->threads[idx];
14345	mtx_lock(&thr->queue_lock);
14346	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14347	mtx_unlock(&thr->queue_lock);
14348	wakeup(thr);
14349}
14350
14351static void
14352ctl_enqueue_rtr(union ctl_io *io)
14353{
14354	struct ctl_softc *softc = control_softc;
14355	struct ctl_thread *thr;
14356
14357	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14358	mtx_lock(&thr->queue_lock);
14359	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14360	mtx_unlock(&thr->queue_lock);
14361	wakeup(thr);
14362}
14363
14364static void
14365ctl_enqueue_done(union ctl_io *io)
14366{
14367	struct ctl_softc *softc = control_softc;
14368	struct ctl_thread *thr;
14369
14370	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14371	mtx_lock(&thr->queue_lock);
14372	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14373	mtx_unlock(&thr->queue_lock);
14374	wakeup(thr);
14375}
14376
14377static void
14378ctl_enqueue_isc(union ctl_io *io)
14379{
14380	struct ctl_softc *softc = control_softc;
14381	struct ctl_thread *thr;
14382
14383	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14384	mtx_lock(&thr->queue_lock);
14385	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14386	mtx_unlock(&thr->queue_lock);
14387	wakeup(thr);
14388}
14389
14390/* Initialization and failover */
14391
14392void
14393ctl_init_isc_msg(void)
14394{
14395	printf("CTL: Still calling this thing\n");
14396}
14397
14398/*
14399 * Init component
14400 * 	Initializes component into configuration defined by bootMode
14401 *	(see hasc-sv.c)
14402 *  	returns hasc_Status:
14403 * 		OK
14404 *		ERROR - fatal error
14405 */
14406static ctl_ha_comp_status
14407ctl_isc_init(struct ctl_ha_component *c)
14408{
14409	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14410
14411	c->status = ret;
14412	return ret;
14413}
14414
14415/* Start component
14416 * 	Starts component in state requested. If component starts successfully,
14417 *	it must set its own state to the requestrd state
14418 *	When requested state is HASC_STATE_HA, the component may refine it
14419 * 	by adding _SLAVE or _MASTER flags.
14420 *	Currently allowed state transitions are:
14421 *	UNKNOWN->HA		- initial startup
14422 *	UNKNOWN->SINGLE - initial startup when no parter detected
14423 *	HA->SINGLE		- failover
14424 * returns ctl_ha_comp_status:
14425 * 		OK	- component successfully started in requested state
14426 *		FAILED  - could not start the requested state, failover may
14427 * 			  be possible
14428 *		ERROR	- fatal error detected, no future startup possible
14429 */
14430static ctl_ha_comp_status
14431ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14432{
14433	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14434
14435	printf("%s: go\n", __func__);
14436
14437	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14438	if (c->state == CTL_HA_STATE_UNKNOWN ) {
14439		control_softc->is_single = 0;
14440		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14441		    != CTL_HA_STATUS_SUCCESS) {
14442			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14443			ret = CTL_HA_COMP_STATUS_ERROR;
14444		}
14445	} else if (CTL_HA_STATE_IS_HA(c->state)
14446		&& CTL_HA_STATE_IS_SINGLE(state)){
14447		// HA->SINGLE transition
14448	        ctl_failover();
14449		control_softc->is_single = 1;
14450	} else {
14451		printf("ctl_isc_start:Invalid state transition %X->%X\n",
14452		       c->state, state);
14453		ret = CTL_HA_COMP_STATUS_ERROR;
14454	}
14455	if (CTL_HA_STATE_IS_SINGLE(state))
14456		control_softc->is_single = 1;
14457
14458	c->state = state;
14459	c->status = ret;
14460	return ret;
14461}
14462
14463/*
14464 * Quiesce component
14465 * The component must clear any error conditions (set status to OK) and
14466 * prepare itself to another Start call
14467 * returns ctl_ha_comp_status:
14468 * 	OK
14469 *	ERROR
14470 */
14471static ctl_ha_comp_status
14472ctl_isc_quiesce(struct ctl_ha_component *c)
14473{
14474	int ret = CTL_HA_COMP_STATUS_OK;
14475
14476	ctl_pause_rtr = 1;
14477	c->status = ret;
14478	return ret;
14479}
14480
14481struct ctl_ha_component ctl_ha_component_ctlisc =
14482{
14483	.name = "CTL ISC",
14484	.state = CTL_HA_STATE_UNKNOWN,
14485	.init = ctl_isc_init,
14486	.start = ctl_isc_start,
14487	.quiesce = ctl_isc_quiesce
14488};
14489
14490/*
14491 *  vim: ts=8
14492 */
14493