ctl.c revision 275884
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 275884 2014-12-18 08:27:46Z 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	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5002	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5003	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5004
5005	if ((io->io_hdr.port_status != 0) &&
5006	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5007	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5008		/*
5009		 * For hardware error sense keys, the sense key
5010		 * specific value is defined to be a retry count,
5011		 * but we use it to pass back an internal FETD
5012		 * error code.  XXX KDM  Hopefully the FETD is only
5013		 * using 16 bits for an error code, since that's
5014		 * all the space we have in the sks field.
5015		 */
5016		ctl_set_internal_failure(&io->scsiio,
5017					 /*sks_valid*/ 1,
5018					 /*retry_count*/
5019					 io->io_hdr.port_status);
5020	}
5021
5022	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5023	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5024	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5025	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5026		/*
5027		 * XXX KDM just assuming a single pointer here, and not a
5028		 * S/G list.  If we start using S/G lists for config data,
5029		 * we'll need to know how to clean them up here as well.
5030		 */
5031		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5032			free(io->scsiio.kern_data_ptr, M_CTL);
5033		ctl_done(io);
5034		retval = CTL_RETVAL_COMPLETE;
5035	} else {
5036		/*
5037		 * XXX KDM now we need to continue data movement.  Some
5038		 * options:
5039		 * - call ctl_scsiio() again?  We don't do this for data
5040		 *   writes, because for those at least we know ahead of
5041		 *   time where the write will go and how long it is.  For
5042		 *   config writes, though, that information is largely
5043		 *   contained within the write itself, thus we need to
5044		 *   parse out the data again.
5045		 *
5046		 * - Call some other function once the data is in?
5047		 */
5048		if (ctl_debug & CTL_DEBUG_CDB_DATA)
5049			ctl_data_print(io);
5050
5051		/*
5052		 * XXX KDM call ctl_scsiio() again for now, and check flag
5053		 * bits to see whether we're allocated or not.
5054		 */
5055		retval = ctl_scsiio(&io->scsiio);
5056	}
5057	return (retval);
5058}
5059
5060/*
5061 * This gets called by a backend driver when it is done with a
5062 * data_submit method.
5063 */
5064void
5065ctl_data_submit_done(union ctl_io *io)
5066{
5067	/*
5068	 * If the IO_CONT flag is set, we need to call the supplied
5069	 * function to continue processing the I/O, instead of completing
5070	 * the I/O just yet.
5071	 *
5072	 * If there is an error, though, we don't want to keep processing.
5073	 * Instead, just send status back to the initiator.
5074	 */
5075	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5076	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5077	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5078	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5079		io->scsiio.io_cont(io);
5080		return;
5081	}
5082	ctl_done(io);
5083}
5084
5085/*
5086 * This gets called by a backend driver when it is done with a
5087 * configuration write.
5088 */
5089void
5090ctl_config_write_done(union ctl_io *io)
5091{
5092	uint8_t *buf;
5093
5094	/*
5095	 * If the IO_CONT flag is set, we need to call the supplied
5096	 * function to continue processing the I/O, instead of completing
5097	 * the I/O just yet.
5098	 *
5099	 * If there is an error, though, we don't want to keep processing.
5100	 * Instead, just send status back to the initiator.
5101	 */
5102	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5103	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5104	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5105	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5106		io->scsiio.io_cont(io);
5107		return;
5108	}
5109	/*
5110	 * Since a configuration write can be done for commands that actually
5111	 * have data allocated, like write buffer, and commands that have
5112	 * no data, like start/stop unit, we need to check here.
5113	 */
5114	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5115		buf = io->scsiio.kern_data_ptr;
5116	else
5117		buf = NULL;
5118	ctl_done(io);
5119	if (buf)
5120		free(buf, M_CTL);
5121}
5122
5123/*
5124 * SCSI release command.
5125 */
5126int
5127ctl_scsi_release(struct ctl_scsiio *ctsio)
5128{
5129	int length, longid, thirdparty_id, resv_id;
5130	struct ctl_softc *ctl_softc;
5131	struct ctl_lun *lun;
5132	uint32_t residx;
5133
5134	length = 0;
5135	resv_id = 0;
5136
5137	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5138
5139	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5140	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5141	ctl_softc = control_softc;
5142
5143	switch (ctsio->cdb[0]) {
5144	case RELEASE_10: {
5145		struct scsi_release_10 *cdb;
5146
5147		cdb = (struct scsi_release_10 *)ctsio->cdb;
5148
5149		if (cdb->byte2 & SR10_LONGID)
5150			longid = 1;
5151		else
5152			thirdparty_id = cdb->thirdparty_id;
5153
5154		resv_id = cdb->resv_id;
5155		length = scsi_2btoul(cdb->length);
5156		break;
5157	}
5158	}
5159
5160
5161	/*
5162	 * XXX KDM right now, we only support LUN reservation.  We don't
5163	 * support 3rd party reservations, or extent reservations, which
5164	 * might actually need the parameter list.  If we've gotten this
5165	 * far, we've got a LUN reservation.  Anything else got kicked out
5166	 * above.  So, according to SPC, ignore the length.
5167	 */
5168	length = 0;
5169
5170	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5171	 && (length > 0)) {
5172		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5173		ctsio->kern_data_len = length;
5174		ctsio->kern_total_len = length;
5175		ctsio->kern_data_resid = 0;
5176		ctsio->kern_rel_offset = 0;
5177		ctsio->kern_sg_entries = 0;
5178		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5179		ctsio->be_move_done = ctl_config_move_done;
5180		ctl_datamove((union ctl_io *)ctsio);
5181
5182		return (CTL_RETVAL_COMPLETE);
5183	}
5184
5185	if (length > 0)
5186		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5187
5188	mtx_lock(&lun->lun_lock);
5189
5190	/*
5191	 * According to SPC, it is not an error for an intiator to attempt
5192	 * to release a reservation on a LUN that isn't reserved, or that
5193	 * is reserved by another initiator.  The reservation can only be
5194	 * released, though, by the initiator who made it or by one of
5195	 * several reset type events.
5196	 */
5197	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5198			lun->flags &= ~CTL_LUN_RESERVED;
5199
5200	mtx_unlock(&lun->lun_lock);
5201
5202	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5203		free(ctsio->kern_data_ptr, M_CTL);
5204		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5205	}
5206
5207	ctl_set_success(ctsio);
5208	ctl_done((union ctl_io *)ctsio);
5209	return (CTL_RETVAL_COMPLETE);
5210}
5211
5212int
5213ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5214{
5215	int extent, thirdparty, longid;
5216	int resv_id, length;
5217	uint64_t thirdparty_id;
5218	struct ctl_softc *ctl_softc;
5219	struct ctl_lun *lun;
5220	uint32_t residx;
5221
5222	extent = 0;
5223	thirdparty = 0;
5224	longid = 0;
5225	resv_id = 0;
5226	length = 0;
5227	thirdparty_id = 0;
5228
5229	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5230
5231	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5232	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5233	ctl_softc = control_softc;
5234
5235	switch (ctsio->cdb[0]) {
5236	case RESERVE_10: {
5237		struct scsi_reserve_10 *cdb;
5238
5239		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5240
5241		if (cdb->byte2 & SR10_LONGID)
5242			longid = 1;
5243		else
5244			thirdparty_id = cdb->thirdparty_id;
5245
5246		resv_id = cdb->resv_id;
5247		length = scsi_2btoul(cdb->length);
5248		break;
5249	}
5250	}
5251
5252	/*
5253	 * XXX KDM right now, we only support LUN reservation.  We don't
5254	 * support 3rd party reservations, or extent reservations, which
5255	 * might actually need the parameter list.  If we've gotten this
5256	 * far, we've got a LUN reservation.  Anything else got kicked out
5257	 * above.  So, according to SPC, ignore the length.
5258	 */
5259	length = 0;
5260
5261	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5262	 && (length > 0)) {
5263		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5264		ctsio->kern_data_len = length;
5265		ctsio->kern_total_len = length;
5266		ctsio->kern_data_resid = 0;
5267		ctsio->kern_rel_offset = 0;
5268		ctsio->kern_sg_entries = 0;
5269		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5270		ctsio->be_move_done = ctl_config_move_done;
5271		ctl_datamove((union ctl_io *)ctsio);
5272
5273		return (CTL_RETVAL_COMPLETE);
5274	}
5275
5276	if (length > 0)
5277		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5278
5279	mtx_lock(&lun->lun_lock);
5280	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5281		ctl_set_reservation_conflict(ctsio);
5282		goto bailout;
5283	}
5284
5285	lun->flags |= CTL_LUN_RESERVED;
5286	lun->res_idx = residx;
5287
5288	ctl_set_success(ctsio);
5289
5290bailout:
5291	mtx_unlock(&lun->lun_lock);
5292
5293	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5294		free(ctsio->kern_data_ptr, M_CTL);
5295		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5296	}
5297
5298	ctl_done((union ctl_io *)ctsio);
5299	return (CTL_RETVAL_COMPLETE);
5300}
5301
5302int
5303ctl_start_stop(struct ctl_scsiio *ctsio)
5304{
5305	struct scsi_start_stop_unit *cdb;
5306	struct ctl_lun *lun;
5307	struct ctl_softc *ctl_softc;
5308	int retval;
5309
5310	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5311
5312	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5313	ctl_softc = control_softc;
5314	retval = 0;
5315
5316	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5317
5318	/*
5319	 * XXX KDM
5320	 * We don't support the immediate bit on a stop unit.  In order to
5321	 * do that, we would need to code up a way to know that a stop is
5322	 * pending, and hold off any new commands until it completes, one
5323	 * way or another.  Then we could accept or reject those commands
5324	 * depending on its status.  We would almost need to do the reverse
5325	 * of what we do below for an immediate start -- return the copy of
5326	 * the ctl_io to the FETD with status to send to the host (and to
5327	 * free the copy!) and then free the original I/O once the stop
5328	 * actually completes.  That way, the OOA queue mechanism can work
5329	 * to block commands that shouldn't proceed.  Another alternative
5330	 * would be to put the copy in the queue in place of the original,
5331	 * and return the original back to the caller.  That could be
5332	 * slightly safer..
5333	 */
5334	if ((cdb->byte2 & SSS_IMMED)
5335	 && ((cdb->how & SSS_START) == 0)) {
5336		ctl_set_invalid_field(ctsio,
5337				      /*sks_valid*/ 1,
5338				      /*command*/ 1,
5339				      /*field*/ 1,
5340				      /*bit_valid*/ 1,
5341				      /*bit*/ 0);
5342		ctl_done((union ctl_io *)ctsio);
5343		return (CTL_RETVAL_COMPLETE);
5344	}
5345
5346	if ((lun->flags & CTL_LUN_PR_RESERVED)
5347	 && ((cdb->how & SSS_START)==0)) {
5348		uint32_t residx;
5349
5350		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5351		if (lun->pr_keys[residx] == 0
5352		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5353
5354			ctl_set_reservation_conflict(ctsio);
5355			ctl_done((union ctl_io *)ctsio);
5356			return (CTL_RETVAL_COMPLETE);
5357		}
5358	}
5359
5360	/*
5361	 * If there is no backend on this device, we can't start or stop
5362	 * it.  In theory we shouldn't get any start/stop commands in the
5363	 * first place at this level if the LUN doesn't have a backend.
5364	 * That should get stopped by the command decode code.
5365	 */
5366	if (lun->backend == NULL) {
5367		ctl_set_invalid_opcode(ctsio);
5368		ctl_done((union ctl_io *)ctsio);
5369		return (CTL_RETVAL_COMPLETE);
5370	}
5371
5372	/*
5373	 * XXX KDM Copan-specific offline behavior.
5374	 * Figure out a reasonable way to port this?
5375	 */
5376#ifdef NEEDTOPORT
5377	mtx_lock(&lun->lun_lock);
5378
5379	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5380	 && (lun->flags & CTL_LUN_OFFLINE)) {
5381		/*
5382		 * If the LUN is offline, and the on/offline bit isn't set,
5383		 * reject the start or stop.  Otherwise, let it through.
5384		 */
5385		mtx_unlock(&lun->lun_lock);
5386		ctl_set_lun_not_ready(ctsio);
5387		ctl_done((union ctl_io *)ctsio);
5388	} else {
5389		mtx_unlock(&lun->lun_lock);
5390#endif /* NEEDTOPORT */
5391		/*
5392		 * This could be a start or a stop when we're online,
5393		 * or a stop/offline or start/online.  A start or stop when
5394		 * we're offline is covered in the case above.
5395		 */
5396		/*
5397		 * In the non-immediate case, we send the request to
5398		 * the backend and return status to the user when
5399		 * it is done.
5400		 *
5401		 * In the immediate case, we allocate a new ctl_io
5402		 * to hold a copy of the request, and send that to
5403		 * the backend.  We then set good status on the
5404		 * user's request and return it immediately.
5405		 */
5406		if (cdb->byte2 & SSS_IMMED) {
5407			union ctl_io *new_io;
5408
5409			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5410			ctl_copy_io((union ctl_io *)ctsio, new_io);
5411			retval = lun->backend->config_write(new_io);
5412			ctl_set_success(ctsio);
5413			ctl_done((union ctl_io *)ctsio);
5414		} else {
5415			retval = lun->backend->config_write(
5416				(union ctl_io *)ctsio);
5417		}
5418#ifdef NEEDTOPORT
5419	}
5420#endif
5421	return (retval);
5422}
5423
5424/*
5425 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5426 * we don't really do anything with the LBA and length fields if the user
5427 * passes them in.  Instead we'll just flush out the cache for the entire
5428 * LUN.
5429 */
5430int
5431ctl_sync_cache(struct ctl_scsiio *ctsio)
5432{
5433	struct ctl_lun *lun;
5434	struct ctl_softc *ctl_softc;
5435	uint64_t starting_lba;
5436	uint32_t block_count;
5437	int retval;
5438
5439	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5440
5441	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5442	ctl_softc = control_softc;
5443	retval = 0;
5444
5445	switch (ctsio->cdb[0]) {
5446	case SYNCHRONIZE_CACHE: {
5447		struct scsi_sync_cache *cdb;
5448		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5449
5450		starting_lba = scsi_4btoul(cdb->begin_lba);
5451		block_count = scsi_2btoul(cdb->lb_count);
5452		break;
5453	}
5454	case SYNCHRONIZE_CACHE_16: {
5455		struct scsi_sync_cache_16 *cdb;
5456		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5457
5458		starting_lba = scsi_8btou64(cdb->begin_lba);
5459		block_count = scsi_4btoul(cdb->lb_count);
5460		break;
5461	}
5462	default:
5463		ctl_set_invalid_opcode(ctsio);
5464		ctl_done((union ctl_io *)ctsio);
5465		goto bailout;
5466		break; /* NOTREACHED */
5467	}
5468
5469	/*
5470	 * We check the LBA and length, but don't do anything with them.
5471	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5472	 * get flushed.  This check will just help satisfy anyone who wants
5473	 * to see an error for an out of range LBA.
5474	 */
5475	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5476		ctl_set_lba_out_of_range(ctsio);
5477		ctl_done((union ctl_io *)ctsio);
5478		goto bailout;
5479	}
5480
5481	/*
5482	 * If this LUN has no backend, we can't flush the cache anyway.
5483	 */
5484	if (lun->backend == NULL) {
5485		ctl_set_invalid_opcode(ctsio);
5486		ctl_done((union ctl_io *)ctsio);
5487		goto bailout;
5488	}
5489
5490	/*
5491	 * Check to see whether we're configured to send the SYNCHRONIZE
5492	 * CACHE command directly to the back end.
5493	 */
5494	mtx_lock(&lun->lun_lock);
5495	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5496	 && (++(lun->sync_count) >= lun->sync_interval)) {
5497		lun->sync_count = 0;
5498		mtx_unlock(&lun->lun_lock);
5499		retval = lun->backend->config_write((union ctl_io *)ctsio);
5500	} else {
5501		mtx_unlock(&lun->lun_lock);
5502		ctl_set_success(ctsio);
5503		ctl_done((union ctl_io *)ctsio);
5504	}
5505
5506bailout:
5507
5508	return (retval);
5509}
5510
5511int
5512ctl_format(struct ctl_scsiio *ctsio)
5513{
5514	struct scsi_format *cdb;
5515	struct ctl_lun *lun;
5516	struct ctl_softc *ctl_softc;
5517	int length, defect_list_len;
5518
5519	CTL_DEBUG_PRINT(("ctl_format\n"));
5520
5521	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5522	ctl_softc = control_softc;
5523
5524	cdb = (struct scsi_format *)ctsio->cdb;
5525
5526	length = 0;
5527	if (cdb->byte2 & SF_FMTDATA) {
5528		if (cdb->byte2 & SF_LONGLIST)
5529			length = sizeof(struct scsi_format_header_long);
5530		else
5531			length = sizeof(struct scsi_format_header_short);
5532	}
5533
5534	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5535	 && (length > 0)) {
5536		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5537		ctsio->kern_data_len = length;
5538		ctsio->kern_total_len = length;
5539		ctsio->kern_data_resid = 0;
5540		ctsio->kern_rel_offset = 0;
5541		ctsio->kern_sg_entries = 0;
5542		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5543		ctsio->be_move_done = ctl_config_move_done;
5544		ctl_datamove((union ctl_io *)ctsio);
5545
5546		return (CTL_RETVAL_COMPLETE);
5547	}
5548
5549	defect_list_len = 0;
5550
5551	if (cdb->byte2 & SF_FMTDATA) {
5552		if (cdb->byte2 & SF_LONGLIST) {
5553			struct scsi_format_header_long *header;
5554
5555			header = (struct scsi_format_header_long *)
5556				ctsio->kern_data_ptr;
5557
5558			defect_list_len = scsi_4btoul(header->defect_list_len);
5559			if (defect_list_len != 0) {
5560				ctl_set_invalid_field(ctsio,
5561						      /*sks_valid*/ 1,
5562						      /*command*/ 0,
5563						      /*field*/ 2,
5564						      /*bit_valid*/ 0,
5565						      /*bit*/ 0);
5566				goto bailout;
5567			}
5568		} else {
5569			struct scsi_format_header_short *header;
5570
5571			header = (struct scsi_format_header_short *)
5572				ctsio->kern_data_ptr;
5573
5574			defect_list_len = scsi_2btoul(header->defect_list_len);
5575			if (defect_list_len != 0) {
5576				ctl_set_invalid_field(ctsio,
5577						      /*sks_valid*/ 1,
5578						      /*command*/ 0,
5579						      /*field*/ 2,
5580						      /*bit_valid*/ 0,
5581						      /*bit*/ 0);
5582				goto bailout;
5583			}
5584		}
5585	}
5586
5587	/*
5588	 * The format command will clear out the "Medium format corrupted"
5589	 * status if set by the configuration code.  That status is really
5590	 * just a way to notify the host that we have lost the media, and
5591	 * get them to issue a command that will basically make them think
5592	 * they're blowing away the media.
5593	 */
5594	mtx_lock(&lun->lun_lock);
5595	lun->flags &= ~CTL_LUN_INOPERABLE;
5596	mtx_unlock(&lun->lun_lock);
5597
5598	ctl_set_success(ctsio);
5599bailout:
5600
5601	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5602		free(ctsio->kern_data_ptr, M_CTL);
5603		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5604	}
5605
5606	ctl_done((union ctl_io *)ctsio);
5607	return (CTL_RETVAL_COMPLETE);
5608}
5609
5610int
5611ctl_read_buffer(struct ctl_scsiio *ctsio)
5612{
5613	struct scsi_read_buffer *cdb;
5614	struct ctl_lun *lun;
5615	int buffer_offset, len;
5616	static uint8_t descr[4];
5617	static uint8_t echo_descr[4] = { 0 };
5618
5619	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5620
5621	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5622	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5623
5624	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5625	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5626	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5627		ctl_set_invalid_field(ctsio,
5628				      /*sks_valid*/ 1,
5629				      /*command*/ 1,
5630				      /*field*/ 1,
5631				      /*bit_valid*/ 1,
5632				      /*bit*/ 4);
5633		ctl_done((union ctl_io *)ctsio);
5634		return (CTL_RETVAL_COMPLETE);
5635	}
5636
5637	len = scsi_3btoul(cdb->length);
5638	buffer_offset = scsi_3btoul(cdb->offset);
5639
5640	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5641		ctl_set_invalid_field(ctsio,
5642				      /*sks_valid*/ 1,
5643				      /*command*/ 1,
5644				      /*field*/ 6,
5645				      /*bit_valid*/ 0,
5646				      /*bit*/ 0);
5647		ctl_done((union ctl_io *)ctsio);
5648		return (CTL_RETVAL_COMPLETE);
5649	}
5650
5651	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5652		descr[0] = 0;
5653		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5654		ctsio->kern_data_ptr = descr;
5655		len = min(len, sizeof(descr));
5656	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5657		ctsio->kern_data_ptr = echo_descr;
5658		len = min(len, sizeof(echo_descr));
5659	} else {
5660		if (lun->write_buffer == NULL) {
5661			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5662			    M_CTL, M_WAITOK);
5663		}
5664		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5665	}
5666	ctsio->kern_data_len = len;
5667	ctsio->kern_total_len = len;
5668	ctsio->kern_data_resid = 0;
5669	ctsio->kern_rel_offset = 0;
5670	ctsio->kern_sg_entries = 0;
5671	ctl_set_success(ctsio);
5672	ctsio->be_move_done = ctl_config_move_done;
5673	ctl_datamove((union ctl_io *)ctsio);
5674	return (CTL_RETVAL_COMPLETE);
5675}
5676
5677int
5678ctl_write_buffer(struct ctl_scsiio *ctsio)
5679{
5680	struct scsi_write_buffer *cdb;
5681	struct ctl_lun *lun;
5682	int buffer_offset, len;
5683
5684	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5685
5686	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5687	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5688
5689	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5690		ctl_set_invalid_field(ctsio,
5691				      /*sks_valid*/ 1,
5692				      /*command*/ 1,
5693				      /*field*/ 1,
5694				      /*bit_valid*/ 1,
5695				      /*bit*/ 4);
5696		ctl_done((union ctl_io *)ctsio);
5697		return (CTL_RETVAL_COMPLETE);
5698	}
5699
5700	len = scsi_3btoul(cdb->length);
5701	buffer_offset = scsi_3btoul(cdb->offset);
5702
5703	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5704		ctl_set_invalid_field(ctsio,
5705				      /*sks_valid*/ 1,
5706				      /*command*/ 1,
5707				      /*field*/ 6,
5708				      /*bit_valid*/ 0,
5709				      /*bit*/ 0);
5710		ctl_done((union ctl_io *)ctsio);
5711		return (CTL_RETVAL_COMPLETE);
5712	}
5713
5714	/*
5715	 * If we've got a kernel request that hasn't been malloced yet,
5716	 * malloc it and tell the caller the data buffer is here.
5717	 */
5718	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5719		if (lun->write_buffer == NULL) {
5720			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5721			    M_CTL, M_WAITOK);
5722		}
5723		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5724		ctsio->kern_data_len = len;
5725		ctsio->kern_total_len = len;
5726		ctsio->kern_data_resid = 0;
5727		ctsio->kern_rel_offset = 0;
5728		ctsio->kern_sg_entries = 0;
5729		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5730		ctsio->be_move_done = ctl_config_move_done;
5731		ctl_datamove((union ctl_io *)ctsio);
5732
5733		return (CTL_RETVAL_COMPLETE);
5734	}
5735
5736	ctl_set_success(ctsio);
5737	ctl_done((union ctl_io *)ctsio);
5738	return (CTL_RETVAL_COMPLETE);
5739}
5740
5741int
5742ctl_write_same(struct ctl_scsiio *ctsio)
5743{
5744	struct ctl_lun *lun;
5745	struct ctl_lba_len_flags *lbalen;
5746	uint64_t lba;
5747	uint32_t num_blocks;
5748	int len, retval;
5749	uint8_t byte2;
5750
5751	retval = CTL_RETVAL_COMPLETE;
5752
5753	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5754
5755	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5756
5757	switch (ctsio->cdb[0]) {
5758	case WRITE_SAME_10: {
5759		struct scsi_write_same_10 *cdb;
5760
5761		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5762
5763		lba = scsi_4btoul(cdb->addr);
5764		num_blocks = scsi_2btoul(cdb->length);
5765		byte2 = cdb->byte2;
5766		break;
5767	}
5768	case WRITE_SAME_16: {
5769		struct scsi_write_same_16 *cdb;
5770
5771		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5772
5773		lba = scsi_8btou64(cdb->addr);
5774		num_blocks = scsi_4btoul(cdb->length);
5775		byte2 = cdb->byte2;
5776		break;
5777	}
5778	default:
5779		/*
5780		 * We got a command we don't support.  This shouldn't
5781		 * happen, commands should be filtered out above us.
5782		 */
5783		ctl_set_invalid_opcode(ctsio);
5784		ctl_done((union ctl_io *)ctsio);
5785
5786		return (CTL_RETVAL_COMPLETE);
5787		break; /* NOTREACHED */
5788	}
5789
5790	/* NDOB and ANCHOR flags can be used only together with UNMAP */
5791	if ((byte2 & SWS_UNMAP) == 0 &&
5792	    (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5793		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5794		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5795		ctl_done((union ctl_io *)ctsio);
5796		return (CTL_RETVAL_COMPLETE);
5797	}
5798
5799	/*
5800	 * The first check is to make sure we're in bounds, the second
5801	 * check is to catch wrap-around problems.  If the lba + num blocks
5802	 * is less than the lba, then we've wrapped around and the block
5803	 * range is invalid anyway.
5804	 */
5805	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5806	 || ((lba + num_blocks) < lba)) {
5807		ctl_set_lba_out_of_range(ctsio);
5808		ctl_done((union ctl_io *)ctsio);
5809		return (CTL_RETVAL_COMPLETE);
5810	}
5811
5812	/* Zero number of blocks means "to the last logical block" */
5813	if (num_blocks == 0) {
5814		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5815			ctl_set_invalid_field(ctsio,
5816					      /*sks_valid*/ 0,
5817					      /*command*/ 1,
5818					      /*field*/ 0,
5819					      /*bit_valid*/ 0,
5820					      /*bit*/ 0);
5821			ctl_done((union ctl_io *)ctsio);
5822			return (CTL_RETVAL_COMPLETE);
5823		}
5824		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5825	}
5826
5827	len = lun->be_lun->blocksize;
5828
5829	/*
5830	 * If we've got a kernel request that hasn't been malloced yet,
5831	 * malloc it and tell the caller the data buffer is here.
5832	 */
5833	if ((byte2 & SWS_NDOB) == 0 &&
5834	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5835		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5836		ctsio->kern_data_len = len;
5837		ctsio->kern_total_len = len;
5838		ctsio->kern_data_resid = 0;
5839		ctsio->kern_rel_offset = 0;
5840		ctsio->kern_sg_entries = 0;
5841		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5842		ctsio->be_move_done = ctl_config_move_done;
5843		ctl_datamove((union ctl_io *)ctsio);
5844
5845		return (CTL_RETVAL_COMPLETE);
5846	}
5847
5848	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5849	lbalen->lba = lba;
5850	lbalen->len = num_blocks;
5851	lbalen->flags = byte2;
5852	retval = lun->backend->config_write((union ctl_io *)ctsio);
5853
5854	return (retval);
5855}
5856
5857int
5858ctl_unmap(struct ctl_scsiio *ctsio)
5859{
5860	struct ctl_lun *lun;
5861	struct scsi_unmap *cdb;
5862	struct ctl_ptr_len_flags *ptrlen;
5863	struct scsi_unmap_header *hdr;
5864	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5865	uint64_t lba;
5866	uint32_t num_blocks;
5867	int len, retval;
5868	uint8_t byte2;
5869
5870	retval = CTL_RETVAL_COMPLETE;
5871
5872	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5873
5874	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5875	cdb = (struct scsi_unmap *)ctsio->cdb;
5876
5877	len = scsi_2btoul(cdb->length);
5878	byte2 = cdb->byte2;
5879
5880	/*
5881	 * If we've got a kernel request that hasn't been malloced yet,
5882	 * malloc it and tell the caller the data buffer is here.
5883	 */
5884	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5885		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5886		ctsio->kern_data_len = len;
5887		ctsio->kern_total_len = len;
5888		ctsio->kern_data_resid = 0;
5889		ctsio->kern_rel_offset = 0;
5890		ctsio->kern_sg_entries = 0;
5891		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5892		ctsio->be_move_done = ctl_config_move_done;
5893		ctl_datamove((union ctl_io *)ctsio);
5894
5895		return (CTL_RETVAL_COMPLETE);
5896	}
5897
5898	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5899	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5900	if (len < sizeof (*hdr) ||
5901	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5902	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5903	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5904		ctl_set_invalid_field(ctsio,
5905				      /*sks_valid*/ 0,
5906				      /*command*/ 0,
5907				      /*field*/ 0,
5908				      /*bit_valid*/ 0,
5909				      /*bit*/ 0);
5910		goto done;
5911	}
5912	len = scsi_2btoul(hdr->desc_length);
5913	buf = (struct scsi_unmap_desc *)(hdr + 1);
5914	end = buf + len / sizeof(*buf);
5915
5916	endnz = buf;
5917	for (range = buf; range < end; range++) {
5918		lba = scsi_8btou64(range->lba);
5919		num_blocks = scsi_4btoul(range->length);
5920		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5921		 || ((lba + num_blocks) < lba)) {
5922			ctl_set_lba_out_of_range(ctsio);
5923			ctl_done((union ctl_io *)ctsio);
5924			return (CTL_RETVAL_COMPLETE);
5925		}
5926		if (num_blocks != 0)
5927			endnz = range + 1;
5928	}
5929
5930	/*
5931	 * Block backend can not handle zero last range.
5932	 * Filter it out and return if there is nothing left.
5933	 */
5934	len = (uint8_t *)endnz - (uint8_t *)buf;
5935	if (len == 0) {
5936		ctl_set_success(ctsio);
5937		goto done;
5938	}
5939
5940	mtx_lock(&lun->lun_lock);
5941	ptrlen = (struct ctl_ptr_len_flags *)
5942	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5943	ptrlen->ptr = (void *)buf;
5944	ptrlen->len = len;
5945	ptrlen->flags = byte2;
5946	ctl_check_blocked(lun);
5947	mtx_unlock(&lun->lun_lock);
5948
5949	retval = lun->backend->config_write((union ctl_io *)ctsio);
5950	return (retval);
5951
5952done:
5953	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5954		free(ctsio->kern_data_ptr, M_CTL);
5955		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5956	}
5957	ctl_done((union ctl_io *)ctsio);
5958	return (CTL_RETVAL_COMPLETE);
5959}
5960
5961/*
5962 * Note that this function currently doesn't actually do anything inside
5963 * CTL to enforce things if the DQue bit is turned on.
5964 *
5965 * Also note that this function can't be used in the default case, because
5966 * the DQue bit isn't set in the changeable mask for the control mode page
5967 * anyway.  This is just here as an example for how to implement a page
5968 * handler, and a placeholder in case we want to allow the user to turn
5969 * tagged queueing on and off.
5970 *
5971 * The D_SENSE bit handling is functional, however, and will turn
5972 * descriptor sense on and off for a given LUN.
5973 */
5974int
5975ctl_control_page_handler(struct ctl_scsiio *ctsio,
5976			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5977{
5978	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5979	struct ctl_lun *lun;
5980	struct ctl_softc *softc;
5981	int set_ua;
5982	uint32_t initidx;
5983
5984	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5985	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5986	set_ua = 0;
5987
5988	user_cp = (struct scsi_control_page *)page_ptr;
5989	current_cp = (struct scsi_control_page *)
5990		(page_index->page_data + (page_index->page_len *
5991		CTL_PAGE_CURRENT));
5992	saved_cp = (struct scsi_control_page *)
5993		(page_index->page_data + (page_index->page_len *
5994		CTL_PAGE_SAVED));
5995
5996	softc = control_softc;
5997
5998	mtx_lock(&lun->lun_lock);
5999	if (((current_cp->rlec & SCP_DSENSE) == 0)
6000	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6001		/*
6002		 * Descriptor sense is currently turned off and the user
6003		 * wants to turn it on.
6004		 */
6005		current_cp->rlec |= SCP_DSENSE;
6006		saved_cp->rlec |= SCP_DSENSE;
6007		lun->flags |= CTL_LUN_SENSE_DESC;
6008		set_ua = 1;
6009	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6010		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6011		/*
6012		 * Descriptor sense is currently turned on, and the user
6013		 * wants to turn it off.
6014		 */
6015		current_cp->rlec &= ~SCP_DSENSE;
6016		saved_cp->rlec &= ~SCP_DSENSE;
6017		lun->flags &= ~CTL_LUN_SENSE_DESC;
6018		set_ua = 1;
6019	}
6020	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6021	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6022		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6023		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6024		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6025		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6026		set_ua = 1;
6027	}
6028	if ((current_cp->eca_and_aen & SCP_SWP) !=
6029	    (user_cp->eca_and_aen & SCP_SWP)) {
6030		current_cp->eca_and_aen &= ~SCP_SWP;
6031		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6032		saved_cp->eca_and_aen &= ~SCP_SWP;
6033		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6034		set_ua = 1;
6035	}
6036	if (set_ua != 0) {
6037		int i;
6038		/*
6039		 * Let other initiators know that the mode
6040		 * parameters for this LUN have changed.
6041		 */
6042		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6043			if (i == initidx)
6044				continue;
6045
6046			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6047		}
6048	}
6049	mtx_unlock(&lun->lun_lock);
6050
6051	return (0);
6052}
6053
6054int
6055ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6056		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6057{
6058	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6059	struct ctl_lun *lun;
6060	int set_ua;
6061	uint32_t initidx;
6062
6063	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6064	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6065	set_ua = 0;
6066
6067	user_cp = (struct scsi_caching_page *)page_ptr;
6068	current_cp = (struct scsi_caching_page *)
6069		(page_index->page_data + (page_index->page_len *
6070		CTL_PAGE_CURRENT));
6071	saved_cp = (struct scsi_caching_page *)
6072		(page_index->page_data + (page_index->page_len *
6073		CTL_PAGE_SAVED));
6074
6075	mtx_lock(&lun->lun_lock);
6076	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6077	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6078		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6079		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6080		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6081		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6082		set_ua = 1;
6083	}
6084	if (set_ua != 0) {
6085		int i;
6086		/*
6087		 * Let other initiators know that the mode
6088		 * parameters for this LUN have changed.
6089		 */
6090		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6091			if (i == initidx)
6092				continue;
6093
6094			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6095		}
6096	}
6097	mtx_unlock(&lun->lun_lock);
6098
6099	return (0);
6100}
6101
6102int
6103ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6104				struct ctl_page_index *page_index,
6105				uint8_t *page_ptr)
6106{
6107	uint8_t *c;
6108	int i;
6109
6110	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6111	ctl_time_io_secs =
6112		(c[0] << 8) |
6113		(c[1] << 0) |
6114		0;
6115	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6116	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6117	printf("page data:");
6118	for (i=0; i<8; i++)
6119		printf(" %.2x",page_ptr[i]);
6120	printf("\n");
6121	return (0);
6122}
6123
6124int
6125ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6126			       struct ctl_page_index *page_index,
6127			       int pc)
6128{
6129	struct copan_debugconf_subpage *page;
6130
6131	page = (struct copan_debugconf_subpage *)page_index->page_data +
6132		(page_index->page_len * pc);
6133
6134	switch (pc) {
6135	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6136	case SMS_PAGE_CTRL_DEFAULT >> 6:
6137	case SMS_PAGE_CTRL_SAVED >> 6:
6138		/*
6139		 * We don't update the changable or default bits for this page.
6140		 */
6141		break;
6142	case SMS_PAGE_CTRL_CURRENT >> 6:
6143		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6144		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6145		break;
6146	default:
6147#ifdef NEEDTOPORT
6148		EPRINT(0, "Invalid PC %d!!", pc);
6149#endif /* NEEDTOPORT */
6150		break;
6151	}
6152	return (0);
6153}
6154
6155
6156static int
6157ctl_do_mode_select(union ctl_io *io)
6158{
6159	struct scsi_mode_page_header *page_header;
6160	struct ctl_page_index *page_index;
6161	struct ctl_scsiio *ctsio;
6162	int control_dev, page_len;
6163	int page_len_offset, page_len_size;
6164	union ctl_modepage_info *modepage_info;
6165	struct ctl_lun *lun;
6166	int *len_left, *len_used;
6167	int retval, i;
6168
6169	ctsio = &io->scsiio;
6170	page_index = NULL;
6171	page_len = 0;
6172	retval = CTL_RETVAL_COMPLETE;
6173
6174	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6175
6176	if (lun->be_lun->lun_type != T_DIRECT)
6177		control_dev = 1;
6178	else
6179		control_dev = 0;
6180
6181	modepage_info = (union ctl_modepage_info *)
6182		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6183	len_left = &modepage_info->header.len_left;
6184	len_used = &modepage_info->header.len_used;
6185
6186do_next_page:
6187
6188	page_header = (struct scsi_mode_page_header *)
6189		(ctsio->kern_data_ptr + *len_used);
6190
6191	if (*len_left == 0) {
6192		free(ctsio->kern_data_ptr, M_CTL);
6193		ctl_set_success(ctsio);
6194		ctl_done((union ctl_io *)ctsio);
6195		return (CTL_RETVAL_COMPLETE);
6196	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6197
6198		free(ctsio->kern_data_ptr, M_CTL);
6199		ctl_set_param_len_error(ctsio);
6200		ctl_done((union ctl_io *)ctsio);
6201		return (CTL_RETVAL_COMPLETE);
6202
6203	} else if ((page_header->page_code & SMPH_SPF)
6204		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6205
6206		free(ctsio->kern_data_ptr, M_CTL);
6207		ctl_set_param_len_error(ctsio);
6208		ctl_done((union ctl_io *)ctsio);
6209		return (CTL_RETVAL_COMPLETE);
6210	}
6211
6212
6213	/*
6214	 * XXX KDM should we do something with the block descriptor?
6215	 */
6216	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6217
6218		if ((control_dev != 0)
6219		 && (lun->mode_pages.index[i].page_flags &
6220		     CTL_PAGE_FLAG_DISK_ONLY))
6221			continue;
6222
6223		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6224		    (page_header->page_code & SMPH_PC_MASK))
6225			continue;
6226
6227		/*
6228		 * If neither page has a subpage code, then we've got a
6229		 * match.
6230		 */
6231		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6232		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6233			page_index = &lun->mode_pages.index[i];
6234			page_len = page_header->page_length;
6235			break;
6236		}
6237
6238		/*
6239		 * If both pages have subpages, then the subpage numbers
6240		 * have to match.
6241		 */
6242		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6243		  && (page_header->page_code & SMPH_SPF)) {
6244			struct scsi_mode_page_header_sp *sph;
6245
6246			sph = (struct scsi_mode_page_header_sp *)page_header;
6247
6248			if (lun->mode_pages.index[i].subpage ==
6249			    sph->subpage) {
6250				page_index = &lun->mode_pages.index[i];
6251				page_len = scsi_2btoul(sph->page_length);
6252				break;
6253			}
6254		}
6255	}
6256
6257	/*
6258	 * If we couldn't find the page, or if we don't have a mode select
6259	 * handler for it, send back an error to the user.
6260	 */
6261	if ((page_index == NULL)
6262	 || (page_index->select_handler == NULL)) {
6263		ctl_set_invalid_field(ctsio,
6264				      /*sks_valid*/ 1,
6265				      /*command*/ 0,
6266				      /*field*/ *len_used,
6267				      /*bit_valid*/ 0,
6268				      /*bit*/ 0);
6269		free(ctsio->kern_data_ptr, M_CTL);
6270		ctl_done((union ctl_io *)ctsio);
6271		return (CTL_RETVAL_COMPLETE);
6272	}
6273
6274	if (page_index->page_code & SMPH_SPF) {
6275		page_len_offset = 2;
6276		page_len_size = 2;
6277	} else {
6278		page_len_size = 1;
6279		page_len_offset = 1;
6280	}
6281
6282	/*
6283	 * If the length the initiator gives us isn't the one we specify in
6284	 * the mode page header, or if they didn't specify enough data in
6285	 * the CDB to avoid truncating this page, kick out the request.
6286	 */
6287	if ((page_len != (page_index->page_len - page_len_offset -
6288			  page_len_size))
6289	 || (*len_left < page_index->page_len)) {
6290
6291
6292		ctl_set_invalid_field(ctsio,
6293				      /*sks_valid*/ 1,
6294				      /*command*/ 0,
6295				      /*field*/ *len_used + page_len_offset,
6296				      /*bit_valid*/ 0,
6297				      /*bit*/ 0);
6298		free(ctsio->kern_data_ptr, M_CTL);
6299		ctl_done((union ctl_io *)ctsio);
6300		return (CTL_RETVAL_COMPLETE);
6301	}
6302
6303	/*
6304	 * Run through the mode page, checking to make sure that the bits
6305	 * the user changed are actually legal for him to change.
6306	 */
6307	for (i = 0; i < page_index->page_len; i++) {
6308		uint8_t *user_byte, *change_mask, *current_byte;
6309		int bad_bit;
6310		int j;
6311
6312		user_byte = (uint8_t *)page_header + i;
6313		change_mask = page_index->page_data +
6314			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6315		current_byte = page_index->page_data +
6316			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6317
6318		/*
6319		 * Check to see whether the user set any bits in this byte
6320		 * that he is not allowed to set.
6321		 */
6322		if ((*user_byte & ~(*change_mask)) ==
6323		    (*current_byte & ~(*change_mask)))
6324			continue;
6325
6326		/*
6327		 * Go through bit by bit to determine which one is illegal.
6328		 */
6329		bad_bit = 0;
6330		for (j = 7; j >= 0; j--) {
6331			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6332			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6333				bad_bit = i;
6334				break;
6335			}
6336		}
6337		ctl_set_invalid_field(ctsio,
6338				      /*sks_valid*/ 1,
6339				      /*command*/ 0,
6340				      /*field*/ *len_used + i,
6341				      /*bit_valid*/ 1,
6342				      /*bit*/ bad_bit);
6343		free(ctsio->kern_data_ptr, M_CTL);
6344		ctl_done((union ctl_io *)ctsio);
6345		return (CTL_RETVAL_COMPLETE);
6346	}
6347
6348	/*
6349	 * Decrement these before we call the page handler, since we may
6350	 * end up getting called back one way or another before the handler
6351	 * returns to this context.
6352	 */
6353	*len_left -= page_index->page_len;
6354	*len_used += page_index->page_len;
6355
6356	retval = page_index->select_handler(ctsio, page_index,
6357					    (uint8_t *)page_header);
6358
6359	/*
6360	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6361	 * wait until this queued command completes to finish processing
6362	 * the mode page.  If it returns anything other than
6363	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6364	 * already set the sense information, freed the data pointer, and
6365	 * completed the io for us.
6366	 */
6367	if (retval != CTL_RETVAL_COMPLETE)
6368		goto bailout_no_done;
6369
6370	/*
6371	 * If the initiator sent us more than one page, parse the next one.
6372	 */
6373	if (*len_left > 0)
6374		goto do_next_page;
6375
6376	ctl_set_success(ctsio);
6377	free(ctsio->kern_data_ptr, M_CTL);
6378	ctl_done((union ctl_io *)ctsio);
6379
6380bailout_no_done:
6381
6382	return (CTL_RETVAL_COMPLETE);
6383
6384}
6385
6386int
6387ctl_mode_select(struct ctl_scsiio *ctsio)
6388{
6389	int param_len, pf, sp;
6390	int header_size, bd_len;
6391	int len_left, len_used;
6392	struct ctl_page_index *page_index;
6393	struct ctl_lun *lun;
6394	int control_dev, page_len;
6395	union ctl_modepage_info *modepage_info;
6396	int retval;
6397
6398	pf = 0;
6399	sp = 0;
6400	page_len = 0;
6401	len_used = 0;
6402	len_left = 0;
6403	retval = 0;
6404	bd_len = 0;
6405	page_index = NULL;
6406
6407	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6408
6409	if (lun->be_lun->lun_type != T_DIRECT)
6410		control_dev = 1;
6411	else
6412		control_dev = 0;
6413
6414	switch (ctsio->cdb[0]) {
6415	case MODE_SELECT_6: {
6416		struct scsi_mode_select_6 *cdb;
6417
6418		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6419
6420		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6421		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6422
6423		param_len = cdb->length;
6424		header_size = sizeof(struct scsi_mode_header_6);
6425		break;
6426	}
6427	case MODE_SELECT_10: {
6428		struct scsi_mode_select_10 *cdb;
6429
6430		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6431
6432		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6433		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6434
6435		param_len = scsi_2btoul(cdb->length);
6436		header_size = sizeof(struct scsi_mode_header_10);
6437		break;
6438	}
6439	default:
6440		ctl_set_invalid_opcode(ctsio);
6441		ctl_done((union ctl_io *)ctsio);
6442		return (CTL_RETVAL_COMPLETE);
6443		break; /* NOTREACHED */
6444	}
6445
6446	/*
6447	 * From SPC-3:
6448	 * "A parameter list length of zero indicates that the Data-Out Buffer
6449	 * shall be empty. This condition shall not be considered as an error."
6450	 */
6451	if (param_len == 0) {
6452		ctl_set_success(ctsio);
6453		ctl_done((union ctl_io *)ctsio);
6454		return (CTL_RETVAL_COMPLETE);
6455	}
6456
6457	/*
6458	 * Since we'll hit this the first time through, prior to
6459	 * allocation, we don't need to free a data buffer here.
6460	 */
6461	if (param_len < header_size) {
6462		ctl_set_param_len_error(ctsio);
6463		ctl_done((union ctl_io *)ctsio);
6464		return (CTL_RETVAL_COMPLETE);
6465	}
6466
6467	/*
6468	 * Allocate the data buffer and grab the user's data.  In theory,
6469	 * we shouldn't have to sanity check the parameter list length here
6470	 * because the maximum size is 64K.  We should be able to malloc
6471	 * that much without too many problems.
6472	 */
6473	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6474		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6475		ctsio->kern_data_len = param_len;
6476		ctsio->kern_total_len = param_len;
6477		ctsio->kern_data_resid = 0;
6478		ctsio->kern_rel_offset = 0;
6479		ctsio->kern_sg_entries = 0;
6480		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6481		ctsio->be_move_done = ctl_config_move_done;
6482		ctl_datamove((union ctl_io *)ctsio);
6483
6484		return (CTL_RETVAL_COMPLETE);
6485	}
6486
6487	switch (ctsio->cdb[0]) {
6488	case MODE_SELECT_6: {
6489		struct scsi_mode_header_6 *mh6;
6490
6491		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6492		bd_len = mh6->blk_desc_len;
6493		break;
6494	}
6495	case MODE_SELECT_10: {
6496		struct scsi_mode_header_10 *mh10;
6497
6498		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6499		bd_len = scsi_2btoul(mh10->blk_desc_len);
6500		break;
6501	}
6502	default:
6503		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6504		break;
6505	}
6506
6507	if (param_len < (header_size + bd_len)) {
6508		free(ctsio->kern_data_ptr, M_CTL);
6509		ctl_set_param_len_error(ctsio);
6510		ctl_done((union ctl_io *)ctsio);
6511		return (CTL_RETVAL_COMPLETE);
6512	}
6513
6514	/*
6515	 * Set the IO_CONT flag, so that if this I/O gets passed to
6516	 * ctl_config_write_done(), it'll get passed back to
6517	 * ctl_do_mode_select() for further processing, or completion if
6518	 * we're all done.
6519	 */
6520	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6521	ctsio->io_cont = ctl_do_mode_select;
6522
6523	modepage_info = (union ctl_modepage_info *)
6524		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6525
6526	memset(modepage_info, 0, sizeof(*modepage_info));
6527
6528	len_left = param_len - header_size - bd_len;
6529	len_used = header_size + bd_len;
6530
6531	modepage_info->header.len_left = len_left;
6532	modepage_info->header.len_used = len_used;
6533
6534	return (ctl_do_mode_select((union ctl_io *)ctsio));
6535}
6536
6537int
6538ctl_mode_sense(struct ctl_scsiio *ctsio)
6539{
6540	struct ctl_lun *lun;
6541	int pc, page_code, dbd, llba, subpage;
6542	int alloc_len, page_len, header_len, total_len;
6543	struct scsi_mode_block_descr *block_desc;
6544	struct ctl_page_index *page_index;
6545	int control_dev;
6546
6547	dbd = 0;
6548	llba = 0;
6549	block_desc = NULL;
6550	page_index = NULL;
6551
6552	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6553
6554	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6555
6556	if (lun->be_lun->lun_type != T_DIRECT)
6557		control_dev = 1;
6558	else
6559		control_dev = 0;
6560
6561	switch (ctsio->cdb[0]) {
6562	case MODE_SENSE_6: {
6563		struct scsi_mode_sense_6 *cdb;
6564
6565		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6566
6567		header_len = sizeof(struct scsi_mode_hdr_6);
6568		if (cdb->byte2 & SMS_DBD)
6569			dbd = 1;
6570		else
6571			header_len += sizeof(struct scsi_mode_block_descr);
6572
6573		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6574		page_code = cdb->page & SMS_PAGE_CODE;
6575		subpage = cdb->subpage;
6576		alloc_len = cdb->length;
6577		break;
6578	}
6579	case MODE_SENSE_10: {
6580		struct scsi_mode_sense_10 *cdb;
6581
6582		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6583
6584		header_len = sizeof(struct scsi_mode_hdr_10);
6585
6586		if (cdb->byte2 & SMS_DBD)
6587			dbd = 1;
6588		else
6589			header_len += sizeof(struct scsi_mode_block_descr);
6590		if (cdb->byte2 & SMS10_LLBAA)
6591			llba = 1;
6592		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6593		page_code = cdb->page & SMS_PAGE_CODE;
6594		subpage = cdb->subpage;
6595		alloc_len = scsi_2btoul(cdb->length);
6596		break;
6597	}
6598	default:
6599		ctl_set_invalid_opcode(ctsio);
6600		ctl_done((union ctl_io *)ctsio);
6601		return (CTL_RETVAL_COMPLETE);
6602		break; /* NOTREACHED */
6603	}
6604
6605	/*
6606	 * We have to make a first pass through to calculate the size of
6607	 * the pages that match the user's query.  Then we allocate enough
6608	 * memory to hold it, and actually copy the data into the buffer.
6609	 */
6610	switch (page_code) {
6611	case SMS_ALL_PAGES_PAGE: {
6612		int i;
6613
6614		page_len = 0;
6615
6616		/*
6617		 * At the moment, values other than 0 and 0xff here are
6618		 * reserved according to SPC-3.
6619		 */
6620		if ((subpage != SMS_SUBPAGE_PAGE_0)
6621		 && (subpage != SMS_SUBPAGE_ALL)) {
6622			ctl_set_invalid_field(ctsio,
6623					      /*sks_valid*/ 1,
6624					      /*command*/ 1,
6625					      /*field*/ 3,
6626					      /*bit_valid*/ 0,
6627					      /*bit*/ 0);
6628			ctl_done((union ctl_io *)ctsio);
6629			return (CTL_RETVAL_COMPLETE);
6630		}
6631
6632		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6633			if ((control_dev != 0)
6634			 && (lun->mode_pages.index[i].page_flags &
6635			     CTL_PAGE_FLAG_DISK_ONLY))
6636				continue;
6637
6638			/*
6639			 * We don't use this subpage if the user didn't
6640			 * request all subpages.
6641			 */
6642			if ((lun->mode_pages.index[i].subpage != 0)
6643			 && (subpage == SMS_SUBPAGE_PAGE_0))
6644				continue;
6645
6646#if 0
6647			printf("found page %#x len %d\n",
6648			       lun->mode_pages.index[i].page_code &
6649			       SMPH_PC_MASK,
6650			       lun->mode_pages.index[i].page_len);
6651#endif
6652			page_len += lun->mode_pages.index[i].page_len;
6653		}
6654		break;
6655	}
6656	default: {
6657		int i;
6658
6659		page_len = 0;
6660
6661		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6662			/* Look for the right page code */
6663			if ((lun->mode_pages.index[i].page_code &
6664			     SMPH_PC_MASK) != page_code)
6665				continue;
6666
6667			/* Look for the right subpage or the subpage wildcard*/
6668			if ((lun->mode_pages.index[i].subpage != subpage)
6669			 && (subpage != SMS_SUBPAGE_ALL))
6670				continue;
6671
6672			/* Make sure the page is supported for this dev type */
6673			if ((control_dev != 0)
6674			 && (lun->mode_pages.index[i].page_flags &
6675			     CTL_PAGE_FLAG_DISK_ONLY))
6676				continue;
6677
6678#if 0
6679			printf("found page %#x len %d\n",
6680			       lun->mode_pages.index[i].page_code &
6681			       SMPH_PC_MASK,
6682			       lun->mode_pages.index[i].page_len);
6683#endif
6684
6685			page_len += lun->mode_pages.index[i].page_len;
6686		}
6687
6688		if (page_len == 0) {
6689			ctl_set_invalid_field(ctsio,
6690					      /*sks_valid*/ 1,
6691					      /*command*/ 1,
6692					      /*field*/ 2,
6693					      /*bit_valid*/ 1,
6694					      /*bit*/ 5);
6695			ctl_done((union ctl_io *)ctsio);
6696			return (CTL_RETVAL_COMPLETE);
6697		}
6698		break;
6699	}
6700	}
6701
6702	total_len = header_len + page_len;
6703#if 0
6704	printf("header_len = %d, page_len = %d, total_len = %d\n",
6705	       header_len, page_len, total_len);
6706#endif
6707
6708	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6709	ctsio->kern_sg_entries = 0;
6710	ctsio->kern_data_resid = 0;
6711	ctsio->kern_rel_offset = 0;
6712	if (total_len < alloc_len) {
6713		ctsio->residual = alloc_len - total_len;
6714		ctsio->kern_data_len = total_len;
6715		ctsio->kern_total_len = total_len;
6716	} else {
6717		ctsio->residual = 0;
6718		ctsio->kern_data_len = alloc_len;
6719		ctsio->kern_total_len = alloc_len;
6720	}
6721
6722	switch (ctsio->cdb[0]) {
6723	case MODE_SENSE_6: {
6724		struct scsi_mode_hdr_6 *header;
6725
6726		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6727
6728		header->datalen = ctl_min(total_len - 1, 254);
6729		if (control_dev == 0) {
6730			header->dev_specific = 0x10; /* DPOFUA */
6731			if ((lun->flags & CTL_LUN_READONLY) ||
6732			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6733			    .eca_and_aen & SCP_SWP) != 0)
6734				    header->dev_specific |= 0x80; /* WP */
6735		}
6736		if (dbd)
6737			header->block_descr_len = 0;
6738		else
6739			header->block_descr_len =
6740				sizeof(struct scsi_mode_block_descr);
6741		block_desc = (struct scsi_mode_block_descr *)&header[1];
6742		break;
6743	}
6744	case MODE_SENSE_10: {
6745		struct scsi_mode_hdr_10 *header;
6746		int datalen;
6747
6748		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6749
6750		datalen = ctl_min(total_len - 2, 65533);
6751		scsi_ulto2b(datalen, header->datalen);
6752		if (control_dev == 0) {
6753			header->dev_specific = 0x10; /* DPOFUA */
6754			if ((lun->flags & CTL_LUN_READONLY) ||
6755			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6756			    .eca_and_aen & SCP_SWP) != 0)
6757				    header->dev_specific |= 0x80; /* WP */
6758		}
6759		if (dbd)
6760			scsi_ulto2b(0, header->block_descr_len);
6761		else
6762			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6763				    header->block_descr_len);
6764		block_desc = (struct scsi_mode_block_descr *)&header[1];
6765		break;
6766	}
6767	default:
6768		panic("invalid CDB type %#x", ctsio->cdb[0]);
6769		break; /* NOTREACHED */
6770	}
6771
6772	/*
6773	 * If we've got a disk, use its blocksize in the block
6774	 * descriptor.  Otherwise, just set it to 0.
6775	 */
6776	if (dbd == 0) {
6777		if (control_dev == 0)
6778			scsi_ulto3b(lun->be_lun->blocksize,
6779				    block_desc->block_len);
6780		else
6781			scsi_ulto3b(0, block_desc->block_len);
6782	}
6783
6784	switch (page_code) {
6785	case SMS_ALL_PAGES_PAGE: {
6786		int i, data_used;
6787
6788		data_used = header_len;
6789		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6790			struct ctl_page_index *page_index;
6791
6792			page_index = &lun->mode_pages.index[i];
6793
6794			if ((control_dev != 0)
6795			 && (page_index->page_flags &
6796			    CTL_PAGE_FLAG_DISK_ONLY))
6797				continue;
6798
6799			/*
6800			 * We don't use this subpage if the user didn't
6801			 * request all subpages.  We already checked (above)
6802			 * to make sure the user only specified a subpage
6803			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6804			 */
6805			if ((page_index->subpage != 0)
6806			 && (subpage == SMS_SUBPAGE_PAGE_0))
6807				continue;
6808
6809			/*
6810			 * Call the handler, if it exists, to update the
6811			 * page to the latest values.
6812			 */
6813			if (page_index->sense_handler != NULL)
6814				page_index->sense_handler(ctsio, page_index,pc);
6815
6816			memcpy(ctsio->kern_data_ptr + data_used,
6817			       page_index->page_data +
6818			       (page_index->page_len * pc),
6819			       page_index->page_len);
6820			data_used += page_index->page_len;
6821		}
6822		break;
6823	}
6824	default: {
6825		int i, data_used;
6826
6827		data_used = header_len;
6828
6829		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6830			struct ctl_page_index *page_index;
6831
6832			page_index = &lun->mode_pages.index[i];
6833
6834			/* Look for the right page code */
6835			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6836				continue;
6837
6838			/* Look for the right subpage or the subpage wildcard*/
6839			if ((page_index->subpage != subpage)
6840			 && (subpage != SMS_SUBPAGE_ALL))
6841				continue;
6842
6843			/* Make sure the page is supported for this dev type */
6844			if ((control_dev != 0)
6845			 && (page_index->page_flags &
6846			     CTL_PAGE_FLAG_DISK_ONLY))
6847				continue;
6848
6849			/*
6850			 * Call the handler, if it exists, to update the
6851			 * page to the latest values.
6852			 */
6853			if (page_index->sense_handler != NULL)
6854				page_index->sense_handler(ctsio, page_index,pc);
6855
6856			memcpy(ctsio->kern_data_ptr + data_used,
6857			       page_index->page_data +
6858			       (page_index->page_len * pc),
6859			       page_index->page_len);
6860			data_used += page_index->page_len;
6861		}
6862		break;
6863	}
6864	}
6865
6866	ctl_set_success(ctsio);
6867	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6868	ctsio->be_move_done = ctl_config_move_done;
6869	ctl_datamove((union ctl_io *)ctsio);
6870	return (CTL_RETVAL_COMPLETE);
6871}
6872
6873int
6874ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6875			       struct ctl_page_index *page_index,
6876			       int pc)
6877{
6878	struct ctl_lun *lun;
6879	struct scsi_log_param_header *phdr;
6880	uint8_t *data;
6881	uint64_t val;
6882
6883	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6884	data = page_index->page_data;
6885
6886	if (lun->backend->lun_attr != NULL &&
6887	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6888	     != UINT64_MAX) {
6889		phdr = (struct scsi_log_param_header *)data;
6890		scsi_ulto2b(0x0001, phdr->param_code);
6891		phdr->param_control = SLP_LBIN | SLP_LP;
6892		phdr->param_len = 8;
6893		data = (uint8_t *)(phdr + 1);
6894		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6895		data[4] = 0x02; /* per-pool */
6896		data += phdr->param_len;
6897	}
6898
6899	if (lun->backend->lun_attr != NULL &&
6900	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6901	     != UINT64_MAX) {
6902		phdr = (struct scsi_log_param_header *)data;
6903		scsi_ulto2b(0x0002, phdr->param_code);
6904		phdr->param_control = SLP_LBIN | SLP_LP;
6905		phdr->param_len = 8;
6906		data = (uint8_t *)(phdr + 1);
6907		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6908		data[4] = 0x01; /* per-LUN */
6909		data += phdr->param_len;
6910	}
6911
6912	if (lun->backend->lun_attr != NULL &&
6913	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6914	     != UINT64_MAX) {
6915		phdr = (struct scsi_log_param_header *)data;
6916		scsi_ulto2b(0x00f1, phdr->param_code);
6917		phdr->param_control = SLP_LBIN | SLP_LP;
6918		phdr->param_len = 8;
6919		data = (uint8_t *)(phdr + 1);
6920		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6921		data[4] = 0x02; /* per-pool */
6922		data += phdr->param_len;
6923	}
6924
6925	if (lun->backend->lun_attr != NULL &&
6926	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6927	     != UINT64_MAX) {
6928		phdr = (struct scsi_log_param_header *)data;
6929		scsi_ulto2b(0x00f2, phdr->param_code);
6930		phdr->param_control = SLP_LBIN | SLP_LP;
6931		phdr->param_len = 8;
6932		data = (uint8_t *)(phdr + 1);
6933		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6934		data[4] = 0x02; /* per-pool */
6935		data += phdr->param_len;
6936	}
6937
6938	page_index->page_len = data - page_index->page_data;
6939	return (0);
6940}
6941
6942int
6943ctl_log_sense(struct ctl_scsiio *ctsio)
6944{
6945	struct ctl_lun *lun;
6946	int i, pc, page_code, subpage;
6947	int alloc_len, total_len;
6948	struct ctl_page_index *page_index;
6949	struct scsi_log_sense *cdb;
6950	struct scsi_log_header *header;
6951
6952	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6953
6954	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6955	cdb = (struct scsi_log_sense *)ctsio->cdb;
6956	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6957	page_code = cdb->page & SLS_PAGE_CODE;
6958	subpage = cdb->subpage;
6959	alloc_len = scsi_2btoul(cdb->length);
6960
6961	page_index = NULL;
6962	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6963		page_index = &lun->log_pages.index[i];
6964
6965		/* Look for the right page code */
6966		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6967			continue;
6968
6969		/* Look for the right subpage or the subpage wildcard*/
6970		if (page_index->subpage != subpage)
6971			continue;
6972
6973		break;
6974	}
6975	if (i >= CTL_NUM_LOG_PAGES) {
6976		ctl_set_invalid_field(ctsio,
6977				      /*sks_valid*/ 1,
6978				      /*command*/ 1,
6979				      /*field*/ 2,
6980				      /*bit_valid*/ 0,
6981				      /*bit*/ 0);
6982		ctl_done((union ctl_io *)ctsio);
6983		return (CTL_RETVAL_COMPLETE);
6984	}
6985
6986	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6987
6988	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6989	ctsio->kern_sg_entries = 0;
6990	ctsio->kern_data_resid = 0;
6991	ctsio->kern_rel_offset = 0;
6992	if (total_len < alloc_len) {
6993		ctsio->residual = alloc_len - total_len;
6994		ctsio->kern_data_len = total_len;
6995		ctsio->kern_total_len = total_len;
6996	} else {
6997		ctsio->residual = 0;
6998		ctsio->kern_data_len = alloc_len;
6999		ctsio->kern_total_len = alloc_len;
7000	}
7001
7002	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7003	header->page = page_index->page_code;
7004	if (page_index->subpage) {
7005		header->page |= SL_SPF;
7006		header->subpage = page_index->subpage;
7007	}
7008	scsi_ulto2b(page_index->page_len, header->datalen);
7009
7010	/*
7011	 * Call the handler, if it exists, to update the
7012	 * page to the latest values.
7013	 */
7014	if (page_index->sense_handler != NULL)
7015		page_index->sense_handler(ctsio, page_index, pc);
7016
7017	memcpy(header + 1, page_index->page_data, page_index->page_len);
7018
7019	ctl_set_success(ctsio);
7020	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7021	ctsio->be_move_done = ctl_config_move_done;
7022	ctl_datamove((union ctl_io *)ctsio);
7023	return (CTL_RETVAL_COMPLETE);
7024}
7025
7026int
7027ctl_read_capacity(struct ctl_scsiio *ctsio)
7028{
7029	struct scsi_read_capacity *cdb;
7030	struct scsi_read_capacity_data *data;
7031	struct ctl_lun *lun;
7032	uint32_t lba;
7033
7034	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7035
7036	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7037
7038	lba = scsi_4btoul(cdb->addr);
7039	if (((cdb->pmi & SRC_PMI) == 0)
7040	 && (lba != 0)) {
7041		ctl_set_invalid_field(/*ctsio*/ ctsio,
7042				      /*sks_valid*/ 1,
7043				      /*command*/ 1,
7044				      /*field*/ 2,
7045				      /*bit_valid*/ 0,
7046				      /*bit*/ 0);
7047		ctl_done((union ctl_io *)ctsio);
7048		return (CTL_RETVAL_COMPLETE);
7049	}
7050
7051	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7052
7053	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7054	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7055	ctsio->residual = 0;
7056	ctsio->kern_data_len = sizeof(*data);
7057	ctsio->kern_total_len = sizeof(*data);
7058	ctsio->kern_data_resid = 0;
7059	ctsio->kern_rel_offset = 0;
7060	ctsio->kern_sg_entries = 0;
7061
7062	/*
7063	 * If the maximum LBA is greater than 0xfffffffe, the user must
7064	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7065	 * serivce action set.
7066	 */
7067	if (lun->be_lun->maxlba > 0xfffffffe)
7068		scsi_ulto4b(0xffffffff, data->addr);
7069	else
7070		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7071
7072	/*
7073	 * XXX KDM this may not be 512 bytes...
7074	 */
7075	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7076
7077	ctl_set_success(ctsio);
7078	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7079	ctsio->be_move_done = ctl_config_move_done;
7080	ctl_datamove((union ctl_io *)ctsio);
7081	return (CTL_RETVAL_COMPLETE);
7082}
7083
7084int
7085ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7086{
7087	struct scsi_read_capacity_16 *cdb;
7088	struct scsi_read_capacity_data_long *data;
7089	struct ctl_lun *lun;
7090	uint64_t lba;
7091	uint32_t alloc_len;
7092
7093	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7094
7095	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7096
7097	alloc_len = scsi_4btoul(cdb->alloc_len);
7098	lba = scsi_8btou64(cdb->addr);
7099
7100	if ((cdb->reladr & SRC16_PMI)
7101	 && (lba != 0)) {
7102		ctl_set_invalid_field(/*ctsio*/ ctsio,
7103				      /*sks_valid*/ 1,
7104				      /*command*/ 1,
7105				      /*field*/ 2,
7106				      /*bit_valid*/ 0,
7107				      /*bit*/ 0);
7108		ctl_done((union ctl_io *)ctsio);
7109		return (CTL_RETVAL_COMPLETE);
7110	}
7111
7112	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7113
7114	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7115	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7116
7117	if (sizeof(*data) < alloc_len) {
7118		ctsio->residual = alloc_len - sizeof(*data);
7119		ctsio->kern_data_len = sizeof(*data);
7120		ctsio->kern_total_len = sizeof(*data);
7121	} else {
7122		ctsio->residual = 0;
7123		ctsio->kern_data_len = alloc_len;
7124		ctsio->kern_total_len = alloc_len;
7125	}
7126	ctsio->kern_data_resid = 0;
7127	ctsio->kern_rel_offset = 0;
7128	ctsio->kern_sg_entries = 0;
7129
7130	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7131	/* XXX KDM this may not be 512 bytes... */
7132	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7133	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7134	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7135	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7136		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7137
7138	ctl_set_success(ctsio);
7139	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7140	ctsio->be_move_done = ctl_config_move_done;
7141	ctl_datamove((union ctl_io *)ctsio);
7142	return (CTL_RETVAL_COMPLETE);
7143}
7144
7145int
7146ctl_read_defect(struct ctl_scsiio *ctsio)
7147{
7148	struct scsi_read_defect_data_10 *ccb10;
7149	struct scsi_read_defect_data_12 *ccb12;
7150	struct scsi_read_defect_data_hdr_10 *data10;
7151	struct scsi_read_defect_data_hdr_12 *data12;
7152	uint32_t alloc_len, data_len;
7153	uint8_t format;
7154
7155	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7156
7157	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7158		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7159		format = ccb10->format;
7160		alloc_len = scsi_2btoul(ccb10->alloc_length);
7161		data_len = sizeof(*data10);
7162	} else {
7163		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7164		format = ccb12->format;
7165		alloc_len = scsi_4btoul(ccb12->alloc_length);
7166		data_len = sizeof(*data12);
7167	}
7168	if (alloc_len == 0) {
7169		ctl_set_success(ctsio);
7170		ctl_done((union ctl_io *)ctsio);
7171		return (CTL_RETVAL_COMPLETE);
7172	}
7173
7174	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7175	if (data_len < alloc_len) {
7176		ctsio->residual = alloc_len - data_len;
7177		ctsio->kern_data_len = data_len;
7178		ctsio->kern_total_len = data_len;
7179	} else {
7180		ctsio->residual = 0;
7181		ctsio->kern_data_len = alloc_len;
7182		ctsio->kern_total_len = alloc_len;
7183	}
7184	ctsio->kern_data_resid = 0;
7185	ctsio->kern_rel_offset = 0;
7186	ctsio->kern_sg_entries = 0;
7187
7188	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7189		data10 = (struct scsi_read_defect_data_hdr_10 *)
7190		    ctsio->kern_data_ptr;
7191		data10->format = format;
7192		scsi_ulto2b(0, data10->length);
7193	} else {
7194		data12 = (struct scsi_read_defect_data_hdr_12 *)
7195		    ctsio->kern_data_ptr;
7196		data12->format = format;
7197		scsi_ulto2b(0, data12->generation);
7198		scsi_ulto4b(0, data12->length);
7199	}
7200
7201	ctl_set_success(ctsio);
7202	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7203	ctsio->be_move_done = ctl_config_move_done;
7204	ctl_datamove((union ctl_io *)ctsio);
7205	return (CTL_RETVAL_COMPLETE);
7206}
7207
7208int
7209ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7210{
7211	struct scsi_maintenance_in *cdb;
7212	int retval;
7213	int alloc_len, ext, total_len = 0, g, p, pc, pg, gs, os;
7214	int num_target_port_groups, num_target_ports;
7215	struct ctl_lun *lun;
7216	struct ctl_softc *softc;
7217	struct ctl_port *port;
7218	struct scsi_target_group_data *rtg_ptr;
7219	struct scsi_target_group_data_extended *rtg_ext_ptr;
7220	struct scsi_target_port_group_descriptor *tpg_desc;
7221
7222	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7223
7224	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7225	softc = control_softc;
7226	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7227
7228	retval = CTL_RETVAL_COMPLETE;
7229
7230	switch (cdb->byte2 & STG_PDF_MASK) {
7231	case STG_PDF_LENGTH:
7232		ext = 0;
7233		break;
7234	case STG_PDF_EXTENDED:
7235		ext = 1;
7236		break;
7237	default:
7238		ctl_set_invalid_field(/*ctsio*/ ctsio,
7239				      /*sks_valid*/ 1,
7240				      /*command*/ 1,
7241				      /*field*/ 2,
7242				      /*bit_valid*/ 1,
7243				      /*bit*/ 5);
7244		ctl_done((union ctl_io *)ctsio);
7245		return(retval);
7246	}
7247
7248	if (softc->is_single)
7249		num_target_port_groups = 1;
7250	else
7251		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7252	num_target_ports = 0;
7253	mtx_lock(&softc->ctl_lock);
7254	STAILQ_FOREACH(port, &softc->port_list, links) {
7255		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7256			continue;
7257		if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7258			continue;
7259		num_target_ports++;
7260	}
7261	mtx_unlock(&softc->ctl_lock);
7262
7263	if (ext)
7264		total_len = sizeof(struct scsi_target_group_data_extended);
7265	else
7266		total_len = sizeof(struct scsi_target_group_data);
7267	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7268		num_target_port_groups +
7269	    sizeof(struct scsi_target_port_descriptor) *
7270		num_target_ports * num_target_port_groups;
7271
7272	alloc_len = scsi_4btoul(cdb->length);
7273
7274	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7275
7276	ctsio->kern_sg_entries = 0;
7277
7278	if (total_len < alloc_len) {
7279		ctsio->residual = alloc_len - total_len;
7280		ctsio->kern_data_len = total_len;
7281		ctsio->kern_total_len = total_len;
7282	} else {
7283		ctsio->residual = 0;
7284		ctsio->kern_data_len = alloc_len;
7285		ctsio->kern_total_len = alloc_len;
7286	}
7287	ctsio->kern_data_resid = 0;
7288	ctsio->kern_rel_offset = 0;
7289
7290	if (ext) {
7291		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7292		    ctsio->kern_data_ptr;
7293		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7294		rtg_ext_ptr->format_type = 0x10;
7295		rtg_ext_ptr->implicit_transition_time = 0;
7296		tpg_desc = &rtg_ext_ptr->groups[0];
7297	} else {
7298		rtg_ptr = (struct scsi_target_group_data *)
7299		    ctsio->kern_data_ptr;
7300		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7301		tpg_desc = &rtg_ptr->groups[0];
7302	}
7303
7304	mtx_lock(&softc->ctl_lock);
7305	pg = softc->port_offset / CTL_MAX_PORTS;
7306	if (softc->flags & CTL_FLAG_ACTIVE_SHELF) {
7307		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY) {
7308			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7309			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7310		} else if (lun->flags & CTL_LUN_PRIMARY_SC) {
7311			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7312			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7313		} else {
7314			gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7315			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7316		}
7317	} else {
7318		gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7319		os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7320	}
7321	for (g = 0; g < num_target_port_groups; g++) {
7322		tpg_desc->pref_state = (g == pg) ? gs : os;
7323		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP;
7324		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7325		tpg_desc->status = TPG_IMPLICIT;
7326		pc = 0;
7327		STAILQ_FOREACH(port, &softc->port_list, links) {
7328			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7329				continue;
7330			if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7331			    CTL_MAX_LUNS)
7332				continue;
7333			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7334			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7335			    relative_target_port_identifier);
7336			pc++;
7337		}
7338		tpg_desc->target_port_count = pc;
7339		tpg_desc = (struct scsi_target_port_group_descriptor *)
7340		    &tpg_desc->descriptors[pc];
7341	}
7342	mtx_unlock(&softc->ctl_lock);
7343
7344	ctl_set_success(ctsio);
7345	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7346	ctsio->be_move_done = ctl_config_move_done;
7347	ctl_datamove((union ctl_io *)ctsio);
7348	return(retval);
7349}
7350
7351int
7352ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7353{
7354	struct ctl_lun *lun;
7355	struct scsi_report_supported_opcodes *cdb;
7356	const struct ctl_cmd_entry *entry, *sentry;
7357	struct scsi_report_supported_opcodes_all *all;
7358	struct scsi_report_supported_opcodes_descr *descr;
7359	struct scsi_report_supported_opcodes_one *one;
7360	int retval;
7361	int alloc_len, total_len;
7362	int opcode, service_action, i, j, num;
7363
7364	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7365
7366	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7367	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7368
7369	retval = CTL_RETVAL_COMPLETE;
7370
7371	opcode = cdb->requested_opcode;
7372	service_action = scsi_2btoul(cdb->requested_service_action);
7373	switch (cdb->options & RSO_OPTIONS_MASK) {
7374	case RSO_OPTIONS_ALL:
7375		num = 0;
7376		for (i = 0; i < 256; i++) {
7377			entry = &ctl_cmd_table[i];
7378			if (entry->flags & CTL_CMD_FLAG_SA5) {
7379				for (j = 0; j < 32; j++) {
7380					sentry = &((const struct ctl_cmd_entry *)
7381					    entry->execute)[j];
7382					if (ctl_cmd_applicable(
7383					    lun->be_lun->lun_type, sentry))
7384						num++;
7385				}
7386			} else {
7387				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7388				    entry))
7389					num++;
7390			}
7391		}
7392		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7393		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7394		break;
7395	case RSO_OPTIONS_OC:
7396		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7397			ctl_set_invalid_field(/*ctsio*/ ctsio,
7398					      /*sks_valid*/ 1,
7399					      /*command*/ 1,
7400					      /*field*/ 2,
7401					      /*bit_valid*/ 1,
7402					      /*bit*/ 2);
7403			ctl_done((union ctl_io *)ctsio);
7404			return (CTL_RETVAL_COMPLETE);
7405		}
7406		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7407		break;
7408	case RSO_OPTIONS_OC_SA:
7409		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7410		    service_action >= 32) {
7411			ctl_set_invalid_field(/*ctsio*/ ctsio,
7412					      /*sks_valid*/ 1,
7413					      /*command*/ 1,
7414					      /*field*/ 2,
7415					      /*bit_valid*/ 1,
7416					      /*bit*/ 2);
7417			ctl_done((union ctl_io *)ctsio);
7418			return (CTL_RETVAL_COMPLETE);
7419		}
7420		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7421		break;
7422	default:
7423		ctl_set_invalid_field(/*ctsio*/ ctsio,
7424				      /*sks_valid*/ 1,
7425				      /*command*/ 1,
7426				      /*field*/ 2,
7427				      /*bit_valid*/ 1,
7428				      /*bit*/ 2);
7429		ctl_done((union ctl_io *)ctsio);
7430		return (CTL_RETVAL_COMPLETE);
7431	}
7432
7433	alloc_len = scsi_4btoul(cdb->length);
7434
7435	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7436
7437	ctsio->kern_sg_entries = 0;
7438
7439	if (total_len < alloc_len) {
7440		ctsio->residual = alloc_len - total_len;
7441		ctsio->kern_data_len = total_len;
7442		ctsio->kern_total_len = total_len;
7443	} else {
7444		ctsio->residual = 0;
7445		ctsio->kern_data_len = alloc_len;
7446		ctsio->kern_total_len = alloc_len;
7447	}
7448	ctsio->kern_data_resid = 0;
7449	ctsio->kern_rel_offset = 0;
7450
7451	switch (cdb->options & RSO_OPTIONS_MASK) {
7452	case RSO_OPTIONS_ALL:
7453		all = (struct scsi_report_supported_opcodes_all *)
7454		    ctsio->kern_data_ptr;
7455		num = 0;
7456		for (i = 0; i < 256; i++) {
7457			entry = &ctl_cmd_table[i];
7458			if (entry->flags & CTL_CMD_FLAG_SA5) {
7459				for (j = 0; j < 32; j++) {
7460					sentry = &((const struct ctl_cmd_entry *)
7461					    entry->execute)[j];
7462					if (!ctl_cmd_applicable(
7463					    lun->be_lun->lun_type, sentry))
7464						continue;
7465					descr = &all->descr[num++];
7466					descr->opcode = i;
7467					scsi_ulto2b(j, descr->service_action);
7468					descr->flags = RSO_SERVACTV;
7469					scsi_ulto2b(sentry->length,
7470					    descr->cdb_length);
7471				}
7472			} else {
7473				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7474				    entry))
7475					continue;
7476				descr = &all->descr[num++];
7477				descr->opcode = i;
7478				scsi_ulto2b(0, descr->service_action);
7479				descr->flags = 0;
7480				scsi_ulto2b(entry->length, descr->cdb_length);
7481			}
7482		}
7483		scsi_ulto4b(
7484		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7485		    all->length);
7486		break;
7487	case RSO_OPTIONS_OC:
7488		one = (struct scsi_report_supported_opcodes_one *)
7489		    ctsio->kern_data_ptr;
7490		entry = &ctl_cmd_table[opcode];
7491		goto fill_one;
7492	case RSO_OPTIONS_OC_SA:
7493		one = (struct scsi_report_supported_opcodes_one *)
7494		    ctsio->kern_data_ptr;
7495		entry = &ctl_cmd_table[opcode];
7496		entry = &((const struct ctl_cmd_entry *)
7497		    entry->execute)[service_action];
7498fill_one:
7499		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7500			one->support = 3;
7501			scsi_ulto2b(entry->length, one->cdb_length);
7502			one->cdb_usage[0] = opcode;
7503			memcpy(&one->cdb_usage[1], entry->usage,
7504			    entry->length - 1);
7505		} else
7506			one->support = 1;
7507		break;
7508	}
7509
7510	ctl_set_success(ctsio);
7511	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7512	ctsio->be_move_done = ctl_config_move_done;
7513	ctl_datamove((union ctl_io *)ctsio);
7514	return(retval);
7515}
7516
7517int
7518ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7519{
7520	struct scsi_report_supported_tmf *cdb;
7521	struct scsi_report_supported_tmf_data *data;
7522	int retval;
7523	int alloc_len, total_len;
7524
7525	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7526
7527	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7528
7529	retval = CTL_RETVAL_COMPLETE;
7530
7531	total_len = sizeof(struct scsi_report_supported_tmf_data);
7532	alloc_len = scsi_4btoul(cdb->length);
7533
7534	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7535
7536	ctsio->kern_sg_entries = 0;
7537
7538	if (total_len < alloc_len) {
7539		ctsio->residual = alloc_len - total_len;
7540		ctsio->kern_data_len = total_len;
7541		ctsio->kern_total_len = total_len;
7542	} else {
7543		ctsio->residual = 0;
7544		ctsio->kern_data_len = alloc_len;
7545		ctsio->kern_total_len = alloc_len;
7546	}
7547	ctsio->kern_data_resid = 0;
7548	ctsio->kern_rel_offset = 0;
7549
7550	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7551	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7552	data->byte2 |= RST_ITNRS;
7553
7554	ctl_set_success(ctsio);
7555	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7556	ctsio->be_move_done = ctl_config_move_done;
7557	ctl_datamove((union ctl_io *)ctsio);
7558	return (retval);
7559}
7560
7561int
7562ctl_report_timestamp(struct ctl_scsiio *ctsio)
7563{
7564	struct scsi_report_timestamp *cdb;
7565	struct scsi_report_timestamp_data *data;
7566	struct timeval tv;
7567	int64_t timestamp;
7568	int retval;
7569	int alloc_len, total_len;
7570
7571	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7572
7573	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7574
7575	retval = CTL_RETVAL_COMPLETE;
7576
7577	total_len = sizeof(struct scsi_report_timestamp_data);
7578	alloc_len = scsi_4btoul(cdb->length);
7579
7580	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7581
7582	ctsio->kern_sg_entries = 0;
7583
7584	if (total_len < alloc_len) {
7585		ctsio->residual = alloc_len - total_len;
7586		ctsio->kern_data_len = total_len;
7587		ctsio->kern_total_len = total_len;
7588	} else {
7589		ctsio->residual = 0;
7590		ctsio->kern_data_len = alloc_len;
7591		ctsio->kern_total_len = alloc_len;
7592	}
7593	ctsio->kern_data_resid = 0;
7594	ctsio->kern_rel_offset = 0;
7595
7596	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7597	scsi_ulto2b(sizeof(*data) - 2, data->length);
7598	data->origin = RTS_ORIG_OUTSIDE;
7599	getmicrotime(&tv);
7600	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7601	scsi_ulto4b(timestamp >> 16, data->timestamp);
7602	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7603
7604	ctl_set_success(ctsio);
7605	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7606	ctsio->be_move_done = ctl_config_move_done;
7607	ctl_datamove((union ctl_io *)ctsio);
7608	return (retval);
7609}
7610
7611int
7612ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7613{
7614	struct scsi_per_res_in *cdb;
7615	int alloc_len, total_len = 0;
7616	/* struct scsi_per_res_in_rsrv in_data; */
7617	struct ctl_lun *lun;
7618	struct ctl_softc *softc;
7619
7620	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7621
7622	softc = control_softc;
7623
7624	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7625
7626	alloc_len = scsi_2btoul(cdb->length);
7627
7628	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7629
7630retry:
7631	mtx_lock(&lun->lun_lock);
7632	switch (cdb->action) {
7633	case SPRI_RK: /* read keys */
7634		total_len = sizeof(struct scsi_per_res_in_keys) +
7635			lun->pr_key_count *
7636			sizeof(struct scsi_per_res_key);
7637		break;
7638	case SPRI_RR: /* read reservation */
7639		if (lun->flags & CTL_LUN_PR_RESERVED)
7640			total_len = sizeof(struct scsi_per_res_in_rsrv);
7641		else
7642			total_len = sizeof(struct scsi_per_res_in_header);
7643		break;
7644	case SPRI_RC: /* report capabilities */
7645		total_len = sizeof(struct scsi_per_res_cap);
7646		break;
7647	case SPRI_RS: /* read full status */
7648		total_len = sizeof(struct scsi_per_res_in_header) +
7649		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7650		    lun->pr_key_count;
7651		break;
7652	default:
7653		panic("Invalid PR type %x", cdb->action);
7654	}
7655	mtx_unlock(&lun->lun_lock);
7656
7657	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7658
7659	if (total_len < alloc_len) {
7660		ctsio->residual = alloc_len - total_len;
7661		ctsio->kern_data_len = total_len;
7662		ctsio->kern_total_len = total_len;
7663	} else {
7664		ctsio->residual = 0;
7665		ctsio->kern_data_len = alloc_len;
7666		ctsio->kern_total_len = alloc_len;
7667	}
7668
7669	ctsio->kern_data_resid = 0;
7670	ctsio->kern_rel_offset = 0;
7671	ctsio->kern_sg_entries = 0;
7672
7673	mtx_lock(&lun->lun_lock);
7674	switch (cdb->action) {
7675	case SPRI_RK: { // read keys
7676        struct scsi_per_res_in_keys *res_keys;
7677		int i, key_count;
7678
7679		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7680
7681		/*
7682		 * We had to drop the lock to allocate our buffer, which
7683		 * leaves time for someone to come in with another
7684		 * persistent reservation.  (That is unlikely, though,
7685		 * since this should be the only persistent reservation
7686		 * command active right now.)
7687		 */
7688		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7689		    (lun->pr_key_count *
7690		     sizeof(struct scsi_per_res_key)))){
7691			mtx_unlock(&lun->lun_lock);
7692			free(ctsio->kern_data_ptr, M_CTL);
7693			printf("%s: reservation length changed, retrying\n",
7694			       __func__);
7695			goto retry;
7696		}
7697
7698		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7699
7700		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7701			     lun->pr_key_count, res_keys->header.length);
7702
7703		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7704			if (lun->pr_keys[i] == 0)
7705				continue;
7706
7707			/*
7708			 * We used lun->pr_key_count to calculate the
7709			 * size to allocate.  If it turns out the number of
7710			 * initiators with the registered flag set is
7711			 * larger than that (i.e. they haven't been kept in
7712			 * sync), we've got a problem.
7713			 */
7714			if (key_count >= lun->pr_key_count) {
7715#ifdef NEEDTOPORT
7716				csevent_log(CSC_CTL | CSC_SHELF_SW |
7717					    CTL_PR_ERROR,
7718					    csevent_LogType_Fault,
7719					    csevent_AlertLevel_Yellow,
7720					    csevent_FRU_ShelfController,
7721					    csevent_FRU_Firmware,
7722				        csevent_FRU_Unknown,
7723					    "registered keys %d >= key "
7724					    "count %d", key_count,
7725					    lun->pr_key_count);
7726#endif
7727				key_count++;
7728				continue;
7729			}
7730			scsi_u64to8b(lun->pr_keys[i],
7731			    res_keys->keys[key_count].key);
7732			key_count++;
7733		}
7734		break;
7735	}
7736	case SPRI_RR: { // read reservation
7737		struct scsi_per_res_in_rsrv *res;
7738		int tmp_len, header_only;
7739
7740		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7741
7742		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7743
7744		if (lun->flags & CTL_LUN_PR_RESERVED)
7745		{
7746			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7747			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7748				    res->header.length);
7749			header_only = 0;
7750		} else {
7751			tmp_len = sizeof(struct scsi_per_res_in_header);
7752			scsi_ulto4b(0, res->header.length);
7753			header_only = 1;
7754		}
7755
7756		/*
7757		 * We had to drop the lock to allocate our buffer, which
7758		 * leaves time for someone to come in with another
7759		 * persistent reservation.  (That is unlikely, though,
7760		 * since this should be the only persistent reservation
7761		 * command active right now.)
7762		 */
7763		if (tmp_len != total_len) {
7764			mtx_unlock(&lun->lun_lock);
7765			free(ctsio->kern_data_ptr, M_CTL);
7766			printf("%s: reservation status changed, retrying\n",
7767			       __func__);
7768			goto retry;
7769		}
7770
7771		/*
7772		 * No reservation held, so we're done.
7773		 */
7774		if (header_only != 0)
7775			break;
7776
7777		/*
7778		 * If the registration is an All Registrants type, the key
7779		 * is 0, since it doesn't really matter.
7780		 */
7781		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7782			scsi_u64to8b(lun->pr_keys[lun->pr_res_idx],
7783			    res->data.reservation);
7784		}
7785		res->data.scopetype = lun->res_type;
7786		break;
7787	}
7788	case SPRI_RC:     //report capabilities
7789	{
7790		struct scsi_per_res_cap *res_cap;
7791		uint16_t type_mask;
7792
7793		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7794		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7795		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7796		type_mask = SPRI_TM_WR_EX_AR |
7797			    SPRI_TM_EX_AC_RO |
7798			    SPRI_TM_WR_EX_RO |
7799			    SPRI_TM_EX_AC |
7800			    SPRI_TM_WR_EX |
7801			    SPRI_TM_EX_AC_AR;
7802		scsi_ulto2b(type_mask, res_cap->type_mask);
7803		break;
7804	}
7805	case SPRI_RS: { // read full status
7806		struct scsi_per_res_in_full *res_status;
7807		struct scsi_per_res_in_full_desc *res_desc;
7808		struct ctl_port *port;
7809		int i, len;
7810
7811		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7812
7813		/*
7814		 * We had to drop the lock to allocate our buffer, which
7815		 * leaves time for someone to come in with another
7816		 * persistent reservation.  (That is unlikely, though,
7817		 * since this should be the only persistent reservation
7818		 * command active right now.)
7819		 */
7820		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7821		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7822		     lun->pr_key_count)){
7823			mtx_unlock(&lun->lun_lock);
7824			free(ctsio->kern_data_ptr, M_CTL);
7825			printf("%s: reservation length changed, retrying\n",
7826			       __func__);
7827			goto retry;
7828		}
7829
7830		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7831
7832		res_desc = &res_status->desc[0];
7833		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7834			if (lun->pr_keys[i] == 0)
7835				continue;
7836
7837			scsi_u64to8b(lun->pr_keys[i], res_desc->res_key.key);
7838			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7839			    (lun->pr_res_idx == i ||
7840			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7841				res_desc->flags = SPRI_FULL_R_HOLDER;
7842				res_desc->scopetype = lun->res_type;
7843			}
7844			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7845			    res_desc->rel_trgt_port_id);
7846			len = 0;
7847			port = softc->ctl_ports[
7848			    ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
7849			if (port != NULL)
7850				len = ctl_create_iid(port,
7851				    i % CTL_MAX_INIT_PER_PORT,
7852				    res_desc->transport_id);
7853			scsi_ulto4b(len, res_desc->additional_length);
7854			res_desc = (struct scsi_per_res_in_full_desc *)
7855			    &res_desc->transport_id[len];
7856		}
7857		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7858		    res_status->header.length);
7859		break;
7860	}
7861	default:
7862		/*
7863		 * This is a bug, because we just checked for this above,
7864		 * and should have returned an error.
7865		 */
7866		panic("Invalid PR type %x", cdb->action);
7867		break; /* NOTREACHED */
7868	}
7869	mtx_unlock(&lun->lun_lock);
7870
7871	ctl_set_success(ctsio);
7872	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7873	ctsio->be_move_done = ctl_config_move_done;
7874	ctl_datamove((union ctl_io *)ctsio);
7875	return (CTL_RETVAL_COMPLETE);
7876}
7877
7878static void
7879ctl_set_res_ua(struct ctl_lun *lun, uint32_t residx, ctl_ua_type ua)
7880{
7881
7882	if (residx >= persis_offset &&
7883	    residx < persis_offset + CTL_MAX_INITIATORS)
7884		lun->pending_ua[residx - persis_offset] |= ua;
7885}
7886
7887/*
7888 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7889 * it should return.
7890 */
7891static int
7892ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7893		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7894		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7895		struct scsi_per_res_out_parms* param)
7896{
7897	union ctl_ha_msg persis_io;
7898	int retval, i;
7899	int isc_retval;
7900
7901	retval = 0;
7902
7903	mtx_lock(&lun->lun_lock);
7904	if (sa_res_key == 0) {
7905		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7906			/* validate scope and type */
7907			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7908			     SPR_LU_SCOPE) {
7909				mtx_unlock(&lun->lun_lock);
7910				ctl_set_invalid_field(/*ctsio*/ ctsio,
7911						      /*sks_valid*/ 1,
7912						      /*command*/ 1,
7913						      /*field*/ 2,
7914						      /*bit_valid*/ 1,
7915						      /*bit*/ 4);
7916				ctl_done((union ctl_io *)ctsio);
7917				return (1);
7918			}
7919
7920		        if (type>8 || type==2 || type==4 || type==0) {
7921				mtx_unlock(&lun->lun_lock);
7922				ctl_set_invalid_field(/*ctsio*/ ctsio,
7923       	           				      /*sks_valid*/ 1,
7924						      /*command*/ 1,
7925						      /*field*/ 2,
7926						      /*bit_valid*/ 1,
7927						      /*bit*/ 0);
7928				ctl_done((union ctl_io *)ctsio);
7929				return (1);
7930		        }
7931
7932			/*
7933			 * Unregister everybody else and build UA for
7934			 * them
7935			 */
7936			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7937				if (i == residx || lun->pr_keys[i] == 0)
7938					continue;
7939
7940				lun->pr_keys[i] = 0;
7941				ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
7942			}
7943			lun->pr_key_count = 1;
7944			lun->res_type = type;
7945			if (lun->res_type != SPR_TYPE_WR_EX_AR
7946			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7947				lun->pr_res_idx = residx;
7948
7949			/* send msg to other side */
7950			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7951			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7952			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7953			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7954			persis_io.pr.pr_info.res_type = type;
7955			memcpy(persis_io.pr.pr_info.sa_res_key,
7956			       param->serv_act_res_key,
7957			       sizeof(param->serv_act_res_key));
7958			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7959			     &persis_io, sizeof(persis_io), 0)) >
7960			     CTL_HA_STATUS_SUCCESS) {
7961				printf("CTL:Persis Out error returned "
7962				       "from ctl_ha_msg_send %d\n",
7963				       isc_retval);
7964			}
7965		} else {
7966			/* not all registrants */
7967			mtx_unlock(&lun->lun_lock);
7968			free(ctsio->kern_data_ptr, M_CTL);
7969			ctl_set_invalid_field(ctsio,
7970					      /*sks_valid*/ 1,
7971					      /*command*/ 0,
7972					      /*field*/ 8,
7973					      /*bit_valid*/ 0,
7974					      /*bit*/ 0);
7975			ctl_done((union ctl_io *)ctsio);
7976			return (1);
7977		}
7978	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7979		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7980		int found = 0;
7981
7982		if (res_key == sa_res_key) {
7983			/* special case */
7984			/*
7985			 * The spec implies this is not good but doesn't
7986			 * say what to do. There are two choices either
7987			 * generate a res conflict or check condition
7988			 * with illegal field in parameter data. Since
7989			 * that is what is done when the sa_res_key is
7990			 * zero I'll take that approach since this has
7991			 * to do with the sa_res_key.
7992			 */
7993			mtx_unlock(&lun->lun_lock);
7994			free(ctsio->kern_data_ptr, M_CTL);
7995			ctl_set_invalid_field(ctsio,
7996					      /*sks_valid*/ 1,
7997					      /*command*/ 0,
7998					      /*field*/ 8,
7999					      /*bit_valid*/ 0,
8000					      /*bit*/ 0);
8001			ctl_done((union ctl_io *)ctsio);
8002			return (1);
8003		}
8004
8005		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8006			if (lun->pr_keys[i] != sa_res_key)
8007				continue;
8008
8009			found = 1;
8010			lun->pr_keys[i] = 0;
8011			lun->pr_key_count--;
8012			ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8013		}
8014		if (!found) {
8015			mtx_unlock(&lun->lun_lock);
8016			free(ctsio->kern_data_ptr, M_CTL);
8017			ctl_set_reservation_conflict(ctsio);
8018			ctl_done((union ctl_io *)ctsio);
8019			return (CTL_RETVAL_COMPLETE);
8020		}
8021		/* send msg to other side */
8022		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8023		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8024		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8025		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8026		persis_io.pr.pr_info.res_type = type;
8027		memcpy(persis_io.pr.pr_info.sa_res_key,
8028		       param->serv_act_res_key,
8029		       sizeof(param->serv_act_res_key));
8030		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8031		     &persis_io, sizeof(persis_io), 0)) >
8032		     CTL_HA_STATUS_SUCCESS) {
8033			printf("CTL:Persis Out error returned from "
8034			       "ctl_ha_msg_send %d\n", isc_retval);
8035		}
8036	} else {
8037		/* Reserved but not all registrants */
8038		/* sa_res_key is res holder */
8039		if (sa_res_key == lun->pr_keys[lun->pr_res_idx]) {
8040			/* validate scope and type */
8041			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8042			     SPR_LU_SCOPE) {
8043				mtx_unlock(&lun->lun_lock);
8044				ctl_set_invalid_field(/*ctsio*/ ctsio,
8045						      /*sks_valid*/ 1,
8046						      /*command*/ 1,
8047						      /*field*/ 2,
8048						      /*bit_valid*/ 1,
8049						      /*bit*/ 4);
8050				ctl_done((union ctl_io *)ctsio);
8051				return (1);
8052			}
8053
8054			if (type>8 || type==2 || type==4 || type==0) {
8055				mtx_unlock(&lun->lun_lock);
8056				ctl_set_invalid_field(/*ctsio*/ ctsio,
8057						      /*sks_valid*/ 1,
8058						      /*command*/ 1,
8059						      /*field*/ 2,
8060						      /*bit_valid*/ 1,
8061						      /*bit*/ 0);
8062				ctl_done((union ctl_io *)ctsio);
8063				return (1);
8064			}
8065
8066			/*
8067			 * Do the following:
8068			 * if sa_res_key != res_key remove all
8069			 * registrants w/sa_res_key and generate UA
8070			 * for these registrants(Registrations
8071			 * Preempted) if it wasn't an exclusive
8072			 * reservation generate UA(Reservations
8073			 * Preempted) for all other registered nexuses
8074			 * if the type has changed. Establish the new
8075			 * reservation and holder. If res_key and
8076			 * sa_res_key are the same do the above
8077			 * except don't unregister the res holder.
8078			 */
8079
8080			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8081				if (i == residx || lun->pr_keys[i] == 0)
8082					continue;
8083
8084				if (sa_res_key == lun->pr_keys[i]) {
8085					lun->pr_keys[i] = 0;
8086					lun->pr_key_count--;
8087					ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8088				} else if (type != lun->res_type
8089					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8090					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8091					ctl_set_res_ua(lun, i, CTL_UA_RES_RELEASE);
8092				}
8093			}
8094			lun->res_type = type;
8095			if (lun->res_type != SPR_TYPE_WR_EX_AR
8096			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8097				lun->pr_res_idx = residx;
8098			else
8099				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8100
8101			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8102			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8103			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8104			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8105			persis_io.pr.pr_info.res_type = type;
8106			memcpy(persis_io.pr.pr_info.sa_res_key,
8107			       param->serv_act_res_key,
8108			       sizeof(param->serv_act_res_key));
8109			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8110			     &persis_io, sizeof(persis_io), 0)) >
8111			     CTL_HA_STATUS_SUCCESS) {
8112				printf("CTL:Persis Out error returned "
8113				       "from ctl_ha_msg_send %d\n",
8114				       isc_retval);
8115			}
8116		} else {
8117			/*
8118			 * sa_res_key is not the res holder just
8119			 * remove registrants
8120			 */
8121			int found=0;
8122
8123			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8124				if (sa_res_key != lun->pr_keys[i])
8125					continue;
8126
8127				found = 1;
8128				lun->pr_keys[i] = 0;
8129				lun->pr_key_count--;
8130				ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8131			}
8132
8133			if (!found) {
8134				mtx_unlock(&lun->lun_lock);
8135				free(ctsio->kern_data_ptr, M_CTL);
8136				ctl_set_reservation_conflict(ctsio);
8137				ctl_done((union ctl_io *)ctsio);
8138		        	return (1);
8139			}
8140			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8141			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8142			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8143			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8144			persis_io.pr.pr_info.res_type = type;
8145			memcpy(persis_io.pr.pr_info.sa_res_key,
8146			       param->serv_act_res_key,
8147			       sizeof(param->serv_act_res_key));
8148			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8149			     &persis_io, sizeof(persis_io), 0)) >
8150			     CTL_HA_STATUS_SUCCESS) {
8151				printf("CTL:Persis Out error returned "
8152				       "from ctl_ha_msg_send %d\n",
8153				isc_retval);
8154			}
8155		}
8156	}
8157
8158	lun->PRGeneration++;
8159	mtx_unlock(&lun->lun_lock);
8160
8161	return (retval);
8162}
8163
8164static void
8165ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8166{
8167	uint64_t sa_res_key;
8168	int i;
8169
8170	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8171
8172	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8173	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8174	 || sa_res_key != lun->pr_keys[lun->pr_res_idx]) {
8175		if (sa_res_key == 0) {
8176			/*
8177			 * Unregister everybody else and build UA for
8178			 * them
8179			 */
8180			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8181				if (i == msg->pr.pr_info.residx ||
8182				    lun->pr_keys[i] == 0)
8183					continue;
8184
8185				lun->pr_keys[i] = 0;
8186				ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8187			}
8188
8189			lun->pr_key_count = 1;
8190			lun->res_type = msg->pr.pr_info.res_type;
8191			if (lun->res_type != SPR_TYPE_WR_EX_AR
8192			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8193				lun->pr_res_idx = msg->pr.pr_info.residx;
8194		} else {
8195		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8196				if (sa_res_key == lun->pr_keys[i])
8197					continue;
8198
8199				lun->pr_keys[i] = 0;
8200				lun->pr_key_count--;
8201				ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8202			}
8203		}
8204	} else {
8205		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8206			if (i == msg->pr.pr_info.residx ||
8207			    lun->pr_keys[i] == 0)
8208				continue;
8209
8210			if (sa_res_key == lun->pr_keys[i]) {
8211				lun->pr_keys[i] = 0;
8212				lun->pr_key_count--;
8213				ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8214			} else if (msg->pr.pr_info.res_type != lun->res_type
8215				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8216				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8217				ctl_set_res_ua(lun, i, CTL_UA_RES_RELEASE);
8218			}
8219		}
8220		lun->res_type = msg->pr.pr_info.res_type;
8221		if (lun->res_type != SPR_TYPE_WR_EX_AR
8222		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8223			lun->pr_res_idx = msg->pr.pr_info.residx;
8224		else
8225			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8226	}
8227	lun->PRGeneration++;
8228
8229}
8230
8231
8232int
8233ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8234{
8235	int retval;
8236	int isc_retval;
8237	u_int32_t param_len;
8238	struct scsi_per_res_out *cdb;
8239	struct ctl_lun *lun;
8240	struct scsi_per_res_out_parms* param;
8241	struct ctl_softc *softc;
8242	uint32_t residx;
8243	uint64_t res_key, sa_res_key;
8244	uint8_t type;
8245	union ctl_ha_msg persis_io;
8246	int    i;
8247
8248	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8249
8250	retval = CTL_RETVAL_COMPLETE;
8251
8252	softc = control_softc;
8253
8254	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8255	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8256
8257	/*
8258	 * We only support whole-LUN scope.  The scope & type are ignored for
8259	 * register, register and ignore existing key and clear.
8260	 * We sometimes ignore scope and type on preempts too!!
8261	 * Verify reservation type here as well.
8262	 */
8263	type = cdb->scope_type & SPR_TYPE_MASK;
8264	if ((cdb->action == SPRO_RESERVE)
8265	 || (cdb->action == SPRO_RELEASE)) {
8266		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8267			ctl_set_invalid_field(/*ctsio*/ ctsio,
8268					      /*sks_valid*/ 1,
8269					      /*command*/ 1,
8270					      /*field*/ 2,
8271					      /*bit_valid*/ 1,
8272					      /*bit*/ 4);
8273			ctl_done((union ctl_io *)ctsio);
8274			return (CTL_RETVAL_COMPLETE);
8275		}
8276
8277		if (type>8 || type==2 || type==4 || type==0) {
8278			ctl_set_invalid_field(/*ctsio*/ ctsio,
8279					      /*sks_valid*/ 1,
8280					      /*command*/ 1,
8281					      /*field*/ 2,
8282					      /*bit_valid*/ 1,
8283					      /*bit*/ 0);
8284			ctl_done((union ctl_io *)ctsio);
8285			return (CTL_RETVAL_COMPLETE);
8286		}
8287	}
8288
8289	param_len = scsi_4btoul(cdb->length);
8290
8291	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8292		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8293		ctsio->kern_data_len = param_len;
8294		ctsio->kern_total_len = param_len;
8295		ctsio->kern_data_resid = 0;
8296		ctsio->kern_rel_offset = 0;
8297		ctsio->kern_sg_entries = 0;
8298		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8299		ctsio->be_move_done = ctl_config_move_done;
8300		ctl_datamove((union ctl_io *)ctsio);
8301
8302		return (CTL_RETVAL_COMPLETE);
8303	}
8304
8305	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8306
8307	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8308	res_key = scsi_8btou64(param->res_key.key);
8309	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8310
8311	/*
8312	 * Validate the reservation key here except for SPRO_REG_IGNO
8313	 * This must be done for all other service actions
8314	 */
8315	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8316		mtx_lock(&lun->lun_lock);
8317		if (lun->pr_keys[residx] != 0) {
8318		    if (res_key != lun->pr_keys[residx]) {
8319				/*
8320				 * The current key passed in doesn't match
8321				 * the one the initiator previously
8322				 * registered.
8323				 */
8324				mtx_unlock(&lun->lun_lock);
8325				free(ctsio->kern_data_ptr, M_CTL);
8326				ctl_set_reservation_conflict(ctsio);
8327				ctl_done((union ctl_io *)ctsio);
8328				return (CTL_RETVAL_COMPLETE);
8329			}
8330		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8331			/*
8332			 * We are not registered
8333			 */
8334			mtx_unlock(&lun->lun_lock);
8335			free(ctsio->kern_data_ptr, M_CTL);
8336			ctl_set_reservation_conflict(ctsio);
8337			ctl_done((union ctl_io *)ctsio);
8338			return (CTL_RETVAL_COMPLETE);
8339		} else if (res_key != 0) {
8340			/*
8341			 * We are not registered and trying to register but
8342			 * the register key isn't zero.
8343			 */
8344			mtx_unlock(&lun->lun_lock);
8345			free(ctsio->kern_data_ptr, M_CTL);
8346			ctl_set_reservation_conflict(ctsio);
8347			ctl_done((union ctl_io *)ctsio);
8348			return (CTL_RETVAL_COMPLETE);
8349		}
8350		mtx_unlock(&lun->lun_lock);
8351	}
8352
8353	switch (cdb->action & SPRO_ACTION_MASK) {
8354	case SPRO_REGISTER:
8355	case SPRO_REG_IGNO: {
8356
8357#if 0
8358		printf("Registration received\n");
8359#endif
8360
8361		/*
8362		 * We don't support any of these options, as we report in
8363		 * the read capabilities request (see
8364		 * ctl_persistent_reserve_in(), above).
8365		 */
8366		if ((param->flags & SPR_SPEC_I_PT)
8367		 || (param->flags & SPR_ALL_TG_PT)
8368		 || (param->flags & SPR_APTPL)) {
8369			int bit_ptr;
8370
8371			if (param->flags & SPR_APTPL)
8372				bit_ptr = 0;
8373			else if (param->flags & SPR_ALL_TG_PT)
8374				bit_ptr = 2;
8375			else /* SPR_SPEC_I_PT */
8376				bit_ptr = 3;
8377
8378			free(ctsio->kern_data_ptr, M_CTL);
8379			ctl_set_invalid_field(ctsio,
8380					      /*sks_valid*/ 1,
8381					      /*command*/ 0,
8382					      /*field*/ 20,
8383					      /*bit_valid*/ 1,
8384					      /*bit*/ bit_ptr);
8385			ctl_done((union ctl_io *)ctsio);
8386			return (CTL_RETVAL_COMPLETE);
8387		}
8388
8389		mtx_lock(&lun->lun_lock);
8390
8391		/*
8392		 * The initiator wants to clear the
8393		 * key/unregister.
8394		 */
8395		if (sa_res_key == 0) {
8396			if ((res_key == 0
8397			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8398			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8399			  && lun->pr_keys[residx] == 0)) {
8400				mtx_unlock(&lun->lun_lock);
8401				goto done;
8402			}
8403
8404			lun->pr_keys[residx] = 0;
8405			lun->pr_key_count--;
8406
8407			if (residx == lun->pr_res_idx) {
8408				lun->flags &= ~CTL_LUN_PR_RESERVED;
8409				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8410
8411				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8412				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8413				 && lun->pr_key_count) {
8414					/*
8415					 * If the reservation is a registrants
8416					 * only type we need to generate a UA
8417					 * for other registered inits.  The
8418					 * sense code should be RESERVATIONS
8419					 * RELEASED
8420					 */
8421
8422					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8423						if (lun->pr_keys[
8424						    i + persis_offset] == 0)
8425							continue;
8426						lun->pending_ua[i] |=
8427							CTL_UA_RES_RELEASE;
8428					}
8429				}
8430				lun->res_type = 0;
8431			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8432				if (lun->pr_key_count==0) {
8433					lun->flags &= ~CTL_LUN_PR_RESERVED;
8434					lun->res_type = 0;
8435					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8436				}
8437			}
8438			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8439			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8440			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8441			persis_io.pr.pr_info.residx = residx;
8442			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8443			     &persis_io, sizeof(persis_io), 0 )) >
8444			     CTL_HA_STATUS_SUCCESS) {
8445				printf("CTL:Persis Out error returned from "
8446				       "ctl_ha_msg_send %d\n", isc_retval);
8447			}
8448		} else /* sa_res_key != 0 */ {
8449
8450			/*
8451			 * If we aren't registered currently then increment
8452			 * the key count and set the registered flag.
8453			 */
8454			if (lun->pr_keys[residx] == 0)
8455				lun->pr_key_count++;
8456			lun->pr_keys[residx] = sa_res_key;
8457
8458			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8459			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8460			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8461			persis_io.pr.pr_info.residx = residx;
8462			memcpy(persis_io.pr.pr_info.sa_res_key,
8463			       param->serv_act_res_key,
8464			       sizeof(param->serv_act_res_key));
8465			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8466			     &persis_io, sizeof(persis_io), 0)) >
8467			     CTL_HA_STATUS_SUCCESS) {
8468				printf("CTL:Persis Out error returned from "
8469				       "ctl_ha_msg_send %d\n", isc_retval);
8470			}
8471		}
8472		lun->PRGeneration++;
8473		mtx_unlock(&lun->lun_lock);
8474
8475		break;
8476	}
8477	case SPRO_RESERVE:
8478#if 0
8479                printf("Reserve executed type %d\n", type);
8480#endif
8481		mtx_lock(&lun->lun_lock);
8482		if (lun->flags & CTL_LUN_PR_RESERVED) {
8483			/*
8484			 * if this isn't the reservation holder and it's
8485			 * not a "all registrants" type or if the type is
8486			 * different then we have a conflict
8487			 */
8488			if ((lun->pr_res_idx != residx
8489			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8490			 || lun->res_type != type) {
8491				mtx_unlock(&lun->lun_lock);
8492				free(ctsio->kern_data_ptr, M_CTL);
8493				ctl_set_reservation_conflict(ctsio);
8494				ctl_done((union ctl_io *)ctsio);
8495				return (CTL_RETVAL_COMPLETE);
8496			}
8497			mtx_unlock(&lun->lun_lock);
8498		} else /* create a reservation */ {
8499			/*
8500			 * If it's not an "all registrants" type record
8501			 * reservation holder
8502			 */
8503			if (type != SPR_TYPE_WR_EX_AR
8504			 && type != SPR_TYPE_EX_AC_AR)
8505				lun->pr_res_idx = residx; /* Res holder */
8506			else
8507				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8508
8509			lun->flags |= CTL_LUN_PR_RESERVED;
8510			lun->res_type = type;
8511
8512			mtx_unlock(&lun->lun_lock);
8513
8514			/* send msg to other side */
8515			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8516			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8517			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8518			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8519			persis_io.pr.pr_info.res_type = type;
8520			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8521			     &persis_io, sizeof(persis_io), 0)) >
8522			     CTL_HA_STATUS_SUCCESS) {
8523				printf("CTL:Persis Out error returned from "
8524				       "ctl_ha_msg_send %d\n", isc_retval);
8525			}
8526		}
8527		break;
8528
8529	case SPRO_RELEASE:
8530		mtx_lock(&lun->lun_lock);
8531		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8532			/* No reservation exists return good status */
8533			mtx_unlock(&lun->lun_lock);
8534			goto done;
8535		}
8536		/*
8537		 * Is this nexus a reservation holder?
8538		 */
8539		if (lun->pr_res_idx != residx
8540		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8541			/*
8542			 * not a res holder return good status but
8543			 * do nothing
8544			 */
8545			mtx_unlock(&lun->lun_lock);
8546			goto done;
8547		}
8548
8549		if (lun->res_type != type) {
8550			mtx_unlock(&lun->lun_lock);
8551			free(ctsio->kern_data_ptr, M_CTL);
8552			ctl_set_illegal_pr_release(ctsio);
8553			ctl_done((union ctl_io *)ctsio);
8554			return (CTL_RETVAL_COMPLETE);
8555		}
8556
8557		/* okay to release */
8558		lun->flags &= ~CTL_LUN_PR_RESERVED;
8559		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8560		lun->res_type = 0;
8561
8562		/*
8563		 * if this isn't an exclusive access
8564		 * res generate UA for all other
8565		 * registrants.
8566		 */
8567		if (type != SPR_TYPE_EX_AC
8568		 && type != SPR_TYPE_WR_EX) {
8569			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8570				if (i == residx ||
8571				    lun->pr_keys[i + persis_offset] == 0)
8572					continue;
8573				lun->pending_ua[i] |= CTL_UA_RES_RELEASE;
8574			}
8575		}
8576		mtx_unlock(&lun->lun_lock);
8577		/* Send msg to other side */
8578		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8579		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8580		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8581		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8582		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8583			printf("CTL:Persis Out error returned from "
8584			       "ctl_ha_msg_send %d\n", isc_retval);
8585		}
8586		break;
8587
8588	case SPRO_CLEAR:
8589		/* send msg to other side */
8590
8591		mtx_lock(&lun->lun_lock);
8592		lun->flags &= ~CTL_LUN_PR_RESERVED;
8593		lun->res_type = 0;
8594		lun->pr_key_count = 0;
8595		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8596
8597		lun->pr_keys[residx] = 0;
8598
8599		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8600			if (lun->pr_keys[i] != 0) {
8601				lun->pr_keys[i] = 0;
8602				ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8603			}
8604		lun->PRGeneration++;
8605		mtx_unlock(&lun->lun_lock);
8606		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8607		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8608		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8609		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8610		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8611			printf("CTL:Persis Out error returned from "
8612			       "ctl_ha_msg_send %d\n", isc_retval);
8613		}
8614		break;
8615
8616	case SPRO_PREEMPT:
8617	case SPRO_PRE_ABO: {
8618		int nretval;
8619
8620		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8621					  residx, ctsio, cdb, param);
8622		if (nretval != 0)
8623			return (CTL_RETVAL_COMPLETE);
8624		break;
8625	}
8626	default:
8627		panic("Invalid PR type %x", cdb->action);
8628	}
8629
8630done:
8631	free(ctsio->kern_data_ptr, M_CTL);
8632	ctl_set_success(ctsio);
8633	ctl_done((union ctl_io *)ctsio);
8634
8635	return (retval);
8636}
8637
8638/*
8639 * This routine is for handling a message from the other SC pertaining to
8640 * persistent reserve out. All the error checking will have been done
8641 * so only perorming the action need be done here to keep the two
8642 * in sync.
8643 */
8644static void
8645ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8646{
8647	struct ctl_lun *lun;
8648	struct ctl_softc *softc;
8649	int i;
8650	uint32_t targ_lun;
8651
8652	softc = control_softc;
8653
8654	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8655	lun = softc->ctl_luns[targ_lun];
8656	mtx_lock(&lun->lun_lock);
8657	switch(msg->pr.pr_info.action) {
8658	case CTL_PR_REG_KEY:
8659		if (lun->pr_keys[msg->pr.pr_info.residx] == 0)
8660			lun->pr_key_count++;
8661		lun->pr_keys[msg->pr.pr_info.residx] =
8662		    scsi_8btou64(msg->pr.pr_info.sa_res_key);
8663		lun->PRGeneration++;
8664		break;
8665
8666	case CTL_PR_UNREG_KEY:
8667		lun->pr_keys[msg->pr.pr_info.residx] = 0;
8668		lun->pr_key_count--;
8669
8670		/* XXX Need to see if the reservation has been released */
8671		/* if so do we need to generate UA? */
8672		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8673			lun->flags &= ~CTL_LUN_PR_RESERVED;
8674			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8675
8676			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8677			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8678			 && lun->pr_key_count) {
8679				/*
8680				 * If the reservation is a registrants
8681				 * only type we need to generate a UA
8682				 * for other registered inits.  The
8683				 * sense code should be RESERVATIONS
8684				 * RELEASED
8685				 */
8686
8687				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8688					if (lun->pr_keys[i+
8689					    persis_offset] == 0)
8690						continue;
8691
8692					lun->pending_ua[i] |=
8693						CTL_UA_RES_RELEASE;
8694				}
8695			}
8696			lun->res_type = 0;
8697		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8698			if (lun->pr_key_count==0) {
8699				lun->flags &= ~CTL_LUN_PR_RESERVED;
8700				lun->res_type = 0;
8701				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8702			}
8703		}
8704		lun->PRGeneration++;
8705		break;
8706
8707	case CTL_PR_RESERVE:
8708		lun->flags |= CTL_LUN_PR_RESERVED;
8709		lun->res_type = msg->pr.pr_info.res_type;
8710		lun->pr_res_idx = msg->pr.pr_info.residx;
8711
8712		break;
8713
8714	case CTL_PR_RELEASE:
8715		/*
8716		 * if this isn't an exclusive access res generate UA for all
8717		 * other registrants.
8718		 */
8719		if (lun->res_type != SPR_TYPE_EX_AC
8720		 && lun->res_type != SPR_TYPE_WR_EX) {
8721			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8722				if (lun->pr_keys[i+persis_offset] != 0)
8723					lun->pending_ua[i] |=
8724						CTL_UA_RES_RELEASE;
8725		}
8726
8727		lun->flags &= ~CTL_LUN_PR_RESERVED;
8728		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8729		lun->res_type = 0;
8730		break;
8731
8732	case CTL_PR_PREEMPT:
8733		ctl_pro_preempt_other(lun, msg);
8734		break;
8735	case CTL_PR_CLEAR:
8736		lun->flags &= ~CTL_LUN_PR_RESERVED;
8737		lun->res_type = 0;
8738		lun->pr_key_count = 0;
8739		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8740
8741		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8742			if (lun->pr_keys[i] == 0)
8743				continue;
8744			lun->pr_keys[i] = 0;
8745			ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8746		}
8747		lun->PRGeneration++;
8748		break;
8749	}
8750
8751	mtx_unlock(&lun->lun_lock);
8752}
8753
8754int
8755ctl_read_write(struct ctl_scsiio *ctsio)
8756{
8757	struct ctl_lun *lun;
8758	struct ctl_lba_len_flags *lbalen;
8759	uint64_t lba;
8760	uint32_t num_blocks;
8761	int flags, retval;
8762	int isread;
8763
8764	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8765
8766	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8767
8768	flags = 0;
8769	retval = CTL_RETVAL_COMPLETE;
8770
8771	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8772	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8773	switch (ctsio->cdb[0]) {
8774	case READ_6:
8775	case WRITE_6: {
8776		struct scsi_rw_6 *cdb;
8777
8778		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8779
8780		lba = scsi_3btoul(cdb->addr);
8781		/* only 5 bits are valid in the most significant address byte */
8782		lba &= 0x1fffff;
8783		num_blocks = cdb->length;
8784		/*
8785		 * This is correct according to SBC-2.
8786		 */
8787		if (num_blocks == 0)
8788			num_blocks = 256;
8789		break;
8790	}
8791	case READ_10:
8792	case WRITE_10: {
8793		struct scsi_rw_10 *cdb;
8794
8795		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8796		if (cdb->byte2 & SRW10_FUA)
8797			flags |= CTL_LLF_FUA;
8798		if (cdb->byte2 & SRW10_DPO)
8799			flags |= CTL_LLF_DPO;
8800		lba = scsi_4btoul(cdb->addr);
8801		num_blocks = scsi_2btoul(cdb->length);
8802		break;
8803	}
8804	case WRITE_VERIFY_10: {
8805		struct scsi_write_verify_10 *cdb;
8806
8807		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8808		flags |= CTL_LLF_FUA;
8809		if (cdb->byte2 & SWV_DPO)
8810			flags |= CTL_LLF_DPO;
8811		lba = scsi_4btoul(cdb->addr);
8812		num_blocks = scsi_2btoul(cdb->length);
8813		break;
8814	}
8815	case READ_12:
8816	case WRITE_12: {
8817		struct scsi_rw_12 *cdb;
8818
8819		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8820		if (cdb->byte2 & SRW12_FUA)
8821			flags |= CTL_LLF_FUA;
8822		if (cdb->byte2 & SRW12_DPO)
8823			flags |= CTL_LLF_DPO;
8824		lba = scsi_4btoul(cdb->addr);
8825		num_blocks = scsi_4btoul(cdb->length);
8826		break;
8827	}
8828	case WRITE_VERIFY_12: {
8829		struct scsi_write_verify_12 *cdb;
8830
8831		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8832		flags |= CTL_LLF_FUA;
8833		if (cdb->byte2 & SWV_DPO)
8834			flags |= CTL_LLF_DPO;
8835		lba = scsi_4btoul(cdb->addr);
8836		num_blocks = scsi_4btoul(cdb->length);
8837		break;
8838	}
8839	case READ_16:
8840	case WRITE_16: {
8841		struct scsi_rw_16 *cdb;
8842
8843		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8844		if (cdb->byte2 & SRW12_FUA)
8845			flags |= CTL_LLF_FUA;
8846		if (cdb->byte2 & SRW12_DPO)
8847			flags |= CTL_LLF_DPO;
8848		lba = scsi_8btou64(cdb->addr);
8849		num_blocks = scsi_4btoul(cdb->length);
8850		break;
8851	}
8852	case WRITE_ATOMIC_16: {
8853		struct scsi_rw_16 *cdb;
8854
8855		if (lun->be_lun->atomicblock == 0) {
8856			ctl_set_invalid_opcode(ctsio);
8857			ctl_done((union ctl_io *)ctsio);
8858			return (CTL_RETVAL_COMPLETE);
8859		}
8860
8861		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8862		if (cdb->byte2 & SRW12_FUA)
8863			flags |= CTL_LLF_FUA;
8864		if (cdb->byte2 & SRW12_DPO)
8865			flags |= CTL_LLF_DPO;
8866		lba = scsi_8btou64(cdb->addr);
8867		num_blocks = scsi_4btoul(cdb->length);
8868		if (num_blocks > lun->be_lun->atomicblock) {
8869			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8870			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8871			    /*bit*/ 0);
8872			ctl_done((union ctl_io *)ctsio);
8873			return (CTL_RETVAL_COMPLETE);
8874		}
8875		break;
8876	}
8877	case WRITE_VERIFY_16: {
8878		struct scsi_write_verify_16 *cdb;
8879
8880		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8881		flags |= CTL_LLF_FUA;
8882		if (cdb->byte2 & SWV_DPO)
8883			flags |= CTL_LLF_DPO;
8884		lba = scsi_8btou64(cdb->addr);
8885		num_blocks = scsi_4btoul(cdb->length);
8886		break;
8887	}
8888	default:
8889		/*
8890		 * We got a command we don't support.  This shouldn't
8891		 * happen, commands should be filtered out above us.
8892		 */
8893		ctl_set_invalid_opcode(ctsio);
8894		ctl_done((union ctl_io *)ctsio);
8895
8896		return (CTL_RETVAL_COMPLETE);
8897		break; /* NOTREACHED */
8898	}
8899
8900	/*
8901	 * The first check is to make sure we're in bounds, the second
8902	 * check is to catch wrap-around problems.  If the lba + num blocks
8903	 * is less than the lba, then we've wrapped around and the block
8904	 * range is invalid anyway.
8905	 */
8906	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8907	 || ((lba + num_blocks) < lba)) {
8908		ctl_set_lba_out_of_range(ctsio);
8909		ctl_done((union ctl_io *)ctsio);
8910		return (CTL_RETVAL_COMPLETE);
8911	}
8912
8913	/*
8914	 * According to SBC-3, a transfer length of 0 is not an error.
8915	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8916	 * translates to 256 blocks for those commands.
8917	 */
8918	if (num_blocks == 0) {
8919		ctl_set_success(ctsio);
8920		ctl_done((union ctl_io *)ctsio);
8921		return (CTL_RETVAL_COMPLETE);
8922	}
8923
8924	/* Set FUA and/or DPO if caches are disabled. */
8925	if (isread) {
8926		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8927		    SCP_RCD) != 0)
8928			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8929	} else {
8930		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8931		    SCP_WCE) == 0)
8932			flags |= CTL_LLF_FUA;
8933	}
8934
8935	lbalen = (struct ctl_lba_len_flags *)
8936	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8937	lbalen->lba = lba;
8938	lbalen->len = num_blocks;
8939	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8940
8941	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8942	ctsio->kern_rel_offset = 0;
8943
8944	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8945
8946	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8947
8948	return (retval);
8949}
8950
8951static int
8952ctl_cnw_cont(union ctl_io *io)
8953{
8954	struct ctl_scsiio *ctsio;
8955	struct ctl_lun *lun;
8956	struct ctl_lba_len_flags *lbalen;
8957	int retval;
8958
8959	ctsio = &io->scsiio;
8960	ctsio->io_hdr.status = CTL_STATUS_NONE;
8961	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8962	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8963	lbalen = (struct ctl_lba_len_flags *)
8964	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8965	lbalen->flags &= ~CTL_LLF_COMPARE;
8966	lbalen->flags |= CTL_LLF_WRITE;
8967
8968	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8969	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8970	return (retval);
8971}
8972
8973int
8974ctl_cnw(struct ctl_scsiio *ctsio)
8975{
8976	struct ctl_lun *lun;
8977	struct ctl_lba_len_flags *lbalen;
8978	uint64_t lba;
8979	uint32_t num_blocks;
8980	int flags, retval;
8981
8982	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8983
8984	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8985
8986	flags = 0;
8987	retval = CTL_RETVAL_COMPLETE;
8988
8989	switch (ctsio->cdb[0]) {
8990	case COMPARE_AND_WRITE: {
8991		struct scsi_compare_and_write *cdb;
8992
8993		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8994		if (cdb->byte2 & SRW10_FUA)
8995			flags |= CTL_LLF_FUA;
8996		if (cdb->byte2 & SRW10_DPO)
8997			flags |= CTL_LLF_DPO;
8998		lba = scsi_8btou64(cdb->addr);
8999		num_blocks = cdb->length;
9000		break;
9001	}
9002	default:
9003		/*
9004		 * We got a command we don't support.  This shouldn't
9005		 * happen, commands should be filtered out above us.
9006		 */
9007		ctl_set_invalid_opcode(ctsio);
9008		ctl_done((union ctl_io *)ctsio);
9009
9010		return (CTL_RETVAL_COMPLETE);
9011		break; /* NOTREACHED */
9012	}
9013
9014	/*
9015	 * The first check is to make sure we're in bounds, the second
9016	 * check is to catch wrap-around problems.  If the lba + num blocks
9017	 * is less than the lba, then we've wrapped around and the block
9018	 * range is invalid anyway.
9019	 */
9020	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9021	 || ((lba + num_blocks) < lba)) {
9022		ctl_set_lba_out_of_range(ctsio);
9023		ctl_done((union ctl_io *)ctsio);
9024		return (CTL_RETVAL_COMPLETE);
9025	}
9026
9027	/*
9028	 * According to SBC-3, a transfer length of 0 is not an error.
9029	 */
9030	if (num_blocks == 0) {
9031		ctl_set_success(ctsio);
9032		ctl_done((union ctl_io *)ctsio);
9033		return (CTL_RETVAL_COMPLETE);
9034	}
9035
9036	/* Set FUA if write cache is disabled. */
9037	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9038	    SCP_WCE) == 0)
9039		flags |= CTL_LLF_FUA;
9040
9041	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9042	ctsio->kern_rel_offset = 0;
9043
9044	/*
9045	 * Set the IO_CONT flag, so that if this I/O gets passed to
9046	 * ctl_data_submit_done(), it'll get passed back to
9047	 * ctl_ctl_cnw_cont() for further processing.
9048	 */
9049	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9050	ctsio->io_cont = ctl_cnw_cont;
9051
9052	lbalen = (struct ctl_lba_len_flags *)
9053	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9054	lbalen->lba = lba;
9055	lbalen->len = num_blocks;
9056	lbalen->flags = CTL_LLF_COMPARE | flags;
9057
9058	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9059	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9060	return (retval);
9061}
9062
9063int
9064ctl_verify(struct ctl_scsiio *ctsio)
9065{
9066	struct ctl_lun *lun;
9067	struct ctl_lba_len_flags *lbalen;
9068	uint64_t lba;
9069	uint32_t num_blocks;
9070	int bytchk, flags;
9071	int retval;
9072
9073	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9074
9075	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9076
9077	bytchk = 0;
9078	flags = CTL_LLF_FUA;
9079	retval = CTL_RETVAL_COMPLETE;
9080
9081	switch (ctsio->cdb[0]) {
9082	case VERIFY_10: {
9083		struct scsi_verify_10 *cdb;
9084
9085		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9086		if (cdb->byte2 & SVFY_BYTCHK)
9087			bytchk = 1;
9088		if (cdb->byte2 & SVFY_DPO)
9089			flags |= CTL_LLF_DPO;
9090		lba = scsi_4btoul(cdb->addr);
9091		num_blocks = scsi_2btoul(cdb->length);
9092		break;
9093	}
9094	case VERIFY_12: {
9095		struct scsi_verify_12 *cdb;
9096
9097		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9098		if (cdb->byte2 & SVFY_BYTCHK)
9099			bytchk = 1;
9100		if (cdb->byte2 & SVFY_DPO)
9101			flags |= CTL_LLF_DPO;
9102		lba = scsi_4btoul(cdb->addr);
9103		num_blocks = scsi_4btoul(cdb->length);
9104		break;
9105	}
9106	case VERIFY_16: {
9107		struct scsi_rw_16 *cdb;
9108
9109		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9110		if (cdb->byte2 & SVFY_BYTCHK)
9111			bytchk = 1;
9112		if (cdb->byte2 & SVFY_DPO)
9113			flags |= CTL_LLF_DPO;
9114		lba = scsi_8btou64(cdb->addr);
9115		num_blocks = scsi_4btoul(cdb->length);
9116		break;
9117	}
9118	default:
9119		/*
9120		 * We got a command we don't support.  This shouldn't
9121		 * happen, commands should be filtered out above us.
9122		 */
9123		ctl_set_invalid_opcode(ctsio);
9124		ctl_done((union ctl_io *)ctsio);
9125		return (CTL_RETVAL_COMPLETE);
9126	}
9127
9128	/*
9129	 * The first check is to make sure we're in bounds, the second
9130	 * check is to catch wrap-around problems.  If the lba + num blocks
9131	 * is less than the lba, then we've wrapped around and the block
9132	 * range is invalid anyway.
9133	 */
9134	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9135	 || ((lba + num_blocks) < lba)) {
9136		ctl_set_lba_out_of_range(ctsio);
9137		ctl_done((union ctl_io *)ctsio);
9138		return (CTL_RETVAL_COMPLETE);
9139	}
9140
9141	/*
9142	 * According to SBC-3, a transfer length of 0 is not an error.
9143	 */
9144	if (num_blocks == 0) {
9145		ctl_set_success(ctsio);
9146		ctl_done((union ctl_io *)ctsio);
9147		return (CTL_RETVAL_COMPLETE);
9148	}
9149
9150	lbalen = (struct ctl_lba_len_flags *)
9151	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9152	lbalen->lba = lba;
9153	lbalen->len = num_blocks;
9154	if (bytchk) {
9155		lbalen->flags = CTL_LLF_COMPARE | flags;
9156		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9157	} else {
9158		lbalen->flags = CTL_LLF_VERIFY | flags;
9159		ctsio->kern_total_len = 0;
9160	}
9161	ctsio->kern_rel_offset = 0;
9162
9163	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9164	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9165	return (retval);
9166}
9167
9168int
9169ctl_report_luns(struct ctl_scsiio *ctsio)
9170{
9171	struct scsi_report_luns *cdb;
9172	struct scsi_report_luns_data *lun_data;
9173	struct ctl_lun *lun, *request_lun;
9174	int num_luns, retval;
9175	uint32_t alloc_len, lun_datalen;
9176	int num_filled, well_known;
9177	uint32_t initidx, targ_lun_id, lun_id;
9178
9179	retval = CTL_RETVAL_COMPLETE;
9180	well_known = 0;
9181
9182	cdb = (struct scsi_report_luns *)ctsio->cdb;
9183
9184	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9185
9186	mtx_lock(&control_softc->ctl_lock);
9187	num_luns = control_softc->num_luns;
9188	mtx_unlock(&control_softc->ctl_lock);
9189
9190	switch (cdb->select_report) {
9191	case RPL_REPORT_DEFAULT:
9192	case RPL_REPORT_ALL:
9193		break;
9194	case RPL_REPORT_WELLKNOWN:
9195		well_known = 1;
9196		num_luns = 0;
9197		break;
9198	default:
9199		ctl_set_invalid_field(ctsio,
9200				      /*sks_valid*/ 1,
9201				      /*command*/ 1,
9202				      /*field*/ 2,
9203				      /*bit_valid*/ 0,
9204				      /*bit*/ 0);
9205		ctl_done((union ctl_io *)ctsio);
9206		return (retval);
9207		break; /* NOTREACHED */
9208	}
9209
9210	alloc_len = scsi_4btoul(cdb->length);
9211	/*
9212	 * The initiator has to allocate at least 16 bytes for this request,
9213	 * so he can at least get the header and the first LUN.  Otherwise
9214	 * we reject the request (per SPC-3 rev 14, section 6.21).
9215	 */
9216	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9217	    sizeof(struct scsi_report_luns_lundata))) {
9218		ctl_set_invalid_field(ctsio,
9219				      /*sks_valid*/ 1,
9220				      /*command*/ 1,
9221				      /*field*/ 6,
9222				      /*bit_valid*/ 0,
9223				      /*bit*/ 0);
9224		ctl_done((union ctl_io *)ctsio);
9225		return (retval);
9226	}
9227
9228	request_lun = (struct ctl_lun *)
9229		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9230
9231	lun_datalen = sizeof(*lun_data) +
9232		(num_luns * sizeof(struct scsi_report_luns_lundata));
9233
9234	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9235	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9236	ctsio->kern_sg_entries = 0;
9237
9238	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9239
9240	mtx_lock(&control_softc->ctl_lock);
9241	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9242		lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9243		if (lun_id >= CTL_MAX_LUNS)
9244			continue;
9245		lun = control_softc->ctl_luns[lun_id];
9246		if (lun == NULL)
9247			continue;
9248
9249		if (targ_lun_id <= 0xff) {
9250			/*
9251			 * Peripheral addressing method, bus number 0.
9252			 */
9253			lun_data->luns[num_filled].lundata[0] =
9254				RPL_LUNDATA_ATYP_PERIPH;
9255			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9256			num_filled++;
9257		} else if (targ_lun_id <= 0x3fff) {
9258			/*
9259			 * Flat addressing method.
9260			 */
9261			lun_data->luns[num_filled].lundata[0] =
9262				RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9263			lun_data->luns[num_filled].lundata[1] =
9264				(targ_lun_id & 0xff);
9265			num_filled++;
9266		} else if (targ_lun_id <= 0xffffff) {
9267			/*
9268			 * Extended flat addressing method.
9269			 */
9270			lun_data->luns[num_filled].lundata[0] =
9271			    RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9272			scsi_ulto3b(targ_lun_id,
9273			    &lun_data->luns[num_filled].lundata[1]);
9274			num_filled++;
9275		} else {
9276			printf("ctl_report_luns: bogus LUN number %jd, "
9277			       "skipping\n", (intmax_t)targ_lun_id);
9278		}
9279		/*
9280		 * According to SPC-3, rev 14 section 6.21:
9281		 *
9282		 * "The execution of a REPORT LUNS command to any valid and
9283		 * installed logical unit shall clear the REPORTED LUNS DATA
9284		 * HAS CHANGED unit attention condition for all logical
9285		 * units of that target with respect to the requesting
9286		 * initiator. A valid and installed logical unit is one
9287		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9288		 * INQUIRY data (see 6.4.2)."
9289		 *
9290		 * If request_lun is NULL, the LUN this report luns command
9291		 * was issued to is either disabled or doesn't exist. In that
9292		 * case, we shouldn't clear any pending lun change unit
9293		 * attention.
9294		 */
9295		if (request_lun != NULL) {
9296			mtx_lock(&lun->lun_lock);
9297			lun->pending_ua[initidx] &= ~CTL_UA_LUN_CHANGE;
9298			mtx_unlock(&lun->lun_lock);
9299		}
9300	}
9301	mtx_unlock(&control_softc->ctl_lock);
9302
9303	/*
9304	 * It's quite possible that we've returned fewer LUNs than we allocated
9305	 * space for.  Trim it.
9306	 */
9307	lun_datalen = sizeof(*lun_data) +
9308		(num_filled * sizeof(struct scsi_report_luns_lundata));
9309
9310	if (lun_datalen < alloc_len) {
9311		ctsio->residual = alloc_len - lun_datalen;
9312		ctsio->kern_data_len = lun_datalen;
9313		ctsio->kern_total_len = lun_datalen;
9314	} else {
9315		ctsio->residual = 0;
9316		ctsio->kern_data_len = alloc_len;
9317		ctsio->kern_total_len = alloc_len;
9318	}
9319	ctsio->kern_data_resid = 0;
9320	ctsio->kern_rel_offset = 0;
9321	ctsio->kern_sg_entries = 0;
9322
9323	/*
9324	 * We set this to the actual data length, regardless of how much
9325	 * space we actually have to return results.  If the user looks at
9326	 * this value, he'll know whether or not he allocated enough space
9327	 * and reissue the command if necessary.  We don't support well
9328	 * known logical units, so if the user asks for that, return none.
9329	 */
9330	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9331
9332	/*
9333	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9334	 * this request.
9335	 */
9336	ctl_set_success(ctsio);
9337	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9338	ctsio->be_move_done = ctl_config_move_done;
9339	ctl_datamove((union ctl_io *)ctsio);
9340	return (retval);
9341}
9342
9343int
9344ctl_request_sense(struct ctl_scsiio *ctsio)
9345{
9346	struct scsi_request_sense *cdb;
9347	struct scsi_sense_data *sense_ptr;
9348	struct ctl_lun *lun;
9349	uint32_t initidx;
9350	int have_error;
9351	scsi_sense_data_type sense_format;
9352
9353	cdb = (struct scsi_request_sense *)ctsio->cdb;
9354
9355	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9356
9357	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9358
9359	/*
9360	 * Determine which sense format the user wants.
9361	 */
9362	if (cdb->byte2 & SRS_DESC)
9363		sense_format = SSD_TYPE_DESC;
9364	else
9365		sense_format = SSD_TYPE_FIXED;
9366
9367	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9368	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9369	ctsio->kern_sg_entries = 0;
9370
9371	/*
9372	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9373	 * larger than the largest allowed value for the length field in the
9374	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9375	 */
9376	ctsio->residual = 0;
9377	ctsio->kern_data_len = cdb->length;
9378	ctsio->kern_total_len = cdb->length;
9379
9380	ctsio->kern_data_resid = 0;
9381	ctsio->kern_rel_offset = 0;
9382	ctsio->kern_sg_entries = 0;
9383
9384	/*
9385	 * If we don't have a LUN, we don't have any pending sense.
9386	 */
9387	if (lun == NULL)
9388		goto no_sense;
9389
9390	have_error = 0;
9391	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9392	/*
9393	 * Check for pending sense, and then for pending unit attentions.
9394	 * Pending sense gets returned first, then pending unit attentions.
9395	 */
9396	mtx_lock(&lun->lun_lock);
9397#ifdef CTL_WITH_CA
9398	if (ctl_is_set(lun->have_ca, initidx)) {
9399		scsi_sense_data_type stored_format;
9400
9401		/*
9402		 * Check to see which sense format was used for the stored
9403		 * sense data.
9404		 */
9405		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9406
9407		/*
9408		 * If the user requested a different sense format than the
9409		 * one we stored, then we need to convert it to the other
9410		 * format.  If we're going from descriptor to fixed format
9411		 * sense data, we may lose things in translation, depending
9412		 * on what options were used.
9413		 *
9414		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9415		 * for some reason we'll just copy it out as-is.
9416		 */
9417		if ((stored_format == SSD_TYPE_FIXED)
9418		 && (sense_format == SSD_TYPE_DESC))
9419			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9420			    &lun->pending_sense[initidx],
9421			    (struct scsi_sense_data_desc *)sense_ptr);
9422		else if ((stored_format == SSD_TYPE_DESC)
9423		      && (sense_format == SSD_TYPE_FIXED))
9424			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9425			    &lun->pending_sense[initidx],
9426			    (struct scsi_sense_data_fixed *)sense_ptr);
9427		else
9428			memcpy(sense_ptr, &lun->pending_sense[initidx],
9429			       ctl_min(sizeof(*sense_ptr),
9430			       sizeof(lun->pending_sense[initidx])));
9431
9432		ctl_clear_mask(lun->have_ca, initidx);
9433		have_error = 1;
9434	} else
9435#endif
9436	if (lun->pending_ua[initidx] != CTL_UA_NONE) {
9437		ctl_ua_type ua_type;
9438
9439		ua_type = ctl_build_ua(&lun->pending_ua[initidx],
9440				       sense_ptr, sense_format);
9441		if (ua_type != CTL_UA_NONE)
9442			have_error = 1;
9443	}
9444	mtx_unlock(&lun->lun_lock);
9445
9446	/*
9447	 * We already have a pending error, return it.
9448	 */
9449	if (have_error != 0) {
9450		/*
9451		 * We report the SCSI status as OK, since the status of the
9452		 * request sense command itself is OK.
9453		 * We report 0 for the sense length, because we aren't doing
9454		 * autosense in this case.  We're reporting sense as
9455		 * parameter data.
9456		 */
9457		ctl_set_success(ctsio);
9458		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9459		ctsio->be_move_done = ctl_config_move_done;
9460		ctl_datamove((union ctl_io *)ctsio);
9461		return (CTL_RETVAL_COMPLETE);
9462	}
9463
9464no_sense:
9465
9466	/*
9467	 * No sense information to report, so we report that everything is
9468	 * okay.
9469	 */
9470	ctl_set_sense_data(sense_ptr,
9471			   lun,
9472			   sense_format,
9473			   /*current_error*/ 1,
9474			   /*sense_key*/ SSD_KEY_NO_SENSE,
9475			   /*asc*/ 0x00,
9476			   /*ascq*/ 0x00,
9477			   SSD_ELEM_NONE);
9478
9479	/*
9480	 * We report 0 for the sense length, because we aren't doing
9481	 * autosense in this case.  We're reporting sense as parameter data.
9482	 */
9483	ctl_set_success(ctsio);
9484	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9485	ctsio->be_move_done = ctl_config_move_done;
9486	ctl_datamove((union ctl_io *)ctsio);
9487	return (CTL_RETVAL_COMPLETE);
9488}
9489
9490int
9491ctl_tur(struct ctl_scsiio *ctsio)
9492{
9493
9494	CTL_DEBUG_PRINT(("ctl_tur\n"));
9495
9496	ctl_set_success(ctsio);
9497	ctl_done((union ctl_io *)ctsio);
9498
9499	return (CTL_RETVAL_COMPLETE);
9500}
9501
9502#ifdef notyet
9503static int
9504ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9505{
9506
9507}
9508#endif
9509
9510static int
9511ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9512{
9513	struct scsi_vpd_supported_pages *pages;
9514	int sup_page_size;
9515	struct ctl_lun *lun;
9516
9517	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9518
9519	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9520	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9521	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9522	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9523	ctsio->kern_sg_entries = 0;
9524
9525	if (sup_page_size < alloc_len) {
9526		ctsio->residual = alloc_len - sup_page_size;
9527		ctsio->kern_data_len = sup_page_size;
9528		ctsio->kern_total_len = sup_page_size;
9529	} else {
9530		ctsio->residual = 0;
9531		ctsio->kern_data_len = alloc_len;
9532		ctsio->kern_total_len = alloc_len;
9533	}
9534	ctsio->kern_data_resid = 0;
9535	ctsio->kern_rel_offset = 0;
9536	ctsio->kern_sg_entries = 0;
9537
9538	/*
9539	 * The control device is always connected.  The disk device, on the
9540	 * other hand, may not be online all the time.  Need to change this
9541	 * to figure out whether the disk device is actually online or not.
9542	 */
9543	if (lun != NULL)
9544		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9545				lun->be_lun->lun_type;
9546	else
9547		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9548
9549	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9550	/* Supported VPD pages */
9551	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9552	/* Serial Number */
9553	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9554	/* Device Identification */
9555	pages->page_list[2] = SVPD_DEVICE_ID;
9556	/* Extended INQUIRY Data */
9557	pages->page_list[3] = SVPD_EXTENDED_INQUIRY_DATA;
9558	/* Mode Page Policy */
9559	pages->page_list[4] = SVPD_MODE_PAGE_POLICY;
9560	/* SCSI Ports */
9561	pages->page_list[5] = SVPD_SCSI_PORTS;
9562	/* Third-party Copy */
9563	pages->page_list[6] = SVPD_SCSI_TPC;
9564	/* Block limits */
9565	pages->page_list[7] = SVPD_BLOCK_LIMITS;
9566	/* Block Device Characteristics */
9567	pages->page_list[8] = SVPD_BDC;
9568	/* Logical Block Provisioning */
9569	pages->page_list[9] = SVPD_LBP;
9570
9571	ctl_set_success(ctsio);
9572	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9573	ctsio->be_move_done = ctl_config_move_done;
9574	ctl_datamove((union ctl_io *)ctsio);
9575	return (CTL_RETVAL_COMPLETE);
9576}
9577
9578static int
9579ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9580{
9581	struct scsi_vpd_unit_serial_number *sn_ptr;
9582	struct ctl_lun *lun;
9583	int data_len;
9584
9585	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9586
9587	data_len = 4 + CTL_SN_LEN;
9588	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9589	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9590	if (data_len < alloc_len) {
9591		ctsio->residual = alloc_len - data_len;
9592		ctsio->kern_data_len = data_len;
9593		ctsio->kern_total_len = data_len;
9594	} else {
9595		ctsio->residual = 0;
9596		ctsio->kern_data_len = alloc_len;
9597		ctsio->kern_total_len = alloc_len;
9598	}
9599	ctsio->kern_data_resid = 0;
9600	ctsio->kern_rel_offset = 0;
9601	ctsio->kern_sg_entries = 0;
9602
9603	/*
9604	 * The control device is always connected.  The disk device, on the
9605	 * other hand, may not be online all the time.  Need to change this
9606	 * to figure out whether the disk device is actually online or not.
9607	 */
9608	if (lun != NULL)
9609		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9610				  lun->be_lun->lun_type;
9611	else
9612		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9613
9614	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9615	sn_ptr->length = CTL_SN_LEN;
9616	/*
9617	 * If we don't have a LUN, we just leave the serial number as
9618	 * all spaces.
9619	 */
9620	if (lun != NULL) {
9621		strncpy((char *)sn_ptr->serial_num,
9622			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9623	} else
9624		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9625
9626	ctl_set_success(ctsio);
9627	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9628	ctsio->be_move_done = ctl_config_move_done;
9629	ctl_datamove((union ctl_io *)ctsio);
9630	return (CTL_RETVAL_COMPLETE);
9631}
9632
9633
9634static int
9635ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9636{
9637	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9638	struct ctl_lun *lun;
9639	int data_len;
9640
9641	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9642
9643	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9644	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9645	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9646	ctsio->kern_sg_entries = 0;
9647
9648	if (data_len < alloc_len) {
9649		ctsio->residual = alloc_len - data_len;
9650		ctsio->kern_data_len = data_len;
9651		ctsio->kern_total_len = data_len;
9652	} else {
9653		ctsio->residual = 0;
9654		ctsio->kern_data_len = alloc_len;
9655		ctsio->kern_total_len = alloc_len;
9656	}
9657	ctsio->kern_data_resid = 0;
9658	ctsio->kern_rel_offset = 0;
9659	ctsio->kern_sg_entries = 0;
9660
9661	/*
9662	 * The control device is always connected.  The disk device, on the
9663	 * other hand, may not be online all the time.
9664	 */
9665	if (lun != NULL)
9666		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9667				     lun->be_lun->lun_type;
9668	else
9669		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9670	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9671	eid_ptr->page_length = data_len - 4;
9672	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9673	eid_ptr->flags3 = SVPD_EID_V_SUP;
9674
9675	ctl_set_success(ctsio);
9676	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9677	ctsio->be_move_done = ctl_config_move_done;
9678	ctl_datamove((union ctl_io *)ctsio);
9679	return (CTL_RETVAL_COMPLETE);
9680}
9681
9682static int
9683ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9684{
9685	struct scsi_vpd_mode_page_policy *mpp_ptr;
9686	struct ctl_lun *lun;
9687	int data_len;
9688
9689	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9690
9691	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9692	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9693
9694	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9695	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9696	ctsio->kern_sg_entries = 0;
9697
9698	if (data_len < alloc_len) {
9699		ctsio->residual = alloc_len - data_len;
9700		ctsio->kern_data_len = data_len;
9701		ctsio->kern_total_len = data_len;
9702	} else {
9703		ctsio->residual = 0;
9704		ctsio->kern_data_len = alloc_len;
9705		ctsio->kern_total_len = alloc_len;
9706	}
9707	ctsio->kern_data_resid = 0;
9708	ctsio->kern_rel_offset = 0;
9709	ctsio->kern_sg_entries = 0;
9710
9711	/*
9712	 * The control device is always connected.  The disk device, on the
9713	 * other hand, may not be online all the time.
9714	 */
9715	if (lun != NULL)
9716		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9717				     lun->be_lun->lun_type;
9718	else
9719		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9720	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9721	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9722	mpp_ptr->descr[0].page_code = 0x3f;
9723	mpp_ptr->descr[0].subpage_code = 0xff;
9724	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9725
9726	ctl_set_success(ctsio);
9727	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9728	ctsio->be_move_done = ctl_config_move_done;
9729	ctl_datamove((union ctl_io *)ctsio);
9730	return (CTL_RETVAL_COMPLETE);
9731}
9732
9733static int
9734ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9735{
9736	struct scsi_vpd_device_id *devid_ptr;
9737	struct scsi_vpd_id_descriptor *desc;
9738	struct ctl_softc *ctl_softc;
9739	struct ctl_lun *lun;
9740	struct ctl_port *port;
9741	int data_len;
9742	uint8_t proto;
9743
9744	ctl_softc = control_softc;
9745
9746	port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9747	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9748
9749	data_len = sizeof(struct scsi_vpd_device_id) +
9750	    sizeof(struct scsi_vpd_id_descriptor) +
9751		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9752	    sizeof(struct scsi_vpd_id_descriptor) +
9753		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9754	if (lun && lun->lun_devid)
9755		data_len += lun->lun_devid->len;
9756	if (port->port_devid)
9757		data_len += port->port_devid->len;
9758	if (port->target_devid)
9759		data_len += port->target_devid->len;
9760
9761	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9762	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9763	ctsio->kern_sg_entries = 0;
9764
9765	if (data_len < alloc_len) {
9766		ctsio->residual = alloc_len - data_len;
9767		ctsio->kern_data_len = data_len;
9768		ctsio->kern_total_len = data_len;
9769	} else {
9770		ctsio->residual = 0;
9771		ctsio->kern_data_len = alloc_len;
9772		ctsio->kern_total_len = alloc_len;
9773	}
9774	ctsio->kern_data_resid = 0;
9775	ctsio->kern_rel_offset = 0;
9776	ctsio->kern_sg_entries = 0;
9777
9778	/*
9779	 * The control device is always connected.  The disk device, on the
9780	 * other hand, may not be online all the time.
9781	 */
9782	if (lun != NULL)
9783		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9784				     lun->be_lun->lun_type;
9785	else
9786		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9787	devid_ptr->page_code = SVPD_DEVICE_ID;
9788	scsi_ulto2b(data_len - 4, devid_ptr->length);
9789
9790	if (port->port_type == CTL_PORT_FC)
9791		proto = SCSI_PROTO_FC << 4;
9792	else if (port->port_type == CTL_PORT_ISCSI)
9793		proto = SCSI_PROTO_ISCSI << 4;
9794	else
9795		proto = SCSI_PROTO_SPI << 4;
9796	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9797
9798	/*
9799	 * We're using a LUN association here.  i.e., this device ID is a
9800	 * per-LUN identifier.
9801	 */
9802	if (lun && lun->lun_devid) {
9803		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9804		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9805		    lun->lun_devid->len);
9806	}
9807
9808	/*
9809	 * This is for the WWPN which is a port association.
9810	 */
9811	if (port->port_devid) {
9812		memcpy(desc, port->port_devid->data, port->port_devid->len);
9813		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9814		    port->port_devid->len);
9815	}
9816
9817	/*
9818	 * This is for the Relative Target Port(type 4h) identifier
9819	 */
9820	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9821	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9822	    SVPD_ID_TYPE_RELTARG;
9823	desc->length = 4;
9824	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9825	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9826	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9827
9828	/*
9829	 * This is for the Target Port Group(type 5h) identifier
9830	 */
9831	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9832	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9833	    SVPD_ID_TYPE_TPORTGRP;
9834	desc->length = 4;
9835	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
9836	    &desc->identifier[2]);
9837	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9838	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9839
9840	/*
9841	 * This is for the Target identifier
9842	 */
9843	if (port->target_devid) {
9844		memcpy(desc, port->target_devid->data, port->target_devid->len);
9845	}
9846
9847	ctl_set_success(ctsio);
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	return (CTL_RETVAL_COMPLETE);
9852}
9853
9854static int
9855ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9856{
9857	struct ctl_softc *softc = control_softc;
9858	struct scsi_vpd_scsi_ports *sp;
9859	struct scsi_vpd_port_designation *pd;
9860	struct scsi_vpd_port_designation_cont *pdc;
9861	struct ctl_lun *lun;
9862	struct ctl_port *port;
9863	int data_len, num_target_ports, iid_len, id_len, g, pg, p;
9864	int num_target_port_groups;
9865
9866	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9867
9868	if (softc->is_single)
9869		num_target_port_groups = 1;
9870	else
9871		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
9872	num_target_ports = 0;
9873	iid_len = 0;
9874	id_len = 0;
9875	mtx_lock(&softc->ctl_lock);
9876	STAILQ_FOREACH(port, &softc->port_list, links) {
9877		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9878			continue;
9879		if (lun != NULL &&
9880		    ctl_map_lun_back(port->targ_port, lun->lun) >=
9881		    CTL_MAX_LUNS)
9882			continue;
9883		num_target_ports++;
9884		if (port->init_devid)
9885			iid_len += port->init_devid->len;
9886		if (port->port_devid)
9887			id_len += port->port_devid->len;
9888	}
9889	mtx_unlock(&softc->ctl_lock);
9890
9891	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
9892	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9893	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9894	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9895	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9896	ctsio->kern_sg_entries = 0;
9897
9898	if (data_len < alloc_len) {
9899		ctsio->residual = alloc_len - data_len;
9900		ctsio->kern_data_len = data_len;
9901		ctsio->kern_total_len = data_len;
9902	} else {
9903		ctsio->residual = 0;
9904		ctsio->kern_data_len = alloc_len;
9905		ctsio->kern_total_len = alloc_len;
9906	}
9907	ctsio->kern_data_resid = 0;
9908	ctsio->kern_rel_offset = 0;
9909	ctsio->kern_sg_entries = 0;
9910
9911	/*
9912	 * The control device is always connected.  The disk device, on the
9913	 * other hand, may not be online all the time.  Need to change this
9914	 * to figure out whether the disk device is actually online or not.
9915	 */
9916	if (lun != NULL)
9917		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9918				  lun->be_lun->lun_type;
9919	else
9920		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9921
9922	sp->page_code = SVPD_SCSI_PORTS;
9923	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9924	    sp->page_length);
9925	pd = &sp->design[0];
9926
9927	mtx_lock(&softc->ctl_lock);
9928	pg = softc->port_offset / CTL_MAX_PORTS;
9929	for (g = 0; g < num_target_port_groups; g++) {
9930		STAILQ_FOREACH(port, &softc->port_list, links) {
9931			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9932				continue;
9933			if (lun != NULL &&
9934			    ctl_map_lun_back(port->targ_port, lun->lun) >=
9935			    CTL_MAX_LUNS)
9936				continue;
9937			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
9938			scsi_ulto2b(p, pd->relative_port_id);
9939			if (port->init_devid && g == pg) {
9940				iid_len = port->init_devid->len;
9941				memcpy(pd->initiator_transportid,
9942				    port->init_devid->data, port->init_devid->len);
9943			} else
9944				iid_len = 0;
9945			scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9946			pdc = (struct scsi_vpd_port_designation_cont *)
9947			    (&pd->initiator_transportid[iid_len]);
9948			if (port->port_devid && g == pg) {
9949				id_len = port->port_devid->len;
9950				memcpy(pdc->target_port_descriptors,
9951				    port->port_devid->data, port->port_devid->len);
9952			} else
9953				id_len = 0;
9954			scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9955			pd = (struct scsi_vpd_port_designation *)
9956			    ((uint8_t *)pdc->target_port_descriptors + id_len);
9957		}
9958	}
9959	mtx_unlock(&softc->ctl_lock);
9960
9961	ctl_set_success(ctsio);
9962	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9963	ctsio->be_move_done = ctl_config_move_done;
9964	ctl_datamove((union ctl_io *)ctsio);
9965	return (CTL_RETVAL_COMPLETE);
9966}
9967
9968static int
9969ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9970{
9971	struct scsi_vpd_block_limits *bl_ptr;
9972	struct ctl_lun *lun;
9973	int bs;
9974
9975	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9976
9977	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9978	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9979	ctsio->kern_sg_entries = 0;
9980
9981	if (sizeof(*bl_ptr) < alloc_len) {
9982		ctsio->residual = alloc_len - sizeof(*bl_ptr);
9983		ctsio->kern_data_len = sizeof(*bl_ptr);
9984		ctsio->kern_total_len = sizeof(*bl_ptr);
9985	} else {
9986		ctsio->residual = 0;
9987		ctsio->kern_data_len = alloc_len;
9988		ctsio->kern_total_len = alloc_len;
9989	}
9990	ctsio->kern_data_resid = 0;
9991	ctsio->kern_rel_offset = 0;
9992	ctsio->kern_sg_entries = 0;
9993
9994	/*
9995	 * The control device is always connected.  The disk device, on the
9996	 * other hand, may not be online all the time.  Need to change this
9997	 * to figure out whether the disk device is actually online or not.
9998	 */
9999	if (lun != NULL)
10000		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10001				  lun->be_lun->lun_type;
10002	else
10003		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10004
10005	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10006	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10007	bl_ptr->max_cmp_write_len = 0xff;
10008	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10009	if (lun != NULL) {
10010		bs = lun->be_lun->blocksize;
10011		scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10012		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10013			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10014			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10015			if (lun->be_lun->pblockexp != 0) {
10016				scsi_ulto4b((1 << lun->be_lun->pblockexp),
10017				    bl_ptr->opt_unmap_grain);
10018				scsi_ulto4b(0x80000000 | lun->be_lun->pblockoff,
10019				    bl_ptr->unmap_grain_align);
10020			}
10021		}
10022		scsi_ulto4b(lun->be_lun->atomicblock,
10023		    bl_ptr->max_atomic_transfer_length);
10024		scsi_ulto4b(0, bl_ptr->atomic_alignment);
10025		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10026	}
10027	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10028
10029	ctl_set_success(ctsio);
10030	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10031	ctsio->be_move_done = ctl_config_move_done;
10032	ctl_datamove((union ctl_io *)ctsio);
10033	return (CTL_RETVAL_COMPLETE);
10034}
10035
10036static int
10037ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10038{
10039	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10040	struct ctl_lun *lun;
10041	const char *value;
10042	u_int i;
10043
10044	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10045
10046	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10047	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10048	ctsio->kern_sg_entries = 0;
10049
10050	if (sizeof(*bdc_ptr) < alloc_len) {
10051		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10052		ctsio->kern_data_len = sizeof(*bdc_ptr);
10053		ctsio->kern_total_len = sizeof(*bdc_ptr);
10054	} else {
10055		ctsio->residual = 0;
10056		ctsio->kern_data_len = alloc_len;
10057		ctsio->kern_total_len = alloc_len;
10058	}
10059	ctsio->kern_data_resid = 0;
10060	ctsio->kern_rel_offset = 0;
10061	ctsio->kern_sg_entries = 0;
10062
10063	/*
10064	 * The control device is always connected.  The disk device, on the
10065	 * other hand, may not be online all the time.  Need to change this
10066	 * to figure out whether the disk device is actually online or not.
10067	 */
10068	if (lun != NULL)
10069		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10070				  lun->be_lun->lun_type;
10071	else
10072		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10073	bdc_ptr->page_code = SVPD_BDC;
10074	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10075	if (lun != NULL &&
10076	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10077		i = strtol(value, NULL, 0);
10078	else
10079		i = CTL_DEFAULT_ROTATION_RATE;
10080	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10081	if (lun != NULL &&
10082	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10083		i = strtol(value, NULL, 0);
10084	else
10085		i = 0;
10086	bdc_ptr->wab_wac_ff = (i & 0x0f);
10087	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10088
10089	ctl_set_success(ctsio);
10090	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10091	ctsio->be_move_done = ctl_config_move_done;
10092	ctl_datamove((union ctl_io *)ctsio);
10093	return (CTL_RETVAL_COMPLETE);
10094}
10095
10096static int
10097ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10098{
10099	struct scsi_vpd_logical_block_prov *lbp_ptr;
10100	struct ctl_lun *lun;
10101
10102	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10103
10104	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10105	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10106	ctsio->kern_sg_entries = 0;
10107
10108	if (sizeof(*lbp_ptr) < alloc_len) {
10109		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10110		ctsio->kern_data_len = sizeof(*lbp_ptr);
10111		ctsio->kern_total_len = sizeof(*lbp_ptr);
10112	} else {
10113		ctsio->residual = 0;
10114		ctsio->kern_data_len = alloc_len;
10115		ctsio->kern_total_len = alloc_len;
10116	}
10117	ctsio->kern_data_resid = 0;
10118	ctsio->kern_rel_offset = 0;
10119	ctsio->kern_sg_entries = 0;
10120
10121	/*
10122	 * The control device is always connected.  The disk device, on the
10123	 * other hand, may not be online all the time.  Need to change this
10124	 * to figure out whether the disk device is actually online or not.
10125	 */
10126	if (lun != NULL)
10127		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10128				  lun->be_lun->lun_type;
10129	else
10130		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10131
10132	lbp_ptr->page_code = SVPD_LBP;
10133	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10134	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10135		lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10136		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10137		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10138		lbp_ptr->prov_type = SVPD_LBP_THIN;
10139	}
10140
10141	ctl_set_success(ctsio);
10142	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10143	ctsio->be_move_done = ctl_config_move_done;
10144	ctl_datamove((union ctl_io *)ctsio);
10145	return (CTL_RETVAL_COMPLETE);
10146}
10147
10148static int
10149ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10150{
10151	struct scsi_inquiry *cdb;
10152	int alloc_len, retval;
10153
10154	cdb = (struct scsi_inquiry *)ctsio->cdb;
10155
10156	retval = CTL_RETVAL_COMPLETE;
10157
10158	alloc_len = scsi_2btoul(cdb->length);
10159
10160	switch (cdb->page_code) {
10161	case SVPD_SUPPORTED_PAGES:
10162		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10163		break;
10164	case SVPD_UNIT_SERIAL_NUMBER:
10165		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10166		break;
10167	case SVPD_DEVICE_ID:
10168		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10169		break;
10170	case SVPD_EXTENDED_INQUIRY_DATA:
10171		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10172		break;
10173	case SVPD_MODE_PAGE_POLICY:
10174		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10175		break;
10176	case SVPD_SCSI_PORTS:
10177		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10178		break;
10179	case SVPD_SCSI_TPC:
10180		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10181		break;
10182	case SVPD_BLOCK_LIMITS:
10183		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10184		break;
10185	case SVPD_BDC:
10186		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10187		break;
10188	case SVPD_LBP:
10189		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10190		break;
10191	default:
10192		ctl_set_invalid_field(ctsio,
10193				      /*sks_valid*/ 1,
10194				      /*command*/ 1,
10195				      /*field*/ 2,
10196				      /*bit_valid*/ 0,
10197				      /*bit*/ 0);
10198		ctl_done((union ctl_io *)ctsio);
10199		retval = CTL_RETVAL_COMPLETE;
10200		break;
10201	}
10202
10203	return (retval);
10204}
10205
10206static int
10207ctl_inquiry_std(struct ctl_scsiio *ctsio)
10208{
10209	struct scsi_inquiry_data *inq_ptr;
10210	struct scsi_inquiry *cdb;
10211	struct ctl_softc *ctl_softc;
10212	struct ctl_lun *lun;
10213	char *val;
10214	uint32_t alloc_len, data_len;
10215	ctl_port_type port_type;
10216
10217	ctl_softc = control_softc;
10218
10219	/*
10220	 * Figure out whether we're talking to a Fibre Channel port or not.
10221	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10222	 * SCSI front ends.
10223	 */
10224	port_type = ctl_softc->ctl_ports[
10225	    ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10226	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10227		port_type = CTL_PORT_SCSI;
10228
10229	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10230	cdb = (struct scsi_inquiry *)ctsio->cdb;
10231	alloc_len = scsi_2btoul(cdb->length);
10232
10233	/*
10234	 * We malloc the full inquiry data size here and fill it
10235	 * in.  If the user only asks for less, we'll give him
10236	 * that much.
10237	 */
10238	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10239	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10240	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10241	ctsio->kern_sg_entries = 0;
10242	ctsio->kern_data_resid = 0;
10243	ctsio->kern_rel_offset = 0;
10244
10245	if (data_len < alloc_len) {
10246		ctsio->residual = alloc_len - data_len;
10247		ctsio->kern_data_len = data_len;
10248		ctsio->kern_total_len = data_len;
10249	} else {
10250		ctsio->residual = 0;
10251		ctsio->kern_data_len = alloc_len;
10252		ctsio->kern_total_len = alloc_len;
10253	}
10254
10255	/*
10256	 * If we have a LUN configured, report it as connected.  Otherwise,
10257	 * report that it is offline or no device is supported, depending
10258	 * on the value of inquiry_pq_no_lun.
10259	 *
10260	 * According to the spec (SPC-4 r34), the peripheral qualifier
10261	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10262	 *
10263	 * "A peripheral device having the specified peripheral device type
10264	 * is not connected to this logical unit. However, the device
10265	 * server is capable of supporting the specified peripheral device
10266	 * type on this logical unit."
10267	 *
10268	 * According to the same spec, the peripheral qualifier
10269	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10270	 *
10271	 * "The device server is not capable of supporting a peripheral
10272	 * device on this logical unit. For this peripheral qualifier the
10273	 * peripheral device type shall be set to 1Fh. All other peripheral
10274	 * device type values are reserved for this peripheral qualifier."
10275	 *
10276	 * Given the text, it would seem that we probably want to report that
10277	 * the LUN is offline here.  There is no LUN connected, but we can
10278	 * support a LUN at the given LUN number.
10279	 *
10280	 * In the real world, though, it sounds like things are a little
10281	 * different:
10282	 *
10283	 * - Linux, when presented with a LUN with the offline peripheral
10284	 *   qualifier, will create an sg driver instance for it.  So when
10285	 *   you attach it to CTL, you wind up with a ton of sg driver
10286	 *   instances.  (One for every LUN that Linux bothered to probe.)
10287	 *   Linux does this despite the fact that it issues a REPORT LUNs
10288	 *   to LUN 0 to get the inventory of supported LUNs.
10289	 *
10290	 * - There is other anecdotal evidence (from Emulex folks) about
10291	 *   arrays that use the offline peripheral qualifier for LUNs that
10292	 *   are on the "passive" path in an active/passive array.
10293	 *
10294	 * So the solution is provide a hopefully reasonable default
10295	 * (return bad/no LUN) and allow the user to change the behavior
10296	 * with a tunable/sysctl variable.
10297	 */
10298	if (lun != NULL)
10299		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10300				  lun->be_lun->lun_type;
10301	else if (ctl_softc->inquiry_pq_no_lun == 0)
10302		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10303	else
10304		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10305
10306	/* RMB in byte 2 is 0 */
10307	inq_ptr->version = SCSI_REV_SPC4;
10308
10309	/*
10310	 * According to SAM-3, even if a device only supports a single
10311	 * level of LUN addressing, it should still set the HISUP bit:
10312	 *
10313	 * 4.9.1 Logical unit numbers overview
10314	 *
10315	 * All logical unit number formats described in this standard are
10316	 * hierarchical in structure even when only a single level in that
10317	 * hierarchy is used. The HISUP bit shall be set to one in the
10318	 * standard INQUIRY data (see SPC-2) when any logical unit number
10319	 * format described in this standard is used.  Non-hierarchical
10320	 * formats are outside the scope of this standard.
10321	 *
10322	 * Therefore we set the HiSup bit here.
10323	 *
10324	 * The reponse format is 2, per SPC-3.
10325	 */
10326	inq_ptr->response_format = SID_HiSup | 2;
10327
10328	inq_ptr->additional_length = data_len -
10329	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10330	CTL_DEBUG_PRINT(("additional_length = %d\n",
10331			 inq_ptr->additional_length));
10332
10333	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10334	/* 16 bit addressing */
10335	if (port_type == CTL_PORT_SCSI)
10336		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10337	/* XXX set the SID_MultiP bit here if we're actually going to
10338	   respond on multiple ports */
10339	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10340
10341	/* 16 bit data bus, synchronous transfers */
10342	if (port_type == CTL_PORT_SCSI)
10343		inq_ptr->flags = SID_WBus16 | SID_Sync;
10344	/*
10345	 * XXX KDM do we want to support tagged queueing on the control
10346	 * device at all?
10347	 */
10348	if ((lun == NULL)
10349	 || (lun->be_lun->lun_type != T_PROCESSOR))
10350		inq_ptr->flags |= SID_CmdQue;
10351	/*
10352	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10353	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10354	 * name and 4 bytes for the revision.
10355	 */
10356	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10357	    "vendor")) == NULL) {
10358		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10359	} else {
10360		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10361		strncpy(inq_ptr->vendor, val,
10362		    min(sizeof(inq_ptr->vendor), strlen(val)));
10363	}
10364	if (lun == NULL) {
10365		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10366		    sizeof(inq_ptr->product));
10367	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10368		switch (lun->be_lun->lun_type) {
10369		case T_DIRECT:
10370			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10371			    sizeof(inq_ptr->product));
10372			break;
10373		case T_PROCESSOR:
10374			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10375			    sizeof(inq_ptr->product));
10376			break;
10377		default:
10378			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10379			    sizeof(inq_ptr->product));
10380			break;
10381		}
10382	} else {
10383		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10384		strncpy(inq_ptr->product, val,
10385		    min(sizeof(inq_ptr->product), strlen(val)));
10386	}
10387
10388	/*
10389	 * XXX make this a macro somewhere so it automatically gets
10390	 * incremented when we make changes.
10391	 */
10392	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10393	    "revision")) == NULL) {
10394		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10395	} else {
10396		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10397		strncpy(inq_ptr->revision, val,
10398		    min(sizeof(inq_ptr->revision), strlen(val)));
10399	}
10400
10401	/*
10402	 * For parallel SCSI, we support double transition and single
10403	 * transition clocking.  We also support QAS (Quick Arbitration
10404	 * and Selection) and Information Unit transfers on both the
10405	 * control and array devices.
10406	 */
10407	if (port_type == CTL_PORT_SCSI)
10408		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10409				    SID_SPI_IUS;
10410
10411	/* SAM-5 (no version claimed) */
10412	scsi_ulto2b(0x00A0, inq_ptr->version1);
10413	/* SPC-4 (no version claimed) */
10414	scsi_ulto2b(0x0460, inq_ptr->version2);
10415	if (port_type == CTL_PORT_FC) {
10416		/* FCP-2 ANSI INCITS.350:2003 */
10417		scsi_ulto2b(0x0917, inq_ptr->version3);
10418	} else if (port_type == CTL_PORT_SCSI) {
10419		/* SPI-4 ANSI INCITS.362:200x */
10420		scsi_ulto2b(0x0B56, inq_ptr->version3);
10421	} else if (port_type == CTL_PORT_ISCSI) {
10422		/* iSCSI (no version claimed) */
10423		scsi_ulto2b(0x0960, inq_ptr->version3);
10424	} else if (port_type == CTL_PORT_SAS) {
10425		/* SAS (no version claimed) */
10426		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10427	}
10428
10429	if (lun == NULL) {
10430		/* SBC-4 (no version claimed) */
10431		scsi_ulto2b(0x0600, inq_ptr->version4);
10432	} else {
10433		switch (lun->be_lun->lun_type) {
10434		case T_DIRECT:
10435			/* SBC-4 (no version claimed) */
10436			scsi_ulto2b(0x0600, inq_ptr->version4);
10437			break;
10438		case T_PROCESSOR:
10439		default:
10440			break;
10441		}
10442	}
10443
10444	ctl_set_success(ctsio);
10445	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10446	ctsio->be_move_done = ctl_config_move_done;
10447	ctl_datamove((union ctl_io *)ctsio);
10448	return (CTL_RETVAL_COMPLETE);
10449}
10450
10451int
10452ctl_inquiry(struct ctl_scsiio *ctsio)
10453{
10454	struct scsi_inquiry *cdb;
10455	int retval;
10456
10457	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10458
10459	cdb = (struct scsi_inquiry *)ctsio->cdb;
10460	if (cdb->byte2 & SI_EVPD)
10461		retval = ctl_inquiry_evpd(ctsio);
10462	else if (cdb->page_code == 0)
10463		retval = ctl_inquiry_std(ctsio);
10464	else {
10465		ctl_set_invalid_field(ctsio,
10466				      /*sks_valid*/ 1,
10467				      /*command*/ 1,
10468				      /*field*/ 2,
10469				      /*bit_valid*/ 0,
10470				      /*bit*/ 0);
10471		ctl_done((union ctl_io *)ctsio);
10472		return (CTL_RETVAL_COMPLETE);
10473	}
10474
10475	return (retval);
10476}
10477
10478/*
10479 * For known CDB types, parse the LBA and length.
10480 */
10481static int
10482ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10483{
10484	if (io->io_hdr.io_type != CTL_IO_SCSI)
10485		return (1);
10486
10487	switch (io->scsiio.cdb[0]) {
10488	case COMPARE_AND_WRITE: {
10489		struct scsi_compare_and_write *cdb;
10490
10491		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10492
10493		*lba = scsi_8btou64(cdb->addr);
10494		*len = cdb->length;
10495		break;
10496	}
10497	case READ_6:
10498	case WRITE_6: {
10499		struct scsi_rw_6 *cdb;
10500
10501		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10502
10503		*lba = scsi_3btoul(cdb->addr);
10504		/* only 5 bits are valid in the most significant address byte */
10505		*lba &= 0x1fffff;
10506		*len = cdb->length;
10507		break;
10508	}
10509	case READ_10:
10510	case WRITE_10: {
10511		struct scsi_rw_10 *cdb;
10512
10513		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10514
10515		*lba = scsi_4btoul(cdb->addr);
10516		*len = scsi_2btoul(cdb->length);
10517		break;
10518	}
10519	case WRITE_VERIFY_10: {
10520		struct scsi_write_verify_10 *cdb;
10521
10522		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10523
10524		*lba = scsi_4btoul(cdb->addr);
10525		*len = scsi_2btoul(cdb->length);
10526		break;
10527	}
10528	case READ_12:
10529	case WRITE_12: {
10530		struct scsi_rw_12 *cdb;
10531
10532		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10533
10534		*lba = scsi_4btoul(cdb->addr);
10535		*len = scsi_4btoul(cdb->length);
10536		break;
10537	}
10538	case WRITE_VERIFY_12: {
10539		struct scsi_write_verify_12 *cdb;
10540
10541		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10542
10543		*lba = scsi_4btoul(cdb->addr);
10544		*len = scsi_4btoul(cdb->length);
10545		break;
10546	}
10547	case READ_16:
10548	case WRITE_16:
10549	case WRITE_ATOMIC_16: {
10550		struct scsi_rw_16 *cdb;
10551
10552		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10553
10554		*lba = scsi_8btou64(cdb->addr);
10555		*len = scsi_4btoul(cdb->length);
10556		break;
10557	}
10558	case WRITE_VERIFY_16: {
10559		struct scsi_write_verify_16 *cdb;
10560
10561		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10562
10563		*lba = scsi_8btou64(cdb->addr);
10564		*len = scsi_4btoul(cdb->length);
10565		break;
10566	}
10567	case WRITE_SAME_10: {
10568		struct scsi_write_same_10 *cdb;
10569
10570		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10571
10572		*lba = scsi_4btoul(cdb->addr);
10573		*len = scsi_2btoul(cdb->length);
10574		break;
10575	}
10576	case WRITE_SAME_16: {
10577		struct scsi_write_same_16 *cdb;
10578
10579		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10580
10581		*lba = scsi_8btou64(cdb->addr);
10582		*len = scsi_4btoul(cdb->length);
10583		break;
10584	}
10585	case VERIFY_10: {
10586		struct scsi_verify_10 *cdb;
10587
10588		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10589
10590		*lba = scsi_4btoul(cdb->addr);
10591		*len = scsi_2btoul(cdb->length);
10592		break;
10593	}
10594	case VERIFY_12: {
10595		struct scsi_verify_12 *cdb;
10596
10597		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10598
10599		*lba = scsi_4btoul(cdb->addr);
10600		*len = scsi_4btoul(cdb->length);
10601		break;
10602	}
10603	case VERIFY_16: {
10604		struct scsi_verify_16 *cdb;
10605
10606		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10607
10608		*lba = scsi_8btou64(cdb->addr);
10609		*len = scsi_4btoul(cdb->length);
10610		break;
10611	}
10612	case UNMAP: {
10613		*lba = 0;
10614		*len = UINT64_MAX;
10615		break;
10616	}
10617	default:
10618		return (1);
10619		break; /* NOTREACHED */
10620	}
10621
10622	return (0);
10623}
10624
10625static ctl_action
10626ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2)
10627{
10628	uint64_t endlba1, endlba2;
10629
10630	endlba1 = lba1 + len1 - 1;
10631	endlba2 = lba2 + len2 - 1;
10632
10633	if ((endlba1 < lba2)
10634	 || (endlba2 < lba1))
10635		return (CTL_ACTION_PASS);
10636	else
10637		return (CTL_ACTION_BLOCK);
10638}
10639
10640static int
10641ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10642{
10643	struct ctl_ptr_len_flags *ptrlen;
10644	struct scsi_unmap_desc *buf, *end, *range;
10645	uint64_t lba;
10646	uint32_t len;
10647
10648	/* If not UNMAP -- go other way. */
10649	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10650	    io->scsiio.cdb[0] != UNMAP)
10651		return (CTL_ACTION_ERROR);
10652
10653	/* If UNMAP without data -- block and wait for data. */
10654	ptrlen = (struct ctl_ptr_len_flags *)
10655	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10656	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10657	    ptrlen->ptr == NULL)
10658		return (CTL_ACTION_BLOCK);
10659
10660	/* UNMAP with data -- check for collision. */
10661	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10662	end = buf + ptrlen->len / sizeof(*buf);
10663	for (range = buf; range < end; range++) {
10664		lba = scsi_8btou64(range->lba);
10665		len = scsi_4btoul(range->length);
10666		if ((lba < lba2 + len2) && (lba + len > lba2))
10667			return (CTL_ACTION_BLOCK);
10668	}
10669	return (CTL_ACTION_PASS);
10670}
10671
10672static ctl_action
10673ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10674{
10675	uint64_t lba1, lba2;
10676	uint64_t len1, len2;
10677	int retval;
10678
10679	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10680		return (CTL_ACTION_ERROR);
10681
10682	retval = ctl_extent_check_unmap(io2, lba1, len1);
10683	if (retval != CTL_ACTION_ERROR)
10684		return (retval);
10685
10686	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10687		return (CTL_ACTION_ERROR);
10688
10689	return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10690}
10691
10692static ctl_action
10693ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10694    union ctl_io *ooa_io)
10695{
10696	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10697	ctl_serialize_action *serialize_row;
10698
10699	/*
10700	 * The initiator attempted multiple untagged commands at the same
10701	 * time.  Can't do that.
10702	 */
10703	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10704	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10705	 && ((pending_io->io_hdr.nexus.targ_port ==
10706	      ooa_io->io_hdr.nexus.targ_port)
10707	  && (pending_io->io_hdr.nexus.initid.id ==
10708	      ooa_io->io_hdr.nexus.initid.id))
10709	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10710		return (CTL_ACTION_OVERLAP);
10711
10712	/*
10713	 * The initiator attempted to send multiple tagged commands with
10714	 * the same ID.  (It's fine if different initiators have the same
10715	 * tag ID.)
10716	 *
10717	 * Even if all of those conditions are true, we don't kill the I/O
10718	 * if the command ahead of us has been aborted.  We won't end up
10719	 * sending it to the FETD, and it's perfectly legal to resend a
10720	 * command with the same tag number as long as the previous
10721	 * instance of this tag number has been aborted somehow.
10722	 */
10723	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10724	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10725	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10726	 && ((pending_io->io_hdr.nexus.targ_port ==
10727	      ooa_io->io_hdr.nexus.targ_port)
10728	  && (pending_io->io_hdr.nexus.initid.id ==
10729	      ooa_io->io_hdr.nexus.initid.id))
10730	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10731		return (CTL_ACTION_OVERLAP_TAG);
10732
10733	/*
10734	 * If we get a head of queue tag, SAM-3 says that we should
10735	 * immediately execute it.
10736	 *
10737	 * What happens if this command would normally block for some other
10738	 * reason?  e.g. a request sense with a head of queue tag
10739	 * immediately after a write.  Normally that would block, but this
10740	 * will result in its getting executed immediately...
10741	 *
10742	 * We currently return "pass" instead of "skip", so we'll end up
10743	 * going through the rest of the queue to check for overlapped tags.
10744	 *
10745	 * XXX KDM check for other types of blockage first??
10746	 */
10747	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10748		return (CTL_ACTION_PASS);
10749
10750	/*
10751	 * Ordered tags have to block until all items ahead of them
10752	 * have completed.  If we get called with an ordered tag, we always
10753	 * block, if something else is ahead of us in the queue.
10754	 */
10755	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10756		return (CTL_ACTION_BLOCK);
10757
10758	/*
10759	 * Simple tags get blocked until all head of queue and ordered tags
10760	 * ahead of them have completed.  I'm lumping untagged commands in
10761	 * with simple tags here.  XXX KDM is that the right thing to do?
10762	 */
10763	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10764	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10765	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10766	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10767		return (CTL_ACTION_BLOCK);
10768
10769	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10770	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10771
10772	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10773
10774	switch (serialize_row[pending_entry->seridx]) {
10775	case CTL_SER_BLOCK:
10776		return (CTL_ACTION_BLOCK);
10777	case CTL_SER_EXTENT:
10778		return (ctl_extent_check(pending_io, ooa_io));
10779	case CTL_SER_EXTENTOPT:
10780		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10781		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10782			return (ctl_extent_check(pending_io, ooa_io));
10783		/* FALLTHROUGH */
10784	case CTL_SER_PASS:
10785		return (CTL_ACTION_PASS);
10786	case CTL_SER_BLOCKOPT:
10787		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10788		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10789			return (CTL_ACTION_BLOCK);
10790		return (CTL_ACTION_PASS);
10791	case CTL_SER_SKIP:
10792		return (CTL_ACTION_SKIP);
10793	default:
10794		panic("invalid serialization value %d",
10795		      serialize_row[pending_entry->seridx]);
10796	}
10797
10798	return (CTL_ACTION_ERROR);
10799}
10800
10801/*
10802 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10803 * Assumptions:
10804 * - pending_io is generally either incoming, or on the blocked queue
10805 * - starting I/O is the I/O we want to start the check with.
10806 */
10807static ctl_action
10808ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10809	      union ctl_io *starting_io)
10810{
10811	union ctl_io *ooa_io;
10812	ctl_action action;
10813
10814	mtx_assert(&lun->lun_lock, MA_OWNED);
10815
10816	/*
10817	 * Run back along the OOA queue, starting with the current
10818	 * blocked I/O and going through every I/O before it on the
10819	 * queue.  If starting_io is NULL, we'll just end up returning
10820	 * CTL_ACTION_PASS.
10821	 */
10822	for (ooa_io = starting_io; ooa_io != NULL;
10823	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10824	     ooa_links)){
10825
10826		/*
10827		 * This routine just checks to see whether
10828		 * cur_blocked is blocked by ooa_io, which is ahead
10829		 * of it in the queue.  It doesn't queue/dequeue
10830		 * cur_blocked.
10831		 */
10832		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10833		switch (action) {
10834		case CTL_ACTION_BLOCK:
10835		case CTL_ACTION_OVERLAP:
10836		case CTL_ACTION_OVERLAP_TAG:
10837		case CTL_ACTION_SKIP:
10838		case CTL_ACTION_ERROR:
10839			return (action);
10840			break; /* NOTREACHED */
10841		case CTL_ACTION_PASS:
10842			break;
10843		default:
10844			panic("invalid action %d", action);
10845			break;  /* NOTREACHED */
10846		}
10847	}
10848
10849	return (CTL_ACTION_PASS);
10850}
10851
10852/*
10853 * Assumptions:
10854 * - An I/O has just completed, and has been removed from the per-LUN OOA
10855 *   queue, so some items on the blocked queue may now be unblocked.
10856 */
10857static int
10858ctl_check_blocked(struct ctl_lun *lun)
10859{
10860	union ctl_io *cur_blocked, *next_blocked;
10861
10862	mtx_assert(&lun->lun_lock, MA_OWNED);
10863
10864	/*
10865	 * Run forward from the head of the blocked queue, checking each
10866	 * entry against the I/Os prior to it on the OOA queue to see if
10867	 * there is still any blockage.
10868	 *
10869	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10870	 * with our removing a variable on it while it is traversing the
10871	 * list.
10872	 */
10873	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10874	     cur_blocked != NULL; cur_blocked = next_blocked) {
10875		union ctl_io *prev_ooa;
10876		ctl_action action;
10877
10878		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10879							  blocked_links);
10880
10881		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10882						      ctl_ooaq, ooa_links);
10883
10884		/*
10885		 * If cur_blocked happens to be the first item in the OOA
10886		 * queue now, prev_ooa will be NULL, and the action
10887		 * returned will just be CTL_ACTION_PASS.
10888		 */
10889		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
10890
10891		switch (action) {
10892		case CTL_ACTION_BLOCK:
10893			/* Nothing to do here, still blocked */
10894			break;
10895		case CTL_ACTION_OVERLAP:
10896		case CTL_ACTION_OVERLAP_TAG:
10897			/*
10898			 * This shouldn't happen!  In theory we've already
10899			 * checked this command for overlap...
10900			 */
10901			break;
10902		case CTL_ACTION_PASS:
10903		case CTL_ACTION_SKIP: {
10904			struct ctl_softc *softc;
10905			const struct ctl_cmd_entry *entry;
10906			int isc_retval;
10907
10908			/*
10909			 * The skip case shouldn't happen, this transaction
10910			 * should have never made it onto the blocked queue.
10911			 */
10912			/*
10913			 * This I/O is no longer blocked, we can remove it
10914			 * from the blocked queue.  Since this is a TAILQ
10915			 * (doubly linked list), we can do O(1) removals
10916			 * from any place on the list.
10917			 */
10918			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
10919				     blocked_links);
10920			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10921
10922			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
10923				/*
10924				 * Need to send IO back to original side to
10925				 * run
10926				 */
10927				union ctl_ha_msg msg_info;
10928
10929				msg_info.hdr.original_sc =
10930					cur_blocked->io_hdr.original_sc;
10931				msg_info.hdr.serializing_sc = cur_blocked;
10932				msg_info.hdr.msg_type = CTL_MSG_R2R;
10933				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
10934				     &msg_info, sizeof(msg_info), 0)) >
10935				     CTL_HA_STATUS_SUCCESS) {
10936					printf("CTL:Check Blocked error from "
10937					       "ctl_ha_msg_send %d\n",
10938					       isc_retval);
10939				}
10940				break;
10941			}
10942			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
10943			softc = control_softc;
10944
10945			/*
10946			 * Check this I/O for LUN state changes that may
10947			 * have happened while this command was blocked.
10948			 * The LUN state may have been changed by a command
10949			 * ahead of us in the queue, so we need to re-check
10950			 * for any states that can be caused by SCSI
10951			 * commands.
10952			 */
10953			if (ctl_scsiio_lun_check(softc, lun, entry,
10954						 &cur_blocked->scsiio) == 0) {
10955				cur_blocked->io_hdr.flags |=
10956				                      CTL_FLAG_IS_WAS_ON_RTR;
10957				ctl_enqueue_rtr(cur_blocked);
10958			} else
10959				ctl_done(cur_blocked);
10960			break;
10961		}
10962		default:
10963			/*
10964			 * This probably shouldn't happen -- we shouldn't
10965			 * get CTL_ACTION_ERROR, or anything else.
10966			 */
10967			break;
10968		}
10969	}
10970
10971	return (CTL_RETVAL_COMPLETE);
10972}
10973
10974/*
10975 * This routine (with one exception) checks LUN flags that can be set by
10976 * commands ahead of us in the OOA queue.  These flags have to be checked
10977 * when a command initially comes in, and when we pull a command off the
10978 * blocked queue and are preparing to execute it.  The reason we have to
10979 * check these flags for commands on the blocked queue is that the LUN
10980 * state may have been changed by a command ahead of us while we're on the
10981 * blocked queue.
10982 *
10983 * Ordering is somewhat important with these checks, so please pay
10984 * careful attention to the placement of any new checks.
10985 */
10986static int
10987ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
10988    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
10989{
10990	int retval;
10991	uint32_t residx;
10992
10993	retval = 0;
10994
10995	mtx_assert(&lun->lun_lock, MA_OWNED);
10996
10997	/*
10998	 * If this shelf is a secondary shelf controller, we have to reject
10999	 * any media access commands.
11000	 */
11001	if ((ctl_softc->flags & CTL_FLAG_ACTIVE_SHELF) == 0 &&
11002	    (entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0) {
11003		ctl_set_lun_standby(ctsio);
11004		retval = 1;
11005		goto bailout;
11006	}
11007
11008	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11009		if (lun->flags & CTL_LUN_READONLY) {
11010			ctl_set_sense(ctsio, /*current_error*/ 1,
11011			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11012			    /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11013			retval = 1;
11014			goto bailout;
11015		}
11016		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11017		    .eca_and_aen & SCP_SWP) != 0) {
11018			ctl_set_sense(ctsio, /*current_error*/ 1,
11019			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11020			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11021			retval = 1;
11022			goto bailout;
11023		}
11024	}
11025
11026	/*
11027	 * Check for a reservation conflict.  If this command isn't allowed
11028	 * even on reserved LUNs, and if this initiator isn't the one who
11029	 * reserved us, reject the command with a reservation conflict.
11030	 */
11031	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11032	if ((lun->flags & CTL_LUN_RESERVED)
11033	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11034		if (lun->res_idx != residx) {
11035			ctl_set_reservation_conflict(ctsio);
11036			retval = 1;
11037			goto bailout;
11038		}
11039	}
11040
11041	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11042	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11043		/* No reservation or command is allowed. */;
11044	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11045	    (lun->res_type == SPR_TYPE_WR_EX ||
11046	     lun->res_type == SPR_TYPE_WR_EX_RO ||
11047	     lun->res_type == SPR_TYPE_WR_EX_AR)) {
11048		/* The command is allowed for Write Exclusive resv. */;
11049	} else {
11050		/*
11051		 * if we aren't registered or it's a res holder type
11052		 * reservation and this isn't the res holder then set a
11053		 * conflict.
11054		 */
11055		if (lun->pr_keys[residx] == 0
11056		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11057			ctl_set_reservation_conflict(ctsio);
11058			retval = 1;
11059			goto bailout;
11060		}
11061
11062	}
11063
11064	if ((lun->flags & CTL_LUN_OFFLINE)
11065	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11066		ctl_set_lun_not_ready(ctsio);
11067		retval = 1;
11068		goto bailout;
11069	}
11070
11071	/*
11072	 * If the LUN is stopped, see if this particular command is allowed
11073	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11074	 */
11075	if ((lun->flags & CTL_LUN_STOPPED)
11076	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11077		/* "Logical unit not ready, initializing cmd. required" */
11078		ctl_set_lun_stopped(ctsio);
11079		retval = 1;
11080		goto bailout;
11081	}
11082
11083	if ((lun->flags & CTL_LUN_INOPERABLE)
11084	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11085		/* "Medium format corrupted" */
11086		ctl_set_medium_format_corrupted(ctsio);
11087		retval = 1;
11088		goto bailout;
11089	}
11090
11091bailout:
11092	return (retval);
11093
11094}
11095
11096static void
11097ctl_failover_io(union ctl_io *io, int have_lock)
11098{
11099	ctl_set_busy(&io->scsiio);
11100	ctl_done(io);
11101}
11102
11103static void
11104ctl_failover(void)
11105{
11106	struct ctl_lun *lun;
11107	struct ctl_softc *ctl_softc;
11108	union ctl_io *next_io, *pending_io;
11109	union ctl_io *io;
11110	int lun_idx;
11111	int i;
11112
11113	ctl_softc = control_softc;
11114
11115	mtx_lock(&ctl_softc->ctl_lock);
11116	/*
11117	 * Remove any cmds from the other SC from the rtr queue.  These
11118	 * will obviously only be for LUNs for which we're the primary.
11119	 * We can't send status or get/send data for these commands.
11120	 * Since they haven't been executed yet, we can just remove them.
11121	 * We'll either abort them or delete them below, depending on
11122	 * which HA mode we're in.
11123	 */
11124#ifdef notyet
11125	mtx_lock(&ctl_softc->queue_lock);
11126	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11127	     io != NULL; io = next_io) {
11128		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11129		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11130			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11131				      ctl_io_hdr, links);
11132	}
11133	mtx_unlock(&ctl_softc->queue_lock);
11134#endif
11135
11136	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11137		lun = ctl_softc->ctl_luns[lun_idx];
11138		if (lun==NULL)
11139			continue;
11140
11141		/*
11142		 * Processor LUNs are primary on both sides.
11143		 * XXX will this always be true?
11144		 */
11145		if (lun->be_lun->lun_type == T_PROCESSOR)
11146			continue;
11147
11148		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11149		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11150			printf("FAILOVER: primary lun %d\n", lun_idx);
11151		        /*
11152			 * Remove all commands from the other SC. First from the
11153			 * blocked queue then from the ooa queue. Once we have
11154			 * removed them. Call ctl_check_blocked to see if there
11155			 * is anything that can run.
11156			 */
11157			for (io = (union ctl_io *)TAILQ_FIRST(
11158			     &lun->blocked_queue); io != NULL; io = next_io) {
11159
11160		        	next_io = (union ctl_io *)TAILQ_NEXT(
11161				    &io->io_hdr, blocked_links);
11162
11163				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11164					TAILQ_REMOVE(&lun->blocked_queue,
11165						     &io->io_hdr,blocked_links);
11166					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11167					TAILQ_REMOVE(&lun->ooa_queue,
11168						     &io->io_hdr, ooa_links);
11169
11170					ctl_free_io(io);
11171				}
11172			}
11173
11174			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11175	     		     io != NULL; io = next_io) {
11176
11177		        	next_io = (union ctl_io *)TAILQ_NEXT(
11178				    &io->io_hdr, ooa_links);
11179
11180				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11181
11182					TAILQ_REMOVE(&lun->ooa_queue,
11183						&io->io_hdr,
11184					     	ooa_links);
11185
11186					ctl_free_io(io);
11187				}
11188			}
11189			ctl_check_blocked(lun);
11190		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11191			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11192
11193			printf("FAILOVER: primary lun %d\n", lun_idx);
11194			/*
11195			 * Abort all commands from the other SC.  We can't
11196			 * send status back for them now.  These should get
11197			 * cleaned up when they are completed or come out
11198			 * for a datamove operation.
11199			 */
11200			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11201	     		     io != NULL; io = next_io) {
11202		        	next_io = (union ctl_io *)TAILQ_NEXT(
11203					&io->io_hdr, ooa_links);
11204
11205				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11206					io->io_hdr.flags |= CTL_FLAG_ABORT;
11207			}
11208		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11209			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11210
11211			printf("FAILOVER: secondary lun %d\n", lun_idx);
11212
11213			lun->flags |= CTL_LUN_PRIMARY_SC;
11214
11215			/*
11216			 * We send all I/O that was sent to this controller
11217			 * and redirected to the other side back with
11218			 * busy status, and have the initiator retry it.
11219			 * Figuring out how much data has been transferred,
11220			 * etc. and picking up where we left off would be
11221			 * very tricky.
11222			 *
11223			 * XXX KDM need to remove I/O from the blocked
11224			 * queue as well!
11225			 */
11226			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11227			     &lun->ooa_queue); pending_io != NULL;
11228			     pending_io = next_io) {
11229
11230				next_io =  (union ctl_io *)TAILQ_NEXT(
11231					&pending_io->io_hdr, ooa_links);
11232
11233				pending_io->io_hdr.flags &=
11234					~CTL_FLAG_SENT_2OTHER_SC;
11235
11236				if (pending_io->io_hdr.flags &
11237				    CTL_FLAG_IO_ACTIVE) {
11238					pending_io->io_hdr.flags |=
11239						CTL_FLAG_FAILOVER;
11240				} else {
11241					ctl_set_busy(&pending_io->scsiio);
11242					ctl_done(pending_io);
11243				}
11244			}
11245
11246			/*
11247			 * Build Unit Attention
11248			 */
11249			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11250				lun->pending_ua[i] |=
11251				                     CTL_UA_ASYM_ACC_CHANGE;
11252			}
11253		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11254			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11255			printf("FAILOVER: secondary lun %d\n", lun_idx);
11256			/*
11257			 * if the first io on the OOA is not on the RtR queue
11258			 * add it.
11259			 */
11260			lun->flags |= CTL_LUN_PRIMARY_SC;
11261
11262			pending_io = (union ctl_io *)TAILQ_FIRST(
11263			    &lun->ooa_queue);
11264			if (pending_io==NULL) {
11265				printf("Nothing on OOA queue\n");
11266				continue;
11267			}
11268
11269			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11270			if ((pending_io->io_hdr.flags &
11271			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11272				pending_io->io_hdr.flags |=
11273				    CTL_FLAG_IS_WAS_ON_RTR;
11274				ctl_enqueue_rtr(pending_io);
11275			}
11276#if 0
11277			else
11278			{
11279				printf("Tag 0x%04x is running\n",
11280				      pending_io->scsiio.tag_num);
11281			}
11282#endif
11283
11284			next_io = (union ctl_io *)TAILQ_NEXT(
11285			    &pending_io->io_hdr, ooa_links);
11286			for (pending_io=next_io; pending_io != NULL;
11287			     pending_io = next_io) {
11288				pending_io->io_hdr.flags &=
11289				    ~CTL_FLAG_SENT_2OTHER_SC;
11290				next_io = (union ctl_io *)TAILQ_NEXT(
11291					&pending_io->io_hdr, ooa_links);
11292				if (pending_io->io_hdr.flags &
11293				    CTL_FLAG_IS_WAS_ON_RTR) {
11294#if 0
11295				        printf("Tag 0x%04x is running\n",
11296				      		pending_io->scsiio.tag_num);
11297#endif
11298					continue;
11299				}
11300
11301				switch (ctl_check_ooa(lun, pending_io,
11302			            (union ctl_io *)TAILQ_PREV(
11303				    &pending_io->io_hdr, ctl_ooaq,
11304				    ooa_links))) {
11305
11306				case CTL_ACTION_BLOCK:
11307					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11308							  &pending_io->io_hdr,
11309							  blocked_links);
11310					pending_io->io_hdr.flags |=
11311					    CTL_FLAG_BLOCKED;
11312					break;
11313				case CTL_ACTION_PASS:
11314				case CTL_ACTION_SKIP:
11315					pending_io->io_hdr.flags |=
11316					    CTL_FLAG_IS_WAS_ON_RTR;
11317					ctl_enqueue_rtr(pending_io);
11318					break;
11319				case CTL_ACTION_OVERLAP:
11320					ctl_set_overlapped_cmd(
11321					    (struct ctl_scsiio *)pending_io);
11322					ctl_done(pending_io);
11323					break;
11324				case CTL_ACTION_OVERLAP_TAG:
11325					ctl_set_overlapped_tag(
11326					    (struct ctl_scsiio *)pending_io,
11327					    pending_io->scsiio.tag_num & 0xff);
11328					ctl_done(pending_io);
11329					break;
11330				case CTL_ACTION_ERROR:
11331				default:
11332					ctl_set_internal_failure(
11333						(struct ctl_scsiio *)pending_io,
11334						0,  // sks_valid
11335						0); //retry count
11336					ctl_done(pending_io);
11337					break;
11338				}
11339			}
11340
11341			/*
11342			 * Build Unit Attention
11343			 */
11344			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11345				lun->pending_ua[i] |=
11346				                     CTL_UA_ASYM_ACC_CHANGE;
11347			}
11348		} else {
11349			panic("Unhandled HA mode failover, LUN flags = %#x, "
11350			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11351		}
11352	}
11353	ctl_pause_rtr = 0;
11354	mtx_unlock(&ctl_softc->ctl_lock);
11355}
11356
11357static int
11358ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11359{
11360	struct ctl_lun *lun;
11361	const struct ctl_cmd_entry *entry;
11362	uint32_t initidx, targ_lun;
11363	int retval;
11364
11365	retval = 0;
11366
11367	lun = NULL;
11368
11369	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11370	if ((targ_lun < CTL_MAX_LUNS)
11371	 && ((lun = ctl_softc->ctl_luns[targ_lun]) != NULL)) {
11372		/*
11373		 * If the LUN is invalid, pretend that it doesn't exist.
11374		 * It will go away as soon as all pending I/O has been
11375		 * completed.
11376		 */
11377		mtx_lock(&lun->lun_lock);
11378		if (lun->flags & CTL_LUN_DISABLED) {
11379			mtx_unlock(&lun->lun_lock);
11380			lun = NULL;
11381			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11382			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11383		} else {
11384			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11385			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11386				lun->be_lun;
11387			if (lun->be_lun->lun_type == T_PROCESSOR) {
11388				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11389			}
11390
11391			/*
11392			 * Every I/O goes into the OOA queue for a
11393			 * particular LUN, and stays there until completion.
11394			 */
11395			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11396			    ooa_links);
11397		}
11398	} else {
11399		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11400		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11401	}
11402
11403	/* Get command entry and return error if it is unsuppotyed. */
11404	entry = ctl_validate_command(ctsio);
11405	if (entry == NULL) {
11406		if (lun)
11407			mtx_unlock(&lun->lun_lock);
11408		return (retval);
11409	}
11410
11411	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11412	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11413
11414	/*
11415	 * Check to see whether we can send this command to LUNs that don't
11416	 * exist.  This should pretty much only be the case for inquiry
11417	 * and request sense.  Further checks, below, really require having
11418	 * a LUN, so we can't really check the command anymore.  Just put
11419	 * it on the rtr queue.
11420	 */
11421	if (lun == NULL) {
11422		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11423			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11424			ctl_enqueue_rtr((union ctl_io *)ctsio);
11425			return (retval);
11426		}
11427
11428		ctl_set_unsupported_lun(ctsio);
11429		ctl_done((union ctl_io *)ctsio);
11430		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11431		return (retval);
11432	} else {
11433		/*
11434		 * Make sure we support this particular command on this LUN.
11435		 * e.g., we don't support writes to the control LUN.
11436		 */
11437		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11438			mtx_unlock(&lun->lun_lock);
11439			ctl_set_invalid_opcode(ctsio);
11440			ctl_done((union ctl_io *)ctsio);
11441			return (retval);
11442		}
11443	}
11444
11445	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11446
11447#ifdef CTL_WITH_CA
11448	/*
11449	 * If we've got a request sense, it'll clear the contingent
11450	 * allegiance condition.  Otherwise, if we have a CA condition for
11451	 * this initiator, clear it, because it sent down a command other
11452	 * than request sense.
11453	 */
11454	if ((ctsio->cdb[0] != REQUEST_SENSE)
11455	 && (ctl_is_set(lun->have_ca, initidx)))
11456		ctl_clear_mask(lun->have_ca, initidx);
11457#endif
11458
11459	/*
11460	 * If the command has this flag set, it handles its own unit
11461	 * attention reporting, we shouldn't do anything.  Otherwise we
11462	 * check for any pending unit attentions, and send them back to the
11463	 * initiator.  We only do this when a command initially comes in,
11464	 * not when we pull it off the blocked queue.
11465	 *
11466	 * According to SAM-3, section 5.3.2, the order that things get
11467	 * presented back to the host is basically unit attentions caused
11468	 * by some sort of reset event, busy status, reservation conflicts
11469	 * or task set full, and finally any other status.
11470	 *
11471	 * One issue here is that some of the unit attentions we report
11472	 * don't fall into the "reset" category (e.g. "reported luns data
11473	 * has changed").  So reporting it here, before the reservation
11474	 * check, may be technically wrong.  I guess the only thing to do
11475	 * would be to check for and report the reset events here, and then
11476	 * check for the other unit attention types after we check for a
11477	 * reservation conflict.
11478	 *
11479	 * XXX KDM need to fix this
11480	 */
11481	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11482		ctl_ua_type ua_type;
11483
11484		if (lun->pending_ua[initidx] != CTL_UA_NONE) {
11485			scsi_sense_data_type sense_format;
11486
11487			if (lun != NULL)
11488				sense_format = (lun->flags &
11489				    CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11490				    SSD_TYPE_FIXED;
11491			else
11492				sense_format = SSD_TYPE_FIXED;
11493
11494			ua_type = ctl_build_ua(&lun->pending_ua[initidx],
11495			    &ctsio->sense_data, sense_format);
11496			if (ua_type != CTL_UA_NONE) {
11497				ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11498				ctsio->io_hdr.status = CTL_SCSI_ERROR |
11499						       CTL_AUTOSENSE;
11500				ctsio->sense_len = SSD_FULL_SIZE;
11501				mtx_unlock(&lun->lun_lock);
11502				ctl_done((union ctl_io *)ctsio);
11503				return (retval);
11504			}
11505		}
11506	}
11507
11508
11509	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11510		mtx_unlock(&lun->lun_lock);
11511		ctl_done((union ctl_io *)ctsio);
11512		return (retval);
11513	}
11514
11515	/*
11516	 * XXX CHD this is where we want to send IO to other side if
11517	 * this LUN is secondary on this SC. We will need to make a copy
11518	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11519	 * the copy we send as FROM_OTHER.
11520	 * We also need to stuff the address of the original IO so we can
11521	 * find it easily. Something similar will need be done on the other
11522	 * side so when we are done we can find the copy.
11523	 */
11524	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11525		union ctl_ha_msg msg_info;
11526		int isc_retval;
11527
11528		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11529
11530		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11531		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11532#if 0
11533		printf("1. ctsio %p\n", ctsio);
11534#endif
11535		msg_info.hdr.serializing_sc = NULL;
11536		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11537		msg_info.scsi.tag_num = ctsio->tag_num;
11538		msg_info.scsi.tag_type = ctsio->tag_type;
11539		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11540
11541		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11542
11543		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11544		    (void *)&msg_info, sizeof(msg_info), 0)) >
11545		    CTL_HA_STATUS_SUCCESS) {
11546			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11547			       isc_retval);
11548			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11549		} else {
11550#if 0
11551			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11552#endif
11553		}
11554
11555		/*
11556		 * XXX KDM this I/O is off the incoming queue, but hasn't
11557		 * been inserted on any other queue.  We may need to come
11558		 * up with a holding queue while we wait for serialization
11559		 * so that we have an idea of what we're waiting for from
11560		 * the other side.
11561		 */
11562		mtx_unlock(&lun->lun_lock);
11563		return (retval);
11564	}
11565
11566	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11567			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11568			      ctl_ooaq, ooa_links))) {
11569	case CTL_ACTION_BLOCK:
11570		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11571		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11572				  blocked_links);
11573		mtx_unlock(&lun->lun_lock);
11574		return (retval);
11575	case CTL_ACTION_PASS:
11576	case CTL_ACTION_SKIP:
11577		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11578		mtx_unlock(&lun->lun_lock);
11579		ctl_enqueue_rtr((union ctl_io *)ctsio);
11580		break;
11581	case CTL_ACTION_OVERLAP:
11582		mtx_unlock(&lun->lun_lock);
11583		ctl_set_overlapped_cmd(ctsio);
11584		ctl_done((union ctl_io *)ctsio);
11585		break;
11586	case CTL_ACTION_OVERLAP_TAG:
11587		mtx_unlock(&lun->lun_lock);
11588		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11589		ctl_done((union ctl_io *)ctsio);
11590		break;
11591	case CTL_ACTION_ERROR:
11592	default:
11593		mtx_unlock(&lun->lun_lock);
11594		ctl_set_internal_failure(ctsio,
11595					 /*sks_valid*/ 0,
11596					 /*retry_count*/ 0);
11597		ctl_done((union ctl_io *)ctsio);
11598		break;
11599	}
11600	return (retval);
11601}
11602
11603const struct ctl_cmd_entry *
11604ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11605{
11606	const struct ctl_cmd_entry *entry;
11607	int service_action;
11608
11609	entry = &ctl_cmd_table[ctsio->cdb[0]];
11610	if (sa)
11611		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11612	if (entry->flags & CTL_CMD_FLAG_SA5) {
11613		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11614		entry = &((const struct ctl_cmd_entry *)
11615		    entry->execute)[service_action];
11616	}
11617	return (entry);
11618}
11619
11620const struct ctl_cmd_entry *
11621ctl_validate_command(struct ctl_scsiio *ctsio)
11622{
11623	const struct ctl_cmd_entry *entry;
11624	int i, sa;
11625	uint8_t diff;
11626
11627	entry = ctl_get_cmd_entry(ctsio, &sa);
11628	if (entry->execute == NULL) {
11629		if (sa)
11630			ctl_set_invalid_field(ctsio,
11631					      /*sks_valid*/ 1,
11632					      /*command*/ 1,
11633					      /*field*/ 1,
11634					      /*bit_valid*/ 1,
11635					      /*bit*/ 4);
11636		else
11637			ctl_set_invalid_opcode(ctsio);
11638		ctl_done((union ctl_io *)ctsio);
11639		return (NULL);
11640	}
11641	KASSERT(entry->length > 0,
11642	    ("Not defined length for command 0x%02x/0x%02x",
11643	     ctsio->cdb[0], ctsio->cdb[1]));
11644	for (i = 1; i < entry->length; i++) {
11645		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11646		if (diff == 0)
11647			continue;
11648		ctl_set_invalid_field(ctsio,
11649				      /*sks_valid*/ 1,
11650				      /*command*/ 1,
11651				      /*field*/ i,
11652				      /*bit_valid*/ 1,
11653				      /*bit*/ fls(diff) - 1);
11654		ctl_done((union ctl_io *)ctsio);
11655		return (NULL);
11656	}
11657	return (entry);
11658}
11659
11660static int
11661ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11662{
11663
11664	switch (lun_type) {
11665	case T_PROCESSOR:
11666		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11667		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11668			return (0);
11669		break;
11670	case T_DIRECT:
11671		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11672		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11673			return (0);
11674		break;
11675	default:
11676		return (0);
11677	}
11678	return (1);
11679}
11680
11681static int
11682ctl_scsiio(struct ctl_scsiio *ctsio)
11683{
11684	int retval;
11685	const struct ctl_cmd_entry *entry;
11686
11687	retval = CTL_RETVAL_COMPLETE;
11688
11689	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11690
11691	entry = ctl_get_cmd_entry(ctsio, NULL);
11692
11693	/*
11694	 * If this I/O has been aborted, just send it straight to
11695	 * ctl_done() without executing it.
11696	 */
11697	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11698		ctl_done((union ctl_io *)ctsio);
11699		goto bailout;
11700	}
11701
11702	/*
11703	 * All the checks should have been handled by ctl_scsiio_precheck().
11704	 * We should be clear now to just execute the I/O.
11705	 */
11706	retval = entry->execute(ctsio);
11707
11708bailout:
11709	return (retval);
11710}
11711
11712/*
11713 * Since we only implement one target right now, a bus reset simply resets
11714 * our single target.
11715 */
11716static int
11717ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11718{
11719	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11720}
11721
11722static int
11723ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11724		 ctl_ua_type ua_type)
11725{
11726	struct ctl_lun *lun;
11727	int retval;
11728
11729	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11730		union ctl_ha_msg msg_info;
11731
11732		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11733		msg_info.hdr.nexus = io->io_hdr.nexus;
11734		if (ua_type==CTL_UA_TARG_RESET)
11735			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11736		else
11737			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11738		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11739		msg_info.hdr.original_sc = NULL;
11740		msg_info.hdr.serializing_sc = NULL;
11741		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11742		    (void *)&msg_info, sizeof(msg_info), 0)) {
11743		}
11744	}
11745	retval = 0;
11746
11747	mtx_lock(&ctl_softc->ctl_lock);
11748	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11749		retval += ctl_lun_reset(lun, io, ua_type);
11750	mtx_unlock(&ctl_softc->ctl_lock);
11751
11752	return (retval);
11753}
11754
11755/*
11756 * The LUN should always be set.  The I/O is optional, and is used to
11757 * distinguish between I/Os sent by this initiator, and by other
11758 * initiators.  We set unit attention for initiators other than this one.
11759 * SAM-3 is vague on this point.  It does say that a unit attention should
11760 * be established for other initiators when a LUN is reset (see section
11761 * 5.7.3), but it doesn't specifically say that the unit attention should
11762 * be established for this particular initiator when a LUN is reset.  Here
11763 * is the relevant text, from SAM-3 rev 8:
11764 *
11765 * 5.7.2 When a SCSI initiator port aborts its own tasks
11766 *
11767 * When a SCSI initiator port causes its own task(s) to be aborted, no
11768 * notification that the task(s) have been aborted shall be returned to
11769 * the SCSI initiator port other than the completion response for the
11770 * command or task management function action that caused the task(s) to
11771 * be aborted and notification(s) associated with related effects of the
11772 * action (e.g., a reset unit attention condition).
11773 *
11774 * XXX KDM for now, we're setting unit attention for all initiators.
11775 */
11776static int
11777ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11778{
11779	union ctl_io *xio;
11780#if 0
11781	uint32_t initidx;
11782#endif
11783	int i;
11784
11785	mtx_lock(&lun->lun_lock);
11786	/*
11787	 * Run through the OOA queue and abort each I/O.
11788	 */
11789#if 0
11790	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11791#endif
11792	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11793	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11794		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11795	}
11796
11797	/*
11798	 * This version sets unit attention for every
11799	 */
11800#if 0
11801	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11802	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11803		if (initidx == i)
11804			continue;
11805		lun->pending_ua[i] |= ua_type;
11806	}
11807#endif
11808
11809	/*
11810	 * A reset (any kind, really) clears reservations established with
11811	 * RESERVE/RELEASE.  It does not clear reservations established
11812	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11813	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11814	 * reservations made with the RESERVE/RELEASE commands, because
11815	 * those commands are obsolete in SPC-3.
11816	 */
11817	lun->flags &= ~CTL_LUN_RESERVED;
11818
11819	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11820#ifdef CTL_WITH_CA
11821		ctl_clear_mask(lun->have_ca, i);
11822#endif
11823		lun->pending_ua[i] |= ua_type;
11824	}
11825	mtx_unlock(&lun->lun_lock);
11826
11827	return (0);
11828}
11829
11830static void
11831ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11832    int other_sc)
11833{
11834	union ctl_io *xio;
11835
11836	mtx_assert(&lun->lun_lock, MA_OWNED);
11837
11838	/*
11839	 * Run through the OOA queue and attempt to find the given I/O.
11840	 * The target port, initiator ID, tag type and tag number have to
11841	 * match the values that we got from the initiator.  If we have an
11842	 * untagged command to abort, simply abort the first untagged command
11843	 * we come to.  We only allow one untagged command at a time of course.
11844	 */
11845	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11846	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11847
11848		if ((targ_port == UINT32_MAX ||
11849		     targ_port == xio->io_hdr.nexus.targ_port) &&
11850		    (init_id == UINT32_MAX ||
11851		     init_id == xio->io_hdr.nexus.initid.id)) {
11852			if (targ_port != xio->io_hdr.nexus.targ_port ||
11853			    init_id != xio->io_hdr.nexus.initid.id)
11854				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11855			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11856			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11857				union ctl_ha_msg msg_info;
11858
11859				msg_info.hdr.nexus = xio->io_hdr.nexus;
11860				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11861				msg_info.task.tag_num = xio->scsiio.tag_num;
11862				msg_info.task.tag_type = xio->scsiio.tag_type;
11863				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11864				msg_info.hdr.original_sc = NULL;
11865				msg_info.hdr.serializing_sc = NULL;
11866				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11867				    (void *)&msg_info, sizeof(msg_info), 0);
11868			}
11869		}
11870	}
11871}
11872
11873static int
11874ctl_abort_task_set(union ctl_io *io)
11875{
11876	struct ctl_softc *softc = control_softc;
11877	struct ctl_lun *lun;
11878	uint32_t targ_lun;
11879
11880	/*
11881	 * Look up the LUN.
11882	 */
11883	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11884	mtx_lock(&softc->ctl_lock);
11885	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
11886		lun = softc->ctl_luns[targ_lun];
11887	else {
11888		mtx_unlock(&softc->ctl_lock);
11889		return (1);
11890	}
11891
11892	mtx_lock(&lun->lun_lock);
11893	mtx_unlock(&softc->ctl_lock);
11894	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11895		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11896		    io->io_hdr.nexus.initid.id,
11897		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11898	} else { /* CTL_TASK_CLEAR_TASK_SET */
11899		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11900		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11901	}
11902	mtx_unlock(&lun->lun_lock);
11903	return (0);
11904}
11905
11906static int
11907ctl_i_t_nexus_reset(union ctl_io *io)
11908{
11909	struct ctl_softc *softc = control_softc;
11910	struct ctl_lun *lun;
11911	uint32_t initidx, residx;
11912
11913	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11914	residx = ctl_get_resindex(&io->io_hdr.nexus);
11915	mtx_lock(&softc->ctl_lock);
11916	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11917		mtx_lock(&lun->lun_lock);
11918		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11919		    io->io_hdr.nexus.initid.id,
11920		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11921#ifdef CTL_WITH_CA
11922		ctl_clear_mask(lun->have_ca, initidx);
11923#endif
11924		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
11925			lun->flags &= ~CTL_LUN_RESERVED;
11926		lun->pending_ua[initidx] |= CTL_UA_I_T_NEXUS_LOSS;
11927		mtx_unlock(&lun->lun_lock);
11928	}
11929	mtx_unlock(&softc->ctl_lock);
11930	return (0);
11931}
11932
11933static int
11934ctl_abort_task(union ctl_io *io)
11935{
11936	union ctl_io *xio;
11937	struct ctl_lun *lun;
11938	struct ctl_softc *ctl_softc;
11939#if 0
11940	struct sbuf sb;
11941	char printbuf[128];
11942#endif
11943	int found;
11944	uint32_t targ_lun;
11945
11946	ctl_softc = control_softc;
11947	found = 0;
11948
11949	/*
11950	 * Look up the LUN.
11951	 */
11952	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11953	mtx_lock(&ctl_softc->ctl_lock);
11954	if ((targ_lun < CTL_MAX_LUNS)
11955	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
11956		lun = ctl_softc->ctl_luns[targ_lun];
11957	else {
11958		mtx_unlock(&ctl_softc->ctl_lock);
11959		return (1);
11960	}
11961
11962#if 0
11963	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11964	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11965#endif
11966
11967	mtx_lock(&lun->lun_lock);
11968	mtx_unlock(&ctl_softc->ctl_lock);
11969	/*
11970	 * Run through the OOA queue and attempt to find the given I/O.
11971	 * The target port, initiator ID, tag type and tag number have to
11972	 * match the values that we got from the initiator.  If we have an
11973	 * untagged command to abort, simply abort the first untagged command
11974	 * we come to.  We only allow one untagged command at a time of course.
11975	 */
11976#if 0
11977	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11978#endif
11979	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11980	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11981#if 0
11982		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
11983
11984		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
11985			    lun->lun, xio->scsiio.tag_num,
11986			    xio->scsiio.tag_type,
11987			    (xio->io_hdr.blocked_links.tqe_prev
11988			    == NULL) ? "" : " BLOCKED",
11989			    (xio->io_hdr.flags &
11990			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
11991			    (xio->io_hdr.flags &
11992			    CTL_FLAG_ABORT) ? " ABORT" : "",
11993			    (xio->io_hdr.flags &
11994			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
11995		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
11996		sbuf_finish(&sb);
11997		printf("%s\n", sbuf_data(&sb));
11998#endif
11999
12000		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12001		 && (xio->io_hdr.nexus.initid.id ==
12002		     io->io_hdr.nexus.initid.id)) {
12003			/*
12004			 * If the abort says that the task is untagged, the
12005			 * task in the queue must be untagged.  Otherwise,
12006			 * we just check to see whether the tag numbers
12007			 * match.  This is because the QLogic firmware
12008			 * doesn't pass back the tag type in an abort
12009			 * request.
12010			 */
12011#if 0
12012			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12013			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12014			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12015#endif
12016			/*
12017			 * XXX KDM we've got problems with FC, because it
12018			 * doesn't send down a tag type with aborts.  So we
12019			 * can only really go by the tag number...
12020			 * This may cause problems with parallel SCSI.
12021			 * Need to figure that out!!
12022			 */
12023			if (xio->scsiio.tag_num == io->taskio.tag_num) {
12024				xio->io_hdr.flags |= CTL_FLAG_ABORT;
12025				found = 1;
12026				if ((io->io_hdr.flags &
12027				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
12028				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12029					union ctl_ha_msg msg_info;
12030
12031					io->io_hdr.flags |=
12032					                CTL_FLAG_SENT_2OTHER_SC;
12033					msg_info.hdr.nexus = io->io_hdr.nexus;
12034					msg_info.task.task_action =
12035						CTL_TASK_ABORT_TASK;
12036					msg_info.task.tag_num =
12037						io->taskio.tag_num;
12038					msg_info.task.tag_type =
12039						io->taskio.tag_type;
12040					msg_info.hdr.msg_type =
12041						CTL_MSG_MANAGE_TASKS;
12042					msg_info.hdr.original_sc = NULL;
12043					msg_info.hdr.serializing_sc = NULL;
12044#if 0
12045					printf("Sent Abort to other side\n");
12046#endif
12047					if (CTL_HA_STATUS_SUCCESS !=
12048					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12049		    				(void *)&msg_info,
12050						sizeof(msg_info), 0)) {
12051					}
12052				}
12053#if 0
12054				printf("ctl_abort_task: found I/O to abort\n");
12055#endif
12056				break;
12057			}
12058		}
12059	}
12060	mtx_unlock(&lun->lun_lock);
12061
12062	if (found == 0) {
12063		/*
12064		 * This isn't really an error.  It's entirely possible for
12065		 * the abort and command completion to cross on the wire.
12066		 * This is more of an informative/diagnostic error.
12067		 */
12068#if 0
12069		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12070		       "%d:%d:%d:%d tag %d type %d\n",
12071		       io->io_hdr.nexus.initid.id,
12072		       io->io_hdr.nexus.targ_port,
12073		       io->io_hdr.nexus.targ_target.id,
12074		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12075		       io->taskio.tag_type);
12076#endif
12077	}
12078	return (0);
12079}
12080
12081static void
12082ctl_run_task(union ctl_io *io)
12083{
12084	struct ctl_softc *ctl_softc = control_softc;
12085	int retval = 1;
12086	const char *task_desc;
12087
12088	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12089
12090	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12091	    ("ctl_run_task: Unextected io_type %d\n",
12092	     io->io_hdr.io_type));
12093
12094	task_desc = ctl_scsi_task_string(&io->taskio);
12095	if (task_desc != NULL) {
12096#ifdef NEEDTOPORT
12097		csevent_log(CSC_CTL | CSC_SHELF_SW |
12098			    CTL_TASK_REPORT,
12099			    csevent_LogType_Trace,
12100			    csevent_Severity_Information,
12101			    csevent_AlertLevel_Green,
12102			    csevent_FRU_Firmware,
12103			    csevent_FRU_Unknown,
12104			    "CTL: received task: %s",task_desc);
12105#endif
12106	} else {
12107#ifdef NEEDTOPORT
12108		csevent_log(CSC_CTL | CSC_SHELF_SW |
12109			    CTL_TASK_REPORT,
12110			    csevent_LogType_Trace,
12111			    csevent_Severity_Information,
12112			    csevent_AlertLevel_Green,
12113			    csevent_FRU_Firmware,
12114			    csevent_FRU_Unknown,
12115			    "CTL: received unknown task "
12116			    "type: %d (%#x)",
12117			    io->taskio.task_action,
12118			    io->taskio.task_action);
12119#endif
12120	}
12121	switch (io->taskio.task_action) {
12122	case CTL_TASK_ABORT_TASK:
12123		retval = ctl_abort_task(io);
12124		break;
12125	case CTL_TASK_ABORT_TASK_SET:
12126	case CTL_TASK_CLEAR_TASK_SET:
12127		retval = ctl_abort_task_set(io);
12128		break;
12129	case CTL_TASK_CLEAR_ACA:
12130		break;
12131	case CTL_TASK_I_T_NEXUS_RESET:
12132		retval = ctl_i_t_nexus_reset(io);
12133		break;
12134	case CTL_TASK_LUN_RESET: {
12135		struct ctl_lun *lun;
12136		uint32_t targ_lun;
12137
12138		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12139		mtx_lock(&ctl_softc->ctl_lock);
12140		if ((targ_lun < CTL_MAX_LUNS)
12141		 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12142			lun = ctl_softc->ctl_luns[targ_lun];
12143		else {
12144			mtx_unlock(&ctl_softc->ctl_lock);
12145			retval = 1;
12146			break;
12147		}
12148
12149		if (!(io->io_hdr.flags &
12150		    CTL_FLAG_FROM_OTHER_SC)) {
12151			union ctl_ha_msg msg_info;
12152
12153			io->io_hdr.flags |=
12154				CTL_FLAG_SENT_2OTHER_SC;
12155			msg_info.hdr.msg_type =
12156				CTL_MSG_MANAGE_TASKS;
12157			msg_info.hdr.nexus = io->io_hdr.nexus;
12158			msg_info.task.task_action =
12159				CTL_TASK_LUN_RESET;
12160			msg_info.hdr.original_sc = NULL;
12161			msg_info.hdr.serializing_sc = NULL;
12162			if (CTL_HA_STATUS_SUCCESS !=
12163			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12164			    (void *)&msg_info,
12165			    sizeof(msg_info), 0)) {
12166			}
12167		}
12168
12169		retval = ctl_lun_reset(lun, io,
12170				       CTL_UA_LUN_RESET);
12171		mtx_unlock(&ctl_softc->ctl_lock);
12172		break;
12173	}
12174	case CTL_TASK_TARGET_RESET:
12175		retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12176		break;
12177	case CTL_TASK_BUS_RESET:
12178		retval = ctl_bus_reset(ctl_softc, io);
12179		break;
12180	case CTL_TASK_PORT_LOGIN:
12181		break;
12182	case CTL_TASK_PORT_LOGOUT:
12183		break;
12184	default:
12185		printf("ctl_run_task: got unknown task management event %d\n",
12186		       io->taskio.task_action);
12187		break;
12188	}
12189	if (retval == 0)
12190		io->io_hdr.status = CTL_SUCCESS;
12191	else
12192		io->io_hdr.status = CTL_ERROR;
12193	ctl_done(io);
12194}
12195
12196/*
12197 * For HA operation.  Handle commands that come in from the other
12198 * controller.
12199 */
12200static void
12201ctl_handle_isc(union ctl_io *io)
12202{
12203	int free_io;
12204	struct ctl_lun *lun;
12205	struct ctl_softc *ctl_softc;
12206	uint32_t targ_lun;
12207
12208	ctl_softc = control_softc;
12209
12210	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12211	lun = ctl_softc->ctl_luns[targ_lun];
12212
12213	switch (io->io_hdr.msg_type) {
12214	case CTL_MSG_SERIALIZE:
12215		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12216		break;
12217	case CTL_MSG_R2R: {
12218		const struct ctl_cmd_entry *entry;
12219
12220		/*
12221		 * This is only used in SER_ONLY mode.
12222		 */
12223		free_io = 0;
12224		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12225		mtx_lock(&lun->lun_lock);
12226		if (ctl_scsiio_lun_check(ctl_softc, lun,
12227		    entry, (struct ctl_scsiio *)io) != 0) {
12228			mtx_unlock(&lun->lun_lock);
12229			ctl_done(io);
12230			break;
12231		}
12232		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12233		mtx_unlock(&lun->lun_lock);
12234		ctl_enqueue_rtr(io);
12235		break;
12236	}
12237	case CTL_MSG_FINISH_IO:
12238		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12239			free_io = 0;
12240			ctl_done(io);
12241		} else {
12242			free_io = 1;
12243			mtx_lock(&lun->lun_lock);
12244			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12245				     ooa_links);
12246			ctl_check_blocked(lun);
12247			mtx_unlock(&lun->lun_lock);
12248		}
12249		break;
12250	case CTL_MSG_PERS_ACTION:
12251		ctl_hndl_per_res_out_on_other_sc(
12252			(union ctl_ha_msg *)&io->presio.pr_msg);
12253		free_io = 1;
12254		break;
12255	case CTL_MSG_BAD_JUJU:
12256		free_io = 0;
12257		ctl_done(io);
12258		break;
12259	case CTL_MSG_DATAMOVE:
12260		/* Only used in XFER mode */
12261		free_io = 0;
12262		ctl_datamove_remote(io);
12263		break;
12264	case CTL_MSG_DATAMOVE_DONE:
12265		/* Only used in XFER mode */
12266		free_io = 0;
12267		io->scsiio.be_move_done(io);
12268		break;
12269	default:
12270		free_io = 1;
12271		printf("%s: Invalid message type %d\n",
12272		       __func__, io->io_hdr.msg_type);
12273		break;
12274	}
12275	if (free_io)
12276		ctl_free_io(io);
12277
12278}
12279
12280
12281/*
12282 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12283 * there is no match.
12284 */
12285static ctl_lun_error_pattern
12286ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12287{
12288	const struct ctl_cmd_entry *entry;
12289	ctl_lun_error_pattern filtered_pattern, pattern;
12290
12291	pattern = desc->error_pattern;
12292
12293	/*
12294	 * XXX KDM we need more data passed into this function to match a
12295	 * custom pattern, and we actually need to implement custom pattern
12296	 * matching.
12297	 */
12298	if (pattern & CTL_LUN_PAT_CMD)
12299		return (CTL_LUN_PAT_CMD);
12300
12301	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12302		return (CTL_LUN_PAT_ANY);
12303
12304	entry = ctl_get_cmd_entry(ctsio, NULL);
12305
12306	filtered_pattern = entry->pattern & pattern;
12307
12308	/*
12309	 * If the user requested specific flags in the pattern (e.g.
12310	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12311	 * flags.
12312	 *
12313	 * If the user did not specify any flags, it doesn't matter whether
12314	 * or not the command supports the flags.
12315	 */
12316	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12317	     (pattern & ~CTL_LUN_PAT_MASK))
12318		return (CTL_LUN_PAT_NONE);
12319
12320	/*
12321	 * If the user asked for a range check, see if the requested LBA
12322	 * range overlaps with this command's LBA range.
12323	 */
12324	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12325		uint64_t lba1;
12326		uint64_t len1;
12327		ctl_action action;
12328		int retval;
12329
12330		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12331		if (retval != 0)
12332			return (CTL_LUN_PAT_NONE);
12333
12334		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12335					      desc->lba_range.len);
12336		/*
12337		 * A "pass" means that the LBA ranges don't overlap, so
12338		 * this doesn't match the user's range criteria.
12339		 */
12340		if (action == CTL_ACTION_PASS)
12341			return (CTL_LUN_PAT_NONE);
12342	}
12343
12344	return (filtered_pattern);
12345}
12346
12347static void
12348ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12349{
12350	struct ctl_error_desc *desc, *desc2;
12351
12352	mtx_assert(&lun->lun_lock, MA_OWNED);
12353
12354	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12355		ctl_lun_error_pattern pattern;
12356		/*
12357		 * Check to see whether this particular command matches
12358		 * the pattern in the descriptor.
12359		 */
12360		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12361		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12362			continue;
12363
12364		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12365		case CTL_LUN_INJ_ABORTED:
12366			ctl_set_aborted(&io->scsiio);
12367			break;
12368		case CTL_LUN_INJ_MEDIUM_ERR:
12369			ctl_set_medium_error(&io->scsiio);
12370			break;
12371		case CTL_LUN_INJ_UA:
12372			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12373			 * OCCURRED */
12374			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12375			break;
12376		case CTL_LUN_INJ_CUSTOM:
12377			/*
12378			 * We're assuming the user knows what he is doing.
12379			 * Just copy the sense information without doing
12380			 * checks.
12381			 */
12382			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12383			      ctl_min(sizeof(desc->custom_sense),
12384				      sizeof(io->scsiio.sense_data)));
12385			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12386			io->scsiio.sense_len = SSD_FULL_SIZE;
12387			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12388			break;
12389		case CTL_LUN_INJ_NONE:
12390		default:
12391			/*
12392			 * If this is an error injection type we don't know
12393			 * about, clear the continuous flag (if it is set)
12394			 * so it will get deleted below.
12395			 */
12396			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12397			break;
12398		}
12399		/*
12400		 * By default, each error injection action is a one-shot
12401		 */
12402		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12403			continue;
12404
12405		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12406
12407		free(desc, M_CTL);
12408	}
12409}
12410
12411#ifdef CTL_IO_DELAY
12412static void
12413ctl_datamove_timer_wakeup(void *arg)
12414{
12415	union ctl_io *io;
12416
12417	io = (union ctl_io *)arg;
12418
12419	ctl_datamove(io);
12420}
12421#endif /* CTL_IO_DELAY */
12422
12423void
12424ctl_datamove(union ctl_io *io)
12425{
12426	void (*fe_datamove)(union ctl_io *io);
12427
12428	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12429
12430	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12431
12432#ifdef CTL_TIME_IO
12433	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12434		char str[256];
12435		char path_str[64];
12436		struct sbuf sb;
12437
12438		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12439		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12440
12441		sbuf_cat(&sb, path_str);
12442		switch (io->io_hdr.io_type) {
12443		case CTL_IO_SCSI:
12444			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12445			sbuf_printf(&sb, "\n");
12446			sbuf_cat(&sb, path_str);
12447			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12448				    io->scsiio.tag_num, io->scsiio.tag_type);
12449			break;
12450		case CTL_IO_TASK:
12451			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12452				    "Tag Type: %d\n", io->taskio.task_action,
12453				    io->taskio.tag_num, io->taskio.tag_type);
12454			break;
12455		default:
12456			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12457			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12458			break;
12459		}
12460		sbuf_cat(&sb, path_str);
12461		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12462			    (intmax_t)time_uptime - io->io_hdr.start_time);
12463		sbuf_finish(&sb);
12464		printf("%s", sbuf_data(&sb));
12465	}
12466#endif /* CTL_TIME_IO */
12467
12468#ifdef CTL_IO_DELAY
12469	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12470		struct ctl_lun *lun;
12471
12472		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12473
12474		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12475	} else {
12476		struct ctl_lun *lun;
12477
12478		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12479		if ((lun != NULL)
12480		 && (lun->delay_info.datamove_delay > 0)) {
12481			struct callout *callout;
12482
12483			callout = (struct callout *)&io->io_hdr.timer_bytes;
12484			callout_init(callout, /*mpsafe*/ 1);
12485			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12486			callout_reset(callout,
12487				      lun->delay_info.datamove_delay * hz,
12488				      ctl_datamove_timer_wakeup, io);
12489			if (lun->delay_info.datamove_type ==
12490			    CTL_DELAY_TYPE_ONESHOT)
12491				lun->delay_info.datamove_delay = 0;
12492			return;
12493		}
12494	}
12495#endif
12496
12497	/*
12498	 * This command has been aborted.  Set the port status, so we fail
12499	 * the data move.
12500	 */
12501	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12502		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12503		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12504		       io->io_hdr.nexus.targ_port,
12505		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12506		       io->io_hdr.nexus.targ_lun);
12507		io->io_hdr.port_status = 31337;
12508		/*
12509		 * Note that the backend, in this case, will get the
12510		 * callback in its context.  In other cases it may get
12511		 * called in the frontend's interrupt thread context.
12512		 */
12513		io->scsiio.be_move_done(io);
12514		return;
12515	}
12516
12517	/* Don't confuse frontend with zero length data move. */
12518	if (io->scsiio.kern_data_len == 0) {
12519		io->scsiio.be_move_done(io);
12520		return;
12521	}
12522
12523	/*
12524	 * If we're in XFER mode and this I/O is from the other shelf
12525	 * controller, we need to send the DMA to the other side to
12526	 * actually transfer the data to/from the host.  In serialize only
12527	 * mode the transfer happens below CTL and ctl_datamove() is only
12528	 * called on the machine that originally received the I/O.
12529	 */
12530	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12531	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12532		union ctl_ha_msg msg;
12533		uint32_t sg_entries_sent;
12534		int do_sg_copy;
12535		int i;
12536
12537		memset(&msg, 0, sizeof(msg));
12538		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12539		msg.hdr.original_sc = io->io_hdr.original_sc;
12540		msg.hdr.serializing_sc = io;
12541		msg.hdr.nexus = io->io_hdr.nexus;
12542		msg.dt.flags = io->io_hdr.flags;
12543		/*
12544		 * We convert everything into a S/G list here.  We can't
12545		 * pass by reference, only by value between controllers.
12546		 * So we can't pass a pointer to the S/G list, only as many
12547		 * S/G entries as we can fit in here.  If it's possible for
12548		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12549		 * then we need to break this up into multiple transfers.
12550		 */
12551		if (io->scsiio.kern_sg_entries == 0) {
12552			msg.dt.kern_sg_entries = 1;
12553			/*
12554			 * If this is in cached memory, flush the cache
12555			 * before we send the DMA request to the other
12556			 * controller.  We want to do this in either the
12557			 * read or the write case.  The read case is
12558			 * straightforward.  In the write case, we want to
12559			 * make sure nothing is in the local cache that
12560			 * could overwrite the DMAed data.
12561			 */
12562			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12563				/*
12564				 * XXX KDM use bus_dmamap_sync() here.
12565				 */
12566			}
12567
12568			/*
12569			 * Convert to a physical address if this is a
12570			 * virtual address.
12571			 */
12572			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12573				msg.dt.sg_list[0].addr =
12574					io->scsiio.kern_data_ptr;
12575			} else {
12576				/*
12577				 * XXX KDM use busdma here!
12578				 */
12579#if 0
12580				msg.dt.sg_list[0].addr = (void *)
12581					vtophys(io->scsiio.kern_data_ptr);
12582#endif
12583			}
12584
12585			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12586			do_sg_copy = 0;
12587		} else {
12588			struct ctl_sg_entry *sgl;
12589
12590			do_sg_copy = 1;
12591			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12592			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12593			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12594				/*
12595				 * XXX KDM use bus_dmamap_sync() here.
12596				 */
12597			}
12598		}
12599
12600		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12601		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12602		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12603		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12604		msg.dt.sg_sequence = 0;
12605
12606		/*
12607		 * Loop until we've sent all of the S/G entries.  On the
12608		 * other end, we'll recompose these S/G entries into one
12609		 * contiguous list before passing it to the
12610		 */
12611		for (sg_entries_sent = 0; sg_entries_sent <
12612		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12613			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12614				sizeof(msg.dt.sg_list[0])),
12615				msg.dt.kern_sg_entries - sg_entries_sent);
12616
12617			if (do_sg_copy != 0) {
12618				struct ctl_sg_entry *sgl;
12619				int j;
12620
12621				sgl = (struct ctl_sg_entry *)
12622					io->scsiio.kern_data_ptr;
12623				/*
12624				 * If this is in cached memory, flush the cache
12625				 * before we send the DMA request to the other
12626				 * controller.  We want to do this in either
12627				 * the * read or the write case.  The read
12628				 * case is straightforward.  In the write
12629				 * case, we want to make sure nothing is
12630				 * in the local cache that could overwrite
12631				 * the DMAed data.
12632				 */
12633
12634				for (i = sg_entries_sent, j = 0;
12635				     i < msg.dt.cur_sg_entries; i++, j++) {
12636					if ((io->io_hdr.flags &
12637					     CTL_FLAG_NO_DATASYNC) == 0) {
12638						/*
12639						 * XXX KDM use bus_dmamap_sync()
12640						 */
12641					}
12642					if ((io->io_hdr.flags &
12643					     CTL_FLAG_BUS_ADDR) == 0) {
12644						/*
12645						 * XXX KDM use busdma.
12646						 */
12647#if 0
12648						msg.dt.sg_list[j].addr =(void *)
12649						       vtophys(sgl[i].addr);
12650#endif
12651					} else {
12652						msg.dt.sg_list[j].addr =
12653							sgl[i].addr;
12654					}
12655					msg.dt.sg_list[j].len = sgl[i].len;
12656				}
12657			}
12658
12659			sg_entries_sent += msg.dt.cur_sg_entries;
12660			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12661				msg.dt.sg_last = 1;
12662			else
12663				msg.dt.sg_last = 0;
12664
12665			/*
12666			 * XXX KDM drop and reacquire the lock here?
12667			 */
12668			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12669			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12670				/*
12671				 * XXX do something here.
12672				 */
12673			}
12674
12675			msg.dt.sent_sg_entries = sg_entries_sent;
12676		}
12677		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12678		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12679			ctl_failover_io(io, /*have_lock*/ 0);
12680
12681	} else {
12682
12683		/*
12684		 * Lookup the fe_datamove() function for this particular
12685		 * front end.
12686		 */
12687		fe_datamove =
12688		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12689
12690		fe_datamove(io);
12691	}
12692}
12693
12694static void
12695ctl_send_datamove_done(union ctl_io *io, int have_lock)
12696{
12697	union ctl_ha_msg msg;
12698	int isc_status;
12699
12700	memset(&msg, 0, sizeof(msg));
12701
12702	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12703	msg.hdr.original_sc = io;
12704	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12705	msg.hdr.nexus = io->io_hdr.nexus;
12706	msg.hdr.status = io->io_hdr.status;
12707	msg.scsi.tag_num = io->scsiio.tag_num;
12708	msg.scsi.tag_type = io->scsiio.tag_type;
12709	msg.scsi.scsi_status = io->scsiio.scsi_status;
12710	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12711	       sizeof(io->scsiio.sense_data));
12712	msg.scsi.sense_len = io->scsiio.sense_len;
12713	msg.scsi.sense_residual = io->scsiio.sense_residual;
12714	msg.scsi.fetd_status = io->io_hdr.port_status;
12715	msg.scsi.residual = io->scsiio.residual;
12716	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12717
12718	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12719		ctl_failover_io(io, /*have_lock*/ have_lock);
12720		return;
12721	}
12722
12723	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12724	if (isc_status > CTL_HA_STATUS_SUCCESS) {
12725		/* XXX do something if this fails */
12726	}
12727
12728}
12729
12730/*
12731 * The DMA to the remote side is done, now we need to tell the other side
12732 * we're done so it can continue with its data movement.
12733 */
12734static void
12735ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12736{
12737	union ctl_io *io;
12738
12739	io = rq->context;
12740
12741	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12742		printf("%s: ISC DMA write failed with error %d", __func__,
12743		       rq->ret);
12744		ctl_set_internal_failure(&io->scsiio,
12745					 /*sks_valid*/ 1,
12746					 /*retry_count*/ rq->ret);
12747	}
12748
12749	ctl_dt_req_free(rq);
12750
12751	/*
12752	 * In this case, we had to malloc the memory locally.  Free it.
12753	 */
12754	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12755		int i;
12756		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12757			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12758	}
12759	/*
12760	 * The data is in local and remote memory, so now we need to send
12761	 * status (good or back) back to the other side.
12762	 */
12763	ctl_send_datamove_done(io, /*have_lock*/ 0);
12764}
12765
12766/*
12767 * We've moved the data from the host/controller into local memory.  Now we
12768 * need to push it over to the remote controller's memory.
12769 */
12770static int
12771ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12772{
12773	int retval;
12774
12775	retval = 0;
12776
12777	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12778					  ctl_datamove_remote_write_cb);
12779
12780	return (retval);
12781}
12782
12783static void
12784ctl_datamove_remote_write(union ctl_io *io)
12785{
12786	int retval;
12787	void (*fe_datamove)(union ctl_io *io);
12788
12789	/*
12790	 * - Get the data from the host/HBA into local memory.
12791	 * - DMA memory from the local controller to the remote controller.
12792	 * - Send status back to the remote controller.
12793	 */
12794
12795	retval = ctl_datamove_remote_sgl_setup(io);
12796	if (retval != 0)
12797		return;
12798
12799	/* Switch the pointer over so the FETD knows what to do */
12800	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12801
12802	/*
12803	 * Use a custom move done callback, since we need to send completion
12804	 * back to the other controller, not to the backend on this side.
12805	 */
12806	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12807
12808	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12809
12810	fe_datamove(io);
12811
12812	return;
12813
12814}
12815
12816static int
12817ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12818{
12819#if 0
12820	char str[256];
12821	char path_str[64];
12822	struct sbuf sb;
12823#endif
12824
12825	/*
12826	 * In this case, we had to malloc the memory locally.  Free it.
12827	 */
12828	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12829		int i;
12830		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12831			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12832	}
12833
12834#if 0
12835	scsi_path_string(io, path_str, sizeof(path_str));
12836	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12837	sbuf_cat(&sb, path_str);
12838	scsi_command_string(&io->scsiio, NULL, &sb);
12839	sbuf_printf(&sb, "\n");
12840	sbuf_cat(&sb, path_str);
12841	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12842		    io->scsiio.tag_num, io->scsiio.tag_type);
12843	sbuf_cat(&sb, path_str);
12844	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12845		    io->io_hdr.flags, io->io_hdr.status);
12846	sbuf_finish(&sb);
12847	printk("%s", sbuf_data(&sb));
12848#endif
12849
12850
12851	/*
12852	 * The read is done, now we need to send status (good or bad) back
12853	 * to the other side.
12854	 */
12855	ctl_send_datamove_done(io, /*have_lock*/ 0);
12856
12857	return (0);
12858}
12859
12860static void
12861ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12862{
12863	union ctl_io *io;
12864	void (*fe_datamove)(union ctl_io *io);
12865
12866	io = rq->context;
12867
12868	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12869		printf("%s: ISC DMA read failed with error %d", __func__,
12870		       rq->ret);
12871		ctl_set_internal_failure(&io->scsiio,
12872					 /*sks_valid*/ 1,
12873					 /*retry_count*/ rq->ret);
12874	}
12875
12876	ctl_dt_req_free(rq);
12877
12878	/* Switch the pointer over so the FETD knows what to do */
12879	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12880
12881	/*
12882	 * Use a custom move done callback, since we need to send completion
12883	 * back to the other controller, not to the backend on this side.
12884	 */
12885	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12886
12887	/* XXX KDM add checks like the ones in ctl_datamove? */
12888
12889	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12890
12891	fe_datamove(io);
12892}
12893
12894static int
12895ctl_datamove_remote_sgl_setup(union ctl_io *io)
12896{
12897	struct ctl_sg_entry *local_sglist, *remote_sglist;
12898	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
12899	struct ctl_softc *softc;
12900	int retval;
12901	int i;
12902
12903	retval = 0;
12904	softc = control_softc;
12905
12906	local_sglist = io->io_hdr.local_sglist;
12907	local_dma_sglist = io->io_hdr.local_dma_sglist;
12908	remote_sglist = io->io_hdr.remote_sglist;
12909	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
12910
12911	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
12912		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
12913			local_sglist[i].len = remote_sglist[i].len;
12914
12915			/*
12916			 * XXX Detect the situation where the RS-level I/O
12917			 * redirector on the other side has already read the
12918			 * data off of the AOR RS on this side, and
12919			 * transferred it to remote (mirror) memory on the
12920			 * other side.  Since we already have the data in
12921			 * memory here, we just need to use it.
12922			 *
12923			 * XXX KDM this can probably be removed once we
12924			 * get the cache device code in and take the
12925			 * current AOR implementation out.
12926			 */
12927#ifdef NEEDTOPORT
12928			if ((remote_sglist[i].addr >=
12929			     (void *)vtophys(softc->mirr->addr))
12930			 && (remote_sglist[i].addr <
12931			     ((void *)vtophys(softc->mirr->addr) +
12932			     CacheMirrorOffset))) {
12933				local_sglist[i].addr = remote_sglist[i].addr -
12934					CacheMirrorOffset;
12935				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12936				     CTL_FLAG_DATA_IN)
12937					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
12938			} else {
12939				local_sglist[i].addr = remote_sglist[i].addr +
12940					CacheMirrorOffset;
12941			}
12942#endif
12943#if 0
12944			printf("%s: local %p, remote %p, len %d\n",
12945			       __func__, local_sglist[i].addr,
12946			       remote_sglist[i].addr, local_sglist[i].len);
12947#endif
12948		}
12949	} else {
12950		uint32_t len_to_go;
12951
12952		/*
12953		 * In this case, we don't have automatically allocated
12954		 * memory for this I/O on this controller.  This typically
12955		 * happens with internal CTL I/O -- e.g. inquiry, mode
12956		 * sense, etc.  Anything coming from RAIDCore will have
12957		 * a mirror area available.
12958		 */
12959		len_to_go = io->scsiio.kern_data_len;
12960
12961		/*
12962		 * Clear the no datasync flag, we have to use malloced
12963		 * buffers.
12964		 */
12965		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
12966
12967		/*
12968		 * The difficult thing here is that the size of the various
12969		 * S/G segments may be different than the size from the
12970		 * remote controller.  That'll make it harder when DMAing
12971		 * the data back to the other side.
12972		 */
12973		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
12974		     sizeof(io->io_hdr.remote_sglist[0])) &&
12975		     (len_to_go > 0); i++) {
12976			local_sglist[i].len = ctl_min(len_to_go, 131072);
12977			CTL_SIZE_8B(local_dma_sglist[i].len,
12978				    local_sglist[i].len);
12979			local_sglist[i].addr =
12980				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
12981
12982			local_dma_sglist[i].addr = local_sglist[i].addr;
12983
12984			if (local_sglist[i].addr == NULL) {
12985				int j;
12986
12987				printf("malloc failed for %zd bytes!",
12988				       local_dma_sglist[i].len);
12989				for (j = 0; j < i; j++) {
12990					free(local_sglist[j].addr, M_CTL);
12991				}
12992				ctl_set_internal_failure(&io->scsiio,
12993							 /*sks_valid*/ 1,
12994							 /*retry_count*/ 4857);
12995				retval = 1;
12996				goto bailout_error;
12997
12998			}
12999			/* XXX KDM do we need a sync here? */
13000
13001			len_to_go -= local_sglist[i].len;
13002		}
13003		/*
13004		 * Reset the number of S/G entries accordingly.  The
13005		 * original number of S/G entries is available in
13006		 * rem_sg_entries.
13007		 */
13008		io->scsiio.kern_sg_entries = i;
13009
13010#if 0
13011		printf("%s: kern_sg_entries = %d\n", __func__,
13012		       io->scsiio.kern_sg_entries);
13013		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13014			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13015			       local_sglist[i].addr, local_sglist[i].len,
13016			       local_dma_sglist[i].len);
13017#endif
13018	}
13019
13020
13021	return (retval);
13022
13023bailout_error:
13024
13025	ctl_send_datamove_done(io, /*have_lock*/ 0);
13026
13027	return (retval);
13028}
13029
13030static int
13031ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13032			 ctl_ha_dt_cb callback)
13033{
13034	struct ctl_ha_dt_req *rq;
13035	struct ctl_sg_entry *remote_sglist, *local_sglist;
13036	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13037	uint32_t local_used, remote_used, total_used;
13038	int retval;
13039	int i, j;
13040
13041	retval = 0;
13042
13043	rq = ctl_dt_req_alloc();
13044
13045	/*
13046	 * If we failed to allocate the request, and if the DMA didn't fail
13047	 * anyway, set busy status.  This is just a resource allocation
13048	 * failure.
13049	 */
13050	if ((rq == NULL)
13051	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13052		ctl_set_busy(&io->scsiio);
13053
13054	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13055
13056		if (rq != NULL)
13057			ctl_dt_req_free(rq);
13058
13059		/*
13060		 * The data move failed.  We need to return status back
13061		 * to the other controller.  No point in trying to DMA
13062		 * data to the remote controller.
13063		 */
13064
13065		ctl_send_datamove_done(io, /*have_lock*/ 0);
13066
13067		retval = 1;
13068
13069		goto bailout;
13070	}
13071
13072	local_sglist = io->io_hdr.local_sglist;
13073	local_dma_sglist = io->io_hdr.local_dma_sglist;
13074	remote_sglist = io->io_hdr.remote_sglist;
13075	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13076	local_used = 0;
13077	remote_used = 0;
13078	total_used = 0;
13079
13080	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13081		rq->ret = CTL_HA_STATUS_SUCCESS;
13082		rq->context = io;
13083		callback(rq);
13084		goto bailout;
13085	}
13086
13087	/*
13088	 * Pull/push the data over the wire from/to the other controller.
13089	 * This takes into account the possibility that the local and
13090	 * remote sglists may not be identical in terms of the size of
13091	 * the elements and the number of elements.
13092	 *
13093	 * One fundamental assumption here is that the length allocated for
13094	 * both the local and remote sglists is identical.  Otherwise, we've
13095	 * essentially got a coding error of some sort.
13096	 */
13097	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13098		int isc_ret;
13099		uint32_t cur_len, dma_length;
13100		uint8_t *tmp_ptr;
13101
13102		rq->id = CTL_HA_DATA_CTL;
13103		rq->command = command;
13104		rq->context = io;
13105
13106		/*
13107		 * Both pointers should be aligned.  But it is possible
13108		 * that the allocation length is not.  They should both
13109		 * also have enough slack left over at the end, though,
13110		 * to round up to the next 8 byte boundary.
13111		 */
13112		cur_len = ctl_min(local_sglist[i].len - local_used,
13113				  remote_sglist[j].len - remote_used);
13114
13115		/*
13116		 * In this case, we have a size issue and need to decrease
13117		 * the size, except in the case where we actually have less
13118		 * than 8 bytes left.  In that case, we need to increase
13119		 * the DMA length to get the last bit.
13120		 */
13121		if ((cur_len & 0x7) != 0) {
13122			if (cur_len > 0x7) {
13123				cur_len = cur_len - (cur_len & 0x7);
13124				dma_length = cur_len;
13125			} else {
13126				CTL_SIZE_8B(dma_length, cur_len);
13127			}
13128
13129		} else
13130			dma_length = cur_len;
13131
13132		/*
13133		 * If we had to allocate memory for this I/O, instead of using
13134		 * the non-cached mirror memory, we'll need to flush the cache
13135		 * before trying to DMA to the other controller.
13136		 *
13137		 * We could end up doing this multiple times for the same
13138		 * segment if we have a larger local segment than remote
13139		 * segment.  That shouldn't be an issue.
13140		 */
13141		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13142			/*
13143			 * XXX KDM use bus_dmamap_sync() here.
13144			 */
13145		}
13146
13147		rq->size = dma_length;
13148
13149		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13150		tmp_ptr += local_used;
13151
13152		/* Use physical addresses when talking to ISC hardware */
13153		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13154			/* XXX KDM use busdma */
13155#if 0
13156			rq->local = vtophys(tmp_ptr);
13157#endif
13158		} else
13159			rq->local = tmp_ptr;
13160
13161		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13162		tmp_ptr += remote_used;
13163		rq->remote = tmp_ptr;
13164
13165		rq->callback = NULL;
13166
13167		local_used += cur_len;
13168		if (local_used >= local_sglist[i].len) {
13169			i++;
13170			local_used = 0;
13171		}
13172
13173		remote_used += cur_len;
13174		if (remote_used >= remote_sglist[j].len) {
13175			j++;
13176			remote_used = 0;
13177		}
13178		total_used += cur_len;
13179
13180		if (total_used >= io->scsiio.kern_data_len)
13181			rq->callback = callback;
13182
13183		if ((rq->size & 0x7) != 0) {
13184			printf("%s: warning: size %d is not on 8b boundary\n",
13185			       __func__, rq->size);
13186		}
13187		if (((uintptr_t)rq->local & 0x7) != 0) {
13188			printf("%s: warning: local %p not on 8b boundary\n",
13189			       __func__, rq->local);
13190		}
13191		if (((uintptr_t)rq->remote & 0x7) != 0) {
13192			printf("%s: warning: remote %p not on 8b boundary\n",
13193			       __func__, rq->local);
13194		}
13195#if 0
13196		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13197		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13198		       rq->local, rq->remote, rq->size);
13199#endif
13200
13201		isc_ret = ctl_dt_single(rq);
13202		if (isc_ret == CTL_HA_STATUS_WAIT)
13203			continue;
13204
13205		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13206			rq->ret = CTL_HA_STATUS_SUCCESS;
13207		} else {
13208			rq->ret = isc_ret;
13209		}
13210		callback(rq);
13211		goto bailout;
13212	}
13213
13214bailout:
13215	return (retval);
13216
13217}
13218
13219static void
13220ctl_datamove_remote_read(union ctl_io *io)
13221{
13222	int retval;
13223	int i;
13224
13225	/*
13226	 * This will send an error to the other controller in the case of a
13227	 * failure.
13228	 */
13229	retval = ctl_datamove_remote_sgl_setup(io);
13230	if (retval != 0)
13231		return;
13232
13233	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13234					  ctl_datamove_remote_read_cb);
13235	if ((retval != 0)
13236	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13237		/*
13238		 * Make sure we free memory if there was an error..  The
13239		 * ctl_datamove_remote_xfer() function will send the
13240		 * datamove done message, or call the callback with an
13241		 * error if there is a problem.
13242		 */
13243		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13244			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13245	}
13246
13247	return;
13248}
13249
13250/*
13251 * Process a datamove request from the other controller.  This is used for
13252 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13253 * first.  Once that is complete, the data gets DMAed into the remote
13254 * controller's memory.  For reads, we DMA from the remote controller's
13255 * memory into our memory first, and then move it out to the FETD.
13256 */
13257static void
13258ctl_datamove_remote(union ctl_io *io)
13259{
13260	struct ctl_softc *softc;
13261
13262	softc = control_softc;
13263
13264	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13265
13266	/*
13267	 * Note that we look for an aborted I/O here, but don't do some of
13268	 * the other checks that ctl_datamove() normally does.
13269	 * We don't need to run the datamove delay code, since that should
13270	 * have been done if need be on the other controller.
13271	 */
13272	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13273		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13274		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13275		       io->io_hdr.nexus.targ_port,
13276		       io->io_hdr.nexus.targ_target.id,
13277		       io->io_hdr.nexus.targ_lun);
13278		io->io_hdr.port_status = 31338;
13279		ctl_send_datamove_done(io, /*have_lock*/ 0);
13280		return;
13281	}
13282
13283	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13284		ctl_datamove_remote_write(io);
13285	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13286		ctl_datamove_remote_read(io);
13287	} else {
13288		union ctl_ha_msg msg;
13289		struct scsi_sense_data *sense;
13290		uint8_t sks[3];
13291		int retry_count;
13292
13293		memset(&msg, 0, sizeof(msg));
13294
13295		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13296		msg.hdr.status = CTL_SCSI_ERROR;
13297		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13298
13299		retry_count = 4243;
13300
13301		sense = &msg.scsi.sense_data;
13302		sks[0] = SSD_SCS_VALID;
13303		sks[1] = (retry_count >> 8) & 0xff;
13304		sks[2] = retry_count & 0xff;
13305
13306		/* "Internal target failure" */
13307		scsi_set_sense_data(sense,
13308				    /*sense_format*/ SSD_TYPE_NONE,
13309				    /*current_error*/ 1,
13310				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13311				    /*asc*/ 0x44,
13312				    /*ascq*/ 0x00,
13313				    /*type*/ SSD_ELEM_SKS,
13314				    /*size*/ sizeof(sks),
13315				    /*data*/ sks,
13316				    SSD_ELEM_NONE);
13317
13318		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13319		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13320			ctl_failover_io(io, /*have_lock*/ 1);
13321			return;
13322		}
13323
13324		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13325		    CTL_HA_STATUS_SUCCESS) {
13326			/* XXX KDM what to do if this fails? */
13327		}
13328		return;
13329	}
13330
13331}
13332
13333static int
13334ctl_process_done(union ctl_io *io)
13335{
13336	struct ctl_lun *lun;
13337	struct ctl_softc *ctl_softc = control_softc;
13338	void (*fe_done)(union ctl_io *io);
13339	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13340
13341	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13342
13343	fe_done =
13344	    control_softc->ctl_ports[targ_port]->fe_done;
13345
13346#ifdef CTL_TIME_IO
13347	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13348		char str[256];
13349		char path_str[64];
13350		struct sbuf sb;
13351
13352		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13353		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13354
13355		sbuf_cat(&sb, path_str);
13356		switch (io->io_hdr.io_type) {
13357		case CTL_IO_SCSI:
13358			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13359			sbuf_printf(&sb, "\n");
13360			sbuf_cat(&sb, path_str);
13361			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13362				    io->scsiio.tag_num, io->scsiio.tag_type);
13363			break;
13364		case CTL_IO_TASK:
13365			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13366				    "Tag Type: %d\n", io->taskio.task_action,
13367				    io->taskio.tag_num, io->taskio.tag_type);
13368			break;
13369		default:
13370			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13371			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13372			break;
13373		}
13374		sbuf_cat(&sb, path_str);
13375		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13376			    (intmax_t)time_uptime - io->io_hdr.start_time);
13377		sbuf_finish(&sb);
13378		printf("%s", sbuf_data(&sb));
13379	}
13380#endif /* CTL_TIME_IO */
13381
13382	switch (io->io_hdr.io_type) {
13383	case CTL_IO_SCSI:
13384		break;
13385	case CTL_IO_TASK:
13386		if (bootverbose || (ctl_debug & CTL_DEBUG_INFO))
13387			ctl_io_error_print(io, NULL);
13388		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13389			ctl_free_io(io);
13390		else
13391			fe_done(io);
13392		return (CTL_RETVAL_COMPLETE);
13393	default:
13394		panic("ctl_process_done: invalid io type %d\n",
13395		      io->io_hdr.io_type);
13396		break; /* NOTREACHED */
13397	}
13398
13399	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13400	if (lun == NULL) {
13401		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13402				 io->io_hdr.nexus.targ_mapped_lun));
13403		goto bailout;
13404	}
13405
13406	mtx_lock(&lun->lun_lock);
13407
13408	/*
13409	 * Check to see if we have any errors to inject here.  We only
13410	 * inject errors for commands that don't already have errors set.
13411	 */
13412	if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
13413	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13414	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13415		ctl_inject_error(lun, io);
13416
13417	/*
13418	 * XXX KDM how do we treat commands that aren't completed
13419	 * successfully?
13420	 *
13421	 * XXX KDM should we also track I/O latency?
13422	 */
13423	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13424	    io->io_hdr.io_type == CTL_IO_SCSI) {
13425#ifdef CTL_TIME_IO
13426		struct bintime cur_bt;
13427#endif
13428		int type;
13429
13430		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13431		    CTL_FLAG_DATA_IN)
13432			type = CTL_STATS_READ;
13433		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13434		    CTL_FLAG_DATA_OUT)
13435			type = CTL_STATS_WRITE;
13436		else
13437			type = CTL_STATS_NO_IO;
13438
13439		lun->stats.ports[targ_port].bytes[type] +=
13440		    io->scsiio.kern_total_len;
13441		lun->stats.ports[targ_port].operations[type]++;
13442#ifdef CTL_TIME_IO
13443		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13444		   &io->io_hdr.dma_bt);
13445		lun->stats.ports[targ_port].num_dmas[type] +=
13446		    io->io_hdr.num_dmas;
13447		getbintime(&cur_bt);
13448		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13449		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13450#endif
13451	}
13452
13453	/*
13454	 * Remove this from the OOA queue.
13455	 */
13456	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13457
13458	/*
13459	 * Run through the blocked queue on this LUN and see if anything
13460	 * has become unblocked, now that this transaction is done.
13461	 */
13462	ctl_check_blocked(lun);
13463
13464	/*
13465	 * If the LUN has been invalidated, free it if there is nothing
13466	 * left on its OOA queue.
13467	 */
13468	if ((lun->flags & CTL_LUN_INVALID)
13469	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13470		mtx_unlock(&lun->lun_lock);
13471		mtx_lock(&ctl_softc->ctl_lock);
13472		ctl_free_lun(lun);
13473		mtx_unlock(&ctl_softc->ctl_lock);
13474	} else
13475		mtx_unlock(&lun->lun_lock);
13476
13477bailout:
13478
13479	/*
13480	 * If this command has been aborted, make sure we set the status
13481	 * properly.  The FETD is responsible for freeing the I/O and doing
13482	 * whatever it needs to do to clean up its state.
13483	 */
13484	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13485		ctl_set_task_aborted(&io->scsiio);
13486
13487	/*
13488	 * If enabled, print command error status.
13489	 * We don't print UAs unless debugging was enabled explicitly.
13490	 */
13491	do {
13492		if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)
13493			break;
13494		if (!bootverbose && (ctl_debug & CTL_DEBUG_INFO) == 0)
13495			break;
13496		if ((ctl_debug & CTL_DEBUG_INFO) == 0 &&
13497		    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR) &&
13498		     (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13499			int error_code, sense_key, asc, ascq;
13500
13501			scsi_extract_sense_len(&io->scsiio.sense_data,
13502			    io->scsiio.sense_len, &error_code, &sense_key,
13503			    &asc, &ascq, /*show_errors*/ 0);
13504			if (sense_key == SSD_KEY_UNIT_ATTENTION)
13505				break;
13506		}
13507
13508		ctl_io_error_print(io, NULL);
13509	} while (0);
13510
13511	/*
13512	 * Tell the FETD or the other shelf controller we're done with this
13513	 * command.  Note that only SCSI commands get to this point.  Task
13514	 * management commands are completed above.
13515	 *
13516	 * We only send status to the other controller if we're in XFER
13517	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13518	 * received the I/O (from CTL's perspective), and so the status is
13519	 * generated there.
13520	 *
13521	 * XXX KDM if we hold the lock here, we could cause a deadlock
13522	 * if the frontend comes back in in this context to queue
13523	 * something.
13524	 */
13525	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13526	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13527		union ctl_ha_msg msg;
13528
13529		memset(&msg, 0, sizeof(msg));
13530		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13531		msg.hdr.original_sc = io->io_hdr.original_sc;
13532		msg.hdr.nexus = io->io_hdr.nexus;
13533		msg.hdr.status = io->io_hdr.status;
13534		msg.scsi.scsi_status = io->scsiio.scsi_status;
13535		msg.scsi.tag_num = io->scsiio.tag_num;
13536		msg.scsi.tag_type = io->scsiio.tag_type;
13537		msg.scsi.sense_len = io->scsiio.sense_len;
13538		msg.scsi.sense_residual = io->scsiio.sense_residual;
13539		msg.scsi.residual = io->scsiio.residual;
13540		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13541		       sizeof(io->scsiio.sense_data));
13542		/*
13543		 * We copy this whether or not this is an I/O-related
13544		 * command.  Otherwise, we'd have to go and check to see
13545		 * whether it's a read/write command, and it really isn't
13546		 * worth it.
13547		 */
13548		memcpy(&msg.scsi.lbalen,
13549		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13550		       sizeof(msg.scsi.lbalen));
13551
13552		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13553				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13554			/* XXX do something here */
13555		}
13556
13557		ctl_free_io(io);
13558	} else
13559		fe_done(io);
13560
13561	return (CTL_RETVAL_COMPLETE);
13562}
13563
13564#ifdef CTL_WITH_CA
13565/*
13566 * Front end should call this if it doesn't do autosense.  When the request
13567 * sense comes back in from the initiator, we'll dequeue this and send it.
13568 */
13569int
13570ctl_queue_sense(union ctl_io *io)
13571{
13572	struct ctl_lun *lun;
13573	struct ctl_softc *ctl_softc;
13574	uint32_t initidx, targ_lun;
13575
13576	ctl_softc = control_softc;
13577
13578	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13579
13580	/*
13581	 * LUN lookup will likely move to the ctl_work_thread() once we
13582	 * have our new queueing infrastructure (that doesn't put things on
13583	 * a per-LUN queue initially).  That is so that we can handle
13584	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13585	 * can't deal with that right now.
13586	 */
13587	mtx_lock(&ctl_softc->ctl_lock);
13588
13589	/*
13590	 * If we don't have a LUN for this, just toss the sense
13591	 * information.
13592	 */
13593	targ_lun = io->io_hdr.nexus.targ_lun;
13594	targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13595	if ((targ_lun < CTL_MAX_LUNS)
13596	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
13597		lun = ctl_softc->ctl_luns[targ_lun];
13598	else
13599		goto bailout;
13600
13601	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13602
13603	mtx_lock(&lun->lun_lock);
13604	/*
13605	 * Already have CA set for this LUN...toss the sense information.
13606	 */
13607	if (ctl_is_set(lun->have_ca, initidx)) {
13608		mtx_unlock(&lun->lun_lock);
13609		goto bailout;
13610	}
13611
13612	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13613	       ctl_min(sizeof(lun->pending_sense[initidx]),
13614	       sizeof(io->scsiio.sense_data)));
13615	ctl_set_mask(lun->have_ca, initidx);
13616	mtx_unlock(&lun->lun_lock);
13617
13618bailout:
13619	mtx_unlock(&ctl_softc->ctl_lock);
13620
13621	ctl_free_io(io);
13622
13623	return (CTL_RETVAL_COMPLETE);
13624}
13625#endif
13626
13627/*
13628 * Primary command inlet from frontend ports.  All SCSI and task I/O
13629 * requests must go through this function.
13630 */
13631int
13632ctl_queue(union ctl_io *io)
13633{
13634	struct ctl_softc *ctl_softc;
13635
13636	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13637
13638	ctl_softc = control_softc;
13639
13640#ifdef CTL_TIME_IO
13641	io->io_hdr.start_time = time_uptime;
13642	getbintime(&io->io_hdr.start_bt);
13643#endif /* CTL_TIME_IO */
13644
13645	/* Map FE-specific LUN ID into global one. */
13646	io->io_hdr.nexus.targ_mapped_lun =
13647	    ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13648
13649	switch (io->io_hdr.io_type) {
13650	case CTL_IO_SCSI:
13651	case CTL_IO_TASK:
13652		if (ctl_debug & CTL_DEBUG_CDB)
13653			ctl_io_print(io);
13654		ctl_enqueue_incoming(io);
13655		break;
13656	default:
13657		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13658		return (EINVAL);
13659	}
13660
13661	return (CTL_RETVAL_COMPLETE);
13662}
13663
13664#ifdef CTL_IO_DELAY
13665static void
13666ctl_done_timer_wakeup(void *arg)
13667{
13668	union ctl_io *io;
13669
13670	io = (union ctl_io *)arg;
13671	ctl_done(io);
13672}
13673#endif /* CTL_IO_DELAY */
13674
13675void
13676ctl_done(union ctl_io *io)
13677{
13678	struct ctl_softc *ctl_softc;
13679
13680	ctl_softc = control_softc;
13681
13682	/*
13683	 * Enable this to catch duplicate completion issues.
13684	 */
13685#if 0
13686	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13687		printf("%s: type %d msg %d cdb %x iptl: "
13688		       "%d:%d:%d:%d tag 0x%04x "
13689		       "flag %#x status %x\n",
13690			__func__,
13691			io->io_hdr.io_type,
13692			io->io_hdr.msg_type,
13693			io->scsiio.cdb[0],
13694			io->io_hdr.nexus.initid.id,
13695			io->io_hdr.nexus.targ_port,
13696			io->io_hdr.nexus.targ_target.id,
13697			io->io_hdr.nexus.targ_lun,
13698			(io->io_hdr.io_type ==
13699			CTL_IO_TASK) ?
13700			io->taskio.tag_num :
13701			io->scsiio.tag_num,
13702		        io->io_hdr.flags,
13703			io->io_hdr.status);
13704	} else
13705		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13706#endif
13707
13708	/*
13709	 * This is an internal copy of an I/O, and should not go through
13710	 * the normal done processing logic.
13711	 */
13712	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13713		return;
13714
13715	/*
13716	 * We need to send a msg to the serializing shelf to finish the IO
13717	 * as well.  We don't send a finish message to the other shelf if
13718	 * this is a task management command.  Task management commands
13719	 * aren't serialized in the OOA queue, but rather just executed on
13720	 * both shelf controllers for commands that originated on that
13721	 * controller.
13722	 */
13723	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13724	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
13725		union ctl_ha_msg msg_io;
13726
13727		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13728		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13729		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13730		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13731		}
13732		/* continue on to finish IO */
13733	}
13734#ifdef CTL_IO_DELAY
13735	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13736		struct ctl_lun *lun;
13737
13738		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13739
13740		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13741	} else {
13742		struct ctl_lun *lun;
13743
13744		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13745
13746		if ((lun != NULL)
13747		 && (lun->delay_info.done_delay > 0)) {
13748			struct callout *callout;
13749
13750			callout = (struct callout *)&io->io_hdr.timer_bytes;
13751			callout_init(callout, /*mpsafe*/ 1);
13752			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13753			callout_reset(callout,
13754				      lun->delay_info.done_delay * hz,
13755				      ctl_done_timer_wakeup, io);
13756			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13757				lun->delay_info.done_delay = 0;
13758			return;
13759		}
13760	}
13761#endif /* CTL_IO_DELAY */
13762
13763	ctl_enqueue_done(io);
13764}
13765
13766int
13767ctl_isc(struct ctl_scsiio *ctsio)
13768{
13769	struct ctl_lun *lun;
13770	int retval;
13771
13772	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13773
13774	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13775
13776	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13777
13778	retval = lun->backend->data_submit((union ctl_io *)ctsio);
13779
13780	return (retval);
13781}
13782
13783
13784static void
13785ctl_work_thread(void *arg)
13786{
13787	struct ctl_thread *thr = (struct ctl_thread *)arg;
13788	struct ctl_softc *softc = thr->ctl_softc;
13789	union ctl_io *io;
13790	int retval;
13791
13792	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13793
13794	for (;;) {
13795		retval = 0;
13796
13797		/*
13798		 * We handle the queues in this order:
13799		 * - ISC
13800		 * - done queue (to free up resources, unblock other commands)
13801		 * - RtR queue
13802		 * - incoming queue
13803		 *
13804		 * If those queues are empty, we break out of the loop and
13805		 * go to sleep.
13806		 */
13807		mtx_lock(&thr->queue_lock);
13808		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13809		if (io != NULL) {
13810			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13811			mtx_unlock(&thr->queue_lock);
13812			ctl_handle_isc(io);
13813			continue;
13814		}
13815		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13816		if (io != NULL) {
13817			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13818			/* clear any blocked commands, call fe_done */
13819			mtx_unlock(&thr->queue_lock);
13820			retval = ctl_process_done(io);
13821			continue;
13822		}
13823		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13824		if (io != NULL) {
13825			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13826			mtx_unlock(&thr->queue_lock);
13827			if (io->io_hdr.io_type == CTL_IO_TASK)
13828				ctl_run_task(io);
13829			else
13830				ctl_scsiio_precheck(softc, &io->scsiio);
13831			continue;
13832		}
13833		if (!ctl_pause_rtr) {
13834			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13835			if (io != NULL) {
13836				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13837				mtx_unlock(&thr->queue_lock);
13838				retval = ctl_scsiio(&io->scsiio);
13839				if (retval != CTL_RETVAL_COMPLETE)
13840					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13841				continue;
13842			}
13843		}
13844
13845		/* Sleep until we have something to do. */
13846		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13847	}
13848}
13849
13850static void
13851ctl_lun_thread(void *arg)
13852{
13853	struct ctl_softc *softc = (struct ctl_softc *)arg;
13854	struct ctl_be_lun *be_lun;
13855	int retval;
13856
13857	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13858
13859	for (;;) {
13860		retval = 0;
13861		mtx_lock(&softc->ctl_lock);
13862		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13863		if (be_lun != NULL) {
13864			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13865			mtx_unlock(&softc->ctl_lock);
13866			ctl_create_lun(be_lun);
13867			continue;
13868		}
13869
13870		/* Sleep until we have something to do. */
13871		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13872		    PDROP | PRIBIO, "-", 0);
13873	}
13874}
13875
13876static void
13877ctl_thresh_thread(void *arg)
13878{
13879	struct ctl_softc *softc = (struct ctl_softc *)arg;
13880	struct ctl_lun *lun;
13881	struct ctl_be_lun *be_lun;
13882	struct scsi_da_rw_recovery_page *rwpage;
13883	struct ctl_logical_block_provisioning_page *page;
13884	const char *attr;
13885	uint64_t thres, val;
13886	int i, e;
13887
13888	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13889
13890	for (;;) {
13891		mtx_lock(&softc->ctl_lock);
13892		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13893			be_lun = lun->be_lun;
13894			if ((lun->flags & CTL_LUN_DISABLED) ||
13895			    (lun->flags & CTL_LUN_OFFLINE) ||
13896			    (be_lun->flags & CTL_LUN_FLAG_UNMAP) == 0 ||
13897			    lun->backend->lun_attr == NULL)
13898				continue;
13899			rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13900			if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13901				continue;
13902			e = 0;
13903			page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13904			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13905				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13906					continue;
13907				thres = scsi_4btoul(page->descr[i].count);
13908				thres <<= CTL_LBP_EXPONENT;
13909				switch (page->descr[i].resource) {
13910				case 0x01:
13911					attr = "blocksavail";
13912					break;
13913				case 0x02:
13914					attr = "blocksused";
13915					break;
13916				case 0xf1:
13917					attr = "poolblocksavail";
13918					break;
13919				case 0xf2:
13920					attr = "poolblocksused";
13921					break;
13922				default:
13923					continue;
13924				}
13925				mtx_unlock(&softc->ctl_lock); // XXX
13926				val = lun->backend->lun_attr(
13927				    lun->be_lun->be_lun, attr);
13928				mtx_lock(&softc->ctl_lock);
13929				if (val == UINT64_MAX)
13930					continue;
13931				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13932				    == SLBPPD_ARMING_INC)
13933					e |= (val >= thres);
13934				else
13935					e |= (val <= thres);
13936			}
13937			mtx_lock(&lun->lun_lock);
13938			if (e) {
13939				if (lun->lasttpt == 0 ||
13940				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13941					lun->lasttpt = time_uptime;
13942					for (i = 0; i < CTL_MAX_INITIATORS; i++)
13943						lun->pending_ua[i] |=
13944						    CTL_UA_THIN_PROV_THRES;
13945				}
13946			} else {
13947				lun->lasttpt = 0;
13948				for (i = 0; i < CTL_MAX_INITIATORS; i++)
13949					lun->pending_ua[i] &= ~CTL_UA_THIN_PROV_THRES;
13950			}
13951			mtx_unlock(&lun->lun_lock);
13952		}
13953		mtx_unlock(&softc->ctl_lock);
13954		pause("-", CTL_LBP_PERIOD * hz);
13955	}
13956}
13957
13958static void
13959ctl_enqueue_incoming(union ctl_io *io)
13960{
13961	struct ctl_softc *softc = control_softc;
13962	struct ctl_thread *thr;
13963	u_int idx;
13964
13965	idx = (io->io_hdr.nexus.targ_port * 127 +
13966	       io->io_hdr.nexus.initid.id) % worker_threads;
13967	thr = &softc->threads[idx];
13968	mtx_lock(&thr->queue_lock);
13969	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13970	mtx_unlock(&thr->queue_lock);
13971	wakeup(thr);
13972}
13973
13974static void
13975ctl_enqueue_rtr(union ctl_io *io)
13976{
13977	struct ctl_softc *softc = control_softc;
13978	struct ctl_thread *thr;
13979
13980	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13981	mtx_lock(&thr->queue_lock);
13982	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13983	mtx_unlock(&thr->queue_lock);
13984	wakeup(thr);
13985}
13986
13987static void
13988ctl_enqueue_done(union ctl_io *io)
13989{
13990	struct ctl_softc *softc = control_softc;
13991	struct ctl_thread *thr;
13992
13993	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13994	mtx_lock(&thr->queue_lock);
13995	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13996	mtx_unlock(&thr->queue_lock);
13997	wakeup(thr);
13998}
13999
14000static void
14001ctl_enqueue_isc(union ctl_io *io)
14002{
14003	struct ctl_softc *softc = control_softc;
14004	struct ctl_thread *thr;
14005
14006	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14007	mtx_lock(&thr->queue_lock);
14008	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14009	mtx_unlock(&thr->queue_lock);
14010	wakeup(thr);
14011}
14012
14013/* Initialization and failover */
14014
14015void
14016ctl_init_isc_msg(void)
14017{
14018	printf("CTL: Still calling this thing\n");
14019}
14020
14021/*
14022 * Init component
14023 * 	Initializes component into configuration defined by bootMode
14024 *	(see hasc-sv.c)
14025 *  	returns hasc_Status:
14026 * 		OK
14027 *		ERROR - fatal error
14028 */
14029static ctl_ha_comp_status
14030ctl_isc_init(struct ctl_ha_component *c)
14031{
14032	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14033
14034	c->status = ret;
14035	return ret;
14036}
14037
14038/* Start component
14039 * 	Starts component in state requested. If component starts successfully,
14040 *	it must set its own state to the requestrd state
14041 *	When requested state is HASC_STATE_HA, the component may refine it
14042 * 	by adding _SLAVE or _MASTER flags.
14043 *	Currently allowed state transitions are:
14044 *	UNKNOWN->HA		- initial startup
14045 *	UNKNOWN->SINGLE - initial startup when no parter detected
14046 *	HA->SINGLE		- failover
14047 * returns ctl_ha_comp_status:
14048 * 		OK	- component successfully started in requested state
14049 *		FAILED  - could not start the requested state, failover may
14050 * 			  be possible
14051 *		ERROR	- fatal error detected, no future startup possible
14052 */
14053static ctl_ha_comp_status
14054ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14055{
14056	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14057
14058	printf("%s: go\n", __func__);
14059
14060	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14061	if (c->state == CTL_HA_STATE_UNKNOWN ) {
14062		control_softc->is_single = 0;
14063		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14064		    != CTL_HA_STATUS_SUCCESS) {
14065			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14066			ret = CTL_HA_COMP_STATUS_ERROR;
14067		}
14068	} else if (CTL_HA_STATE_IS_HA(c->state)
14069		&& CTL_HA_STATE_IS_SINGLE(state)){
14070		// HA->SINGLE transition
14071	        ctl_failover();
14072		control_softc->is_single = 1;
14073	} else {
14074		printf("ctl_isc_start:Invalid state transition %X->%X\n",
14075		       c->state, state);
14076		ret = CTL_HA_COMP_STATUS_ERROR;
14077	}
14078	if (CTL_HA_STATE_IS_SINGLE(state))
14079		control_softc->is_single = 1;
14080
14081	c->state = state;
14082	c->status = ret;
14083	return ret;
14084}
14085
14086/*
14087 * Quiesce component
14088 * The component must clear any error conditions (set status to OK) and
14089 * prepare itself to another Start call
14090 * returns ctl_ha_comp_status:
14091 * 	OK
14092 *	ERROR
14093 */
14094static ctl_ha_comp_status
14095ctl_isc_quiesce(struct ctl_ha_component *c)
14096{
14097	int ret = CTL_HA_COMP_STATUS_OK;
14098
14099	ctl_pause_rtr = 1;
14100	c->status = ret;
14101	return ret;
14102}
14103
14104struct ctl_ha_component ctl_ha_component_ctlisc =
14105{
14106	.name = "CTL ISC",
14107	.state = CTL_HA_STATE_UNKNOWN,
14108	.init = ctl_isc_init,
14109	.start = ctl_isc_start,
14110	.quiesce = ctl_isc_quiesce
14111};
14112
14113/*
14114 *  vim: ts=8
14115 */
14116