ctl.c revision 275878
1/*-
2 * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3 * Copyright (c) 2012 The FreeBSD Foundation
4 * All rights reserved.
5 *
6 * Portions of this software were developed by Edward Tomasz Napierala
7 * under sponsorship from the FreeBSD Foundation.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions, and the following disclaimer,
14 *    without modification.
15 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
16 *    substantially similar to the "NO WARRANTY" disclaimer below
17 *    ("Disclaimer") and any redistribution must be conditioned upon
18 *    including a substantially similar Disclaimer requirement for further
19 *    binary redistribution.
20 *
21 * NO WARRANTY
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
25 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
31 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGES.
33 *
34 * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/ctl.c#8 $
35 */
36/*
37 * CAM Target Layer, a SCSI device emulation subsystem.
38 *
39 * Author: Ken Merry <ken@FreeBSD.org>
40 */
41
42#define _CTL_C
43
44#include <sys/cdefs.h>
45__FBSDID("$FreeBSD: stable/10/sys/cam/ctl/ctl.c 275878 2014-12-18 08:22:16Z mav $");
46
47#include <sys/param.h>
48#include <sys/systm.h>
49#include <sys/ctype.h>
50#include <sys/kernel.h>
51#include <sys/types.h>
52#include <sys/kthread.h>
53#include <sys/bio.h>
54#include <sys/fcntl.h>
55#include <sys/lock.h>
56#include <sys/module.h>
57#include <sys/mutex.h>
58#include <sys/condvar.h>
59#include <sys/malloc.h>
60#include <sys/conf.h>
61#include <sys/ioccom.h>
62#include <sys/queue.h>
63#include <sys/sbuf.h>
64#include <sys/smp.h>
65#include <sys/endian.h>
66#include <sys/sysctl.h>
67#include <vm/uma.h>
68
69#include <cam/cam.h>
70#include <cam/scsi/scsi_all.h>
71#include <cam/scsi/scsi_da.h>
72#include <cam/ctl/ctl_io.h>
73#include <cam/ctl/ctl.h>
74#include <cam/ctl/ctl_frontend.h>
75#include <cam/ctl/ctl_frontend_internal.h>
76#include <cam/ctl/ctl_util.h>
77#include <cam/ctl/ctl_backend.h>
78#include <cam/ctl/ctl_ioctl.h>
79#include <cam/ctl/ctl_ha.h>
80#include <cam/ctl/ctl_private.h>
81#include <cam/ctl/ctl_debug.h>
82#include <cam/ctl/ctl_scsi_all.h>
83#include <cam/ctl/ctl_error.h>
84
85struct ctl_softc *control_softc = NULL;
86
87/*
88 * Size and alignment macros needed for Copan-specific HA hardware.  These
89 * can go away when the HA code is re-written, and uses busdma for any
90 * hardware.
91 */
92#define	CTL_ALIGN_8B(target, source, type)				\
93	if (((uint32_t)source & 0x7) != 0)				\
94		target = (type)(source + (0x8 - ((uint32_t)source & 0x7)));\
95	else								\
96		target = (type)source;
97
98#define	CTL_SIZE_8B(target, size)					\
99	if ((size & 0x7) != 0)						\
100		target = size + (0x8 - (size & 0x7));			\
101	else								\
102		target = size;
103
104#define CTL_ALIGN_8B_MARGIN	16
105
106/*
107 * Template mode pages.
108 */
109
110/*
111 * Note that these are default values only.  The actual values will be
112 * filled in when the user does a mode sense.
113 */
114static struct copan_debugconf_subpage debugconf_page_default = {
115	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
116	DBGCNF_SUBPAGE_CODE,		/* subpage */
117	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
118	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
119	DBGCNF_VERSION,			/* page_version */
120	{CTL_TIME_IO_DEFAULT_SECS>>8,
121	 CTL_TIME_IO_DEFAULT_SECS>>0},	/* ctl_time_io_secs */
122};
123
124static struct copan_debugconf_subpage debugconf_page_changeable = {
125	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
126	DBGCNF_SUBPAGE_CODE,		/* subpage */
127	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
128	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
129	0,				/* page_version */
130	{0xff,0xff},			/* ctl_time_io_secs */
131};
132
133static struct scsi_da_rw_recovery_page rw_er_page_default = {
134	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
135	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
136	/*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
137	/*read_retry_count*/0,
138	/*correction_span*/0,
139	/*head_offset_count*/0,
140	/*data_strobe_offset_cnt*/0,
141	/*byte8*/SMS_RWER_LBPERE,
142	/*write_retry_count*/0,
143	/*reserved2*/0,
144	/*recovery_time_limit*/{0, 0},
145};
146
147static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
148	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
149	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
150	/*byte3*/0,
151	/*read_retry_count*/0,
152	/*correction_span*/0,
153	/*head_offset_count*/0,
154	/*data_strobe_offset_cnt*/0,
155	/*byte8*/0,
156	/*write_retry_count*/0,
157	/*reserved2*/0,
158	/*recovery_time_limit*/{0, 0},
159};
160
161static struct scsi_format_page format_page_default = {
162	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
163	/*page_length*/sizeof(struct scsi_format_page) - 2,
164	/*tracks_per_zone*/ {0, 0},
165	/*alt_sectors_per_zone*/ {0, 0},
166	/*alt_tracks_per_zone*/ {0, 0},
167	/*alt_tracks_per_lun*/ {0, 0},
168	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
169			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
170	/*bytes_per_sector*/ {0, 0},
171	/*interleave*/ {0, 0},
172	/*track_skew*/ {0, 0},
173	/*cylinder_skew*/ {0, 0},
174	/*flags*/ SFP_HSEC,
175	/*reserved*/ {0, 0, 0}
176};
177
178static struct scsi_format_page format_page_changeable = {
179	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
180	/*page_length*/sizeof(struct scsi_format_page) - 2,
181	/*tracks_per_zone*/ {0, 0},
182	/*alt_sectors_per_zone*/ {0, 0},
183	/*alt_tracks_per_zone*/ {0, 0},
184	/*alt_tracks_per_lun*/ {0, 0},
185	/*sectors_per_track*/ {0, 0},
186	/*bytes_per_sector*/ {0, 0},
187	/*interleave*/ {0, 0},
188	/*track_skew*/ {0, 0},
189	/*cylinder_skew*/ {0, 0},
190	/*flags*/ 0,
191	/*reserved*/ {0, 0, 0}
192};
193
194static struct scsi_rigid_disk_page rigid_disk_page_default = {
195	/*page_code*/SMS_RIGID_DISK_PAGE,
196	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
197	/*cylinders*/ {0, 0, 0},
198	/*heads*/ CTL_DEFAULT_HEADS,
199	/*start_write_precomp*/ {0, 0, 0},
200	/*start_reduced_current*/ {0, 0, 0},
201	/*step_rate*/ {0, 0},
202	/*landing_zone_cylinder*/ {0, 0, 0},
203	/*rpl*/ SRDP_RPL_DISABLED,
204	/*rotational_offset*/ 0,
205	/*reserved1*/ 0,
206	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
207			   CTL_DEFAULT_ROTATION_RATE & 0xff},
208	/*reserved2*/ {0, 0}
209};
210
211static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
212	/*page_code*/SMS_RIGID_DISK_PAGE,
213	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
214	/*cylinders*/ {0, 0, 0},
215	/*heads*/ 0,
216	/*start_write_precomp*/ {0, 0, 0},
217	/*start_reduced_current*/ {0, 0, 0},
218	/*step_rate*/ {0, 0},
219	/*landing_zone_cylinder*/ {0, 0, 0},
220	/*rpl*/ 0,
221	/*rotational_offset*/ 0,
222	/*reserved1*/ 0,
223	/*rotation_rate*/ {0, 0},
224	/*reserved2*/ {0, 0}
225};
226
227static struct scsi_caching_page caching_page_default = {
228	/*page_code*/SMS_CACHING_PAGE,
229	/*page_length*/sizeof(struct scsi_caching_page) - 2,
230	/*flags1*/ SCP_DISC | SCP_WCE,
231	/*ret_priority*/ 0,
232	/*disable_pf_transfer_len*/ {0xff, 0xff},
233	/*min_prefetch*/ {0, 0},
234	/*max_prefetch*/ {0xff, 0xff},
235	/*max_pf_ceiling*/ {0xff, 0xff},
236	/*flags2*/ 0,
237	/*cache_segments*/ 0,
238	/*cache_seg_size*/ {0, 0},
239	/*reserved*/ 0,
240	/*non_cache_seg_size*/ {0, 0, 0}
241};
242
243static struct scsi_caching_page caching_page_changeable = {
244	/*page_code*/SMS_CACHING_PAGE,
245	/*page_length*/sizeof(struct scsi_caching_page) - 2,
246	/*flags1*/ SCP_WCE | SCP_RCD,
247	/*ret_priority*/ 0,
248	/*disable_pf_transfer_len*/ {0, 0},
249	/*min_prefetch*/ {0, 0},
250	/*max_prefetch*/ {0, 0},
251	/*max_pf_ceiling*/ {0, 0},
252	/*flags2*/ 0,
253	/*cache_segments*/ 0,
254	/*cache_seg_size*/ {0, 0},
255	/*reserved*/ 0,
256	/*non_cache_seg_size*/ {0, 0, 0}
257};
258
259static struct scsi_control_page control_page_default = {
260	/*page_code*/SMS_CONTROL_MODE_PAGE,
261	/*page_length*/sizeof(struct scsi_control_page) - 2,
262	/*rlec*/0,
263	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
264	/*eca_and_aen*/0,
265	/*flags4*/SCP_TAS,
266	/*aen_holdoff_period*/{0, 0},
267	/*busy_timeout_period*/{0, 0},
268	/*extended_selftest_completion_time*/{0, 0}
269};
270
271static struct scsi_control_page control_page_changeable = {
272	/*page_code*/SMS_CONTROL_MODE_PAGE,
273	/*page_length*/sizeof(struct scsi_control_page) - 2,
274	/*rlec*/SCP_DSENSE,
275	/*queue_flags*/SCP_QUEUE_ALG_MASK,
276	/*eca_and_aen*/SCP_SWP,
277	/*flags4*/0,
278	/*aen_holdoff_period*/{0, 0},
279	/*busy_timeout_period*/{0, 0},
280	/*extended_selftest_completion_time*/{0, 0}
281};
282
283static struct scsi_info_exceptions_page ie_page_default = {
284	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
285	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
286	/*info_flags*/SIEP_FLAGS_DEXCPT,
287	/*mrie*/0,
288	/*interval_timer*/{0, 0, 0, 0},
289	/*report_count*/{0, 0, 0, 0}
290};
291
292static struct scsi_info_exceptions_page ie_page_changeable = {
293	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
294	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
295	/*info_flags*/0,
296	/*mrie*/0,
297	/*interval_timer*/{0, 0, 0, 0},
298	/*report_count*/{0, 0, 0, 0}
299};
300
301#define CTL_LBPM_LEN	(sizeof(struct ctl_logical_block_provisioning_page) - 4)
302
303static struct ctl_logical_block_provisioning_page lbp_page_default = {{
304	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
305	/*subpage_code*/0x02,
306	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
307	/*flags*/0,
308	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
309	/*descr*/{}},
310	{{/*flags*/0,
311	  /*resource*/0x01,
312	  /*reserved*/{0, 0},
313	  /*count*/{0, 0, 0, 0}},
314	 {/*flags*/0,
315	  /*resource*/0x02,
316	  /*reserved*/{0, 0},
317	  /*count*/{0, 0, 0, 0}},
318	 {/*flags*/0,
319	  /*resource*/0xf1,
320	  /*reserved*/{0, 0},
321	  /*count*/{0, 0, 0, 0}},
322	 {/*flags*/0,
323	  /*resource*/0xf2,
324	  /*reserved*/{0, 0},
325	  /*count*/{0, 0, 0, 0}}
326	}
327};
328
329static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
330	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
331	/*subpage_code*/0x02,
332	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
333	/*flags*/0,
334	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
335	/*descr*/{}},
336	{{/*flags*/0,
337	  /*resource*/0,
338	  /*reserved*/{0, 0},
339	  /*count*/{0, 0, 0, 0}},
340	 {/*flags*/0,
341	  /*resource*/0,
342	  /*reserved*/{0, 0},
343	  /*count*/{0, 0, 0, 0}},
344	 {/*flags*/0,
345	  /*resource*/0,
346	  /*reserved*/{0, 0},
347	  /*count*/{0, 0, 0, 0}},
348	 {/*flags*/0,
349	  /*resource*/0,
350	  /*reserved*/{0, 0},
351	  /*count*/{0, 0, 0, 0}}
352	}
353};
354
355/*
356 * XXX KDM move these into the softc.
357 */
358static int rcv_sync_msg;
359static int persis_offset;
360static uint8_t ctl_pause_rtr;
361
362SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
363static int worker_threads = -1;
364TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
365SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
366    &worker_threads, 1, "Number of worker threads");
367static int ctl_debug = CTL_DEBUG_NONE;
368TUNABLE_INT("kern.cam.ctl.debug", &ctl_debug);
369SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
370    &ctl_debug, 0, "Enabled debug flags");
371
372/*
373 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
374 * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
375 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
376 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
377 */
378#define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
379
380static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
381				  int param);
382static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
383static int ctl_init(void);
384void ctl_shutdown(void);
385static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
386static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
387static void ctl_ioctl_online(void *arg);
388static void ctl_ioctl_offline(void *arg);
389static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
390static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
391static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
392static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
393static int ctl_ioctl_submit_wait(union ctl_io *io);
394static void ctl_ioctl_datamove(union ctl_io *io);
395static void ctl_ioctl_done(union ctl_io *io);
396static void ctl_ioctl_hard_startstop_callback(void *arg,
397					      struct cfi_metatask *metatask);
398static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
399static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
400			      struct ctl_ooa *ooa_hdr,
401			      struct ctl_ooa_entry *kern_entries);
402static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
403		     struct thread *td);
404static uint32_t ctl_map_lun(int port_num, uint32_t lun);
405static uint32_t ctl_map_lun_back(int port_num, uint32_t lun);
406#ifdef unused
407static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
408				   uint32_t targ_target, uint32_t targ_lun,
409				   int can_wait);
410static void ctl_kfree_io(union ctl_io *io);
411#endif /* unused */
412static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
413			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
414static int ctl_free_lun(struct ctl_lun *lun);
415static void ctl_create_lun(struct ctl_be_lun *be_lun);
416/**
417static void ctl_failover_change_pages(struct ctl_softc *softc,
418				      struct ctl_scsiio *ctsio, int master);
419**/
420
421static int ctl_do_mode_select(union ctl_io *io);
422static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
423			   uint64_t res_key, uint64_t sa_res_key,
424			   uint8_t type, uint32_t residx,
425			   struct ctl_scsiio *ctsio,
426			   struct scsi_per_res_out *cdb,
427			   struct scsi_per_res_out_parms* param);
428static void ctl_pro_preempt_other(struct ctl_lun *lun,
429				  union ctl_ha_msg *msg);
430static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
431static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
432static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
433static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
434static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
435static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
436static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
437					 int alloc_len);
438static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
439					 int alloc_len);
440static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
441static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
442static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
443static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
444static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
445static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
446static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
447    union ctl_io *pending_io, union ctl_io *ooa_io);
448static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
449				union ctl_io *starting_io);
450static int ctl_check_blocked(struct ctl_lun *lun);
451static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
452				struct ctl_lun *lun,
453				const struct ctl_cmd_entry *entry,
454				struct ctl_scsiio *ctsio);
455//static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
456static void ctl_failover(void);
457static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
458			       struct ctl_scsiio *ctsio);
459static int ctl_scsiio(struct ctl_scsiio *ctsio);
460
461static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
462static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
463			    ctl_ua_type ua_type);
464static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
465			 ctl_ua_type ua_type);
466static int ctl_abort_task(union ctl_io *io);
467static int ctl_abort_task_set(union ctl_io *io);
468static int ctl_i_t_nexus_reset(union ctl_io *io);
469static void ctl_run_task(union ctl_io *io);
470#ifdef CTL_IO_DELAY
471static void ctl_datamove_timer_wakeup(void *arg);
472static void ctl_done_timer_wakeup(void *arg);
473#endif /* CTL_IO_DELAY */
474
475static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
476static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
477static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
478static void ctl_datamove_remote_write(union ctl_io *io);
479static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
480static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
481static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
482static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
483				    ctl_ha_dt_cb callback);
484static void ctl_datamove_remote_read(union ctl_io *io);
485static void ctl_datamove_remote(union ctl_io *io);
486static int ctl_process_done(union ctl_io *io);
487static void ctl_lun_thread(void *arg);
488static void ctl_thresh_thread(void *arg);
489static void ctl_work_thread(void *arg);
490static void ctl_enqueue_incoming(union ctl_io *io);
491static void ctl_enqueue_rtr(union ctl_io *io);
492static void ctl_enqueue_done(union ctl_io *io);
493static void ctl_enqueue_isc(union ctl_io *io);
494static const struct ctl_cmd_entry *
495    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
496static const struct ctl_cmd_entry *
497    ctl_validate_command(struct ctl_scsiio *ctsio);
498static int ctl_cmd_applicable(uint8_t lun_type,
499    const struct ctl_cmd_entry *entry);
500
501/*
502 * Load the serialization table.  This isn't very pretty, but is probably
503 * the easiest way to do it.
504 */
505#include "ctl_ser_table.c"
506
507/*
508 * We only need to define open, close and ioctl routines for this driver.
509 */
510static struct cdevsw ctl_cdevsw = {
511	.d_version =	D_VERSION,
512	.d_flags =	0,
513	.d_open =	ctl_open,
514	.d_close =	ctl_close,
515	.d_ioctl =	ctl_ioctl,
516	.d_name =	"ctl",
517};
518
519
520MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
521MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
522
523static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
524
525static moduledata_t ctl_moduledata = {
526	"ctl",
527	ctl_module_event_handler,
528	NULL
529};
530
531DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
532MODULE_VERSION(ctl, 1);
533
534static struct ctl_frontend ioctl_frontend =
535{
536	.name = "ioctl",
537};
538
539static void
540ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
541			    union ctl_ha_msg *msg_info)
542{
543	struct ctl_scsiio *ctsio;
544
545	if (msg_info->hdr.original_sc == NULL) {
546		printf("%s: original_sc == NULL!\n", __func__);
547		/* XXX KDM now what? */
548		return;
549	}
550
551	ctsio = &msg_info->hdr.original_sc->scsiio;
552	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
553	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
554	ctsio->io_hdr.status = msg_info->hdr.status;
555	ctsio->scsi_status = msg_info->scsi.scsi_status;
556	ctsio->sense_len = msg_info->scsi.sense_len;
557	ctsio->sense_residual = msg_info->scsi.sense_residual;
558	ctsio->residual = msg_info->scsi.residual;
559	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
560	       sizeof(ctsio->sense_data));
561	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
562	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
563	ctl_enqueue_isc((union ctl_io *)ctsio);
564}
565
566static void
567ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
568				union ctl_ha_msg *msg_info)
569{
570	struct ctl_scsiio *ctsio;
571
572	if (msg_info->hdr.serializing_sc == NULL) {
573		printf("%s: serializing_sc == NULL!\n", __func__);
574		/* XXX KDM now what? */
575		return;
576	}
577
578	ctsio = &msg_info->hdr.serializing_sc->scsiio;
579#if 0
580	/*
581	 * Attempt to catch the situation where an I/O has
582	 * been freed, and we're using it again.
583	 */
584	if (ctsio->io_hdr.io_type == 0xff) {
585		union ctl_io *tmp_io;
586		tmp_io = (union ctl_io *)ctsio;
587		printf("%s: %p use after free!\n", __func__,
588		       ctsio);
589		printf("%s: type %d msg %d cdb %x iptl: "
590		       "%d:%d:%d:%d tag 0x%04x "
591		       "flag %#x status %x\n",
592			__func__,
593			tmp_io->io_hdr.io_type,
594			tmp_io->io_hdr.msg_type,
595			tmp_io->scsiio.cdb[0],
596			tmp_io->io_hdr.nexus.initid.id,
597			tmp_io->io_hdr.nexus.targ_port,
598			tmp_io->io_hdr.nexus.targ_target.id,
599			tmp_io->io_hdr.nexus.targ_lun,
600			(tmp_io->io_hdr.io_type ==
601			CTL_IO_TASK) ?
602			tmp_io->taskio.tag_num :
603			tmp_io->scsiio.tag_num,
604		        tmp_io->io_hdr.flags,
605			tmp_io->io_hdr.status);
606	}
607#endif
608	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
609	ctl_enqueue_isc((union ctl_io *)ctsio);
610}
611
612/*
613 * ISC (Inter Shelf Communication) event handler.  Events from the HA
614 * subsystem come in here.
615 */
616static void
617ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
618{
619	struct ctl_softc *ctl_softc;
620	union ctl_io *io;
621	struct ctl_prio *presio;
622	ctl_ha_status isc_status;
623
624	ctl_softc = control_softc;
625	io = NULL;
626
627
628#if 0
629	printf("CTL: Isc Msg event %d\n", event);
630#endif
631	if (event == CTL_HA_EVT_MSG_RECV) {
632		union ctl_ha_msg msg_info;
633
634		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
635					     sizeof(msg_info), /*wait*/ 0);
636#if 0
637		printf("CTL: msg_type %d\n", msg_info.msg_type);
638#endif
639		if (isc_status != 0) {
640			printf("Error receiving message, status = %d\n",
641			       isc_status);
642			return;
643		}
644
645		switch (msg_info.hdr.msg_type) {
646		case CTL_MSG_SERIALIZE:
647#if 0
648			printf("Serialize\n");
649#endif
650			io = ctl_alloc_io_nowait(ctl_softc->othersc_pool);
651			if (io == NULL) {
652				printf("ctl_isc_event_handler: can't allocate "
653				       "ctl_io!\n");
654				/* Bad Juju */
655				/* Need to set busy and send msg back */
656				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
657				msg_info.hdr.status = CTL_SCSI_ERROR;
658				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
659				msg_info.scsi.sense_len = 0;
660			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
661				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
662				}
663				goto bailout;
664			}
665			ctl_zero_io(io);
666			// populate ctsio from msg_info
667			io->io_hdr.io_type = CTL_IO_SCSI;
668			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
669			io->io_hdr.original_sc = msg_info.hdr.original_sc;
670#if 0
671			printf("pOrig %x\n", (int)msg_info.original_sc);
672#endif
673			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
674					    CTL_FLAG_IO_ACTIVE;
675			/*
676			 * If we're in serialization-only mode, we don't
677			 * want to go through full done processing.  Thus
678			 * the COPY flag.
679			 *
680			 * XXX KDM add another flag that is more specific.
681			 */
682			if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
683				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
684			io->io_hdr.nexus = msg_info.hdr.nexus;
685#if 0
686			printf("targ %d, port %d, iid %d, lun %d\n",
687			       io->io_hdr.nexus.targ_target.id,
688			       io->io_hdr.nexus.targ_port,
689			       io->io_hdr.nexus.initid.id,
690			       io->io_hdr.nexus.targ_lun);
691#endif
692			io->scsiio.tag_num = msg_info.scsi.tag_num;
693			io->scsiio.tag_type = msg_info.scsi.tag_type;
694			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
695			       CTL_MAX_CDBLEN);
696			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
697				const struct ctl_cmd_entry *entry;
698
699				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
700				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
701				io->io_hdr.flags |=
702					entry->flags & CTL_FLAG_DATA_MASK;
703			}
704			ctl_enqueue_isc(io);
705			break;
706
707		/* Performed on the Originating SC, XFER mode only */
708		case CTL_MSG_DATAMOVE: {
709			struct ctl_sg_entry *sgl;
710			int i, j;
711
712			io = msg_info.hdr.original_sc;
713			if (io == NULL) {
714				printf("%s: original_sc == NULL!\n", __func__);
715				/* XXX KDM do something here */
716				break;
717			}
718			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
719			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
720			/*
721			 * Keep track of this, we need to send it back over
722			 * when the datamove is complete.
723			 */
724			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
725
726			if (msg_info.dt.sg_sequence == 0) {
727				/*
728				 * XXX KDM we use the preallocated S/G list
729				 * here, but we'll need to change this to
730				 * dynamic allocation if we need larger S/G
731				 * lists.
732				 */
733				if (msg_info.dt.kern_sg_entries >
734				    sizeof(io->io_hdr.remote_sglist) /
735				    sizeof(io->io_hdr.remote_sglist[0])) {
736					printf("%s: number of S/G entries "
737					    "needed %u > allocated num %zd\n",
738					    __func__,
739					    msg_info.dt.kern_sg_entries,
740					    sizeof(io->io_hdr.remote_sglist)/
741					    sizeof(io->io_hdr.remote_sglist[0]));
742
743					/*
744					 * XXX KDM send a message back to
745					 * the other side to shut down the
746					 * DMA.  The error will come back
747					 * through via the normal channel.
748					 */
749					break;
750				}
751				sgl = io->io_hdr.remote_sglist;
752				memset(sgl, 0,
753				       sizeof(io->io_hdr.remote_sglist));
754
755				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
756
757				io->scsiio.kern_sg_entries =
758					msg_info.dt.kern_sg_entries;
759				io->scsiio.rem_sg_entries =
760					msg_info.dt.kern_sg_entries;
761				io->scsiio.kern_data_len =
762					msg_info.dt.kern_data_len;
763				io->scsiio.kern_total_len =
764					msg_info.dt.kern_total_len;
765				io->scsiio.kern_data_resid =
766					msg_info.dt.kern_data_resid;
767				io->scsiio.kern_rel_offset =
768					msg_info.dt.kern_rel_offset;
769				/*
770				 * Clear out per-DMA flags.
771				 */
772				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
773				/*
774				 * Add per-DMA flags that are set for this
775				 * particular DMA request.
776				 */
777				io->io_hdr.flags |= msg_info.dt.flags &
778						    CTL_FLAG_RDMA_MASK;
779			} else
780				sgl = (struct ctl_sg_entry *)
781					io->scsiio.kern_data_ptr;
782
783			for (i = msg_info.dt.sent_sg_entries, j = 0;
784			     i < (msg_info.dt.sent_sg_entries +
785			     msg_info.dt.cur_sg_entries); i++, j++) {
786				sgl[i].addr = msg_info.dt.sg_list[j].addr;
787				sgl[i].len = msg_info.dt.sg_list[j].len;
788
789#if 0
790				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
791				       __func__,
792				       msg_info.dt.sg_list[j].addr,
793				       msg_info.dt.sg_list[j].len,
794				       sgl[i].addr, sgl[i].len, j, i);
795#endif
796			}
797#if 0
798			memcpy(&sgl[msg_info.dt.sent_sg_entries],
799			       msg_info.dt.sg_list,
800			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
801#endif
802
803			/*
804			 * If this is the last piece of the I/O, we've got
805			 * the full S/G list.  Queue processing in the thread.
806			 * Otherwise wait for the next piece.
807			 */
808			if (msg_info.dt.sg_last != 0)
809				ctl_enqueue_isc(io);
810			break;
811		}
812		/* Performed on the Serializing (primary) SC, XFER mode only */
813		case CTL_MSG_DATAMOVE_DONE: {
814			if (msg_info.hdr.serializing_sc == NULL) {
815				printf("%s: serializing_sc == NULL!\n",
816				       __func__);
817				/* XXX KDM now what? */
818				break;
819			}
820			/*
821			 * We grab the sense information here in case
822			 * there was a failure, so we can return status
823			 * back to the initiator.
824			 */
825			io = msg_info.hdr.serializing_sc;
826			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
827			io->io_hdr.status = msg_info.hdr.status;
828			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
829			io->scsiio.sense_len = msg_info.scsi.sense_len;
830			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
831			io->io_hdr.port_status = msg_info.scsi.fetd_status;
832			io->scsiio.residual = msg_info.scsi.residual;
833			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
834			       sizeof(io->scsiio.sense_data));
835			ctl_enqueue_isc(io);
836			break;
837		}
838
839		/* Preformed on Originating SC, SER_ONLY mode */
840		case CTL_MSG_R2R:
841			io = msg_info.hdr.original_sc;
842			if (io == NULL) {
843				printf("%s: Major Bummer\n", __func__);
844				return;
845			} else {
846#if 0
847				printf("pOrig %x\n",(int) ctsio);
848#endif
849			}
850			io->io_hdr.msg_type = CTL_MSG_R2R;
851			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
852			ctl_enqueue_isc(io);
853			break;
854
855		/*
856		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
857		 * mode.
858		 * Performed on the Originating (i.e. secondary) SC in XFER
859		 * mode
860		 */
861		case CTL_MSG_FINISH_IO:
862			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
863				ctl_isc_handler_finish_xfer(ctl_softc,
864							    &msg_info);
865			else
866				ctl_isc_handler_finish_ser_only(ctl_softc,
867								&msg_info);
868			break;
869
870		/* Preformed on Originating SC */
871		case CTL_MSG_BAD_JUJU:
872			io = msg_info.hdr.original_sc;
873			if (io == NULL) {
874				printf("%s: Bad JUJU!, original_sc is NULL!\n",
875				       __func__);
876				break;
877			}
878			ctl_copy_sense_data(&msg_info, io);
879			/*
880			 * IO should have already been cleaned up on other
881			 * SC so clear this flag so we won't send a message
882			 * back to finish the IO there.
883			 */
884			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
885			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
886
887			/* io = msg_info.hdr.serializing_sc; */
888			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
889			ctl_enqueue_isc(io);
890			break;
891
892		/* Handle resets sent from the other side */
893		case CTL_MSG_MANAGE_TASKS: {
894			struct ctl_taskio *taskio;
895			taskio = (struct ctl_taskio *)ctl_alloc_io_nowait(
896			    ctl_softc->othersc_pool);
897			if (taskio == NULL) {
898				printf("ctl_isc_event_handler: can't allocate "
899				       "ctl_io!\n");
900				/* Bad Juju */
901				/* should I just call the proper reset func
902				   here??? */
903				goto bailout;
904			}
905			ctl_zero_io((union ctl_io *)taskio);
906			taskio->io_hdr.io_type = CTL_IO_TASK;
907			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
908			taskio->io_hdr.nexus = msg_info.hdr.nexus;
909			taskio->task_action = msg_info.task.task_action;
910			taskio->tag_num = msg_info.task.tag_num;
911			taskio->tag_type = msg_info.task.tag_type;
912#ifdef CTL_TIME_IO
913			taskio->io_hdr.start_time = time_uptime;
914			getbintime(&taskio->io_hdr.start_bt);
915#if 0
916			cs_prof_gettime(&taskio->io_hdr.start_ticks);
917#endif
918#endif /* CTL_TIME_IO */
919			ctl_run_task((union ctl_io *)taskio);
920			break;
921		}
922		/* Persistent Reserve action which needs attention */
923		case CTL_MSG_PERS_ACTION:
924			presio = (struct ctl_prio *)ctl_alloc_io_nowait(
925			    ctl_softc->othersc_pool);
926			if (presio == NULL) {
927				printf("ctl_isc_event_handler: can't allocate "
928				       "ctl_io!\n");
929				/* Bad Juju */
930				/* Need to set busy and send msg back */
931				goto bailout;
932			}
933			ctl_zero_io((union ctl_io *)presio);
934			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
935			presio->pr_msg = msg_info.pr;
936			ctl_enqueue_isc((union ctl_io *)presio);
937			break;
938		case CTL_MSG_SYNC_FE:
939			rcv_sync_msg = 1;
940			break;
941		default:
942		        printf("How did I get here?\n");
943		}
944	} else if (event == CTL_HA_EVT_MSG_SENT) {
945		if (param != CTL_HA_STATUS_SUCCESS) {
946			printf("Bad status from ctl_ha_msg_send status %d\n",
947			       param);
948		}
949		return;
950	} else if (event == CTL_HA_EVT_DISCONNECT) {
951		printf("CTL: Got a disconnect from Isc\n");
952		return;
953	} else {
954		printf("ctl_isc_event_handler: Unknown event %d\n", event);
955		return;
956	}
957
958bailout:
959	return;
960}
961
962static void
963ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
964{
965	struct scsi_sense_data *sense;
966
967	sense = &dest->scsiio.sense_data;
968	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
969	dest->scsiio.scsi_status = src->scsi.scsi_status;
970	dest->scsiio.sense_len = src->scsi.sense_len;
971	dest->io_hdr.status = src->hdr.status;
972}
973
974static int
975ctl_ha_state_sysctl(SYSCTL_HANDLER_ARGS)
976{
977	struct ctl_softc *softc = (struct ctl_softc *)arg1;
978	struct ctl_lun *lun;
979	int error, value, i;
980
981	if (softc->flags & CTL_FLAG_ACTIVE_SHELF)
982		value = 0;
983	else
984		value = 1;
985
986	error = sysctl_handle_int(oidp, &value, 0, req);
987	if ((error != 0) || (req->newptr == NULL))
988		return (error);
989
990	mtx_lock(&softc->ctl_lock);
991	if (value == 0)
992		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
993	else
994		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
995	STAILQ_FOREACH(lun, &softc->lun_list, links) {
996		mtx_lock(&lun->lun_lock);
997		for (i = 0; i < CTL_MAX_INITIATORS; i++)
998			lun->pending_ua[i] |= CTL_UA_ASYM_ACC_CHANGE;
999		mtx_unlock(&lun->lun_lock);
1000	}
1001	mtx_unlock(&softc->ctl_lock);
1002	return (0);
1003}
1004
1005static int
1006ctl_init(void)
1007{
1008	struct ctl_softc *softc;
1009	void *other_pool;
1010	struct ctl_port *port;
1011	int i, error, retval;
1012	//int isc_retval;
1013
1014	retval = 0;
1015	ctl_pause_rtr = 0;
1016        rcv_sync_msg = 0;
1017
1018	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1019			       M_WAITOK | M_ZERO);
1020	softc = control_softc;
1021
1022	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1023			      "cam/ctl");
1024
1025	softc->dev->si_drv1 = softc;
1026
1027	/*
1028	 * By default, return a "bad LUN" peripheral qualifier for unknown
1029	 * LUNs.  The user can override this default using the tunable or
1030	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
1031	 */
1032	softc->inquiry_pq_no_lun = 1;
1033	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
1034			  &softc->inquiry_pq_no_lun);
1035	sysctl_ctx_init(&softc->sysctl_ctx);
1036	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1037		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1038		CTLFLAG_RD, 0, "CAM Target Layer");
1039
1040	if (softc->sysctl_tree == NULL) {
1041		printf("%s: unable to allocate sysctl tree\n", __func__);
1042		destroy_dev(softc->dev);
1043		free(control_softc, M_DEVBUF);
1044		control_softc = NULL;
1045		return (ENOMEM);
1046	}
1047
1048	SYSCTL_ADD_INT(&softc->sysctl_ctx,
1049		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1050		       "inquiry_pq_no_lun", CTLFLAG_RW,
1051		       &softc->inquiry_pq_no_lun, 0,
1052		       "Report no lun possible for invalid LUNs");
1053
1054	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1055	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1056	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1057	softc->open_count = 0;
1058
1059	/*
1060	 * Default to actually sending a SYNCHRONIZE CACHE command down to
1061	 * the drive.
1062	 */
1063	softc->flags = CTL_FLAG_REAL_SYNC;
1064
1065	/*
1066	 * In Copan's HA scheme, the "master" and "slave" roles are
1067	 * figured out through the slot the controller is in.  Although it
1068	 * is an active/active system, someone has to be in charge.
1069	 */
1070	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1071	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1072	    "HA head ID (0 - no HA)");
1073	if (softc->ha_id == 0) {
1074		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1075		softc->is_single = 1;
1076		softc->port_offset = 0;
1077	} else
1078		softc->port_offset = (softc->ha_id - 1) * CTL_MAX_PORTS;
1079	persis_offset = softc->port_offset * CTL_MAX_INIT_PER_PORT;
1080
1081	/*
1082	 * XXX KDM need to figure out where we want to get our target ID
1083	 * and WWID.  Is it different on each port?
1084	 */
1085	softc->target.id = 0;
1086	softc->target.wwid[0] = 0x12345678;
1087	softc->target.wwid[1] = 0x87654321;
1088	STAILQ_INIT(&softc->lun_list);
1089	STAILQ_INIT(&softc->pending_lun_queue);
1090	STAILQ_INIT(&softc->fe_list);
1091	STAILQ_INIT(&softc->port_list);
1092	STAILQ_INIT(&softc->be_list);
1093	ctl_tpc_init(softc);
1094
1095	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1096	                    &other_pool) != 0)
1097	{
1098		printf("ctl: can't allocate %d entry other SC pool, "
1099		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1100		return (ENOMEM);
1101	}
1102	softc->othersc_pool = other_pool;
1103
1104	if (worker_threads <= 0)
1105		worker_threads = max(1, mp_ncpus / 4);
1106	if (worker_threads > CTL_MAX_THREADS)
1107		worker_threads = CTL_MAX_THREADS;
1108
1109	for (i = 0; i < worker_threads; i++) {
1110		struct ctl_thread *thr = &softc->threads[i];
1111
1112		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1113		thr->ctl_softc = softc;
1114		STAILQ_INIT(&thr->incoming_queue);
1115		STAILQ_INIT(&thr->rtr_queue);
1116		STAILQ_INIT(&thr->done_queue);
1117		STAILQ_INIT(&thr->isc_queue);
1118
1119		error = kproc_kthread_add(ctl_work_thread, thr,
1120		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1121		if (error != 0) {
1122			printf("error creating CTL work thread!\n");
1123			ctl_pool_free(other_pool);
1124			return (error);
1125		}
1126	}
1127	error = kproc_kthread_add(ctl_lun_thread, softc,
1128	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1129	if (error != 0) {
1130		printf("error creating CTL lun thread!\n");
1131		ctl_pool_free(other_pool);
1132		return (error);
1133	}
1134	error = kproc_kthread_add(ctl_thresh_thread, softc,
1135	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1136	if (error != 0) {
1137		printf("error creating CTL threshold thread!\n");
1138		ctl_pool_free(other_pool);
1139		return (error);
1140	}
1141	if (bootverbose)
1142		printf("ctl: CAM Target Layer loaded\n");
1143
1144	/*
1145	 * Initialize the ioctl front end.
1146	 */
1147	ctl_frontend_register(&ioctl_frontend);
1148	port = &softc->ioctl_info.port;
1149	port->frontend = &ioctl_frontend;
1150	sprintf(softc->ioctl_info.port_name, "ioctl");
1151	port->port_type = CTL_PORT_IOCTL;
1152	port->num_requested_ctl_io = 100;
1153	port->port_name = softc->ioctl_info.port_name;
1154	port->port_online = ctl_ioctl_online;
1155	port->port_offline = ctl_ioctl_offline;
1156	port->onoff_arg = &softc->ioctl_info;
1157	port->lun_enable = ctl_ioctl_lun_enable;
1158	port->lun_disable = ctl_ioctl_lun_disable;
1159	port->targ_lun_arg = &softc->ioctl_info;
1160	port->fe_datamove = ctl_ioctl_datamove;
1161	port->fe_done = ctl_ioctl_done;
1162	port->max_targets = 15;
1163	port->max_target_id = 15;
1164
1165	if (ctl_port_register(&softc->ioctl_info.port) != 0) {
1166		printf("ctl: ioctl front end registration failed, will "
1167		       "continue anyway\n");
1168	}
1169
1170	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1171	    OID_AUTO, "ha_state", CTLTYPE_INT | CTLFLAG_RWTUN,
1172	    softc, 0, ctl_ha_state_sysctl, "I", "HA state for this head");
1173
1174#ifdef CTL_IO_DELAY
1175	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1176		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1177		       sizeof(struct callout), CTL_TIMER_BYTES);
1178		return (EINVAL);
1179	}
1180#endif /* CTL_IO_DELAY */
1181
1182	return (0);
1183}
1184
1185void
1186ctl_shutdown(void)
1187{
1188	struct ctl_softc *softc;
1189	struct ctl_lun *lun, *next_lun;
1190
1191	softc = (struct ctl_softc *)control_softc;
1192
1193	if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1194		printf("ctl: ioctl front end deregistration failed\n");
1195
1196	mtx_lock(&softc->ctl_lock);
1197
1198	/*
1199	 * Free up each LUN.
1200	 */
1201	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1202		next_lun = STAILQ_NEXT(lun, links);
1203		ctl_free_lun(lun);
1204	}
1205
1206	mtx_unlock(&softc->ctl_lock);
1207
1208	ctl_frontend_deregister(&ioctl_frontend);
1209
1210#if 0
1211	ctl_shutdown_thread(softc->work_thread);
1212	mtx_destroy(&softc->queue_lock);
1213#endif
1214
1215	ctl_tpc_shutdown(softc);
1216	uma_zdestroy(softc->io_zone);
1217	mtx_destroy(&softc->ctl_lock);
1218
1219	destroy_dev(softc->dev);
1220
1221	sysctl_ctx_free(&softc->sysctl_ctx);
1222
1223	free(control_softc, M_DEVBUF);
1224	control_softc = NULL;
1225
1226	if (bootverbose)
1227		printf("ctl: CAM Target Layer unloaded\n");
1228}
1229
1230static int
1231ctl_module_event_handler(module_t mod, int what, void *arg)
1232{
1233
1234	switch (what) {
1235	case MOD_LOAD:
1236		return (ctl_init());
1237	case MOD_UNLOAD:
1238		return (EBUSY);
1239	default:
1240		return (EOPNOTSUPP);
1241	}
1242}
1243
1244/*
1245 * XXX KDM should we do some access checks here?  Bump a reference count to
1246 * prevent a CTL module from being unloaded while someone has it open?
1247 */
1248static int
1249ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1250{
1251	return (0);
1252}
1253
1254static int
1255ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1256{
1257	return (0);
1258}
1259
1260int
1261ctl_port_enable(ctl_port_type port_type)
1262{
1263	struct ctl_softc *softc = control_softc;
1264	struct ctl_port *port;
1265
1266	if (softc->is_single == 0) {
1267		union ctl_ha_msg msg_info;
1268		int isc_retval;
1269
1270#if 0
1271		printf("%s: HA mode, synchronizing frontend enable\n",
1272		        __func__);
1273#endif
1274		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1275	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1276		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1277			printf("Sync msg send error retval %d\n", isc_retval);
1278		}
1279		if (!rcv_sync_msg) {
1280			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1281			        sizeof(msg_info), 1);
1282		}
1283#if 0
1284        	printf("CTL:Frontend Enable\n");
1285	} else {
1286		printf("%s: single mode, skipping frontend synchronization\n",
1287		        __func__);
1288#endif
1289	}
1290
1291	STAILQ_FOREACH(port, &softc->port_list, links) {
1292		if (port_type & port->port_type)
1293		{
1294#if 0
1295			printf("port %d\n", port->targ_port);
1296#endif
1297			ctl_port_online(port);
1298		}
1299	}
1300
1301	return (0);
1302}
1303
1304int
1305ctl_port_disable(ctl_port_type port_type)
1306{
1307	struct ctl_softc *softc;
1308	struct ctl_port *port;
1309
1310	softc = control_softc;
1311
1312	STAILQ_FOREACH(port, &softc->port_list, links) {
1313		if (port_type & port->port_type)
1314			ctl_port_offline(port);
1315	}
1316
1317	return (0);
1318}
1319
1320/*
1321 * Returns 0 for success, 1 for failure.
1322 * Currently the only failure mode is if there aren't enough entries
1323 * allocated.  So, in case of a failure, look at num_entries_dropped,
1324 * reallocate and try again.
1325 */
1326int
1327ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1328	      int *num_entries_filled, int *num_entries_dropped,
1329	      ctl_port_type port_type, int no_virtual)
1330{
1331	struct ctl_softc *softc;
1332	struct ctl_port *port;
1333	int entries_dropped, entries_filled;
1334	int retval;
1335	int i;
1336
1337	softc = control_softc;
1338
1339	retval = 0;
1340	entries_filled = 0;
1341	entries_dropped = 0;
1342
1343	i = 0;
1344	mtx_lock(&softc->ctl_lock);
1345	STAILQ_FOREACH(port, &softc->port_list, links) {
1346		struct ctl_port_entry *entry;
1347
1348		if ((port->port_type & port_type) == 0)
1349			continue;
1350
1351		if ((no_virtual != 0)
1352		 && (port->virtual_port != 0))
1353			continue;
1354
1355		if (entries_filled >= num_entries_alloced) {
1356			entries_dropped++;
1357			continue;
1358		}
1359		entry = &entries[i];
1360
1361		entry->port_type = port->port_type;
1362		strlcpy(entry->port_name, port->port_name,
1363			sizeof(entry->port_name));
1364		entry->physical_port = port->physical_port;
1365		entry->virtual_port = port->virtual_port;
1366		entry->wwnn = port->wwnn;
1367		entry->wwpn = port->wwpn;
1368
1369		i++;
1370		entries_filled++;
1371	}
1372
1373	mtx_unlock(&softc->ctl_lock);
1374
1375	if (entries_dropped > 0)
1376		retval = 1;
1377
1378	*num_entries_dropped = entries_dropped;
1379	*num_entries_filled = entries_filled;
1380
1381	return (retval);
1382}
1383
1384static void
1385ctl_ioctl_online(void *arg)
1386{
1387	struct ctl_ioctl_info *ioctl_info;
1388
1389	ioctl_info = (struct ctl_ioctl_info *)arg;
1390
1391	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1392}
1393
1394static void
1395ctl_ioctl_offline(void *arg)
1396{
1397	struct ctl_ioctl_info *ioctl_info;
1398
1399	ioctl_info = (struct ctl_ioctl_info *)arg;
1400
1401	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1402}
1403
1404/*
1405 * Remove an initiator by port number and initiator ID.
1406 * Returns 0 for success, -1 for failure.
1407 */
1408int
1409ctl_remove_initiator(struct ctl_port *port, int iid)
1410{
1411	struct ctl_softc *softc = control_softc;
1412
1413	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1414
1415	if (iid > CTL_MAX_INIT_PER_PORT) {
1416		printf("%s: initiator ID %u > maximun %u!\n",
1417		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1418		return (-1);
1419	}
1420
1421	mtx_lock(&softc->ctl_lock);
1422	port->wwpn_iid[iid].in_use--;
1423	port->wwpn_iid[iid].last_use = time_uptime;
1424	mtx_unlock(&softc->ctl_lock);
1425
1426	return (0);
1427}
1428
1429/*
1430 * Add an initiator to the initiator map.
1431 * Returns iid for success, < 0 for failure.
1432 */
1433int
1434ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1435{
1436	struct ctl_softc *softc = control_softc;
1437	time_t best_time;
1438	int i, best;
1439
1440	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1441
1442	if (iid >= CTL_MAX_INIT_PER_PORT) {
1443		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1444		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1445		free(name, M_CTL);
1446		return (-1);
1447	}
1448
1449	mtx_lock(&softc->ctl_lock);
1450
1451	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1452		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1453			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1454				iid = i;
1455				break;
1456			}
1457			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1458			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1459				iid = i;
1460				break;
1461			}
1462		}
1463	}
1464
1465	if (iid < 0) {
1466		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1467			if (port->wwpn_iid[i].in_use == 0 &&
1468			    port->wwpn_iid[i].wwpn == 0 &&
1469			    port->wwpn_iid[i].name == NULL) {
1470				iid = i;
1471				break;
1472			}
1473		}
1474	}
1475
1476	if (iid < 0) {
1477		best = -1;
1478		best_time = INT32_MAX;
1479		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1480			if (port->wwpn_iid[i].in_use == 0) {
1481				if (port->wwpn_iid[i].last_use < best_time) {
1482					best = i;
1483					best_time = port->wwpn_iid[i].last_use;
1484				}
1485			}
1486		}
1487		iid = best;
1488	}
1489
1490	if (iid < 0) {
1491		mtx_unlock(&softc->ctl_lock);
1492		free(name, M_CTL);
1493		return (-2);
1494	}
1495
1496	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1497		/*
1498		 * This is not an error yet.
1499		 */
1500		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1501#if 0
1502			printf("%s: port %d iid %u WWPN %#jx arrived"
1503			    " again\n", __func__, port->targ_port,
1504			    iid, (uintmax_t)wwpn);
1505#endif
1506			goto take;
1507		}
1508		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1509		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1510#if 0
1511			printf("%s: port %d iid %u name '%s' arrived"
1512			    " again\n", __func__, port->targ_port,
1513			    iid, name);
1514#endif
1515			goto take;
1516		}
1517
1518		/*
1519		 * This is an error, but what do we do about it?  The
1520		 * driver is telling us we have a new WWPN for this
1521		 * initiator ID, so we pretty much need to use it.
1522		 */
1523		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1524		    " but WWPN %#jx '%s' is still at that address\n",
1525		    __func__, port->targ_port, iid, wwpn, name,
1526		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1527		    port->wwpn_iid[iid].name);
1528
1529		/*
1530		 * XXX KDM clear have_ca and ua_pending on each LUN for
1531		 * this initiator.
1532		 */
1533	}
1534take:
1535	free(port->wwpn_iid[iid].name, M_CTL);
1536	port->wwpn_iid[iid].name = name;
1537	port->wwpn_iid[iid].wwpn = wwpn;
1538	port->wwpn_iid[iid].in_use++;
1539	mtx_unlock(&softc->ctl_lock);
1540
1541	return (iid);
1542}
1543
1544static int
1545ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1546{
1547	int len;
1548
1549	switch (port->port_type) {
1550	case CTL_PORT_FC:
1551	{
1552		struct scsi_transportid_fcp *id =
1553		    (struct scsi_transportid_fcp *)buf;
1554		if (port->wwpn_iid[iid].wwpn == 0)
1555			return (0);
1556		memset(id, 0, sizeof(*id));
1557		id->format_protocol = SCSI_PROTO_FC;
1558		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1559		return (sizeof(*id));
1560	}
1561	case CTL_PORT_ISCSI:
1562	{
1563		struct scsi_transportid_iscsi_port *id =
1564		    (struct scsi_transportid_iscsi_port *)buf;
1565		if (port->wwpn_iid[iid].name == NULL)
1566			return (0);
1567		memset(id, 0, 256);
1568		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1569		    SCSI_PROTO_ISCSI;
1570		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1571		len = roundup2(min(len, 252), 4);
1572		scsi_ulto2b(len, id->additional_length);
1573		return (sizeof(*id) + len);
1574	}
1575	case CTL_PORT_SAS:
1576	{
1577		struct scsi_transportid_sas *id =
1578		    (struct scsi_transportid_sas *)buf;
1579		if (port->wwpn_iid[iid].wwpn == 0)
1580			return (0);
1581		memset(id, 0, sizeof(*id));
1582		id->format_protocol = SCSI_PROTO_SAS;
1583		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1584		return (sizeof(*id));
1585	}
1586	default:
1587	{
1588		struct scsi_transportid_spi *id =
1589		    (struct scsi_transportid_spi *)buf;
1590		memset(id, 0, sizeof(*id));
1591		id->format_protocol = SCSI_PROTO_SPI;
1592		scsi_ulto2b(iid, id->scsi_addr);
1593		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1594		return (sizeof(*id));
1595	}
1596	}
1597}
1598
1599static int
1600ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1601{
1602	return (0);
1603}
1604
1605static int
1606ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1607{
1608	return (0);
1609}
1610
1611/*
1612 * Data movement routine for the CTL ioctl frontend port.
1613 */
1614static int
1615ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1616{
1617	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1618	struct ctl_sg_entry ext_entry, kern_entry;
1619	int ext_sglen, ext_sg_entries, kern_sg_entries;
1620	int ext_sg_start, ext_offset;
1621	int len_to_copy, len_copied;
1622	int kern_watermark, ext_watermark;
1623	int ext_sglist_malloced;
1624	int i, j;
1625
1626	ext_sglist_malloced = 0;
1627	ext_sg_start = 0;
1628	ext_offset = 0;
1629
1630	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1631
1632	/*
1633	 * If this flag is set, fake the data transfer.
1634	 */
1635	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1636		ctsio->ext_data_filled = ctsio->ext_data_len;
1637		goto bailout;
1638	}
1639
1640	/*
1641	 * To simplify things here, if we have a single buffer, stick it in
1642	 * a S/G entry and just make it a single entry S/G list.
1643	 */
1644	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1645		int len_seen;
1646
1647		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1648
1649		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1650							   M_WAITOK);
1651		ext_sglist_malloced = 1;
1652		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1653				   ext_sglen) != 0) {
1654			ctl_set_internal_failure(ctsio,
1655						 /*sks_valid*/ 0,
1656						 /*retry_count*/ 0);
1657			goto bailout;
1658		}
1659		ext_sg_entries = ctsio->ext_sg_entries;
1660		len_seen = 0;
1661		for (i = 0; i < ext_sg_entries; i++) {
1662			if ((len_seen + ext_sglist[i].len) >=
1663			     ctsio->ext_data_filled) {
1664				ext_sg_start = i;
1665				ext_offset = ctsio->ext_data_filled - len_seen;
1666				break;
1667			}
1668			len_seen += ext_sglist[i].len;
1669		}
1670	} else {
1671		ext_sglist = &ext_entry;
1672		ext_sglist->addr = ctsio->ext_data_ptr;
1673		ext_sglist->len = ctsio->ext_data_len;
1674		ext_sg_entries = 1;
1675		ext_sg_start = 0;
1676		ext_offset = ctsio->ext_data_filled;
1677	}
1678
1679	if (ctsio->kern_sg_entries > 0) {
1680		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1681		kern_sg_entries = ctsio->kern_sg_entries;
1682	} else {
1683		kern_sglist = &kern_entry;
1684		kern_sglist->addr = ctsio->kern_data_ptr;
1685		kern_sglist->len = ctsio->kern_data_len;
1686		kern_sg_entries = 1;
1687	}
1688
1689
1690	kern_watermark = 0;
1691	ext_watermark = ext_offset;
1692	len_copied = 0;
1693	for (i = ext_sg_start, j = 0;
1694	     i < ext_sg_entries && j < kern_sg_entries;) {
1695		uint8_t *ext_ptr, *kern_ptr;
1696
1697		len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1698				      kern_sglist[j].len - kern_watermark);
1699
1700		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1701		ext_ptr = ext_ptr + ext_watermark;
1702		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1703			/*
1704			 * XXX KDM fix this!
1705			 */
1706			panic("need to implement bus address support");
1707#if 0
1708			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1709#endif
1710		} else
1711			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1712		kern_ptr = kern_ptr + kern_watermark;
1713
1714		kern_watermark += len_to_copy;
1715		ext_watermark += len_to_copy;
1716
1717		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1718		     CTL_FLAG_DATA_IN) {
1719			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1720					 "bytes to user\n", len_to_copy));
1721			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1722					 "to %p\n", kern_ptr, ext_ptr));
1723			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1724				ctl_set_internal_failure(ctsio,
1725							 /*sks_valid*/ 0,
1726							 /*retry_count*/ 0);
1727				goto bailout;
1728			}
1729		} else {
1730			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1731					 "bytes from user\n", len_to_copy));
1732			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1733					 "to %p\n", ext_ptr, kern_ptr));
1734			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1735				ctl_set_internal_failure(ctsio,
1736							 /*sks_valid*/ 0,
1737							 /*retry_count*/0);
1738				goto bailout;
1739			}
1740		}
1741
1742		len_copied += len_to_copy;
1743
1744		if (ext_sglist[i].len == ext_watermark) {
1745			i++;
1746			ext_watermark = 0;
1747		}
1748
1749		if (kern_sglist[j].len == kern_watermark) {
1750			j++;
1751			kern_watermark = 0;
1752		}
1753	}
1754
1755	ctsio->ext_data_filled += len_copied;
1756
1757	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1758			 "kern_sg_entries: %d\n", ext_sg_entries,
1759			 kern_sg_entries));
1760	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1761			 "kern_data_len = %d\n", ctsio->ext_data_len,
1762			 ctsio->kern_data_len));
1763
1764
1765	/* XXX KDM set residual?? */
1766bailout:
1767
1768	if (ext_sglist_malloced != 0)
1769		free(ext_sglist, M_CTL);
1770
1771	return (CTL_RETVAL_COMPLETE);
1772}
1773
1774/*
1775 * Serialize a command that went down the "wrong" side, and so was sent to
1776 * this controller for execution.  The logic is a little different than the
1777 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1778 * sent back to the other side, but in the success case, we execute the
1779 * command on this side (XFER mode) or tell the other side to execute it
1780 * (SER_ONLY mode).
1781 */
1782static int
1783ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1784{
1785	struct ctl_softc *ctl_softc;
1786	union ctl_ha_msg msg_info;
1787	struct ctl_lun *lun;
1788	int retval = 0;
1789	uint32_t targ_lun;
1790
1791	ctl_softc = control_softc;
1792
1793	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1794	lun = ctl_softc->ctl_luns[targ_lun];
1795	if (lun==NULL)
1796	{
1797		/*
1798		 * Why isn't LUN defined? The other side wouldn't
1799		 * send a cmd if the LUN is undefined.
1800		 */
1801		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1802
1803		/* "Logical unit not supported" */
1804		ctl_set_sense_data(&msg_info.scsi.sense_data,
1805				   lun,
1806				   /*sense_format*/SSD_TYPE_NONE,
1807				   /*current_error*/ 1,
1808				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1809				   /*asc*/ 0x25,
1810				   /*ascq*/ 0x00,
1811				   SSD_ELEM_NONE);
1812
1813		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1814		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1815		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1816		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1817		msg_info.hdr.serializing_sc = NULL;
1818		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1819	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1820				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1821		}
1822		return(1);
1823
1824	}
1825
1826	mtx_lock(&lun->lun_lock);
1827    	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1828
1829	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1830		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1831		 ooa_links))) {
1832	case CTL_ACTION_BLOCK:
1833		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1834		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1835				  blocked_links);
1836		break;
1837	case CTL_ACTION_PASS:
1838	case CTL_ACTION_SKIP:
1839		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1840			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1841			ctl_enqueue_rtr((union ctl_io *)ctsio);
1842		} else {
1843
1844			/* send msg back to other side */
1845			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1846			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1847			msg_info.hdr.msg_type = CTL_MSG_R2R;
1848#if 0
1849			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1850#endif
1851		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1852			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1853			}
1854		}
1855		break;
1856	case CTL_ACTION_OVERLAP:
1857		/* OVERLAPPED COMMANDS ATTEMPTED */
1858		ctl_set_sense_data(&msg_info.scsi.sense_data,
1859				   lun,
1860				   /*sense_format*/SSD_TYPE_NONE,
1861				   /*current_error*/ 1,
1862				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1863				   /*asc*/ 0x4E,
1864				   /*ascq*/ 0x00,
1865				   SSD_ELEM_NONE);
1866
1867		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1868		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1869		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1870		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1871		msg_info.hdr.serializing_sc = NULL;
1872		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1873#if 0
1874		printf("BAD JUJU:Major Bummer Overlap\n");
1875#endif
1876		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1877		retval = 1;
1878		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1879		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1880		}
1881		break;
1882	case CTL_ACTION_OVERLAP_TAG:
1883		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1884		ctl_set_sense_data(&msg_info.scsi.sense_data,
1885				   lun,
1886				   /*sense_format*/SSD_TYPE_NONE,
1887				   /*current_error*/ 1,
1888				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1889				   /*asc*/ 0x4D,
1890				   /*ascq*/ ctsio->tag_num & 0xff,
1891				   SSD_ELEM_NONE);
1892
1893		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1894		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1895		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1896		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1897		msg_info.hdr.serializing_sc = NULL;
1898		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1899#if 0
1900		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1901#endif
1902		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1903		retval = 1;
1904		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1905		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1906		}
1907		break;
1908	case CTL_ACTION_ERROR:
1909	default:
1910		/* "Internal target failure" */
1911		ctl_set_sense_data(&msg_info.scsi.sense_data,
1912				   lun,
1913				   /*sense_format*/SSD_TYPE_NONE,
1914				   /*current_error*/ 1,
1915				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1916				   /*asc*/ 0x44,
1917				   /*ascq*/ 0x00,
1918				   SSD_ELEM_NONE);
1919
1920		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1921		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1922		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1923		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1924		msg_info.hdr.serializing_sc = NULL;
1925		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1926#if 0
1927		printf("BAD JUJU:Major Bummer HW Error\n");
1928#endif
1929		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1930		retval = 1;
1931		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1932		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1933		}
1934		break;
1935	}
1936	mtx_unlock(&lun->lun_lock);
1937	return (retval);
1938}
1939
1940static int
1941ctl_ioctl_submit_wait(union ctl_io *io)
1942{
1943	struct ctl_fe_ioctl_params params;
1944	ctl_fe_ioctl_state last_state;
1945	int done, retval;
1946
1947	retval = 0;
1948
1949	bzero(&params, sizeof(params));
1950
1951	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1952	cv_init(&params.sem, "ctlioccv");
1953	params.state = CTL_IOCTL_INPROG;
1954	last_state = params.state;
1955
1956	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1957
1958	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1959
1960	/* This shouldn't happen */
1961	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1962		return (retval);
1963
1964	done = 0;
1965
1966	do {
1967		mtx_lock(&params.ioctl_mtx);
1968		/*
1969		 * Check the state here, and don't sleep if the state has
1970		 * already changed (i.e. wakeup has already occured, but we
1971		 * weren't waiting yet).
1972		 */
1973		if (params.state == last_state) {
1974			/* XXX KDM cv_wait_sig instead? */
1975			cv_wait(&params.sem, &params.ioctl_mtx);
1976		}
1977		last_state = params.state;
1978
1979		switch (params.state) {
1980		case CTL_IOCTL_INPROG:
1981			/* Why did we wake up? */
1982			/* XXX KDM error here? */
1983			mtx_unlock(&params.ioctl_mtx);
1984			break;
1985		case CTL_IOCTL_DATAMOVE:
1986			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1987
1988			/*
1989			 * change last_state back to INPROG to avoid
1990			 * deadlock on subsequent data moves.
1991			 */
1992			params.state = last_state = CTL_IOCTL_INPROG;
1993
1994			mtx_unlock(&params.ioctl_mtx);
1995			ctl_ioctl_do_datamove(&io->scsiio);
1996			/*
1997			 * Note that in some cases, most notably writes,
1998			 * this will queue the I/O and call us back later.
1999			 * In other cases, generally reads, this routine
2000			 * will immediately call back and wake us up,
2001			 * probably using our own context.
2002			 */
2003			io->scsiio.be_move_done(io);
2004			break;
2005		case CTL_IOCTL_DONE:
2006			mtx_unlock(&params.ioctl_mtx);
2007			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
2008			done = 1;
2009			break;
2010		default:
2011			mtx_unlock(&params.ioctl_mtx);
2012			/* XXX KDM error here? */
2013			break;
2014		}
2015	} while (done == 0);
2016
2017	mtx_destroy(&params.ioctl_mtx);
2018	cv_destroy(&params.sem);
2019
2020	return (CTL_RETVAL_COMPLETE);
2021}
2022
2023static void
2024ctl_ioctl_datamove(union ctl_io *io)
2025{
2026	struct ctl_fe_ioctl_params *params;
2027
2028	params = (struct ctl_fe_ioctl_params *)
2029		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2030
2031	mtx_lock(&params->ioctl_mtx);
2032	params->state = CTL_IOCTL_DATAMOVE;
2033	cv_broadcast(&params->sem);
2034	mtx_unlock(&params->ioctl_mtx);
2035}
2036
2037static void
2038ctl_ioctl_done(union ctl_io *io)
2039{
2040	struct ctl_fe_ioctl_params *params;
2041
2042	params = (struct ctl_fe_ioctl_params *)
2043		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2044
2045	mtx_lock(&params->ioctl_mtx);
2046	params->state = CTL_IOCTL_DONE;
2047	cv_broadcast(&params->sem);
2048	mtx_unlock(&params->ioctl_mtx);
2049}
2050
2051static void
2052ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2053{
2054	struct ctl_fe_ioctl_startstop_info *sd_info;
2055
2056	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2057
2058	sd_info->hs_info.status = metatask->status;
2059	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2060	sd_info->hs_info.luns_complete =
2061		metatask->taskinfo.startstop.luns_complete;
2062	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2063
2064	cv_broadcast(&sd_info->sem);
2065}
2066
2067static void
2068ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2069{
2070	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2071
2072	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2073
2074	mtx_lock(fe_bbr_info->lock);
2075	fe_bbr_info->bbr_info->status = metatask->status;
2076	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2077	fe_bbr_info->wakeup_done = 1;
2078	mtx_unlock(fe_bbr_info->lock);
2079
2080	cv_broadcast(&fe_bbr_info->sem);
2081}
2082
2083/*
2084 * Returns 0 for success, errno for failure.
2085 */
2086static int
2087ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2088		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2089{
2090	union ctl_io *io;
2091	int retval;
2092
2093	retval = 0;
2094
2095	mtx_lock(&lun->lun_lock);
2096	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2097	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2098	     ooa_links)) {
2099		struct ctl_ooa_entry *entry;
2100
2101		/*
2102		 * If we've got more than we can fit, just count the
2103		 * remaining entries.
2104		 */
2105		if (*cur_fill_num >= ooa_hdr->alloc_num)
2106			continue;
2107
2108		entry = &kern_entries[*cur_fill_num];
2109
2110		entry->tag_num = io->scsiio.tag_num;
2111		entry->lun_num = lun->lun;
2112#ifdef CTL_TIME_IO
2113		entry->start_bt = io->io_hdr.start_bt;
2114#endif
2115		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2116		entry->cdb_len = io->scsiio.cdb_len;
2117		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2118			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2119
2120		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2121			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2122
2123		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2124			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2125
2126		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2127			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2128
2129		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2130			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2131	}
2132	mtx_unlock(&lun->lun_lock);
2133
2134	return (retval);
2135}
2136
2137static void *
2138ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2139		 size_t error_str_len)
2140{
2141	void *kptr;
2142
2143	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2144
2145	if (copyin(user_addr, kptr, len) != 0) {
2146		snprintf(error_str, error_str_len, "Error copying %d bytes "
2147			 "from user address %p to kernel address %p", len,
2148			 user_addr, kptr);
2149		free(kptr, M_CTL);
2150		return (NULL);
2151	}
2152
2153	return (kptr);
2154}
2155
2156static void
2157ctl_free_args(int num_args, struct ctl_be_arg *args)
2158{
2159	int i;
2160
2161	if (args == NULL)
2162		return;
2163
2164	for (i = 0; i < num_args; i++) {
2165		free(args[i].kname, M_CTL);
2166		free(args[i].kvalue, M_CTL);
2167	}
2168
2169	free(args, M_CTL);
2170}
2171
2172static struct ctl_be_arg *
2173ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2174		char *error_str, size_t error_str_len)
2175{
2176	struct ctl_be_arg *args;
2177	int i;
2178
2179	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2180				error_str, error_str_len);
2181
2182	if (args == NULL)
2183		goto bailout;
2184
2185	for (i = 0; i < num_args; i++) {
2186		args[i].kname = NULL;
2187		args[i].kvalue = NULL;
2188	}
2189
2190	for (i = 0; i < num_args; i++) {
2191		uint8_t *tmpptr;
2192
2193		args[i].kname = ctl_copyin_alloc(args[i].name,
2194			args[i].namelen, error_str, error_str_len);
2195		if (args[i].kname == NULL)
2196			goto bailout;
2197
2198		if (args[i].kname[args[i].namelen - 1] != '\0') {
2199			snprintf(error_str, error_str_len, "Argument %d "
2200				 "name is not NUL-terminated", i);
2201			goto bailout;
2202		}
2203
2204		if (args[i].flags & CTL_BEARG_RD) {
2205			tmpptr = ctl_copyin_alloc(args[i].value,
2206				args[i].vallen, error_str, error_str_len);
2207			if (tmpptr == NULL)
2208				goto bailout;
2209			if ((args[i].flags & CTL_BEARG_ASCII)
2210			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2211				snprintf(error_str, error_str_len, "Argument "
2212				    "%d value is not NUL-terminated", i);
2213				goto bailout;
2214			}
2215			args[i].kvalue = tmpptr;
2216		} else {
2217			args[i].kvalue = malloc(args[i].vallen,
2218			    M_CTL, M_WAITOK | M_ZERO);
2219		}
2220	}
2221
2222	return (args);
2223bailout:
2224
2225	ctl_free_args(num_args, args);
2226
2227	return (NULL);
2228}
2229
2230static void
2231ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2232{
2233	int i;
2234
2235	for (i = 0; i < num_args; i++) {
2236		if (args[i].flags & CTL_BEARG_WR)
2237			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2238	}
2239}
2240
2241/*
2242 * Escape characters that are illegal or not recommended in XML.
2243 */
2244int
2245ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2246{
2247	char *end = str + size;
2248	int retval;
2249
2250	retval = 0;
2251
2252	for (; *str && str < end; str++) {
2253		switch (*str) {
2254		case '&':
2255			retval = sbuf_printf(sb, "&amp;");
2256			break;
2257		case '>':
2258			retval = sbuf_printf(sb, "&gt;");
2259			break;
2260		case '<':
2261			retval = sbuf_printf(sb, "&lt;");
2262			break;
2263		default:
2264			retval = sbuf_putc(sb, *str);
2265			break;
2266		}
2267
2268		if (retval != 0)
2269			break;
2270
2271	}
2272
2273	return (retval);
2274}
2275
2276static void
2277ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2278{
2279	struct scsi_vpd_id_descriptor *desc;
2280	int i;
2281
2282	if (id == NULL || id->len < 4)
2283		return;
2284	desc = (struct scsi_vpd_id_descriptor *)id->data;
2285	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2286	case SVPD_ID_TYPE_T10:
2287		sbuf_printf(sb, "t10.");
2288		break;
2289	case SVPD_ID_TYPE_EUI64:
2290		sbuf_printf(sb, "eui.");
2291		break;
2292	case SVPD_ID_TYPE_NAA:
2293		sbuf_printf(sb, "naa.");
2294		break;
2295	case SVPD_ID_TYPE_SCSI_NAME:
2296		break;
2297	}
2298	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2299	case SVPD_ID_CODESET_BINARY:
2300		for (i = 0; i < desc->length; i++)
2301			sbuf_printf(sb, "%02x", desc->identifier[i]);
2302		break;
2303	case SVPD_ID_CODESET_ASCII:
2304		sbuf_printf(sb, "%.*s", (int)desc->length,
2305		    (char *)desc->identifier);
2306		break;
2307	case SVPD_ID_CODESET_UTF8:
2308		sbuf_printf(sb, "%s", (char *)desc->identifier);
2309		break;
2310	}
2311}
2312
2313static int
2314ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2315	  struct thread *td)
2316{
2317	struct ctl_softc *softc;
2318	int retval;
2319
2320	softc = control_softc;
2321
2322	retval = 0;
2323
2324	switch (cmd) {
2325	case CTL_IO: {
2326		union ctl_io *io;
2327		void *pool_tmp;
2328
2329		/*
2330		 * If we haven't been "enabled", don't allow any SCSI I/O
2331		 * to this FETD.
2332		 */
2333		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2334			retval = EPERM;
2335			break;
2336		}
2337
2338		io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2339
2340		/*
2341		 * Need to save the pool reference so it doesn't get
2342		 * spammed by the user's ctl_io.
2343		 */
2344		pool_tmp = io->io_hdr.pool;
2345		memcpy(io, (void *)addr, sizeof(*io));
2346		io->io_hdr.pool = pool_tmp;
2347
2348		/*
2349		 * No status yet, so make sure the status is set properly.
2350		 */
2351		io->io_hdr.status = CTL_STATUS_NONE;
2352
2353		/*
2354		 * The user sets the initiator ID, target and LUN IDs.
2355		 */
2356		io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2357		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2358		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2359		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2360			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2361
2362		retval = ctl_ioctl_submit_wait(io);
2363
2364		if (retval != 0) {
2365			ctl_free_io(io);
2366			break;
2367		}
2368
2369		memcpy((void *)addr, io, sizeof(*io));
2370
2371		/* return this to our pool */
2372		ctl_free_io(io);
2373
2374		break;
2375	}
2376	case CTL_ENABLE_PORT:
2377	case CTL_DISABLE_PORT:
2378	case CTL_SET_PORT_WWNS: {
2379		struct ctl_port *port;
2380		struct ctl_port_entry *entry;
2381
2382		entry = (struct ctl_port_entry *)addr;
2383
2384		mtx_lock(&softc->ctl_lock);
2385		STAILQ_FOREACH(port, &softc->port_list, links) {
2386			int action, done;
2387
2388			action = 0;
2389			done = 0;
2390
2391			if ((entry->port_type == CTL_PORT_NONE)
2392			 && (entry->targ_port == port->targ_port)) {
2393				/*
2394				 * If the user only wants to enable or
2395				 * disable or set WWNs on a specific port,
2396				 * do the operation and we're done.
2397				 */
2398				action = 1;
2399				done = 1;
2400			} else if (entry->port_type & port->port_type) {
2401				/*
2402				 * Compare the user's type mask with the
2403				 * particular frontend type to see if we
2404				 * have a match.
2405				 */
2406				action = 1;
2407				done = 0;
2408
2409				/*
2410				 * Make sure the user isn't trying to set
2411				 * WWNs on multiple ports at the same time.
2412				 */
2413				if (cmd == CTL_SET_PORT_WWNS) {
2414					printf("%s: Can't set WWNs on "
2415					       "multiple ports\n", __func__);
2416					retval = EINVAL;
2417					break;
2418				}
2419			}
2420			if (action != 0) {
2421				/*
2422				 * XXX KDM we have to drop the lock here,
2423				 * because the online/offline operations
2424				 * can potentially block.  We need to
2425				 * reference count the frontends so they
2426				 * can't go away,
2427				 */
2428				mtx_unlock(&softc->ctl_lock);
2429
2430				if (cmd == CTL_ENABLE_PORT) {
2431					struct ctl_lun *lun;
2432
2433					STAILQ_FOREACH(lun, &softc->lun_list,
2434						       links) {
2435						port->lun_enable(port->targ_lun_arg,
2436						    lun->target,
2437						    lun->lun);
2438					}
2439
2440					ctl_port_online(port);
2441				} else if (cmd == CTL_DISABLE_PORT) {
2442					struct ctl_lun *lun;
2443
2444					ctl_port_offline(port);
2445
2446					STAILQ_FOREACH(lun, &softc->lun_list,
2447						       links) {
2448						port->lun_disable(
2449						    port->targ_lun_arg,
2450						    lun->target,
2451						    lun->lun);
2452					}
2453				}
2454
2455				mtx_lock(&softc->ctl_lock);
2456
2457				if (cmd == CTL_SET_PORT_WWNS)
2458					ctl_port_set_wwns(port,
2459					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2460					    1 : 0, entry->wwnn,
2461					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2462					    1 : 0, entry->wwpn);
2463			}
2464			if (done != 0)
2465				break;
2466		}
2467		mtx_unlock(&softc->ctl_lock);
2468		break;
2469	}
2470	case CTL_GET_PORT_LIST: {
2471		struct ctl_port *port;
2472		struct ctl_port_list *list;
2473		int i;
2474
2475		list = (struct ctl_port_list *)addr;
2476
2477		if (list->alloc_len != (list->alloc_num *
2478		    sizeof(struct ctl_port_entry))) {
2479			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2480			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2481			       "%zu\n", __func__, list->alloc_len,
2482			       list->alloc_num, sizeof(struct ctl_port_entry));
2483			retval = EINVAL;
2484			break;
2485		}
2486		list->fill_len = 0;
2487		list->fill_num = 0;
2488		list->dropped_num = 0;
2489		i = 0;
2490		mtx_lock(&softc->ctl_lock);
2491		STAILQ_FOREACH(port, &softc->port_list, links) {
2492			struct ctl_port_entry entry, *list_entry;
2493
2494			if (list->fill_num >= list->alloc_num) {
2495				list->dropped_num++;
2496				continue;
2497			}
2498
2499			entry.port_type = port->port_type;
2500			strlcpy(entry.port_name, port->port_name,
2501				sizeof(entry.port_name));
2502			entry.targ_port = port->targ_port;
2503			entry.physical_port = port->physical_port;
2504			entry.virtual_port = port->virtual_port;
2505			entry.wwnn = port->wwnn;
2506			entry.wwpn = port->wwpn;
2507			if (port->status & CTL_PORT_STATUS_ONLINE)
2508				entry.online = 1;
2509			else
2510				entry.online = 0;
2511
2512			list_entry = &list->entries[i];
2513
2514			retval = copyout(&entry, list_entry, sizeof(entry));
2515			if (retval != 0) {
2516				printf("%s: CTL_GET_PORT_LIST: copyout "
2517				       "returned %d\n", __func__, retval);
2518				break;
2519			}
2520			i++;
2521			list->fill_num++;
2522			list->fill_len += sizeof(entry);
2523		}
2524		mtx_unlock(&softc->ctl_lock);
2525
2526		/*
2527		 * If this is non-zero, we had a copyout fault, so there's
2528		 * probably no point in attempting to set the status inside
2529		 * the structure.
2530		 */
2531		if (retval != 0)
2532			break;
2533
2534		if (list->dropped_num > 0)
2535			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2536		else
2537			list->status = CTL_PORT_LIST_OK;
2538		break;
2539	}
2540	case CTL_DUMP_OOA: {
2541		struct ctl_lun *lun;
2542		union ctl_io *io;
2543		char printbuf[128];
2544		struct sbuf sb;
2545
2546		mtx_lock(&softc->ctl_lock);
2547		printf("Dumping OOA queues:\n");
2548		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2549			mtx_lock(&lun->lun_lock);
2550			for (io = (union ctl_io *)TAILQ_FIRST(
2551			     &lun->ooa_queue); io != NULL;
2552			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2553			     ooa_links)) {
2554				sbuf_new(&sb, printbuf, sizeof(printbuf),
2555					 SBUF_FIXEDLEN);
2556				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2557					    (intmax_t)lun->lun,
2558					    io->scsiio.tag_num,
2559					    (io->io_hdr.flags &
2560					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2561					    (io->io_hdr.flags &
2562					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2563					    (io->io_hdr.flags &
2564					    CTL_FLAG_ABORT) ? " ABORT" : "",
2565			                    (io->io_hdr.flags &
2566		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2567				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2568				sbuf_finish(&sb);
2569				printf("%s\n", sbuf_data(&sb));
2570			}
2571			mtx_unlock(&lun->lun_lock);
2572		}
2573		printf("OOA queues dump done\n");
2574		mtx_unlock(&softc->ctl_lock);
2575		break;
2576	}
2577	case CTL_GET_OOA: {
2578		struct ctl_lun *lun;
2579		struct ctl_ooa *ooa_hdr;
2580		struct ctl_ooa_entry *entries;
2581		uint32_t cur_fill_num;
2582
2583		ooa_hdr = (struct ctl_ooa *)addr;
2584
2585		if ((ooa_hdr->alloc_len == 0)
2586		 || (ooa_hdr->alloc_num == 0)) {
2587			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2588			       "must be non-zero\n", __func__,
2589			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2590			retval = EINVAL;
2591			break;
2592		}
2593
2594		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2595		    sizeof(struct ctl_ooa_entry))) {
2596			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2597			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2598			       __func__, ooa_hdr->alloc_len,
2599			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2600			retval = EINVAL;
2601			break;
2602		}
2603
2604		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2605		if (entries == NULL) {
2606			printf("%s: could not allocate %d bytes for OOA "
2607			       "dump\n", __func__, ooa_hdr->alloc_len);
2608			retval = ENOMEM;
2609			break;
2610		}
2611
2612		mtx_lock(&softc->ctl_lock);
2613		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2614		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2615		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2616			mtx_unlock(&softc->ctl_lock);
2617			free(entries, M_CTL);
2618			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2619			       __func__, (uintmax_t)ooa_hdr->lun_num);
2620			retval = EINVAL;
2621			break;
2622		}
2623
2624		cur_fill_num = 0;
2625
2626		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2627			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2628				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2629					ooa_hdr, entries);
2630				if (retval != 0)
2631					break;
2632			}
2633			if (retval != 0) {
2634				mtx_unlock(&softc->ctl_lock);
2635				free(entries, M_CTL);
2636				break;
2637			}
2638		} else {
2639			lun = softc->ctl_luns[ooa_hdr->lun_num];
2640
2641			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2642						    entries);
2643		}
2644		mtx_unlock(&softc->ctl_lock);
2645
2646		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2647		ooa_hdr->fill_len = ooa_hdr->fill_num *
2648			sizeof(struct ctl_ooa_entry);
2649		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2650		if (retval != 0) {
2651			printf("%s: error copying out %d bytes for OOA dump\n",
2652			       __func__, ooa_hdr->fill_len);
2653		}
2654
2655		getbintime(&ooa_hdr->cur_bt);
2656
2657		if (cur_fill_num > ooa_hdr->alloc_num) {
2658			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2659			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2660		} else {
2661			ooa_hdr->dropped_num = 0;
2662			ooa_hdr->status = CTL_OOA_OK;
2663		}
2664
2665		free(entries, M_CTL);
2666		break;
2667	}
2668	case CTL_CHECK_OOA: {
2669		union ctl_io *io;
2670		struct ctl_lun *lun;
2671		struct ctl_ooa_info *ooa_info;
2672
2673
2674		ooa_info = (struct ctl_ooa_info *)addr;
2675
2676		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2677			ooa_info->status = CTL_OOA_INVALID_LUN;
2678			break;
2679		}
2680		mtx_lock(&softc->ctl_lock);
2681		lun = softc->ctl_luns[ooa_info->lun_id];
2682		if (lun == NULL) {
2683			mtx_unlock(&softc->ctl_lock);
2684			ooa_info->status = CTL_OOA_INVALID_LUN;
2685			break;
2686		}
2687		mtx_lock(&lun->lun_lock);
2688		mtx_unlock(&softc->ctl_lock);
2689		ooa_info->num_entries = 0;
2690		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2691		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2692		     &io->io_hdr, ooa_links)) {
2693			ooa_info->num_entries++;
2694		}
2695		mtx_unlock(&lun->lun_lock);
2696
2697		ooa_info->status = CTL_OOA_SUCCESS;
2698
2699		break;
2700	}
2701	case CTL_HARD_START:
2702	case CTL_HARD_STOP: {
2703		struct ctl_fe_ioctl_startstop_info ss_info;
2704		struct cfi_metatask *metatask;
2705		struct mtx hs_mtx;
2706
2707		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2708
2709		cv_init(&ss_info.sem, "hard start/stop cv" );
2710
2711		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2712		if (metatask == NULL) {
2713			retval = ENOMEM;
2714			mtx_destroy(&hs_mtx);
2715			break;
2716		}
2717
2718		if (cmd == CTL_HARD_START)
2719			metatask->tasktype = CFI_TASK_STARTUP;
2720		else
2721			metatask->tasktype = CFI_TASK_SHUTDOWN;
2722
2723		metatask->callback = ctl_ioctl_hard_startstop_callback;
2724		metatask->callback_arg = &ss_info;
2725
2726		cfi_action(metatask);
2727
2728		/* Wait for the callback */
2729		mtx_lock(&hs_mtx);
2730		cv_wait_sig(&ss_info.sem, &hs_mtx);
2731		mtx_unlock(&hs_mtx);
2732
2733		/*
2734		 * All information has been copied from the metatask by the
2735		 * time cv_broadcast() is called, so we free the metatask here.
2736		 */
2737		cfi_free_metatask(metatask);
2738
2739		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2740
2741		mtx_destroy(&hs_mtx);
2742		break;
2743	}
2744	case CTL_BBRREAD: {
2745		struct ctl_bbrread_info *bbr_info;
2746		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2747		struct mtx bbr_mtx;
2748		struct cfi_metatask *metatask;
2749
2750		bbr_info = (struct ctl_bbrread_info *)addr;
2751
2752		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2753
2754		bzero(&bbr_mtx, sizeof(bbr_mtx));
2755		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2756
2757		fe_bbr_info.bbr_info = bbr_info;
2758		fe_bbr_info.lock = &bbr_mtx;
2759
2760		cv_init(&fe_bbr_info.sem, "BBR read cv");
2761		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2762
2763		if (metatask == NULL) {
2764			mtx_destroy(&bbr_mtx);
2765			cv_destroy(&fe_bbr_info.sem);
2766			retval = ENOMEM;
2767			break;
2768		}
2769		metatask->tasktype = CFI_TASK_BBRREAD;
2770		metatask->callback = ctl_ioctl_bbrread_callback;
2771		metatask->callback_arg = &fe_bbr_info;
2772		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2773		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2774		metatask->taskinfo.bbrread.len = bbr_info->len;
2775
2776		cfi_action(metatask);
2777
2778		mtx_lock(&bbr_mtx);
2779		while (fe_bbr_info.wakeup_done == 0)
2780			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2781		mtx_unlock(&bbr_mtx);
2782
2783		bbr_info->status = metatask->status;
2784		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2785		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2786		memcpy(&bbr_info->sense_data,
2787		       &metatask->taskinfo.bbrread.sense_data,
2788		       ctl_min(sizeof(bbr_info->sense_data),
2789			       sizeof(metatask->taskinfo.bbrread.sense_data)));
2790
2791		cfi_free_metatask(metatask);
2792
2793		mtx_destroy(&bbr_mtx);
2794		cv_destroy(&fe_bbr_info.sem);
2795
2796		break;
2797	}
2798	case CTL_DELAY_IO: {
2799		struct ctl_io_delay_info *delay_info;
2800#ifdef CTL_IO_DELAY
2801		struct ctl_lun *lun;
2802#endif /* CTL_IO_DELAY */
2803
2804		delay_info = (struct ctl_io_delay_info *)addr;
2805
2806#ifdef CTL_IO_DELAY
2807		mtx_lock(&softc->ctl_lock);
2808
2809		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2810		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2811			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2812		} else {
2813			lun = softc->ctl_luns[delay_info->lun_id];
2814			mtx_lock(&lun->lun_lock);
2815
2816			delay_info->status = CTL_DELAY_STATUS_OK;
2817
2818			switch (delay_info->delay_type) {
2819			case CTL_DELAY_TYPE_CONT:
2820				break;
2821			case CTL_DELAY_TYPE_ONESHOT:
2822				break;
2823			default:
2824				delay_info->status =
2825					CTL_DELAY_STATUS_INVALID_TYPE;
2826				break;
2827			}
2828
2829			switch (delay_info->delay_loc) {
2830			case CTL_DELAY_LOC_DATAMOVE:
2831				lun->delay_info.datamove_type =
2832					delay_info->delay_type;
2833				lun->delay_info.datamove_delay =
2834					delay_info->delay_secs;
2835				break;
2836			case CTL_DELAY_LOC_DONE:
2837				lun->delay_info.done_type =
2838					delay_info->delay_type;
2839				lun->delay_info.done_delay =
2840					delay_info->delay_secs;
2841				break;
2842			default:
2843				delay_info->status =
2844					CTL_DELAY_STATUS_INVALID_LOC;
2845				break;
2846			}
2847			mtx_unlock(&lun->lun_lock);
2848		}
2849
2850		mtx_unlock(&softc->ctl_lock);
2851#else
2852		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2853#endif /* CTL_IO_DELAY */
2854		break;
2855	}
2856	case CTL_REALSYNC_SET: {
2857		int *syncstate;
2858
2859		syncstate = (int *)addr;
2860
2861		mtx_lock(&softc->ctl_lock);
2862		switch (*syncstate) {
2863		case 0:
2864			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2865			break;
2866		case 1:
2867			softc->flags |= CTL_FLAG_REAL_SYNC;
2868			break;
2869		default:
2870			retval = EINVAL;
2871			break;
2872		}
2873		mtx_unlock(&softc->ctl_lock);
2874		break;
2875	}
2876	case CTL_REALSYNC_GET: {
2877		int *syncstate;
2878
2879		syncstate = (int*)addr;
2880
2881		mtx_lock(&softc->ctl_lock);
2882		if (softc->flags & CTL_FLAG_REAL_SYNC)
2883			*syncstate = 1;
2884		else
2885			*syncstate = 0;
2886		mtx_unlock(&softc->ctl_lock);
2887
2888		break;
2889	}
2890	case CTL_SETSYNC:
2891	case CTL_GETSYNC: {
2892		struct ctl_sync_info *sync_info;
2893		struct ctl_lun *lun;
2894
2895		sync_info = (struct ctl_sync_info *)addr;
2896
2897		mtx_lock(&softc->ctl_lock);
2898		lun = softc->ctl_luns[sync_info->lun_id];
2899		if (lun == NULL) {
2900			mtx_unlock(&softc->ctl_lock);
2901			sync_info->status = CTL_GS_SYNC_NO_LUN;
2902		}
2903		/*
2904		 * Get or set the sync interval.  We're not bounds checking
2905		 * in the set case, hopefully the user won't do something
2906		 * silly.
2907		 */
2908		mtx_lock(&lun->lun_lock);
2909		mtx_unlock(&softc->ctl_lock);
2910		if (cmd == CTL_GETSYNC)
2911			sync_info->sync_interval = lun->sync_interval;
2912		else
2913			lun->sync_interval = sync_info->sync_interval;
2914		mtx_unlock(&lun->lun_lock);
2915
2916		sync_info->status = CTL_GS_SYNC_OK;
2917
2918		break;
2919	}
2920	case CTL_GETSTATS: {
2921		struct ctl_stats *stats;
2922		struct ctl_lun *lun;
2923		int i;
2924
2925		stats = (struct ctl_stats *)addr;
2926
2927		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2928		     stats->alloc_len) {
2929			stats->status = CTL_SS_NEED_MORE_SPACE;
2930			stats->num_luns = softc->num_luns;
2931			break;
2932		}
2933		/*
2934		 * XXX KDM no locking here.  If the LUN list changes,
2935		 * things can blow up.
2936		 */
2937		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2938		     i++, lun = STAILQ_NEXT(lun, links)) {
2939			retval = copyout(&lun->stats, &stats->lun_stats[i],
2940					 sizeof(lun->stats));
2941			if (retval != 0)
2942				break;
2943		}
2944		stats->num_luns = softc->num_luns;
2945		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2946				 softc->num_luns;
2947		stats->status = CTL_SS_OK;
2948#ifdef CTL_TIME_IO
2949		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2950#else
2951		stats->flags = CTL_STATS_FLAG_NONE;
2952#endif
2953		getnanouptime(&stats->timestamp);
2954		break;
2955	}
2956	case CTL_ERROR_INJECT: {
2957		struct ctl_error_desc *err_desc, *new_err_desc;
2958		struct ctl_lun *lun;
2959
2960		err_desc = (struct ctl_error_desc *)addr;
2961
2962		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2963				      M_WAITOK | M_ZERO);
2964		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2965
2966		mtx_lock(&softc->ctl_lock);
2967		lun = softc->ctl_luns[err_desc->lun_id];
2968		if (lun == NULL) {
2969			mtx_unlock(&softc->ctl_lock);
2970			free(new_err_desc, M_CTL);
2971			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2972			       __func__, (uintmax_t)err_desc->lun_id);
2973			retval = EINVAL;
2974			break;
2975		}
2976		mtx_lock(&lun->lun_lock);
2977		mtx_unlock(&softc->ctl_lock);
2978
2979		/*
2980		 * We could do some checking here to verify the validity
2981		 * of the request, but given the complexity of error
2982		 * injection requests, the checking logic would be fairly
2983		 * complex.
2984		 *
2985		 * For now, if the request is invalid, it just won't get
2986		 * executed and might get deleted.
2987		 */
2988		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2989
2990		/*
2991		 * XXX KDM check to make sure the serial number is unique,
2992		 * in case we somehow manage to wrap.  That shouldn't
2993		 * happen for a very long time, but it's the right thing to
2994		 * do.
2995		 */
2996		new_err_desc->serial = lun->error_serial;
2997		err_desc->serial = lun->error_serial;
2998		lun->error_serial++;
2999
3000		mtx_unlock(&lun->lun_lock);
3001		break;
3002	}
3003	case CTL_ERROR_INJECT_DELETE: {
3004		struct ctl_error_desc *delete_desc, *desc, *desc2;
3005		struct ctl_lun *lun;
3006		int delete_done;
3007
3008		delete_desc = (struct ctl_error_desc *)addr;
3009		delete_done = 0;
3010
3011		mtx_lock(&softc->ctl_lock);
3012		lun = softc->ctl_luns[delete_desc->lun_id];
3013		if (lun == NULL) {
3014			mtx_unlock(&softc->ctl_lock);
3015			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
3016			       __func__, (uintmax_t)delete_desc->lun_id);
3017			retval = EINVAL;
3018			break;
3019		}
3020		mtx_lock(&lun->lun_lock);
3021		mtx_unlock(&softc->ctl_lock);
3022		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
3023			if (desc->serial != delete_desc->serial)
3024				continue;
3025
3026			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
3027				      links);
3028			free(desc, M_CTL);
3029			delete_done = 1;
3030		}
3031		mtx_unlock(&lun->lun_lock);
3032		if (delete_done == 0) {
3033			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
3034			       "error serial %ju on LUN %u\n", __func__,
3035			       delete_desc->serial, delete_desc->lun_id);
3036			retval = EINVAL;
3037			break;
3038		}
3039		break;
3040	}
3041	case CTL_DUMP_STRUCTS: {
3042		int i, j, k, idx;
3043		struct ctl_port *port;
3044		struct ctl_frontend *fe;
3045
3046		mtx_lock(&softc->ctl_lock);
3047		printf("CTL Persistent Reservation information start:\n");
3048		for (i = 0; i < CTL_MAX_LUNS; i++) {
3049			struct ctl_lun *lun;
3050
3051			lun = softc->ctl_luns[i];
3052
3053			if ((lun == NULL)
3054			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
3055				continue;
3056
3057			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
3058				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
3059					idx = j * CTL_MAX_INIT_PER_PORT + k;
3060					if (lun->pr_keys[idx] == 0)
3061						continue;
3062					printf("  LUN %d port %d iid %d key "
3063					       "%#jx\n", i, j, k,
3064					       (uintmax_t)lun->pr_keys[idx]);
3065				}
3066			}
3067		}
3068		printf("CTL Persistent Reservation information end\n");
3069		printf("CTL Ports:\n");
3070		STAILQ_FOREACH(port, &softc->port_list, links) {
3071			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3072			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3073			       port->frontend->name, port->port_type,
3074			       port->physical_port, port->virtual_port,
3075			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3076			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3077				if (port->wwpn_iid[j].in_use == 0 &&
3078				    port->wwpn_iid[j].wwpn == 0 &&
3079				    port->wwpn_iid[j].name == NULL)
3080					continue;
3081
3082				printf("    iid %u use %d WWPN %#jx '%s'\n",
3083				    j, port->wwpn_iid[j].in_use,
3084				    (uintmax_t)port->wwpn_iid[j].wwpn,
3085				    port->wwpn_iid[j].name);
3086			}
3087		}
3088		printf("CTL Port information end\n");
3089		mtx_unlock(&softc->ctl_lock);
3090		/*
3091		 * XXX KDM calling this without a lock.  We'd likely want
3092		 * to drop the lock before calling the frontend's dump
3093		 * routine anyway.
3094		 */
3095		printf("CTL Frontends:\n");
3096		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3097			printf("  Frontend '%s'\n", fe->name);
3098			if (fe->fe_dump != NULL)
3099				fe->fe_dump();
3100		}
3101		printf("CTL Frontend information end\n");
3102		break;
3103	}
3104	case CTL_LUN_REQ: {
3105		struct ctl_lun_req *lun_req;
3106		struct ctl_backend_driver *backend;
3107
3108		lun_req = (struct ctl_lun_req *)addr;
3109
3110		backend = ctl_backend_find(lun_req->backend);
3111		if (backend == NULL) {
3112			lun_req->status = CTL_LUN_ERROR;
3113			snprintf(lun_req->error_str,
3114				 sizeof(lun_req->error_str),
3115				 "Backend \"%s\" not found.",
3116				 lun_req->backend);
3117			break;
3118		}
3119		if (lun_req->num_be_args > 0) {
3120			lun_req->kern_be_args = ctl_copyin_args(
3121				lun_req->num_be_args,
3122				lun_req->be_args,
3123				lun_req->error_str,
3124				sizeof(lun_req->error_str));
3125			if (lun_req->kern_be_args == NULL) {
3126				lun_req->status = CTL_LUN_ERROR;
3127				break;
3128			}
3129		}
3130
3131		retval = backend->ioctl(dev, cmd, addr, flag, td);
3132
3133		if (lun_req->num_be_args > 0) {
3134			ctl_copyout_args(lun_req->num_be_args,
3135				      lun_req->kern_be_args);
3136			ctl_free_args(lun_req->num_be_args,
3137				      lun_req->kern_be_args);
3138		}
3139		break;
3140	}
3141	case CTL_LUN_LIST: {
3142		struct sbuf *sb;
3143		struct ctl_lun *lun;
3144		struct ctl_lun_list *list;
3145		struct ctl_option *opt;
3146
3147		list = (struct ctl_lun_list *)addr;
3148
3149		/*
3150		 * Allocate a fixed length sbuf here, based on the length
3151		 * of the user's buffer.  We could allocate an auto-extending
3152		 * buffer, and then tell the user how much larger our
3153		 * amount of data is than his buffer, but that presents
3154		 * some problems:
3155		 *
3156		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3157		 *     we can't hold a lock while calling them with an
3158		 *     auto-extending buffer.
3159 		 *
3160		 * 2.  There is not currently a LUN reference counting
3161		 *     mechanism, outside of outstanding transactions on
3162		 *     the LUN's OOA queue.  So a LUN could go away on us
3163		 *     while we're getting the LUN number, backend-specific
3164		 *     information, etc.  Thus, given the way things
3165		 *     currently work, we need to hold the CTL lock while
3166		 *     grabbing LUN information.
3167		 *
3168		 * So, from the user's standpoint, the best thing to do is
3169		 * allocate what he thinks is a reasonable buffer length,
3170		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3171		 * double the buffer length and try again.  (And repeat
3172		 * that until he succeeds.)
3173		 */
3174		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3175		if (sb == NULL) {
3176			list->status = CTL_LUN_LIST_ERROR;
3177			snprintf(list->error_str, sizeof(list->error_str),
3178				 "Unable to allocate %d bytes for LUN list",
3179				 list->alloc_len);
3180			break;
3181		}
3182
3183		sbuf_printf(sb, "<ctllunlist>\n");
3184
3185		mtx_lock(&softc->ctl_lock);
3186		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3187			mtx_lock(&lun->lun_lock);
3188			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3189					     (uintmax_t)lun->lun);
3190
3191			/*
3192			 * Bail out as soon as we see that we've overfilled
3193			 * the buffer.
3194			 */
3195			if (retval != 0)
3196				break;
3197
3198			retval = sbuf_printf(sb, "\t<backend_type>%s"
3199					     "</backend_type>\n",
3200					     (lun->backend == NULL) ?  "none" :
3201					     lun->backend->name);
3202
3203			if (retval != 0)
3204				break;
3205
3206			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3207					     lun->be_lun->lun_type);
3208
3209			if (retval != 0)
3210				break;
3211
3212			if (lun->backend == NULL) {
3213				retval = sbuf_printf(sb, "</lun>\n");
3214				if (retval != 0)
3215					break;
3216				continue;
3217			}
3218
3219			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3220					     (lun->be_lun->maxlba > 0) ?
3221					     lun->be_lun->maxlba + 1 : 0);
3222
3223			if (retval != 0)
3224				break;
3225
3226			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3227					     lun->be_lun->blocksize);
3228
3229			if (retval != 0)
3230				break;
3231
3232			retval = sbuf_printf(sb, "\t<serial_number>");
3233
3234			if (retval != 0)
3235				break;
3236
3237			retval = ctl_sbuf_printf_esc(sb,
3238			    lun->be_lun->serial_num,
3239			    sizeof(lun->be_lun->serial_num));
3240
3241			if (retval != 0)
3242				break;
3243
3244			retval = sbuf_printf(sb, "</serial_number>\n");
3245
3246			if (retval != 0)
3247				break;
3248
3249			retval = sbuf_printf(sb, "\t<device_id>");
3250
3251			if (retval != 0)
3252				break;
3253
3254			retval = ctl_sbuf_printf_esc(sb,
3255			    lun->be_lun->device_id,
3256			    sizeof(lun->be_lun->device_id));
3257
3258			if (retval != 0)
3259				break;
3260
3261			retval = sbuf_printf(sb, "</device_id>\n");
3262
3263			if (retval != 0)
3264				break;
3265
3266			if (lun->backend->lun_info != NULL) {
3267				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3268				if (retval != 0)
3269					break;
3270			}
3271			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3272				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3273				    opt->name, opt->value, opt->name);
3274				if (retval != 0)
3275					break;
3276			}
3277
3278			retval = sbuf_printf(sb, "</lun>\n");
3279
3280			if (retval != 0)
3281				break;
3282			mtx_unlock(&lun->lun_lock);
3283		}
3284		if (lun != NULL)
3285			mtx_unlock(&lun->lun_lock);
3286		mtx_unlock(&softc->ctl_lock);
3287
3288		if ((retval != 0)
3289		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3290			retval = 0;
3291			sbuf_delete(sb);
3292			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3293			snprintf(list->error_str, sizeof(list->error_str),
3294				 "Out of space, %d bytes is too small",
3295				 list->alloc_len);
3296			break;
3297		}
3298
3299		sbuf_finish(sb);
3300
3301		retval = copyout(sbuf_data(sb), list->lun_xml,
3302				 sbuf_len(sb) + 1);
3303
3304		list->fill_len = sbuf_len(sb) + 1;
3305		list->status = CTL_LUN_LIST_OK;
3306		sbuf_delete(sb);
3307		break;
3308	}
3309	case CTL_ISCSI: {
3310		struct ctl_iscsi *ci;
3311		struct ctl_frontend *fe;
3312
3313		ci = (struct ctl_iscsi *)addr;
3314
3315		fe = ctl_frontend_find("iscsi");
3316		if (fe == NULL) {
3317			ci->status = CTL_ISCSI_ERROR;
3318			snprintf(ci->error_str, sizeof(ci->error_str),
3319			    "Frontend \"iscsi\" not found.");
3320			break;
3321		}
3322
3323		retval = fe->ioctl(dev, cmd, addr, flag, td);
3324		break;
3325	}
3326	case CTL_PORT_REQ: {
3327		struct ctl_req *req;
3328		struct ctl_frontend *fe;
3329
3330		req = (struct ctl_req *)addr;
3331
3332		fe = ctl_frontend_find(req->driver);
3333		if (fe == NULL) {
3334			req->status = CTL_LUN_ERROR;
3335			snprintf(req->error_str, sizeof(req->error_str),
3336			    "Frontend \"%s\" not found.", req->driver);
3337			break;
3338		}
3339		if (req->num_args > 0) {
3340			req->kern_args = ctl_copyin_args(req->num_args,
3341			    req->args, req->error_str, sizeof(req->error_str));
3342			if (req->kern_args == NULL) {
3343				req->status = CTL_LUN_ERROR;
3344				break;
3345			}
3346		}
3347
3348		retval = fe->ioctl(dev, cmd, addr, flag, td);
3349
3350		if (req->num_args > 0) {
3351			ctl_copyout_args(req->num_args, req->kern_args);
3352			ctl_free_args(req->num_args, req->kern_args);
3353		}
3354		break;
3355	}
3356	case CTL_PORT_LIST: {
3357		struct sbuf *sb;
3358		struct ctl_port *port;
3359		struct ctl_lun_list *list;
3360		struct ctl_option *opt;
3361		int j;
3362
3363		list = (struct ctl_lun_list *)addr;
3364
3365		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3366		if (sb == NULL) {
3367			list->status = CTL_LUN_LIST_ERROR;
3368			snprintf(list->error_str, sizeof(list->error_str),
3369				 "Unable to allocate %d bytes for LUN list",
3370				 list->alloc_len);
3371			break;
3372		}
3373
3374		sbuf_printf(sb, "<ctlportlist>\n");
3375
3376		mtx_lock(&softc->ctl_lock);
3377		STAILQ_FOREACH(port, &softc->port_list, links) {
3378			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3379					     (uintmax_t)port->targ_port);
3380
3381			/*
3382			 * Bail out as soon as we see that we've overfilled
3383			 * the buffer.
3384			 */
3385			if (retval != 0)
3386				break;
3387
3388			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3389			    "</frontend_type>\n", port->frontend->name);
3390			if (retval != 0)
3391				break;
3392
3393			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3394					     port->port_type);
3395			if (retval != 0)
3396				break;
3397
3398			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3399			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3400			if (retval != 0)
3401				break;
3402
3403			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3404			    port->port_name);
3405			if (retval != 0)
3406				break;
3407
3408			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3409			    port->physical_port);
3410			if (retval != 0)
3411				break;
3412
3413			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3414			    port->virtual_port);
3415			if (retval != 0)
3416				break;
3417
3418			if (port->target_devid != NULL) {
3419				sbuf_printf(sb, "\t<target>");
3420				ctl_id_sbuf(port->target_devid, sb);
3421				sbuf_printf(sb, "</target>\n");
3422			}
3423
3424			if (port->port_devid != NULL) {
3425				sbuf_printf(sb, "\t<port>");
3426				ctl_id_sbuf(port->port_devid, sb);
3427				sbuf_printf(sb, "</port>\n");
3428			}
3429
3430			if (port->port_info != NULL) {
3431				retval = port->port_info(port->onoff_arg, sb);
3432				if (retval != 0)
3433					break;
3434			}
3435			STAILQ_FOREACH(opt, &port->options, links) {
3436				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3437				    opt->name, opt->value, opt->name);
3438				if (retval != 0)
3439					break;
3440			}
3441
3442			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3443				if (port->wwpn_iid[j].in_use == 0 ||
3444				    (port->wwpn_iid[j].wwpn == 0 &&
3445				     port->wwpn_iid[j].name == NULL))
3446					continue;
3447
3448				if (port->wwpn_iid[j].name != NULL)
3449					retval = sbuf_printf(sb,
3450					    "\t<initiator>%u %s</initiator>\n",
3451					    j, port->wwpn_iid[j].name);
3452				else
3453					retval = sbuf_printf(sb,
3454					    "\t<initiator>%u naa.%08jx</initiator>\n",
3455					    j, port->wwpn_iid[j].wwpn);
3456				if (retval != 0)
3457					break;
3458			}
3459			if (retval != 0)
3460				break;
3461
3462			retval = sbuf_printf(sb, "</targ_port>\n");
3463			if (retval != 0)
3464				break;
3465		}
3466		mtx_unlock(&softc->ctl_lock);
3467
3468		if ((retval != 0)
3469		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3470			retval = 0;
3471			sbuf_delete(sb);
3472			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3473			snprintf(list->error_str, sizeof(list->error_str),
3474				 "Out of space, %d bytes is too small",
3475				 list->alloc_len);
3476			break;
3477		}
3478
3479		sbuf_finish(sb);
3480
3481		retval = copyout(sbuf_data(sb), list->lun_xml,
3482				 sbuf_len(sb) + 1);
3483
3484		list->fill_len = sbuf_len(sb) + 1;
3485		list->status = CTL_LUN_LIST_OK;
3486		sbuf_delete(sb);
3487		break;
3488	}
3489	default: {
3490		/* XXX KDM should we fix this? */
3491#if 0
3492		struct ctl_backend_driver *backend;
3493		unsigned int type;
3494		int found;
3495
3496		found = 0;
3497
3498		/*
3499		 * We encode the backend type as the ioctl type for backend
3500		 * ioctls.  So parse it out here, and then search for a
3501		 * backend of this type.
3502		 */
3503		type = _IOC_TYPE(cmd);
3504
3505		STAILQ_FOREACH(backend, &softc->be_list, links) {
3506			if (backend->type == type) {
3507				found = 1;
3508				break;
3509			}
3510		}
3511		if (found == 0) {
3512			printf("ctl: unknown ioctl command %#lx or backend "
3513			       "%d\n", cmd, type);
3514			retval = EINVAL;
3515			break;
3516		}
3517		retval = backend->ioctl(dev, cmd, addr, flag, td);
3518#endif
3519		retval = ENOTTY;
3520		break;
3521	}
3522	}
3523	return (retval);
3524}
3525
3526uint32_t
3527ctl_get_initindex(struct ctl_nexus *nexus)
3528{
3529	if (nexus->targ_port < CTL_MAX_PORTS)
3530		return (nexus->initid.id +
3531			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3532	else
3533		return (nexus->initid.id +
3534		       ((nexus->targ_port - CTL_MAX_PORTS) *
3535			CTL_MAX_INIT_PER_PORT));
3536}
3537
3538uint32_t
3539ctl_get_resindex(struct ctl_nexus *nexus)
3540{
3541	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3542}
3543
3544uint32_t
3545ctl_port_idx(int port_num)
3546{
3547	if (port_num < CTL_MAX_PORTS)
3548		return(port_num);
3549	else
3550		return(port_num - CTL_MAX_PORTS);
3551}
3552
3553static uint32_t
3554ctl_map_lun(int port_num, uint32_t lun_id)
3555{
3556	struct ctl_port *port;
3557
3558	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3559	if (port == NULL)
3560		return (UINT32_MAX);
3561	if (port->lun_map == NULL)
3562		return (lun_id);
3563	return (port->lun_map(port->targ_lun_arg, lun_id));
3564}
3565
3566static uint32_t
3567ctl_map_lun_back(int port_num, uint32_t lun_id)
3568{
3569	struct ctl_port *port;
3570	uint32_t i;
3571
3572	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3573	if (port->lun_map == NULL)
3574		return (lun_id);
3575	for (i = 0; i < CTL_MAX_LUNS; i++) {
3576		if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3577			return (i);
3578	}
3579	return (UINT32_MAX);
3580}
3581
3582/*
3583 * Note:  This only works for bitmask sizes that are at least 32 bits, and
3584 * that are a power of 2.
3585 */
3586int
3587ctl_ffz(uint32_t *mask, uint32_t size)
3588{
3589	uint32_t num_chunks, num_pieces;
3590	int i, j;
3591
3592	num_chunks = (size >> 5);
3593	if (num_chunks == 0)
3594		num_chunks++;
3595	num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3596
3597	for (i = 0; i < num_chunks; i++) {
3598		for (j = 0; j < num_pieces; j++) {
3599			if ((mask[i] & (1 << j)) == 0)
3600				return ((i << 5) + j);
3601		}
3602	}
3603
3604	return (-1);
3605}
3606
3607int
3608ctl_set_mask(uint32_t *mask, uint32_t bit)
3609{
3610	uint32_t chunk, piece;
3611
3612	chunk = bit >> 5;
3613	piece = bit % (sizeof(uint32_t) * 8);
3614
3615	if ((mask[chunk] & (1 << piece)) != 0)
3616		return (-1);
3617	else
3618		mask[chunk] |= (1 << piece);
3619
3620	return (0);
3621}
3622
3623int
3624ctl_clear_mask(uint32_t *mask, uint32_t bit)
3625{
3626	uint32_t chunk, piece;
3627
3628	chunk = bit >> 5;
3629	piece = bit % (sizeof(uint32_t) * 8);
3630
3631	if ((mask[chunk] & (1 << piece)) == 0)
3632		return (-1);
3633	else
3634		mask[chunk] &= ~(1 << piece);
3635
3636	return (0);
3637}
3638
3639int
3640ctl_is_set(uint32_t *mask, uint32_t bit)
3641{
3642	uint32_t chunk, piece;
3643
3644	chunk = bit >> 5;
3645	piece = bit % (sizeof(uint32_t) * 8);
3646
3647	if ((mask[chunk] & (1 << piece)) == 0)
3648		return (0);
3649	else
3650		return (1);
3651}
3652
3653#ifdef unused
3654/*
3655 * The bus, target and lun are optional, they can be filled in later.
3656 * can_wait is used to determine whether we can wait on the malloc or not.
3657 */
3658union ctl_io*
3659ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3660	      uint32_t targ_lun, int can_wait)
3661{
3662	union ctl_io *io;
3663
3664	if (can_wait)
3665		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3666	else
3667		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3668
3669	if (io != NULL) {
3670		io->io_hdr.io_type = io_type;
3671		io->io_hdr.targ_port = targ_port;
3672		/*
3673		 * XXX KDM this needs to change/go away.  We need to move
3674		 * to a preallocated pool of ctl_scsiio structures.
3675		 */
3676		io->io_hdr.nexus.targ_target.id = targ_target;
3677		io->io_hdr.nexus.targ_lun = targ_lun;
3678	}
3679
3680	return (io);
3681}
3682
3683void
3684ctl_kfree_io(union ctl_io *io)
3685{
3686	free(io, M_CTL);
3687}
3688#endif /* unused */
3689
3690/*
3691 * ctl_softc, pool_name, total_ctl_io are passed in.
3692 * npool is passed out.
3693 */
3694int
3695ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3696		uint32_t total_ctl_io, void **npool)
3697{
3698#ifdef IO_POOLS
3699	struct ctl_io_pool *pool;
3700
3701	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3702					    M_NOWAIT | M_ZERO);
3703	if (pool == NULL)
3704		return (ENOMEM);
3705
3706	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3707	pool->ctl_softc = ctl_softc;
3708	pool->zone = uma_zsecond_create(pool->name, NULL,
3709	    NULL, NULL, NULL, ctl_softc->io_zone);
3710	/* uma_prealloc(pool->zone, total_ctl_io); */
3711
3712	*npool = pool;
3713#else
3714	*npool = ctl_softc->io_zone;
3715#endif
3716	return (0);
3717}
3718
3719void
3720ctl_pool_free(struct ctl_io_pool *pool)
3721{
3722
3723	if (pool == NULL)
3724		return;
3725
3726#ifdef IO_POOLS
3727	uma_zdestroy(pool->zone);
3728	free(pool, M_CTL);
3729#endif
3730}
3731
3732union ctl_io *
3733ctl_alloc_io(void *pool_ref)
3734{
3735	union ctl_io *io;
3736#ifdef IO_POOLS
3737	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3738
3739	io = uma_zalloc(pool->zone, M_WAITOK);
3740#else
3741	io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3742#endif
3743	if (io != NULL)
3744		io->io_hdr.pool = pool_ref;
3745	return (io);
3746}
3747
3748union ctl_io *
3749ctl_alloc_io_nowait(void *pool_ref)
3750{
3751	union ctl_io *io;
3752#ifdef IO_POOLS
3753	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3754
3755	io = uma_zalloc(pool->zone, M_NOWAIT);
3756#else
3757	io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3758#endif
3759	if (io != NULL)
3760		io->io_hdr.pool = pool_ref;
3761	return (io);
3762}
3763
3764void
3765ctl_free_io(union ctl_io *io)
3766{
3767#ifdef IO_POOLS
3768	struct ctl_io_pool *pool;
3769#endif
3770
3771	if (io == NULL)
3772		return;
3773
3774#ifdef IO_POOLS
3775	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3776	uma_zfree(pool->zone, io);
3777#else
3778	uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3779#endif
3780}
3781
3782void
3783ctl_zero_io(union ctl_io *io)
3784{
3785	void *pool_ref;
3786
3787	if (io == NULL)
3788		return;
3789
3790	/*
3791	 * May need to preserve linked list pointers at some point too.
3792	 */
3793	pool_ref = io->io_hdr.pool;
3794	memset(io, 0, sizeof(*io));
3795	io->io_hdr.pool = pool_ref;
3796}
3797
3798/*
3799 * This routine is currently used for internal copies of ctl_ios that need
3800 * to persist for some reason after we've already returned status to the
3801 * FETD.  (Thus the flag set.)
3802 *
3803 * XXX XXX
3804 * Note that this makes a blind copy of all fields in the ctl_io, except
3805 * for the pool reference.  This includes any memory that has been
3806 * allocated!  That memory will no longer be valid after done has been
3807 * called, so this would be VERY DANGEROUS for command that actually does
3808 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3809 * start and stop commands, which don't transfer any data, so this is not a
3810 * problem.  If it is used for anything else, the caller would also need to
3811 * allocate data buffer space and this routine would need to be modified to
3812 * copy the data buffer(s) as well.
3813 */
3814void
3815ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3816{
3817	void *pool_ref;
3818
3819	if ((src == NULL)
3820	 || (dest == NULL))
3821		return;
3822
3823	/*
3824	 * May need to preserve linked list pointers at some point too.
3825	 */
3826	pool_ref = dest->io_hdr.pool;
3827
3828	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3829
3830	dest->io_hdr.pool = pool_ref;
3831	/*
3832	 * We need to know that this is an internal copy, and doesn't need
3833	 * to get passed back to the FETD that allocated it.
3834	 */
3835	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3836}
3837
3838static int
3839ctl_expand_number(const char *buf, uint64_t *num)
3840{
3841	char *endptr;
3842	uint64_t number;
3843	unsigned shift;
3844
3845	number = strtoq(buf, &endptr, 0);
3846
3847	switch (tolower((unsigned char)*endptr)) {
3848	case 'e':
3849		shift = 60;
3850		break;
3851	case 'p':
3852		shift = 50;
3853		break;
3854	case 't':
3855		shift = 40;
3856		break;
3857	case 'g':
3858		shift = 30;
3859		break;
3860	case 'm':
3861		shift = 20;
3862		break;
3863	case 'k':
3864		shift = 10;
3865		break;
3866	case 'b':
3867	case '\0': /* No unit. */
3868		*num = number;
3869		return (0);
3870	default:
3871		/* Unrecognized unit. */
3872		return (-1);
3873	}
3874
3875	if ((number << shift) >> shift != number) {
3876		/* Overflow */
3877		return (-1);
3878	}
3879	*num = number << shift;
3880	return (0);
3881}
3882
3883
3884/*
3885 * This routine could be used in the future to load default and/or saved
3886 * mode page parameters for a particuar lun.
3887 */
3888static int
3889ctl_init_page_index(struct ctl_lun *lun)
3890{
3891	int i;
3892	struct ctl_page_index *page_index;
3893	const char *value;
3894	uint64_t ival;
3895
3896	memcpy(&lun->mode_pages.index, page_index_template,
3897	       sizeof(page_index_template));
3898
3899	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3900
3901		page_index = &lun->mode_pages.index[i];
3902		/*
3903		 * If this is a disk-only mode page, there's no point in
3904		 * setting it up.  For some pages, we have to have some
3905		 * basic information about the disk in order to calculate the
3906		 * mode page data.
3907		 */
3908		if ((lun->be_lun->lun_type != T_DIRECT)
3909		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3910			continue;
3911
3912		switch (page_index->page_code & SMPH_PC_MASK) {
3913		case SMS_RW_ERROR_RECOVERY_PAGE: {
3914			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3915				panic("subpage is incorrect!");
3916			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3917			       &rw_er_page_default,
3918			       sizeof(rw_er_page_default));
3919			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3920			       &rw_er_page_changeable,
3921			       sizeof(rw_er_page_changeable));
3922			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3923			       &rw_er_page_default,
3924			       sizeof(rw_er_page_default));
3925			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3926			       &rw_er_page_default,
3927			       sizeof(rw_er_page_default));
3928			page_index->page_data =
3929				(uint8_t *)lun->mode_pages.rw_er_page;
3930			break;
3931		}
3932		case SMS_FORMAT_DEVICE_PAGE: {
3933			struct scsi_format_page *format_page;
3934
3935			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3936				panic("subpage is incorrect!");
3937
3938			/*
3939			 * Sectors per track are set above.  Bytes per
3940			 * sector need to be set here on a per-LUN basis.
3941			 */
3942			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3943			       &format_page_default,
3944			       sizeof(format_page_default));
3945			memcpy(&lun->mode_pages.format_page[
3946			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
3947			       sizeof(format_page_changeable));
3948			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3949			       &format_page_default,
3950			       sizeof(format_page_default));
3951			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3952			       &format_page_default,
3953			       sizeof(format_page_default));
3954
3955			format_page = &lun->mode_pages.format_page[
3956				CTL_PAGE_CURRENT];
3957			scsi_ulto2b(lun->be_lun->blocksize,
3958				    format_page->bytes_per_sector);
3959
3960			format_page = &lun->mode_pages.format_page[
3961				CTL_PAGE_DEFAULT];
3962			scsi_ulto2b(lun->be_lun->blocksize,
3963				    format_page->bytes_per_sector);
3964
3965			format_page = &lun->mode_pages.format_page[
3966				CTL_PAGE_SAVED];
3967			scsi_ulto2b(lun->be_lun->blocksize,
3968				    format_page->bytes_per_sector);
3969
3970			page_index->page_data =
3971				(uint8_t *)lun->mode_pages.format_page;
3972			break;
3973		}
3974		case SMS_RIGID_DISK_PAGE: {
3975			struct scsi_rigid_disk_page *rigid_disk_page;
3976			uint32_t sectors_per_cylinder;
3977			uint64_t cylinders;
3978#ifndef	__XSCALE__
3979			int shift;
3980#endif /* !__XSCALE__ */
3981
3982			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3983				panic("invalid subpage value %d",
3984				      page_index->subpage);
3985
3986			/*
3987			 * Rotation rate and sectors per track are set
3988			 * above.  We calculate the cylinders here based on
3989			 * capacity.  Due to the number of heads and
3990			 * sectors per track we're using, smaller arrays
3991			 * may turn out to have 0 cylinders.  Linux and
3992			 * FreeBSD don't pay attention to these mode pages
3993			 * to figure out capacity, but Solaris does.  It
3994			 * seems to deal with 0 cylinders just fine, and
3995			 * works out a fake geometry based on the capacity.
3996			 */
3997			memcpy(&lun->mode_pages.rigid_disk_page[
3998			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
3999			       sizeof(rigid_disk_page_default));
4000			memcpy(&lun->mode_pages.rigid_disk_page[
4001			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4002			       sizeof(rigid_disk_page_changeable));
4003
4004			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4005				CTL_DEFAULT_HEADS;
4006
4007			/*
4008			 * The divide method here will be more accurate,
4009			 * probably, but results in floating point being
4010			 * used in the kernel on i386 (__udivdi3()).  On the
4011			 * XScale, though, __udivdi3() is implemented in
4012			 * software.
4013			 *
4014			 * The shift method for cylinder calculation is
4015			 * accurate if sectors_per_cylinder is a power of
4016			 * 2.  Otherwise it might be slightly off -- you
4017			 * might have a bit of a truncation problem.
4018			 */
4019#ifdef	__XSCALE__
4020			cylinders = (lun->be_lun->maxlba + 1) /
4021				sectors_per_cylinder;
4022#else
4023			for (shift = 31; shift > 0; shift--) {
4024				if (sectors_per_cylinder & (1 << shift))
4025					break;
4026			}
4027			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4028#endif
4029
4030			/*
4031			 * We've basically got 3 bytes, or 24 bits for the
4032			 * cylinder size in the mode page.  If we're over,
4033			 * just round down to 2^24.
4034			 */
4035			if (cylinders > 0xffffff)
4036				cylinders = 0xffffff;
4037
4038			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4039				CTL_PAGE_DEFAULT];
4040			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4041
4042			if ((value = ctl_get_opt(&lun->be_lun->options,
4043			    "rpm")) != NULL) {
4044				scsi_ulto2b(strtol(value, NULL, 0),
4045				     rigid_disk_page->rotation_rate);
4046			}
4047
4048			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4049			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4050			       sizeof(rigid_disk_page_default));
4051			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4052			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4053			       sizeof(rigid_disk_page_default));
4054
4055			page_index->page_data =
4056				(uint8_t *)lun->mode_pages.rigid_disk_page;
4057			break;
4058		}
4059		case SMS_CACHING_PAGE: {
4060			struct scsi_caching_page *caching_page;
4061
4062			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4063				panic("invalid subpage value %d",
4064				      page_index->subpage);
4065			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4066			       &caching_page_default,
4067			       sizeof(caching_page_default));
4068			memcpy(&lun->mode_pages.caching_page[
4069			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4070			       sizeof(caching_page_changeable));
4071			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4072			       &caching_page_default,
4073			       sizeof(caching_page_default));
4074			caching_page = &lun->mode_pages.caching_page[
4075			    CTL_PAGE_SAVED];
4076			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4077			if (value != NULL && strcmp(value, "off") == 0)
4078				caching_page->flags1 &= ~SCP_WCE;
4079			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4080			if (value != NULL && strcmp(value, "off") == 0)
4081				caching_page->flags1 |= SCP_RCD;
4082			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4083			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4084			       sizeof(caching_page_default));
4085			page_index->page_data =
4086				(uint8_t *)lun->mode_pages.caching_page;
4087			break;
4088		}
4089		case SMS_CONTROL_MODE_PAGE: {
4090			struct scsi_control_page *control_page;
4091
4092			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4093				panic("invalid subpage value %d",
4094				      page_index->subpage);
4095
4096			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4097			       &control_page_default,
4098			       sizeof(control_page_default));
4099			memcpy(&lun->mode_pages.control_page[
4100			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4101			       sizeof(control_page_changeable));
4102			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4103			       &control_page_default,
4104			       sizeof(control_page_default));
4105			control_page = &lun->mode_pages.control_page[
4106			    CTL_PAGE_SAVED];
4107			value = ctl_get_opt(&lun->be_lun->options, "reordering");
4108			if (value != NULL && strcmp(value, "unrestricted") == 0) {
4109				control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4110				control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4111			}
4112			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4113			       &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4114			       sizeof(control_page_default));
4115			page_index->page_data =
4116				(uint8_t *)lun->mode_pages.control_page;
4117			break;
4118
4119		}
4120		case SMS_INFO_EXCEPTIONS_PAGE: {
4121			switch (page_index->subpage) {
4122			case SMS_SUBPAGE_PAGE_0:
4123				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4124				       &ie_page_default,
4125				       sizeof(ie_page_default));
4126				memcpy(&lun->mode_pages.ie_page[
4127				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4128				       sizeof(ie_page_changeable));
4129				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4130				       &ie_page_default,
4131				       sizeof(ie_page_default));
4132				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4133				       &ie_page_default,
4134				       sizeof(ie_page_default));
4135				page_index->page_data =
4136					(uint8_t *)lun->mode_pages.ie_page;
4137				break;
4138			case 0x02: {
4139				struct ctl_logical_block_provisioning_page *page;
4140
4141				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4142				       &lbp_page_default,
4143				       sizeof(lbp_page_default));
4144				memcpy(&lun->mode_pages.lbp_page[
4145				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4146				       sizeof(lbp_page_changeable));
4147				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4148				       &lbp_page_default,
4149				       sizeof(lbp_page_default));
4150				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4151				value = ctl_get_opt(&lun->be_lun->options,
4152				    "avail-threshold");
4153				if (value != NULL &&
4154				    ctl_expand_number(value, &ival) == 0) {
4155					page->descr[0].flags |= SLBPPD_ENABLED |
4156					    SLBPPD_ARMING_DEC;
4157					if (lun->be_lun->blocksize)
4158						ival /= lun->be_lun->blocksize;
4159					else
4160						ival /= 512;
4161					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4162					    page->descr[0].count);
4163				}
4164				value = ctl_get_opt(&lun->be_lun->options,
4165				    "used-threshold");
4166				if (value != NULL &&
4167				    ctl_expand_number(value, &ival) == 0) {
4168					page->descr[1].flags |= SLBPPD_ENABLED |
4169					    SLBPPD_ARMING_INC;
4170					if (lun->be_lun->blocksize)
4171						ival /= lun->be_lun->blocksize;
4172					else
4173						ival /= 512;
4174					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4175					    page->descr[1].count);
4176				}
4177				value = ctl_get_opt(&lun->be_lun->options,
4178				    "pool-avail-threshold");
4179				if (value != NULL &&
4180				    ctl_expand_number(value, &ival) == 0) {
4181					page->descr[2].flags |= SLBPPD_ENABLED |
4182					    SLBPPD_ARMING_DEC;
4183					if (lun->be_lun->blocksize)
4184						ival /= lun->be_lun->blocksize;
4185					else
4186						ival /= 512;
4187					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4188					    page->descr[2].count);
4189				}
4190				value = ctl_get_opt(&lun->be_lun->options,
4191				    "pool-used-threshold");
4192				if (value != NULL &&
4193				    ctl_expand_number(value, &ival) == 0) {
4194					page->descr[3].flags |= SLBPPD_ENABLED |
4195					    SLBPPD_ARMING_INC;
4196					if (lun->be_lun->blocksize)
4197						ival /= lun->be_lun->blocksize;
4198					else
4199						ival /= 512;
4200					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4201					    page->descr[3].count);
4202				}
4203				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4204				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4205				       sizeof(lbp_page_default));
4206				page_index->page_data =
4207					(uint8_t *)lun->mode_pages.lbp_page;
4208			}}
4209			break;
4210		}
4211		case SMS_VENDOR_SPECIFIC_PAGE:{
4212			switch (page_index->subpage) {
4213			case DBGCNF_SUBPAGE_CODE: {
4214				struct copan_debugconf_subpage *current_page,
4215							       *saved_page;
4216
4217				memcpy(&lun->mode_pages.debugconf_subpage[
4218				       CTL_PAGE_CURRENT],
4219				       &debugconf_page_default,
4220				       sizeof(debugconf_page_default));
4221				memcpy(&lun->mode_pages.debugconf_subpage[
4222				       CTL_PAGE_CHANGEABLE],
4223				       &debugconf_page_changeable,
4224				       sizeof(debugconf_page_changeable));
4225				memcpy(&lun->mode_pages.debugconf_subpage[
4226				       CTL_PAGE_DEFAULT],
4227				       &debugconf_page_default,
4228				       sizeof(debugconf_page_default));
4229				memcpy(&lun->mode_pages.debugconf_subpage[
4230				       CTL_PAGE_SAVED],
4231				       &debugconf_page_default,
4232				       sizeof(debugconf_page_default));
4233				page_index->page_data =
4234					(uint8_t *)lun->mode_pages.debugconf_subpage;
4235
4236				current_page = (struct copan_debugconf_subpage *)
4237					(page_index->page_data +
4238					 (page_index->page_len *
4239					  CTL_PAGE_CURRENT));
4240				saved_page = (struct copan_debugconf_subpage *)
4241					(page_index->page_data +
4242					 (page_index->page_len *
4243					  CTL_PAGE_SAVED));
4244				break;
4245			}
4246			default:
4247				panic("invalid subpage value %d",
4248				      page_index->subpage);
4249				break;
4250			}
4251   			break;
4252		}
4253		default:
4254			panic("invalid page value %d",
4255			      page_index->page_code & SMPH_PC_MASK);
4256			break;
4257    	}
4258	}
4259
4260	return (CTL_RETVAL_COMPLETE);
4261}
4262
4263static int
4264ctl_init_log_page_index(struct ctl_lun *lun)
4265{
4266	struct ctl_page_index *page_index;
4267	int i, j, k, prev;
4268
4269	memcpy(&lun->log_pages.index, log_page_index_template,
4270	       sizeof(log_page_index_template));
4271
4272	prev = -1;
4273	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4274
4275		page_index = &lun->log_pages.index[i];
4276		/*
4277		 * If this is a disk-only mode page, there's no point in
4278		 * setting it up.  For some pages, we have to have some
4279		 * basic information about the disk in order to calculate the
4280		 * mode page data.
4281		 */
4282		if ((lun->be_lun->lun_type != T_DIRECT)
4283		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4284			continue;
4285
4286		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4287		    ((lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) == 0 ||
4288		     lun->backend->lun_attr == NULL))
4289			continue;
4290
4291		if (page_index->page_code != prev) {
4292			lun->log_pages.pages_page[j] = page_index->page_code;
4293			prev = page_index->page_code;
4294			j++;
4295		}
4296		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4297		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4298		k++;
4299	}
4300	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4301	lun->log_pages.index[0].page_len = j;
4302	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4303	lun->log_pages.index[1].page_len = k * 2;
4304	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4305	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4306
4307	return (CTL_RETVAL_COMPLETE);
4308}
4309
4310static int
4311hex2bin(const char *str, uint8_t *buf, int buf_size)
4312{
4313	int i;
4314	u_char c;
4315
4316	memset(buf, 0, buf_size);
4317	while (isspace(str[0]))
4318		str++;
4319	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4320		str += 2;
4321	buf_size *= 2;
4322	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4323		c = str[i];
4324		if (isdigit(c))
4325			c -= '0';
4326		else if (isalpha(c))
4327			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4328		else
4329			break;
4330		if (c >= 16)
4331			break;
4332		if ((i & 1) == 0)
4333			buf[i / 2] |= (c << 4);
4334		else
4335			buf[i / 2] |= c;
4336	}
4337	return ((i + 1) / 2);
4338}
4339
4340/*
4341 * LUN allocation.
4342 *
4343 * Requirements:
4344 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4345 *   wants us to allocate the LUN and he can block.
4346 * - ctl_softc is always set
4347 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4348 *
4349 * Returns 0 for success, non-zero (errno) for failure.
4350 */
4351static int
4352ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4353	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4354{
4355	struct ctl_lun *nlun, *lun;
4356	struct ctl_port *port;
4357	struct scsi_vpd_id_descriptor *desc;
4358	struct scsi_vpd_id_t10 *t10id;
4359	const char *eui, *naa, *scsiname, *vendor, *value;
4360	int lun_number, i, lun_malloced;
4361	int devidlen, idlen1, idlen2 = 0, len;
4362
4363	if (be_lun == NULL)
4364		return (EINVAL);
4365
4366	/*
4367	 * We currently only support Direct Access or Processor LUN types.
4368	 */
4369	switch (be_lun->lun_type) {
4370	case T_DIRECT:
4371		break;
4372	case T_PROCESSOR:
4373		break;
4374	case T_SEQUENTIAL:
4375	case T_CHANGER:
4376	default:
4377		be_lun->lun_config_status(be_lun->be_lun,
4378					  CTL_LUN_CONFIG_FAILURE);
4379		break;
4380	}
4381	if (ctl_lun == NULL) {
4382		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4383		lun_malloced = 1;
4384	} else {
4385		lun_malloced = 0;
4386		lun = ctl_lun;
4387	}
4388
4389	memset(lun, 0, sizeof(*lun));
4390	if (lun_malloced)
4391		lun->flags = CTL_LUN_MALLOCED;
4392
4393	/* Generate LUN ID. */
4394	devidlen = max(CTL_DEVID_MIN_LEN,
4395	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4396	idlen1 = sizeof(*t10id) + devidlen;
4397	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4398	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4399	if (scsiname != NULL) {
4400		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4401		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4402	}
4403	eui = ctl_get_opt(&be_lun->options, "eui");
4404	if (eui != NULL) {
4405		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4406	}
4407	naa = ctl_get_opt(&be_lun->options, "naa");
4408	if (naa != NULL) {
4409		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4410	}
4411	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4412	    M_CTL, M_WAITOK | M_ZERO);
4413	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4414	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4415	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4416	desc->length = idlen1;
4417	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4418	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4419	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4420		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4421	} else {
4422		strncpy(t10id->vendor, vendor,
4423		    min(sizeof(t10id->vendor), strlen(vendor)));
4424	}
4425	strncpy((char *)t10id->vendor_spec_id,
4426	    (char *)be_lun->device_id, devidlen);
4427	if (scsiname != NULL) {
4428		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4429		    desc->length);
4430		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4431		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4432		    SVPD_ID_TYPE_SCSI_NAME;
4433		desc->length = idlen2;
4434		strlcpy(desc->identifier, scsiname, idlen2);
4435	}
4436	if (eui != NULL) {
4437		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4438		    desc->length);
4439		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4440		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4441		    SVPD_ID_TYPE_EUI64;
4442		desc->length = hex2bin(eui, desc->identifier, 16);
4443		desc->length = desc->length > 12 ? 16 :
4444		    (desc->length > 8 ? 12 : 8);
4445		len -= 16 - desc->length;
4446	}
4447	if (naa != NULL) {
4448		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4449		    desc->length);
4450		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4451		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4452		    SVPD_ID_TYPE_NAA;
4453		desc->length = hex2bin(naa, desc->identifier, 16);
4454		desc->length = desc->length > 8 ? 16 : 8;
4455		len -= 16 - desc->length;
4456	}
4457	lun->lun_devid->len = len;
4458
4459	mtx_lock(&ctl_softc->ctl_lock);
4460	/*
4461	 * See if the caller requested a particular LUN number.  If so, see
4462	 * if it is available.  Otherwise, allocate the first available LUN.
4463	 */
4464	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4465		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4466		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4467			mtx_unlock(&ctl_softc->ctl_lock);
4468			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4469				printf("ctl: requested LUN ID %d is higher "
4470				       "than CTL_MAX_LUNS - 1 (%d)\n",
4471				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4472			} else {
4473				/*
4474				 * XXX KDM return an error, or just assign
4475				 * another LUN ID in this case??
4476				 */
4477				printf("ctl: requested LUN ID %d is already "
4478				       "in use\n", be_lun->req_lun_id);
4479			}
4480			if (lun->flags & CTL_LUN_MALLOCED)
4481				free(lun, M_CTL);
4482			be_lun->lun_config_status(be_lun->be_lun,
4483						  CTL_LUN_CONFIG_FAILURE);
4484			return (ENOSPC);
4485		}
4486		lun_number = be_lun->req_lun_id;
4487	} else {
4488		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4489		if (lun_number == -1) {
4490			mtx_unlock(&ctl_softc->ctl_lock);
4491			printf("ctl: can't allocate LUN on target %ju, out of "
4492			       "LUNs\n", (uintmax_t)target_id.id);
4493			if (lun->flags & CTL_LUN_MALLOCED)
4494				free(lun, M_CTL);
4495			be_lun->lun_config_status(be_lun->be_lun,
4496						  CTL_LUN_CONFIG_FAILURE);
4497			return (ENOSPC);
4498		}
4499	}
4500	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4501
4502	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4503	lun->target = target_id;
4504	lun->lun = lun_number;
4505	lun->be_lun = be_lun;
4506	/*
4507	 * The processor LUN is always enabled.  Disk LUNs come on line
4508	 * disabled, and must be enabled by the backend.
4509	 */
4510	lun->flags |= CTL_LUN_DISABLED;
4511	lun->backend = be_lun->be;
4512	be_lun->ctl_lun = lun;
4513	be_lun->lun_id = lun_number;
4514	atomic_add_int(&be_lun->be->num_luns, 1);
4515	if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4516		lun->flags |= CTL_LUN_OFFLINE;
4517
4518	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4519		lun->flags |= CTL_LUN_STOPPED;
4520
4521	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4522		lun->flags |= CTL_LUN_INOPERABLE;
4523
4524	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4525		lun->flags |= CTL_LUN_PRIMARY_SC;
4526
4527	value = ctl_get_opt(&be_lun->options, "readonly");
4528	if (value != NULL && strcmp(value, "on") == 0)
4529		lun->flags |= CTL_LUN_READONLY;
4530
4531	lun->ctl_softc = ctl_softc;
4532	TAILQ_INIT(&lun->ooa_queue);
4533	TAILQ_INIT(&lun->blocked_queue);
4534	STAILQ_INIT(&lun->error_list);
4535	ctl_tpc_lun_init(lun);
4536
4537	/*
4538	 * Initialize the mode and log page index.
4539	 */
4540	ctl_init_page_index(lun);
4541	ctl_init_log_page_index(lun);
4542
4543	/*
4544	 * Set the poweron UA for all initiators on this LUN only.
4545	 */
4546	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4547		lun->pending_ua[i] = CTL_UA_POWERON;
4548
4549	/*
4550	 * Now, before we insert this lun on the lun list, set the lun
4551	 * inventory changed UA for all other luns.
4552	 */
4553	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4554		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4555			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4556		}
4557	}
4558
4559	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4560
4561	ctl_softc->ctl_luns[lun_number] = lun;
4562
4563	ctl_softc->num_luns++;
4564
4565	/* Setup statistics gathering */
4566	lun->stats.device_type = be_lun->lun_type;
4567	lun->stats.lun_number = lun_number;
4568	if (lun->stats.device_type == T_DIRECT)
4569		lun->stats.blocksize = be_lun->blocksize;
4570	else
4571		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4572	for (i = 0;i < CTL_MAX_PORTS;i++)
4573		lun->stats.ports[i].targ_port = i;
4574
4575	mtx_unlock(&ctl_softc->ctl_lock);
4576
4577	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4578
4579	/*
4580	 * Run through each registered FETD and bring it online if it isn't
4581	 * already.  Enable the target ID if it hasn't been enabled, and
4582	 * enable this particular LUN.
4583	 */
4584	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4585		int retval;
4586
4587		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4588		if (retval != 0) {
4589			printf("ctl_alloc_lun: FETD %s port %d returned error "
4590			       "%d for lun_enable on target %ju lun %d\n",
4591			       port->port_name, port->targ_port, retval,
4592			       (uintmax_t)target_id.id, lun_number);
4593		} else
4594			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4595	}
4596	return (0);
4597}
4598
4599/*
4600 * Delete a LUN.
4601 * Assumptions:
4602 * - LUN has already been marked invalid and any pending I/O has been taken
4603 *   care of.
4604 */
4605static int
4606ctl_free_lun(struct ctl_lun *lun)
4607{
4608	struct ctl_softc *softc;
4609#if 0
4610	struct ctl_port *port;
4611#endif
4612	struct ctl_lun *nlun;
4613	int i;
4614
4615	softc = lun->ctl_softc;
4616
4617	mtx_assert(&softc->ctl_lock, MA_OWNED);
4618
4619	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4620
4621	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4622
4623	softc->ctl_luns[lun->lun] = NULL;
4624
4625	if (!TAILQ_EMPTY(&lun->ooa_queue))
4626		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4627
4628	softc->num_luns--;
4629
4630	/*
4631	 * XXX KDM this scheme only works for a single target/multiple LUN
4632	 * setup.  It needs to be revamped for a multiple target scheme.
4633	 *
4634	 * XXX KDM this results in port->lun_disable() getting called twice,
4635	 * once when ctl_disable_lun() is called, and a second time here.
4636	 * We really need to re-think the LUN disable semantics.  There
4637	 * should probably be several steps/levels to LUN removal:
4638	 *  - disable
4639	 *  - invalidate
4640	 *  - free
4641 	 *
4642	 * Right now we only have a disable method when communicating to
4643	 * the front end ports, at least for individual LUNs.
4644	 */
4645#if 0
4646	STAILQ_FOREACH(port, &softc->port_list, links) {
4647		int retval;
4648
4649		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4650					 lun->lun);
4651		if (retval != 0) {
4652			printf("ctl_free_lun: FETD %s port %d returned error "
4653			       "%d for lun_disable on target %ju lun %jd\n",
4654			       port->port_name, port->targ_port, retval,
4655			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4656		}
4657
4658		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4659			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4660
4661			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4662			if (retval != 0) {
4663				printf("ctl_free_lun: FETD %s port %d "
4664				       "returned error %d for targ_disable on "
4665				       "target %ju\n", port->port_name,
4666				       port->targ_port, retval,
4667				       (uintmax_t)lun->target.id);
4668			} else
4669				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4670
4671			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4672				continue;
4673
4674#if 0
4675			port->port_offline(port->onoff_arg);
4676			port->status &= ~CTL_PORT_STATUS_ONLINE;
4677#endif
4678		}
4679	}
4680#endif
4681
4682	/*
4683	 * Tell the backend to free resources, if this LUN has a backend.
4684	 */
4685	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4686	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4687
4688	ctl_tpc_lun_shutdown(lun);
4689	mtx_destroy(&lun->lun_lock);
4690	free(lun->lun_devid, M_CTL);
4691	free(lun->write_buffer, M_CTL);
4692	if (lun->flags & CTL_LUN_MALLOCED)
4693		free(lun, M_CTL);
4694
4695	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4696		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4697			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4698		}
4699	}
4700
4701	return (0);
4702}
4703
4704static void
4705ctl_create_lun(struct ctl_be_lun *be_lun)
4706{
4707	struct ctl_softc *ctl_softc;
4708
4709	ctl_softc = control_softc;
4710
4711	/*
4712	 * ctl_alloc_lun() should handle all potential failure cases.
4713	 */
4714	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4715}
4716
4717int
4718ctl_add_lun(struct ctl_be_lun *be_lun)
4719{
4720	struct ctl_softc *ctl_softc = control_softc;
4721
4722	mtx_lock(&ctl_softc->ctl_lock);
4723	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4724	mtx_unlock(&ctl_softc->ctl_lock);
4725	wakeup(&ctl_softc->pending_lun_queue);
4726
4727	return (0);
4728}
4729
4730int
4731ctl_enable_lun(struct ctl_be_lun *be_lun)
4732{
4733	struct ctl_softc *ctl_softc;
4734	struct ctl_port *port, *nport;
4735	struct ctl_lun *lun;
4736	int retval;
4737
4738	ctl_softc = control_softc;
4739
4740	lun = (struct ctl_lun *)be_lun->ctl_lun;
4741
4742	mtx_lock(&ctl_softc->ctl_lock);
4743	mtx_lock(&lun->lun_lock);
4744	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4745		/*
4746		 * eh?  Why did we get called if the LUN is already
4747		 * enabled?
4748		 */
4749		mtx_unlock(&lun->lun_lock);
4750		mtx_unlock(&ctl_softc->ctl_lock);
4751		return (0);
4752	}
4753	lun->flags &= ~CTL_LUN_DISABLED;
4754	mtx_unlock(&lun->lun_lock);
4755
4756	for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4757		nport = STAILQ_NEXT(port, links);
4758
4759		/*
4760		 * Drop the lock while we call the FETD's enable routine.
4761		 * This can lead to a callback into CTL (at least in the
4762		 * case of the internal initiator frontend.
4763		 */
4764		mtx_unlock(&ctl_softc->ctl_lock);
4765		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4766		mtx_lock(&ctl_softc->ctl_lock);
4767		if (retval != 0) {
4768			printf("%s: FETD %s port %d returned error "
4769			       "%d for lun_enable on target %ju lun %jd\n",
4770			       __func__, port->port_name, port->targ_port, retval,
4771			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4772		}
4773#if 0
4774		 else {
4775            /* NOTE:  TODO:  why does lun enable affect port status? */
4776			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4777		}
4778#endif
4779	}
4780
4781	mtx_unlock(&ctl_softc->ctl_lock);
4782
4783	return (0);
4784}
4785
4786int
4787ctl_disable_lun(struct ctl_be_lun *be_lun)
4788{
4789	struct ctl_softc *ctl_softc;
4790	struct ctl_port *port;
4791	struct ctl_lun *lun;
4792	int retval;
4793
4794	ctl_softc = control_softc;
4795
4796	lun = (struct ctl_lun *)be_lun->ctl_lun;
4797
4798	mtx_lock(&ctl_softc->ctl_lock);
4799	mtx_lock(&lun->lun_lock);
4800	if (lun->flags & CTL_LUN_DISABLED) {
4801		mtx_unlock(&lun->lun_lock);
4802		mtx_unlock(&ctl_softc->ctl_lock);
4803		return (0);
4804	}
4805	lun->flags |= CTL_LUN_DISABLED;
4806	mtx_unlock(&lun->lun_lock);
4807
4808	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4809		mtx_unlock(&ctl_softc->ctl_lock);
4810		/*
4811		 * Drop the lock before we call the frontend's disable
4812		 * routine, to avoid lock order reversals.
4813		 *
4814		 * XXX KDM what happens if the frontend list changes while
4815		 * we're traversing it?  It's unlikely, but should be handled.
4816		 */
4817		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4818					 lun->lun);
4819		mtx_lock(&ctl_softc->ctl_lock);
4820		if (retval != 0) {
4821			printf("ctl_alloc_lun: FETD %s port %d returned error "
4822			       "%d for lun_disable on target %ju lun %jd\n",
4823			       port->port_name, port->targ_port, retval,
4824			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4825		}
4826	}
4827
4828	mtx_unlock(&ctl_softc->ctl_lock);
4829
4830	return (0);
4831}
4832
4833int
4834ctl_start_lun(struct ctl_be_lun *be_lun)
4835{
4836	struct ctl_softc *ctl_softc;
4837	struct ctl_lun *lun;
4838
4839	ctl_softc = control_softc;
4840
4841	lun = (struct ctl_lun *)be_lun->ctl_lun;
4842
4843	mtx_lock(&lun->lun_lock);
4844	lun->flags &= ~CTL_LUN_STOPPED;
4845	mtx_unlock(&lun->lun_lock);
4846
4847	return (0);
4848}
4849
4850int
4851ctl_stop_lun(struct ctl_be_lun *be_lun)
4852{
4853	struct ctl_softc *ctl_softc;
4854	struct ctl_lun *lun;
4855
4856	ctl_softc = control_softc;
4857
4858	lun = (struct ctl_lun *)be_lun->ctl_lun;
4859
4860	mtx_lock(&lun->lun_lock);
4861	lun->flags |= CTL_LUN_STOPPED;
4862	mtx_unlock(&lun->lun_lock);
4863
4864	return (0);
4865}
4866
4867int
4868ctl_lun_offline(struct ctl_be_lun *be_lun)
4869{
4870	struct ctl_softc *ctl_softc;
4871	struct ctl_lun *lun;
4872
4873	ctl_softc = control_softc;
4874
4875	lun = (struct ctl_lun *)be_lun->ctl_lun;
4876
4877	mtx_lock(&lun->lun_lock);
4878	lun->flags |= CTL_LUN_OFFLINE;
4879	mtx_unlock(&lun->lun_lock);
4880
4881	return (0);
4882}
4883
4884int
4885ctl_lun_online(struct ctl_be_lun *be_lun)
4886{
4887	struct ctl_softc *ctl_softc;
4888	struct ctl_lun *lun;
4889
4890	ctl_softc = control_softc;
4891
4892	lun = (struct ctl_lun *)be_lun->ctl_lun;
4893
4894	mtx_lock(&lun->lun_lock);
4895	lun->flags &= ~CTL_LUN_OFFLINE;
4896	mtx_unlock(&lun->lun_lock);
4897
4898	return (0);
4899}
4900
4901int
4902ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4903{
4904	struct ctl_softc *ctl_softc;
4905	struct ctl_lun *lun;
4906
4907	ctl_softc = control_softc;
4908
4909	lun = (struct ctl_lun *)be_lun->ctl_lun;
4910
4911	mtx_lock(&lun->lun_lock);
4912
4913	/*
4914	 * The LUN needs to be disabled before it can be marked invalid.
4915	 */
4916	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4917		mtx_unlock(&lun->lun_lock);
4918		return (-1);
4919	}
4920	/*
4921	 * Mark the LUN invalid.
4922	 */
4923	lun->flags |= CTL_LUN_INVALID;
4924
4925	/*
4926	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4927	 * If we have something in the OOA queue, we'll free it when the
4928	 * last I/O completes.
4929	 */
4930	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4931		mtx_unlock(&lun->lun_lock);
4932		mtx_lock(&ctl_softc->ctl_lock);
4933		ctl_free_lun(lun);
4934		mtx_unlock(&ctl_softc->ctl_lock);
4935	} else
4936		mtx_unlock(&lun->lun_lock);
4937
4938	return (0);
4939}
4940
4941int
4942ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4943{
4944	struct ctl_softc *ctl_softc;
4945	struct ctl_lun *lun;
4946
4947	ctl_softc = control_softc;
4948	lun = (struct ctl_lun *)be_lun->ctl_lun;
4949
4950	mtx_lock(&lun->lun_lock);
4951	lun->flags |= CTL_LUN_INOPERABLE;
4952	mtx_unlock(&lun->lun_lock);
4953
4954	return (0);
4955}
4956
4957int
4958ctl_lun_operable(struct ctl_be_lun *be_lun)
4959{
4960	struct ctl_softc *ctl_softc;
4961	struct ctl_lun *lun;
4962
4963	ctl_softc = control_softc;
4964	lun = (struct ctl_lun *)be_lun->ctl_lun;
4965
4966	mtx_lock(&lun->lun_lock);
4967	lun->flags &= ~CTL_LUN_INOPERABLE;
4968	mtx_unlock(&lun->lun_lock);
4969
4970	return (0);
4971}
4972
4973void
4974ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4975{
4976	struct ctl_lun *lun;
4977	struct ctl_softc *softc;
4978	int i;
4979
4980	softc = control_softc;
4981
4982	lun = (struct ctl_lun *)be_lun->ctl_lun;
4983
4984	mtx_lock(&lun->lun_lock);
4985
4986	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4987		lun->pending_ua[i] |= CTL_UA_CAPACITY_CHANGED;
4988
4989	mtx_unlock(&lun->lun_lock);
4990}
4991
4992/*
4993 * Backend "memory move is complete" callback for requests that never
4994 * make it down to say RAIDCore's configuration code.
4995 */
4996int
4997ctl_config_move_done(union ctl_io *io)
4998{
4999	int retval;
5000
5001	retval = CTL_RETVAL_COMPLETE;
5002
5003
5004	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5005	/*
5006	 * XXX KDM this shouldn't happen, but what if it does?
5007	 */
5008	if (io->io_hdr.io_type != CTL_IO_SCSI)
5009		panic("I/O type isn't CTL_IO_SCSI!");
5010
5011	if ((io->io_hdr.port_status == 0)
5012	 && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5013	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
5014		io->io_hdr.status = CTL_SUCCESS;
5015	else if ((io->io_hdr.port_status != 0)
5016	      && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5017	      && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
5018		/*
5019		 * For hardware error sense keys, the sense key
5020		 * specific value is defined to be a retry count,
5021		 * but we use it to pass back an internal FETD
5022		 * error code.  XXX KDM  Hopefully the FETD is only
5023		 * using 16 bits for an error code, since that's
5024		 * all the space we have in the sks field.
5025		 */
5026		ctl_set_internal_failure(&io->scsiio,
5027					 /*sks_valid*/ 1,
5028					 /*retry_count*/
5029					 io->io_hdr.port_status);
5030		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5031			free(io->scsiio.kern_data_ptr, M_CTL);
5032		ctl_done(io);
5033		goto bailout;
5034	}
5035
5036	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
5037	 || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
5038	 || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5039		/*
5040		 * XXX KDM just assuming a single pointer here, and not a
5041		 * S/G list.  If we start using S/G lists for config data,
5042		 * we'll need to know how to clean them up here as well.
5043		 */
5044		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5045			free(io->scsiio.kern_data_ptr, M_CTL);
5046		/* Hopefully the user has already set the status... */
5047		ctl_done(io);
5048	} else {
5049		/*
5050		 * XXX KDM now we need to continue data movement.  Some
5051		 * options:
5052		 * - call ctl_scsiio() again?  We don't do this for data
5053		 *   writes, because for those at least we know ahead of
5054		 *   time where the write will go and how long it is.  For
5055		 *   config writes, though, that information is largely
5056		 *   contained within the write itself, thus we need to
5057		 *   parse out the data again.
5058		 *
5059		 * - Call some other function once the data is in?
5060		 */
5061		if (ctl_debug & CTL_DEBUG_CDB_DATA)
5062			ctl_data_print(io);
5063
5064		/*
5065		 * XXX KDM call ctl_scsiio() again for now, and check flag
5066		 * bits to see whether we're allocated or not.
5067		 */
5068		retval = ctl_scsiio(&io->scsiio);
5069	}
5070bailout:
5071	return (retval);
5072}
5073
5074/*
5075 * This gets called by a backend driver when it is done with a
5076 * data_submit method.
5077 */
5078void
5079ctl_data_submit_done(union ctl_io *io)
5080{
5081	/*
5082	 * If the IO_CONT flag is set, we need to call the supplied
5083	 * function to continue processing the I/O, instead of completing
5084	 * the I/O just yet.
5085	 *
5086	 * If there is an error, though, we don't want to keep processing.
5087	 * Instead, just send status back to the initiator.
5088	 */
5089	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5090	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5091	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5092	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5093		io->scsiio.io_cont(io);
5094		return;
5095	}
5096	ctl_done(io);
5097}
5098
5099/*
5100 * This gets called by a backend driver when it is done with a
5101 * configuration write.
5102 */
5103void
5104ctl_config_write_done(union ctl_io *io)
5105{
5106	uint8_t *buf;
5107
5108	/*
5109	 * If the IO_CONT flag is set, we need to call the supplied
5110	 * function to continue processing the I/O, instead of completing
5111	 * the I/O just yet.
5112	 *
5113	 * If there is an error, though, we don't want to keep processing.
5114	 * Instead, just send status back to the initiator.
5115	 */
5116	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5117	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5118	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5119	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5120		io->scsiio.io_cont(io);
5121		return;
5122	}
5123	/*
5124	 * Since a configuration write can be done for commands that actually
5125	 * have data allocated, like write buffer, and commands that have
5126	 * no data, like start/stop unit, we need to check here.
5127	 */
5128	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5129		buf = io->scsiio.kern_data_ptr;
5130	else
5131		buf = NULL;
5132	ctl_done(io);
5133	if (buf)
5134		free(buf, M_CTL);
5135}
5136
5137/*
5138 * SCSI release command.
5139 */
5140int
5141ctl_scsi_release(struct ctl_scsiio *ctsio)
5142{
5143	int length, longid, thirdparty_id, resv_id;
5144	struct ctl_softc *ctl_softc;
5145	struct ctl_lun *lun;
5146	uint32_t residx;
5147
5148	length = 0;
5149	resv_id = 0;
5150
5151	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5152
5153	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5154	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5155	ctl_softc = control_softc;
5156
5157	switch (ctsio->cdb[0]) {
5158	case RELEASE_10: {
5159		struct scsi_release_10 *cdb;
5160
5161		cdb = (struct scsi_release_10 *)ctsio->cdb;
5162
5163		if (cdb->byte2 & SR10_LONGID)
5164			longid = 1;
5165		else
5166			thirdparty_id = cdb->thirdparty_id;
5167
5168		resv_id = cdb->resv_id;
5169		length = scsi_2btoul(cdb->length);
5170		break;
5171	}
5172	}
5173
5174
5175	/*
5176	 * XXX KDM right now, we only support LUN reservation.  We don't
5177	 * support 3rd party reservations, or extent reservations, which
5178	 * might actually need the parameter list.  If we've gotten this
5179	 * far, we've got a LUN reservation.  Anything else got kicked out
5180	 * above.  So, according to SPC, ignore the length.
5181	 */
5182	length = 0;
5183
5184	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5185	 && (length > 0)) {
5186		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5187		ctsio->kern_data_len = length;
5188		ctsio->kern_total_len = length;
5189		ctsio->kern_data_resid = 0;
5190		ctsio->kern_rel_offset = 0;
5191		ctsio->kern_sg_entries = 0;
5192		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5193		ctsio->be_move_done = ctl_config_move_done;
5194		ctl_datamove((union ctl_io *)ctsio);
5195
5196		return (CTL_RETVAL_COMPLETE);
5197	}
5198
5199	if (length > 0)
5200		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5201
5202	mtx_lock(&lun->lun_lock);
5203
5204	/*
5205	 * According to SPC, it is not an error for an intiator to attempt
5206	 * to release a reservation on a LUN that isn't reserved, or that
5207	 * is reserved by another initiator.  The reservation can only be
5208	 * released, though, by the initiator who made it or by one of
5209	 * several reset type events.
5210	 */
5211	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5212			lun->flags &= ~CTL_LUN_RESERVED;
5213
5214	mtx_unlock(&lun->lun_lock);
5215
5216	ctsio->scsi_status = SCSI_STATUS_OK;
5217	ctsio->io_hdr.status = CTL_SUCCESS;
5218
5219	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5220		free(ctsio->kern_data_ptr, M_CTL);
5221		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5222	}
5223
5224	ctl_done((union ctl_io *)ctsio);
5225	return (CTL_RETVAL_COMPLETE);
5226}
5227
5228int
5229ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5230{
5231	int extent, thirdparty, longid;
5232	int resv_id, length;
5233	uint64_t thirdparty_id;
5234	struct ctl_softc *ctl_softc;
5235	struct ctl_lun *lun;
5236	uint32_t residx;
5237
5238	extent = 0;
5239	thirdparty = 0;
5240	longid = 0;
5241	resv_id = 0;
5242	length = 0;
5243	thirdparty_id = 0;
5244
5245	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5246
5247	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5248	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5249	ctl_softc = control_softc;
5250
5251	switch (ctsio->cdb[0]) {
5252	case RESERVE_10: {
5253		struct scsi_reserve_10 *cdb;
5254
5255		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5256
5257		if (cdb->byte2 & SR10_LONGID)
5258			longid = 1;
5259		else
5260			thirdparty_id = cdb->thirdparty_id;
5261
5262		resv_id = cdb->resv_id;
5263		length = scsi_2btoul(cdb->length);
5264		break;
5265	}
5266	}
5267
5268	/*
5269	 * XXX KDM right now, we only support LUN reservation.  We don't
5270	 * support 3rd party reservations, or extent reservations, which
5271	 * might actually need the parameter list.  If we've gotten this
5272	 * far, we've got a LUN reservation.  Anything else got kicked out
5273	 * above.  So, according to SPC, ignore the length.
5274	 */
5275	length = 0;
5276
5277	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5278	 && (length > 0)) {
5279		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5280		ctsio->kern_data_len = length;
5281		ctsio->kern_total_len = length;
5282		ctsio->kern_data_resid = 0;
5283		ctsio->kern_rel_offset = 0;
5284		ctsio->kern_sg_entries = 0;
5285		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5286		ctsio->be_move_done = ctl_config_move_done;
5287		ctl_datamove((union ctl_io *)ctsio);
5288
5289		return (CTL_RETVAL_COMPLETE);
5290	}
5291
5292	if (length > 0)
5293		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5294
5295	mtx_lock(&lun->lun_lock);
5296	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5297		ctl_set_reservation_conflict(ctsio);
5298		goto bailout;
5299	}
5300
5301	lun->flags |= CTL_LUN_RESERVED;
5302	lun->res_idx = residx;
5303
5304	ctsio->scsi_status = SCSI_STATUS_OK;
5305	ctsio->io_hdr.status = CTL_SUCCESS;
5306
5307bailout:
5308	mtx_unlock(&lun->lun_lock);
5309
5310	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5311		free(ctsio->kern_data_ptr, M_CTL);
5312		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5313	}
5314
5315	ctl_done((union ctl_io *)ctsio);
5316	return (CTL_RETVAL_COMPLETE);
5317}
5318
5319int
5320ctl_start_stop(struct ctl_scsiio *ctsio)
5321{
5322	struct scsi_start_stop_unit *cdb;
5323	struct ctl_lun *lun;
5324	struct ctl_softc *ctl_softc;
5325	int retval;
5326
5327	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5328
5329	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5330	ctl_softc = control_softc;
5331	retval = 0;
5332
5333	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5334
5335	/*
5336	 * XXX KDM
5337	 * We don't support the immediate bit on a stop unit.  In order to
5338	 * do that, we would need to code up a way to know that a stop is
5339	 * pending, and hold off any new commands until it completes, one
5340	 * way or another.  Then we could accept or reject those commands
5341	 * depending on its status.  We would almost need to do the reverse
5342	 * of what we do below for an immediate start -- return the copy of
5343	 * the ctl_io to the FETD with status to send to the host (and to
5344	 * free the copy!) and then free the original I/O once the stop
5345	 * actually completes.  That way, the OOA queue mechanism can work
5346	 * to block commands that shouldn't proceed.  Another alternative
5347	 * would be to put the copy in the queue in place of the original,
5348	 * and return the original back to the caller.  That could be
5349	 * slightly safer..
5350	 */
5351	if ((cdb->byte2 & SSS_IMMED)
5352	 && ((cdb->how & SSS_START) == 0)) {
5353		ctl_set_invalid_field(ctsio,
5354				      /*sks_valid*/ 1,
5355				      /*command*/ 1,
5356				      /*field*/ 1,
5357				      /*bit_valid*/ 1,
5358				      /*bit*/ 0);
5359		ctl_done((union ctl_io *)ctsio);
5360		return (CTL_RETVAL_COMPLETE);
5361	}
5362
5363	if ((lun->flags & CTL_LUN_PR_RESERVED)
5364	 && ((cdb->how & SSS_START)==0)) {
5365		uint32_t residx;
5366
5367		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5368		if (lun->pr_keys[residx] == 0
5369		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5370
5371			ctl_set_reservation_conflict(ctsio);
5372			ctl_done((union ctl_io *)ctsio);
5373			return (CTL_RETVAL_COMPLETE);
5374		}
5375	}
5376
5377	/*
5378	 * If there is no backend on this device, we can't start or stop
5379	 * it.  In theory we shouldn't get any start/stop commands in the
5380	 * first place at this level if the LUN doesn't have a backend.
5381	 * That should get stopped by the command decode code.
5382	 */
5383	if (lun->backend == NULL) {
5384		ctl_set_invalid_opcode(ctsio);
5385		ctl_done((union ctl_io *)ctsio);
5386		return (CTL_RETVAL_COMPLETE);
5387	}
5388
5389	/*
5390	 * XXX KDM Copan-specific offline behavior.
5391	 * Figure out a reasonable way to port this?
5392	 */
5393#ifdef NEEDTOPORT
5394	mtx_lock(&lun->lun_lock);
5395
5396	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5397	 && (lun->flags & CTL_LUN_OFFLINE)) {
5398		/*
5399		 * If the LUN is offline, and the on/offline bit isn't set,
5400		 * reject the start or stop.  Otherwise, let it through.
5401		 */
5402		mtx_unlock(&lun->lun_lock);
5403		ctl_set_lun_not_ready(ctsio);
5404		ctl_done((union ctl_io *)ctsio);
5405	} else {
5406		mtx_unlock(&lun->lun_lock);
5407#endif /* NEEDTOPORT */
5408		/*
5409		 * This could be a start or a stop when we're online,
5410		 * or a stop/offline or start/online.  A start or stop when
5411		 * we're offline is covered in the case above.
5412		 */
5413		/*
5414		 * In the non-immediate case, we send the request to
5415		 * the backend and return status to the user when
5416		 * it is done.
5417		 *
5418		 * In the immediate case, we allocate a new ctl_io
5419		 * to hold a copy of the request, and send that to
5420		 * the backend.  We then set good status on the
5421		 * user's request and return it immediately.
5422		 */
5423		if (cdb->byte2 & SSS_IMMED) {
5424			union ctl_io *new_io;
5425
5426			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5427			ctl_copy_io((union ctl_io *)ctsio, new_io);
5428			retval = lun->backend->config_write(new_io);
5429			ctl_set_success(ctsio);
5430			ctl_done((union ctl_io *)ctsio);
5431		} else {
5432			retval = lun->backend->config_write(
5433				(union ctl_io *)ctsio);
5434		}
5435#ifdef NEEDTOPORT
5436	}
5437#endif
5438	return (retval);
5439}
5440
5441/*
5442 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5443 * we don't really do anything with the LBA and length fields if the user
5444 * passes them in.  Instead we'll just flush out the cache for the entire
5445 * LUN.
5446 */
5447int
5448ctl_sync_cache(struct ctl_scsiio *ctsio)
5449{
5450	struct ctl_lun *lun;
5451	struct ctl_softc *ctl_softc;
5452	uint64_t starting_lba;
5453	uint32_t block_count;
5454	int retval;
5455
5456	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5457
5458	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5459	ctl_softc = control_softc;
5460	retval = 0;
5461
5462	switch (ctsio->cdb[0]) {
5463	case SYNCHRONIZE_CACHE: {
5464		struct scsi_sync_cache *cdb;
5465		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5466
5467		starting_lba = scsi_4btoul(cdb->begin_lba);
5468		block_count = scsi_2btoul(cdb->lb_count);
5469		break;
5470	}
5471	case SYNCHRONIZE_CACHE_16: {
5472		struct scsi_sync_cache_16 *cdb;
5473		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5474
5475		starting_lba = scsi_8btou64(cdb->begin_lba);
5476		block_count = scsi_4btoul(cdb->lb_count);
5477		break;
5478	}
5479	default:
5480		ctl_set_invalid_opcode(ctsio);
5481		ctl_done((union ctl_io *)ctsio);
5482		goto bailout;
5483		break; /* NOTREACHED */
5484	}
5485
5486	/*
5487	 * We check the LBA and length, but don't do anything with them.
5488	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5489	 * get flushed.  This check will just help satisfy anyone who wants
5490	 * to see an error for an out of range LBA.
5491	 */
5492	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5493		ctl_set_lba_out_of_range(ctsio);
5494		ctl_done((union ctl_io *)ctsio);
5495		goto bailout;
5496	}
5497
5498	/*
5499	 * If this LUN has no backend, we can't flush the cache anyway.
5500	 */
5501	if (lun->backend == NULL) {
5502		ctl_set_invalid_opcode(ctsio);
5503		ctl_done((union ctl_io *)ctsio);
5504		goto bailout;
5505	}
5506
5507	/*
5508	 * Check to see whether we're configured to send the SYNCHRONIZE
5509	 * CACHE command directly to the back end.
5510	 */
5511	mtx_lock(&lun->lun_lock);
5512	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5513	 && (++(lun->sync_count) >= lun->sync_interval)) {
5514		lun->sync_count = 0;
5515		mtx_unlock(&lun->lun_lock);
5516		retval = lun->backend->config_write((union ctl_io *)ctsio);
5517	} else {
5518		mtx_unlock(&lun->lun_lock);
5519		ctl_set_success(ctsio);
5520		ctl_done((union ctl_io *)ctsio);
5521	}
5522
5523bailout:
5524
5525	return (retval);
5526}
5527
5528int
5529ctl_format(struct ctl_scsiio *ctsio)
5530{
5531	struct scsi_format *cdb;
5532	struct ctl_lun *lun;
5533	struct ctl_softc *ctl_softc;
5534	int length, defect_list_len;
5535
5536	CTL_DEBUG_PRINT(("ctl_format\n"));
5537
5538	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5539	ctl_softc = control_softc;
5540
5541	cdb = (struct scsi_format *)ctsio->cdb;
5542
5543	length = 0;
5544	if (cdb->byte2 & SF_FMTDATA) {
5545		if (cdb->byte2 & SF_LONGLIST)
5546			length = sizeof(struct scsi_format_header_long);
5547		else
5548			length = sizeof(struct scsi_format_header_short);
5549	}
5550
5551	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5552	 && (length > 0)) {
5553		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5554		ctsio->kern_data_len = length;
5555		ctsio->kern_total_len = length;
5556		ctsio->kern_data_resid = 0;
5557		ctsio->kern_rel_offset = 0;
5558		ctsio->kern_sg_entries = 0;
5559		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5560		ctsio->be_move_done = ctl_config_move_done;
5561		ctl_datamove((union ctl_io *)ctsio);
5562
5563		return (CTL_RETVAL_COMPLETE);
5564	}
5565
5566	defect_list_len = 0;
5567
5568	if (cdb->byte2 & SF_FMTDATA) {
5569		if (cdb->byte2 & SF_LONGLIST) {
5570			struct scsi_format_header_long *header;
5571
5572			header = (struct scsi_format_header_long *)
5573				ctsio->kern_data_ptr;
5574
5575			defect_list_len = scsi_4btoul(header->defect_list_len);
5576			if (defect_list_len != 0) {
5577				ctl_set_invalid_field(ctsio,
5578						      /*sks_valid*/ 1,
5579						      /*command*/ 0,
5580						      /*field*/ 2,
5581						      /*bit_valid*/ 0,
5582						      /*bit*/ 0);
5583				goto bailout;
5584			}
5585		} else {
5586			struct scsi_format_header_short *header;
5587
5588			header = (struct scsi_format_header_short *)
5589				ctsio->kern_data_ptr;
5590
5591			defect_list_len = scsi_2btoul(header->defect_list_len);
5592			if (defect_list_len != 0) {
5593				ctl_set_invalid_field(ctsio,
5594						      /*sks_valid*/ 1,
5595						      /*command*/ 0,
5596						      /*field*/ 2,
5597						      /*bit_valid*/ 0,
5598						      /*bit*/ 0);
5599				goto bailout;
5600			}
5601		}
5602	}
5603
5604	/*
5605	 * The format command will clear out the "Medium format corrupted"
5606	 * status if set by the configuration code.  That status is really
5607	 * just a way to notify the host that we have lost the media, and
5608	 * get them to issue a command that will basically make them think
5609	 * they're blowing away the media.
5610	 */
5611	mtx_lock(&lun->lun_lock);
5612	lun->flags &= ~CTL_LUN_INOPERABLE;
5613	mtx_unlock(&lun->lun_lock);
5614
5615	ctsio->scsi_status = SCSI_STATUS_OK;
5616	ctsio->io_hdr.status = CTL_SUCCESS;
5617bailout:
5618
5619	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5620		free(ctsio->kern_data_ptr, M_CTL);
5621		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5622	}
5623
5624	ctl_done((union ctl_io *)ctsio);
5625	return (CTL_RETVAL_COMPLETE);
5626}
5627
5628int
5629ctl_read_buffer(struct ctl_scsiio *ctsio)
5630{
5631	struct scsi_read_buffer *cdb;
5632	struct ctl_lun *lun;
5633	int buffer_offset, len;
5634	static uint8_t descr[4];
5635	static uint8_t echo_descr[4] = { 0 };
5636
5637	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5638
5639	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5640	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5641
5642	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5643	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5644	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5645		ctl_set_invalid_field(ctsio,
5646				      /*sks_valid*/ 1,
5647				      /*command*/ 1,
5648				      /*field*/ 1,
5649				      /*bit_valid*/ 1,
5650				      /*bit*/ 4);
5651		ctl_done((union ctl_io *)ctsio);
5652		return (CTL_RETVAL_COMPLETE);
5653	}
5654
5655	len = scsi_3btoul(cdb->length);
5656	buffer_offset = scsi_3btoul(cdb->offset);
5657
5658	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5659		ctl_set_invalid_field(ctsio,
5660				      /*sks_valid*/ 1,
5661				      /*command*/ 1,
5662				      /*field*/ 6,
5663				      /*bit_valid*/ 0,
5664				      /*bit*/ 0);
5665		ctl_done((union ctl_io *)ctsio);
5666		return (CTL_RETVAL_COMPLETE);
5667	}
5668
5669	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5670		descr[0] = 0;
5671		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5672		ctsio->kern_data_ptr = descr;
5673		len = min(len, sizeof(descr));
5674	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5675		ctsio->kern_data_ptr = echo_descr;
5676		len = min(len, sizeof(echo_descr));
5677	} else {
5678		if (lun->write_buffer == NULL) {
5679			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5680			    M_CTL, M_WAITOK);
5681		}
5682		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5683	}
5684	ctsio->kern_data_len = len;
5685	ctsio->kern_total_len = len;
5686	ctsio->kern_data_resid = 0;
5687	ctsio->kern_rel_offset = 0;
5688	ctsio->kern_sg_entries = 0;
5689	ctsio->be_move_done = ctl_config_move_done;
5690	ctl_datamove((union ctl_io *)ctsio);
5691
5692	return (CTL_RETVAL_COMPLETE);
5693}
5694
5695int
5696ctl_write_buffer(struct ctl_scsiio *ctsio)
5697{
5698	struct scsi_write_buffer *cdb;
5699	struct ctl_lun *lun;
5700	int buffer_offset, len;
5701
5702	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5703
5704	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5705	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5706
5707	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5708		ctl_set_invalid_field(ctsio,
5709				      /*sks_valid*/ 1,
5710				      /*command*/ 1,
5711				      /*field*/ 1,
5712				      /*bit_valid*/ 1,
5713				      /*bit*/ 4);
5714		ctl_done((union ctl_io *)ctsio);
5715		return (CTL_RETVAL_COMPLETE);
5716	}
5717
5718	len = scsi_3btoul(cdb->length);
5719	buffer_offset = scsi_3btoul(cdb->offset);
5720
5721	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5722		ctl_set_invalid_field(ctsio,
5723				      /*sks_valid*/ 1,
5724				      /*command*/ 1,
5725				      /*field*/ 6,
5726				      /*bit_valid*/ 0,
5727				      /*bit*/ 0);
5728		ctl_done((union ctl_io *)ctsio);
5729		return (CTL_RETVAL_COMPLETE);
5730	}
5731
5732	/*
5733	 * If we've got a kernel request that hasn't been malloced yet,
5734	 * malloc it and tell the caller the data buffer is here.
5735	 */
5736	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5737		if (lun->write_buffer == NULL) {
5738			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5739			    M_CTL, M_WAITOK);
5740		}
5741		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5742		ctsio->kern_data_len = len;
5743		ctsio->kern_total_len = len;
5744		ctsio->kern_data_resid = 0;
5745		ctsio->kern_rel_offset = 0;
5746		ctsio->kern_sg_entries = 0;
5747		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5748		ctsio->be_move_done = ctl_config_move_done;
5749		ctl_datamove((union ctl_io *)ctsio);
5750
5751		return (CTL_RETVAL_COMPLETE);
5752	}
5753
5754	ctl_done((union ctl_io *)ctsio);
5755
5756	return (CTL_RETVAL_COMPLETE);
5757}
5758
5759int
5760ctl_write_same(struct ctl_scsiio *ctsio)
5761{
5762	struct ctl_lun *lun;
5763	struct ctl_lba_len_flags *lbalen;
5764	uint64_t lba;
5765	uint32_t num_blocks;
5766	int len, retval;
5767	uint8_t byte2;
5768
5769	retval = CTL_RETVAL_COMPLETE;
5770
5771	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5772
5773	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5774
5775	switch (ctsio->cdb[0]) {
5776	case WRITE_SAME_10: {
5777		struct scsi_write_same_10 *cdb;
5778
5779		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5780
5781		lba = scsi_4btoul(cdb->addr);
5782		num_blocks = scsi_2btoul(cdb->length);
5783		byte2 = cdb->byte2;
5784		break;
5785	}
5786	case WRITE_SAME_16: {
5787		struct scsi_write_same_16 *cdb;
5788
5789		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5790
5791		lba = scsi_8btou64(cdb->addr);
5792		num_blocks = scsi_4btoul(cdb->length);
5793		byte2 = cdb->byte2;
5794		break;
5795	}
5796	default:
5797		/*
5798		 * We got a command we don't support.  This shouldn't
5799		 * happen, commands should be filtered out above us.
5800		 */
5801		ctl_set_invalid_opcode(ctsio);
5802		ctl_done((union ctl_io *)ctsio);
5803
5804		return (CTL_RETVAL_COMPLETE);
5805		break; /* NOTREACHED */
5806	}
5807
5808	/* NDOB and ANCHOR flags can be used only together with UNMAP */
5809	if ((byte2 & SWS_UNMAP) == 0 &&
5810	    (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5811		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5812		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5813		ctl_done((union ctl_io *)ctsio);
5814		return (CTL_RETVAL_COMPLETE);
5815	}
5816
5817	/*
5818	 * The first check is to make sure we're in bounds, the second
5819	 * check is to catch wrap-around problems.  If the lba + num blocks
5820	 * is less than the lba, then we've wrapped around and the block
5821	 * range is invalid anyway.
5822	 */
5823	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5824	 || ((lba + num_blocks) < lba)) {
5825		ctl_set_lba_out_of_range(ctsio);
5826		ctl_done((union ctl_io *)ctsio);
5827		return (CTL_RETVAL_COMPLETE);
5828	}
5829
5830	/* Zero number of blocks means "to the last logical block" */
5831	if (num_blocks == 0) {
5832		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5833			ctl_set_invalid_field(ctsio,
5834					      /*sks_valid*/ 0,
5835					      /*command*/ 1,
5836					      /*field*/ 0,
5837					      /*bit_valid*/ 0,
5838					      /*bit*/ 0);
5839			ctl_done((union ctl_io *)ctsio);
5840			return (CTL_RETVAL_COMPLETE);
5841		}
5842		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5843	}
5844
5845	len = lun->be_lun->blocksize;
5846
5847	/*
5848	 * If we've got a kernel request that hasn't been malloced yet,
5849	 * malloc it and tell the caller the data buffer is here.
5850	 */
5851	if ((byte2 & SWS_NDOB) == 0 &&
5852	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5853		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5854		ctsio->kern_data_len = len;
5855		ctsio->kern_total_len = len;
5856		ctsio->kern_data_resid = 0;
5857		ctsio->kern_rel_offset = 0;
5858		ctsio->kern_sg_entries = 0;
5859		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5860		ctsio->be_move_done = ctl_config_move_done;
5861		ctl_datamove((union ctl_io *)ctsio);
5862
5863		return (CTL_RETVAL_COMPLETE);
5864	}
5865
5866	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5867	lbalen->lba = lba;
5868	lbalen->len = num_blocks;
5869	lbalen->flags = byte2;
5870	retval = lun->backend->config_write((union ctl_io *)ctsio);
5871
5872	return (retval);
5873}
5874
5875int
5876ctl_unmap(struct ctl_scsiio *ctsio)
5877{
5878	struct ctl_lun *lun;
5879	struct scsi_unmap *cdb;
5880	struct ctl_ptr_len_flags *ptrlen;
5881	struct scsi_unmap_header *hdr;
5882	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5883	uint64_t lba;
5884	uint32_t num_blocks;
5885	int len, retval;
5886	uint8_t byte2;
5887
5888	retval = CTL_RETVAL_COMPLETE;
5889
5890	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5891
5892	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5893	cdb = (struct scsi_unmap *)ctsio->cdb;
5894
5895	len = scsi_2btoul(cdb->length);
5896	byte2 = cdb->byte2;
5897
5898	/*
5899	 * If we've got a kernel request that hasn't been malloced yet,
5900	 * malloc it and tell the caller the data buffer is here.
5901	 */
5902	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5903		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5904		ctsio->kern_data_len = len;
5905		ctsio->kern_total_len = len;
5906		ctsio->kern_data_resid = 0;
5907		ctsio->kern_rel_offset = 0;
5908		ctsio->kern_sg_entries = 0;
5909		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5910		ctsio->be_move_done = ctl_config_move_done;
5911		ctl_datamove((union ctl_io *)ctsio);
5912
5913		return (CTL_RETVAL_COMPLETE);
5914	}
5915
5916	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5917	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5918	if (len < sizeof (*hdr) ||
5919	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5920	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5921	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5922		ctl_set_invalid_field(ctsio,
5923				      /*sks_valid*/ 0,
5924				      /*command*/ 0,
5925				      /*field*/ 0,
5926				      /*bit_valid*/ 0,
5927				      /*bit*/ 0);
5928		goto done;
5929	}
5930	len = scsi_2btoul(hdr->desc_length);
5931	buf = (struct scsi_unmap_desc *)(hdr + 1);
5932	end = buf + len / sizeof(*buf);
5933
5934	endnz = buf;
5935	for (range = buf; range < end; range++) {
5936		lba = scsi_8btou64(range->lba);
5937		num_blocks = scsi_4btoul(range->length);
5938		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5939		 || ((lba + num_blocks) < lba)) {
5940			ctl_set_lba_out_of_range(ctsio);
5941			ctl_done((union ctl_io *)ctsio);
5942			return (CTL_RETVAL_COMPLETE);
5943		}
5944		if (num_blocks != 0)
5945			endnz = range + 1;
5946	}
5947
5948	/*
5949	 * Block backend can not handle zero last range.
5950	 * Filter it out and return if there is nothing left.
5951	 */
5952	len = (uint8_t *)endnz - (uint8_t *)buf;
5953	if (len == 0) {
5954		ctl_set_success(ctsio);
5955		goto done;
5956	}
5957
5958	mtx_lock(&lun->lun_lock);
5959	ptrlen = (struct ctl_ptr_len_flags *)
5960	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5961	ptrlen->ptr = (void *)buf;
5962	ptrlen->len = len;
5963	ptrlen->flags = byte2;
5964	ctl_check_blocked(lun);
5965	mtx_unlock(&lun->lun_lock);
5966
5967	retval = lun->backend->config_write((union ctl_io *)ctsio);
5968	return (retval);
5969
5970done:
5971	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5972		free(ctsio->kern_data_ptr, M_CTL);
5973		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5974	}
5975	ctl_done((union ctl_io *)ctsio);
5976	return (CTL_RETVAL_COMPLETE);
5977}
5978
5979/*
5980 * Note that this function currently doesn't actually do anything inside
5981 * CTL to enforce things if the DQue bit is turned on.
5982 *
5983 * Also note that this function can't be used in the default case, because
5984 * the DQue bit isn't set in the changeable mask for the control mode page
5985 * anyway.  This is just here as an example for how to implement a page
5986 * handler, and a placeholder in case we want to allow the user to turn
5987 * tagged queueing on and off.
5988 *
5989 * The D_SENSE bit handling is functional, however, and will turn
5990 * descriptor sense on and off for a given LUN.
5991 */
5992int
5993ctl_control_page_handler(struct ctl_scsiio *ctsio,
5994			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5995{
5996	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5997	struct ctl_lun *lun;
5998	struct ctl_softc *softc;
5999	int set_ua;
6000	uint32_t initidx;
6001
6002	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6003	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6004	set_ua = 0;
6005
6006	user_cp = (struct scsi_control_page *)page_ptr;
6007	current_cp = (struct scsi_control_page *)
6008		(page_index->page_data + (page_index->page_len *
6009		CTL_PAGE_CURRENT));
6010	saved_cp = (struct scsi_control_page *)
6011		(page_index->page_data + (page_index->page_len *
6012		CTL_PAGE_SAVED));
6013
6014	softc = control_softc;
6015
6016	mtx_lock(&lun->lun_lock);
6017	if (((current_cp->rlec & SCP_DSENSE) == 0)
6018	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6019		/*
6020		 * Descriptor sense is currently turned off and the user
6021		 * wants to turn it on.
6022		 */
6023		current_cp->rlec |= SCP_DSENSE;
6024		saved_cp->rlec |= SCP_DSENSE;
6025		lun->flags |= CTL_LUN_SENSE_DESC;
6026		set_ua = 1;
6027	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6028		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6029		/*
6030		 * Descriptor sense is currently turned on, and the user
6031		 * wants to turn it off.
6032		 */
6033		current_cp->rlec &= ~SCP_DSENSE;
6034		saved_cp->rlec &= ~SCP_DSENSE;
6035		lun->flags &= ~CTL_LUN_SENSE_DESC;
6036		set_ua = 1;
6037	}
6038	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6039	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6040		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6041		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6042		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6043		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6044		set_ua = 1;
6045	}
6046	if ((current_cp->eca_and_aen & SCP_SWP) !=
6047	    (user_cp->eca_and_aen & SCP_SWP)) {
6048		current_cp->eca_and_aen &= ~SCP_SWP;
6049		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6050		saved_cp->eca_and_aen &= ~SCP_SWP;
6051		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6052		set_ua = 1;
6053	}
6054	if (set_ua != 0) {
6055		int i;
6056		/*
6057		 * Let other initiators know that the mode
6058		 * parameters for this LUN have changed.
6059		 */
6060		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6061			if (i == initidx)
6062				continue;
6063
6064			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6065		}
6066	}
6067	mtx_unlock(&lun->lun_lock);
6068
6069	return (0);
6070}
6071
6072int
6073ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6074		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6075{
6076	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6077	struct ctl_lun *lun;
6078	int set_ua;
6079	uint32_t initidx;
6080
6081	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6082	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6083	set_ua = 0;
6084
6085	user_cp = (struct scsi_caching_page *)page_ptr;
6086	current_cp = (struct scsi_caching_page *)
6087		(page_index->page_data + (page_index->page_len *
6088		CTL_PAGE_CURRENT));
6089	saved_cp = (struct scsi_caching_page *)
6090		(page_index->page_data + (page_index->page_len *
6091		CTL_PAGE_SAVED));
6092
6093	mtx_lock(&lun->lun_lock);
6094	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6095	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6096		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6097		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6098		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6099		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6100		set_ua = 1;
6101	}
6102	if (set_ua != 0) {
6103		int i;
6104		/*
6105		 * Let other initiators know that the mode
6106		 * parameters for this LUN have changed.
6107		 */
6108		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6109			if (i == initidx)
6110				continue;
6111
6112			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6113		}
6114	}
6115	mtx_unlock(&lun->lun_lock);
6116
6117	return (0);
6118}
6119
6120int
6121ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6122				struct ctl_page_index *page_index,
6123				uint8_t *page_ptr)
6124{
6125	uint8_t *c;
6126	int i;
6127
6128	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6129	ctl_time_io_secs =
6130		(c[0] << 8) |
6131		(c[1] << 0) |
6132		0;
6133	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6134	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6135	printf("page data:");
6136	for (i=0; i<8; i++)
6137		printf(" %.2x",page_ptr[i]);
6138	printf("\n");
6139	return (0);
6140}
6141
6142int
6143ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6144			       struct ctl_page_index *page_index,
6145			       int pc)
6146{
6147	struct copan_debugconf_subpage *page;
6148
6149	page = (struct copan_debugconf_subpage *)page_index->page_data +
6150		(page_index->page_len * pc);
6151
6152	switch (pc) {
6153	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6154	case SMS_PAGE_CTRL_DEFAULT >> 6:
6155	case SMS_PAGE_CTRL_SAVED >> 6:
6156		/*
6157		 * We don't update the changable or default bits for this page.
6158		 */
6159		break;
6160	case SMS_PAGE_CTRL_CURRENT >> 6:
6161		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6162		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6163		break;
6164	default:
6165#ifdef NEEDTOPORT
6166		EPRINT(0, "Invalid PC %d!!", pc);
6167#endif /* NEEDTOPORT */
6168		break;
6169	}
6170	return (0);
6171}
6172
6173
6174static int
6175ctl_do_mode_select(union ctl_io *io)
6176{
6177	struct scsi_mode_page_header *page_header;
6178	struct ctl_page_index *page_index;
6179	struct ctl_scsiio *ctsio;
6180	int control_dev, page_len;
6181	int page_len_offset, page_len_size;
6182	union ctl_modepage_info *modepage_info;
6183	struct ctl_lun *lun;
6184	int *len_left, *len_used;
6185	int retval, i;
6186
6187	ctsio = &io->scsiio;
6188	page_index = NULL;
6189	page_len = 0;
6190	retval = CTL_RETVAL_COMPLETE;
6191
6192	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6193
6194	if (lun->be_lun->lun_type != T_DIRECT)
6195		control_dev = 1;
6196	else
6197		control_dev = 0;
6198
6199	modepage_info = (union ctl_modepage_info *)
6200		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6201	len_left = &modepage_info->header.len_left;
6202	len_used = &modepage_info->header.len_used;
6203
6204do_next_page:
6205
6206	page_header = (struct scsi_mode_page_header *)
6207		(ctsio->kern_data_ptr + *len_used);
6208
6209	if (*len_left == 0) {
6210		free(ctsio->kern_data_ptr, M_CTL);
6211		ctl_set_success(ctsio);
6212		ctl_done((union ctl_io *)ctsio);
6213		return (CTL_RETVAL_COMPLETE);
6214	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6215
6216		free(ctsio->kern_data_ptr, M_CTL);
6217		ctl_set_param_len_error(ctsio);
6218		ctl_done((union ctl_io *)ctsio);
6219		return (CTL_RETVAL_COMPLETE);
6220
6221	} else if ((page_header->page_code & SMPH_SPF)
6222		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6223
6224		free(ctsio->kern_data_ptr, M_CTL);
6225		ctl_set_param_len_error(ctsio);
6226		ctl_done((union ctl_io *)ctsio);
6227		return (CTL_RETVAL_COMPLETE);
6228	}
6229
6230
6231	/*
6232	 * XXX KDM should we do something with the block descriptor?
6233	 */
6234	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6235
6236		if ((control_dev != 0)
6237		 && (lun->mode_pages.index[i].page_flags &
6238		     CTL_PAGE_FLAG_DISK_ONLY))
6239			continue;
6240
6241		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6242		    (page_header->page_code & SMPH_PC_MASK))
6243			continue;
6244
6245		/*
6246		 * If neither page has a subpage code, then we've got a
6247		 * match.
6248		 */
6249		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6250		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6251			page_index = &lun->mode_pages.index[i];
6252			page_len = page_header->page_length;
6253			break;
6254		}
6255
6256		/*
6257		 * If both pages have subpages, then the subpage numbers
6258		 * have to match.
6259		 */
6260		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6261		  && (page_header->page_code & SMPH_SPF)) {
6262			struct scsi_mode_page_header_sp *sph;
6263
6264			sph = (struct scsi_mode_page_header_sp *)page_header;
6265
6266			if (lun->mode_pages.index[i].subpage ==
6267			    sph->subpage) {
6268				page_index = &lun->mode_pages.index[i];
6269				page_len = scsi_2btoul(sph->page_length);
6270				break;
6271			}
6272		}
6273	}
6274
6275	/*
6276	 * If we couldn't find the page, or if we don't have a mode select
6277	 * handler for it, send back an error to the user.
6278	 */
6279	if ((page_index == NULL)
6280	 || (page_index->select_handler == NULL)) {
6281		ctl_set_invalid_field(ctsio,
6282				      /*sks_valid*/ 1,
6283				      /*command*/ 0,
6284				      /*field*/ *len_used,
6285				      /*bit_valid*/ 0,
6286				      /*bit*/ 0);
6287		free(ctsio->kern_data_ptr, M_CTL);
6288		ctl_done((union ctl_io *)ctsio);
6289		return (CTL_RETVAL_COMPLETE);
6290	}
6291
6292	if (page_index->page_code & SMPH_SPF) {
6293		page_len_offset = 2;
6294		page_len_size = 2;
6295	} else {
6296		page_len_size = 1;
6297		page_len_offset = 1;
6298	}
6299
6300	/*
6301	 * If the length the initiator gives us isn't the one we specify in
6302	 * the mode page header, or if they didn't specify enough data in
6303	 * the CDB to avoid truncating this page, kick out the request.
6304	 */
6305	if ((page_len != (page_index->page_len - page_len_offset -
6306			  page_len_size))
6307	 || (*len_left < page_index->page_len)) {
6308
6309
6310		ctl_set_invalid_field(ctsio,
6311				      /*sks_valid*/ 1,
6312				      /*command*/ 0,
6313				      /*field*/ *len_used + page_len_offset,
6314				      /*bit_valid*/ 0,
6315				      /*bit*/ 0);
6316		free(ctsio->kern_data_ptr, M_CTL);
6317		ctl_done((union ctl_io *)ctsio);
6318		return (CTL_RETVAL_COMPLETE);
6319	}
6320
6321	/*
6322	 * Run through the mode page, checking to make sure that the bits
6323	 * the user changed are actually legal for him to change.
6324	 */
6325	for (i = 0; i < page_index->page_len; i++) {
6326		uint8_t *user_byte, *change_mask, *current_byte;
6327		int bad_bit;
6328		int j;
6329
6330		user_byte = (uint8_t *)page_header + i;
6331		change_mask = page_index->page_data +
6332			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6333		current_byte = page_index->page_data +
6334			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6335
6336		/*
6337		 * Check to see whether the user set any bits in this byte
6338		 * that he is not allowed to set.
6339		 */
6340		if ((*user_byte & ~(*change_mask)) ==
6341		    (*current_byte & ~(*change_mask)))
6342			continue;
6343
6344		/*
6345		 * Go through bit by bit to determine which one is illegal.
6346		 */
6347		bad_bit = 0;
6348		for (j = 7; j >= 0; j--) {
6349			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6350			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6351				bad_bit = i;
6352				break;
6353			}
6354		}
6355		ctl_set_invalid_field(ctsio,
6356				      /*sks_valid*/ 1,
6357				      /*command*/ 0,
6358				      /*field*/ *len_used + i,
6359				      /*bit_valid*/ 1,
6360				      /*bit*/ bad_bit);
6361		free(ctsio->kern_data_ptr, M_CTL);
6362		ctl_done((union ctl_io *)ctsio);
6363		return (CTL_RETVAL_COMPLETE);
6364	}
6365
6366	/*
6367	 * Decrement these before we call the page handler, since we may
6368	 * end up getting called back one way or another before the handler
6369	 * returns to this context.
6370	 */
6371	*len_left -= page_index->page_len;
6372	*len_used += page_index->page_len;
6373
6374	retval = page_index->select_handler(ctsio, page_index,
6375					    (uint8_t *)page_header);
6376
6377	/*
6378	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6379	 * wait until this queued command completes to finish processing
6380	 * the mode page.  If it returns anything other than
6381	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6382	 * already set the sense information, freed the data pointer, and
6383	 * completed the io for us.
6384	 */
6385	if (retval != CTL_RETVAL_COMPLETE)
6386		goto bailout_no_done;
6387
6388	/*
6389	 * If the initiator sent us more than one page, parse the next one.
6390	 */
6391	if (*len_left > 0)
6392		goto do_next_page;
6393
6394	ctl_set_success(ctsio);
6395	free(ctsio->kern_data_ptr, M_CTL);
6396	ctl_done((union ctl_io *)ctsio);
6397
6398bailout_no_done:
6399
6400	return (CTL_RETVAL_COMPLETE);
6401
6402}
6403
6404int
6405ctl_mode_select(struct ctl_scsiio *ctsio)
6406{
6407	int param_len, pf, sp;
6408	int header_size, bd_len;
6409	int len_left, len_used;
6410	struct ctl_page_index *page_index;
6411	struct ctl_lun *lun;
6412	int control_dev, page_len;
6413	union ctl_modepage_info *modepage_info;
6414	int retval;
6415
6416	pf = 0;
6417	sp = 0;
6418	page_len = 0;
6419	len_used = 0;
6420	len_left = 0;
6421	retval = 0;
6422	bd_len = 0;
6423	page_index = NULL;
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	switch (ctsio->cdb[0]) {
6433	case MODE_SELECT_6: {
6434		struct scsi_mode_select_6 *cdb;
6435
6436		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6437
6438		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6439		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6440
6441		param_len = cdb->length;
6442		header_size = sizeof(struct scsi_mode_header_6);
6443		break;
6444	}
6445	case MODE_SELECT_10: {
6446		struct scsi_mode_select_10 *cdb;
6447
6448		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6449
6450		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6451		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6452
6453		param_len = scsi_2btoul(cdb->length);
6454		header_size = sizeof(struct scsi_mode_header_10);
6455		break;
6456	}
6457	default:
6458		ctl_set_invalid_opcode(ctsio);
6459		ctl_done((union ctl_io *)ctsio);
6460		return (CTL_RETVAL_COMPLETE);
6461		break; /* NOTREACHED */
6462	}
6463
6464	/*
6465	 * From SPC-3:
6466	 * "A parameter list length of zero indicates that the Data-Out Buffer
6467	 * shall be empty. This condition shall not be considered as an error."
6468	 */
6469	if (param_len == 0) {
6470		ctl_set_success(ctsio);
6471		ctl_done((union ctl_io *)ctsio);
6472		return (CTL_RETVAL_COMPLETE);
6473	}
6474
6475	/*
6476	 * Since we'll hit this the first time through, prior to
6477	 * allocation, we don't need to free a data buffer here.
6478	 */
6479	if (param_len < header_size) {
6480		ctl_set_param_len_error(ctsio);
6481		ctl_done((union ctl_io *)ctsio);
6482		return (CTL_RETVAL_COMPLETE);
6483	}
6484
6485	/*
6486	 * Allocate the data buffer and grab the user's data.  In theory,
6487	 * we shouldn't have to sanity check the parameter list length here
6488	 * because the maximum size is 64K.  We should be able to malloc
6489	 * that much without too many problems.
6490	 */
6491	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6492		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6493		ctsio->kern_data_len = param_len;
6494		ctsio->kern_total_len = param_len;
6495		ctsio->kern_data_resid = 0;
6496		ctsio->kern_rel_offset = 0;
6497		ctsio->kern_sg_entries = 0;
6498		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6499		ctsio->be_move_done = ctl_config_move_done;
6500		ctl_datamove((union ctl_io *)ctsio);
6501
6502		return (CTL_RETVAL_COMPLETE);
6503	}
6504
6505	switch (ctsio->cdb[0]) {
6506	case MODE_SELECT_6: {
6507		struct scsi_mode_header_6 *mh6;
6508
6509		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6510		bd_len = mh6->blk_desc_len;
6511		break;
6512	}
6513	case MODE_SELECT_10: {
6514		struct scsi_mode_header_10 *mh10;
6515
6516		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6517		bd_len = scsi_2btoul(mh10->blk_desc_len);
6518		break;
6519	}
6520	default:
6521		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6522		break;
6523	}
6524
6525	if (param_len < (header_size + bd_len)) {
6526		free(ctsio->kern_data_ptr, M_CTL);
6527		ctl_set_param_len_error(ctsio);
6528		ctl_done((union ctl_io *)ctsio);
6529		return (CTL_RETVAL_COMPLETE);
6530	}
6531
6532	/*
6533	 * Set the IO_CONT flag, so that if this I/O gets passed to
6534	 * ctl_config_write_done(), it'll get passed back to
6535	 * ctl_do_mode_select() for further processing, or completion if
6536	 * we're all done.
6537	 */
6538	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6539	ctsio->io_cont = ctl_do_mode_select;
6540
6541	modepage_info = (union ctl_modepage_info *)
6542		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6543
6544	memset(modepage_info, 0, sizeof(*modepage_info));
6545
6546	len_left = param_len - header_size - bd_len;
6547	len_used = header_size + bd_len;
6548
6549	modepage_info->header.len_left = len_left;
6550	modepage_info->header.len_used = len_used;
6551
6552	return (ctl_do_mode_select((union ctl_io *)ctsio));
6553}
6554
6555int
6556ctl_mode_sense(struct ctl_scsiio *ctsio)
6557{
6558	struct ctl_lun *lun;
6559	int pc, page_code, dbd, llba, subpage;
6560	int alloc_len, page_len, header_len, total_len;
6561	struct scsi_mode_block_descr *block_desc;
6562	struct ctl_page_index *page_index;
6563	int control_dev;
6564
6565	dbd = 0;
6566	llba = 0;
6567	block_desc = NULL;
6568	page_index = NULL;
6569
6570	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6571
6572	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6573
6574	if (lun->be_lun->lun_type != T_DIRECT)
6575		control_dev = 1;
6576	else
6577		control_dev = 0;
6578
6579	switch (ctsio->cdb[0]) {
6580	case MODE_SENSE_6: {
6581		struct scsi_mode_sense_6 *cdb;
6582
6583		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6584
6585		header_len = sizeof(struct scsi_mode_hdr_6);
6586		if (cdb->byte2 & SMS_DBD)
6587			dbd = 1;
6588		else
6589			header_len += sizeof(struct scsi_mode_block_descr);
6590
6591		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6592		page_code = cdb->page & SMS_PAGE_CODE;
6593		subpage = cdb->subpage;
6594		alloc_len = cdb->length;
6595		break;
6596	}
6597	case MODE_SENSE_10: {
6598		struct scsi_mode_sense_10 *cdb;
6599
6600		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6601
6602		header_len = sizeof(struct scsi_mode_hdr_10);
6603
6604		if (cdb->byte2 & SMS_DBD)
6605			dbd = 1;
6606		else
6607			header_len += sizeof(struct scsi_mode_block_descr);
6608		if (cdb->byte2 & SMS10_LLBAA)
6609			llba = 1;
6610		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6611		page_code = cdb->page & SMS_PAGE_CODE;
6612		subpage = cdb->subpage;
6613		alloc_len = scsi_2btoul(cdb->length);
6614		break;
6615	}
6616	default:
6617		ctl_set_invalid_opcode(ctsio);
6618		ctl_done((union ctl_io *)ctsio);
6619		return (CTL_RETVAL_COMPLETE);
6620		break; /* NOTREACHED */
6621	}
6622
6623	/*
6624	 * We have to make a first pass through to calculate the size of
6625	 * the pages that match the user's query.  Then we allocate enough
6626	 * memory to hold it, and actually copy the data into the buffer.
6627	 */
6628	switch (page_code) {
6629	case SMS_ALL_PAGES_PAGE: {
6630		int i;
6631
6632		page_len = 0;
6633
6634		/*
6635		 * At the moment, values other than 0 and 0xff here are
6636		 * reserved according to SPC-3.
6637		 */
6638		if ((subpage != SMS_SUBPAGE_PAGE_0)
6639		 && (subpage != SMS_SUBPAGE_ALL)) {
6640			ctl_set_invalid_field(ctsio,
6641					      /*sks_valid*/ 1,
6642					      /*command*/ 1,
6643					      /*field*/ 3,
6644					      /*bit_valid*/ 0,
6645					      /*bit*/ 0);
6646			ctl_done((union ctl_io *)ctsio);
6647			return (CTL_RETVAL_COMPLETE);
6648		}
6649
6650		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6651			if ((control_dev != 0)
6652			 && (lun->mode_pages.index[i].page_flags &
6653			     CTL_PAGE_FLAG_DISK_ONLY))
6654				continue;
6655
6656			/*
6657			 * We don't use this subpage if the user didn't
6658			 * request all subpages.
6659			 */
6660			if ((lun->mode_pages.index[i].subpage != 0)
6661			 && (subpage == SMS_SUBPAGE_PAGE_0))
6662				continue;
6663
6664#if 0
6665			printf("found page %#x len %d\n",
6666			       lun->mode_pages.index[i].page_code &
6667			       SMPH_PC_MASK,
6668			       lun->mode_pages.index[i].page_len);
6669#endif
6670			page_len += lun->mode_pages.index[i].page_len;
6671		}
6672		break;
6673	}
6674	default: {
6675		int i;
6676
6677		page_len = 0;
6678
6679		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6680			/* Look for the right page code */
6681			if ((lun->mode_pages.index[i].page_code &
6682			     SMPH_PC_MASK) != page_code)
6683				continue;
6684
6685			/* Look for the right subpage or the subpage wildcard*/
6686			if ((lun->mode_pages.index[i].subpage != subpage)
6687			 && (subpage != SMS_SUBPAGE_ALL))
6688				continue;
6689
6690			/* Make sure the page is supported for this dev type */
6691			if ((control_dev != 0)
6692			 && (lun->mode_pages.index[i].page_flags &
6693			     CTL_PAGE_FLAG_DISK_ONLY))
6694				continue;
6695
6696#if 0
6697			printf("found page %#x len %d\n",
6698			       lun->mode_pages.index[i].page_code &
6699			       SMPH_PC_MASK,
6700			       lun->mode_pages.index[i].page_len);
6701#endif
6702
6703			page_len += lun->mode_pages.index[i].page_len;
6704		}
6705
6706		if (page_len == 0) {
6707			ctl_set_invalid_field(ctsio,
6708					      /*sks_valid*/ 1,
6709					      /*command*/ 1,
6710					      /*field*/ 2,
6711					      /*bit_valid*/ 1,
6712					      /*bit*/ 5);
6713			ctl_done((union ctl_io *)ctsio);
6714			return (CTL_RETVAL_COMPLETE);
6715		}
6716		break;
6717	}
6718	}
6719
6720	total_len = header_len + page_len;
6721#if 0
6722	printf("header_len = %d, page_len = %d, total_len = %d\n",
6723	       header_len, page_len, total_len);
6724#endif
6725
6726	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6727	ctsio->kern_sg_entries = 0;
6728	ctsio->kern_data_resid = 0;
6729	ctsio->kern_rel_offset = 0;
6730	if (total_len < alloc_len) {
6731		ctsio->residual = alloc_len - total_len;
6732		ctsio->kern_data_len = total_len;
6733		ctsio->kern_total_len = total_len;
6734	} else {
6735		ctsio->residual = 0;
6736		ctsio->kern_data_len = alloc_len;
6737		ctsio->kern_total_len = alloc_len;
6738	}
6739
6740	switch (ctsio->cdb[0]) {
6741	case MODE_SENSE_6: {
6742		struct scsi_mode_hdr_6 *header;
6743
6744		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6745
6746		header->datalen = ctl_min(total_len - 1, 254);
6747		if (control_dev == 0) {
6748			header->dev_specific = 0x10; /* DPOFUA */
6749			if ((lun->flags & CTL_LUN_READONLY) ||
6750			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6751			    .eca_and_aen & SCP_SWP) != 0)
6752				    header->dev_specific |= 0x80; /* WP */
6753		}
6754		if (dbd)
6755			header->block_descr_len = 0;
6756		else
6757			header->block_descr_len =
6758				sizeof(struct scsi_mode_block_descr);
6759		block_desc = (struct scsi_mode_block_descr *)&header[1];
6760		break;
6761	}
6762	case MODE_SENSE_10: {
6763		struct scsi_mode_hdr_10 *header;
6764		int datalen;
6765
6766		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6767
6768		datalen = ctl_min(total_len - 2, 65533);
6769		scsi_ulto2b(datalen, header->datalen);
6770		if (control_dev == 0) {
6771			header->dev_specific = 0x10; /* DPOFUA */
6772			if ((lun->flags & CTL_LUN_READONLY) ||
6773			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6774			    .eca_and_aen & SCP_SWP) != 0)
6775				    header->dev_specific |= 0x80; /* WP */
6776		}
6777		if (dbd)
6778			scsi_ulto2b(0, header->block_descr_len);
6779		else
6780			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6781				    header->block_descr_len);
6782		block_desc = (struct scsi_mode_block_descr *)&header[1];
6783		break;
6784	}
6785	default:
6786		panic("invalid CDB type %#x", ctsio->cdb[0]);
6787		break; /* NOTREACHED */
6788	}
6789
6790	/*
6791	 * If we've got a disk, use its blocksize in the block
6792	 * descriptor.  Otherwise, just set it to 0.
6793	 */
6794	if (dbd == 0) {
6795		if (control_dev == 0)
6796			scsi_ulto3b(lun->be_lun->blocksize,
6797				    block_desc->block_len);
6798		else
6799			scsi_ulto3b(0, block_desc->block_len);
6800	}
6801
6802	switch (page_code) {
6803	case SMS_ALL_PAGES_PAGE: {
6804		int i, data_used;
6805
6806		data_used = header_len;
6807		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6808			struct ctl_page_index *page_index;
6809
6810			page_index = &lun->mode_pages.index[i];
6811
6812			if ((control_dev != 0)
6813			 && (page_index->page_flags &
6814			    CTL_PAGE_FLAG_DISK_ONLY))
6815				continue;
6816
6817			/*
6818			 * We don't use this subpage if the user didn't
6819			 * request all subpages.  We already checked (above)
6820			 * to make sure the user only specified a subpage
6821			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6822			 */
6823			if ((page_index->subpage != 0)
6824			 && (subpage == SMS_SUBPAGE_PAGE_0))
6825				continue;
6826
6827			/*
6828			 * Call the handler, if it exists, to update the
6829			 * page to the latest values.
6830			 */
6831			if (page_index->sense_handler != NULL)
6832				page_index->sense_handler(ctsio, page_index,pc);
6833
6834			memcpy(ctsio->kern_data_ptr + data_used,
6835			       page_index->page_data +
6836			       (page_index->page_len * pc),
6837			       page_index->page_len);
6838			data_used += page_index->page_len;
6839		}
6840		break;
6841	}
6842	default: {
6843		int i, data_used;
6844
6845		data_used = header_len;
6846
6847		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6848			struct ctl_page_index *page_index;
6849
6850			page_index = &lun->mode_pages.index[i];
6851
6852			/* Look for the right page code */
6853			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6854				continue;
6855
6856			/* Look for the right subpage or the subpage wildcard*/
6857			if ((page_index->subpage != subpage)
6858			 && (subpage != SMS_SUBPAGE_ALL))
6859				continue;
6860
6861			/* Make sure the page is supported for this dev type */
6862			if ((control_dev != 0)
6863			 && (page_index->page_flags &
6864			     CTL_PAGE_FLAG_DISK_ONLY))
6865				continue;
6866
6867			/*
6868			 * Call the handler, if it exists, to update the
6869			 * page to the latest values.
6870			 */
6871			if (page_index->sense_handler != NULL)
6872				page_index->sense_handler(ctsio, page_index,pc);
6873
6874			memcpy(ctsio->kern_data_ptr + data_used,
6875			       page_index->page_data +
6876			       (page_index->page_len * pc),
6877			       page_index->page_len);
6878			data_used += page_index->page_len;
6879		}
6880		break;
6881	}
6882	}
6883
6884	ctsio->scsi_status = SCSI_STATUS_OK;
6885
6886	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6887	ctsio->be_move_done = ctl_config_move_done;
6888	ctl_datamove((union ctl_io *)ctsio);
6889
6890	return (CTL_RETVAL_COMPLETE);
6891}
6892
6893int
6894ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6895			       struct ctl_page_index *page_index,
6896			       int pc)
6897{
6898	struct ctl_lun *lun;
6899	struct scsi_log_param_header *phdr;
6900	uint8_t *data;
6901	uint64_t val;
6902
6903	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6904	data = page_index->page_data;
6905
6906	if (lun->backend->lun_attr != NULL &&
6907	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6908	     != UINT64_MAX) {
6909		phdr = (struct scsi_log_param_header *)data;
6910		scsi_ulto2b(0x0001, phdr->param_code);
6911		phdr->param_control = SLP_LBIN | SLP_LP;
6912		phdr->param_len = 8;
6913		data = (uint8_t *)(phdr + 1);
6914		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6915		data[4] = 0x02; /* per-pool */
6916		data += phdr->param_len;
6917	}
6918
6919	if (lun->backend->lun_attr != NULL &&
6920	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6921	     != UINT64_MAX) {
6922		phdr = (struct scsi_log_param_header *)data;
6923		scsi_ulto2b(0x0002, phdr->param_code);
6924		phdr->param_control = SLP_LBIN | SLP_LP;
6925		phdr->param_len = 8;
6926		data = (uint8_t *)(phdr + 1);
6927		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6928		data[4] = 0x01; /* per-LUN */
6929		data += phdr->param_len;
6930	}
6931
6932	if (lun->backend->lun_attr != NULL &&
6933	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6934	     != UINT64_MAX) {
6935		phdr = (struct scsi_log_param_header *)data;
6936		scsi_ulto2b(0x00f1, phdr->param_code);
6937		phdr->param_control = SLP_LBIN | SLP_LP;
6938		phdr->param_len = 8;
6939		data = (uint8_t *)(phdr + 1);
6940		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6941		data[4] = 0x02; /* per-pool */
6942		data += phdr->param_len;
6943	}
6944
6945	if (lun->backend->lun_attr != NULL &&
6946	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6947	     != UINT64_MAX) {
6948		phdr = (struct scsi_log_param_header *)data;
6949		scsi_ulto2b(0x00f2, phdr->param_code);
6950		phdr->param_control = SLP_LBIN | SLP_LP;
6951		phdr->param_len = 8;
6952		data = (uint8_t *)(phdr + 1);
6953		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6954		data[4] = 0x02; /* per-pool */
6955		data += phdr->param_len;
6956	}
6957
6958	page_index->page_len = data - page_index->page_data;
6959	return (0);
6960}
6961
6962int
6963ctl_log_sense(struct ctl_scsiio *ctsio)
6964{
6965	struct ctl_lun *lun;
6966	int i, pc, page_code, subpage;
6967	int alloc_len, total_len;
6968	struct ctl_page_index *page_index;
6969	struct scsi_log_sense *cdb;
6970	struct scsi_log_header *header;
6971
6972	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6973
6974	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6975	cdb = (struct scsi_log_sense *)ctsio->cdb;
6976	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6977	page_code = cdb->page & SLS_PAGE_CODE;
6978	subpage = cdb->subpage;
6979	alloc_len = scsi_2btoul(cdb->length);
6980
6981	page_index = NULL;
6982	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6983		page_index = &lun->log_pages.index[i];
6984
6985		/* Look for the right page code */
6986		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6987			continue;
6988
6989		/* Look for the right subpage or the subpage wildcard*/
6990		if (page_index->subpage != subpage)
6991			continue;
6992
6993		break;
6994	}
6995	if (i >= CTL_NUM_LOG_PAGES) {
6996		ctl_set_invalid_field(ctsio,
6997				      /*sks_valid*/ 1,
6998				      /*command*/ 1,
6999				      /*field*/ 2,
7000				      /*bit_valid*/ 0,
7001				      /*bit*/ 0);
7002		ctl_done((union ctl_io *)ctsio);
7003		return (CTL_RETVAL_COMPLETE);
7004	}
7005
7006	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
7007
7008	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7009	ctsio->kern_sg_entries = 0;
7010	ctsio->kern_data_resid = 0;
7011	ctsio->kern_rel_offset = 0;
7012	if (total_len < alloc_len) {
7013		ctsio->residual = alloc_len - total_len;
7014		ctsio->kern_data_len = total_len;
7015		ctsio->kern_total_len = total_len;
7016	} else {
7017		ctsio->residual = 0;
7018		ctsio->kern_data_len = alloc_len;
7019		ctsio->kern_total_len = alloc_len;
7020	}
7021
7022	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7023	header->page = page_index->page_code;
7024	if (page_index->subpage) {
7025		header->page |= SL_SPF;
7026		header->subpage = page_index->subpage;
7027	}
7028	scsi_ulto2b(page_index->page_len, header->datalen);
7029
7030	/*
7031	 * Call the handler, if it exists, to update the
7032	 * page to the latest values.
7033	 */
7034	if (page_index->sense_handler != NULL)
7035		page_index->sense_handler(ctsio, page_index, pc);
7036
7037	memcpy(header + 1, page_index->page_data, page_index->page_len);
7038
7039	ctsio->scsi_status = SCSI_STATUS_OK;
7040	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7041	ctsio->be_move_done = ctl_config_move_done;
7042	ctl_datamove((union ctl_io *)ctsio);
7043
7044	return (CTL_RETVAL_COMPLETE);
7045}
7046
7047int
7048ctl_read_capacity(struct ctl_scsiio *ctsio)
7049{
7050	struct scsi_read_capacity *cdb;
7051	struct scsi_read_capacity_data *data;
7052	struct ctl_lun *lun;
7053	uint32_t lba;
7054
7055	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7056
7057	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7058
7059	lba = scsi_4btoul(cdb->addr);
7060	if (((cdb->pmi & SRC_PMI) == 0)
7061	 && (lba != 0)) {
7062		ctl_set_invalid_field(/*ctsio*/ ctsio,
7063				      /*sks_valid*/ 1,
7064				      /*command*/ 1,
7065				      /*field*/ 2,
7066				      /*bit_valid*/ 0,
7067				      /*bit*/ 0);
7068		ctl_done((union ctl_io *)ctsio);
7069		return (CTL_RETVAL_COMPLETE);
7070	}
7071
7072	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7073
7074	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7075	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7076	ctsio->residual = 0;
7077	ctsio->kern_data_len = sizeof(*data);
7078	ctsio->kern_total_len = sizeof(*data);
7079	ctsio->kern_data_resid = 0;
7080	ctsio->kern_rel_offset = 0;
7081	ctsio->kern_sg_entries = 0;
7082
7083	/*
7084	 * If the maximum LBA is greater than 0xfffffffe, the user must
7085	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7086	 * serivce action set.
7087	 */
7088	if (lun->be_lun->maxlba > 0xfffffffe)
7089		scsi_ulto4b(0xffffffff, data->addr);
7090	else
7091		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7092
7093	/*
7094	 * XXX KDM this may not be 512 bytes...
7095	 */
7096	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7097
7098	ctsio->scsi_status = SCSI_STATUS_OK;
7099
7100	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7101	ctsio->be_move_done = ctl_config_move_done;
7102	ctl_datamove((union ctl_io *)ctsio);
7103
7104	return (CTL_RETVAL_COMPLETE);
7105}
7106
7107int
7108ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7109{
7110	struct scsi_read_capacity_16 *cdb;
7111	struct scsi_read_capacity_data_long *data;
7112	struct ctl_lun *lun;
7113	uint64_t lba;
7114	uint32_t alloc_len;
7115
7116	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7117
7118	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7119
7120	alloc_len = scsi_4btoul(cdb->alloc_len);
7121	lba = scsi_8btou64(cdb->addr);
7122
7123	if ((cdb->reladr & SRC16_PMI)
7124	 && (lba != 0)) {
7125		ctl_set_invalid_field(/*ctsio*/ ctsio,
7126				      /*sks_valid*/ 1,
7127				      /*command*/ 1,
7128				      /*field*/ 2,
7129				      /*bit_valid*/ 0,
7130				      /*bit*/ 0);
7131		ctl_done((union ctl_io *)ctsio);
7132		return (CTL_RETVAL_COMPLETE);
7133	}
7134
7135	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7136
7137	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7138	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7139
7140	if (sizeof(*data) < alloc_len) {
7141		ctsio->residual = alloc_len - sizeof(*data);
7142		ctsio->kern_data_len = sizeof(*data);
7143		ctsio->kern_total_len = sizeof(*data);
7144	} else {
7145		ctsio->residual = 0;
7146		ctsio->kern_data_len = alloc_len;
7147		ctsio->kern_total_len = alloc_len;
7148	}
7149	ctsio->kern_data_resid = 0;
7150	ctsio->kern_rel_offset = 0;
7151	ctsio->kern_sg_entries = 0;
7152
7153	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7154	/* XXX KDM this may not be 512 bytes... */
7155	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7156	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7157	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7158	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7159		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7160
7161	ctsio->scsi_status = SCSI_STATUS_OK;
7162
7163	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7164	ctsio->be_move_done = ctl_config_move_done;
7165	ctl_datamove((union ctl_io *)ctsio);
7166
7167	return (CTL_RETVAL_COMPLETE);
7168}
7169
7170int
7171ctl_read_defect(struct ctl_scsiio *ctsio)
7172{
7173	struct scsi_read_defect_data_10 *ccb10;
7174	struct scsi_read_defect_data_12 *ccb12;
7175	struct scsi_read_defect_data_hdr_10 *data10;
7176	struct scsi_read_defect_data_hdr_12 *data12;
7177	uint32_t alloc_len, data_len;
7178	uint8_t format;
7179
7180	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7181
7182	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7183		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7184		format = ccb10->format;
7185		alloc_len = scsi_2btoul(ccb10->alloc_length);
7186		data_len = sizeof(*data10);
7187	} else {
7188		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7189		format = ccb12->format;
7190		alloc_len = scsi_4btoul(ccb12->alloc_length);
7191		data_len = sizeof(*data12);
7192	}
7193	if (alloc_len == 0) {
7194		ctl_set_success(ctsio);
7195		ctl_done((union ctl_io *)ctsio);
7196		return (CTL_RETVAL_COMPLETE);
7197	}
7198
7199	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7200	if (data_len < alloc_len) {
7201		ctsio->residual = alloc_len - data_len;
7202		ctsio->kern_data_len = data_len;
7203		ctsio->kern_total_len = data_len;
7204	} else {
7205		ctsio->residual = 0;
7206		ctsio->kern_data_len = alloc_len;
7207		ctsio->kern_total_len = alloc_len;
7208	}
7209	ctsio->kern_data_resid = 0;
7210	ctsio->kern_rel_offset = 0;
7211	ctsio->kern_sg_entries = 0;
7212
7213	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7214		data10 = (struct scsi_read_defect_data_hdr_10 *)
7215		    ctsio->kern_data_ptr;
7216		data10->format = format;
7217		scsi_ulto2b(0, data10->length);
7218	} else {
7219		data12 = (struct scsi_read_defect_data_hdr_12 *)
7220		    ctsio->kern_data_ptr;
7221		data12->format = format;
7222		scsi_ulto2b(0, data12->generation);
7223		scsi_ulto4b(0, data12->length);
7224	}
7225
7226	ctsio->scsi_status = SCSI_STATUS_OK;
7227	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7228	ctsio->be_move_done = ctl_config_move_done;
7229	ctl_datamove((union ctl_io *)ctsio);
7230	return (CTL_RETVAL_COMPLETE);
7231}
7232
7233int
7234ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7235{
7236	struct scsi_maintenance_in *cdb;
7237	int retval;
7238	int alloc_len, ext, total_len = 0, g, p, pc, pg, gs, os;
7239	int num_target_port_groups, num_target_ports;
7240	struct ctl_lun *lun;
7241	struct ctl_softc *softc;
7242	struct ctl_port *port;
7243	struct scsi_target_group_data *rtg_ptr;
7244	struct scsi_target_group_data_extended *rtg_ext_ptr;
7245	struct scsi_target_port_group_descriptor *tpg_desc;
7246
7247	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7248
7249	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7250	softc = control_softc;
7251	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7252
7253	retval = CTL_RETVAL_COMPLETE;
7254
7255	switch (cdb->byte2 & STG_PDF_MASK) {
7256	case STG_PDF_LENGTH:
7257		ext = 0;
7258		break;
7259	case STG_PDF_EXTENDED:
7260		ext = 1;
7261		break;
7262	default:
7263		ctl_set_invalid_field(/*ctsio*/ ctsio,
7264				      /*sks_valid*/ 1,
7265				      /*command*/ 1,
7266				      /*field*/ 2,
7267				      /*bit_valid*/ 1,
7268				      /*bit*/ 5);
7269		ctl_done((union ctl_io *)ctsio);
7270		return(retval);
7271	}
7272
7273	if (softc->is_single)
7274		num_target_port_groups = 1;
7275	else
7276		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7277	num_target_ports = 0;
7278	mtx_lock(&softc->ctl_lock);
7279	STAILQ_FOREACH(port, &softc->port_list, links) {
7280		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7281			continue;
7282		if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7283			continue;
7284		num_target_ports++;
7285	}
7286	mtx_unlock(&softc->ctl_lock);
7287
7288	if (ext)
7289		total_len = sizeof(struct scsi_target_group_data_extended);
7290	else
7291		total_len = sizeof(struct scsi_target_group_data);
7292	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7293		num_target_port_groups +
7294	    sizeof(struct scsi_target_port_descriptor) *
7295		num_target_ports * num_target_port_groups;
7296
7297	alloc_len = scsi_4btoul(cdb->length);
7298
7299	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7300
7301	ctsio->kern_sg_entries = 0;
7302
7303	if (total_len < alloc_len) {
7304		ctsio->residual = alloc_len - total_len;
7305		ctsio->kern_data_len = total_len;
7306		ctsio->kern_total_len = total_len;
7307	} else {
7308		ctsio->residual = 0;
7309		ctsio->kern_data_len = alloc_len;
7310		ctsio->kern_total_len = alloc_len;
7311	}
7312	ctsio->kern_data_resid = 0;
7313	ctsio->kern_rel_offset = 0;
7314
7315	if (ext) {
7316		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7317		    ctsio->kern_data_ptr;
7318		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7319		rtg_ext_ptr->format_type = 0x10;
7320		rtg_ext_ptr->implicit_transition_time = 0;
7321		tpg_desc = &rtg_ext_ptr->groups[0];
7322	} else {
7323		rtg_ptr = (struct scsi_target_group_data *)
7324		    ctsio->kern_data_ptr;
7325		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7326		tpg_desc = &rtg_ptr->groups[0];
7327	}
7328
7329	mtx_lock(&softc->ctl_lock);
7330	pg = softc->port_offset / CTL_MAX_PORTS;
7331	if (softc->flags & CTL_FLAG_ACTIVE_SHELF) {
7332		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY) {
7333			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7334			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7335		} else if (lun->flags & CTL_LUN_PRIMARY_SC) {
7336			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7337			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7338		} else {
7339			gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7340			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7341		}
7342	} else {
7343		gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7344		os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7345	}
7346	for (g = 0; g < num_target_port_groups; g++) {
7347		tpg_desc->pref_state = (g == pg) ? gs : os;
7348		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP;
7349		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7350		tpg_desc->status = TPG_IMPLICIT;
7351		pc = 0;
7352		STAILQ_FOREACH(port, &softc->port_list, links) {
7353			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7354				continue;
7355			if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7356			    CTL_MAX_LUNS)
7357				continue;
7358			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7359			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7360			    relative_target_port_identifier);
7361			pc++;
7362		}
7363		tpg_desc->target_port_count = pc;
7364		tpg_desc = (struct scsi_target_port_group_descriptor *)
7365		    &tpg_desc->descriptors[pc];
7366	}
7367	mtx_unlock(&softc->ctl_lock);
7368
7369	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7370	ctsio->be_move_done = ctl_config_move_done;
7371
7372	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7373			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7374			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7375			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7376			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7377
7378	ctl_datamove((union ctl_io *)ctsio);
7379	return(retval);
7380}
7381
7382int
7383ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7384{
7385	struct ctl_lun *lun;
7386	struct scsi_report_supported_opcodes *cdb;
7387	const struct ctl_cmd_entry *entry, *sentry;
7388	struct scsi_report_supported_opcodes_all *all;
7389	struct scsi_report_supported_opcodes_descr *descr;
7390	struct scsi_report_supported_opcodes_one *one;
7391	int retval;
7392	int alloc_len, total_len;
7393	int opcode, service_action, i, j, num;
7394
7395	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7396
7397	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7398	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7399
7400	retval = CTL_RETVAL_COMPLETE;
7401
7402	opcode = cdb->requested_opcode;
7403	service_action = scsi_2btoul(cdb->requested_service_action);
7404	switch (cdb->options & RSO_OPTIONS_MASK) {
7405	case RSO_OPTIONS_ALL:
7406		num = 0;
7407		for (i = 0; i < 256; i++) {
7408			entry = &ctl_cmd_table[i];
7409			if (entry->flags & CTL_CMD_FLAG_SA5) {
7410				for (j = 0; j < 32; j++) {
7411					sentry = &((const struct ctl_cmd_entry *)
7412					    entry->execute)[j];
7413					if (ctl_cmd_applicable(
7414					    lun->be_lun->lun_type, sentry))
7415						num++;
7416				}
7417			} else {
7418				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7419				    entry))
7420					num++;
7421			}
7422		}
7423		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7424		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7425		break;
7426	case RSO_OPTIONS_OC:
7427		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7428			ctl_set_invalid_field(/*ctsio*/ ctsio,
7429					      /*sks_valid*/ 1,
7430					      /*command*/ 1,
7431					      /*field*/ 2,
7432					      /*bit_valid*/ 1,
7433					      /*bit*/ 2);
7434			ctl_done((union ctl_io *)ctsio);
7435			return (CTL_RETVAL_COMPLETE);
7436		}
7437		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7438		break;
7439	case RSO_OPTIONS_OC_SA:
7440		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7441		    service_action >= 32) {
7442			ctl_set_invalid_field(/*ctsio*/ ctsio,
7443					      /*sks_valid*/ 1,
7444					      /*command*/ 1,
7445					      /*field*/ 2,
7446					      /*bit_valid*/ 1,
7447					      /*bit*/ 2);
7448			ctl_done((union ctl_io *)ctsio);
7449			return (CTL_RETVAL_COMPLETE);
7450		}
7451		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7452		break;
7453	default:
7454		ctl_set_invalid_field(/*ctsio*/ ctsio,
7455				      /*sks_valid*/ 1,
7456				      /*command*/ 1,
7457				      /*field*/ 2,
7458				      /*bit_valid*/ 1,
7459				      /*bit*/ 2);
7460		ctl_done((union ctl_io *)ctsio);
7461		return (CTL_RETVAL_COMPLETE);
7462	}
7463
7464	alloc_len = scsi_4btoul(cdb->length);
7465
7466	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7467
7468	ctsio->kern_sg_entries = 0;
7469
7470	if (total_len < alloc_len) {
7471		ctsio->residual = alloc_len - total_len;
7472		ctsio->kern_data_len = total_len;
7473		ctsio->kern_total_len = total_len;
7474	} else {
7475		ctsio->residual = 0;
7476		ctsio->kern_data_len = alloc_len;
7477		ctsio->kern_total_len = alloc_len;
7478	}
7479	ctsio->kern_data_resid = 0;
7480	ctsio->kern_rel_offset = 0;
7481
7482	switch (cdb->options & RSO_OPTIONS_MASK) {
7483	case RSO_OPTIONS_ALL:
7484		all = (struct scsi_report_supported_opcodes_all *)
7485		    ctsio->kern_data_ptr;
7486		num = 0;
7487		for (i = 0; i < 256; i++) {
7488			entry = &ctl_cmd_table[i];
7489			if (entry->flags & CTL_CMD_FLAG_SA5) {
7490				for (j = 0; j < 32; j++) {
7491					sentry = &((const struct ctl_cmd_entry *)
7492					    entry->execute)[j];
7493					if (!ctl_cmd_applicable(
7494					    lun->be_lun->lun_type, sentry))
7495						continue;
7496					descr = &all->descr[num++];
7497					descr->opcode = i;
7498					scsi_ulto2b(j, descr->service_action);
7499					descr->flags = RSO_SERVACTV;
7500					scsi_ulto2b(sentry->length,
7501					    descr->cdb_length);
7502				}
7503			} else {
7504				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7505				    entry))
7506					continue;
7507				descr = &all->descr[num++];
7508				descr->opcode = i;
7509				scsi_ulto2b(0, descr->service_action);
7510				descr->flags = 0;
7511				scsi_ulto2b(entry->length, descr->cdb_length);
7512			}
7513		}
7514		scsi_ulto4b(
7515		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7516		    all->length);
7517		break;
7518	case RSO_OPTIONS_OC:
7519		one = (struct scsi_report_supported_opcodes_one *)
7520		    ctsio->kern_data_ptr;
7521		entry = &ctl_cmd_table[opcode];
7522		goto fill_one;
7523	case RSO_OPTIONS_OC_SA:
7524		one = (struct scsi_report_supported_opcodes_one *)
7525		    ctsio->kern_data_ptr;
7526		entry = &ctl_cmd_table[opcode];
7527		entry = &((const struct ctl_cmd_entry *)
7528		    entry->execute)[service_action];
7529fill_one:
7530		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7531			one->support = 3;
7532			scsi_ulto2b(entry->length, one->cdb_length);
7533			one->cdb_usage[0] = opcode;
7534			memcpy(&one->cdb_usage[1], entry->usage,
7535			    entry->length - 1);
7536		} else
7537			one->support = 1;
7538		break;
7539	}
7540
7541	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7542	ctsio->be_move_done = ctl_config_move_done;
7543
7544	ctl_datamove((union ctl_io *)ctsio);
7545	return(retval);
7546}
7547
7548int
7549ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7550{
7551	struct scsi_report_supported_tmf *cdb;
7552	struct scsi_report_supported_tmf_data *data;
7553	int retval;
7554	int alloc_len, total_len;
7555
7556	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7557
7558	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7559
7560	retval = CTL_RETVAL_COMPLETE;
7561
7562	total_len = sizeof(struct scsi_report_supported_tmf_data);
7563	alloc_len = scsi_4btoul(cdb->length);
7564
7565	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7566
7567	ctsio->kern_sg_entries = 0;
7568
7569	if (total_len < alloc_len) {
7570		ctsio->residual = alloc_len - total_len;
7571		ctsio->kern_data_len = total_len;
7572		ctsio->kern_total_len = total_len;
7573	} else {
7574		ctsio->residual = 0;
7575		ctsio->kern_data_len = alloc_len;
7576		ctsio->kern_total_len = alloc_len;
7577	}
7578	ctsio->kern_data_resid = 0;
7579	ctsio->kern_rel_offset = 0;
7580
7581	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7582	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7583	data->byte2 |= RST_ITNRS;
7584
7585	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7586	ctsio->be_move_done = ctl_config_move_done;
7587
7588	ctl_datamove((union ctl_io *)ctsio);
7589	return (retval);
7590}
7591
7592int
7593ctl_report_timestamp(struct ctl_scsiio *ctsio)
7594{
7595	struct scsi_report_timestamp *cdb;
7596	struct scsi_report_timestamp_data *data;
7597	struct timeval tv;
7598	int64_t timestamp;
7599	int retval;
7600	int alloc_len, total_len;
7601
7602	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7603
7604	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7605
7606	retval = CTL_RETVAL_COMPLETE;
7607
7608	total_len = sizeof(struct scsi_report_timestamp_data);
7609	alloc_len = scsi_4btoul(cdb->length);
7610
7611	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7612
7613	ctsio->kern_sg_entries = 0;
7614
7615	if (total_len < alloc_len) {
7616		ctsio->residual = alloc_len - total_len;
7617		ctsio->kern_data_len = total_len;
7618		ctsio->kern_total_len = total_len;
7619	} else {
7620		ctsio->residual = 0;
7621		ctsio->kern_data_len = alloc_len;
7622		ctsio->kern_total_len = alloc_len;
7623	}
7624	ctsio->kern_data_resid = 0;
7625	ctsio->kern_rel_offset = 0;
7626
7627	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7628	scsi_ulto2b(sizeof(*data) - 2, data->length);
7629	data->origin = RTS_ORIG_OUTSIDE;
7630	getmicrotime(&tv);
7631	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7632	scsi_ulto4b(timestamp >> 16, data->timestamp);
7633	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7634
7635	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7636	ctsio->be_move_done = ctl_config_move_done;
7637
7638	ctl_datamove((union ctl_io *)ctsio);
7639	return (retval);
7640}
7641
7642int
7643ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7644{
7645	struct scsi_per_res_in *cdb;
7646	int alloc_len, total_len = 0;
7647	/* struct scsi_per_res_in_rsrv in_data; */
7648	struct ctl_lun *lun;
7649	struct ctl_softc *softc;
7650
7651	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7652
7653	softc = control_softc;
7654
7655	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7656
7657	alloc_len = scsi_2btoul(cdb->length);
7658
7659	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7660
7661retry:
7662	mtx_lock(&lun->lun_lock);
7663	switch (cdb->action) {
7664	case SPRI_RK: /* read keys */
7665		total_len = sizeof(struct scsi_per_res_in_keys) +
7666			lun->pr_key_count *
7667			sizeof(struct scsi_per_res_key);
7668		break;
7669	case SPRI_RR: /* read reservation */
7670		if (lun->flags & CTL_LUN_PR_RESERVED)
7671			total_len = sizeof(struct scsi_per_res_in_rsrv);
7672		else
7673			total_len = sizeof(struct scsi_per_res_in_header);
7674		break;
7675	case SPRI_RC: /* report capabilities */
7676		total_len = sizeof(struct scsi_per_res_cap);
7677		break;
7678	case SPRI_RS: /* read full status */
7679		total_len = sizeof(struct scsi_per_res_in_header) +
7680		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7681		    lun->pr_key_count;
7682		break;
7683	default:
7684		panic("Invalid PR type %x", cdb->action);
7685	}
7686	mtx_unlock(&lun->lun_lock);
7687
7688	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7689
7690	if (total_len < alloc_len) {
7691		ctsio->residual = alloc_len - total_len;
7692		ctsio->kern_data_len = total_len;
7693		ctsio->kern_total_len = total_len;
7694	} else {
7695		ctsio->residual = 0;
7696		ctsio->kern_data_len = alloc_len;
7697		ctsio->kern_total_len = alloc_len;
7698	}
7699
7700	ctsio->kern_data_resid = 0;
7701	ctsio->kern_rel_offset = 0;
7702	ctsio->kern_sg_entries = 0;
7703
7704	mtx_lock(&lun->lun_lock);
7705	switch (cdb->action) {
7706	case SPRI_RK: { // read keys
7707        struct scsi_per_res_in_keys *res_keys;
7708		int i, key_count;
7709
7710		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7711
7712		/*
7713		 * We had to drop the lock to allocate our buffer, which
7714		 * leaves time for someone to come in with another
7715		 * persistent reservation.  (That is unlikely, though,
7716		 * since this should be the only persistent reservation
7717		 * command active right now.)
7718		 */
7719		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7720		    (lun->pr_key_count *
7721		     sizeof(struct scsi_per_res_key)))){
7722			mtx_unlock(&lun->lun_lock);
7723			free(ctsio->kern_data_ptr, M_CTL);
7724			printf("%s: reservation length changed, retrying\n",
7725			       __func__);
7726			goto retry;
7727		}
7728
7729		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7730
7731		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7732			     lun->pr_key_count, res_keys->header.length);
7733
7734		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7735			if (lun->pr_keys[i] == 0)
7736				continue;
7737
7738			/*
7739			 * We used lun->pr_key_count to calculate the
7740			 * size to allocate.  If it turns out the number of
7741			 * initiators with the registered flag set is
7742			 * larger than that (i.e. they haven't been kept in
7743			 * sync), we've got a problem.
7744			 */
7745			if (key_count >= lun->pr_key_count) {
7746#ifdef NEEDTOPORT
7747				csevent_log(CSC_CTL | CSC_SHELF_SW |
7748					    CTL_PR_ERROR,
7749					    csevent_LogType_Fault,
7750					    csevent_AlertLevel_Yellow,
7751					    csevent_FRU_ShelfController,
7752					    csevent_FRU_Firmware,
7753				        csevent_FRU_Unknown,
7754					    "registered keys %d >= key "
7755					    "count %d", key_count,
7756					    lun->pr_key_count);
7757#endif
7758				key_count++;
7759				continue;
7760			}
7761			scsi_u64to8b(lun->pr_keys[i],
7762			    res_keys->keys[key_count].key);
7763			key_count++;
7764		}
7765		break;
7766	}
7767	case SPRI_RR: { // read reservation
7768		struct scsi_per_res_in_rsrv *res;
7769		int tmp_len, header_only;
7770
7771		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7772
7773		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7774
7775		if (lun->flags & CTL_LUN_PR_RESERVED)
7776		{
7777			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7778			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7779				    res->header.length);
7780			header_only = 0;
7781		} else {
7782			tmp_len = sizeof(struct scsi_per_res_in_header);
7783			scsi_ulto4b(0, res->header.length);
7784			header_only = 1;
7785		}
7786
7787		/*
7788		 * We had to drop the lock to allocate our buffer, which
7789		 * leaves time for someone to come in with another
7790		 * persistent reservation.  (That is unlikely, though,
7791		 * since this should be the only persistent reservation
7792		 * command active right now.)
7793		 */
7794		if (tmp_len != total_len) {
7795			mtx_unlock(&lun->lun_lock);
7796			free(ctsio->kern_data_ptr, M_CTL);
7797			printf("%s: reservation status changed, retrying\n",
7798			       __func__);
7799			goto retry;
7800		}
7801
7802		/*
7803		 * No reservation held, so we're done.
7804		 */
7805		if (header_only != 0)
7806			break;
7807
7808		/*
7809		 * If the registration is an All Registrants type, the key
7810		 * is 0, since it doesn't really matter.
7811		 */
7812		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7813			scsi_u64to8b(lun->pr_keys[lun->pr_res_idx],
7814			    res->data.reservation);
7815		}
7816		res->data.scopetype = lun->res_type;
7817		break;
7818	}
7819	case SPRI_RC:     //report capabilities
7820	{
7821		struct scsi_per_res_cap *res_cap;
7822		uint16_t type_mask;
7823
7824		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7825		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7826		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7827		type_mask = SPRI_TM_WR_EX_AR |
7828			    SPRI_TM_EX_AC_RO |
7829			    SPRI_TM_WR_EX_RO |
7830			    SPRI_TM_EX_AC |
7831			    SPRI_TM_WR_EX |
7832			    SPRI_TM_EX_AC_AR;
7833		scsi_ulto2b(type_mask, res_cap->type_mask);
7834		break;
7835	}
7836	case SPRI_RS: { // read full status
7837		struct scsi_per_res_in_full *res_status;
7838		struct scsi_per_res_in_full_desc *res_desc;
7839		struct ctl_port *port;
7840		int i, len;
7841
7842		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7843
7844		/*
7845		 * We had to drop the lock to allocate our buffer, which
7846		 * leaves time for someone to come in with another
7847		 * persistent reservation.  (That is unlikely, though,
7848		 * since this should be the only persistent reservation
7849		 * command active right now.)
7850		 */
7851		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7852		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7853		     lun->pr_key_count)){
7854			mtx_unlock(&lun->lun_lock);
7855			free(ctsio->kern_data_ptr, M_CTL);
7856			printf("%s: reservation length changed, retrying\n",
7857			       __func__);
7858			goto retry;
7859		}
7860
7861		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7862
7863		res_desc = &res_status->desc[0];
7864		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7865			if (lun->pr_keys[i] == 0)
7866				continue;
7867
7868			scsi_u64to8b(lun->pr_keys[i], res_desc->res_key.key);
7869			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7870			    (lun->pr_res_idx == i ||
7871			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7872				res_desc->flags = SPRI_FULL_R_HOLDER;
7873				res_desc->scopetype = lun->res_type;
7874			}
7875			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7876			    res_desc->rel_trgt_port_id);
7877			len = 0;
7878			port = softc->ctl_ports[
7879			    ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
7880			if (port != NULL)
7881				len = ctl_create_iid(port,
7882				    i % CTL_MAX_INIT_PER_PORT,
7883				    res_desc->transport_id);
7884			scsi_ulto4b(len, res_desc->additional_length);
7885			res_desc = (struct scsi_per_res_in_full_desc *)
7886			    &res_desc->transport_id[len];
7887		}
7888		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7889		    res_status->header.length);
7890		break;
7891	}
7892	default:
7893		/*
7894		 * This is a bug, because we just checked for this above,
7895		 * and should have returned an error.
7896		 */
7897		panic("Invalid PR type %x", cdb->action);
7898		break; /* NOTREACHED */
7899	}
7900	mtx_unlock(&lun->lun_lock);
7901
7902	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7903	ctsio->be_move_done = ctl_config_move_done;
7904
7905	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7906			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7907			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7908			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7909			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7910
7911	ctl_datamove((union ctl_io *)ctsio);
7912
7913	return (CTL_RETVAL_COMPLETE);
7914}
7915
7916/*
7917 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7918 * it should return.
7919 */
7920static int
7921ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7922		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7923		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7924		struct scsi_per_res_out_parms* param)
7925{
7926	union ctl_ha_msg persis_io;
7927	int retval, i;
7928	int isc_retval;
7929
7930	retval = 0;
7931
7932	mtx_lock(&lun->lun_lock);
7933	if (sa_res_key == 0) {
7934		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7935			/* validate scope and type */
7936			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7937			     SPR_LU_SCOPE) {
7938				mtx_unlock(&lun->lun_lock);
7939				ctl_set_invalid_field(/*ctsio*/ ctsio,
7940						      /*sks_valid*/ 1,
7941						      /*command*/ 1,
7942						      /*field*/ 2,
7943						      /*bit_valid*/ 1,
7944						      /*bit*/ 4);
7945				ctl_done((union ctl_io *)ctsio);
7946				return (1);
7947			}
7948
7949		        if (type>8 || type==2 || type==4 || type==0) {
7950				mtx_unlock(&lun->lun_lock);
7951				ctl_set_invalid_field(/*ctsio*/ ctsio,
7952       	           				      /*sks_valid*/ 1,
7953						      /*command*/ 1,
7954						      /*field*/ 2,
7955						      /*bit_valid*/ 1,
7956						      /*bit*/ 0);
7957				ctl_done((union ctl_io *)ctsio);
7958				return (1);
7959		        }
7960
7961			/*
7962			 * Unregister everybody else and build UA for
7963			 * them
7964			 */
7965			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7966				if (i == residx || lun->pr_keys[i] == 0)
7967					continue;
7968
7969				if (!persis_offset
7970				 && i <CTL_MAX_INITIATORS)
7971					lun->pending_ua[i] |=
7972						CTL_UA_REG_PREEMPT;
7973				else if (persis_offset
7974				      && i >= persis_offset)
7975					lun->pending_ua[i-persis_offset] |=
7976						CTL_UA_REG_PREEMPT;
7977				lun->pr_keys[i] = 0;
7978			}
7979			lun->pr_key_count = 1;
7980			lun->res_type = type;
7981			if (lun->res_type != SPR_TYPE_WR_EX_AR
7982			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7983				lun->pr_res_idx = residx;
7984
7985			/* send msg to other side */
7986			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7987			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7988			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7989			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7990			persis_io.pr.pr_info.res_type = type;
7991			memcpy(persis_io.pr.pr_info.sa_res_key,
7992			       param->serv_act_res_key,
7993			       sizeof(param->serv_act_res_key));
7994			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7995			     &persis_io, sizeof(persis_io), 0)) >
7996			     CTL_HA_STATUS_SUCCESS) {
7997				printf("CTL:Persis Out error returned "
7998				       "from ctl_ha_msg_send %d\n",
7999				       isc_retval);
8000			}
8001		} else {
8002			/* not all registrants */
8003			mtx_unlock(&lun->lun_lock);
8004			free(ctsio->kern_data_ptr, M_CTL);
8005			ctl_set_invalid_field(ctsio,
8006					      /*sks_valid*/ 1,
8007					      /*command*/ 0,
8008					      /*field*/ 8,
8009					      /*bit_valid*/ 0,
8010					      /*bit*/ 0);
8011			ctl_done((union ctl_io *)ctsio);
8012			return (1);
8013		}
8014	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8015		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8016		int found = 0;
8017
8018		if (res_key == sa_res_key) {
8019			/* special case */
8020			/*
8021			 * The spec implies this is not good but doesn't
8022			 * say what to do. There are two choices either
8023			 * generate a res conflict or check condition
8024			 * with illegal field in parameter data. Since
8025			 * that is what is done when the sa_res_key is
8026			 * zero I'll take that approach since this has
8027			 * to do with the sa_res_key.
8028			 */
8029			mtx_unlock(&lun->lun_lock);
8030			free(ctsio->kern_data_ptr, M_CTL);
8031			ctl_set_invalid_field(ctsio,
8032					      /*sks_valid*/ 1,
8033					      /*command*/ 0,
8034					      /*field*/ 8,
8035					      /*bit_valid*/ 0,
8036					      /*bit*/ 0);
8037			ctl_done((union ctl_io *)ctsio);
8038			return (1);
8039		}
8040
8041		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8042			if (lun->pr_keys[i] != sa_res_key)
8043				continue;
8044
8045			found = 1;
8046			lun->pr_keys[i] = 0;
8047			lun->pr_key_count--;
8048
8049			if (!persis_offset && i < CTL_MAX_INITIATORS)
8050				lun->pending_ua[i] |= CTL_UA_REG_PREEMPT;
8051			else if (persis_offset && i >= persis_offset)
8052				lun->pending_ua[i-persis_offset] |=
8053					CTL_UA_REG_PREEMPT;
8054		}
8055		if (!found) {
8056			mtx_unlock(&lun->lun_lock);
8057			free(ctsio->kern_data_ptr, M_CTL);
8058			ctl_set_reservation_conflict(ctsio);
8059			ctl_done((union ctl_io *)ctsio);
8060			return (CTL_RETVAL_COMPLETE);
8061		}
8062		/* send msg to other side */
8063		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8064		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8065		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8066		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8067		persis_io.pr.pr_info.res_type = type;
8068		memcpy(persis_io.pr.pr_info.sa_res_key,
8069		       param->serv_act_res_key,
8070		       sizeof(param->serv_act_res_key));
8071		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8072		     &persis_io, sizeof(persis_io), 0)) >
8073		     CTL_HA_STATUS_SUCCESS) {
8074			printf("CTL:Persis Out error returned from "
8075			       "ctl_ha_msg_send %d\n", isc_retval);
8076		}
8077	} else {
8078		/* Reserved but not all registrants */
8079		/* sa_res_key is res holder */
8080		if (sa_res_key == lun->pr_keys[lun->pr_res_idx]) {
8081			/* validate scope and type */
8082			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8083			     SPR_LU_SCOPE) {
8084				mtx_unlock(&lun->lun_lock);
8085				ctl_set_invalid_field(/*ctsio*/ ctsio,
8086						      /*sks_valid*/ 1,
8087						      /*command*/ 1,
8088						      /*field*/ 2,
8089						      /*bit_valid*/ 1,
8090						      /*bit*/ 4);
8091				ctl_done((union ctl_io *)ctsio);
8092				return (1);
8093			}
8094
8095			if (type>8 || type==2 || type==4 || type==0) {
8096				mtx_unlock(&lun->lun_lock);
8097				ctl_set_invalid_field(/*ctsio*/ ctsio,
8098						      /*sks_valid*/ 1,
8099						      /*command*/ 1,
8100						      /*field*/ 2,
8101						      /*bit_valid*/ 1,
8102						      /*bit*/ 0);
8103				ctl_done((union ctl_io *)ctsio);
8104				return (1);
8105			}
8106
8107			/*
8108			 * Do the following:
8109			 * if sa_res_key != res_key remove all
8110			 * registrants w/sa_res_key and generate UA
8111			 * for these registrants(Registrations
8112			 * Preempted) if it wasn't an exclusive
8113			 * reservation generate UA(Reservations
8114			 * Preempted) for all other registered nexuses
8115			 * if the type has changed. Establish the new
8116			 * reservation and holder. If res_key and
8117			 * sa_res_key are the same do the above
8118			 * except don't unregister the res holder.
8119			 */
8120
8121			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8122				if (i == residx || lun->pr_keys[i] == 0)
8123					continue;
8124
8125				if (sa_res_key == lun->pr_keys[i]) {
8126					lun->pr_keys[i] = 0;
8127					lun->pr_key_count--;
8128
8129					if (!persis_offset
8130					 && i < CTL_MAX_INITIATORS)
8131						lun->pending_ua[i] |=
8132							CTL_UA_REG_PREEMPT;
8133					else if (persis_offset
8134					      && i >= persis_offset)
8135						lun->pending_ua[i-persis_offset] |=
8136						  CTL_UA_REG_PREEMPT;
8137				} else if (type != lun->res_type
8138					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8139					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8140						if (!persis_offset
8141						 && i < CTL_MAX_INITIATORS)
8142							lun->pending_ua[i] |=
8143							CTL_UA_RES_RELEASE;
8144						else if (persis_offset
8145						      && i >= persis_offset)
8146							lun->pending_ua[
8147							i-persis_offset] |=
8148							CTL_UA_RES_RELEASE;
8149				}
8150			}
8151			lun->res_type = type;
8152			if (lun->res_type != SPR_TYPE_WR_EX_AR
8153			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8154				lun->pr_res_idx = residx;
8155			else
8156				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8157
8158			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8159			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8160			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8161			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8162			persis_io.pr.pr_info.res_type = type;
8163			memcpy(persis_io.pr.pr_info.sa_res_key,
8164			       param->serv_act_res_key,
8165			       sizeof(param->serv_act_res_key));
8166			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8167			     &persis_io, sizeof(persis_io), 0)) >
8168			     CTL_HA_STATUS_SUCCESS) {
8169				printf("CTL:Persis Out error returned "
8170				       "from ctl_ha_msg_send %d\n",
8171				       isc_retval);
8172			}
8173		} else {
8174			/*
8175			 * sa_res_key is not the res holder just
8176			 * remove registrants
8177			 */
8178			int found=0;
8179
8180			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8181				if (sa_res_key != lun->pr_keys[i])
8182					continue;
8183
8184				found = 1;
8185				lun->pr_keys[i] = 0;
8186				lun->pr_key_count--;
8187
8188				if (!persis_offset
8189				 && i < CTL_MAX_INITIATORS)
8190					lun->pending_ua[i] |=
8191						CTL_UA_REG_PREEMPT;
8192				else if (persis_offset
8193				      && i >= persis_offset)
8194					lun->pending_ua[i-persis_offset] |=
8195						CTL_UA_REG_PREEMPT;
8196			}
8197
8198			if (!found) {
8199				mtx_unlock(&lun->lun_lock);
8200				free(ctsio->kern_data_ptr, M_CTL);
8201				ctl_set_reservation_conflict(ctsio);
8202				ctl_done((union ctl_io *)ctsio);
8203		        	return (1);
8204			}
8205			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8206			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8207			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8208			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8209			persis_io.pr.pr_info.res_type = type;
8210			memcpy(persis_io.pr.pr_info.sa_res_key,
8211			       param->serv_act_res_key,
8212			       sizeof(param->serv_act_res_key));
8213			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8214			     &persis_io, sizeof(persis_io), 0)) >
8215			     CTL_HA_STATUS_SUCCESS) {
8216				printf("CTL:Persis Out error returned "
8217				       "from ctl_ha_msg_send %d\n",
8218				isc_retval);
8219			}
8220		}
8221	}
8222
8223	lun->PRGeneration++;
8224	mtx_unlock(&lun->lun_lock);
8225
8226	return (retval);
8227}
8228
8229static void
8230ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8231{
8232	uint64_t sa_res_key;
8233	int i;
8234
8235	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8236
8237	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8238	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8239	 || sa_res_key != lun->pr_keys[lun->pr_res_idx]) {
8240		if (sa_res_key == 0) {
8241			/*
8242			 * Unregister everybody else and build UA for
8243			 * them
8244			 */
8245			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8246				if (i == msg->pr.pr_info.residx ||
8247				    lun->pr_keys[i] == 0)
8248					continue;
8249
8250				if (!persis_offset
8251				 && i < CTL_MAX_INITIATORS)
8252					lun->pending_ua[i] |=
8253						CTL_UA_REG_PREEMPT;
8254				else if (persis_offset && i >= persis_offset)
8255					lun->pending_ua[i - persis_offset] |=
8256						CTL_UA_REG_PREEMPT;
8257				lun->pr_keys[i] = 0;
8258			}
8259
8260			lun->pr_key_count = 1;
8261			lun->res_type = msg->pr.pr_info.res_type;
8262			if (lun->res_type != SPR_TYPE_WR_EX_AR
8263			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8264				lun->pr_res_idx = msg->pr.pr_info.residx;
8265		} else {
8266		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8267				if (sa_res_key == lun->pr_keys[i])
8268					continue;
8269
8270				lun->pr_keys[i] = 0;
8271				lun->pr_key_count--;
8272
8273				if (!persis_offset
8274				 && i < persis_offset)
8275					lun->pending_ua[i] |=
8276						CTL_UA_REG_PREEMPT;
8277				else if (persis_offset
8278				      && i >= persis_offset)
8279					lun->pending_ua[i - persis_offset] |=
8280						CTL_UA_REG_PREEMPT;
8281			}
8282		}
8283	} else {
8284		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8285			if (i == msg->pr.pr_info.residx ||
8286			    lun->pr_keys[i] == 0)
8287				continue;
8288
8289			if (sa_res_key == lun->pr_keys[i]) {
8290				lun->pr_keys[i] = 0;
8291				lun->pr_key_count--;
8292				if (!persis_offset
8293				 && i < CTL_MAX_INITIATORS)
8294					lun->pending_ua[i] |=
8295						CTL_UA_REG_PREEMPT;
8296				else if (persis_offset
8297				      && i >= persis_offset)
8298					lun->pending_ua[i - persis_offset] |=
8299						CTL_UA_REG_PREEMPT;
8300			} else if (msg->pr.pr_info.res_type != lun->res_type
8301				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8302				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8303					if (!persis_offset
8304					 && i < persis_offset)
8305						lun->pending_ua[i] |=
8306							CTL_UA_RES_RELEASE;
8307					else if (persis_offset
8308					      && i >= persis_offset)
8309					lun->pending_ua[i - persis_offset] |=
8310						CTL_UA_RES_RELEASE;
8311			}
8312		}
8313		lun->res_type = msg->pr.pr_info.res_type;
8314		if (lun->res_type != SPR_TYPE_WR_EX_AR
8315		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8316			lun->pr_res_idx = msg->pr.pr_info.residx;
8317		else
8318			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8319	}
8320	lun->PRGeneration++;
8321
8322}
8323
8324
8325int
8326ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8327{
8328	int retval;
8329	int isc_retval;
8330	u_int32_t param_len;
8331	struct scsi_per_res_out *cdb;
8332	struct ctl_lun *lun;
8333	struct scsi_per_res_out_parms* param;
8334	struct ctl_softc *softc;
8335	uint32_t residx;
8336	uint64_t res_key, sa_res_key;
8337	uint8_t type;
8338	union ctl_ha_msg persis_io;
8339	int    i;
8340
8341	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8342
8343	retval = CTL_RETVAL_COMPLETE;
8344
8345	softc = control_softc;
8346
8347	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8348	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8349
8350	/*
8351	 * We only support whole-LUN scope.  The scope & type are ignored for
8352	 * register, register and ignore existing key and clear.
8353	 * We sometimes ignore scope and type on preempts too!!
8354	 * Verify reservation type here as well.
8355	 */
8356	type = cdb->scope_type & SPR_TYPE_MASK;
8357	if ((cdb->action == SPRO_RESERVE)
8358	 || (cdb->action == SPRO_RELEASE)) {
8359		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8360			ctl_set_invalid_field(/*ctsio*/ ctsio,
8361					      /*sks_valid*/ 1,
8362					      /*command*/ 1,
8363					      /*field*/ 2,
8364					      /*bit_valid*/ 1,
8365					      /*bit*/ 4);
8366			ctl_done((union ctl_io *)ctsio);
8367			return (CTL_RETVAL_COMPLETE);
8368		}
8369
8370		if (type>8 || type==2 || type==4 || type==0) {
8371			ctl_set_invalid_field(/*ctsio*/ ctsio,
8372					      /*sks_valid*/ 1,
8373					      /*command*/ 1,
8374					      /*field*/ 2,
8375					      /*bit_valid*/ 1,
8376					      /*bit*/ 0);
8377			ctl_done((union ctl_io *)ctsio);
8378			return (CTL_RETVAL_COMPLETE);
8379		}
8380	}
8381
8382	param_len = scsi_4btoul(cdb->length);
8383
8384	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8385		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8386		ctsio->kern_data_len = param_len;
8387		ctsio->kern_total_len = param_len;
8388		ctsio->kern_data_resid = 0;
8389		ctsio->kern_rel_offset = 0;
8390		ctsio->kern_sg_entries = 0;
8391		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8392		ctsio->be_move_done = ctl_config_move_done;
8393		ctl_datamove((union ctl_io *)ctsio);
8394
8395		return (CTL_RETVAL_COMPLETE);
8396	}
8397
8398	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8399
8400	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8401	res_key = scsi_8btou64(param->res_key.key);
8402	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8403
8404	/*
8405	 * Validate the reservation key here except for SPRO_REG_IGNO
8406	 * This must be done for all other service actions
8407	 */
8408	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8409		mtx_lock(&lun->lun_lock);
8410		if (lun->pr_keys[residx] != 0) {
8411		    if (res_key != lun->pr_keys[residx]) {
8412				/*
8413				 * The current key passed in doesn't match
8414				 * the one the initiator previously
8415				 * registered.
8416				 */
8417				mtx_unlock(&lun->lun_lock);
8418				free(ctsio->kern_data_ptr, M_CTL);
8419				ctl_set_reservation_conflict(ctsio);
8420				ctl_done((union ctl_io *)ctsio);
8421				return (CTL_RETVAL_COMPLETE);
8422			}
8423		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8424			/*
8425			 * We are not registered
8426			 */
8427			mtx_unlock(&lun->lun_lock);
8428			free(ctsio->kern_data_ptr, M_CTL);
8429			ctl_set_reservation_conflict(ctsio);
8430			ctl_done((union ctl_io *)ctsio);
8431			return (CTL_RETVAL_COMPLETE);
8432		} else if (res_key != 0) {
8433			/*
8434			 * We are not registered and trying to register but
8435			 * the register key isn't zero.
8436			 */
8437			mtx_unlock(&lun->lun_lock);
8438			free(ctsio->kern_data_ptr, M_CTL);
8439			ctl_set_reservation_conflict(ctsio);
8440			ctl_done((union ctl_io *)ctsio);
8441			return (CTL_RETVAL_COMPLETE);
8442		}
8443		mtx_unlock(&lun->lun_lock);
8444	}
8445
8446	switch (cdb->action & SPRO_ACTION_MASK) {
8447	case SPRO_REGISTER:
8448	case SPRO_REG_IGNO: {
8449
8450#if 0
8451		printf("Registration received\n");
8452#endif
8453
8454		/*
8455		 * We don't support any of these options, as we report in
8456		 * the read capabilities request (see
8457		 * ctl_persistent_reserve_in(), above).
8458		 */
8459		if ((param->flags & SPR_SPEC_I_PT)
8460		 || (param->flags & SPR_ALL_TG_PT)
8461		 || (param->flags & SPR_APTPL)) {
8462			int bit_ptr;
8463
8464			if (param->flags & SPR_APTPL)
8465				bit_ptr = 0;
8466			else if (param->flags & SPR_ALL_TG_PT)
8467				bit_ptr = 2;
8468			else /* SPR_SPEC_I_PT */
8469				bit_ptr = 3;
8470
8471			free(ctsio->kern_data_ptr, M_CTL);
8472			ctl_set_invalid_field(ctsio,
8473					      /*sks_valid*/ 1,
8474					      /*command*/ 0,
8475					      /*field*/ 20,
8476					      /*bit_valid*/ 1,
8477					      /*bit*/ bit_ptr);
8478			ctl_done((union ctl_io *)ctsio);
8479			return (CTL_RETVAL_COMPLETE);
8480		}
8481
8482		mtx_lock(&lun->lun_lock);
8483
8484		/*
8485		 * The initiator wants to clear the
8486		 * key/unregister.
8487		 */
8488		if (sa_res_key == 0) {
8489			if ((res_key == 0
8490			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8491			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8492			  && lun->pr_keys[residx] == 0)) {
8493				mtx_unlock(&lun->lun_lock);
8494				goto done;
8495			}
8496
8497			lun->pr_keys[residx] = 0;
8498			lun->pr_key_count--;
8499
8500			if (residx == lun->pr_res_idx) {
8501				lun->flags &= ~CTL_LUN_PR_RESERVED;
8502				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8503
8504				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8505				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8506				 && lun->pr_key_count) {
8507					/*
8508					 * If the reservation is a registrants
8509					 * only type we need to generate a UA
8510					 * for other registered inits.  The
8511					 * sense code should be RESERVATIONS
8512					 * RELEASED
8513					 */
8514
8515					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8516						if (lun->pr_keys[
8517						    i + persis_offset] == 0)
8518							continue;
8519						lun->pending_ua[i] |=
8520							CTL_UA_RES_RELEASE;
8521					}
8522				}
8523				lun->res_type = 0;
8524			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8525				if (lun->pr_key_count==0) {
8526					lun->flags &= ~CTL_LUN_PR_RESERVED;
8527					lun->res_type = 0;
8528					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8529				}
8530			}
8531			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8532			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8533			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8534			persis_io.pr.pr_info.residx = residx;
8535			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8536			     &persis_io, sizeof(persis_io), 0 )) >
8537			     CTL_HA_STATUS_SUCCESS) {
8538				printf("CTL:Persis Out error returned from "
8539				       "ctl_ha_msg_send %d\n", isc_retval);
8540			}
8541		} else /* sa_res_key != 0 */ {
8542
8543			/*
8544			 * If we aren't registered currently then increment
8545			 * the key count and set the registered flag.
8546			 */
8547			if (lun->pr_keys[residx] == 0)
8548				lun->pr_key_count++;
8549			lun->pr_keys[residx] = sa_res_key;
8550
8551			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8552			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8553			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8554			persis_io.pr.pr_info.residx = residx;
8555			memcpy(persis_io.pr.pr_info.sa_res_key,
8556			       param->serv_act_res_key,
8557			       sizeof(param->serv_act_res_key));
8558			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8559			     &persis_io, sizeof(persis_io), 0)) >
8560			     CTL_HA_STATUS_SUCCESS) {
8561				printf("CTL:Persis Out error returned from "
8562				       "ctl_ha_msg_send %d\n", isc_retval);
8563			}
8564		}
8565		lun->PRGeneration++;
8566		mtx_unlock(&lun->lun_lock);
8567
8568		break;
8569	}
8570	case SPRO_RESERVE:
8571#if 0
8572                printf("Reserve executed type %d\n", type);
8573#endif
8574		mtx_lock(&lun->lun_lock);
8575		if (lun->flags & CTL_LUN_PR_RESERVED) {
8576			/*
8577			 * if this isn't the reservation holder and it's
8578			 * not a "all registrants" type or if the type is
8579			 * different then we have a conflict
8580			 */
8581			if ((lun->pr_res_idx != residx
8582			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8583			 || lun->res_type != type) {
8584				mtx_unlock(&lun->lun_lock);
8585				free(ctsio->kern_data_ptr, M_CTL);
8586				ctl_set_reservation_conflict(ctsio);
8587				ctl_done((union ctl_io *)ctsio);
8588				return (CTL_RETVAL_COMPLETE);
8589			}
8590			mtx_unlock(&lun->lun_lock);
8591		} else /* create a reservation */ {
8592			/*
8593			 * If it's not an "all registrants" type record
8594			 * reservation holder
8595			 */
8596			if (type != SPR_TYPE_WR_EX_AR
8597			 && type != SPR_TYPE_EX_AC_AR)
8598				lun->pr_res_idx = residx; /* Res holder */
8599			else
8600				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8601
8602			lun->flags |= CTL_LUN_PR_RESERVED;
8603			lun->res_type = type;
8604
8605			mtx_unlock(&lun->lun_lock);
8606
8607			/* send msg to other side */
8608			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8609			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8610			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8611			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8612			persis_io.pr.pr_info.res_type = type;
8613			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8614			     &persis_io, sizeof(persis_io), 0)) >
8615			     CTL_HA_STATUS_SUCCESS) {
8616				printf("CTL:Persis Out error returned from "
8617				       "ctl_ha_msg_send %d\n", isc_retval);
8618			}
8619		}
8620		break;
8621
8622	case SPRO_RELEASE:
8623		mtx_lock(&lun->lun_lock);
8624		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8625			/* No reservation exists return good status */
8626			mtx_unlock(&lun->lun_lock);
8627			goto done;
8628		}
8629		/*
8630		 * Is this nexus a reservation holder?
8631		 */
8632		if (lun->pr_res_idx != residx
8633		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8634			/*
8635			 * not a res holder return good status but
8636			 * do nothing
8637			 */
8638			mtx_unlock(&lun->lun_lock);
8639			goto done;
8640		}
8641
8642		if (lun->res_type != type) {
8643			mtx_unlock(&lun->lun_lock);
8644			free(ctsio->kern_data_ptr, M_CTL);
8645			ctl_set_illegal_pr_release(ctsio);
8646			ctl_done((union ctl_io *)ctsio);
8647			return (CTL_RETVAL_COMPLETE);
8648		}
8649
8650		/* okay to release */
8651		lun->flags &= ~CTL_LUN_PR_RESERVED;
8652		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8653		lun->res_type = 0;
8654
8655		/*
8656		 * if this isn't an exclusive access
8657		 * res generate UA for all other
8658		 * registrants.
8659		 */
8660		if (type != SPR_TYPE_EX_AC
8661		 && type != SPR_TYPE_WR_EX) {
8662			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8663				if (i == residx ||
8664				    lun->pr_keys[i + persis_offset] == 0)
8665					continue;
8666				lun->pending_ua[i] |= CTL_UA_RES_RELEASE;
8667			}
8668		}
8669		mtx_unlock(&lun->lun_lock);
8670		/* Send msg to other side */
8671		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8672		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8673		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8674		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8675		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8676			printf("CTL:Persis Out error returned from "
8677			       "ctl_ha_msg_send %d\n", isc_retval);
8678		}
8679		break;
8680
8681	case SPRO_CLEAR:
8682		/* send msg to other side */
8683
8684		mtx_lock(&lun->lun_lock);
8685		lun->flags &= ~CTL_LUN_PR_RESERVED;
8686		lun->res_type = 0;
8687		lun->pr_key_count = 0;
8688		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8689
8690		lun->pr_keys[residx] = 0;
8691
8692		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8693			if (lun->pr_keys[i] != 0) {
8694				if (!persis_offset && i < CTL_MAX_INITIATORS)
8695					lun->pending_ua[i] |=
8696						CTL_UA_RES_PREEMPT;
8697				else if (persis_offset && i >= persis_offset)
8698					lun->pending_ua[i-persis_offset] |=
8699					    CTL_UA_RES_PREEMPT;
8700
8701				lun->pr_keys[i] = 0;
8702			}
8703		lun->PRGeneration++;
8704		mtx_unlock(&lun->lun_lock);
8705		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8706		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8707		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8708		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8709		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8710			printf("CTL:Persis Out error returned from "
8711			       "ctl_ha_msg_send %d\n", isc_retval);
8712		}
8713		break;
8714
8715	case SPRO_PREEMPT:
8716	case SPRO_PRE_ABO: {
8717		int nretval;
8718
8719		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8720					  residx, ctsio, cdb, param);
8721		if (nretval != 0)
8722			return (CTL_RETVAL_COMPLETE);
8723		break;
8724	}
8725	default:
8726		panic("Invalid PR type %x", cdb->action);
8727	}
8728
8729done:
8730	free(ctsio->kern_data_ptr, M_CTL);
8731	ctl_set_success(ctsio);
8732	ctl_done((union ctl_io *)ctsio);
8733
8734	return (retval);
8735}
8736
8737/*
8738 * This routine is for handling a message from the other SC pertaining to
8739 * persistent reserve out. All the error checking will have been done
8740 * so only perorming the action need be done here to keep the two
8741 * in sync.
8742 */
8743static void
8744ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8745{
8746	struct ctl_lun *lun;
8747	struct ctl_softc *softc;
8748	int i;
8749	uint32_t targ_lun;
8750
8751	softc = control_softc;
8752
8753	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8754	lun = softc->ctl_luns[targ_lun];
8755	mtx_lock(&lun->lun_lock);
8756	switch(msg->pr.pr_info.action) {
8757	case CTL_PR_REG_KEY:
8758		if (lun->pr_keys[msg->pr.pr_info.residx] == 0)
8759			lun->pr_key_count++;
8760		lun->pr_keys[msg->pr.pr_info.residx] =
8761		    scsi_8btou64(msg->pr.pr_info.sa_res_key);
8762		lun->PRGeneration++;
8763		break;
8764
8765	case CTL_PR_UNREG_KEY:
8766		lun->pr_keys[msg->pr.pr_info.residx] = 0;
8767		lun->pr_key_count--;
8768
8769		/* XXX Need to see if the reservation has been released */
8770		/* if so do we need to generate UA? */
8771		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8772			lun->flags &= ~CTL_LUN_PR_RESERVED;
8773			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8774
8775			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8776			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8777			 && lun->pr_key_count) {
8778				/*
8779				 * If the reservation is a registrants
8780				 * only type we need to generate a UA
8781				 * for other registered inits.  The
8782				 * sense code should be RESERVATIONS
8783				 * RELEASED
8784				 */
8785
8786				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8787					if (lun->pr_keys[i+
8788					    persis_offset] == 0)
8789						continue;
8790
8791					lun->pending_ua[i] |=
8792						CTL_UA_RES_RELEASE;
8793				}
8794			}
8795			lun->res_type = 0;
8796		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8797			if (lun->pr_key_count==0) {
8798				lun->flags &= ~CTL_LUN_PR_RESERVED;
8799				lun->res_type = 0;
8800				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8801			}
8802		}
8803		lun->PRGeneration++;
8804		break;
8805
8806	case CTL_PR_RESERVE:
8807		lun->flags |= CTL_LUN_PR_RESERVED;
8808		lun->res_type = msg->pr.pr_info.res_type;
8809		lun->pr_res_idx = msg->pr.pr_info.residx;
8810
8811		break;
8812
8813	case CTL_PR_RELEASE:
8814		/*
8815		 * if this isn't an exclusive access res generate UA for all
8816		 * other registrants.
8817		 */
8818		if (lun->res_type != SPR_TYPE_EX_AC
8819		 && lun->res_type != SPR_TYPE_WR_EX) {
8820			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8821				if (lun->pr_keys[i+persis_offset] != 0)
8822					lun->pending_ua[i] |=
8823						CTL_UA_RES_RELEASE;
8824		}
8825
8826		lun->flags &= ~CTL_LUN_PR_RESERVED;
8827		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8828		lun->res_type = 0;
8829		break;
8830
8831	case CTL_PR_PREEMPT:
8832		ctl_pro_preempt_other(lun, msg);
8833		break;
8834	case CTL_PR_CLEAR:
8835		lun->flags &= ~CTL_LUN_PR_RESERVED;
8836		lun->res_type = 0;
8837		lun->pr_key_count = 0;
8838		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8839
8840		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8841			if (lun->pr_keys[i] == 0)
8842				continue;
8843			if (!persis_offset
8844			 && i < CTL_MAX_INITIATORS)
8845				lun->pending_ua[i] |= CTL_UA_RES_PREEMPT;
8846			else if (persis_offset
8847			      && i >= persis_offset)
8848				lun->pending_ua[i-persis_offset] |=
8849					CTL_UA_RES_PREEMPT;
8850			lun->pr_keys[i] = 0;
8851		}
8852		lun->PRGeneration++;
8853		break;
8854	}
8855
8856	mtx_unlock(&lun->lun_lock);
8857}
8858
8859int
8860ctl_read_write(struct ctl_scsiio *ctsio)
8861{
8862	struct ctl_lun *lun;
8863	struct ctl_lba_len_flags *lbalen;
8864	uint64_t lba;
8865	uint32_t num_blocks;
8866	int flags, retval;
8867	int isread;
8868
8869	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8870
8871	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8872
8873	flags = 0;
8874	retval = CTL_RETVAL_COMPLETE;
8875
8876	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8877	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8878	switch (ctsio->cdb[0]) {
8879	case READ_6:
8880	case WRITE_6: {
8881		struct scsi_rw_6 *cdb;
8882
8883		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8884
8885		lba = scsi_3btoul(cdb->addr);
8886		/* only 5 bits are valid in the most significant address byte */
8887		lba &= 0x1fffff;
8888		num_blocks = cdb->length;
8889		/*
8890		 * This is correct according to SBC-2.
8891		 */
8892		if (num_blocks == 0)
8893			num_blocks = 256;
8894		break;
8895	}
8896	case READ_10:
8897	case WRITE_10: {
8898		struct scsi_rw_10 *cdb;
8899
8900		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8901		if (cdb->byte2 & SRW10_FUA)
8902			flags |= CTL_LLF_FUA;
8903		if (cdb->byte2 & SRW10_DPO)
8904			flags |= CTL_LLF_DPO;
8905		lba = scsi_4btoul(cdb->addr);
8906		num_blocks = scsi_2btoul(cdb->length);
8907		break;
8908	}
8909	case WRITE_VERIFY_10: {
8910		struct scsi_write_verify_10 *cdb;
8911
8912		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8913		flags |= CTL_LLF_FUA;
8914		if (cdb->byte2 & SWV_DPO)
8915			flags |= CTL_LLF_DPO;
8916		lba = scsi_4btoul(cdb->addr);
8917		num_blocks = scsi_2btoul(cdb->length);
8918		break;
8919	}
8920	case READ_12:
8921	case WRITE_12: {
8922		struct scsi_rw_12 *cdb;
8923
8924		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8925		if (cdb->byte2 & SRW12_FUA)
8926			flags |= CTL_LLF_FUA;
8927		if (cdb->byte2 & SRW12_DPO)
8928			flags |= CTL_LLF_DPO;
8929		lba = scsi_4btoul(cdb->addr);
8930		num_blocks = scsi_4btoul(cdb->length);
8931		break;
8932	}
8933	case WRITE_VERIFY_12: {
8934		struct scsi_write_verify_12 *cdb;
8935
8936		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8937		flags |= CTL_LLF_FUA;
8938		if (cdb->byte2 & SWV_DPO)
8939			flags |= CTL_LLF_DPO;
8940		lba = scsi_4btoul(cdb->addr);
8941		num_blocks = scsi_4btoul(cdb->length);
8942		break;
8943	}
8944	case READ_16:
8945	case WRITE_16: {
8946		struct scsi_rw_16 *cdb;
8947
8948		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8949		if (cdb->byte2 & SRW12_FUA)
8950			flags |= CTL_LLF_FUA;
8951		if (cdb->byte2 & SRW12_DPO)
8952			flags |= CTL_LLF_DPO;
8953		lba = scsi_8btou64(cdb->addr);
8954		num_blocks = scsi_4btoul(cdb->length);
8955		break;
8956	}
8957	case WRITE_ATOMIC_16: {
8958		struct scsi_rw_16 *cdb;
8959
8960		if (lun->be_lun->atomicblock == 0) {
8961			ctl_set_invalid_opcode(ctsio);
8962			ctl_done((union ctl_io *)ctsio);
8963			return (CTL_RETVAL_COMPLETE);
8964		}
8965
8966		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8967		if (cdb->byte2 & SRW12_FUA)
8968			flags |= CTL_LLF_FUA;
8969		if (cdb->byte2 & SRW12_DPO)
8970			flags |= CTL_LLF_DPO;
8971		lba = scsi_8btou64(cdb->addr);
8972		num_blocks = scsi_4btoul(cdb->length);
8973		if (num_blocks > lun->be_lun->atomicblock) {
8974			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8975			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8976			    /*bit*/ 0);
8977			ctl_done((union ctl_io *)ctsio);
8978			return (CTL_RETVAL_COMPLETE);
8979		}
8980		break;
8981	}
8982	case WRITE_VERIFY_16: {
8983		struct scsi_write_verify_16 *cdb;
8984
8985		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8986		flags |= CTL_LLF_FUA;
8987		if (cdb->byte2 & SWV_DPO)
8988			flags |= CTL_LLF_DPO;
8989		lba = scsi_8btou64(cdb->addr);
8990		num_blocks = scsi_4btoul(cdb->length);
8991		break;
8992	}
8993	default:
8994		/*
8995		 * We got a command we don't support.  This shouldn't
8996		 * happen, commands should be filtered out above us.
8997		 */
8998		ctl_set_invalid_opcode(ctsio);
8999		ctl_done((union ctl_io *)ctsio);
9000
9001		return (CTL_RETVAL_COMPLETE);
9002		break; /* NOTREACHED */
9003	}
9004
9005	/*
9006	 * The first check is to make sure we're in bounds, the second
9007	 * check is to catch wrap-around problems.  If the lba + num blocks
9008	 * is less than the lba, then we've wrapped around and the block
9009	 * range is invalid anyway.
9010	 */
9011	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9012	 || ((lba + num_blocks) < lba)) {
9013		ctl_set_lba_out_of_range(ctsio);
9014		ctl_done((union ctl_io *)ctsio);
9015		return (CTL_RETVAL_COMPLETE);
9016	}
9017
9018	/*
9019	 * According to SBC-3, a transfer length of 0 is not an error.
9020	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
9021	 * translates to 256 blocks for those commands.
9022	 */
9023	if (num_blocks == 0) {
9024		ctl_set_success(ctsio);
9025		ctl_done((union ctl_io *)ctsio);
9026		return (CTL_RETVAL_COMPLETE);
9027	}
9028
9029	/* Set FUA and/or DPO if caches are disabled. */
9030	if (isread) {
9031		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9032		    SCP_RCD) != 0)
9033			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9034	} else {
9035		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9036		    SCP_WCE) == 0)
9037			flags |= CTL_LLF_FUA;
9038	}
9039
9040	lbalen = (struct ctl_lba_len_flags *)
9041	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9042	lbalen->lba = lba;
9043	lbalen->len = num_blocks;
9044	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9045
9046	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9047	ctsio->kern_rel_offset = 0;
9048
9049	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9050
9051	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9052
9053	return (retval);
9054}
9055
9056static int
9057ctl_cnw_cont(union ctl_io *io)
9058{
9059	struct ctl_scsiio *ctsio;
9060	struct ctl_lun *lun;
9061	struct ctl_lba_len_flags *lbalen;
9062	int retval;
9063
9064	ctsio = &io->scsiio;
9065	ctsio->io_hdr.status = CTL_STATUS_NONE;
9066	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9067	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9068	lbalen = (struct ctl_lba_len_flags *)
9069	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9070	lbalen->flags &= ~CTL_LLF_COMPARE;
9071	lbalen->flags |= CTL_LLF_WRITE;
9072
9073	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9074	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9075	return (retval);
9076}
9077
9078int
9079ctl_cnw(struct ctl_scsiio *ctsio)
9080{
9081	struct ctl_lun *lun;
9082	struct ctl_lba_len_flags *lbalen;
9083	uint64_t lba;
9084	uint32_t num_blocks;
9085	int flags, retval;
9086
9087	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9088
9089	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9090
9091	flags = 0;
9092	retval = CTL_RETVAL_COMPLETE;
9093
9094	switch (ctsio->cdb[0]) {
9095	case COMPARE_AND_WRITE: {
9096		struct scsi_compare_and_write *cdb;
9097
9098		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9099		if (cdb->byte2 & SRW10_FUA)
9100			flags |= CTL_LLF_FUA;
9101		if (cdb->byte2 & SRW10_DPO)
9102			flags |= CTL_LLF_DPO;
9103		lba = scsi_8btou64(cdb->addr);
9104		num_blocks = cdb->length;
9105		break;
9106	}
9107	default:
9108		/*
9109		 * We got a command we don't support.  This shouldn't
9110		 * happen, commands should be filtered out above us.
9111		 */
9112		ctl_set_invalid_opcode(ctsio);
9113		ctl_done((union ctl_io *)ctsio);
9114
9115		return (CTL_RETVAL_COMPLETE);
9116		break; /* NOTREACHED */
9117	}
9118
9119	/*
9120	 * The first check is to make sure we're in bounds, the second
9121	 * check is to catch wrap-around problems.  If the lba + num blocks
9122	 * is less than the lba, then we've wrapped around and the block
9123	 * range is invalid anyway.
9124	 */
9125	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9126	 || ((lba + num_blocks) < lba)) {
9127		ctl_set_lba_out_of_range(ctsio);
9128		ctl_done((union ctl_io *)ctsio);
9129		return (CTL_RETVAL_COMPLETE);
9130	}
9131
9132	/*
9133	 * According to SBC-3, a transfer length of 0 is not an error.
9134	 */
9135	if (num_blocks == 0) {
9136		ctl_set_success(ctsio);
9137		ctl_done((union ctl_io *)ctsio);
9138		return (CTL_RETVAL_COMPLETE);
9139	}
9140
9141	/* Set FUA if write cache is disabled. */
9142	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9143	    SCP_WCE) == 0)
9144		flags |= CTL_LLF_FUA;
9145
9146	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9147	ctsio->kern_rel_offset = 0;
9148
9149	/*
9150	 * Set the IO_CONT flag, so that if this I/O gets passed to
9151	 * ctl_data_submit_done(), it'll get passed back to
9152	 * ctl_ctl_cnw_cont() for further processing.
9153	 */
9154	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9155	ctsio->io_cont = ctl_cnw_cont;
9156
9157	lbalen = (struct ctl_lba_len_flags *)
9158	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9159	lbalen->lba = lba;
9160	lbalen->len = num_blocks;
9161	lbalen->flags = CTL_LLF_COMPARE | flags;
9162
9163	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9164	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9165	return (retval);
9166}
9167
9168int
9169ctl_verify(struct ctl_scsiio *ctsio)
9170{
9171	struct ctl_lun *lun;
9172	struct ctl_lba_len_flags *lbalen;
9173	uint64_t lba;
9174	uint32_t num_blocks;
9175	int bytchk, flags;
9176	int retval;
9177
9178	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9179
9180	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9181
9182	bytchk = 0;
9183	flags = CTL_LLF_FUA;
9184	retval = CTL_RETVAL_COMPLETE;
9185
9186	switch (ctsio->cdb[0]) {
9187	case VERIFY_10: {
9188		struct scsi_verify_10 *cdb;
9189
9190		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9191		if (cdb->byte2 & SVFY_BYTCHK)
9192			bytchk = 1;
9193		if (cdb->byte2 & SVFY_DPO)
9194			flags |= CTL_LLF_DPO;
9195		lba = scsi_4btoul(cdb->addr);
9196		num_blocks = scsi_2btoul(cdb->length);
9197		break;
9198	}
9199	case VERIFY_12: {
9200		struct scsi_verify_12 *cdb;
9201
9202		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9203		if (cdb->byte2 & SVFY_BYTCHK)
9204			bytchk = 1;
9205		if (cdb->byte2 & SVFY_DPO)
9206			flags |= CTL_LLF_DPO;
9207		lba = scsi_4btoul(cdb->addr);
9208		num_blocks = scsi_4btoul(cdb->length);
9209		break;
9210	}
9211	case VERIFY_16: {
9212		struct scsi_rw_16 *cdb;
9213
9214		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9215		if (cdb->byte2 & SVFY_BYTCHK)
9216			bytchk = 1;
9217		if (cdb->byte2 & SVFY_DPO)
9218			flags |= CTL_LLF_DPO;
9219		lba = scsi_8btou64(cdb->addr);
9220		num_blocks = scsi_4btoul(cdb->length);
9221		break;
9222	}
9223	default:
9224		/*
9225		 * We got a command we don't support.  This shouldn't
9226		 * happen, commands should be filtered out above us.
9227		 */
9228		ctl_set_invalid_opcode(ctsio);
9229		ctl_done((union ctl_io *)ctsio);
9230		return (CTL_RETVAL_COMPLETE);
9231	}
9232
9233	/*
9234	 * The first check is to make sure we're in bounds, the second
9235	 * check is to catch wrap-around problems.  If the lba + num blocks
9236	 * is less than the lba, then we've wrapped around and the block
9237	 * range is invalid anyway.
9238	 */
9239	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9240	 || ((lba + num_blocks) < lba)) {
9241		ctl_set_lba_out_of_range(ctsio);
9242		ctl_done((union ctl_io *)ctsio);
9243		return (CTL_RETVAL_COMPLETE);
9244	}
9245
9246	/*
9247	 * According to SBC-3, a transfer length of 0 is not an error.
9248	 */
9249	if (num_blocks == 0) {
9250		ctl_set_success(ctsio);
9251		ctl_done((union ctl_io *)ctsio);
9252		return (CTL_RETVAL_COMPLETE);
9253	}
9254
9255	lbalen = (struct ctl_lba_len_flags *)
9256	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9257	lbalen->lba = lba;
9258	lbalen->len = num_blocks;
9259	if (bytchk) {
9260		lbalen->flags = CTL_LLF_COMPARE | flags;
9261		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9262	} else {
9263		lbalen->flags = CTL_LLF_VERIFY | flags;
9264		ctsio->kern_total_len = 0;
9265	}
9266	ctsio->kern_rel_offset = 0;
9267
9268	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9269	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9270	return (retval);
9271}
9272
9273int
9274ctl_report_luns(struct ctl_scsiio *ctsio)
9275{
9276	struct scsi_report_luns *cdb;
9277	struct scsi_report_luns_data *lun_data;
9278	struct ctl_lun *lun, *request_lun;
9279	int num_luns, retval;
9280	uint32_t alloc_len, lun_datalen;
9281	int num_filled, well_known;
9282	uint32_t initidx, targ_lun_id, lun_id;
9283
9284	retval = CTL_RETVAL_COMPLETE;
9285	well_known = 0;
9286
9287	cdb = (struct scsi_report_luns *)ctsio->cdb;
9288
9289	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9290
9291	mtx_lock(&control_softc->ctl_lock);
9292	num_luns = control_softc->num_luns;
9293	mtx_unlock(&control_softc->ctl_lock);
9294
9295	switch (cdb->select_report) {
9296	case RPL_REPORT_DEFAULT:
9297	case RPL_REPORT_ALL:
9298		break;
9299	case RPL_REPORT_WELLKNOWN:
9300		well_known = 1;
9301		num_luns = 0;
9302		break;
9303	default:
9304		ctl_set_invalid_field(ctsio,
9305				      /*sks_valid*/ 1,
9306				      /*command*/ 1,
9307				      /*field*/ 2,
9308				      /*bit_valid*/ 0,
9309				      /*bit*/ 0);
9310		ctl_done((union ctl_io *)ctsio);
9311		return (retval);
9312		break; /* NOTREACHED */
9313	}
9314
9315	alloc_len = scsi_4btoul(cdb->length);
9316	/*
9317	 * The initiator has to allocate at least 16 bytes for this request,
9318	 * so he can at least get the header and the first LUN.  Otherwise
9319	 * we reject the request (per SPC-3 rev 14, section 6.21).
9320	 */
9321	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9322	    sizeof(struct scsi_report_luns_lundata))) {
9323		ctl_set_invalid_field(ctsio,
9324				      /*sks_valid*/ 1,
9325				      /*command*/ 1,
9326				      /*field*/ 6,
9327				      /*bit_valid*/ 0,
9328				      /*bit*/ 0);
9329		ctl_done((union ctl_io *)ctsio);
9330		return (retval);
9331	}
9332
9333	request_lun = (struct ctl_lun *)
9334		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9335
9336	lun_datalen = sizeof(*lun_data) +
9337		(num_luns * sizeof(struct scsi_report_luns_lundata));
9338
9339	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9340	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9341	ctsio->kern_sg_entries = 0;
9342
9343	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9344
9345	mtx_lock(&control_softc->ctl_lock);
9346	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9347		lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9348		if (lun_id >= CTL_MAX_LUNS)
9349			continue;
9350		lun = control_softc->ctl_luns[lun_id];
9351		if (lun == NULL)
9352			continue;
9353
9354		if (targ_lun_id <= 0xff) {
9355			/*
9356			 * Peripheral addressing method, bus number 0.
9357			 */
9358			lun_data->luns[num_filled].lundata[0] =
9359				RPL_LUNDATA_ATYP_PERIPH;
9360			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9361			num_filled++;
9362		} else if (targ_lun_id <= 0x3fff) {
9363			/*
9364			 * Flat addressing method.
9365			 */
9366			lun_data->luns[num_filled].lundata[0] =
9367				RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9368			lun_data->luns[num_filled].lundata[1] =
9369				(targ_lun_id & 0xff);
9370			num_filled++;
9371		} else if (targ_lun_id <= 0xffffff) {
9372			/*
9373			 * Extended flat addressing method.
9374			 */
9375			lun_data->luns[num_filled].lundata[0] =
9376			    RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9377			scsi_ulto3b(targ_lun_id,
9378			    &lun_data->luns[num_filled].lundata[1]);
9379			num_filled++;
9380		} else {
9381			printf("ctl_report_luns: bogus LUN number %jd, "
9382			       "skipping\n", (intmax_t)targ_lun_id);
9383		}
9384		/*
9385		 * According to SPC-3, rev 14 section 6.21:
9386		 *
9387		 * "The execution of a REPORT LUNS command to any valid and
9388		 * installed logical unit shall clear the REPORTED LUNS DATA
9389		 * HAS CHANGED unit attention condition for all logical
9390		 * units of that target with respect to the requesting
9391		 * initiator. A valid and installed logical unit is one
9392		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9393		 * INQUIRY data (see 6.4.2)."
9394		 *
9395		 * If request_lun is NULL, the LUN this report luns command
9396		 * was issued to is either disabled or doesn't exist. In that
9397		 * case, we shouldn't clear any pending lun change unit
9398		 * attention.
9399		 */
9400		if (request_lun != NULL) {
9401			mtx_lock(&lun->lun_lock);
9402			lun->pending_ua[initidx] &= ~CTL_UA_LUN_CHANGE;
9403			mtx_unlock(&lun->lun_lock);
9404		}
9405	}
9406	mtx_unlock(&control_softc->ctl_lock);
9407
9408	/*
9409	 * It's quite possible that we've returned fewer LUNs than we allocated
9410	 * space for.  Trim it.
9411	 */
9412	lun_datalen = sizeof(*lun_data) +
9413		(num_filled * sizeof(struct scsi_report_luns_lundata));
9414
9415	if (lun_datalen < alloc_len) {
9416		ctsio->residual = alloc_len - lun_datalen;
9417		ctsio->kern_data_len = lun_datalen;
9418		ctsio->kern_total_len = lun_datalen;
9419	} else {
9420		ctsio->residual = 0;
9421		ctsio->kern_data_len = alloc_len;
9422		ctsio->kern_total_len = alloc_len;
9423	}
9424	ctsio->kern_data_resid = 0;
9425	ctsio->kern_rel_offset = 0;
9426	ctsio->kern_sg_entries = 0;
9427
9428	/*
9429	 * We set this to the actual data length, regardless of how much
9430	 * space we actually have to return results.  If the user looks at
9431	 * this value, he'll know whether or not he allocated enough space
9432	 * and reissue the command if necessary.  We don't support well
9433	 * known logical units, so if the user asks for that, return none.
9434	 */
9435	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9436
9437	/*
9438	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9439	 * this request.
9440	 */
9441	ctsio->scsi_status = SCSI_STATUS_OK;
9442
9443	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9444	ctsio->be_move_done = ctl_config_move_done;
9445	ctl_datamove((union ctl_io *)ctsio);
9446
9447	return (retval);
9448}
9449
9450int
9451ctl_request_sense(struct ctl_scsiio *ctsio)
9452{
9453	struct scsi_request_sense *cdb;
9454	struct scsi_sense_data *sense_ptr;
9455	struct ctl_lun *lun;
9456	uint32_t initidx;
9457	int have_error;
9458	scsi_sense_data_type sense_format;
9459
9460	cdb = (struct scsi_request_sense *)ctsio->cdb;
9461
9462	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9463
9464	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9465
9466	/*
9467	 * Determine which sense format the user wants.
9468	 */
9469	if (cdb->byte2 & SRS_DESC)
9470		sense_format = SSD_TYPE_DESC;
9471	else
9472		sense_format = SSD_TYPE_FIXED;
9473
9474	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9475	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9476	ctsio->kern_sg_entries = 0;
9477
9478	/*
9479	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9480	 * larger than the largest allowed value for the length field in the
9481	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9482	 */
9483	ctsio->residual = 0;
9484	ctsio->kern_data_len = cdb->length;
9485	ctsio->kern_total_len = cdb->length;
9486
9487	ctsio->kern_data_resid = 0;
9488	ctsio->kern_rel_offset = 0;
9489	ctsio->kern_sg_entries = 0;
9490
9491	/*
9492	 * If we don't have a LUN, we don't have any pending sense.
9493	 */
9494	if (lun == NULL)
9495		goto no_sense;
9496
9497	have_error = 0;
9498	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9499	/*
9500	 * Check for pending sense, and then for pending unit attentions.
9501	 * Pending sense gets returned first, then pending unit attentions.
9502	 */
9503	mtx_lock(&lun->lun_lock);
9504#ifdef CTL_WITH_CA
9505	if (ctl_is_set(lun->have_ca, initidx)) {
9506		scsi_sense_data_type stored_format;
9507
9508		/*
9509		 * Check to see which sense format was used for the stored
9510		 * sense data.
9511		 */
9512		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9513
9514		/*
9515		 * If the user requested a different sense format than the
9516		 * one we stored, then we need to convert it to the other
9517		 * format.  If we're going from descriptor to fixed format
9518		 * sense data, we may lose things in translation, depending
9519		 * on what options were used.
9520		 *
9521		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9522		 * for some reason we'll just copy it out as-is.
9523		 */
9524		if ((stored_format == SSD_TYPE_FIXED)
9525		 && (sense_format == SSD_TYPE_DESC))
9526			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9527			    &lun->pending_sense[initidx],
9528			    (struct scsi_sense_data_desc *)sense_ptr);
9529		else if ((stored_format == SSD_TYPE_DESC)
9530		      && (sense_format == SSD_TYPE_FIXED))
9531			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9532			    &lun->pending_sense[initidx],
9533			    (struct scsi_sense_data_fixed *)sense_ptr);
9534		else
9535			memcpy(sense_ptr, &lun->pending_sense[initidx],
9536			       ctl_min(sizeof(*sense_ptr),
9537			       sizeof(lun->pending_sense[initidx])));
9538
9539		ctl_clear_mask(lun->have_ca, initidx);
9540		have_error = 1;
9541	} else
9542#endif
9543	if (lun->pending_ua[initidx] != CTL_UA_NONE) {
9544		ctl_ua_type ua_type;
9545
9546		ua_type = ctl_build_ua(&lun->pending_ua[initidx],
9547				       sense_ptr, sense_format);
9548		if (ua_type != CTL_UA_NONE)
9549			have_error = 1;
9550	}
9551	mtx_unlock(&lun->lun_lock);
9552
9553	/*
9554	 * We already have a pending error, return it.
9555	 */
9556	if (have_error != 0) {
9557		/*
9558		 * We report the SCSI status as OK, since the status of the
9559		 * request sense command itself is OK.
9560		 */
9561		ctsio->scsi_status = SCSI_STATUS_OK;
9562
9563		/*
9564		 * We report 0 for the sense length, because we aren't doing
9565		 * autosense in this case.  We're reporting sense as
9566		 * parameter data.
9567		 */
9568		ctsio->sense_len = 0;
9569		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9570		ctsio->be_move_done = ctl_config_move_done;
9571		ctl_datamove((union ctl_io *)ctsio);
9572
9573		return (CTL_RETVAL_COMPLETE);
9574	}
9575
9576no_sense:
9577
9578	/*
9579	 * No sense information to report, so we report that everything is
9580	 * okay.
9581	 */
9582	ctl_set_sense_data(sense_ptr,
9583			   lun,
9584			   sense_format,
9585			   /*current_error*/ 1,
9586			   /*sense_key*/ SSD_KEY_NO_SENSE,
9587			   /*asc*/ 0x00,
9588			   /*ascq*/ 0x00,
9589			   SSD_ELEM_NONE);
9590
9591	ctsio->scsi_status = SCSI_STATUS_OK;
9592
9593	/*
9594	 * We report 0 for the sense length, because we aren't doing
9595	 * autosense in this case.  We're reporting sense as parameter data.
9596	 */
9597	ctsio->sense_len = 0;
9598	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9599	ctsio->be_move_done = ctl_config_move_done;
9600	ctl_datamove((union ctl_io *)ctsio);
9601
9602	return (CTL_RETVAL_COMPLETE);
9603}
9604
9605int
9606ctl_tur(struct ctl_scsiio *ctsio)
9607{
9608
9609	CTL_DEBUG_PRINT(("ctl_tur\n"));
9610
9611	ctsio->scsi_status = SCSI_STATUS_OK;
9612	ctsio->io_hdr.status = CTL_SUCCESS;
9613
9614	ctl_done((union ctl_io *)ctsio);
9615
9616	return (CTL_RETVAL_COMPLETE);
9617}
9618
9619#ifdef notyet
9620static int
9621ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9622{
9623
9624}
9625#endif
9626
9627static int
9628ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9629{
9630	struct scsi_vpd_supported_pages *pages;
9631	int sup_page_size;
9632	struct ctl_lun *lun;
9633
9634	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9635
9636	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9637	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9638	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9639	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9640	ctsio->kern_sg_entries = 0;
9641
9642	if (sup_page_size < alloc_len) {
9643		ctsio->residual = alloc_len - sup_page_size;
9644		ctsio->kern_data_len = sup_page_size;
9645		ctsio->kern_total_len = sup_page_size;
9646	} else {
9647		ctsio->residual = 0;
9648		ctsio->kern_data_len = alloc_len;
9649		ctsio->kern_total_len = alloc_len;
9650	}
9651	ctsio->kern_data_resid = 0;
9652	ctsio->kern_rel_offset = 0;
9653	ctsio->kern_sg_entries = 0;
9654
9655	/*
9656	 * The control device is always connected.  The disk device, on the
9657	 * other hand, may not be online all the time.  Need to change this
9658	 * to figure out whether the disk device is actually online or not.
9659	 */
9660	if (lun != NULL)
9661		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9662				lun->be_lun->lun_type;
9663	else
9664		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9665
9666	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9667	/* Supported VPD pages */
9668	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9669	/* Serial Number */
9670	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9671	/* Device Identification */
9672	pages->page_list[2] = SVPD_DEVICE_ID;
9673	/* Extended INQUIRY Data */
9674	pages->page_list[3] = SVPD_EXTENDED_INQUIRY_DATA;
9675	/* Mode Page Policy */
9676	pages->page_list[4] = SVPD_MODE_PAGE_POLICY;
9677	/* SCSI Ports */
9678	pages->page_list[5] = SVPD_SCSI_PORTS;
9679	/* Third-party Copy */
9680	pages->page_list[6] = SVPD_SCSI_TPC;
9681	/* Block limits */
9682	pages->page_list[7] = SVPD_BLOCK_LIMITS;
9683	/* Block Device Characteristics */
9684	pages->page_list[8] = SVPD_BDC;
9685	/* Logical Block Provisioning */
9686	pages->page_list[9] = SVPD_LBP;
9687
9688	ctsio->scsi_status = SCSI_STATUS_OK;
9689
9690	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9691	ctsio->be_move_done = ctl_config_move_done;
9692	ctl_datamove((union ctl_io *)ctsio);
9693
9694	return (CTL_RETVAL_COMPLETE);
9695}
9696
9697static int
9698ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9699{
9700	struct scsi_vpd_unit_serial_number *sn_ptr;
9701	struct ctl_lun *lun;
9702	int data_len;
9703
9704	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9705
9706	data_len = 4 + CTL_SN_LEN;
9707	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9708	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9709	if (data_len < alloc_len) {
9710		ctsio->residual = alloc_len - data_len;
9711		ctsio->kern_data_len = data_len;
9712		ctsio->kern_total_len = data_len;
9713	} else {
9714		ctsio->residual = 0;
9715		ctsio->kern_data_len = alloc_len;
9716		ctsio->kern_total_len = alloc_len;
9717	}
9718	ctsio->kern_data_resid = 0;
9719	ctsio->kern_rel_offset = 0;
9720	ctsio->kern_sg_entries = 0;
9721
9722	/*
9723	 * The control device is always connected.  The disk device, on the
9724	 * other hand, may not be online all the time.  Need to change this
9725	 * to figure out whether the disk device is actually online or not.
9726	 */
9727	if (lun != NULL)
9728		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9729				  lun->be_lun->lun_type;
9730	else
9731		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9732
9733	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9734	sn_ptr->length = CTL_SN_LEN;
9735	/*
9736	 * If we don't have a LUN, we just leave the serial number as
9737	 * all spaces.
9738	 */
9739	if (lun != NULL) {
9740		strncpy((char *)sn_ptr->serial_num,
9741			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9742	} else
9743		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9744	ctsio->scsi_status = SCSI_STATUS_OK;
9745
9746	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9747	ctsio->be_move_done = ctl_config_move_done;
9748	ctl_datamove((union ctl_io *)ctsio);
9749
9750	return (CTL_RETVAL_COMPLETE);
9751}
9752
9753
9754static int
9755ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9756{
9757	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9758	struct ctl_lun *lun;
9759	int data_len;
9760
9761	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9762
9763	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9764	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9765	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9766	ctsio->kern_sg_entries = 0;
9767
9768	if (data_len < alloc_len) {
9769		ctsio->residual = alloc_len - data_len;
9770		ctsio->kern_data_len = data_len;
9771		ctsio->kern_total_len = data_len;
9772	} else {
9773		ctsio->residual = 0;
9774		ctsio->kern_data_len = alloc_len;
9775		ctsio->kern_total_len = alloc_len;
9776	}
9777	ctsio->kern_data_resid = 0;
9778	ctsio->kern_rel_offset = 0;
9779	ctsio->kern_sg_entries = 0;
9780
9781	/*
9782	 * The control device is always connected.  The disk device, on the
9783	 * other hand, may not be online all the time.
9784	 */
9785	if (lun != NULL)
9786		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9787				     lun->be_lun->lun_type;
9788	else
9789		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9790	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9791	eid_ptr->page_length = data_len - 4;
9792	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9793	eid_ptr->flags3 = SVPD_EID_V_SUP;
9794
9795	ctsio->scsi_status = SCSI_STATUS_OK;
9796	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9797	ctsio->be_move_done = ctl_config_move_done;
9798	ctl_datamove((union ctl_io *)ctsio);
9799
9800	return (CTL_RETVAL_COMPLETE);
9801}
9802
9803static int
9804ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9805{
9806	struct scsi_vpd_mode_page_policy *mpp_ptr;
9807	struct ctl_lun *lun;
9808	int data_len;
9809
9810	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9811
9812	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9813	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9814
9815	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9816	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9817	ctsio->kern_sg_entries = 0;
9818
9819	if (data_len < alloc_len) {
9820		ctsio->residual = alloc_len - data_len;
9821		ctsio->kern_data_len = data_len;
9822		ctsio->kern_total_len = data_len;
9823	} else {
9824		ctsio->residual = 0;
9825		ctsio->kern_data_len = alloc_len;
9826		ctsio->kern_total_len = alloc_len;
9827	}
9828	ctsio->kern_data_resid = 0;
9829	ctsio->kern_rel_offset = 0;
9830	ctsio->kern_sg_entries = 0;
9831
9832	/*
9833	 * The control device is always connected.  The disk device, on the
9834	 * other hand, may not be online all the time.
9835	 */
9836	if (lun != NULL)
9837		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9838				     lun->be_lun->lun_type;
9839	else
9840		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9841	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9842	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9843	mpp_ptr->descr[0].page_code = 0x3f;
9844	mpp_ptr->descr[0].subpage_code = 0xff;
9845	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9846
9847	ctsio->scsi_status = SCSI_STATUS_OK;
9848	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9849	ctsio->be_move_done = ctl_config_move_done;
9850	ctl_datamove((union ctl_io *)ctsio);
9851
9852	return (CTL_RETVAL_COMPLETE);
9853}
9854
9855static int
9856ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9857{
9858	struct scsi_vpd_device_id *devid_ptr;
9859	struct scsi_vpd_id_descriptor *desc;
9860	struct ctl_softc *ctl_softc;
9861	struct ctl_lun *lun;
9862	struct ctl_port *port;
9863	int data_len;
9864	uint8_t proto;
9865
9866	ctl_softc = control_softc;
9867
9868	port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9869	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9870
9871	data_len = sizeof(struct scsi_vpd_device_id) +
9872	    sizeof(struct scsi_vpd_id_descriptor) +
9873		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9874	    sizeof(struct scsi_vpd_id_descriptor) +
9875		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9876	if (lun && lun->lun_devid)
9877		data_len += lun->lun_devid->len;
9878	if (port->port_devid)
9879		data_len += port->port_devid->len;
9880	if (port->target_devid)
9881		data_len += port->target_devid->len;
9882
9883	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9884	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9885	ctsio->kern_sg_entries = 0;
9886
9887	if (data_len < alloc_len) {
9888		ctsio->residual = alloc_len - data_len;
9889		ctsio->kern_data_len = data_len;
9890		ctsio->kern_total_len = data_len;
9891	} else {
9892		ctsio->residual = 0;
9893		ctsio->kern_data_len = alloc_len;
9894		ctsio->kern_total_len = alloc_len;
9895	}
9896	ctsio->kern_data_resid = 0;
9897	ctsio->kern_rel_offset = 0;
9898	ctsio->kern_sg_entries = 0;
9899
9900	/*
9901	 * The control device is always connected.  The disk device, on the
9902	 * other hand, may not be online all the time.
9903	 */
9904	if (lun != NULL)
9905		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9906				     lun->be_lun->lun_type;
9907	else
9908		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9909	devid_ptr->page_code = SVPD_DEVICE_ID;
9910	scsi_ulto2b(data_len - 4, devid_ptr->length);
9911
9912	if (port->port_type == CTL_PORT_FC)
9913		proto = SCSI_PROTO_FC << 4;
9914	else if (port->port_type == CTL_PORT_ISCSI)
9915		proto = SCSI_PROTO_ISCSI << 4;
9916	else
9917		proto = SCSI_PROTO_SPI << 4;
9918	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9919
9920	/*
9921	 * We're using a LUN association here.  i.e., this device ID is a
9922	 * per-LUN identifier.
9923	 */
9924	if (lun && lun->lun_devid) {
9925		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9926		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9927		    lun->lun_devid->len);
9928	}
9929
9930	/*
9931	 * This is for the WWPN which is a port association.
9932	 */
9933	if (port->port_devid) {
9934		memcpy(desc, port->port_devid->data, port->port_devid->len);
9935		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9936		    port->port_devid->len);
9937	}
9938
9939	/*
9940	 * This is for the Relative Target Port(type 4h) identifier
9941	 */
9942	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9943	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9944	    SVPD_ID_TYPE_RELTARG;
9945	desc->length = 4;
9946	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9947	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9948	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9949
9950	/*
9951	 * This is for the Target Port Group(type 5h) identifier
9952	 */
9953	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9954	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9955	    SVPD_ID_TYPE_TPORTGRP;
9956	desc->length = 4;
9957	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
9958	    &desc->identifier[2]);
9959	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9960	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9961
9962	/*
9963	 * This is for the Target identifier
9964	 */
9965	if (port->target_devid) {
9966		memcpy(desc, port->target_devid->data, port->target_devid->len);
9967	}
9968
9969	ctsio->scsi_status = SCSI_STATUS_OK;
9970	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9971	ctsio->be_move_done = ctl_config_move_done;
9972	ctl_datamove((union ctl_io *)ctsio);
9973
9974	return (CTL_RETVAL_COMPLETE);
9975}
9976
9977static int
9978ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9979{
9980	struct ctl_softc *softc = control_softc;
9981	struct scsi_vpd_scsi_ports *sp;
9982	struct scsi_vpd_port_designation *pd;
9983	struct scsi_vpd_port_designation_cont *pdc;
9984	struct ctl_lun *lun;
9985	struct ctl_port *port;
9986	int data_len, num_target_ports, iid_len, id_len, g, pg, p;
9987	int num_target_port_groups;
9988
9989	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9990
9991	if (softc->is_single)
9992		num_target_port_groups = 1;
9993	else
9994		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
9995	num_target_ports = 0;
9996	iid_len = 0;
9997	id_len = 0;
9998	mtx_lock(&softc->ctl_lock);
9999	STAILQ_FOREACH(port, &softc->port_list, links) {
10000		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10001			continue;
10002		if (lun != NULL &&
10003		    ctl_map_lun_back(port->targ_port, lun->lun) >=
10004		    CTL_MAX_LUNS)
10005			continue;
10006		num_target_ports++;
10007		if (port->init_devid)
10008			iid_len += port->init_devid->len;
10009		if (port->port_devid)
10010			id_len += port->port_devid->len;
10011	}
10012	mtx_unlock(&softc->ctl_lock);
10013
10014	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10015	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10016	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10017	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10018	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10019	ctsio->kern_sg_entries = 0;
10020
10021	if (data_len < alloc_len) {
10022		ctsio->residual = alloc_len - data_len;
10023		ctsio->kern_data_len = data_len;
10024		ctsio->kern_total_len = data_len;
10025	} else {
10026		ctsio->residual = 0;
10027		ctsio->kern_data_len = alloc_len;
10028		ctsio->kern_total_len = alloc_len;
10029	}
10030	ctsio->kern_data_resid = 0;
10031	ctsio->kern_rel_offset = 0;
10032	ctsio->kern_sg_entries = 0;
10033
10034	/*
10035	 * The control device is always connected.  The disk device, on the
10036	 * other hand, may not be online all the time.  Need to change this
10037	 * to figure out whether the disk device is actually online or not.
10038	 */
10039	if (lun != NULL)
10040		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10041				  lun->be_lun->lun_type;
10042	else
10043		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10044
10045	sp->page_code = SVPD_SCSI_PORTS;
10046	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10047	    sp->page_length);
10048	pd = &sp->design[0];
10049
10050	mtx_lock(&softc->ctl_lock);
10051	pg = softc->port_offset / CTL_MAX_PORTS;
10052	for (g = 0; g < num_target_port_groups; g++) {
10053		STAILQ_FOREACH(port, &softc->port_list, links) {
10054			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10055				continue;
10056			if (lun != NULL &&
10057			    ctl_map_lun_back(port->targ_port, lun->lun) >=
10058			    CTL_MAX_LUNS)
10059				continue;
10060			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10061			scsi_ulto2b(p, pd->relative_port_id);
10062			if (port->init_devid && g == pg) {
10063				iid_len = port->init_devid->len;
10064				memcpy(pd->initiator_transportid,
10065				    port->init_devid->data, port->init_devid->len);
10066			} else
10067				iid_len = 0;
10068			scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10069			pdc = (struct scsi_vpd_port_designation_cont *)
10070			    (&pd->initiator_transportid[iid_len]);
10071			if (port->port_devid && g == pg) {
10072				id_len = port->port_devid->len;
10073				memcpy(pdc->target_port_descriptors,
10074				    port->port_devid->data, port->port_devid->len);
10075			} else
10076				id_len = 0;
10077			scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10078			pd = (struct scsi_vpd_port_designation *)
10079			    ((uint8_t *)pdc->target_port_descriptors + id_len);
10080		}
10081	}
10082	mtx_unlock(&softc->ctl_lock);
10083
10084	ctsio->scsi_status = SCSI_STATUS_OK;
10085	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10086	ctsio->be_move_done = ctl_config_move_done;
10087	ctl_datamove((union ctl_io *)ctsio);
10088
10089	return (CTL_RETVAL_COMPLETE);
10090}
10091
10092static int
10093ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10094{
10095	struct scsi_vpd_block_limits *bl_ptr;
10096	struct ctl_lun *lun;
10097	int bs;
10098
10099	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10100
10101	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10102	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10103	ctsio->kern_sg_entries = 0;
10104
10105	if (sizeof(*bl_ptr) < alloc_len) {
10106		ctsio->residual = alloc_len - sizeof(*bl_ptr);
10107		ctsio->kern_data_len = sizeof(*bl_ptr);
10108		ctsio->kern_total_len = sizeof(*bl_ptr);
10109	} else {
10110		ctsio->residual = 0;
10111		ctsio->kern_data_len = alloc_len;
10112		ctsio->kern_total_len = alloc_len;
10113	}
10114	ctsio->kern_data_resid = 0;
10115	ctsio->kern_rel_offset = 0;
10116	ctsio->kern_sg_entries = 0;
10117
10118	/*
10119	 * The control device is always connected.  The disk device, on the
10120	 * other hand, may not be online all the time.  Need to change this
10121	 * to figure out whether the disk device is actually online or not.
10122	 */
10123	if (lun != NULL)
10124		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10125				  lun->be_lun->lun_type;
10126	else
10127		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10128
10129	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10130	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10131	bl_ptr->max_cmp_write_len = 0xff;
10132	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10133	if (lun != NULL) {
10134		bs = lun->be_lun->blocksize;
10135		scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10136		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10137			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10138			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10139			if (lun->be_lun->pblockexp != 0) {
10140				scsi_ulto4b((1 << lun->be_lun->pblockexp),
10141				    bl_ptr->opt_unmap_grain);
10142				scsi_ulto4b(0x80000000 | lun->be_lun->pblockoff,
10143				    bl_ptr->unmap_grain_align);
10144			}
10145		}
10146		scsi_ulto4b(lun->be_lun->atomicblock,
10147		    bl_ptr->max_atomic_transfer_length);
10148		scsi_ulto4b(0, bl_ptr->atomic_alignment);
10149		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10150	}
10151	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10152
10153	ctsio->scsi_status = SCSI_STATUS_OK;
10154	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10155	ctsio->be_move_done = ctl_config_move_done;
10156	ctl_datamove((union ctl_io *)ctsio);
10157
10158	return (CTL_RETVAL_COMPLETE);
10159}
10160
10161static int
10162ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10163{
10164	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10165	struct ctl_lun *lun;
10166	const char *value;
10167	u_int i;
10168
10169	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10170
10171	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10172	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10173	ctsio->kern_sg_entries = 0;
10174
10175	if (sizeof(*bdc_ptr) < alloc_len) {
10176		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10177		ctsio->kern_data_len = sizeof(*bdc_ptr);
10178		ctsio->kern_total_len = sizeof(*bdc_ptr);
10179	} else {
10180		ctsio->residual = 0;
10181		ctsio->kern_data_len = alloc_len;
10182		ctsio->kern_total_len = alloc_len;
10183	}
10184	ctsio->kern_data_resid = 0;
10185	ctsio->kern_rel_offset = 0;
10186	ctsio->kern_sg_entries = 0;
10187
10188	/*
10189	 * The control device is always connected.  The disk device, on the
10190	 * other hand, may not be online all the time.  Need to change this
10191	 * to figure out whether the disk device is actually online or not.
10192	 */
10193	if (lun != NULL)
10194		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10195				  lun->be_lun->lun_type;
10196	else
10197		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10198	bdc_ptr->page_code = SVPD_BDC;
10199	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10200	if (lun != NULL &&
10201	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10202		i = strtol(value, NULL, 0);
10203	else
10204		i = CTL_DEFAULT_ROTATION_RATE;
10205	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10206	if (lun != NULL &&
10207	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10208		i = strtol(value, NULL, 0);
10209	else
10210		i = 0;
10211	bdc_ptr->wab_wac_ff = (i & 0x0f);
10212	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10213
10214	ctsio->scsi_status = SCSI_STATUS_OK;
10215	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10216	ctsio->be_move_done = ctl_config_move_done;
10217	ctl_datamove((union ctl_io *)ctsio);
10218
10219	return (CTL_RETVAL_COMPLETE);
10220}
10221
10222static int
10223ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10224{
10225	struct scsi_vpd_logical_block_prov *lbp_ptr;
10226	struct ctl_lun *lun;
10227
10228	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10229
10230	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10231	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10232	ctsio->kern_sg_entries = 0;
10233
10234	if (sizeof(*lbp_ptr) < alloc_len) {
10235		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10236		ctsio->kern_data_len = sizeof(*lbp_ptr);
10237		ctsio->kern_total_len = sizeof(*lbp_ptr);
10238	} else {
10239		ctsio->residual = 0;
10240		ctsio->kern_data_len = alloc_len;
10241		ctsio->kern_total_len = alloc_len;
10242	}
10243	ctsio->kern_data_resid = 0;
10244	ctsio->kern_rel_offset = 0;
10245	ctsio->kern_sg_entries = 0;
10246
10247	/*
10248	 * The control device is always connected.  The disk device, on the
10249	 * other hand, may not be online all the time.  Need to change this
10250	 * to figure out whether the disk device is actually online or not.
10251	 */
10252	if (lun != NULL)
10253		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10254				  lun->be_lun->lun_type;
10255	else
10256		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10257
10258	lbp_ptr->page_code = SVPD_LBP;
10259	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10260	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10261		lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10262		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10263		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10264		lbp_ptr->prov_type = SVPD_LBP_THIN;
10265	}
10266
10267	ctsio->scsi_status = SCSI_STATUS_OK;
10268	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10269	ctsio->be_move_done = ctl_config_move_done;
10270	ctl_datamove((union ctl_io *)ctsio);
10271
10272	return (CTL_RETVAL_COMPLETE);
10273}
10274
10275static int
10276ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10277{
10278	struct scsi_inquiry *cdb;
10279	int alloc_len, retval;
10280
10281	cdb = (struct scsi_inquiry *)ctsio->cdb;
10282
10283	retval = CTL_RETVAL_COMPLETE;
10284
10285	alloc_len = scsi_2btoul(cdb->length);
10286
10287	switch (cdb->page_code) {
10288	case SVPD_SUPPORTED_PAGES:
10289		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10290		break;
10291	case SVPD_UNIT_SERIAL_NUMBER:
10292		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10293		break;
10294	case SVPD_DEVICE_ID:
10295		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10296		break;
10297	case SVPD_EXTENDED_INQUIRY_DATA:
10298		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10299		break;
10300	case SVPD_MODE_PAGE_POLICY:
10301		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10302		break;
10303	case SVPD_SCSI_PORTS:
10304		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10305		break;
10306	case SVPD_SCSI_TPC:
10307		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10308		break;
10309	case SVPD_BLOCK_LIMITS:
10310		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10311		break;
10312	case SVPD_BDC:
10313		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10314		break;
10315	case SVPD_LBP:
10316		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10317		break;
10318	default:
10319		ctl_set_invalid_field(ctsio,
10320				      /*sks_valid*/ 1,
10321				      /*command*/ 1,
10322				      /*field*/ 2,
10323				      /*bit_valid*/ 0,
10324				      /*bit*/ 0);
10325		ctl_done((union ctl_io *)ctsio);
10326		retval = CTL_RETVAL_COMPLETE;
10327		break;
10328	}
10329
10330	return (retval);
10331}
10332
10333static int
10334ctl_inquiry_std(struct ctl_scsiio *ctsio)
10335{
10336	struct scsi_inquiry_data *inq_ptr;
10337	struct scsi_inquiry *cdb;
10338	struct ctl_softc *ctl_softc;
10339	struct ctl_lun *lun;
10340	char *val;
10341	uint32_t alloc_len, data_len;
10342	ctl_port_type port_type;
10343
10344	ctl_softc = control_softc;
10345
10346	/*
10347	 * Figure out whether we're talking to a Fibre Channel port or not.
10348	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10349	 * SCSI front ends.
10350	 */
10351	port_type = ctl_softc->ctl_ports[
10352	    ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10353	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10354		port_type = CTL_PORT_SCSI;
10355
10356	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10357	cdb = (struct scsi_inquiry *)ctsio->cdb;
10358	alloc_len = scsi_2btoul(cdb->length);
10359
10360	/*
10361	 * We malloc the full inquiry data size here and fill it
10362	 * in.  If the user only asks for less, we'll give him
10363	 * that much.
10364	 */
10365	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10366	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10367	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10368	ctsio->kern_sg_entries = 0;
10369	ctsio->kern_data_resid = 0;
10370	ctsio->kern_rel_offset = 0;
10371
10372	if (data_len < alloc_len) {
10373		ctsio->residual = alloc_len - data_len;
10374		ctsio->kern_data_len = data_len;
10375		ctsio->kern_total_len = data_len;
10376	} else {
10377		ctsio->residual = 0;
10378		ctsio->kern_data_len = alloc_len;
10379		ctsio->kern_total_len = alloc_len;
10380	}
10381
10382	/*
10383	 * If we have a LUN configured, report it as connected.  Otherwise,
10384	 * report that it is offline or no device is supported, depending
10385	 * on the value of inquiry_pq_no_lun.
10386	 *
10387	 * According to the spec (SPC-4 r34), the peripheral qualifier
10388	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10389	 *
10390	 * "A peripheral device having the specified peripheral device type
10391	 * is not connected to this logical unit. However, the device
10392	 * server is capable of supporting the specified peripheral device
10393	 * type on this logical unit."
10394	 *
10395	 * According to the same spec, the peripheral qualifier
10396	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10397	 *
10398	 * "The device server is not capable of supporting a peripheral
10399	 * device on this logical unit. For this peripheral qualifier the
10400	 * peripheral device type shall be set to 1Fh. All other peripheral
10401	 * device type values are reserved for this peripheral qualifier."
10402	 *
10403	 * Given the text, it would seem that we probably want to report that
10404	 * the LUN is offline here.  There is no LUN connected, but we can
10405	 * support a LUN at the given LUN number.
10406	 *
10407	 * In the real world, though, it sounds like things are a little
10408	 * different:
10409	 *
10410	 * - Linux, when presented with a LUN with the offline peripheral
10411	 *   qualifier, will create an sg driver instance for it.  So when
10412	 *   you attach it to CTL, you wind up with a ton of sg driver
10413	 *   instances.  (One for every LUN that Linux bothered to probe.)
10414	 *   Linux does this despite the fact that it issues a REPORT LUNs
10415	 *   to LUN 0 to get the inventory of supported LUNs.
10416	 *
10417	 * - There is other anecdotal evidence (from Emulex folks) about
10418	 *   arrays that use the offline peripheral qualifier for LUNs that
10419	 *   are on the "passive" path in an active/passive array.
10420	 *
10421	 * So the solution is provide a hopefully reasonable default
10422	 * (return bad/no LUN) and allow the user to change the behavior
10423	 * with a tunable/sysctl variable.
10424	 */
10425	if (lun != NULL)
10426		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10427				  lun->be_lun->lun_type;
10428	else if (ctl_softc->inquiry_pq_no_lun == 0)
10429		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10430	else
10431		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10432
10433	/* RMB in byte 2 is 0 */
10434	inq_ptr->version = SCSI_REV_SPC4;
10435
10436	/*
10437	 * According to SAM-3, even if a device only supports a single
10438	 * level of LUN addressing, it should still set the HISUP bit:
10439	 *
10440	 * 4.9.1 Logical unit numbers overview
10441	 *
10442	 * All logical unit number formats described in this standard are
10443	 * hierarchical in structure even when only a single level in that
10444	 * hierarchy is used. The HISUP bit shall be set to one in the
10445	 * standard INQUIRY data (see SPC-2) when any logical unit number
10446	 * format described in this standard is used.  Non-hierarchical
10447	 * formats are outside the scope of this standard.
10448	 *
10449	 * Therefore we set the HiSup bit here.
10450	 *
10451	 * The reponse format is 2, per SPC-3.
10452	 */
10453	inq_ptr->response_format = SID_HiSup | 2;
10454
10455	inq_ptr->additional_length = data_len -
10456	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10457	CTL_DEBUG_PRINT(("additional_length = %d\n",
10458			 inq_ptr->additional_length));
10459
10460	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10461	/* 16 bit addressing */
10462	if (port_type == CTL_PORT_SCSI)
10463		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10464	/* XXX set the SID_MultiP bit here if we're actually going to
10465	   respond on multiple ports */
10466	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10467
10468	/* 16 bit data bus, synchronous transfers */
10469	if (port_type == CTL_PORT_SCSI)
10470		inq_ptr->flags = SID_WBus16 | SID_Sync;
10471	/*
10472	 * XXX KDM do we want to support tagged queueing on the control
10473	 * device at all?
10474	 */
10475	if ((lun == NULL)
10476	 || (lun->be_lun->lun_type != T_PROCESSOR))
10477		inq_ptr->flags |= SID_CmdQue;
10478	/*
10479	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10480	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10481	 * name and 4 bytes for the revision.
10482	 */
10483	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10484	    "vendor")) == NULL) {
10485		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10486	} else {
10487		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10488		strncpy(inq_ptr->vendor, val,
10489		    min(sizeof(inq_ptr->vendor), strlen(val)));
10490	}
10491	if (lun == NULL) {
10492		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10493		    sizeof(inq_ptr->product));
10494	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10495		switch (lun->be_lun->lun_type) {
10496		case T_DIRECT:
10497			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10498			    sizeof(inq_ptr->product));
10499			break;
10500		case T_PROCESSOR:
10501			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10502			    sizeof(inq_ptr->product));
10503			break;
10504		default:
10505			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10506			    sizeof(inq_ptr->product));
10507			break;
10508		}
10509	} else {
10510		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10511		strncpy(inq_ptr->product, val,
10512		    min(sizeof(inq_ptr->product), strlen(val)));
10513	}
10514
10515	/*
10516	 * XXX make this a macro somewhere so it automatically gets
10517	 * incremented when we make changes.
10518	 */
10519	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10520	    "revision")) == NULL) {
10521		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10522	} else {
10523		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10524		strncpy(inq_ptr->revision, val,
10525		    min(sizeof(inq_ptr->revision), strlen(val)));
10526	}
10527
10528	/*
10529	 * For parallel SCSI, we support double transition and single
10530	 * transition clocking.  We also support QAS (Quick Arbitration
10531	 * and Selection) and Information Unit transfers on both the
10532	 * control and array devices.
10533	 */
10534	if (port_type == CTL_PORT_SCSI)
10535		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10536				    SID_SPI_IUS;
10537
10538	/* SAM-5 (no version claimed) */
10539	scsi_ulto2b(0x00A0, inq_ptr->version1);
10540	/* SPC-4 (no version claimed) */
10541	scsi_ulto2b(0x0460, inq_ptr->version2);
10542	if (port_type == CTL_PORT_FC) {
10543		/* FCP-2 ANSI INCITS.350:2003 */
10544		scsi_ulto2b(0x0917, inq_ptr->version3);
10545	} else if (port_type == CTL_PORT_SCSI) {
10546		/* SPI-4 ANSI INCITS.362:200x */
10547		scsi_ulto2b(0x0B56, inq_ptr->version3);
10548	} else if (port_type == CTL_PORT_ISCSI) {
10549		/* iSCSI (no version claimed) */
10550		scsi_ulto2b(0x0960, inq_ptr->version3);
10551	} else if (port_type == CTL_PORT_SAS) {
10552		/* SAS (no version claimed) */
10553		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10554	}
10555
10556	if (lun == NULL) {
10557		/* SBC-4 (no version claimed) */
10558		scsi_ulto2b(0x0600, inq_ptr->version4);
10559	} else {
10560		switch (lun->be_lun->lun_type) {
10561		case T_DIRECT:
10562			/* SBC-4 (no version claimed) */
10563			scsi_ulto2b(0x0600, inq_ptr->version4);
10564			break;
10565		case T_PROCESSOR:
10566		default:
10567			break;
10568		}
10569	}
10570
10571	ctsio->scsi_status = SCSI_STATUS_OK;
10572	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10573	ctsio->be_move_done = ctl_config_move_done;
10574	ctl_datamove((union ctl_io *)ctsio);
10575	return (CTL_RETVAL_COMPLETE);
10576}
10577
10578int
10579ctl_inquiry(struct ctl_scsiio *ctsio)
10580{
10581	struct scsi_inquiry *cdb;
10582	int retval;
10583
10584	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10585
10586	cdb = (struct scsi_inquiry *)ctsio->cdb;
10587	if (cdb->byte2 & SI_EVPD)
10588		retval = ctl_inquiry_evpd(ctsio);
10589	else if (cdb->page_code == 0)
10590		retval = ctl_inquiry_std(ctsio);
10591	else {
10592		ctl_set_invalid_field(ctsio,
10593				      /*sks_valid*/ 1,
10594				      /*command*/ 1,
10595				      /*field*/ 2,
10596				      /*bit_valid*/ 0,
10597				      /*bit*/ 0);
10598		ctl_done((union ctl_io *)ctsio);
10599		return (CTL_RETVAL_COMPLETE);
10600	}
10601
10602	return (retval);
10603}
10604
10605/*
10606 * For known CDB types, parse the LBA and length.
10607 */
10608static int
10609ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10610{
10611	if (io->io_hdr.io_type != CTL_IO_SCSI)
10612		return (1);
10613
10614	switch (io->scsiio.cdb[0]) {
10615	case COMPARE_AND_WRITE: {
10616		struct scsi_compare_and_write *cdb;
10617
10618		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10619
10620		*lba = scsi_8btou64(cdb->addr);
10621		*len = cdb->length;
10622		break;
10623	}
10624	case READ_6:
10625	case WRITE_6: {
10626		struct scsi_rw_6 *cdb;
10627
10628		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10629
10630		*lba = scsi_3btoul(cdb->addr);
10631		/* only 5 bits are valid in the most significant address byte */
10632		*lba &= 0x1fffff;
10633		*len = cdb->length;
10634		break;
10635	}
10636	case READ_10:
10637	case WRITE_10: {
10638		struct scsi_rw_10 *cdb;
10639
10640		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10641
10642		*lba = scsi_4btoul(cdb->addr);
10643		*len = scsi_2btoul(cdb->length);
10644		break;
10645	}
10646	case WRITE_VERIFY_10: {
10647		struct scsi_write_verify_10 *cdb;
10648
10649		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10650
10651		*lba = scsi_4btoul(cdb->addr);
10652		*len = scsi_2btoul(cdb->length);
10653		break;
10654	}
10655	case READ_12:
10656	case WRITE_12: {
10657		struct scsi_rw_12 *cdb;
10658
10659		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10660
10661		*lba = scsi_4btoul(cdb->addr);
10662		*len = scsi_4btoul(cdb->length);
10663		break;
10664	}
10665	case WRITE_VERIFY_12: {
10666		struct scsi_write_verify_12 *cdb;
10667
10668		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10669
10670		*lba = scsi_4btoul(cdb->addr);
10671		*len = scsi_4btoul(cdb->length);
10672		break;
10673	}
10674	case READ_16:
10675	case WRITE_16:
10676	case WRITE_ATOMIC_16: {
10677		struct scsi_rw_16 *cdb;
10678
10679		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10680
10681		*lba = scsi_8btou64(cdb->addr);
10682		*len = scsi_4btoul(cdb->length);
10683		break;
10684	}
10685	case WRITE_VERIFY_16: {
10686		struct scsi_write_verify_16 *cdb;
10687
10688		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10689
10690		*lba = scsi_8btou64(cdb->addr);
10691		*len = scsi_4btoul(cdb->length);
10692		break;
10693	}
10694	case WRITE_SAME_10: {
10695		struct scsi_write_same_10 *cdb;
10696
10697		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10698
10699		*lba = scsi_4btoul(cdb->addr);
10700		*len = scsi_2btoul(cdb->length);
10701		break;
10702	}
10703	case WRITE_SAME_16: {
10704		struct scsi_write_same_16 *cdb;
10705
10706		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10707
10708		*lba = scsi_8btou64(cdb->addr);
10709		*len = scsi_4btoul(cdb->length);
10710		break;
10711	}
10712	case VERIFY_10: {
10713		struct scsi_verify_10 *cdb;
10714
10715		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10716
10717		*lba = scsi_4btoul(cdb->addr);
10718		*len = scsi_2btoul(cdb->length);
10719		break;
10720	}
10721	case VERIFY_12: {
10722		struct scsi_verify_12 *cdb;
10723
10724		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10725
10726		*lba = scsi_4btoul(cdb->addr);
10727		*len = scsi_4btoul(cdb->length);
10728		break;
10729	}
10730	case VERIFY_16: {
10731		struct scsi_verify_16 *cdb;
10732
10733		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10734
10735		*lba = scsi_8btou64(cdb->addr);
10736		*len = scsi_4btoul(cdb->length);
10737		break;
10738	}
10739	case UNMAP: {
10740		*lba = 0;
10741		*len = UINT64_MAX;
10742		break;
10743	}
10744	default:
10745		return (1);
10746		break; /* NOTREACHED */
10747	}
10748
10749	return (0);
10750}
10751
10752static ctl_action
10753ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2)
10754{
10755	uint64_t endlba1, endlba2;
10756
10757	endlba1 = lba1 + len1 - 1;
10758	endlba2 = lba2 + len2 - 1;
10759
10760	if ((endlba1 < lba2)
10761	 || (endlba2 < lba1))
10762		return (CTL_ACTION_PASS);
10763	else
10764		return (CTL_ACTION_BLOCK);
10765}
10766
10767static int
10768ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10769{
10770	struct ctl_ptr_len_flags *ptrlen;
10771	struct scsi_unmap_desc *buf, *end, *range;
10772	uint64_t lba;
10773	uint32_t len;
10774
10775	/* If not UNMAP -- go other way. */
10776	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10777	    io->scsiio.cdb[0] != UNMAP)
10778		return (CTL_ACTION_ERROR);
10779
10780	/* If UNMAP without data -- block and wait for data. */
10781	ptrlen = (struct ctl_ptr_len_flags *)
10782	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10783	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10784	    ptrlen->ptr == NULL)
10785		return (CTL_ACTION_BLOCK);
10786
10787	/* UNMAP with data -- check for collision. */
10788	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10789	end = buf + ptrlen->len / sizeof(*buf);
10790	for (range = buf; range < end; range++) {
10791		lba = scsi_8btou64(range->lba);
10792		len = scsi_4btoul(range->length);
10793		if ((lba < lba2 + len2) && (lba + len > lba2))
10794			return (CTL_ACTION_BLOCK);
10795	}
10796	return (CTL_ACTION_PASS);
10797}
10798
10799static ctl_action
10800ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10801{
10802	uint64_t lba1, lba2;
10803	uint64_t len1, len2;
10804	int retval;
10805
10806	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10807		return (CTL_ACTION_ERROR);
10808
10809	retval = ctl_extent_check_unmap(io2, lba1, len1);
10810	if (retval != CTL_ACTION_ERROR)
10811		return (retval);
10812
10813	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10814		return (CTL_ACTION_ERROR);
10815
10816	return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10817}
10818
10819static ctl_action
10820ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10821    union ctl_io *ooa_io)
10822{
10823	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10824	ctl_serialize_action *serialize_row;
10825
10826	/*
10827	 * The initiator attempted multiple untagged commands at the same
10828	 * time.  Can't do that.
10829	 */
10830	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10831	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10832	 && ((pending_io->io_hdr.nexus.targ_port ==
10833	      ooa_io->io_hdr.nexus.targ_port)
10834	  && (pending_io->io_hdr.nexus.initid.id ==
10835	      ooa_io->io_hdr.nexus.initid.id))
10836	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10837		return (CTL_ACTION_OVERLAP);
10838
10839	/*
10840	 * The initiator attempted to send multiple tagged commands with
10841	 * the same ID.  (It's fine if different initiators have the same
10842	 * tag ID.)
10843	 *
10844	 * Even if all of those conditions are true, we don't kill the I/O
10845	 * if the command ahead of us has been aborted.  We won't end up
10846	 * sending it to the FETD, and it's perfectly legal to resend a
10847	 * command with the same tag number as long as the previous
10848	 * instance of this tag number has been aborted somehow.
10849	 */
10850	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10851	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10852	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10853	 && ((pending_io->io_hdr.nexus.targ_port ==
10854	      ooa_io->io_hdr.nexus.targ_port)
10855	  && (pending_io->io_hdr.nexus.initid.id ==
10856	      ooa_io->io_hdr.nexus.initid.id))
10857	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10858		return (CTL_ACTION_OVERLAP_TAG);
10859
10860	/*
10861	 * If we get a head of queue tag, SAM-3 says that we should
10862	 * immediately execute it.
10863	 *
10864	 * What happens if this command would normally block for some other
10865	 * reason?  e.g. a request sense with a head of queue tag
10866	 * immediately after a write.  Normally that would block, but this
10867	 * will result in its getting executed immediately...
10868	 *
10869	 * We currently return "pass" instead of "skip", so we'll end up
10870	 * going through the rest of the queue to check for overlapped tags.
10871	 *
10872	 * XXX KDM check for other types of blockage first??
10873	 */
10874	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10875		return (CTL_ACTION_PASS);
10876
10877	/*
10878	 * Ordered tags have to block until all items ahead of them
10879	 * have completed.  If we get called with an ordered tag, we always
10880	 * block, if something else is ahead of us in the queue.
10881	 */
10882	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10883		return (CTL_ACTION_BLOCK);
10884
10885	/*
10886	 * Simple tags get blocked until all head of queue and ordered tags
10887	 * ahead of them have completed.  I'm lumping untagged commands in
10888	 * with simple tags here.  XXX KDM is that the right thing to do?
10889	 */
10890	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10891	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10892	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10893	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10894		return (CTL_ACTION_BLOCK);
10895
10896	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10897	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10898
10899	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10900
10901	switch (serialize_row[pending_entry->seridx]) {
10902	case CTL_SER_BLOCK:
10903		return (CTL_ACTION_BLOCK);
10904	case CTL_SER_EXTENT:
10905		return (ctl_extent_check(pending_io, ooa_io));
10906	case CTL_SER_EXTENTOPT:
10907		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10908		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10909			return (ctl_extent_check(pending_io, ooa_io));
10910		/* FALLTHROUGH */
10911	case CTL_SER_PASS:
10912		return (CTL_ACTION_PASS);
10913	case CTL_SER_BLOCKOPT:
10914		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10915		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10916			return (CTL_ACTION_BLOCK);
10917		return (CTL_ACTION_PASS);
10918	case CTL_SER_SKIP:
10919		return (CTL_ACTION_SKIP);
10920	default:
10921		panic("invalid serialization value %d",
10922		      serialize_row[pending_entry->seridx]);
10923	}
10924
10925	return (CTL_ACTION_ERROR);
10926}
10927
10928/*
10929 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10930 * Assumptions:
10931 * - pending_io is generally either incoming, or on the blocked queue
10932 * - starting I/O is the I/O we want to start the check with.
10933 */
10934static ctl_action
10935ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10936	      union ctl_io *starting_io)
10937{
10938	union ctl_io *ooa_io;
10939	ctl_action action;
10940
10941	mtx_assert(&lun->lun_lock, MA_OWNED);
10942
10943	/*
10944	 * Run back along the OOA queue, starting with the current
10945	 * blocked I/O and going through every I/O before it on the
10946	 * queue.  If starting_io is NULL, we'll just end up returning
10947	 * CTL_ACTION_PASS.
10948	 */
10949	for (ooa_io = starting_io; ooa_io != NULL;
10950	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10951	     ooa_links)){
10952
10953		/*
10954		 * This routine just checks to see whether
10955		 * cur_blocked is blocked by ooa_io, which is ahead
10956		 * of it in the queue.  It doesn't queue/dequeue
10957		 * cur_blocked.
10958		 */
10959		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10960		switch (action) {
10961		case CTL_ACTION_BLOCK:
10962		case CTL_ACTION_OVERLAP:
10963		case CTL_ACTION_OVERLAP_TAG:
10964		case CTL_ACTION_SKIP:
10965		case CTL_ACTION_ERROR:
10966			return (action);
10967			break; /* NOTREACHED */
10968		case CTL_ACTION_PASS:
10969			break;
10970		default:
10971			panic("invalid action %d", action);
10972			break;  /* NOTREACHED */
10973		}
10974	}
10975
10976	return (CTL_ACTION_PASS);
10977}
10978
10979/*
10980 * Assumptions:
10981 * - An I/O has just completed, and has been removed from the per-LUN OOA
10982 *   queue, so some items on the blocked queue may now be unblocked.
10983 */
10984static int
10985ctl_check_blocked(struct ctl_lun *lun)
10986{
10987	union ctl_io *cur_blocked, *next_blocked;
10988
10989	mtx_assert(&lun->lun_lock, MA_OWNED);
10990
10991	/*
10992	 * Run forward from the head of the blocked queue, checking each
10993	 * entry against the I/Os prior to it on the OOA queue to see if
10994	 * there is still any blockage.
10995	 *
10996	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10997	 * with our removing a variable on it while it is traversing the
10998	 * list.
10999	 */
11000	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11001	     cur_blocked != NULL; cur_blocked = next_blocked) {
11002		union ctl_io *prev_ooa;
11003		ctl_action action;
11004
11005		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11006							  blocked_links);
11007
11008		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11009						      ctl_ooaq, ooa_links);
11010
11011		/*
11012		 * If cur_blocked happens to be the first item in the OOA
11013		 * queue now, prev_ooa will be NULL, and the action
11014		 * returned will just be CTL_ACTION_PASS.
11015		 */
11016		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11017
11018		switch (action) {
11019		case CTL_ACTION_BLOCK:
11020			/* Nothing to do here, still blocked */
11021			break;
11022		case CTL_ACTION_OVERLAP:
11023		case CTL_ACTION_OVERLAP_TAG:
11024			/*
11025			 * This shouldn't happen!  In theory we've already
11026			 * checked this command for overlap...
11027			 */
11028			break;
11029		case CTL_ACTION_PASS:
11030		case CTL_ACTION_SKIP: {
11031			struct ctl_softc *softc;
11032			const struct ctl_cmd_entry *entry;
11033			uint32_t initidx;
11034			int isc_retval;
11035
11036			/*
11037			 * The skip case shouldn't happen, this transaction
11038			 * should have never made it onto the blocked queue.
11039			 */
11040			/*
11041			 * This I/O is no longer blocked, we can remove it
11042			 * from the blocked queue.  Since this is a TAILQ
11043			 * (doubly linked list), we can do O(1) removals
11044			 * from any place on the list.
11045			 */
11046			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11047				     blocked_links);
11048			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11049
11050			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11051				/*
11052				 * Need to send IO back to original side to
11053				 * run
11054				 */
11055				union ctl_ha_msg msg_info;
11056
11057				msg_info.hdr.original_sc =
11058					cur_blocked->io_hdr.original_sc;
11059				msg_info.hdr.serializing_sc = cur_blocked;
11060				msg_info.hdr.msg_type = CTL_MSG_R2R;
11061				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11062				     &msg_info, sizeof(msg_info), 0)) >
11063				     CTL_HA_STATUS_SUCCESS) {
11064					printf("CTL:Check Blocked error from "
11065					       "ctl_ha_msg_send %d\n",
11066					       isc_retval);
11067				}
11068				break;
11069			}
11070			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11071			softc = control_softc;
11072
11073			initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
11074
11075			/*
11076			 * Check this I/O for LUN state changes that may
11077			 * have happened while this command was blocked.
11078			 * The LUN state may have been changed by a command
11079			 * ahead of us in the queue, so we need to re-check
11080			 * for any states that can be caused by SCSI
11081			 * commands.
11082			 */
11083			if (ctl_scsiio_lun_check(softc, lun, entry,
11084						 &cur_blocked->scsiio) == 0) {
11085				cur_blocked->io_hdr.flags |=
11086				                      CTL_FLAG_IS_WAS_ON_RTR;
11087				ctl_enqueue_rtr(cur_blocked);
11088			} else
11089				ctl_done(cur_blocked);
11090			break;
11091		}
11092		default:
11093			/*
11094			 * This probably shouldn't happen -- we shouldn't
11095			 * get CTL_ACTION_ERROR, or anything else.
11096			 */
11097			break;
11098		}
11099	}
11100
11101	return (CTL_RETVAL_COMPLETE);
11102}
11103
11104/*
11105 * This routine (with one exception) checks LUN flags that can be set by
11106 * commands ahead of us in the OOA queue.  These flags have to be checked
11107 * when a command initially comes in, and when we pull a command off the
11108 * blocked queue and are preparing to execute it.  The reason we have to
11109 * check these flags for commands on the blocked queue is that the LUN
11110 * state may have been changed by a command ahead of us while we're on the
11111 * blocked queue.
11112 *
11113 * Ordering is somewhat important with these checks, so please pay
11114 * careful attention to the placement of any new checks.
11115 */
11116static int
11117ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11118    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11119{
11120	int retval;
11121	uint32_t residx;
11122
11123	retval = 0;
11124
11125	mtx_assert(&lun->lun_lock, MA_OWNED);
11126
11127	/*
11128	 * If this shelf is a secondary shelf controller, we have to reject
11129	 * any media access commands.
11130	 */
11131	if ((ctl_softc->flags & CTL_FLAG_ACTIVE_SHELF) == 0 &&
11132	    (entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0) {
11133		ctl_set_lun_standby(ctsio);
11134		retval = 1;
11135		goto bailout;
11136	}
11137
11138	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11139		if (lun->flags & CTL_LUN_READONLY) {
11140			ctl_set_sense(ctsio, /*current_error*/ 1,
11141			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11142			    /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11143			retval = 1;
11144			goto bailout;
11145		}
11146		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11147		    .eca_and_aen & SCP_SWP) != 0) {
11148			ctl_set_sense(ctsio, /*current_error*/ 1,
11149			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11150			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11151			retval = 1;
11152			goto bailout;
11153		}
11154	}
11155
11156	/*
11157	 * Check for a reservation conflict.  If this command isn't allowed
11158	 * even on reserved LUNs, and if this initiator isn't the one who
11159	 * reserved us, reject the command with a reservation conflict.
11160	 */
11161	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11162	if ((lun->flags & CTL_LUN_RESERVED)
11163	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11164		if (lun->res_idx != residx) {
11165			ctl_set_reservation_conflict(ctsio);
11166			retval = 1;
11167			goto bailout;
11168		}
11169	}
11170
11171	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11172	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11173		/* No reservation or command is allowed. */;
11174	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11175	    (lun->res_type == SPR_TYPE_WR_EX ||
11176	     lun->res_type == SPR_TYPE_WR_EX_RO ||
11177	     lun->res_type == SPR_TYPE_WR_EX_AR)) {
11178		/* The command is allowed for Write Exclusive resv. */;
11179	} else {
11180		/*
11181		 * if we aren't registered or it's a res holder type
11182		 * reservation and this isn't the res holder then set a
11183		 * conflict.
11184		 */
11185		if (lun->pr_keys[residx] == 0
11186		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11187			ctl_set_reservation_conflict(ctsio);
11188			retval = 1;
11189			goto bailout;
11190		}
11191
11192	}
11193
11194	if ((lun->flags & CTL_LUN_OFFLINE)
11195	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11196		ctl_set_lun_not_ready(ctsio);
11197		retval = 1;
11198		goto bailout;
11199	}
11200
11201	/*
11202	 * If the LUN is stopped, see if this particular command is allowed
11203	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11204	 */
11205	if ((lun->flags & CTL_LUN_STOPPED)
11206	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11207		/* "Logical unit not ready, initializing cmd. required" */
11208		ctl_set_lun_stopped(ctsio);
11209		retval = 1;
11210		goto bailout;
11211	}
11212
11213	if ((lun->flags & CTL_LUN_INOPERABLE)
11214	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11215		/* "Medium format corrupted" */
11216		ctl_set_medium_format_corrupted(ctsio);
11217		retval = 1;
11218		goto bailout;
11219	}
11220
11221bailout:
11222	return (retval);
11223
11224}
11225
11226static void
11227ctl_failover_io(union ctl_io *io, int have_lock)
11228{
11229	ctl_set_busy(&io->scsiio);
11230	ctl_done(io);
11231}
11232
11233static void
11234ctl_failover(void)
11235{
11236	struct ctl_lun *lun;
11237	struct ctl_softc *ctl_softc;
11238	union ctl_io *next_io, *pending_io;
11239	union ctl_io *io;
11240	int lun_idx;
11241	int i;
11242
11243	ctl_softc = control_softc;
11244
11245	mtx_lock(&ctl_softc->ctl_lock);
11246	/*
11247	 * Remove any cmds from the other SC from the rtr queue.  These
11248	 * will obviously only be for LUNs for which we're the primary.
11249	 * We can't send status or get/send data for these commands.
11250	 * Since they haven't been executed yet, we can just remove them.
11251	 * We'll either abort them or delete them below, depending on
11252	 * which HA mode we're in.
11253	 */
11254#ifdef notyet
11255	mtx_lock(&ctl_softc->queue_lock);
11256	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11257	     io != NULL; io = next_io) {
11258		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11259		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11260			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11261				      ctl_io_hdr, links);
11262	}
11263	mtx_unlock(&ctl_softc->queue_lock);
11264#endif
11265
11266	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11267		lun = ctl_softc->ctl_luns[lun_idx];
11268		if (lun==NULL)
11269			continue;
11270
11271		/*
11272		 * Processor LUNs are primary on both sides.
11273		 * XXX will this always be true?
11274		 */
11275		if (lun->be_lun->lun_type == T_PROCESSOR)
11276			continue;
11277
11278		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11279		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11280			printf("FAILOVER: primary lun %d\n", lun_idx);
11281		        /*
11282			 * Remove all commands from the other SC. First from the
11283			 * blocked queue then from the ooa queue. Once we have
11284			 * removed them. Call ctl_check_blocked to see if there
11285			 * is anything that can run.
11286			 */
11287			for (io = (union ctl_io *)TAILQ_FIRST(
11288			     &lun->blocked_queue); io != NULL; io = next_io) {
11289
11290		        	next_io = (union ctl_io *)TAILQ_NEXT(
11291				    &io->io_hdr, blocked_links);
11292
11293				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11294					TAILQ_REMOVE(&lun->blocked_queue,
11295						     &io->io_hdr,blocked_links);
11296					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11297					TAILQ_REMOVE(&lun->ooa_queue,
11298						     &io->io_hdr, ooa_links);
11299
11300					ctl_free_io(io);
11301				}
11302			}
11303
11304			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11305	     		     io != NULL; io = next_io) {
11306
11307		        	next_io = (union ctl_io *)TAILQ_NEXT(
11308				    &io->io_hdr, ooa_links);
11309
11310				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11311
11312					TAILQ_REMOVE(&lun->ooa_queue,
11313						&io->io_hdr,
11314					     	ooa_links);
11315
11316					ctl_free_io(io);
11317				}
11318			}
11319			ctl_check_blocked(lun);
11320		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11321			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11322
11323			printf("FAILOVER: primary lun %d\n", lun_idx);
11324			/*
11325			 * Abort all commands from the other SC.  We can't
11326			 * send status back for them now.  These should get
11327			 * cleaned up when they are completed or come out
11328			 * for a datamove operation.
11329			 */
11330			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11331	     		     io != NULL; io = next_io) {
11332		        	next_io = (union ctl_io *)TAILQ_NEXT(
11333					&io->io_hdr, ooa_links);
11334
11335				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11336					io->io_hdr.flags |= CTL_FLAG_ABORT;
11337			}
11338		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11339			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11340
11341			printf("FAILOVER: secondary lun %d\n", lun_idx);
11342
11343			lun->flags |= CTL_LUN_PRIMARY_SC;
11344
11345			/*
11346			 * We send all I/O that was sent to this controller
11347			 * and redirected to the other side back with
11348			 * busy status, and have the initiator retry it.
11349			 * Figuring out how much data has been transferred,
11350			 * etc. and picking up where we left off would be
11351			 * very tricky.
11352			 *
11353			 * XXX KDM need to remove I/O from the blocked
11354			 * queue as well!
11355			 */
11356			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11357			     &lun->ooa_queue); pending_io != NULL;
11358			     pending_io = next_io) {
11359
11360				next_io =  (union ctl_io *)TAILQ_NEXT(
11361					&pending_io->io_hdr, ooa_links);
11362
11363				pending_io->io_hdr.flags &=
11364					~CTL_FLAG_SENT_2OTHER_SC;
11365
11366				if (pending_io->io_hdr.flags &
11367				    CTL_FLAG_IO_ACTIVE) {
11368					pending_io->io_hdr.flags |=
11369						CTL_FLAG_FAILOVER;
11370				} else {
11371					ctl_set_busy(&pending_io->scsiio);
11372					ctl_done(pending_io);
11373				}
11374			}
11375
11376			/*
11377			 * Build Unit Attention
11378			 */
11379			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11380				lun->pending_ua[i] |=
11381				                     CTL_UA_ASYM_ACC_CHANGE;
11382			}
11383		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11384			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11385			printf("FAILOVER: secondary lun %d\n", lun_idx);
11386			/*
11387			 * if the first io on the OOA is not on the RtR queue
11388			 * add it.
11389			 */
11390			lun->flags |= CTL_LUN_PRIMARY_SC;
11391
11392			pending_io = (union ctl_io *)TAILQ_FIRST(
11393			    &lun->ooa_queue);
11394			if (pending_io==NULL) {
11395				printf("Nothing on OOA queue\n");
11396				continue;
11397			}
11398
11399			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11400			if ((pending_io->io_hdr.flags &
11401			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11402				pending_io->io_hdr.flags |=
11403				    CTL_FLAG_IS_WAS_ON_RTR;
11404				ctl_enqueue_rtr(pending_io);
11405			}
11406#if 0
11407			else
11408			{
11409				printf("Tag 0x%04x is running\n",
11410				      pending_io->scsiio.tag_num);
11411			}
11412#endif
11413
11414			next_io = (union ctl_io *)TAILQ_NEXT(
11415			    &pending_io->io_hdr, ooa_links);
11416			for (pending_io=next_io; pending_io != NULL;
11417			     pending_io = next_io) {
11418				pending_io->io_hdr.flags &=
11419				    ~CTL_FLAG_SENT_2OTHER_SC;
11420				next_io = (union ctl_io *)TAILQ_NEXT(
11421					&pending_io->io_hdr, ooa_links);
11422				if (pending_io->io_hdr.flags &
11423				    CTL_FLAG_IS_WAS_ON_RTR) {
11424#if 0
11425				        printf("Tag 0x%04x is running\n",
11426				      		pending_io->scsiio.tag_num);
11427#endif
11428					continue;
11429				}
11430
11431				switch (ctl_check_ooa(lun, pending_io,
11432			            (union ctl_io *)TAILQ_PREV(
11433				    &pending_io->io_hdr, ctl_ooaq,
11434				    ooa_links))) {
11435
11436				case CTL_ACTION_BLOCK:
11437					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11438							  &pending_io->io_hdr,
11439							  blocked_links);
11440					pending_io->io_hdr.flags |=
11441					    CTL_FLAG_BLOCKED;
11442					break;
11443				case CTL_ACTION_PASS:
11444				case CTL_ACTION_SKIP:
11445					pending_io->io_hdr.flags |=
11446					    CTL_FLAG_IS_WAS_ON_RTR;
11447					ctl_enqueue_rtr(pending_io);
11448					break;
11449				case CTL_ACTION_OVERLAP:
11450					ctl_set_overlapped_cmd(
11451					    (struct ctl_scsiio *)pending_io);
11452					ctl_done(pending_io);
11453					break;
11454				case CTL_ACTION_OVERLAP_TAG:
11455					ctl_set_overlapped_tag(
11456					    (struct ctl_scsiio *)pending_io,
11457					    pending_io->scsiio.tag_num & 0xff);
11458					ctl_done(pending_io);
11459					break;
11460				case CTL_ACTION_ERROR:
11461				default:
11462					ctl_set_internal_failure(
11463						(struct ctl_scsiio *)pending_io,
11464						0,  // sks_valid
11465						0); //retry count
11466					ctl_done(pending_io);
11467					break;
11468				}
11469			}
11470
11471			/*
11472			 * Build Unit Attention
11473			 */
11474			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11475				lun->pending_ua[i] |=
11476				                     CTL_UA_ASYM_ACC_CHANGE;
11477			}
11478		} else {
11479			panic("Unhandled HA mode failover, LUN flags = %#x, "
11480			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11481		}
11482	}
11483	ctl_pause_rtr = 0;
11484	mtx_unlock(&ctl_softc->ctl_lock);
11485}
11486
11487static int
11488ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11489{
11490	struct ctl_lun *lun;
11491	const struct ctl_cmd_entry *entry;
11492	uint32_t initidx, targ_lun;
11493	int retval;
11494
11495	retval = 0;
11496
11497	lun = NULL;
11498
11499	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11500	if ((targ_lun < CTL_MAX_LUNS)
11501	 && ((lun = ctl_softc->ctl_luns[targ_lun]) != NULL)) {
11502		/*
11503		 * If the LUN is invalid, pretend that it doesn't exist.
11504		 * It will go away as soon as all pending I/O has been
11505		 * completed.
11506		 */
11507		mtx_lock(&lun->lun_lock);
11508		if (lun->flags & CTL_LUN_DISABLED) {
11509			mtx_unlock(&lun->lun_lock);
11510			lun = NULL;
11511			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11512			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11513		} else {
11514			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11515			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11516				lun->be_lun;
11517			if (lun->be_lun->lun_type == T_PROCESSOR) {
11518				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11519			}
11520
11521			/*
11522			 * Every I/O goes into the OOA queue for a
11523			 * particular LUN, and stays there until completion.
11524			 */
11525			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11526			    ooa_links);
11527		}
11528	} else {
11529		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11530		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11531	}
11532
11533	/* Get command entry and return error if it is unsuppotyed. */
11534	entry = ctl_validate_command(ctsio);
11535	if (entry == NULL) {
11536		if (lun)
11537			mtx_unlock(&lun->lun_lock);
11538		return (retval);
11539	}
11540
11541	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11542	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11543
11544	/*
11545	 * Check to see whether we can send this command to LUNs that don't
11546	 * exist.  This should pretty much only be the case for inquiry
11547	 * and request sense.  Further checks, below, really require having
11548	 * a LUN, so we can't really check the command anymore.  Just put
11549	 * it on the rtr queue.
11550	 */
11551	if (lun == NULL) {
11552		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11553			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11554			ctl_enqueue_rtr((union ctl_io *)ctsio);
11555			return (retval);
11556		}
11557
11558		ctl_set_unsupported_lun(ctsio);
11559		ctl_done((union ctl_io *)ctsio);
11560		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11561		return (retval);
11562	} else {
11563		/*
11564		 * Make sure we support this particular command on this LUN.
11565		 * e.g., we don't support writes to the control LUN.
11566		 */
11567		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11568			mtx_unlock(&lun->lun_lock);
11569			ctl_set_invalid_opcode(ctsio);
11570			ctl_done((union ctl_io *)ctsio);
11571			return (retval);
11572		}
11573	}
11574
11575	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11576
11577#ifdef CTL_WITH_CA
11578	/*
11579	 * If we've got a request sense, it'll clear the contingent
11580	 * allegiance condition.  Otherwise, if we have a CA condition for
11581	 * this initiator, clear it, because it sent down a command other
11582	 * than request sense.
11583	 */
11584	if ((ctsio->cdb[0] != REQUEST_SENSE)
11585	 && (ctl_is_set(lun->have_ca, initidx)))
11586		ctl_clear_mask(lun->have_ca, initidx);
11587#endif
11588
11589	/*
11590	 * If the command has this flag set, it handles its own unit
11591	 * attention reporting, we shouldn't do anything.  Otherwise we
11592	 * check for any pending unit attentions, and send them back to the
11593	 * initiator.  We only do this when a command initially comes in,
11594	 * not when we pull it off the blocked queue.
11595	 *
11596	 * According to SAM-3, section 5.3.2, the order that things get
11597	 * presented back to the host is basically unit attentions caused
11598	 * by some sort of reset event, busy status, reservation conflicts
11599	 * or task set full, and finally any other status.
11600	 *
11601	 * One issue here is that some of the unit attentions we report
11602	 * don't fall into the "reset" category (e.g. "reported luns data
11603	 * has changed").  So reporting it here, before the reservation
11604	 * check, may be technically wrong.  I guess the only thing to do
11605	 * would be to check for and report the reset events here, and then
11606	 * check for the other unit attention types after we check for a
11607	 * reservation conflict.
11608	 *
11609	 * XXX KDM need to fix this
11610	 */
11611	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11612		ctl_ua_type ua_type;
11613
11614		if (lun->pending_ua[initidx] != CTL_UA_NONE) {
11615			scsi_sense_data_type sense_format;
11616
11617			if (lun != NULL)
11618				sense_format = (lun->flags &
11619				    CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11620				    SSD_TYPE_FIXED;
11621			else
11622				sense_format = SSD_TYPE_FIXED;
11623
11624			ua_type = ctl_build_ua(&lun->pending_ua[initidx],
11625			    &ctsio->sense_data, sense_format);
11626			if (ua_type != CTL_UA_NONE) {
11627				ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11628				ctsio->io_hdr.status = CTL_SCSI_ERROR |
11629						       CTL_AUTOSENSE;
11630				ctsio->sense_len = SSD_FULL_SIZE;
11631				mtx_unlock(&lun->lun_lock);
11632				ctl_done((union ctl_io *)ctsio);
11633				return (retval);
11634			}
11635		}
11636	}
11637
11638
11639	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11640		mtx_unlock(&lun->lun_lock);
11641		ctl_done((union ctl_io *)ctsio);
11642		return (retval);
11643	}
11644
11645	/*
11646	 * XXX CHD this is where we want to send IO to other side if
11647	 * this LUN is secondary on this SC. We will need to make a copy
11648	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11649	 * the copy we send as FROM_OTHER.
11650	 * We also need to stuff the address of the original IO so we can
11651	 * find it easily. Something similar will need be done on the other
11652	 * side so when we are done we can find the copy.
11653	 */
11654	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11655		union ctl_ha_msg msg_info;
11656		int isc_retval;
11657
11658		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11659
11660		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11661		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11662#if 0
11663		printf("1. ctsio %p\n", ctsio);
11664#endif
11665		msg_info.hdr.serializing_sc = NULL;
11666		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11667		msg_info.scsi.tag_num = ctsio->tag_num;
11668		msg_info.scsi.tag_type = ctsio->tag_type;
11669		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11670
11671		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11672
11673		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11674		    (void *)&msg_info, sizeof(msg_info), 0)) >
11675		    CTL_HA_STATUS_SUCCESS) {
11676			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11677			       isc_retval);
11678			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11679		} else {
11680#if 0
11681			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11682#endif
11683		}
11684
11685		/*
11686		 * XXX KDM this I/O is off the incoming queue, but hasn't
11687		 * been inserted on any other queue.  We may need to come
11688		 * up with a holding queue while we wait for serialization
11689		 * so that we have an idea of what we're waiting for from
11690		 * the other side.
11691		 */
11692		mtx_unlock(&lun->lun_lock);
11693		return (retval);
11694	}
11695
11696	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11697			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11698			      ctl_ooaq, ooa_links))) {
11699	case CTL_ACTION_BLOCK:
11700		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11701		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11702				  blocked_links);
11703		mtx_unlock(&lun->lun_lock);
11704		return (retval);
11705	case CTL_ACTION_PASS:
11706	case CTL_ACTION_SKIP:
11707		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11708		mtx_unlock(&lun->lun_lock);
11709		ctl_enqueue_rtr((union ctl_io *)ctsio);
11710		break;
11711	case CTL_ACTION_OVERLAP:
11712		mtx_unlock(&lun->lun_lock);
11713		ctl_set_overlapped_cmd(ctsio);
11714		ctl_done((union ctl_io *)ctsio);
11715		break;
11716	case CTL_ACTION_OVERLAP_TAG:
11717		mtx_unlock(&lun->lun_lock);
11718		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11719		ctl_done((union ctl_io *)ctsio);
11720		break;
11721	case CTL_ACTION_ERROR:
11722	default:
11723		mtx_unlock(&lun->lun_lock);
11724		ctl_set_internal_failure(ctsio,
11725					 /*sks_valid*/ 0,
11726					 /*retry_count*/ 0);
11727		ctl_done((union ctl_io *)ctsio);
11728		break;
11729	}
11730	return (retval);
11731}
11732
11733const struct ctl_cmd_entry *
11734ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11735{
11736	const struct ctl_cmd_entry *entry;
11737	int service_action;
11738
11739	entry = &ctl_cmd_table[ctsio->cdb[0]];
11740	if (sa)
11741		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11742	if (entry->flags & CTL_CMD_FLAG_SA5) {
11743		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11744		entry = &((const struct ctl_cmd_entry *)
11745		    entry->execute)[service_action];
11746	}
11747	return (entry);
11748}
11749
11750const struct ctl_cmd_entry *
11751ctl_validate_command(struct ctl_scsiio *ctsio)
11752{
11753	const struct ctl_cmd_entry *entry;
11754	int i, sa;
11755	uint8_t diff;
11756
11757	entry = ctl_get_cmd_entry(ctsio, &sa);
11758	if (entry->execute == NULL) {
11759		if (sa)
11760			ctl_set_invalid_field(ctsio,
11761					      /*sks_valid*/ 1,
11762					      /*command*/ 1,
11763					      /*field*/ 1,
11764					      /*bit_valid*/ 1,
11765					      /*bit*/ 4);
11766		else
11767			ctl_set_invalid_opcode(ctsio);
11768		ctl_done((union ctl_io *)ctsio);
11769		return (NULL);
11770	}
11771	KASSERT(entry->length > 0,
11772	    ("Not defined length for command 0x%02x/0x%02x",
11773	     ctsio->cdb[0], ctsio->cdb[1]));
11774	for (i = 1; i < entry->length; i++) {
11775		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11776		if (diff == 0)
11777			continue;
11778		ctl_set_invalid_field(ctsio,
11779				      /*sks_valid*/ 1,
11780				      /*command*/ 1,
11781				      /*field*/ i,
11782				      /*bit_valid*/ 1,
11783				      /*bit*/ fls(diff) - 1);
11784		ctl_done((union ctl_io *)ctsio);
11785		return (NULL);
11786	}
11787	return (entry);
11788}
11789
11790static int
11791ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11792{
11793
11794	switch (lun_type) {
11795	case T_PROCESSOR:
11796		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11797		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11798			return (0);
11799		break;
11800	case T_DIRECT:
11801		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11802		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11803			return (0);
11804		break;
11805	default:
11806		return (0);
11807	}
11808	return (1);
11809}
11810
11811static int
11812ctl_scsiio(struct ctl_scsiio *ctsio)
11813{
11814	int retval;
11815	const struct ctl_cmd_entry *entry;
11816
11817	retval = CTL_RETVAL_COMPLETE;
11818
11819	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11820
11821	entry = ctl_get_cmd_entry(ctsio, NULL);
11822
11823	/*
11824	 * If this I/O has been aborted, just send it straight to
11825	 * ctl_done() without executing it.
11826	 */
11827	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11828		ctl_done((union ctl_io *)ctsio);
11829		goto bailout;
11830	}
11831
11832	/*
11833	 * All the checks should have been handled by ctl_scsiio_precheck().
11834	 * We should be clear now to just execute the I/O.
11835	 */
11836	retval = entry->execute(ctsio);
11837
11838bailout:
11839	return (retval);
11840}
11841
11842/*
11843 * Since we only implement one target right now, a bus reset simply resets
11844 * our single target.
11845 */
11846static int
11847ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11848{
11849	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11850}
11851
11852static int
11853ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11854		 ctl_ua_type ua_type)
11855{
11856	struct ctl_lun *lun;
11857	int retval;
11858
11859	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11860		union ctl_ha_msg msg_info;
11861
11862		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11863		msg_info.hdr.nexus = io->io_hdr.nexus;
11864		if (ua_type==CTL_UA_TARG_RESET)
11865			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11866		else
11867			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11868		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11869		msg_info.hdr.original_sc = NULL;
11870		msg_info.hdr.serializing_sc = NULL;
11871		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11872		    (void *)&msg_info, sizeof(msg_info), 0)) {
11873		}
11874	}
11875	retval = 0;
11876
11877	mtx_lock(&ctl_softc->ctl_lock);
11878	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11879		retval += ctl_lun_reset(lun, io, ua_type);
11880	mtx_unlock(&ctl_softc->ctl_lock);
11881
11882	return (retval);
11883}
11884
11885/*
11886 * The LUN should always be set.  The I/O is optional, and is used to
11887 * distinguish between I/Os sent by this initiator, and by other
11888 * initiators.  We set unit attention for initiators other than this one.
11889 * SAM-3 is vague on this point.  It does say that a unit attention should
11890 * be established for other initiators when a LUN is reset (see section
11891 * 5.7.3), but it doesn't specifically say that the unit attention should
11892 * be established for this particular initiator when a LUN is reset.  Here
11893 * is the relevant text, from SAM-3 rev 8:
11894 *
11895 * 5.7.2 When a SCSI initiator port aborts its own tasks
11896 *
11897 * When a SCSI initiator port causes its own task(s) to be aborted, no
11898 * notification that the task(s) have been aborted shall be returned to
11899 * the SCSI initiator port other than the completion response for the
11900 * command or task management function action that caused the task(s) to
11901 * be aborted and notification(s) associated with related effects of the
11902 * action (e.g., a reset unit attention condition).
11903 *
11904 * XXX KDM for now, we're setting unit attention for all initiators.
11905 */
11906static int
11907ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11908{
11909	union ctl_io *xio;
11910#if 0
11911	uint32_t initindex;
11912#endif
11913	int i;
11914
11915	mtx_lock(&lun->lun_lock);
11916	/*
11917	 * Run through the OOA queue and abort each I/O.
11918	 */
11919#if 0
11920	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11921#endif
11922	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11923	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11924		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11925	}
11926
11927	/*
11928	 * This version sets unit attention for every
11929	 */
11930#if 0
11931	initindex = ctl_get_initindex(&io->io_hdr.nexus);
11932	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11933		if (initindex == i)
11934			continue;
11935		lun->pending_ua[i] |= ua_type;
11936	}
11937#endif
11938
11939	/*
11940	 * A reset (any kind, really) clears reservations established with
11941	 * RESERVE/RELEASE.  It does not clear reservations established
11942	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11943	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11944	 * reservations made with the RESERVE/RELEASE commands, because
11945	 * those commands are obsolete in SPC-3.
11946	 */
11947	lun->flags &= ~CTL_LUN_RESERVED;
11948
11949	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11950#ifdef CTL_WITH_CA
11951		ctl_clear_mask(lun->have_ca, i);
11952#endif
11953		lun->pending_ua[i] |= ua_type;
11954	}
11955	mtx_unlock(&lun->lun_lock);
11956
11957	return (0);
11958}
11959
11960static void
11961ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11962    int other_sc)
11963{
11964	union ctl_io *xio;
11965
11966	mtx_assert(&lun->lun_lock, MA_OWNED);
11967
11968	/*
11969	 * Run through the OOA queue and attempt to find the given I/O.
11970	 * The target port, initiator ID, tag type and tag number have to
11971	 * match the values that we got from the initiator.  If we have an
11972	 * untagged command to abort, simply abort the first untagged command
11973	 * we come to.  We only allow one untagged command at a time of course.
11974	 */
11975	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11976	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11977
11978		if ((targ_port == UINT32_MAX ||
11979		     targ_port == xio->io_hdr.nexus.targ_port) &&
11980		    (init_id == UINT32_MAX ||
11981		     init_id == xio->io_hdr.nexus.initid.id)) {
11982			if (targ_port != xio->io_hdr.nexus.targ_port ||
11983			    init_id != xio->io_hdr.nexus.initid.id)
11984				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11985			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11986			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11987				union ctl_ha_msg msg_info;
11988
11989				msg_info.hdr.nexus = xio->io_hdr.nexus;
11990				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11991				msg_info.task.tag_num = xio->scsiio.tag_num;
11992				msg_info.task.tag_type = xio->scsiio.tag_type;
11993				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11994				msg_info.hdr.original_sc = NULL;
11995				msg_info.hdr.serializing_sc = NULL;
11996				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11997				    (void *)&msg_info, sizeof(msg_info), 0);
11998			}
11999		}
12000	}
12001}
12002
12003static int
12004ctl_abort_task_set(union ctl_io *io)
12005{
12006	struct ctl_softc *softc = control_softc;
12007	struct ctl_lun *lun;
12008	uint32_t targ_lun;
12009
12010	/*
12011	 * Look up the LUN.
12012	 */
12013	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12014	mtx_lock(&softc->ctl_lock);
12015	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
12016		lun = softc->ctl_luns[targ_lun];
12017	else {
12018		mtx_unlock(&softc->ctl_lock);
12019		return (1);
12020	}
12021
12022	mtx_lock(&lun->lun_lock);
12023	mtx_unlock(&softc->ctl_lock);
12024	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12025		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12026		    io->io_hdr.nexus.initid.id,
12027		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12028	} else { /* CTL_TASK_CLEAR_TASK_SET */
12029		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12030		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12031	}
12032	mtx_unlock(&lun->lun_lock);
12033	return (0);
12034}
12035
12036static int
12037ctl_i_t_nexus_reset(union ctl_io *io)
12038{
12039	struct ctl_softc *softc = control_softc;
12040	struct ctl_lun *lun;
12041	uint32_t initindex, residx;
12042
12043	initindex = ctl_get_initindex(&io->io_hdr.nexus);
12044	residx = ctl_get_resindex(&io->io_hdr.nexus);
12045	mtx_lock(&softc->ctl_lock);
12046	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12047		mtx_lock(&lun->lun_lock);
12048		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12049		    io->io_hdr.nexus.initid.id,
12050		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12051#ifdef CTL_WITH_CA
12052		ctl_clear_mask(lun->have_ca, initindex);
12053#endif
12054		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
12055			lun->flags &= ~CTL_LUN_RESERVED;
12056		lun->pending_ua[initindex] |= CTL_UA_I_T_NEXUS_LOSS;
12057		mtx_unlock(&lun->lun_lock);
12058	}
12059	mtx_unlock(&softc->ctl_lock);
12060	return (0);
12061}
12062
12063static int
12064ctl_abort_task(union ctl_io *io)
12065{
12066	union ctl_io *xio;
12067	struct ctl_lun *lun;
12068	struct ctl_softc *ctl_softc;
12069#if 0
12070	struct sbuf sb;
12071	char printbuf[128];
12072#endif
12073	int found;
12074	uint32_t targ_lun;
12075
12076	ctl_softc = control_softc;
12077	found = 0;
12078
12079	/*
12080	 * Look up the LUN.
12081	 */
12082	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12083	mtx_lock(&ctl_softc->ctl_lock);
12084	if ((targ_lun < CTL_MAX_LUNS)
12085	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12086		lun = ctl_softc->ctl_luns[targ_lun];
12087	else {
12088		mtx_unlock(&ctl_softc->ctl_lock);
12089		return (1);
12090	}
12091
12092#if 0
12093	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12094	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12095#endif
12096
12097	mtx_lock(&lun->lun_lock);
12098	mtx_unlock(&ctl_softc->ctl_lock);
12099	/*
12100	 * Run through the OOA queue and attempt to find the given I/O.
12101	 * The target port, initiator ID, tag type and tag number have to
12102	 * match the values that we got from the initiator.  If we have an
12103	 * untagged command to abort, simply abort the first untagged command
12104	 * we come to.  We only allow one untagged command at a time of course.
12105	 */
12106#if 0
12107	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12108#endif
12109	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12110	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12111#if 0
12112		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12113
12114		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12115			    lun->lun, xio->scsiio.tag_num,
12116			    xio->scsiio.tag_type,
12117			    (xio->io_hdr.blocked_links.tqe_prev
12118			    == NULL) ? "" : " BLOCKED",
12119			    (xio->io_hdr.flags &
12120			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12121			    (xio->io_hdr.flags &
12122			    CTL_FLAG_ABORT) ? " ABORT" : "",
12123			    (xio->io_hdr.flags &
12124			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12125		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12126		sbuf_finish(&sb);
12127		printf("%s\n", sbuf_data(&sb));
12128#endif
12129
12130		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12131		 && (xio->io_hdr.nexus.initid.id ==
12132		     io->io_hdr.nexus.initid.id)) {
12133			/*
12134			 * If the abort says that the task is untagged, the
12135			 * task in the queue must be untagged.  Otherwise,
12136			 * we just check to see whether the tag numbers
12137			 * match.  This is because the QLogic firmware
12138			 * doesn't pass back the tag type in an abort
12139			 * request.
12140			 */
12141#if 0
12142			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12143			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12144			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12145#endif
12146			/*
12147			 * XXX KDM we've got problems with FC, because it
12148			 * doesn't send down a tag type with aborts.  So we
12149			 * can only really go by the tag number...
12150			 * This may cause problems with parallel SCSI.
12151			 * Need to figure that out!!
12152			 */
12153			if (xio->scsiio.tag_num == io->taskio.tag_num) {
12154				xio->io_hdr.flags |= CTL_FLAG_ABORT;
12155				found = 1;
12156				if ((io->io_hdr.flags &
12157				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
12158				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12159					union ctl_ha_msg msg_info;
12160
12161					io->io_hdr.flags |=
12162					                CTL_FLAG_SENT_2OTHER_SC;
12163					msg_info.hdr.nexus = io->io_hdr.nexus;
12164					msg_info.task.task_action =
12165						CTL_TASK_ABORT_TASK;
12166					msg_info.task.tag_num =
12167						io->taskio.tag_num;
12168					msg_info.task.tag_type =
12169						io->taskio.tag_type;
12170					msg_info.hdr.msg_type =
12171						CTL_MSG_MANAGE_TASKS;
12172					msg_info.hdr.original_sc = NULL;
12173					msg_info.hdr.serializing_sc = NULL;
12174#if 0
12175					printf("Sent Abort to other side\n");
12176#endif
12177					if (CTL_HA_STATUS_SUCCESS !=
12178					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12179		    				(void *)&msg_info,
12180						sizeof(msg_info), 0)) {
12181					}
12182				}
12183#if 0
12184				printf("ctl_abort_task: found I/O to abort\n");
12185#endif
12186				break;
12187			}
12188		}
12189	}
12190	mtx_unlock(&lun->lun_lock);
12191
12192	if (found == 0) {
12193		/*
12194		 * This isn't really an error.  It's entirely possible for
12195		 * the abort and command completion to cross on the wire.
12196		 * This is more of an informative/diagnostic error.
12197		 */
12198#if 0
12199		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12200		       "%d:%d:%d:%d tag %d type %d\n",
12201		       io->io_hdr.nexus.initid.id,
12202		       io->io_hdr.nexus.targ_port,
12203		       io->io_hdr.nexus.targ_target.id,
12204		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12205		       io->taskio.tag_type);
12206#endif
12207	}
12208	return (0);
12209}
12210
12211static void
12212ctl_run_task(union ctl_io *io)
12213{
12214	struct ctl_softc *ctl_softc = control_softc;
12215	int retval = 1;
12216	const char *task_desc;
12217
12218	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12219
12220	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12221	    ("ctl_run_task: Unextected io_type %d\n",
12222	     io->io_hdr.io_type));
12223
12224	task_desc = ctl_scsi_task_string(&io->taskio);
12225	if (task_desc != NULL) {
12226#ifdef NEEDTOPORT
12227		csevent_log(CSC_CTL | CSC_SHELF_SW |
12228			    CTL_TASK_REPORT,
12229			    csevent_LogType_Trace,
12230			    csevent_Severity_Information,
12231			    csevent_AlertLevel_Green,
12232			    csevent_FRU_Firmware,
12233			    csevent_FRU_Unknown,
12234			    "CTL: received task: %s",task_desc);
12235#endif
12236	} else {
12237#ifdef NEEDTOPORT
12238		csevent_log(CSC_CTL | CSC_SHELF_SW |
12239			    CTL_TASK_REPORT,
12240			    csevent_LogType_Trace,
12241			    csevent_Severity_Information,
12242			    csevent_AlertLevel_Green,
12243			    csevent_FRU_Firmware,
12244			    csevent_FRU_Unknown,
12245			    "CTL: received unknown task "
12246			    "type: %d (%#x)",
12247			    io->taskio.task_action,
12248			    io->taskio.task_action);
12249#endif
12250	}
12251	switch (io->taskio.task_action) {
12252	case CTL_TASK_ABORT_TASK:
12253		retval = ctl_abort_task(io);
12254		break;
12255	case CTL_TASK_ABORT_TASK_SET:
12256	case CTL_TASK_CLEAR_TASK_SET:
12257		retval = ctl_abort_task_set(io);
12258		break;
12259	case CTL_TASK_CLEAR_ACA:
12260		break;
12261	case CTL_TASK_I_T_NEXUS_RESET:
12262		retval = ctl_i_t_nexus_reset(io);
12263		break;
12264	case CTL_TASK_LUN_RESET: {
12265		struct ctl_lun *lun;
12266		uint32_t targ_lun;
12267
12268		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12269		mtx_lock(&ctl_softc->ctl_lock);
12270		if ((targ_lun < CTL_MAX_LUNS)
12271		 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12272			lun = ctl_softc->ctl_luns[targ_lun];
12273		else {
12274			mtx_unlock(&ctl_softc->ctl_lock);
12275			retval = 1;
12276			break;
12277		}
12278
12279		if (!(io->io_hdr.flags &
12280		    CTL_FLAG_FROM_OTHER_SC)) {
12281			union ctl_ha_msg msg_info;
12282
12283			io->io_hdr.flags |=
12284				CTL_FLAG_SENT_2OTHER_SC;
12285			msg_info.hdr.msg_type =
12286				CTL_MSG_MANAGE_TASKS;
12287			msg_info.hdr.nexus = io->io_hdr.nexus;
12288			msg_info.task.task_action =
12289				CTL_TASK_LUN_RESET;
12290			msg_info.hdr.original_sc = NULL;
12291			msg_info.hdr.serializing_sc = NULL;
12292			if (CTL_HA_STATUS_SUCCESS !=
12293			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12294			    (void *)&msg_info,
12295			    sizeof(msg_info), 0)) {
12296			}
12297		}
12298
12299		retval = ctl_lun_reset(lun, io,
12300				       CTL_UA_LUN_RESET);
12301		mtx_unlock(&ctl_softc->ctl_lock);
12302		break;
12303	}
12304	case CTL_TASK_TARGET_RESET:
12305		retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12306		break;
12307	case CTL_TASK_BUS_RESET:
12308		retval = ctl_bus_reset(ctl_softc, io);
12309		break;
12310	case CTL_TASK_PORT_LOGIN:
12311		break;
12312	case CTL_TASK_PORT_LOGOUT:
12313		break;
12314	default:
12315		printf("ctl_run_task: got unknown task management event %d\n",
12316		       io->taskio.task_action);
12317		break;
12318	}
12319	if (retval == 0)
12320		io->io_hdr.status = CTL_SUCCESS;
12321	else
12322		io->io_hdr.status = CTL_ERROR;
12323	ctl_done(io);
12324}
12325
12326/*
12327 * For HA operation.  Handle commands that come in from the other
12328 * controller.
12329 */
12330static void
12331ctl_handle_isc(union ctl_io *io)
12332{
12333	int free_io;
12334	struct ctl_lun *lun;
12335	struct ctl_softc *ctl_softc;
12336	uint32_t targ_lun;
12337
12338	ctl_softc = control_softc;
12339
12340	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12341	lun = ctl_softc->ctl_luns[targ_lun];
12342
12343	switch (io->io_hdr.msg_type) {
12344	case CTL_MSG_SERIALIZE:
12345		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12346		break;
12347	case CTL_MSG_R2R: {
12348		const struct ctl_cmd_entry *entry;
12349
12350		/*
12351		 * This is only used in SER_ONLY mode.
12352		 */
12353		free_io = 0;
12354		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12355		mtx_lock(&lun->lun_lock);
12356		if (ctl_scsiio_lun_check(ctl_softc, lun,
12357		    entry, (struct ctl_scsiio *)io) != 0) {
12358			mtx_unlock(&lun->lun_lock);
12359			ctl_done(io);
12360			break;
12361		}
12362		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12363		mtx_unlock(&lun->lun_lock);
12364		ctl_enqueue_rtr(io);
12365		break;
12366	}
12367	case CTL_MSG_FINISH_IO:
12368		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12369			free_io = 0;
12370			ctl_done(io);
12371		} else {
12372			free_io = 1;
12373			mtx_lock(&lun->lun_lock);
12374			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12375				     ooa_links);
12376			ctl_check_blocked(lun);
12377			mtx_unlock(&lun->lun_lock);
12378		}
12379		break;
12380	case CTL_MSG_PERS_ACTION:
12381		ctl_hndl_per_res_out_on_other_sc(
12382			(union ctl_ha_msg *)&io->presio.pr_msg);
12383		free_io = 1;
12384		break;
12385	case CTL_MSG_BAD_JUJU:
12386		free_io = 0;
12387		ctl_done(io);
12388		break;
12389	case CTL_MSG_DATAMOVE:
12390		/* Only used in XFER mode */
12391		free_io = 0;
12392		ctl_datamove_remote(io);
12393		break;
12394	case CTL_MSG_DATAMOVE_DONE:
12395		/* Only used in XFER mode */
12396		free_io = 0;
12397		io->scsiio.be_move_done(io);
12398		break;
12399	default:
12400		free_io = 1;
12401		printf("%s: Invalid message type %d\n",
12402		       __func__, io->io_hdr.msg_type);
12403		break;
12404	}
12405	if (free_io)
12406		ctl_free_io(io);
12407
12408}
12409
12410
12411/*
12412 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12413 * there is no match.
12414 */
12415static ctl_lun_error_pattern
12416ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12417{
12418	const struct ctl_cmd_entry *entry;
12419	ctl_lun_error_pattern filtered_pattern, pattern;
12420
12421	pattern = desc->error_pattern;
12422
12423	/*
12424	 * XXX KDM we need more data passed into this function to match a
12425	 * custom pattern, and we actually need to implement custom pattern
12426	 * matching.
12427	 */
12428	if (pattern & CTL_LUN_PAT_CMD)
12429		return (CTL_LUN_PAT_CMD);
12430
12431	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12432		return (CTL_LUN_PAT_ANY);
12433
12434	entry = ctl_get_cmd_entry(ctsio, NULL);
12435
12436	filtered_pattern = entry->pattern & pattern;
12437
12438	/*
12439	 * If the user requested specific flags in the pattern (e.g.
12440	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12441	 * flags.
12442	 *
12443	 * If the user did not specify any flags, it doesn't matter whether
12444	 * or not the command supports the flags.
12445	 */
12446	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12447	     (pattern & ~CTL_LUN_PAT_MASK))
12448		return (CTL_LUN_PAT_NONE);
12449
12450	/*
12451	 * If the user asked for a range check, see if the requested LBA
12452	 * range overlaps with this command's LBA range.
12453	 */
12454	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12455		uint64_t lba1;
12456		uint64_t len1;
12457		ctl_action action;
12458		int retval;
12459
12460		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12461		if (retval != 0)
12462			return (CTL_LUN_PAT_NONE);
12463
12464		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12465					      desc->lba_range.len);
12466		/*
12467		 * A "pass" means that the LBA ranges don't overlap, so
12468		 * this doesn't match the user's range criteria.
12469		 */
12470		if (action == CTL_ACTION_PASS)
12471			return (CTL_LUN_PAT_NONE);
12472	}
12473
12474	return (filtered_pattern);
12475}
12476
12477static void
12478ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12479{
12480	struct ctl_error_desc *desc, *desc2;
12481
12482	mtx_assert(&lun->lun_lock, MA_OWNED);
12483
12484	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12485		ctl_lun_error_pattern pattern;
12486		/*
12487		 * Check to see whether this particular command matches
12488		 * the pattern in the descriptor.
12489		 */
12490		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12491		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12492			continue;
12493
12494		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12495		case CTL_LUN_INJ_ABORTED:
12496			ctl_set_aborted(&io->scsiio);
12497			break;
12498		case CTL_LUN_INJ_MEDIUM_ERR:
12499			ctl_set_medium_error(&io->scsiio);
12500			break;
12501		case CTL_LUN_INJ_UA:
12502			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12503			 * OCCURRED */
12504			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12505			break;
12506		case CTL_LUN_INJ_CUSTOM:
12507			/*
12508			 * We're assuming the user knows what he is doing.
12509			 * Just copy the sense information without doing
12510			 * checks.
12511			 */
12512			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12513			      ctl_min(sizeof(desc->custom_sense),
12514				      sizeof(io->scsiio.sense_data)));
12515			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12516			io->scsiio.sense_len = SSD_FULL_SIZE;
12517			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12518			break;
12519		case CTL_LUN_INJ_NONE:
12520		default:
12521			/*
12522			 * If this is an error injection type we don't know
12523			 * about, clear the continuous flag (if it is set)
12524			 * so it will get deleted below.
12525			 */
12526			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12527			break;
12528		}
12529		/*
12530		 * By default, each error injection action is a one-shot
12531		 */
12532		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12533			continue;
12534
12535		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12536
12537		free(desc, M_CTL);
12538	}
12539}
12540
12541#ifdef CTL_IO_DELAY
12542static void
12543ctl_datamove_timer_wakeup(void *arg)
12544{
12545	union ctl_io *io;
12546
12547	io = (union ctl_io *)arg;
12548
12549	ctl_datamove(io);
12550}
12551#endif /* CTL_IO_DELAY */
12552
12553void
12554ctl_datamove(union ctl_io *io)
12555{
12556	void (*fe_datamove)(union ctl_io *io);
12557
12558	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12559
12560	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12561
12562#ifdef CTL_TIME_IO
12563	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12564		char str[256];
12565		char path_str[64];
12566		struct sbuf sb;
12567
12568		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12569		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12570
12571		sbuf_cat(&sb, path_str);
12572		switch (io->io_hdr.io_type) {
12573		case CTL_IO_SCSI:
12574			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12575			sbuf_printf(&sb, "\n");
12576			sbuf_cat(&sb, path_str);
12577			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12578				    io->scsiio.tag_num, io->scsiio.tag_type);
12579			break;
12580		case CTL_IO_TASK:
12581			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12582				    "Tag Type: %d\n", io->taskio.task_action,
12583				    io->taskio.tag_num, io->taskio.tag_type);
12584			break;
12585		default:
12586			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12587			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12588			break;
12589		}
12590		sbuf_cat(&sb, path_str);
12591		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12592			    (intmax_t)time_uptime - io->io_hdr.start_time);
12593		sbuf_finish(&sb);
12594		printf("%s", sbuf_data(&sb));
12595	}
12596#endif /* CTL_TIME_IO */
12597
12598#ifdef CTL_IO_DELAY
12599	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12600		struct ctl_lun *lun;
12601
12602		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12603
12604		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12605	} else {
12606		struct ctl_lun *lun;
12607
12608		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12609		if ((lun != NULL)
12610		 && (lun->delay_info.datamove_delay > 0)) {
12611			struct callout *callout;
12612
12613			callout = (struct callout *)&io->io_hdr.timer_bytes;
12614			callout_init(callout, /*mpsafe*/ 1);
12615			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12616			callout_reset(callout,
12617				      lun->delay_info.datamove_delay * hz,
12618				      ctl_datamove_timer_wakeup, io);
12619			if (lun->delay_info.datamove_type ==
12620			    CTL_DELAY_TYPE_ONESHOT)
12621				lun->delay_info.datamove_delay = 0;
12622			return;
12623		}
12624	}
12625#endif
12626
12627	/*
12628	 * This command has been aborted.  Set the port status, so we fail
12629	 * the data move.
12630	 */
12631	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12632		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12633		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12634		       io->io_hdr.nexus.targ_port,
12635		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12636		       io->io_hdr.nexus.targ_lun);
12637		io->io_hdr.port_status = 31337;
12638		/*
12639		 * Note that the backend, in this case, will get the
12640		 * callback in its context.  In other cases it may get
12641		 * called in the frontend's interrupt thread context.
12642		 */
12643		io->scsiio.be_move_done(io);
12644		return;
12645	}
12646
12647	/* Don't confuse frontend with zero length data move. */
12648	if (io->scsiio.kern_data_len == 0) {
12649		io->scsiio.be_move_done(io);
12650		return;
12651	}
12652
12653	/*
12654	 * If we're in XFER mode and this I/O is from the other shelf
12655	 * controller, we need to send the DMA to the other side to
12656	 * actually transfer the data to/from the host.  In serialize only
12657	 * mode the transfer happens below CTL and ctl_datamove() is only
12658	 * called on the machine that originally received the I/O.
12659	 */
12660	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12661	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12662		union ctl_ha_msg msg;
12663		uint32_t sg_entries_sent;
12664		int do_sg_copy;
12665		int i;
12666
12667		memset(&msg, 0, sizeof(msg));
12668		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12669		msg.hdr.original_sc = io->io_hdr.original_sc;
12670		msg.hdr.serializing_sc = io;
12671		msg.hdr.nexus = io->io_hdr.nexus;
12672		msg.dt.flags = io->io_hdr.flags;
12673		/*
12674		 * We convert everything into a S/G list here.  We can't
12675		 * pass by reference, only by value between controllers.
12676		 * So we can't pass a pointer to the S/G list, only as many
12677		 * S/G entries as we can fit in here.  If it's possible for
12678		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12679		 * then we need to break this up into multiple transfers.
12680		 */
12681		if (io->scsiio.kern_sg_entries == 0) {
12682			msg.dt.kern_sg_entries = 1;
12683			/*
12684			 * If this is in cached memory, flush the cache
12685			 * before we send the DMA request to the other
12686			 * controller.  We want to do this in either the
12687			 * read or the write case.  The read case is
12688			 * straightforward.  In the write case, we want to
12689			 * make sure nothing is in the local cache that
12690			 * could overwrite the DMAed data.
12691			 */
12692			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12693				/*
12694				 * XXX KDM use bus_dmamap_sync() here.
12695				 */
12696			}
12697
12698			/*
12699			 * Convert to a physical address if this is a
12700			 * virtual address.
12701			 */
12702			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12703				msg.dt.sg_list[0].addr =
12704					io->scsiio.kern_data_ptr;
12705			} else {
12706				/*
12707				 * XXX KDM use busdma here!
12708				 */
12709#if 0
12710				msg.dt.sg_list[0].addr = (void *)
12711					vtophys(io->scsiio.kern_data_ptr);
12712#endif
12713			}
12714
12715			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12716			do_sg_copy = 0;
12717		} else {
12718			struct ctl_sg_entry *sgl;
12719
12720			do_sg_copy = 1;
12721			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12722			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12723			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12724				/*
12725				 * XXX KDM use bus_dmamap_sync() here.
12726				 */
12727			}
12728		}
12729
12730		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12731		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12732		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12733		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12734		msg.dt.sg_sequence = 0;
12735
12736		/*
12737		 * Loop until we've sent all of the S/G entries.  On the
12738		 * other end, we'll recompose these S/G entries into one
12739		 * contiguous list before passing it to the
12740		 */
12741		for (sg_entries_sent = 0; sg_entries_sent <
12742		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12743			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12744				sizeof(msg.dt.sg_list[0])),
12745				msg.dt.kern_sg_entries - sg_entries_sent);
12746
12747			if (do_sg_copy != 0) {
12748				struct ctl_sg_entry *sgl;
12749				int j;
12750
12751				sgl = (struct ctl_sg_entry *)
12752					io->scsiio.kern_data_ptr;
12753				/*
12754				 * If this is in cached memory, flush the cache
12755				 * before we send the DMA request to the other
12756				 * controller.  We want to do this in either
12757				 * the * read or the write case.  The read
12758				 * case is straightforward.  In the write
12759				 * case, we want to make sure nothing is
12760				 * in the local cache that could overwrite
12761				 * the DMAed data.
12762				 */
12763
12764				for (i = sg_entries_sent, j = 0;
12765				     i < msg.dt.cur_sg_entries; i++, j++) {
12766					if ((io->io_hdr.flags &
12767					     CTL_FLAG_NO_DATASYNC) == 0) {
12768						/*
12769						 * XXX KDM use bus_dmamap_sync()
12770						 */
12771					}
12772					if ((io->io_hdr.flags &
12773					     CTL_FLAG_BUS_ADDR) == 0) {
12774						/*
12775						 * XXX KDM use busdma.
12776						 */
12777#if 0
12778						msg.dt.sg_list[j].addr =(void *)
12779						       vtophys(sgl[i].addr);
12780#endif
12781					} else {
12782						msg.dt.sg_list[j].addr =
12783							sgl[i].addr;
12784					}
12785					msg.dt.sg_list[j].len = sgl[i].len;
12786				}
12787			}
12788
12789			sg_entries_sent += msg.dt.cur_sg_entries;
12790			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12791				msg.dt.sg_last = 1;
12792			else
12793				msg.dt.sg_last = 0;
12794
12795			/*
12796			 * XXX KDM drop and reacquire the lock here?
12797			 */
12798			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12799			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12800				/*
12801				 * XXX do something here.
12802				 */
12803			}
12804
12805			msg.dt.sent_sg_entries = sg_entries_sent;
12806		}
12807		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12808		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12809			ctl_failover_io(io, /*have_lock*/ 0);
12810
12811	} else {
12812
12813		/*
12814		 * Lookup the fe_datamove() function for this particular
12815		 * front end.
12816		 */
12817		fe_datamove =
12818		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12819
12820		fe_datamove(io);
12821	}
12822}
12823
12824static void
12825ctl_send_datamove_done(union ctl_io *io, int have_lock)
12826{
12827	union ctl_ha_msg msg;
12828	int isc_status;
12829
12830	memset(&msg, 0, sizeof(msg));
12831
12832	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12833	msg.hdr.original_sc = io;
12834	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12835	msg.hdr.nexus = io->io_hdr.nexus;
12836	msg.hdr.status = io->io_hdr.status;
12837	msg.scsi.tag_num = io->scsiio.tag_num;
12838	msg.scsi.tag_type = io->scsiio.tag_type;
12839	msg.scsi.scsi_status = io->scsiio.scsi_status;
12840	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12841	       sizeof(io->scsiio.sense_data));
12842	msg.scsi.sense_len = io->scsiio.sense_len;
12843	msg.scsi.sense_residual = io->scsiio.sense_residual;
12844	msg.scsi.fetd_status = io->io_hdr.port_status;
12845	msg.scsi.residual = io->scsiio.residual;
12846	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12847
12848	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12849		ctl_failover_io(io, /*have_lock*/ have_lock);
12850		return;
12851	}
12852
12853	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12854	if (isc_status > CTL_HA_STATUS_SUCCESS) {
12855		/* XXX do something if this fails */
12856	}
12857
12858}
12859
12860/*
12861 * The DMA to the remote side is done, now we need to tell the other side
12862 * we're done so it can continue with its data movement.
12863 */
12864static void
12865ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12866{
12867	union ctl_io *io;
12868
12869	io = rq->context;
12870
12871	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12872		printf("%s: ISC DMA write failed with error %d", __func__,
12873		       rq->ret);
12874		ctl_set_internal_failure(&io->scsiio,
12875					 /*sks_valid*/ 1,
12876					 /*retry_count*/ rq->ret);
12877	}
12878
12879	ctl_dt_req_free(rq);
12880
12881	/*
12882	 * In this case, we had to malloc the memory locally.  Free it.
12883	 */
12884	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12885		int i;
12886		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12887			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12888	}
12889	/*
12890	 * The data is in local and remote memory, so now we need to send
12891	 * status (good or back) back to the other side.
12892	 */
12893	ctl_send_datamove_done(io, /*have_lock*/ 0);
12894}
12895
12896/*
12897 * We've moved the data from the host/controller into local memory.  Now we
12898 * need to push it over to the remote controller's memory.
12899 */
12900static int
12901ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12902{
12903	int retval;
12904
12905	retval = 0;
12906
12907	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12908					  ctl_datamove_remote_write_cb);
12909
12910	return (retval);
12911}
12912
12913static void
12914ctl_datamove_remote_write(union ctl_io *io)
12915{
12916	int retval;
12917	void (*fe_datamove)(union ctl_io *io);
12918
12919	/*
12920	 * - Get the data from the host/HBA into local memory.
12921	 * - DMA memory from the local controller to the remote controller.
12922	 * - Send status back to the remote controller.
12923	 */
12924
12925	retval = ctl_datamove_remote_sgl_setup(io);
12926	if (retval != 0)
12927		return;
12928
12929	/* Switch the pointer over so the FETD knows what to do */
12930	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12931
12932	/*
12933	 * Use a custom move done callback, since we need to send completion
12934	 * back to the other controller, not to the backend on this side.
12935	 */
12936	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12937
12938	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12939
12940	fe_datamove(io);
12941
12942	return;
12943
12944}
12945
12946static int
12947ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12948{
12949#if 0
12950	char str[256];
12951	char path_str[64];
12952	struct sbuf sb;
12953#endif
12954
12955	/*
12956	 * In this case, we had to malloc the memory locally.  Free it.
12957	 */
12958	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12959		int i;
12960		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12961			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12962	}
12963
12964#if 0
12965	scsi_path_string(io, path_str, sizeof(path_str));
12966	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12967	sbuf_cat(&sb, path_str);
12968	scsi_command_string(&io->scsiio, NULL, &sb);
12969	sbuf_printf(&sb, "\n");
12970	sbuf_cat(&sb, path_str);
12971	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12972		    io->scsiio.tag_num, io->scsiio.tag_type);
12973	sbuf_cat(&sb, path_str);
12974	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12975		    io->io_hdr.flags, io->io_hdr.status);
12976	sbuf_finish(&sb);
12977	printk("%s", sbuf_data(&sb));
12978#endif
12979
12980
12981	/*
12982	 * The read is done, now we need to send status (good or bad) back
12983	 * to the other side.
12984	 */
12985	ctl_send_datamove_done(io, /*have_lock*/ 0);
12986
12987	return (0);
12988}
12989
12990static void
12991ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12992{
12993	union ctl_io *io;
12994	void (*fe_datamove)(union ctl_io *io);
12995
12996	io = rq->context;
12997
12998	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12999		printf("%s: ISC DMA read failed with error %d", __func__,
13000		       rq->ret);
13001		ctl_set_internal_failure(&io->scsiio,
13002					 /*sks_valid*/ 1,
13003					 /*retry_count*/ rq->ret);
13004	}
13005
13006	ctl_dt_req_free(rq);
13007
13008	/* Switch the pointer over so the FETD knows what to do */
13009	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13010
13011	/*
13012	 * Use a custom move done callback, since we need to send completion
13013	 * back to the other controller, not to the backend on this side.
13014	 */
13015	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
13016
13017	/* XXX KDM add checks like the ones in ctl_datamove? */
13018
13019	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13020
13021	fe_datamove(io);
13022}
13023
13024static int
13025ctl_datamove_remote_sgl_setup(union ctl_io *io)
13026{
13027	struct ctl_sg_entry *local_sglist, *remote_sglist;
13028	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13029	struct ctl_softc *softc;
13030	int retval;
13031	int i;
13032
13033	retval = 0;
13034	softc = control_softc;
13035
13036	local_sglist = io->io_hdr.local_sglist;
13037	local_dma_sglist = io->io_hdr.local_dma_sglist;
13038	remote_sglist = io->io_hdr.remote_sglist;
13039	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13040
13041	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13042		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13043			local_sglist[i].len = remote_sglist[i].len;
13044
13045			/*
13046			 * XXX Detect the situation where the RS-level I/O
13047			 * redirector on the other side has already read the
13048			 * data off of the AOR RS on this side, and
13049			 * transferred it to remote (mirror) memory on the
13050			 * other side.  Since we already have the data in
13051			 * memory here, we just need to use it.
13052			 *
13053			 * XXX KDM this can probably be removed once we
13054			 * get the cache device code in and take the
13055			 * current AOR implementation out.
13056			 */
13057#ifdef NEEDTOPORT
13058			if ((remote_sglist[i].addr >=
13059			     (void *)vtophys(softc->mirr->addr))
13060			 && (remote_sglist[i].addr <
13061			     ((void *)vtophys(softc->mirr->addr) +
13062			     CacheMirrorOffset))) {
13063				local_sglist[i].addr = remote_sglist[i].addr -
13064					CacheMirrorOffset;
13065				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13066				     CTL_FLAG_DATA_IN)
13067					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13068			} else {
13069				local_sglist[i].addr = remote_sglist[i].addr +
13070					CacheMirrorOffset;
13071			}
13072#endif
13073#if 0
13074			printf("%s: local %p, remote %p, len %d\n",
13075			       __func__, local_sglist[i].addr,
13076			       remote_sglist[i].addr, local_sglist[i].len);
13077#endif
13078		}
13079	} else {
13080		uint32_t len_to_go;
13081
13082		/*
13083		 * In this case, we don't have automatically allocated
13084		 * memory for this I/O on this controller.  This typically
13085		 * happens with internal CTL I/O -- e.g. inquiry, mode
13086		 * sense, etc.  Anything coming from RAIDCore will have
13087		 * a mirror area available.
13088		 */
13089		len_to_go = io->scsiio.kern_data_len;
13090
13091		/*
13092		 * Clear the no datasync flag, we have to use malloced
13093		 * buffers.
13094		 */
13095		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13096
13097		/*
13098		 * The difficult thing here is that the size of the various
13099		 * S/G segments may be different than the size from the
13100		 * remote controller.  That'll make it harder when DMAing
13101		 * the data back to the other side.
13102		 */
13103		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13104		     sizeof(io->io_hdr.remote_sglist[0])) &&
13105		     (len_to_go > 0); i++) {
13106			local_sglist[i].len = ctl_min(len_to_go, 131072);
13107			CTL_SIZE_8B(local_dma_sglist[i].len,
13108				    local_sglist[i].len);
13109			local_sglist[i].addr =
13110				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13111
13112			local_dma_sglist[i].addr = local_sglist[i].addr;
13113
13114			if (local_sglist[i].addr == NULL) {
13115				int j;
13116
13117				printf("malloc failed for %zd bytes!",
13118				       local_dma_sglist[i].len);
13119				for (j = 0; j < i; j++) {
13120					free(local_sglist[j].addr, M_CTL);
13121				}
13122				ctl_set_internal_failure(&io->scsiio,
13123							 /*sks_valid*/ 1,
13124							 /*retry_count*/ 4857);
13125				retval = 1;
13126				goto bailout_error;
13127
13128			}
13129			/* XXX KDM do we need a sync here? */
13130
13131			len_to_go -= local_sglist[i].len;
13132		}
13133		/*
13134		 * Reset the number of S/G entries accordingly.  The
13135		 * original number of S/G entries is available in
13136		 * rem_sg_entries.
13137		 */
13138		io->scsiio.kern_sg_entries = i;
13139
13140#if 0
13141		printf("%s: kern_sg_entries = %d\n", __func__,
13142		       io->scsiio.kern_sg_entries);
13143		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13144			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13145			       local_sglist[i].addr, local_sglist[i].len,
13146			       local_dma_sglist[i].len);
13147#endif
13148	}
13149
13150
13151	return (retval);
13152
13153bailout_error:
13154
13155	ctl_send_datamove_done(io, /*have_lock*/ 0);
13156
13157	return (retval);
13158}
13159
13160static int
13161ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13162			 ctl_ha_dt_cb callback)
13163{
13164	struct ctl_ha_dt_req *rq;
13165	struct ctl_sg_entry *remote_sglist, *local_sglist;
13166	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13167	uint32_t local_used, remote_used, total_used;
13168	int retval;
13169	int i, j;
13170
13171	retval = 0;
13172
13173	rq = ctl_dt_req_alloc();
13174
13175	/*
13176	 * If we failed to allocate the request, and if the DMA didn't fail
13177	 * anyway, set busy status.  This is just a resource allocation
13178	 * failure.
13179	 */
13180	if ((rq == NULL)
13181	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13182		ctl_set_busy(&io->scsiio);
13183
13184	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13185
13186		if (rq != NULL)
13187			ctl_dt_req_free(rq);
13188
13189		/*
13190		 * The data move failed.  We need to return status back
13191		 * to the other controller.  No point in trying to DMA
13192		 * data to the remote controller.
13193		 */
13194
13195		ctl_send_datamove_done(io, /*have_lock*/ 0);
13196
13197		retval = 1;
13198
13199		goto bailout;
13200	}
13201
13202	local_sglist = io->io_hdr.local_sglist;
13203	local_dma_sglist = io->io_hdr.local_dma_sglist;
13204	remote_sglist = io->io_hdr.remote_sglist;
13205	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13206	local_used = 0;
13207	remote_used = 0;
13208	total_used = 0;
13209
13210	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13211		rq->ret = CTL_HA_STATUS_SUCCESS;
13212		rq->context = io;
13213		callback(rq);
13214		goto bailout;
13215	}
13216
13217	/*
13218	 * Pull/push the data over the wire from/to the other controller.
13219	 * This takes into account the possibility that the local and
13220	 * remote sglists may not be identical in terms of the size of
13221	 * the elements and the number of elements.
13222	 *
13223	 * One fundamental assumption here is that the length allocated for
13224	 * both the local and remote sglists is identical.  Otherwise, we've
13225	 * essentially got a coding error of some sort.
13226	 */
13227	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13228		int isc_ret;
13229		uint32_t cur_len, dma_length;
13230		uint8_t *tmp_ptr;
13231
13232		rq->id = CTL_HA_DATA_CTL;
13233		rq->command = command;
13234		rq->context = io;
13235
13236		/*
13237		 * Both pointers should be aligned.  But it is possible
13238		 * that the allocation length is not.  They should both
13239		 * also have enough slack left over at the end, though,
13240		 * to round up to the next 8 byte boundary.
13241		 */
13242		cur_len = ctl_min(local_sglist[i].len - local_used,
13243				  remote_sglist[j].len - remote_used);
13244
13245		/*
13246		 * In this case, we have a size issue and need to decrease
13247		 * the size, except in the case where we actually have less
13248		 * than 8 bytes left.  In that case, we need to increase
13249		 * the DMA length to get the last bit.
13250		 */
13251		if ((cur_len & 0x7) != 0) {
13252			if (cur_len > 0x7) {
13253				cur_len = cur_len - (cur_len & 0x7);
13254				dma_length = cur_len;
13255			} else {
13256				CTL_SIZE_8B(dma_length, cur_len);
13257			}
13258
13259		} else
13260			dma_length = cur_len;
13261
13262		/*
13263		 * If we had to allocate memory for this I/O, instead of using
13264		 * the non-cached mirror memory, we'll need to flush the cache
13265		 * before trying to DMA to the other controller.
13266		 *
13267		 * We could end up doing this multiple times for the same
13268		 * segment if we have a larger local segment than remote
13269		 * segment.  That shouldn't be an issue.
13270		 */
13271		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13272			/*
13273			 * XXX KDM use bus_dmamap_sync() here.
13274			 */
13275		}
13276
13277		rq->size = dma_length;
13278
13279		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13280		tmp_ptr += local_used;
13281
13282		/* Use physical addresses when talking to ISC hardware */
13283		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13284			/* XXX KDM use busdma */
13285#if 0
13286			rq->local = vtophys(tmp_ptr);
13287#endif
13288		} else
13289			rq->local = tmp_ptr;
13290
13291		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13292		tmp_ptr += remote_used;
13293		rq->remote = tmp_ptr;
13294
13295		rq->callback = NULL;
13296
13297		local_used += cur_len;
13298		if (local_used >= local_sglist[i].len) {
13299			i++;
13300			local_used = 0;
13301		}
13302
13303		remote_used += cur_len;
13304		if (remote_used >= remote_sglist[j].len) {
13305			j++;
13306			remote_used = 0;
13307		}
13308		total_used += cur_len;
13309
13310		if (total_used >= io->scsiio.kern_data_len)
13311			rq->callback = callback;
13312
13313		if ((rq->size & 0x7) != 0) {
13314			printf("%s: warning: size %d is not on 8b boundary\n",
13315			       __func__, rq->size);
13316		}
13317		if (((uintptr_t)rq->local & 0x7) != 0) {
13318			printf("%s: warning: local %p not on 8b boundary\n",
13319			       __func__, rq->local);
13320		}
13321		if (((uintptr_t)rq->remote & 0x7) != 0) {
13322			printf("%s: warning: remote %p not on 8b boundary\n",
13323			       __func__, rq->local);
13324		}
13325#if 0
13326		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13327		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13328		       rq->local, rq->remote, rq->size);
13329#endif
13330
13331		isc_ret = ctl_dt_single(rq);
13332		if (isc_ret == CTL_HA_STATUS_WAIT)
13333			continue;
13334
13335		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13336			rq->ret = CTL_HA_STATUS_SUCCESS;
13337		} else {
13338			rq->ret = isc_ret;
13339		}
13340		callback(rq);
13341		goto bailout;
13342	}
13343
13344bailout:
13345	return (retval);
13346
13347}
13348
13349static void
13350ctl_datamove_remote_read(union ctl_io *io)
13351{
13352	int retval;
13353	int i;
13354
13355	/*
13356	 * This will send an error to the other controller in the case of a
13357	 * failure.
13358	 */
13359	retval = ctl_datamove_remote_sgl_setup(io);
13360	if (retval != 0)
13361		return;
13362
13363	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13364					  ctl_datamove_remote_read_cb);
13365	if ((retval != 0)
13366	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13367		/*
13368		 * Make sure we free memory if there was an error..  The
13369		 * ctl_datamove_remote_xfer() function will send the
13370		 * datamove done message, or call the callback with an
13371		 * error if there is a problem.
13372		 */
13373		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13374			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13375	}
13376
13377	return;
13378}
13379
13380/*
13381 * Process a datamove request from the other controller.  This is used for
13382 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13383 * first.  Once that is complete, the data gets DMAed into the remote
13384 * controller's memory.  For reads, we DMA from the remote controller's
13385 * memory into our memory first, and then move it out to the FETD.
13386 */
13387static void
13388ctl_datamove_remote(union ctl_io *io)
13389{
13390	struct ctl_softc *softc;
13391
13392	softc = control_softc;
13393
13394	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13395
13396	/*
13397	 * Note that we look for an aborted I/O here, but don't do some of
13398	 * the other checks that ctl_datamove() normally does.
13399	 * We don't need to run the datamove delay code, since that should
13400	 * have been done if need be on the other controller.
13401	 */
13402	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13403		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13404		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13405		       io->io_hdr.nexus.targ_port,
13406		       io->io_hdr.nexus.targ_target.id,
13407		       io->io_hdr.nexus.targ_lun);
13408		io->io_hdr.port_status = 31338;
13409		ctl_send_datamove_done(io, /*have_lock*/ 0);
13410		return;
13411	}
13412
13413	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13414		ctl_datamove_remote_write(io);
13415	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13416		ctl_datamove_remote_read(io);
13417	} else {
13418		union ctl_ha_msg msg;
13419		struct scsi_sense_data *sense;
13420		uint8_t sks[3];
13421		int retry_count;
13422
13423		memset(&msg, 0, sizeof(msg));
13424
13425		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13426		msg.hdr.status = CTL_SCSI_ERROR;
13427		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13428
13429		retry_count = 4243;
13430
13431		sense = &msg.scsi.sense_data;
13432		sks[0] = SSD_SCS_VALID;
13433		sks[1] = (retry_count >> 8) & 0xff;
13434		sks[2] = retry_count & 0xff;
13435
13436		/* "Internal target failure" */
13437		scsi_set_sense_data(sense,
13438				    /*sense_format*/ SSD_TYPE_NONE,
13439				    /*current_error*/ 1,
13440				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13441				    /*asc*/ 0x44,
13442				    /*ascq*/ 0x00,
13443				    /*type*/ SSD_ELEM_SKS,
13444				    /*size*/ sizeof(sks),
13445				    /*data*/ sks,
13446				    SSD_ELEM_NONE);
13447
13448		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13449		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13450			ctl_failover_io(io, /*have_lock*/ 1);
13451			return;
13452		}
13453
13454		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13455		    CTL_HA_STATUS_SUCCESS) {
13456			/* XXX KDM what to do if this fails? */
13457		}
13458		return;
13459	}
13460
13461}
13462
13463static int
13464ctl_process_done(union ctl_io *io)
13465{
13466	struct ctl_lun *lun;
13467	struct ctl_softc *ctl_softc = control_softc;
13468	void (*fe_done)(union ctl_io *io);
13469	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13470
13471	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13472
13473	fe_done =
13474	    control_softc->ctl_ports[targ_port]->fe_done;
13475
13476#ifdef CTL_TIME_IO
13477	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13478		char str[256];
13479		char path_str[64];
13480		struct sbuf sb;
13481
13482		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13483		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13484
13485		sbuf_cat(&sb, path_str);
13486		switch (io->io_hdr.io_type) {
13487		case CTL_IO_SCSI:
13488			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13489			sbuf_printf(&sb, "\n");
13490			sbuf_cat(&sb, path_str);
13491			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13492				    io->scsiio.tag_num, io->scsiio.tag_type);
13493			break;
13494		case CTL_IO_TASK:
13495			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13496				    "Tag Type: %d\n", io->taskio.task_action,
13497				    io->taskio.tag_num, io->taskio.tag_type);
13498			break;
13499		default:
13500			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13501			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13502			break;
13503		}
13504		sbuf_cat(&sb, path_str);
13505		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13506			    (intmax_t)time_uptime - io->io_hdr.start_time);
13507		sbuf_finish(&sb);
13508		printf("%s", sbuf_data(&sb));
13509	}
13510#endif /* CTL_TIME_IO */
13511
13512	switch (io->io_hdr.io_type) {
13513	case CTL_IO_SCSI:
13514		break;
13515	case CTL_IO_TASK:
13516		if (bootverbose || (ctl_debug & CTL_DEBUG_INFO))
13517			ctl_io_error_print(io, NULL);
13518		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13519			ctl_free_io(io);
13520		else
13521			fe_done(io);
13522		return (CTL_RETVAL_COMPLETE);
13523	default:
13524		panic("ctl_process_done: invalid io type %d\n",
13525		      io->io_hdr.io_type);
13526		break; /* NOTREACHED */
13527	}
13528
13529	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13530	if (lun == NULL) {
13531		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13532				 io->io_hdr.nexus.targ_mapped_lun));
13533		goto bailout;
13534	}
13535
13536	mtx_lock(&lun->lun_lock);
13537
13538	/*
13539	 * Check to see if we have any errors to inject here.  We only
13540	 * inject errors for commands that don't already have errors set.
13541	 */
13542	if ((STAILQ_FIRST(&lun->error_list) != NULL)
13543	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
13544		ctl_inject_error(lun, io);
13545
13546	/*
13547	 * XXX KDM how do we treat commands that aren't completed
13548	 * successfully?
13549	 *
13550	 * XXX KDM should we also track I/O latency?
13551	 */
13552	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13553	    io->io_hdr.io_type == CTL_IO_SCSI) {
13554#ifdef CTL_TIME_IO
13555		struct bintime cur_bt;
13556#endif
13557		int type;
13558
13559		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13560		    CTL_FLAG_DATA_IN)
13561			type = CTL_STATS_READ;
13562		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13563		    CTL_FLAG_DATA_OUT)
13564			type = CTL_STATS_WRITE;
13565		else
13566			type = CTL_STATS_NO_IO;
13567
13568		lun->stats.ports[targ_port].bytes[type] +=
13569		    io->scsiio.kern_total_len;
13570		lun->stats.ports[targ_port].operations[type]++;
13571#ifdef CTL_TIME_IO
13572		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13573		   &io->io_hdr.dma_bt);
13574		lun->stats.ports[targ_port].num_dmas[type] +=
13575		    io->io_hdr.num_dmas;
13576		getbintime(&cur_bt);
13577		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13578		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13579#endif
13580	}
13581
13582	/*
13583	 * Remove this from the OOA queue.
13584	 */
13585	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13586
13587	/*
13588	 * Run through the blocked queue on this LUN and see if anything
13589	 * has become unblocked, now that this transaction is done.
13590	 */
13591	ctl_check_blocked(lun);
13592
13593	/*
13594	 * If the LUN has been invalidated, free it if there is nothing
13595	 * left on its OOA queue.
13596	 */
13597	if ((lun->flags & CTL_LUN_INVALID)
13598	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13599		mtx_unlock(&lun->lun_lock);
13600		mtx_lock(&ctl_softc->ctl_lock);
13601		ctl_free_lun(lun);
13602		mtx_unlock(&ctl_softc->ctl_lock);
13603	} else
13604		mtx_unlock(&lun->lun_lock);
13605
13606bailout:
13607
13608	/*
13609	 * If this command has been aborted, make sure we set the status
13610	 * properly.  The FETD is responsible for freeing the I/O and doing
13611	 * whatever it needs to do to clean up its state.
13612	 */
13613	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13614		ctl_set_task_aborted(&io->scsiio);
13615
13616	/*
13617	 * If enabled, print command error status.
13618	 * We don't print UAs unless debugging was enabled explicitly.
13619	 */
13620	do {
13621		if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)
13622			break;
13623		if (!bootverbose && (ctl_debug & CTL_DEBUG_INFO) == 0)
13624			break;
13625		if ((ctl_debug & CTL_DEBUG_INFO) == 0 &&
13626		    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR) &&
13627		     (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13628			int error_code, sense_key, asc, ascq;
13629
13630			scsi_extract_sense_len(&io->scsiio.sense_data,
13631			    io->scsiio.sense_len, &error_code, &sense_key,
13632			    &asc, &ascq, /*show_errors*/ 0);
13633			if (sense_key == SSD_KEY_UNIT_ATTENTION)
13634				break;
13635		}
13636
13637		ctl_io_error_print(io, NULL);
13638	} while (0);
13639
13640	/*
13641	 * Tell the FETD or the other shelf controller we're done with this
13642	 * command.  Note that only SCSI commands get to this point.  Task
13643	 * management commands are completed above.
13644	 *
13645	 * We only send status to the other controller if we're in XFER
13646	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13647	 * received the I/O (from CTL's perspective), and so the status is
13648	 * generated there.
13649	 *
13650	 * XXX KDM if we hold the lock here, we could cause a deadlock
13651	 * if the frontend comes back in in this context to queue
13652	 * something.
13653	 */
13654	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13655	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13656		union ctl_ha_msg msg;
13657
13658		memset(&msg, 0, sizeof(msg));
13659		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13660		msg.hdr.original_sc = io->io_hdr.original_sc;
13661		msg.hdr.nexus = io->io_hdr.nexus;
13662		msg.hdr.status = io->io_hdr.status;
13663		msg.scsi.scsi_status = io->scsiio.scsi_status;
13664		msg.scsi.tag_num = io->scsiio.tag_num;
13665		msg.scsi.tag_type = io->scsiio.tag_type;
13666		msg.scsi.sense_len = io->scsiio.sense_len;
13667		msg.scsi.sense_residual = io->scsiio.sense_residual;
13668		msg.scsi.residual = io->scsiio.residual;
13669		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13670		       sizeof(io->scsiio.sense_data));
13671		/*
13672		 * We copy this whether or not this is an I/O-related
13673		 * command.  Otherwise, we'd have to go and check to see
13674		 * whether it's a read/write command, and it really isn't
13675		 * worth it.
13676		 */
13677		memcpy(&msg.scsi.lbalen,
13678		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13679		       sizeof(msg.scsi.lbalen));
13680
13681		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13682				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13683			/* XXX do something here */
13684		}
13685
13686		ctl_free_io(io);
13687	} else
13688		fe_done(io);
13689
13690	return (CTL_RETVAL_COMPLETE);
13691}
13692
13693#ifdef CTL_WITH_CA
13694/*
13695 * Front end should call this if it doesn't do autosense.  When the request
13696 * sense comes back in from the initiator, we'll dequeue this and send it.
13697 */
13698int
13699ctl_queue_sense(union ctl_io *io)
13700{
13701	struct ctl_lun *lun;
13702	struct ctl_softc *ctl_softc;
13703	uint32_t initidx, targ_lun;
13704
13705	ctl_softc = control_softc;
13706
13707	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13708
13709	/*
13710	 * LUN lookup will likely move to the ctl_work_thread() once we
13711	 * have our new queueing infrastructure (that doesn't put things on
13712	 * a per-LUN queue initially).  That is so that we can handle
13713	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13714	 * can't deal with that right now.
13715	 */
13716	mtx_lock(&ctl_softc->ctl_lock);
13717
13718	/*
13719	 * If we don't have a LUN for this, just toss the sense
13720	 * information.
13721	 */
13722	targ_lun = io->io_hdr.nexus.targ_lun;
13723	targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13724	if ((targ_lun < CTL_MAX_LUNS)
13725	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
13726		lun = ctl_softc->ctl_luns[targ_lun];
13727	else
13728		goto bailout;
13729
13730	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13731
13732	mtx_lock(&lun->lun_lock);
13733	/*
13734	 * Already have CA set for this LUN...toss the sense information.
13735	 */
13736	if (ctl_is_set(lun->have_ca, initidx)) {
13737		mtx_unlock(&lun->lun_lock);
13738		goto bailout;
13739	}
13740
13741	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13742	       ctl_min(sizeof(lun->pending_sense[initidx]),
13743	       sizeof(io->scsiio.sense_data)));
13744	ctl_set_mask(lun->have_ca, initidx);
13745	mtx_unlock(&lun->lun_lock);
13746
13747bailout:
13748	mtx_unlock(&ctl_softc->ctl_lock);
13749
13750	ctl_free_io(io);
13751
13752	return (CTL_RETVAL_COMPLETE);
13753}
13754#endif
13755
13756/*
13757 * Primary command inlet from frontend ports.  All SCSI and task I/O
13758 * requests must go through this function.
13759 */
13760int
13761ctl_queue(union ctl_io *io)
13762{
13763	struct ctl_softc *ctl_softc;
13764
13765	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13766
13767	ctl_softc = control_softc;
13768
13769#ifdef CTL_TIME_IO
13770	io->io_hdr.start_time = time_uptime;
13771	getbintime(&io->io_hdr.start_bt);
13772#endif /* CTL_TIME_IO */
13773
13774	/* Map FE-specific LUN ID into global one. */
13775	io->io_hdr.nexus.targ_mapped_lun =
13776	    ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13777
13778	switch (io->io_hdr.io_type) {
13779	case CTL_IO_SCSI:
13780	case CTL_IO_TASK:
13781		if (ctl_debug & CTL_DEBUG_CDB)
13782			ctl_io_print(io);
13783		ctl_enqueue_incoming(io);
13784		break;
13785	default:
13786		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13787		return (EINVAL);
13788	}
13789
13790	return (CTL_RETVAL_COMPLETE);
13791}
13792
13793#ifdef CTL_IO_DELAY
13794static void
13795ctl_done_timer_wakeup(void *arg)
13796{
13797	union ctl_io *io;
13798
13799	io = (union ctl_io *)arg;
13800	ctl_done(io);
13801}
13802#endif /* CTL_IO_DELAY */
13803
13804void
13805ctl_done(union ctl_io *io)
13806{
13807	struct ctl_softc *ctl_softc;
13808
13809	ctl_softc = control_softc;
13810
13811	/*
13812	 * Enable this to catch duplicate completion issues.
13813	 */
13814#if 0
13815	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13816		printf("%s: type %d msg %d cdb %x iptl: "
13817		       "%d:%d:%d:%d tag 0x%04x "
13818		       "flag %#x status %x\n",
13819			__func__,
13820			io->io_hdr.io_type,
13821			io->io_hdr.msg_type,
13822			io->scsiio.cdb[0],
13823			io->io_hdr.nexus.initid.id,
13824			io->io_hdr.nexus.targ_port,
13825			io->io_hdr.nexus.targ_target.id,
13826			io->io_hdr.nexus.targ_lun,
13827			(io->io_hdr.io_type ==
13828			CTL_IO_TASK) ?
13829			io->taskio.tag_num :
13830			io->scsiio.tag_num,
13831		        io->io_hdr.flags,
13832			io->io_hdr.status);
13833	} else
13834		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13835#endif
13836
13837	/*
13838	 * This is an internal copy of an I/O, and should not go through
13839	 * the normal done processing logic.
13840	 */
13841	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13842		return;
13843
13844	/*
13845	 * We need to send a msg to the serializing shelf to finish the IO
13846	 * as well.  We don't send a finish message to the other shelf if
13847	 * this is a task management command.  Task management commands
13848	 * aren't serialized in the OOA queue, but rather just executed on
13849	 * both shelf controllers for commands that originated on that
13850	 * controller.
13851	 */
13852	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13853	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
13854		union ctl_ha_msg msg_io;
13855
13856		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13857		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13858		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13859		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13860		}
13861		/* continue on to finish IO */
13862	}
13863#ifdef CTL_IO_DELAY
13864	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13865		struct ctl_lun *lun;
13866
13867		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13868
13869		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13870	} else {
13871		struct ctl_lun *lun;
13872
13873		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13874
13875		if ((lun != NULL)
13876		 && (lun->delay_info.done_delay > 0)) {
13877			struct callout *callout;
13878
13879			callout = (struct callout *)&io->io_hdr.timer_bytes;
13880			callout_init(callout, /*mpsafe*/ 1);
13881			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13882			callout_reset(callout,
13883				      lun->delay_info.done_delay * hz,
13884				      ctl_done_timer_wakeup, io);
13885			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13886				lun->delay_info.done_delay = 0;
13887			return;
13888		}
13889	}
13890#endif /* CTL_IO_DELAY */
13891
13892	ctl_enqueue_done(io);
13893}
13894
13895int
13896ctl_isc(struct ctl_scsiio *ctsio)
13897{
13898	struct ctl_lun *lun;
13899	int retval;
13900
13901	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13902
13903	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13904
13905	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13906
13907	retval = lun->backend->data_submit((union ctl_io *)ctsio);
13908
13909	return (retval);
13910}
13911
13912
13913static void
13914ctl_work_thread(void *arg)
13915{
13916	struct ctl_thread *thr = (struct ctl_thread *)arg;
13917	struct ctl_softc *softc = thr->ctl_softc;
13918	union ctl_io *io;
13919	int retval;
13920
13921	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13922
13923	for (;;) {
13924		retval = 0;
13925
13926		/*
13927		 * We handle the queues in this order:
13928		 * - ISC
13929		 * - done queue (to free up resources, unblock other commands)
13930		 * - RtR queue
13931		 * - incoming queue
13932		 *
13933		 * If those queues are empty, we break out of the loop and
13934		 * go to sleep.
13935		 */
13936		mtx_lock(&thr->queue_lock);
13937		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13938		if (io != NULL) {
13939			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13940			mtx_unlock(&thr->queue_lock);
13941			ctl_handle_isc(io);
13942			continue;
13943		}
13944		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13945		if (io != NULL) {
13946			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13947			/* clear any blocked commands, call fe_done */
13948			mtx_unlock(&thr->queue_lock);
13949			retval = ctl_process_done(io);
13950			continue;
13951		}
13952		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13953		if (io != NULL) {
13954			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13955			mtx_unlock(&thr->queue_lock);
13956			if (io->io_hdr.io_type == CTL_IO_TASK)
13957				ctl_run_task(io);
13958			else
13959				ctl_scsiio_precheck(softc, &io->scsiio);
13960			continue;
13961		}
13962		if (!ctl_pause_rtr) {
13963			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13964			if (io != NULL) {
13965				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13966				mtx_unlock(&thr->queue_lock);
13967				retval = ctl_scsiio(&io->scsiio);
13968				if (retval != CTL_RETVAL_COMPLETE)
13969					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13970				continue;
13971			}
13972		}
13973
13974		/* Sleep until we have something to do. */
13975		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13976	}
13977}
13978
13979static void
13980ctl_lun_thread(void *arg)
13981{
13982	struct ctl_softc *softc = (struct ctl_softc *)arg;
13983	struct ctl_be_lun *be_lun;
13984	int retval;
13985
13986	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13987
13988	for (;;) {
13989		retval = 0;
13990		mtx_lock(&softc->ctl_lock);
13991		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13992		if (be_lun != NULL) {
13993			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13994			mtx_unlock(&softc->ctl_lock);
13995			ctl_create_lun(be_lun);
13996			continue;
13997		}
13998
13999		/* Sleep until we have something to do. */
14000		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
14001		    PDROP | PRIBIO, "-", 0);
14002	}
14003}
14004
14005static void
14006ctl_thresh_thread(void *arg)
14007{
14008	struct ctl_softc *softc = (struct ctl_softc *)arg;
14009	struct ctl_lun *lun;
14010	struct ctl_be_lun *be_lun;
14011	struct scsi_da_rw_recovery_page *rwpage;
14012	struct ctl_logical_block_provisioning_page *page;
14013	const char *attr;
14014	uint64_t thres, val;
14015	int i, e;
14016
14017	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
14018
14019	for (;;) {
14020		mtx_lock(&softc->ctl_lock);
14021		STAILQ_FOREACH(lun, &softc->lun_list, links) {
14022			be_lun = lun->be_lun;
14023			if ((lun->flags & CTL_LUN_DISABLED) ||
14024			    (lun->flags & CTL_LUN_OFFLINE) ||
14025			    (be_lun->flags & CTL_LUN_FLAG_UNMAP) == 0 ||
14026			    lun->backend->lun_attr == NULL)
14027				continue;
14028			rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
14029			if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
14030				continue;
14031			e = 0;
14032			page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
14033			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
14034				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
14035					continue;
14036				thres = scsi_4btoul(page->descr[i].count);
14037				thres <<= CTL_LBP_EXPONENT;
14038				switch (page->descr[i].resource) {
14039				case 0x01:
14040					attr = "blocksavail";
14041					break;
14042				case 0x02:
14043					attr = "blocksused";
14044					break;
14045				case 0xf1:
14046					attr = "poolblocksavail";
14047					break;
14048				case 0xf2:
14049					attr = "poolblocksused";
14050					break;
14051				default:
14052					continue;
14053				}
14054				mtx_unlock(&softc->ctl_lock); // XXX
14055				val = lun->backend->lun_attr(
14056				    lun->be_lun->be_lun, attr);
14057				mtx_lock(&softc->ctl_lock);
14058				if (val == UINT64_MAX)
14059					continue;
14060				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
14061				    == SLBPPD_ARMING_INC)
14062					e |= (val >= thres);
14063				else
14064					e |= (val <= thres);
14065			}
14066			mtx_lock(&lun->lun_lock);
14067			if (e) {
14068				if (lun->lasttpt == 0 ||
14069				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
14070					lun->lasttpt = time_uptime;
14071					for (i = 0; i < CTL_MAX_INITIATORS; i++)
14072						lun->pending_ua[i] |=
14073						    CTL_UA_THIN_PROV_THRES;
14074				}
14075			} else {
14076				lun->lasttpt = 0;
14077				for (i = 0; i < CTL_MAX_INITIATORS; i++)
14078					lun->pending_ua[i] &= ~CTL_UA_THIN_PROV_THRES;
14079			}
14080			mtx_unlock(&lun->lun_lock);
14081		}
14082		mtx_unlock(&softc->ctl_lock);
14083		pause("-", CTL_LBP_PERIOD * hz);
14084	}
14085}
14086
14087static void
14088ctl_enqueue_incoming(union ctl_io *io)
14089{
14090	struct ctl_softc *softc = control_softc;
14091	struct ctl_thread *thr;
14092	u_int idx;
14093
14094	idx = (io->io_hdr.nexus.targ_port * 127 +
14095	       io->io_hdr.nexus.initid.id) % worker_threads;
14096	thr = &softc->threads[idx];
14097	mtx_lock(&thr->queue_lock);
14098	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14099	mtx_unlock(&thr->queue_lock);
14100	wakeup(thr);
14101}
14102
14103static void
14104ctl_enqueue_rtr(union ctl_io *io)
14105{
14106	struct ctl_softc *softc = control_softc;
14107	struct ctl_thread *thr;
14108
14109	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14110	mtx_lock(&thr->queue_lock);
14111	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14112	mtx_unlock(&thr->queue_lock);
14113	wakeup(thr);
14114}
14115
14116static void
14117ctl_enqueue_done(union ctl_io *io)
14118{
14119	struct ctl_softc *softc = control_softc;
14120	struct ctl_thread *thr;
14121
14122	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14123	mtx_lock(&thr->queue_lock);
14124	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14125	mtx_unlock(&thr->queue_lock);
14126	wakeup(thr);
14127}
14128
14129static void
14130ctl_enqueue_isc(union ctl_io *io)
14131{
14132	struct ctl_softc *softc = control_softc;
14133	struct ctl_thread *thr;
14134
14135	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14136	mtx_lock(&thr->queue_lock);
14137	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14138	mtx_unlock(&thr->queue_lock);
14139	wakeup(thr);
14140}
14141
14142/* Initialization and failover */
14143
14144void
14145ctl_init_isc_msg(void)
14146{
14147	printf("CTL: Still calling this thing\n");
14148}
14149
14150/*
14151 * Init component
14152 * 	Initializes component into configuration defined by bootMode
14153 *	(see hasc-sv.c)
14154 *  	returns hasc_Status:
14155 * 		OK
14156 *		ERROR - fatal error
14157 */
14158static ctl_ha_comp_status
14159ctl_isc_init(struct ctl_ha_component *c)
14160{
14161	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14162
14163	c->status = ret;
14164	return ret;
14165}
14166
14167/* Start component
14168 * 	Starts component in state requested. If component starts successfully,
14169 *	it must set its own state to the requestrd state
14170 *	When requested state is HASC_STATE_HA, the component may refine it
14171 * 	by adding _SLAVE or _MASTER flags.
14172 *	Currently allowed state transitions are:
14173 *	UNKNOWN->HA		- initial startup
14174 *	UNKNOWN->SINGLE - initial startup when no parter detected
14175 *	HA->SINGLE		- failover
14176 * returns ctl_ha_comp_status:
14177 * 		OK	- component successfully started in requested state
14178 *		FAILED  - could not start the requested state, failover may
14179 * 			  be possible
14180 *		ERROR	- fatal error detected, no future startup possible
14181 */
14182static ctl_ha_comp_status
14183ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14184{
14185	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14186
14187	printf("%s: go\n", __func__);
14188
14189	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14190	if (c->state == CTL_HA_STATE_UNKNOWN ) {
14191		control_softc->is_single = 0;
14192		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14193		    != CTL_HA_STATUS_SUCCESS) {
14194			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14195			ret = CTL_HA_COMP_STATUS_ERROR;
14196		}
14197	} else if (CTL_HA_STATE_IS_HA(c->state)
14198		&& CTL_HA_STATE_IS_SINGLE(state)){
14199		// HA->SINGLE transition
14200	        ctl_failover();
14201		control_softc->is_single = 1;
14202	} else {
14203		printf("ctl_isc_start:Invalid state transition %X->%X\n",
14204		       c->state, state);
14205		ret = CTL_HA_COMP_STATUS_ERROR;
14206	}
14207	if (CTL_HA_STATE_IS_SINGLE(state))
14208		control_softc->is_single = 1;
14209
14210	c->state = state;
14211	c->status = ret;
14212	return ret;
14213}
14214
14215/*
14216 * Quiesce component
14217 * The component must clear any error conditions (set status to OK) and
14218 * prepare itself to another Start call
14219 * returns ctl_ha_comp_status:
14220 * 	OK
14221 *	ERROR
14222 */
14223static ctl_ha_comp_status
14224ctl_isc_quiesce(struct ctl_ha_component *c)
14225{
14226	int ret = CTL_HA_COMP_STATUS_OK;
14227
14228	ctl_pause_rtr = 1;
14229	c->status = ret;
14230	return ret;
14231}
14232
14233struct ctl_ha_component ctl_ha_component_ctlisc =
14234{
14235	.name = "CTL ISC",
14236	.state = CTL_HA_STATE_UNKNOWN,
14237	.init = ctl_isc_init,
14238	.start = ctl_isc_start,
14239	.quiesce = ctl_isc_quiesce
14240};
14241
14242/*
14243 *  vim: ts=8
14244 */
14245