ctl.c revision 275009
1/*-
2 * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3 * Copyright (c) 2012 The FreeBSD Foundation
4 * All rights reserved.
5 *
6 * Portions of this software were developed by Edward Tomasz Napierala
7 * under sponsorship from the FreeBSD Foundation.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions, and the following disclaimer,
14 *    without modification.
15 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
16 *    substantially similar to the "NO WARRANTY" disclaimer below
17 *    ("Disclaimer") and any redistribution must be conditioned upon
18 *    including a substantially similar Disclaimer requirement for further
19 *    binary redistribution.
20 *
21 * NO WARRANTY
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
25 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
31 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGES.
33 *
34 * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/ctl.c#8 $
35 */
36/*
37 * CAM Target Layer, a SCSI device emulation subsystem.
38 *
39 * Author: Ken Merry <ken@FreeBSD.org>
40 */
41
42#define _CTL_C
43
44#include <sys/cdefs.h>
45__FBSDID("$FreeBSD: head/sys/cam/ctl/ctl.c 275009 2014-11-25 06:11:05Z 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;
364SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
365    &worker_threads, 1, "Number of worker threads");
366static int ctl_debug = CTL_DEBUG_NONE;
367SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
368    &ctl_debug, 0, "Enabled debug flags");
369
370/*
371 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
372 * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
373 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
374 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
375 */
376#define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
377
378static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
379				  int param);
380static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
381static int ctl_init(void);
382void ctl_shutdown(void);
383static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
384static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
385static void ctl_ioctl_online(void *arg);
386static void ctl_ioctl_offline(void *arg);
387static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
388static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
389static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
390static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
391static int ctl_ioctl_submit_wait(union ctl_io *io);
392static void ctl_ioctl_datamove(union ctl_io *io);
393static void ctl_ioctl_done(union ctl_io *io);
394static void ctl_ioctl_hard_startstop_callback(void *arg,
395					      struct cfi_metatask *metatask);
396static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
397static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
398			      struct ctl_ooa *ooa_hdr,
399			      struct ctl_ooa_entry *kern_entries);
400static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
401		     struct thread *td);
402static uint32_t ctl_map_lun(int port_num, uint32_t lun);
403static uint32_t ctl_map_lun_back(int port_num, uint32_t lun);
404#ifdef unused
405static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
406				   uint32_t targ_target, uint32_t targ_lun,
407				   int can_wait);
408static void ctl_kfree_io(union ctl_io *io);
409#endif /* unused */
410static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
411			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
412static int ctl_free_lun(struct ctl_lun *lun);
413static void ctl_create_lun(struct ctl_be_lun *be_lun);
414/**
415static void ctl_failover_change_pages(struct ctl_softc *softc,
416				      struct ctl_scsiio *ctsio, int master);
417**/
418
419static int ctl_do_mode_select(union ctl_io *io);
420static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
421			   uint64_t res_key, uint64_t sa_res_key,
422			   uint8_t type, uint32_t residx,
423			   struct ctl_scsiio *ctsio,
424			   struct scsi_per_res_out *cdb,
425			   struct scsi_per_res_out_parms* param);
426static void ctl_pro_preempt_other(struct ctl_lun *lun,
427				  union ctl_ha_msg *msg);
428static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
429static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
430static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
431static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
432static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
433static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
434static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
435					 int alloc_len);
436static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
437					 int alloc_len);
438static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
439static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
440static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
441static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
442static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
443static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
444static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
445    union ctl_io *pending_io, union ctl_io *ooa_io);
446static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
447				union ctl_io *starting_io);
448static int ctl_check_blocked(struct ctl_lun *lun);
449static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
450				struct ctl_lun *lun,
451				const struct ctl_cmd_entry *entry,
452				struct ctl_scsiio *ctsio);
453//static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
454static void ctl_failover(void);
455static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
456			       struct ctl_scsiio *ctsio);
457static int ctl_scsiio(struct ctl_scsiio *ctsio);
458
459static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
460static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
461			    ctl_ua_type ua_type);
462static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
463			 ctl_ua_type ua_type);
464static int ctl_abort_task(union ctl_io *io);
465static int ctl_abort_task_set(union ctl_io *io);
466static int ctl_i_t_nexus_reset(union ctl_io *io);
467static void ctl_run_task(union ctl_io *io);
468#ifdef CTL_IO_DELAY
469static void ctl_datamove_timer_wakeup(void *arg);
470static void ctl_done_timer_wakeup(void *arg);
471#endif /* CTL_IO_DELAY */
472
473static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
474static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
475static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
476static void ctl_datamove_remote_write(union ctl_io *io);
477static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
478static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
479static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
480static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
481				    ctl_ha_dt_cb callback);
482static void ctl_datamove_remote_read(union ctl_io *io);
483static void ctl_datamove_remote(union ctl_io *io);
484static int ctl_process_done(union ctl_io *io);
485static void ctl_lun_thread(void *arg);
486static void ctl_thresh_thread(void *arg);
487static void ctl_work_thread(void *arg);
488static void ctl_enqueue_incoming(union ctl_io *io);
489static void ctl_enqueue_rtr(union ctl_io *io);
490static void ctl_enqueue_done(union ctl_io *io);
491static void ctl_enqueue_isc(union ctl_io *io);
492static const struct ctl_cmd_entry *
493    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
494static const struct ctl_cmd_entry *
495    ctl_validate_command(struct ctl_scsiio *ctsio);
496static int ctl_cmd_applicable(uint8_t lun_type,
497    const struct ctl_cmd_entry *entry);
498
499/*
500 * Load the serialization table.  This isn't very pretty, but is probably
501 * the easiest way to do it.
502 */
503#include "ctl_ser_table.c"
504
505/*
506 * We only need to define open, close and ioctl routines for this driver.
507 */
508static struct cdevsw ctl_cdevsw = {
509	.d_version =	D_VERSION,
510	.d_flags =	0,
511	.d_open =	ctl_open,
512	.d_close =	ctl_close,
513	.d_ioctl =	ctl_ioctl,
514	.d_name =	"ctl",
515};
516
517
518MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
519MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
520
521static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
522
523static moduledata_t ctl_moduledata = {
524	"ctl",
525	ctl_module_event_handler,
526	NULL
527};
528
529DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
530MODULE_VERSION(ctl, 1);
531
532static struct ctl_frontend ioctl_frontend =
533{
534	.name = "ioctl",
535};
536
537static void
538ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
539			    union ctl_ha_msg *msg_info)
540{
541	struct ctl_scsiio *ctsio;
542
543	if (msg_info->hdr.original_sc == NULL) {
544		printf("%s: original_sc == NULL!\n", __func__);
545		/* XXX KDM now what? */
546		return;
547	}
548
549	ctsio = &msg_info->hdr.original_sc->scsiio;
550	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
551	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
552	ctsio->io_hdr.status = msg_info->hdr.status;
553	ctsio->scsi_status = msg_info->scsi.scsi_status;
554	ctsio->sense_len = msg_info->scsi.sense_len;
555	ctsio->sense_residual = msg_info->scsi.sense_residual;
556	ctsio->residual = msg_info->scsi.residual;
557	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
558	       sizeof(ctsio->sense_data));
559	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
560	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
561	ctl_enqueue_isc((union ctl_io *)ctsio);
562}
563
564static void
565ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
566				union ctl_ha_msg *msg_info)
567{
568	struct ctl_scsiio *ctsio;
569
570	if (msg_info->hdr.serializing_sc == NULL) {
571		printf("%s: serializing_sc == NULL!\n", __func__);
572		/* XXX KDM now what? */
573		return;
574	}
575
576	ctsio = &msg_info->hdr.serializing_sc->scsiio;
577#if 0
578	/*
579	 * Attempt to catch the situation where an I/O has
580	 * been freed, and we're using it again.
581	 */
582	if (ctsio->io_hdr.io_type == 0xff) {
583		union ctl_io *tmp_io;
584		tmp_io = (union ctl_io *)ctsio;
585		printf("%s: %p use after free!\n", __func__,
586		       ctsio);
587		printf("%s: type %d msg %d cdb %x iptl: "
588		       "%d:%d:%d:%d tag 0x%04x "
589		       "flag %#x status %x\n",
590			__func__,
591			tmp_io->io_hdr.io_type,
592			tmp_io->io_hdr.msg_type,
593			tmp_io->scsiio.cdb[0],
594			tmp_io->io_hdr.nexus.initid.id,
595			tmp_io->io_hdr.nexus.targ_port,
596			tmp_io->io_hdr.nexus.targ_target.id,
597			tmp_io->io_hdr.nexus.targ_lun,
598			(tmp_io->io_hdr.io_type ==
599			CTL_IO_TASK) ?
600			tmp_io->taskio.tag_num :
601			tmp_io->scsiio.tag_num,
602		        tmp_io->io_hdr.flags,
603			tmp_io->io_hdr.status);
604	}
605#endif
606	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
607	ctl_enqueue_isc((union ctl_io *)ctsio);
608}
609
610/*
611 * ISC (Inter Shelf Communication) event handler.  Events from the HA
612 * subsystem come in here.
613 */
614static void
615ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
616{
617	struct ctl_softc *ctl_softc;
618	union ctl_io *io;
619	struct ctl_prio *presio;
620	ctl_ha_status isc_status;
621
622	ctl_softc = control_softc;
623	io = NULL;
624
625
626#if 0
627	printf("CTL: Isc Msg event %d\n", event);
628#endif
629	if (event == CTL_HA_EVT_MSG_RECV) {
630		union ctl_ha_msg msg_info;
631
632		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
633					     sizeof(msg_info), /*wait*/ 0);
634#if 0
635		printf("CTL: msg_type %d\n", msg_info.msg_type);
636#endif
637		if (isc_status != 0) {
638			printf("Error receiving message, status = %d\n",
639			       isc_status);
640			return;
641		}
642
643		switch (msg_info.hdr.msg_type) {
644		case CTL_MSG_SERIALIZE:
645#if 0
646			printf("Serialize\n");
647#endif
648			io = ctl_alloc_io_nowait(ctl_softc->othersc_pool);
649			if (io == NULL) {
650				printf("ctl_isc_event_handler: can't allocate "
651				       "ctl_io!\n");
652				/* Bad Juju */
653				/* Need to set busy and send msg back */
654				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
655				msg_info.hdr.status = CTL_SCSI_ERROR;
656				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
657				msg_info.scsi.sense_len = 0;
658			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
659				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
660				}
661				goto bailout;
662			}
663			ctl_zero_io(io);
664			// populate ctsio from msg_info
665			io->io_hdr.io_type = CTL_IO_SCSI;
666			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
667			io->io_hdr.original_sc = msg_info.hdr.original_sc;
668#if 0
669			printf("pOrig %x\n", (int)msg_info.original_sc);
670#endif
671			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
672					    CTL_FLAG_IO_ACTIVE;
673			/*
674			 * If we're in serialization-only mode, we don't
675			 * want to go through full done processing.  Thus
676			 * the COPY flag.
677			 *
678			 * XXX KDM add another flag that is more specific.
679			 */
680			if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
681				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
682			io->io_hdr.nexus = msg_info.hdr.nexus;
683#if 0
684			printf("targ %d, port %d, iid %d, lun %d\n",
685			       io->io_hdr.nexus.targ_target.id,
686			       io->io_hdr.nexus.targ_port,
687			       io->io_hdr.nexus.initid.id,
688			       io->io_hdr.nexus.targ_lun);
689#endif
690			io->scsiio.tag_num = msg_info.scsi.tag_num;
691			io->scsiio.tag_type = msg_info.scsi.tag_type;
692			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
693			       CTL_MAX_CDBLEN);
694			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
695				const struct ctl_cmd_entry *entry;
696
697				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
698				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
699				io->io_hdr.flags |=
700					entry->flags & CTL_FLAG_DATA_MASK;
701			}
702			ctl_enqueue_isc(io);
703			break;
704
705		/* Performed on the Originating SC, XFER mode only */
706		case CTL_MSG_DATAMOVE: {
707			struct ctl_sg_entry *sgl;
708			int i, j;
709
710			io = msg_info.hdr.original_sc;
711			if (io == NULL) {
712				printf("%s: original_sc == NULL!\n", __func__);
713				/* XXX KDM do something here */
714				break;
715			}
716			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
717			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
718			/*
719			 * Keep track of this, we need to send it back over
720			 * when the datamove is complete.
721			 */
722			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
723
724			if (msg_info.dt.sg_sequence == 0) {
725				/*
726				 * XXX KDM we use the preallocated S/G list
727				 * here, but we'll need to change this to
728				 * dynamic allocation if we need larger S/G
729				 * lists.
730				 */
731				if (msg_info.dt.kern_sg_entries >
732				    sizeof(io->io_hdr.remote_sglist) /
733				    sizeof(io->io_hdr.remote_sglist[0])) {
734					printf("%s: number of S/G entries "
735					    "needed %u > allocated num %zd\n",
736					    __func__,
737					    msg_info.dt.kern_sg_entries,
738					    sizeof(io->io_hdr.remote_sglist)/
739					    sizeof(io->io_hdr.remote_sglist[0]));
740
741					/*
742					 * XXX KDM send a message back to
743					 * the other side to shut down the
744					 * DMA.  The error will come back
745					 * through via the normal channel.
746					 */
747					break;
748				}
749				sgl = io->io_hdr.remote_sglist;
750				memset(sgl, 0,
751				       sizeof(io->io_hdr.remote_sglist));
752
753				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
754
755				io->scsiio.kern_sg_entries =
756					msg_info.dt.kern_sg_entries;
757				io->scsiio.rem_sg_entries =
758					msg_info.dt.kern_sg_entries;
759				io->scsiio.kern_data_len =
760					msg_info.dt.kern_data_len;
761				io->scsiio.kern_total_len =
762					msg_info.dt.kern_total_len;
763				io->scsiio.kern_data_resid =
764					msg_info.dt.kern_data_resid;
765				io->scsiio.kern_rel_offset =
766					msg_info.dt.kern_rel_offset;
767				/*
768				 * Clear out per-DMA flags.
769				 */
770				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
771				/*
772				 * Add per-DMA flags that are set for this
773				 * particular DMA request.
774				 */
775				io->io_hdr.flags |= msg_info.dt.flags &
776						    CTL_FLAG_RDMA_MASK;
777			} else
778				sgl = (struct ctl_sg_entry *)
779					io->scsiio.kern_data_ptr;
780
781			for (i = msg_info.dt.sent_sg_entries, j = 0;
782			     i < (msg_info.dt.sent_sg_entries +
783			     msg_info.dt.cur_sg_entries); i++, j++) {
784				sgl[i].addr = msg_info.dt.sg_list[j].addr;
785				sgl[i].len = msg_info.dt.sg_list[j].len;
786
787#if 0
788				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
789				       __func__,
790				       msg_info.dt.sg_list[j].addr,
791				       msg_info.dt.sg_list[j].len,
792				       sgl[i].addr, sgl[i].len, j, i);
793#endif
794			}
795#if 0
796			memcpy(&sgl[msg_info.dt.sent_sg_entries],
797			       msg_info.dt.sg_list,
798			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
799#endif
800
801			/*
802			 * If this is the last piece of the I/O, we've got
803			 * the full S/G list.  Queue processing in the thread.
804			 * Otherwise wait for the next piece.
805			 */
806			if (msg_info.dt.sg_last != 0)
807				ctl_enqueue_isc(io);
808			break;
809		}
810		/* Performed on the Serializing (primary) SC, XFER mode only */
811		case CTL_MSG_DATAMOVE_DONE: {
812			if (msg_info.hdr.serializing_sc == NULL) {
813				printf("%s: serializing_sc == NULL!\n",
814				       __func__);
815				/* XXX KDM now what? */
816				break;
817			}
818			/*
819			 * We grab the sense information here in case
820			 * there was a failure, so we can return status
821			 * back to the initiator.
822			 */
823			io = msg_info.hdr.serializing_sc;
824			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
825			io->io_hdr.status = msg_info.hdr.status;
826			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
827			io->scsiio.sense_len = msg_info.scsi.sense_len;
828			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
829			io->io_hdr.port_status = msg_info.scsi.fetd_status;
830			io->scsiio.residual = msg_info.scsi.residual;
831			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
832			       sizeof(io->scsiio.sense_data));
833			ctl_enqueue_isc(io);
834			break;
835		}
836
837		/* Preformed on Originating SC, SER_ONLY mode */
838		case CTL_MSG_R2R:
839			io = msg_info.hdr.original_sc;
840			if (io == NULL) {
841				printf("%s: Major Bummer\n", __func__);
842				return;
843			} else {
844#if 0
845				printf("pOrig %x\n",(int) ctsio);
846#endif
847			}
848			io->io_hdr.msg_type = CTL_MSG_R2R;
849			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
850			ctl_enqueue_isc(io);
851			break;
852
853		/*
854		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
855		 * mode.
856		 * Performed on the Originating (i.e. secondary) SC in XFER
857		 * mode
858		 */
859		case CTL_MSG_FINISH_IO:
860			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
861				ctl_isc_handler_finish_xfer(ctl_softc,
862							    &msg_info);
863			else
864				ctl_isc_handler_finish_ser_only(ctl_softc,
865								&msg_info);
866			break;
867
868		/* Preformed on Originating SC */
869		case CTL_MSG_BAD_JUJU:
870			io = msg_info.hdr.original_sc;
871			if (io == NULL) {
872				printf("%s: Bad JUJU!, original_sc is NULL!\n",
873				       __func__);
874				break;
875			}
876			ctl_copy_sense_data(&msg_info, io);
877			/*
878			 * IO should have already been cleaned up on other
879			 * SC so clear this flag so we won't send a message
880			 * back to finish the IO there.
881			 */
882			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
883			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
884
885			/* io = msg_info.hdr.serializing_sc; */
886			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
887			ctl_enqueue_isc(io);
888			break;
889
890		/* Handle resets sent from the other side */
891		case CTL_MSG_MANAGE_TASKS: {
892			struct ctl_taskio *taskio;
893			taskio = (struct ctl_taskio *)ctl_alloc_io_nowait(
894			    ctl_softc->othersc_pool);
895			if (taskio == NULL) {
896				printf("ctl_isc_event_handler: can't allocate "
897				       "ctl_io!\n");
898				/* Bad Juju */
899				/* should I just call the proper reset func
900				   here??? */
901				goto bailout;
902			}
903			ctl_zero_io((union ctl_io *)taskio);
904			taskio->io_hdr.io_type = CTL_IO_TASK;
905			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
906			taskio->io_hdr.nexus = msg_info.hdr.nexus;
907			taskio->task_action = msg_info.task.task_action;
908			taskio->tag_num = msg_info.task.tag_num;
909			taskio->tag_type = msg_info.task.tag_type;
910#ifdef CTL_TIME_IO
911			taskio->io_hdr.start_time = time_uptime;
912			getbintime(&taskio->io_hdr.start_bt);
913#if 0
914			cs_prof_gettime(&taskio->io_hdr.start_ticks);
915#endif
916#endif /* CTL_TIME_IO */
917			ctl_run_task((union ctl_io *)taskio);
918			break;
919		}
920		/* Persistent Reserve action which needs attention */
921		case CTL_MSG_PERS_ACTION:
922			presio = (struct ctl_prio *)ctl_alloc_io_nowait(
923			    ctl_softc->othersc_pool);
924			if (presio == NULL) {
925				printf("ctl_isc_event_handler: can't allocate "
926				       "ctl_io!\n");
927				/* Bad Juju */
928				/* Need to set busy and send msg back */
929				goto bailout;
930			}
931			ctl_zero_io((union ctl_io *)presio);
932			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
933			presio->pr_msg = msg_info.pr;
934			ctl_enqueue_isc((union ctl_io *)presio);
935			break;
936		case CTL_MSG_SYNC_FE:
937			rcv_sync_msg = 1;
938			break;
939		default:
940		        printf("How did I get here?\n");
941		}
942	} else if (event == CTL_HA_EVT_MSG_SENT) {
943		if (param != CTL_HA_STATUS_SUCCESS) {
944			printf("Bad status from ctl_ha_msg_send status %d\n",
945			       param);
946		}
947		return;
948	} else if (event == CTL_HA_EVT_DISCONNECT) {
949		printf("CTL: Got a disconnect from Isc\n");
950		return;
951	} else {
952		printf("ctl_isc_event_handler: Unknown event %d\n", event);
953		return;
954	}
955
956bailout:
957	return;
958}
959
960static void
961ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
962{
963	struct scsi_sense_data *sense;
964
965	sense = &dest->scsiio.sense_data;
966	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
967	dest->scsiio.scsi_status = src->scsi.scsi_status;
968	dest->scsiio.sense_len = src->scsi.sense_len;
969	dest->io_hdr.status = src->hdr.status;
970}
971
972static int
973ctl_ha_state_sysctl(SYSCTL_HANDLER_ARGS)
974{
975	struct ctl_softc *softc = (struct ctl_softc *)arg1;
976	struct ctl_lun *lun;
977	int error, value, i;
978
979	if (softc->flags & CTL_FLAG_ACTIVE_SHELF)
980		value = 0;
981	else
982		value = 1;
983
984	error = sysctl_handle_int(oidp, &value, 0, req);
985	if ((error != 0) || (req->newptr == NULL))
986		return (error);
987
988	mtx_lock(&softc->ctl_lock);
989	if (value == 0)
990		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
991	else
992		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
993	STAILQ_FOREACH(lun, &softc->lun_list, links) {
994		mtx_lock(&lun->lun_lock);
995		for (i = 0; i < CTL_MAX_INITIATORS; i++)
996			lun->pending_ua[i] |= CTL_UA_ASYM_ACC_CHANGE;
997		mtx_unlock(&lun->lun_lock);
998	}
999	mtx_unlock(&softc->ctl_lock);
1000	return (0);
1001}
1002
1003static int
1004ctl_init(void)
1005{
1006	struct ctl_softc *softc;
1007	void *other_pool;
1008	struct ctl_port *port;
1009	int i, error, retval;
1010	//int isc_retval;
1011
1012	retval = 0;
1013	ctl_pause_rtr = 0;
1014        rcv_sync_msg = 0;
1015
1016	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1017			       M_WAITOK | M_ZERO);
1018	softc = control_softc;
1019
1020	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1021			      "cam/ctl");
1022
1023	softc->dev->si_drv1 = softc;
1024
1025	/*
1026	 * By default, return a "bad LUN" peripheral qualifier for unknown
1027	 * LUNs.  The user can override this default using the tunable or
1028	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
1029	 */
1030	softc->inquiry_pq_no_lun = 1;
1031	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
1032			  &softc->inquiry_pq_no_lun);
1033	sysctl_ctx_init(&softc->sysctl_ctx);
1034	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1035		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1036		CTLFLAG_RD, 0, "CAM Target Layer");
1037
1038	if (softc->sysctl_tree == NULL) {
1039		printf("%s: unable to allocate sysctl tree\n", __func__);
1040		destroy_dev(softc->dev);
1041		free(control_softc, M_DEVBUF);
1042		control_softc = NULL;
1043		return (ENOMEM);
1044	}
1045
1046	SYSCTL_ADD_INT(&softc->sysctl_ctx,
1047		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1048		       "inquiry_pq_no_lun", CTLFLAG_RW,
1049		       &softc->inquiry_pq_no_lun, 0,
1050		       "Report no lun possible for invalid LUNs");
1051
1052	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1053	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1054	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1055	softc->open_count = 0;
1056
1057	/*
1058	 * Default to actually sending a SYNCHRONIZE CACHE command down to
1059	 * the drive.
1060	 */
1061	softc->flags = CTL_FLAG_REAL_SYNC;
1062
1063	/*
1064	 * In Copan's HA scheme, the "master" and "slave" roles are
1065	 * figured out through the slot the controller is in.  Although it
1066	 * is an active/active system, someone has to be in charge.
1067	 */
1068	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1069	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1070	    "HA head ID (0 - no HA)");
1071	if (softc->ha_id == 0) {
1072		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1073		softc->is_single = 1;
1074		softc->port_offset = 0;
1075	} else
1076		softc->port_offset = (softc->ha_id - 1) * CTL_MAX_PORTS;
1077	persis_offset = softc->port_offset * CTL_MAX_INIT_PER_PORT;
1078
1079	/*
1080	 * XXX KDM need to figure out where we want to get our target ID
1081	 * and WWID.  Is it different on each port?
1082	 */
1083	softc->target.id = 0;
1084	softc->target.wwid[0] = 0x12345678;
1085	softc->target.wwid[1] = 0x87654321;
1086	STAILQ_INIT(&softc->lun_list);
1087	STAILQ_INIT(&softc->pending_lun_queue);
1088	STAILQ_INIT(&softc->fe_list);
1089	STAILQ_INIT(&softc->port_list);
1090	STAILQ_INIT(&softc->be_list);
1091	ctl_tpc_init(softc);
1092
1093	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1094	                    &other_pool) != 0)
1095	{
1096		printf("ctl: can't allocate %d entry other SC pool, "
1097		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1098		return (ENOMEM);
1099	}
1100	softc->othersc_pool = other_pool;
1101
1102	if (worker_threads <= 0)
1103		worker_threads = max(1, mp_ncpus / 4);
1104	if (worker_threads > CTL_MAX_THREADS)
1105		worker_threads = CTL_MAX_THREADS;
1106
1107	for (i = 0; i < worker_threads; i++) {
1108		struct ctl_thread *thr = &softc->threads[i];
1109
1110		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1111		thr->ctl_softc = softc;
1112		STAILQ_INIT(&thr->incoming_queue);
1113		STAILQ_INIT(&thr->rtr_queue);
1114		STAILQ_INIT(&thr->done_queue);
1115		STAILQ_INIT(&thr->isc_queue);
1116
1117		error = kproc_kthread_add(ctl_work_thread, thr,
1118		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1119		if (error != 0) {
1120			printf("error creating CTL work thread!\n");
1121			ctl_pool_free(other_pool);
1122			return (error);
1123		}
1124	}
1125	error = kproc_kthread_add(ctl_lun_thread, softc,
1126	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1127	if (error != 0) {
1128		printf("error creating CTL lun thread!\n");
1129		ctl_pool_free(other_pool);
1130		return (error);
1131	}
1132	error = kproc_kthread_add(ctl_thresh_thread, softc,
1133	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1134	if (error != 0) {
1135		printf("error creating CTL threshold thread!\n");
1136		ctl_pool_free(other_pool);
1137		return (error);
1138	}
1139	if (bootverbose)
1140		printf("ctl: CAM Target Layer loaded\n");
1141
1142	/*
1143	 * Initialize the ioctl front end.
1144	 */
1145	ctl_frontend_register(&ioctl_frontend);
1146	port = &softc->ioctl_info.port;
1147	port->frontend = &ioctl_frontend;
1148	sprintf(softc->ioctl_info.port_name, "ioctl");
1149	port->port_type = CTL_PORT_IOCTL;
1150	port->num_requested_ctl_io = 100;
1151	port->port_name = softc->ioctl_info.port_name;
1152	port->port_online = ctl_ioctl_online;
1153	port->port_offline = ctl_ioctl_offline;
1154	port->onoff_arg = &softc->ioctl_info;
1155	port->lun_enable = ctl_ioctl_lun_enable;
1156	port->lun_disable = ctl_ioctl_lun_disable;
1157	port->targ_lun_arg = &softc->ioctl_info;
1158	port->fe_datamove = ctl_ioctl_datamove;
1159	port->fe_done = ctl_ioctl_done;
1160	port->max_targets = 15;
1161	port->max_target_id = 15;
1162
1163	if (ctl_port_register(&softc->ioctl_info.port) != 0) {
1164		printf("ctl: ioctl front end registration failed, will "
1165		       "continue anyway\n");
1166	}
1167
1168	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1169	    OID_AUTO, "ha_state", CTLTYPE_INT | CTLFLAG_RWTUN,
1170	    softc, 0, ctl_ha_state_sysctl, "I", "HA state for this head");
1171
1172#ifdef CTL_IO_DELAY
1173	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1174		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1175		       sizeof(struct callout), CTL_TIMER_BYTES);
1176		return (EINVAL);
1177	}
1178#endif /* CTL_IO_DELAY */
1179
1180	return (0);
1181}
1182
1183void
1184ctl_shutdown(void)
1185{
1186	struct ctl_softc *softc;
1187	struct ctl_lun *lun, *next_lun;
1188
1189	softc = (struct ctl_softc *)control_softc;
1190
1191	if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1192		printf("ctl: ioctl front end deregistration failed\n");
1193
1194	mtx_lock(&softc->ctl_lock);
1195
1196	/*
1197	 * Free up each LUN.
1198	 */
1199	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1200		next_lun = STAILQ_NEXT(lun, links);
1201		ctl_free_lun(lun);
1202	}
1203
1204	mtx_unlock(&softc->ctl_lock);
1205
1206	ctl_frontend_deregister(&ioctl_frontend);
1207
1208#if 0
1209	ctl_shutdown_thread(softc->work_thread);
1210	mtx_destroy(&softc->queue_lock);
1211#endif
1212
1213	ctl_tpc_shutdown(softc);
1214	uma_zdestroy(softc->io_zone);
1215	mtx_destroy(&softc->ctl_lock);
1216
1217	destroy_dev(softc->dev);
1218
1219	sysctl_ctx_free(&softc->sysctl_ctx);
1220
1221	free(control_softc, M_DEVBUF);
1222	control_softc = NULL;
1223
1224	if (bootverbose)
1225		printf("ctl: CAM Target Layer unloaded\n");
1226}
1227
1228static int
1229ctl_module_event_handler(module_t mod, int what, void *arg)
1230{
1231
1232	switch (what) {
1233	case MOD_LOAD:
1234		return (ctl_init());
1235	case MOD_UNLOAD:
1236		return (EBUSY);
1237	default:
1238		return (EOPNOTSUPP);
1239	}
1240}
1241
1242/*
1243 * XXX KDM should we do some access checks here?  Bump a reference count to
1244 * prevent a CTL module from being unloaded while someone has it open?
1245 */
1246static int
1247ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1248{
1249	return (0);
1250}
1251
1252static int
1253ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1254{
1255	return (0);
1256}
1257
1258int
1259ctl_port_enable(ctl_port_type port_type)
1260{
1261	struct ctl_softc *softc = control_softc;
1262	struct ctl_port *port;
1263
1264	if (softc->is_single == 0) {
1265		union ctl_ha_msg msg_info;
1266		int isc_retval;
1267
1268#if 0
1269		printf("%s: HA mode, synchronizing frontend enable\n",
1270		        __func__);
1271#endif
1272		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1273	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1274		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1275			printf("Sync msg send error retval %d\n", isc_retval);
1276		}
1277		if (!rcv_sync_msg) {
1278			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1279			        sizeof(msg_info), 1);
1280		}
1281#if 0
1282        	printf("CTL:Frontend Enable\n");
1283	} else {
1284		printf("%s: single mode, skipping frontend synchronization\n",
1285		        __func__);
1286#endif
1287	}
1288
1289	STAILQ_FOREACH(port, &softc->port_list, links) {
1290		if (port_type & port->port_type)
1291		{
1292#if 0
1293			printf("port %d\n", port->targ_port);
1294#endif
1295			ctl_port_online(port);
1296		}
1297	}
1298
1299	return (0);
1300}
1301
1302int
1303ctl_port_disable(ctl_port_type port_type)
1304{
1305	struct ctl_softc *softc;
1306	struct ctl_port *port;
1307
1308	softc = control_softc;
1309
1310	STAILQ_FOREACH(port, &softc->port_list, links) {
1311		if (port_type & port->port_type)
1312			ctl_port_offline(port);
1313	}
1314
1315	return (0);
1316}
1317
1318/*
1319 * Returns 0 for success, 1 for failure.
1320 * Currently the only failure mode is if there aren't enough entries
1321 * allocated.  So, in case of a failure, look at num_entries_dropped,
1322 * reallocate and try again.
1323 */
1324int
1325ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1326	      int *num_entries_filled, int *num_entries_dropped,
1327	      ctl_port_type port_type, int no_virtual)
1328{
1329	struct ctl_softc *softc;
1330	struct ctl_port *port;
1331	int entries_dropped, entries_filled;
1332	int retval;
1333	int i;
1334
1335	softc = control_softc;
1336
1337	retval = 0;
1338	entries_filled = 0;
1339	entries_dropped = 0;
1340
1341	i = 0;
1342	mtx_lock(&softc->ctl_lock);
1343	STAILQ_FOREACH(port, &softc->port_list, links) {
1344		struct ctl_port_entry *entry;
1345
1346		if ((port->port_type & port_type) == 0)
1347			continue;
1348
1349		if ((no_virtual != 0)
1350		 && (port->virtual_port != 0))
1351			continue;
1352
1353		if (entries_filled >= num_entries_alloced) {
1354			entries_dropped++;
1355			continue;
1356		}
1357		entry = &entries[i];
1358
1359		entry->port_type = port->port_type;
1360		strlcpy(entry->port_name, port->port_name,
1361			sizeof(entry->port_name));
1362		entry->physical_port = port->physical_port;
1363		entry->virtual_port = port->virtual_port;
1364		entry->wwnn = port->wwnn;
1365		entry->wwpn = port->wwpn;
1366
1367		i++;
1368		entries_filled++;
1369	}
1370
1371	mtx_unlock(&softc->ctl_lock);
1372
1373	if (entries_dropped > 0)
1374		retval = 1;
1375
1376	*num_entries_dropped = entries_dropped;
1377	*num_entries_filled = entries_filled;
1378
1379	return (retval);
1380}
1381
1382static void
1383ctl_ioctl_online(void *arg)
1384{
1385	struct ctl_ioctl_info *ioctl_info;
1386
1387	ioctl_info = (struct ctl_ioctl_info *)arg;
1388
1389	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1390}
1391
1392static void
1393ctl_ioctl_offline(void *arg)
1394{
1395	struct ctl_ioctl_info *ioctl_info;
1396
1397	ioctl_info = (struct ctl_ioctl_info *)arg;
1398
1399	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1400}
1401
1402/*
1403 * Remove an initiator by port number and initiator ID.
1404 * Returns 0 for success, -1 for failure.
1405 */
1406int
1407ctl_remove_initiator(struct ctl_port *port, int iid)
1408{
1409	struct ctl_softc *softc = control_softc;
1410
1411	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1412
1413	if (iid > CTL_MAX_INIT_PER_PORT) {
1414		printf("%s: initiator ID %u > maximun %u!\n",
1415		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1416		return (-1);
1417	}
1418
1419	mtx_lock(&softc->ctl_lock);
1420	port->wwpn_iid[iid].in_use--;
1421	port->wwpn_iid[iid].last_use = time_uptime;
1422	mtx_unlock(&softc->ctl_lock);
1423
1424	return (0);
1425}
1426
1427/*
1428 * Add an initiator to the initiator map.
1429 * Returns iid for success, < 0 for failure.
1430 */
1431int
1432ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1433{
1434	struct ctl_softc *softc = control_softc;
1435	time_t best_time;
1436	int i, best;
1437
1438	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1439
1440	if (iid >= CTL_MAX_INIT_PER_PORT) {
1441		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1442		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1443		free(name, M_CTL);
1444		return (-1);
1445	}
1446
1447	mtx_lock(&softc->ctl_lock);
1448
1449	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1450		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1451			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1452				iid = i;
1453				break;
1454			}
1455			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1456			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1457				iid = i;
1458				break;
1459			}
1460		}
1461	}
1462
1463	if (iid < 0) {
1464		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1465			if (port->wwpn_iid[i].in_use == 0 &&
1466			    port->wwpn_iid[i].wwpn == 0 &&
1467			    port->wwpn_iid[i].name == NULL) {
1468				iid = i;
1469				break;
1470			}
1471		}
1472	}
1473
1474	if (iid < 0) {
1475		best = -1;
1476		best_time = INT32_MAX;
1477		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1478			if (port->wwpn_iid[i].in_use == 0) {
1479				if (port->wwpn_iid[i].last_use < best_time) {
1480					best = i;
1481					best_time = port->wwpn_iid[i].last_use;
1482				}
1483			}
1484		}
1485		iid = best;
1486	}
1487
1488	if (iid < 0) {
1489		mtx_unlock(&softc->ctl_lock);
1490		free(name, M_CTL);
1491		return (-2);
1492	}
1493
1494	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1495		/*
1496		 * This is not an error yet.
1497		 */
1498		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1499#if 0
1500			printf("%s: port %d iid %u WWPN %#jx arrived"
1501			    " again\n", __func__, port->targ_port,
1502			    iid, (uintmax_t)wwpn);
1503#endif
1504			goto take;
1505		}
1506		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1507		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1508#if 0
1509			printf("%s: port %d iid %u name '%s' arrived"
1510			    " again\n", __func__, port->targ_port,
1511			    iid, name);
1512#endif
1513			goto take;
1514		}
1515
1516		/*
1517		 * This is an error, but what do we do about it?  The
1518		 * driver is telling us we have a new WWPN for this
1519		 * initiator ID, so we pretty much need to use it.
1520		 */
1521		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1522		    " but WWPN %#jx '%s' is still at that address\n",
1523		    __func__, port->targ_port, iid, wwpn, name,
1524		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1525		    port->wwpn_iid[iid].name);
1526
1527		/*
1528		 * XXX KDM clear have_ca and ua_pending on each LUN for
1529		 * this initiator.
1530		 */
1531	}
1532take:
1533	free(port->wwpn_iid[iid].name, M_CTL);
1534	port->wwpn_iid[iid].name = name;
1535	port->wwpn_iid[iid].wwpn = wwpn;
1536	port->wwpn_iid[iid].in_use++;
1537	mtx_unlock(&softc->ctl_lock);
1538
1539	return (iid);
1540}
1541
1542static int
1543ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1544{
1545	int len;
1546
1547	switch (port->port_type) {
1548	case CTL_PORT_FC:
1549	{
1550		struct scsi_transportid_fcp *id =
1551		    (struct scsi_transportid_fcp *)buf;
1552		if (port->wwpn_iid[iid].wwpn == 0)
1553			return (0);
1554		memset(id, 0, sizeof(*id));
1555		id->format_protocol = SCSI_PROTO_FC;
1556		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1557		return (sizeof(*id));
1558	}
1559	case CTL_PORT_ISCSI:
1560	{
1561		struct scsi_transportid_iscsi_port *id =
1562		    (struct scsi_transportid_iscsi_port *)buf;
1563		if (port->wwpn_iid[iid].name == NULL)
1564			return (0);
1565		memset(id, 0, 256);
1566		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1567		    SCSI_PROTO_ISCSI;
1568		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1569		len = roundup2(min(len, 252), 4);
1570		scsi_ulto2b(len, id->additional_length);
1571		return (sizeof(*id) + len);
1572	}
1573	case CTL_PORT_SAS:
1574	{
1575		struct scsi_transportid_sas *id =
1576		    (struct scsi_transportid_sas *)buf;
1577		if (port->wwpn_iid[iid].wwpn == 0)
1578			return (0);
1579		memset(id, 0, sizeof(*id));
1580		id->format_protocol = SCSI_PROTO_SAS;
1581		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1582		return (sizeof(*id));
1583	}
1584	default:
1585	{
1586		struct scsi_transportid_spi *id =
1587		    (struct scsi_transportid_spi *)buf;
1588		memset(id, 0, sizeof(*id));
1589		id->format_protocol = SCSI_PROTO_SPI;
1590		scsi_ulto2b(iid, id->scsi_addr);
1591		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1592		return (sizeof(*id));
1593	}
1594	}
1595}
1596
1597static int
1598ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1599{
1600	return (0);
1601}
1602
1603static int
1604ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1605{
1606	return (0);
1607}
1608
1609/*
1610 * Data movement routine for the CTL ioctl frontend port.
1611 */
1612static int
1613ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1614{
1615	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1616	struct ctl_sg_entry ext_entry, kern_entry;
1617	int ext_sglen, ext_sg_entries, kern_sg_entries;
1618	int ext_sg_start, ext_offset;
1619	int len_to_copy, len_copied;
1620	int kern_watermark, ext_watermark;
1621	int ext_sglist_malloced;
1622	int i, j;
1623
1624	ext_sglist_malloced = 0;
1625	ext_sg_start = 0;
1626	ext_offset = 0;
1627
1628	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1629
1630	/*
1631	 * If this flag is set, fake the data transfer.
1632	 */
1633	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1634		ctsio->ext_data_filled = ctsio->ext_data_len;
1635		goto bailout;
1636	}
1637
1638	/*
1639	 * To simplify things here, if we have a single buffer, stick it in
1640	 * a S/G entry and just make it a single entry S/G list.
1641	 */
1642	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1643		int len_seen;
1644
1645		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1646
1647		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1648							   M_WAITOK);
1649		ext_sglist_malloced = 1;
1650		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1651				   ext_sglen) != 0) {
1652			ctl_set_internal_failure(ctsio,
1653						 /*sks_valid*/ 0,
1654						 /*retry_count*/ 0);
1655			goto bailout;
1656		}
1657		ext_sg_entries = ctsio->ext_sg_entries;
1658		len_seen = 0;
1659		for (i = 0; i < ext_sg_entries; i++) {
1660			if ((len_seen + ext_sglist[i].len) >=
1661			     ctsio->ext_data_filled) {
1662				ext_sg_start = i;
1663				ext_offset = ctsio->ext_data_filled - len_seen;
1664				break;
1665			}
1666			len_seen += ext_sglist[i].len;
1667		}
1668	} else {
1669		ext_sglist = &ext_entry;
1670		ext_sglist->addr = ctsio->ext_data_ptr;
1671		ext_sglist->len = ctsio->ext_data_len;
1672		ext_sg_entries = 1;
1673		ext_sg_start = 0;
1674		ext_offset = ctsio->ext_data_filled;
1675	}
1676
1677	if (ctsio->kern_sg_entries > 0) {
1678		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1679		kern_sg_entries = ctsio->kern_sg_entries;
1680	} else {
1681		kern_sglist = &kern_entry;
1682		kern_sglist->addr = ctsio->kern_data_ptr;
1683		kern_sglist->len = ctsio->kern_data_len;
1684		kern_sg_entries = 1;
1685	}
1686
1687
1688	kern_watermark = 0;
1689	ext_watermark = ext_offset;
1690	len_copied = 0;
1691	for (i = ext_sg_start, j = 0;
1692	     i < ext_sg_entries && j < kern_sg_entries;) {
1693		uint8_t *ext_ptr, *kern_ptr;
1694
1695		len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1696				      kern_sglist[j].len - kern_watermark);
1697
1698		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1699		ext_ptr = ext_ptr + ext_watermark;
1700		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1701			/*
1702			 * XXX KDM fix this!
1703			 */
1704			panic("need to implement bus address support");
1705#if 0
1706			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1707#endif
1708		} else
1709			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1710		kern_ptr = kern_ptr + kern_watermark;
1711
1712		kern_watermark += len_to_copy;
1713		ext_watermark += len_to_copy;
1714
1715		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1716		     CTL_FLAG_DATA_IN) {
1717			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1718					 "bytes to user\n", len_to_copy));
1719			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1720					 "to %p\n", kern_ptr, ext_ptr));
1721			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1722				ctl_set_internal_failure(ctsio,
1723							 /*sks_valid*/ 0,
1724							 /*retry_count*/ 0);
1725				goto bailout;
1726			}
1727		} else {
1728			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1729					 "bytes from user\n", len_to_copy));
1730			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1731					 "to %p\n", ext_ptr, kern_ptr));
1732			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1733				ctl_set_internal_failure(ctsio,
1734							 /*sks_valid*/ 0,
1735							 /*retry_count*/0);
1736				goto bailout;
1737			}
1738		}
1739
1740		len_copied += len_to_copy;
1741
1742		if (ext_sglist[i].len == ext_watermark) {
1743			i++;
1744			ext_watermark = 0;
1745		}
1746
1747		if (kern_sglist[j].len == kern_watermark) {
1748			j++;
1749			kern_watermark = 0;
1750		}
1751	}
1752
1753	ctsio->ext_data_filled += len_copied;
1754
1755	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1756			 "kern_sg_entries: %d\n", ext_sg_entries,
1757			 kern_sg_entries));
1758	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1759			 "kern_data_len = %d\n", ctsio->ext_data_len,
1760			 ctsio->kern_data_len));
1761
1762
1763	/* XXX KDM set residual?? */
1764bailout:
1765
1766	if (ext_sglist_malloced != 0)
1767		free(ext_sglist, M_CTL);
1768
1769	return (CTL_RETVAL_COMPLETE);
1770}
1771
1772/*
1773 * Serialize a command that went down the "wrong" side, and so was sent to
1774 * this controller for execution.  The logic is a little different than the
1775 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1776 * sent back to the other side, but in the success case, we execute the
1777 * command on this side (XFER mode) or tell the other side to execute it
1778 * (SER_ONLY mode).
1779 */
1780static int
1781ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1782{
1783	struct ctl_softc *ctl_softc;
1784	union ctl_ha_msg msg_info;
1785	struct ctl_lun *lun;
1786	int retval = 0;
1787	uint32_t targ_lun;
1788
1789	ctl_softc = control_softc;
1790
1791	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1792	lun = ctl_softc->ctl_luns[targ_lun];
1793	if (lun==NULL)
1794	{
1795		/*
1796		 * Why isn't LUN defined? The other side wouldn't
1797		 * send a cmd if the LUN is undefined.
1798		 */
1799		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1800
1801		/* "Logical unit not supported" */
1802		ctl_set_sense_data(&msg_info.scsi.sense_data,
1803				   lun,
1804				   /*sense_format*/SSD_TYPE_NONE,
1805				   /*current_error*/ 1,
1806				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1807				   /*asc*/ 0x25,
1808				   /*ascq*/ 0x00,
1809				   SSD_ELEM_NONE);
1810
1811		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1812		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1813		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1814		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1815		msg_info.hdr.serializing_sc = NULL;
1816		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1817	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1818				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1819		}
1820		return(1);
1821
1822	}
1823
1824	mtx_lock(&lun->lun_lock);
1825    	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1826
1827	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1828		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1829		 ooa_links))) {
1830	case CTL_ACTION_BLOCK:
1831		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1832		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1833				  blocked_links);
1834		break;
1835	case CTL_ACTION_PASS:
1836	case CTL_ACTION_SKIP:
1837		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1838			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1839			ctl_enqueue_rtr((union ctl_io *)ctsio);
1840		} else {
1841
1842			/* send msg back to other side */
1843			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1844			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1845			msg_info.hdr.msg_type = CTL_MSG_R2R;
1846#if 0
1847			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1848#endif
1849		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1850			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1851			}
1852		}
1853		break;
1854	case CTL_ACTION_OVERLAP:
1855		/* OVERLAPPED COMMANDS ATTEMPTED */
1856		ctl_set_sense_data(&msg_info.scsi.sense_data,
1857				   lun,
1858				   /*sense_format*/SSD_TYPE_NONE,
1859				   /*current_error*/ 1,
1860				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1861				   /*asc*/ 0x4E,
1862				   /*ascq*/ 0x00,
1863				   SSD_ELEM_NONE);
1864
1865		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1866		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1867		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1868		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1869		msg_info.hdr.serializing_sc = NULL;
1870		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1871#if 0
1872		printf("BAD JUJU:Major Bummer Overlap\n");
1873#endif
1874		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1875		retval = 1;
1876		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1877		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1878		}
1879		break;
1880	case CTL_ACTION_OVERLAP_TAG:
1881		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1882		ctl_set_sense_data(&msg_info.scsi.sense_data,
1883				   lun,
1884				   /*sense_format*/SSD_TYPE_NONE,
1885				   /*current_error*/ 1,
1886				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1887				   /*asc*/ 0x4D,
1888				   /*ascq*/ ctsio->tag_num & 0xff,
1889				   SSD_ELEM_NONE);
1890
1891		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1892		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1893		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1894		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1895		msg_info.hdr.serializing_sc = NULL;
1896		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1897#if 0
1898		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1899#endif
1900		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1901		retval = 1;
1902		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1903		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1904		}
1905		break;
1906	case CTL_ACTION_ERROR:
1907	default:
1908		/* "Internal target failure" */
1909		ctl_set_sense_data(&msg_info.scsi.sense_data,
1910				   lun,
1911				   /*sense_format*/SSD_TYPE_NONE,
1912				   /*current_error*/ 1,
1913				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1914				   /*asc*/ 0x44,
1915				   /*ascq*/ 0x00,
1916				   SSD_ELEM_NONE);
1917
1918		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1919		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1920		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1921		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1922		msg_info.hdr.serializing_sc = NULL;
1923		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1924#if 0
1925		printf("BAD JUJU:Major Bummer HW Error\n");
1926#endif
1927		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1928		retval = 1;
1929		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1930		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1931		}
1932		break;
1933	}
1934	mtx_unlock(&lun->lun_lock);
1935	return (retval);
1936}
1937
1938static int
1939ctl_ioctl_submit_wait(union ctl_io *io)
1940{
1941	struct ctl_fe_ioctl_params params;
1942	ctl_fe_ioctl_state last_state;
1943	int done, retval;
1944
1945	retval = 0;
1946
1947	bzero(&params, sizeof(params));
1948
1949	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1950	cv_init(&params.sem, "ctlioccv");
1951	params.state = CTL_IOCTL_INPROG;
1952	last_state = params.state;
1953
1954	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1955
1956	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1957
1958	/* This shouldn't happen */
1959	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1960		return (retval);
1961
1962	done = 0;
1963
1964	do {
1965		mtx_lock(&params.ioctl_mtx);
1966		/*
1967		 * Check the state here, and don't sleep if the state has
1968		 * already changed (i.e. wakeup has already occured, but we
1969		 * weren't waiting yet).
1970		 */
1971		if (params.state == last_state) {
1972			/* XXX KDM cv_wait_sig instead? */
1973			cv_wait(&params.sem, &params.ioctl_mtx);
1974		}
1975		last_state = params.state;
1976
1977		switch (params.state) {
1978		case CTL_IOCTL_INPROG:
1979			/* Why did we wake up? */
1980			/* XXX KDM error here? */
1981			mtx_unlock(&params.ioctl_mtx);
1982			break;
1983		case CTL_IOCTL_DATAMOVE:
1984			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1985
1986			/*
1987			 * change last_state back to INPROG to avoid
1988			 * deadlock on subsequent data moves.
1989			 */
1990			params.state = last_state = CTL_IOCTL_INPROG;
1991
1992			mtx_unlock(&params.ioctl_mtx);
1993			ctl_ioctl_do_datamove(&io->scsiio);
1994			/*
1995			 * Note that in some cases, most notably writes,
1996			 * this will queue the I/O and call us back later.
1997			 * In other cases, generally reads, this routine
1998			 * will immediately call back and wake us up,
1999			 * probably using our own context.
2000			 */
2001			io->scsiio.be_move_done(io);
2002			break;
2003		case CTL_IOCTL_DONE:
2004			mtx_unlock(&params.ioctl_mtx);
2005			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
2006			done = 1;
2007			break;
2008		default:
2009			mtx_unlock(&params.ioctl_mtx);
2010			/* XXX KDM error here? */
2011			break;
2012		}
2013	} while (done == 0);
2014
2015	mtx_destroy(&params.ioctl_mtx);
2016	cv_destroy(&params.sem);
2017
2018	return (CTL_RETVAL_COMPLETE);
2019}
2020
2021static void
2022ctl_ioctl_datamove(union ctl_io *io)
2023{
2024	struct ctl_fe_ioctl_params *params;
2025
2026	params = (struct ctl_fe_ioctl_params *)
2027		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2028
2029	mtx_lock(&params->ioctl_mtx);
2030	params->state = CTL_IOCTL_DATAMOVE;
2031	cv_broadcast(&params->sem);
2032	mtx_unlock(&params->ioctl_mtx);
2033}
2034
2035static void
2036ctl_ioctl_done(union ctl_io *io)
2037{
2038	struct ctl_fe_ioctl_params *params;
2039
2040	params = (struct ctl_fe_ioctl_params *)
2041		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2042
2043	mtx_lock(&params->ioctl_mtx);
2044	params->state = CTL_IOCTL_DONE;
2045	cv_broadcast(&params->sem);
2046	mtx_unlock(&params->ioctl_mtx);
2047}
2048
2049static void
2050ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2051{
2052	struct ctl_fe_ioctl_startstop_info *sd_info;
2053
2054	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2055
2056	sd_info->hs_info.status = metatask->status;
2057	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2058	sd_info->hs_info.luns_complete =
2059		metatask->taskinfo.startstop.luns_complete;
2060	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2061
2062	cv_broadcast(&sd_info->sem);
2063}
2064
2065static void
2066ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2067{
2068	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2069
2070	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2071
2072	mtx_lock(fe_bbr_info->lock);
2073	fe_bbr_info->bbr_info->status = metatask->status;
2074	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2075	fe_bbr_info->wakeup_done = 1;
2076	mtx_unlock(fe_bbr_info->lock);
2077
2078	cv_broadcast(&fe_bbr_info->sem);
2079}
2080
2081/*
2082 * Returns 0 for success, errno for failure.
2083 */
2084static int
2085ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2086		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2087{
2088	union ctl_io *io;
2089	int retval;
2090
2091	retval = 0;
2092
2093	mtx_lock(&lun->lun_lock);
2094	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2095	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2096	     ooa_links)) {
2097		struct ctl_ooa_entry *entry;
2098
2099		/*
2100		 * If we've got more than we can fit, just count the
2101		 * remaining entries.
2102		 */
2103		if (*cur_fill_num >= ooa_hdr->alloc_num)
2104			continue;
2105
2106		entry = &kern_entries[*cur_fill_num];
2107
2108		entry->tag_num = io->scsiio.tag_num;
2109		entry->lun_num = lun->lun;
2110#ifdef CTL_TIME_IO
2111		entry->start_bt = io->io_hdr.start_bt;
2112#endif
2113		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2114		entry->cdb_len = io->scsiio.cdb_len;
2115		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2116			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2117
2118		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2119			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2120
2121		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2122			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2123
2124		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2125			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2126
2127		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2128			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2129	}
2130	mtx_unlock(&lun->lun_lock);
2131
2132	return (retval);
2133}
2134
2135static void *
2136ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2137		 size_t error_str_len)
2138{
2139	void *kptr;
2140
2141	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2142
2143	if (copyin(user_addr, kptr, len) != 0) {
2144		snprintf(error_str, error_str_len, "Error copying %d bytes "
2145			 "from user address %p to kernel address %p", len,
2146			 user_addr, kptr);
2147		free(kptr, M_CTL);
2148		return (NULL);
2149	}
2150
2151	return (kptr);
2152}
2153
2154static void
2155ctl_free_args(int num_args, struct ctl_be_arg *args)
2156{
2157	int i;
2158
2159	if (args == NULL)
2160		return;
2161
2162	for (i = 0; i < num_args; i++) {
2163		free(args[i].kname, M_CTL);
2164		free(args[i].kvalue, M_CTL);
2165	}
2166
2167	free(args, M_CTL);
2168}
2169
2170static struct ctl_be_arg *
2171ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2172		char *error_str, size_t error_str_len)
2173{
2174	struct ctl_be_arg *args;
2175	int i;
2176
2177	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2178				error_str, error_str_len);
2179
2180	if (args == NULL)
2181		goto bailout;
2182
2183	for (i = 0; i < num_args; i++) {
2184		args[i].kname = NULL;
2185		args[i].kvalue = NULL;
2186	}
2187
2188	for (i = 0; i < num_args; i++) {
2189		uint8_t *tmpptr;
2190
2191		args[i].kname = ctl_copyin_alloc(args[i].name,
2192			args[i].namelen, error_str, error_str_len);
2193		if (args[i].kname == NULL)
2194			goto bailout;
2195
2196		if (args[i].kname[args[i].namelen - 1] != '\0') {
2197			snprintf(error_str, error_str_len, "Argument %d "
2198				 "name is not NUL-terminated", i);
2199			goto bailout;
2200		}
2201
2202		if (args[i].flags & CTL_BEARG_RD) {
2203			tmpptr = ctl_copyin_alloc(args[i].value,
2204				args[i].vallen, error_str, error_str_len);
2205			if (tmpptr == NULL)
2206				goto bailout;
2207			if ((args[i].flags & CTL_BEARG_ASCII)
2208			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2209				snprintf(error_str, error_str_len, "Argument "
2210				    "%d value is not NUL-terminated", i);
2211				goto bailout;
2212			}
2213			args[i].kvalue = tmpptr;
2214		} else {
2215			args[i].kvalue = malloc(args[i].vallen,
2216			    M_CTL, M_WAITOK | M_ZERO);
2217		}
2218	}
2219
2220	return (args);
2221bailout:
2222
2223	ctl_free_args(num_args, args);
2224
2225	return (NULL);
2226}
2227
2228static void
2229ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2230{
2231	int i;
2232
2233	for (i = 0; i < num_args; i++) {
2234		if (args[i].flags & CTL_BEARG_WR)
2235			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2236	}
2237}
2238
2239/*
2240 * Escape characters that are illegal or not recommended in XML.
2241 */
2242int
2243ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2244{
2245	char *end = str + size;
2246	int retval;
2247
2248	retval = 0;
2249
2250	for (; *str && str < end; str++) {
2251		switch (*str) {
2252		case '&':
2253			retval = sbuf_printf(sb, "&amp;");
2254			break;
2255		case '>':
2256			retval = sbuf_printf(sb, "&gt;");
2257			break;
2258		case '<':
2259			retval = sbuf_printf(sb, "&lt;");
2260			break;
2261		default:
2262			retval = sbuf_putc(sb, *str);
2263			break;
2264		}
2265
2266		if (retval != 0)
2267			break;
2268
2269	}
2270
2271	return (retval);
2272}
2273
2274static void
2275ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2276{
2277	struct scsi_vpd_id_descriptor *desc;
2278	int i;
2279
2280	if (id == NULL || id->len < 4)
2281		return;
2282	desc = (struct scsi_vpd_id_descriptor *)id->data;
2283	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2284	case SVPD_ID_TYPE_T10:
2285		sbuf_printf(sb, "t10.");
2286		break;
2287	case SVPD_ID_TYPE_EUI64:
2288		sbuf_printf(sb, "eui.");
2289		break;
2290	case SVPD_ID_TYPE_NAA:
2291		sbuf_printf(sb, "naa.");
2292		break;
2293	case SVPD_ID_TYPE_SCSI_NAME:
2294		break;
2295	}
2296	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2297	case SVPD_ID_CODESET_BINARY:
2298		for (i = 0; i < desc->length; i++)
2299			sbuf_printf(sb, "%02x", desc->identifier[i]);
2300		break;
2301	case SVPD_ID_CODESET_ASCII:
2302		sbuf_printf(sb, "%.*s", (int)desc->length,
2303		    (char *)desc->identifier);
2304		break;
2305	case SVPD_ID_CODESET_UTF8:
2306		sbuf_printf(sb, "%s", (char *)desc->identifier);
2307		break;
2308	}
2309}
2310
2311static int
2312ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2313	  struct thread *td)
2314{
2315	struct ctl_softc *softc;
2316	int retval;
2317
2318	softc = control_softc;
2319
2320	retval = 0;
2321
2322	switch (cmd) {
2323	case CTL_IO: {
2324		union ctl_io *io;
2325		void *pool_tmp;
2326
2327		/*
2328		 * If we haven't been "enabled", don't allow any SCSI I/O
2329		 * to this FETD.
2330		 */
2331		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2332			retval = EPERM;
2333			break;
2334		}
2335
2336		io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2337
2338		/*
2339		 * Need to save the pool reference so it doesn't get
2340		 * spammed by the user's ctl_io.
2341		 */
2342		pool_tmp = io->io_hdr.pool;
2343		memcpy(io, (void *)addr, sizeof(*io));
2344		io->io_hdr.pool = pool_tmp;
2345
2346		/*
2347		 * No status yet, so make sure the status is set properly.
2348		 */
2349		io->io_hdr.status = CTL_STATUS_NONE;
2350
2351		/*
2352		 * The user sets the initiator ID, target and LUN IDs.
2353		 */
2354		io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2355		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2356		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2357		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2358			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2359
2360		retval = ctl_ioctl_submit_wait(io);
2361
2362		if (retval != 0) {
2363			ctl_free_io(io);
2364			break;
2365		}
2366
2367		memcpy((void *)addr, io, sizeof(*io));
2368
2369		/* return this to our pool */
2370		ctl_free_io(io);
2371
2372		break;
2373	}
2374	case CTL_ENABLE_PORT:
2375	case CTL_DISABLE_PORT:
2376	case CTL_SET_PORT_WWNS: {
2377		struct ctl_port *port;
2378		struct ctl_port_entry *entry;
2379
2380		entry = (struct ctl_port_entry *)addr;
2381
2382		mtx_lock(&softc->ctl_lock);
2383		STAILQ_FOREACH(port, &softc->port_list, links) {
2384			int action, done;
2385
2386			action = 0;
2387			done = 0;
2388
2389			if ((entry->port_type == CTL_PORT_NONE)
2390			 && (entry->targ_port == port->targ_port)) {
2391				/*
2392				 * If the user only wants to enable or
2393				 * disable or set WWNs on a specific port,
2394				 * do the operation and we're done.
2395				 */
2396				action = 1;
2397				done = 1;
2398			} else if (entry->port_type & port->port_type) {
2399				/*
2400				 * Compare the user's type mask with the
2401				 * particular frontend type to see if we
2402				 * have a match.
2403				 */
2404				action = 1;
2405				done = 0;
2406
2407				/*
2408				 * Make sure the user isn't trying to set
2409				 * WWNs on multiple ports at the same time.
2410				 */
2411				if (cmd == CTL_SET_PORT_WWNS) {
2412					printf("%s: Can't set WWNs on "
2413					       "multiple ports\n", __func__);
2414					retval = EINVAL;
2415					break;
2416				}
2417			}
2418			if (action != 0) {
2419				/*
2420				 * XXX KDM we have to drop the lock here,
2421				 * because the online/offline operations
2422				 * can potentially block.  We need to
2423				 * reference count the frontends so they
2424				 * can't go away,
2425				 */
2426				mtx_unlock(&softc->ctl_lock);
2427
2428				if (cmd == CTL_ENABLE_PORT) {
2429					struct ctl_lun *lun;
2430
2431					STAILQ_FOREACH(lun, &softc->lun_list,
2432						       links) {
2433						port->lun_enable(port->targ_lun_arg,
2434						    lun->target,
2435						    lun->lun);
2436					}
2437
2438					ctl_port_online(port);
2439				} else if (cmd == CTL_DISABLE_PORT) {
2440					struct ctl_lun *lun;
2441
2442					ctl_port_offline(port);
2443
2444					STAILQ_FOREACH(lun, &softc->lun_list,
2445						       links) {
2446						port->lun_disable(
2447						    port->targ_lun_arg,
2448						    lun->target,
2449						    lun->lun);
2450					}
2451				}
2452
2453				mtx_lock(&softc->ctl_lock);
2454
2455				if (cmd == CTL_SET_PORT_WWNS)
2456					ctl_port_set_wwns(port,
2457					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2458					    1 : 0, entry->wwnn,
2459					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2460					    1 : 0, entry->wwpn);
2461			}
2462			if (done != 0)
2463				break;
2464		}
2465		mtx_unlock(&softc->ctl_lock);
2466		break;
2467	}
2468	case CTL_GET_PORT_LIST: {
2469		struct ctl_port *port;
2470		struct ctl_port_list *list;
2471		int i;
2472
2473		list = (struct ctl_port_list *)addr;
2474
2475		if (list->alloc_len != (list->alloc_num *
2476		    sizeof(struct ctl_port_entry))) {
2477			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2478			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2479			       "%zu\n", __func__, list->alloc_len,
2480			       list->alloc_num, sizeof(struct ctl_port_entry));
2481			retval = EINVAL;
2482			break;
2483		}
2484		list->fill_len = 0;
2485		list->fill_num = 0;
2486		list->dropped_num = 0;
2487		i = 0;
2488		mtx_lock(&softc->ctl_lock);
2489		STAILQ_FOREACH(port, &softc->port_list, links) {
2490			struct ctl_port_entry entry, *list_entry;
2491
2492			if (list->fill_num >= list->alloc_num) {
2493				list->dropped_num++;
2494				continue;
2495			}
2496
2497			entry.port_type = port->port_type;
2498			strlcpy(entry.port_name, port->port_name,
2499				sizeof(entry.port_name));
2500			entry.targ_port = port->targ_port;
2501			entry.physical_port = port->physical_port;
2502			entry.virtual_port = port->virtual_port;
2503			entry.wwnn = port->wwnn;
2504			entry.wwpn = port->wwpn;
2505			if (port->status & CTL_PORT_STATUS_ONLINE)
2506				entry.online = 1;
2507			else
2508				entry.online = 0;
2509
2510			list_entry = &list->entries[i];
2511
2512			retval = copyout(&entry, list_entry, sizeof(entry));
2513			if (retval != 0) {
2514				printf("%s: CTL_GET_PORT_LIST: copyout "
2515				       "returned %d\n", __func__, retval);
2516				break;
2517			}
2518			i++;
2519			list->fill_num++;
2520			list->fill_len += sizeof(entry);
2521		}
2522		mtx_unlock(&softc->ctl_lock);
2523
2524		/*
2525		 * If this is non-zero, we had a copyout fault, so there's
2526		 * probably no point in attempting to set the status inside
2527		 * the structure.
2528		 */
2529		if (retval != 0)
2530			break;
2531
2532		if (list->dropped_num > 0)
2533			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2534		else
2535			list->status = CTL_PORT_LIST_OK;
2536		break;
2537	}
2538	case CTL_DUMP_OOA: {
2539		struct ctl_lun *lun;
2540		union ctl_io *io;
2541		char printbuf[128];
2542		struct sbuf sb;
2543
2544		mtx_lock(&softc->ctl_lock);
2545		printf("Dumping OOA queues:\n");
2546		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2547			mtx_lock(&lun->lun_lock);
2548			for (io = (union ctl_io *)TAILQ_FIRST(
2549			     &lun->ooa_queue); io != NULL;
2550			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2551			     ooa_links)) {
2552				sbuf_new(&sb, printbuf, sizeof(printbuf),
2553					 SBUF_FIXEDLEN);
2554				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2555					    (intmax_t)lun->lun,
2556					    io->scsiio.tag_num,
2557					    (io->io_hdr.flags &
2558					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2559					    (io->io_hdr.flags &
2560					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2561					    (io->io_hdr.flags &
2562					    CTL_FLAG_ABORT) ? " ABORT" : "",
2563			                    (io->io_hdr.flags &
2564		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2565				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2566				sbuf_finish(&sb);
2567				printf("%s\n", sbuf_data(&sb));
2568			}
2569			mtx_unlock(&lun->lun_lock);
2570		}
2571		printf("OOA queues dump done\n");
2572		mtx_unlock(&softc->ctl_lock);
2573		break;
2574	}
2575	case CTL_GET_OOA: {
2576		struct ctl_lun *lun;
2577		struct ctl_ooa *ooa_hdr;
2578		struct ctl_ooa_entry *entries;
2579		uint32_t cur_fill_num;
2580
2581		ooa_hdr = (struct ctl_ooa *)addr;
2582
2583		if ((ooa_hdr->alloc_len == 0)
2584		 || (ooa_hdr->alloc_num == 0)) {
2585			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2586			       "must be non-zero\n", __func__,
2587			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2588			retval = EINVAL;
2589			break;
2590		}
2591
2592		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2593		    sizeof(struct ctl_ooa_entry))) {
2594			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2595			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2596			       __func__, ooa_hdr->alloc_len,
2597			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2598			retval = EINVAL;
2599			break;
2600		}
2601
2602		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2603		if (entries == NULL) {
2604			printf("%s: could not allocate %d bytes for OOA "
2605			       "dump\n", __func__, ooa_hdr->alloc_len);
2606			retval = ENOMEM;
2607			break;
2608		}
2609
2610		mtx_lock(&softc->ctl_lock);
2611		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2612		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2613		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2614			mtx_unlock(&softc->ctl_lock);
2615			free(entries, M_CTL);
2616			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2617			       __func__, (uintmax_t)ooa_hdr->lun_num);
2618			retval = EINVAL;
2619			break;
2620		}
2621
2622		cur_fill_num = 0;
2623
2624		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2625			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2626				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2627					ooa_hdr, entries);
2628				if (retval != 0)
2629					break;
2630			}
2631			if (retval != 0) {
2632				mtx_unlock(&softc->ctl_lock);
2633				free(entries, M_CTL);
2634				break;
2635			}
2636		} else {
2637			lun = softc->ctl_luns[ooa_hdr->lun_num];
2638
2639			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2640						    entries);
2641		}
2642		mtx_unlock(&softc->ctl_lock);
2643
2644		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2645		ooa_hdr->fill_len = ooa_hdr->fill_num *
2646			sizeof(struct ctl_ooa_entry);
2647		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2648		if (retval != 0) {
2649			printf("%s: error copying out %d bytes for OOA dump\n",
2650			       __func__, ooa_hdr->fill_len);
2651		}
2652
2653		getbintime(&ooa_hdr->cur_bt);
2654
2655		if (cur_fill_num > ooa_hdr->alloc_num) {
2656			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2657			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2658		} else {
2659			ooa_hdr->dropped_num = 0;
2660			ooa_hdr->status = CTL_OOA_OK;
2661		}
2662
2663		free(entries, M_CTL);
2664		break;
2665	}
2666	case CTL_CHECK_OOA: {
2667		union ctl_io *io;
2668		struct ctl_lun *lun;
2669		struct ctl_ooa_info *ooa_info;
2670
2671
2672		ooa_info = (struct ctl_ooa_info *)addr;
2673
2674		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2675			ooa_info->status = CTL_OOA_INVALID_LUN;
2676			break;
2677		}
2678		mtx_lock(&softc->ctl_lock);
2679		lun = softc->ctl_luns[ooa_info->lun_id];
2680		if (lun == NULL) {
2681			mtx_unlock(&softc->ctl_lock);
2682			ooa_info->status = CTL_OOA_INVALID_LUN;
2683			break;
2684		}
2685		mtx_lock(&lun->lun_lock);
2686		mtx_unlock(&softc->ctl_lock);
2687		ooa_info->num_entries = 0;
2688		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2689		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2690		     &io->io_hdr, ooa_links)) {
2691			ooa_info->num_entries++;
2692		}
2693		mtx_unlock(&lun->lun_lock);
2694
2695		ooa_info->status = CTL_OOA_SUCCESS;
2696
2697		break;
2698	}
2699	case CTL_HARD_START:
2700	case CTL_HARD_STOP: {
2701		struct ctl_fe_ioctl_startstop_info ss_info;
2702		struct cfi_metatask *metatask;
2703		struct mtx hs_mtx;
2704
2705		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2706
2707		cv_init(&ss_info.sem, "hard start/stop cv" );
2708
2709		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2710		if (metatask == NULL) {
2711			retval = ENOMEM;
2712			mtx_destroy(&hs_mtx);
2713			break;
2714		}
2715
2716		if (cmd == CTL_HARD_START)
2717			metatask->tasktype = CFI_TASK_STARTUP;
2718		else
2719			metatask->tasktype = CFI_TASK_SHUTDOWN;
2720
2721		metatask->callback = ctl_ioctl_hard_startstop_callback;
2722		metatask->callback_arg = &ss_info;
2723
2724		cfi_action(metatask);
2725
2726		/* Wait for the callback */
2727		mtx_lock(&hs_mtx);
2728		cv_wait_sig(&ss_info.sem, &hs_mtx);
2729		mtx_unlock(&hs_mtx);
2730
2731		/*
2732		 * All information has been copied from the metatask by the
2733		 * time cv_broadcast() is called, so we free the metatask here.
2734		 */
2735		cfi_free_metatask(metatask);
2736
2737		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2738
2739		mtx_destroy(&hs_mtx);
2740		break;
2741	}
2742	case CTL_BBRREAD: {
2743		struct ctl_bbrread_info *bbr_info;
2744		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2745		struct mtx bbr_mtx;
2746		struct cfi_metatask *metatask;
2747
2748		bbr_info = (struct ctl_bbrread_info *)addr;
2749
2750		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2751
2752		bzero(&bbr_mtx, sizeof(bbr_mtx));
2753		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2754
2755		fe_bbr_info.bbr_info = bbr_info;
2756		fe_bbr_info.lock = &bbr_mtx;
2757
2758		cv_init(&fe_bbr_info.sem, "BBR read cv");
2759		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2760
2761		if (metatask == NULL) {
2762			mtx_destroy(&bbr_mtx);
2763			cv_destroy(&fe_bbr_info.sem);
2764			retval = ENOMEM;
2765			break;
2766		}
2767		metatask->tasktype = CFI_TASK_BBRREAD;
2768		metatask->callback = ctl_ioctl_bbrread_callback;
2769		metatask->callback_arg = &fe_bbr_info;
2770		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2771		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2772		metatask->taskinfo.bbrread.len = bbr_info->len;
2773
2774		cfi_action(metatask);
2775
2776		mtx_lock(&bbr_mtx);
2777		while (fe_bbr_info.wakeup_done == 0)
2778			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2779		mtx_unlock(&bbr_mtx);
2780
2781		bbr_info->status = metatask->status;
2782		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2783		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2784		memcpy(&bbr_info->sense_data,
2785		       &metatask->taskinfo.bbrread.sense_data,
2786		       ctl_min(sizeof(bbr_info->sense_data),
2787			       sizeof(metatask->taskinfo.bbrread.sense_data)));
2788
2789		cfi_free_metatask(metatask);
2790
2791		mtx_destroy(&bbr_mtx);
2792		cv_destroy(&fe_bbr_info.sem);
2793
2794		break;
2795	}
2796	case CTL_DELAY_IO: {
2797		struct ctl_io_delay_info *delay_info;
2798#ifdef CTL_IO_DELAY
2799		struct ctl_lun *lun;
2800#endif /* CTL_IO_DELAY */
2801
2802		delay_info = (struct ctl_io_delay_info *)addr;
2803
2804#ifdef CTL_IO_DELAY
2805		mtx_lock(&softc->ctl_lock);
2806
2807		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2808		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2809			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2810		} else {
2811			lun = softc->ctl_luns[delay_info->lun_id];
2812			mtx_lock(&lun->lun_lock);
2813
2814			delay_info->status = CTL_DELAY_STATUS_OK;
2815
2816			switch (delay_info->delay_type) {
2817			case CTL_DELAY_TYPE_CONT:
2818				break;
2819			case CTL_DELAY_TYPE_ONESHOT:
2820				break;
2821			default:
2822				delay_info->status =
2823					CTL_DELAY_STATUS_INVALID_TYPE;
2824				break;
2825			}
2826
2827			switch (delay_info->delay_loc) {
2828			case CTL_DELAY_LOC_DATAMOVE:
2829				lun->delay_info.datamove_type =
2830					delay_info->delay_type;
2831				lun->delay_info.datamove_delay =
2832					delay_info->delay_secs;
2833				break;
2834			case CTL_DELAY_LOC_DONE:
2835				lun->delay_info.done_type =
2836					delay_info->delay_type;
2837				lun->delay_info.done_delay =
2838					delay_info->delay_secs;
2839				break;
2840			default:
2841				delay_info->status =
2842					CTL_DELAY_STATUS_INVALID_LOC;
2843				break;
2844			}
2845			mtx_unlock(&lun->lun_lock);
2846		}
2847
2848		mtx_unlock(&softc->ctl_lock);
2849#else
2850		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2851#endif /* CTL_IO_DELAY */
2852		break;
2853	}
2854	case CTL_REALSYNC_SET: {
2855		int *syncstate;
2856
2857		syncstate = (int *)addr;
2858
2859		mtx_lock(&softc->ctl_lock);
2860		switch (*syncstate) {
2861		case 0:
2862			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2863			break;
2864		case 1:
2865			softc->flags |= CTL_FLAG_REAL_SYNC;
2866			break;
2867		default:
2868			retval = EINVAL;
2869			break;
2870		}
2871		mtx_unlock(&softc->ctl_lock);
2872		break;
2873	}
2874	case CTL_REALSYNC_GET: {
2875		int *syncstate;
2876
2877		syncstate = (int*)addr;
2878
2879		mtx_lock(&softc->ctl_lock);
2880		if (softc->flags & CTL_FLAG_REAL_SYNC)
2881			*syncstate = 1;
2882		else
2883			*syncstate = 0;
2884		mtx_unlock(&softc->ctl_lock);
2885
2886		break;
2887	}
2888	case CTL_SETSYNC:
2889	case CTL_GETSYNC: {
2890		struct ctl_sync_info *sync_info;
2891		struct ctl_lun *lun;
2892
2893		sync_info = (struct ctl_sync_info *)addr;
2894
2895		mtx_lock(&softc->ctl_lock);
2896		lun = softc->ctl_luns[sync_info->lun_id];
2897		if (lun == NULL) {
2898			mtx_unlock(&softc->ctl_lock);
2899			sync_info->status = CTL_GS_SYNC_NO_LUN;
2900		}
2901		/*
2902		 * Get or set the sync interval.  We're not bounds checking
2903		 * in the set case, hopefully the user won't do something
2904		 * silly.
2905		 */
2906		mtx_lock(&lun->lun_lock);
2907		mtx_unlock(&softc->ctl_lock);
2908		if (cmd == CTL_GETSYNC)
2909			sync_info->sync_interval = lun->sync_interval;
2910		else
2911			lun->sync_interval = sync_info->sync_interval;
2912		mtx_unlock(&lun->lun_lock);
2913
2914		sync_info->status = CTL_GS_SYNC_OK;
2915
2916		break;
2917	}
2918	case CTL_GETSTATS: {
2919		struct ctl_stats *stats;
2920		struct ctl_lun *lun;
2921		int i;
2922
2923		stats = (struct ctl_stats *)addr;
2924
2925		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2926		     stats->alloc_len) {
2927			stats->status = CTL_SS_NEED_MORE_SPACE;
2928			stats->num_luns = softc->num_luns;
2929			break;
2930		}
2931		/*
2932		 * XXX KDM no locking here.  If the LUN list changes,
2933		 * things can blow up.
2934		 */
2935		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2936		     i++, lun = STAILQ_NEXT(lun, links)) {
2937			retval = copyout(&lun->stats, &stats->lun_stats[i],
2938					 sizeof(lun->stats));
2939			if (retval != 0)
2940				break;
2941		}
2942		stats->num_luns = softc->num_luns;
2943		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2944				 softc->num_luns;
2945		stats->status = CTL_SS_OK;
2946#ifdef CTL_TIME_IO
2947		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2948#else
2949		stats->flags = CTL_STATS_FLAG_NONE;
2950#endif
2951		getnanouptime(&stats->timestamp);
2952		break;
2953	}
2954	case CTL_ERROR_INJECT: {
2955		struct ctl_error_desc *err_desc, *new_err_desc;
2956		struct ctl_lun *lun;
2957
2958		err_desc = (struct ctl_error_desc *)addr;
2959
2960		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2961				      M_WAITOK | M_ZERO);
2962		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2963
2964		mtx_lock(&softc->ctl_lock);
2965		lun = softc->ctl_luns[err_desc->lun_id];
2966		if (lun == NULL) {
2967			mtx_unlock(&softc->ctl_lock);
2968			free(new_err_desc, M_CTL);
2969			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2970			       __func__, (uintmax_t)err_desc->lun_id);
2971			retval = EINVAL;
2972			break;
2973		}
2974		mtx_lock(&lun->lun_lock);
2975		mtx_unlock(&softc->ctl_lock);
2976
2977		/*
2978		 * We could do some checking here to verify the validity
2979		 * of the request, but given the complexity of error
2980		 * injection requests, the checking logic would be fairly
2981		 * complex.
2982		 *
2983		 * For now, if the request is invalid, it just won't get
2984		 * executed and might get deleted.
2985		 */
2986		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2987
2988		/*
2989		 * XXX KDM check to make sure the serial number is unique,
2990		 * in case we somehow manage to wrap.  That shouldn't
2991		 * happen for a very long time, but it's the right thing to
2992		 * do.
2993		 */
2994		new_err_desc->serial = lun->error_serial;
2995		err_desc->serial = lun->error_serial;
2996		lun->error_serial++;
2997
2998		mtx_unlock(&lun->lun_lock);
2999		break;
3000	}
3001	case CTL_ERROR_INJECT_DELETE: {
3002		struct ctl_error_desc *delete_desc, *desc, *desc2;
3003		struct ctl_lun *lun;
3004		int delete_done;
3005
3006		delete_desc = (struct ctl_error_desc *)addr;
3007		delete_done = 0;
3008
3009		mtx_lock(&softc->ctl_lock);
3010		lun = softc->ctl_luns[delete_desc->lun_id];
3011		if (lun == NULL) {
3012			mtx_unlock(&softc->ctl_lock);
3013			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
3014			       __func__, (uintmax_t)delete_desc->lun_id);
3015			retval = EINVAL;
3016			break;
3017		}
3018		mtx_lock(&lun->lun_lock);
3019		mtx_unlock(&softc->ctl_lock);
3020		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
3021			if (desc->serial != delete_desc->serial)
3022				continue;
3023
3024			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
3025				      links);
3026			free(desc, M_CTL);
3027			delete_done = 1;
3028		}
3029		mtx_unlock(&lun->lun_lock);
3030		if (delete_done == 0) {
3031			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
3032			       "error serial %ju on LUN %u\n", __func__,
3033			       delete_desc->serial, delete_desc->lun_id);
3034			retval = EINVAL;
3035			break;
3036		}
3037		break;
3038	}
3039	case CTL_DUMP_STRUCTS: {
3040		int i, j, k, idx;
3041		struct ctl_port *port;
3042		struct ctl_frontend *fe;
3043
3044		mtx_lock(&softc->ctl_lock);
3045		printf("CTL Persistent Reservation information start:\n");
3046		for (i = 0; i < CTL_MAX_LUNS; i++) {
3047			struct ctl_lun *lun;
3048
3049			lun = softc->ctl_luns[i];
3050
3051			if ((lun == NULL)
3052			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
3053				continue;
3054
3055			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
3056				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
3057					idx = j * CTL_MAX_INIT_PER_PORT + k;
3058					if (lun->pr_keys[idx] == 0)
3059						continue;
3060					printf("  LUN %d port %d iid %d key "
3061					       "%#jx\n", i, j, k,
3062					       (uintmax_t)lun->pr_keys[idx]);
3063				}
3064			}
3065		}
3066		printf("CTL Persistent Reservation information end\n");
3067		printf("CTL Ports:\n");
3068		STAILQ_FOREACH(port, &softc->port_list, links) {
3069			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3070			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3071			       port->frontend->name, port->port_type,
3072			       port->physical_port, port->virtual_port,
3073			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3074			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3075				if (port->wwpn_iid[j].in_use == 0 &&
3076				    port->wwpn_iid[j].wwpn == 0 &&
3077				    port->wwpn_iid[j].name == NULL)
3078					continue;
3079
3080				printf("    iid %u use %d WWPN %#jx '%s'\n",
3081				    j, port->wwpn_iid[j].in_use,
3082				    (uintmax_t)port->wwpn_iid[j].wwpn,
3083				    port->wwpn_iid[j].name);
3084			}
3085		}
3086		printf("CTL Port information end\n");
3087		mtx_unlock(&softc->ctl_lock);
3088		/*
3089		 * XXX KDM calling this without a lock.  We'd likely want
3090		 * to drop the lock before calling the frontend's dump
3091		 * routine anyway.
3092		 */
3093		printf("CTL Frontends:\n");
3094		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3095			printf("  Frontend '%s'\n", fe->name);
3096			if (fe->fe_dump != NULL)
3097				fe->fe_dump();
3098		}
3099		printf("CTL Frontend information end\n");
3100		break;
3101	}
3102	case CTL_LUN_REQ: {
3103		struct ctl_lun_req *lun_req;
3104		struct ctl_backend_driver *backend;
3105
3106		lun_req = (struct ctl_lun_req *)addr;
3107
3108		backend = ctl_backend_find(lun_req->backend);
3109		if (backend == NULL) {
3110			lun_req->status = CTL_LUN_ERROR;
3111			snprintf(lun_req->error_str,
3112				 sizeof(lun_req->error_str),
3113				 "Backend \"%s\" not found.",
3114				 lun_req->backend);
3115			break;
3116		}
3117		if (lun_req->num_be_args > 0) {
3118			lun_req->kern_be_args = ctl_copyin_args(
3119				lun_req->num_be_args,
3120				lun_req->be_args,
3121				lun_req->error_str,
3122				sizeof(lun_req->error_str));
3123			if (lun_req->kern_be_args == NULL) {
3124				lun_req->status = CTL_LUN_ERROR;
3125				break;
3126			}
3127		}
3128
3129		retval = backend->ioctl(dev, cmd, addr, flag, td);
3130
3131		if (lun_req->num_be_args > 0) {
3132			ctl_copyout_args(lun_req->num_be_args,
3133				      lun_req->kern_be_args);
3134			ctl_free_args(lun_req->num_be_args,
3135				      lun_req->kern_be_args);
3136		}
3137		break;
3138	}
3139	case CTL_LUN_LIST: {
3140		struct sbuf *sb;
3141		struct ctl_lun *lun;
3142		struct ctl_lun_list *list;
3143		struct ctl_option *opt;
3144
3145		list = (struct ctl_lun_list *)addr;
3146
3147		/*
3148		 * Allocate a fixed length sbuf here, based on the length
3149		 * of the user's buffer.  We could allocate an auto-extending
3150		 * buffer, and then tell the user how much larger our
3151		 * amount of data is than his buffer, but that presents
3152		 * some problems:
3153		 *
3154		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3155		 *     we can't hold a lock while calling them with an
3156		 *     auto-extending buffer.
3157 		 *
3158		 * 2.  There is not currently a LUN reference counting
3159		 *     mechanism, outside of outstanding transactions on
3160		 *     the LUN's OOA queue.  So a LUN could go away on us
3161		 *     while we're getting the LUN number, backend-specific
3162		 *     information, etc.  Thus, given the way things
3163		 *     currently work, we need to hold the CTL lock while
3164		 *     grabbing LUN information.
3165		 *
3166		 * So, from the user's standpoint, the best thing to do is
3167		 * allocate what he thinks is a reasonable buffer length,
3168		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3169		 * double the buffer length and try again.  (And repeat
3170		 * that until he succeeds.)
3171		 */
3172		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3173		if (sb == NULL) {
3174			list->status = CTL_LUN_LIST_ERROR;
3175			snprintf(list->error_str, sizeof(list->error_str),
3176				 "Unable to allocate %d bytes for LUN list",
3177				 list->alloc_len);
3178			break;
3179		}
3180
3181		sbuf_printf(sb, "<ctllunlist>\n");
3182
3183		mtx_lock(&softc->ctl_lock);
3184		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3185			mtx_lock(&lun->lun_lock);
3186			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3187					     (uintmax_t)lun->lun);
3188
3189			/*
3190			 * Bail out as soon as we see that we've overfilled
3191			 * the buffer.
3192			 */
3193			if (retval != 0)
3194				break;
3195
3196			retval = sbuf_printf(sb, "\t<backend_type>%s"
3197					     "</backend_type>\n",
3198					     (lun->backend == NULL) ?  "none" :
3199					     lun->backend->name);
3200
3201			if (retval != 0)
3202				break;
3203
3204			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3205					     lun->be_lun->lun_type);
3206
3207			if (retval != 0)
3208				break;
3209
3210			if (lun->backend == NULL) {
3211				retval = sbuf_printf(sb, "</lun>\n");
3212				if (retval != 0)
3213					break;
3214				continue;
3215			}
3216
3217			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3218					     (lun->be_lun->maxlba > 0) ?
3219					     lun->be_lun->maxlba + 1 : 0);
3220
3221			if (retval != 0)
3222				break;
3223
3224			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3225					     lun->be_lun->blocksize);
3226
3227			if (retval != 0)
3228				break;
3229
3230			retval = sbuf_printf(sb, "\t<serial_number>");
3231
3232			if (retval != 0)
3233				break;
3234
3235			retval = ctl_sbuf_printf_esc(sb,
3236			    lun->be_lun->serial_num,
3237			    sizeof(lun->be_lun->serial_num));
3238
3239			if (retval != 0)
3240				break;
3241
3242			retval = sbuf_printf(sb, "</serial_number>\n");
3243
3244			if (retval != 0)
3245				break;
3246
3247			retval = sbuf_printf(sb, "\t<device_id>");
3248
3249			if (retval != 0)
3250				break;
3251
3252			retval = ctl_sbuf_printf_esc(sb,
3253			    lun->be_lun->device_id,
3254			    sizeof(lun->be_lun->device_id));
3255
3256			if (retval != 0)
3257				break;
3258
3259			retval = sbuf_printf(sb, "</device_id>\n");
3260
3261			if (retval != 0)
3262				break;
3263
3264			if (lun->backend->lun_info != NULL) {
3265				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3266				if (retval != 0)
3267					break;
3268			}
3269			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3270				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3271				    opt->name, opt->value, opt->name);
3272				if (retval != 0)
3273					break;
3274			}
3275
3276			retval = sbuf_printf(sb, "</lun>\n");
3277
3278			if (retval != 0)
3279				break;
3280			mtx_unlock(&lun->lun_lock);
3281		}
3282		if (lun != NULL)
3283			mtx_unlock(&lun->lun_lock);
3284		mtx_unlock(&softc->ctl_lock);
3285
3286		if ((retval != 0)
3287		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3288			retval = 0;
3289			sbuf_delete(sb);
3290			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3291			snprintf(list->error_str, sizeof(list->error_str),
3292				 "Out of space, %d bytes is too small",
3293				 list->alloc_len);
3294			break;
3295		}
3296
3297		sbuf_finish(sb);
3298
3299		retval = copyout(sbuf_data(sb), list->lun_xml,
3300				 sbuf_len(sb) + 1);
3301
3302		list->fill_len = sbuf_len(sb) + 1;
3303		list->status = CTL_LUN_LIST_OK;
3304		sbuf_delete(sb);
3305		break;
3306	}
3307	case CTL_ISCSI: {
3308		struct ctl_iscsi *ci;
3309		struct ctl_frontend *fe;
3310
3311		ci = (struct ctl_iscsi *)addr;
3312
3313		fe = ctl_frontend_find("iscsi");
3314		if (fe == NULL) {
3315			ci->status = CTL_ISCSI_ERROR;
3316			snprintf(ci->error_str, sizeof(ci->error_str),
3317			    "Frontend \"iscsi\" not found.");
3318			break;
3319		}
3320
3321		retval = fe->ioctl(dev, cmd, addr, flag, td);
3322		break;
3323	}
3324	case CTL_PORT_REQ: {
3325		struct ctl_req *req;
3326		struct ctl_frontend *fe;
3327
3328		req = (struct ctl_req *)addr;
3329
3330		fe = ctl_frontend_find(req->driver);
3331		if (fe == NULL) {
3332			req->status = CTL_LUN_ERROR;
3333			snprintf(req->error_str, sizeof(req->error_str),
3334			    "Frontend \"%s\" not found.", req->driver);
3335			break;
3336		}
3337		if (req->num_args > 0) {
3338			req->kern_args = ctl_copyin_args(req->num_args,
3339			    req->args, req->error_str, sizeof(req->error_str));
3340			if (req->kern_args == NULL) {
3341				req->status = CTL_LUN_ERROR;
3342				break;
3343			}
3344		}
3345
3346		retval = fe->ioctl(dev, cmd, addr, flag, td);
3347
3348		if (req->num_args > 0) {
3349			ctl_copyout_args(req->num_args, req->kern_args);
3350			ctl_free_args(req->num_args, req->kern_args);
3351		}
3352		break;
3353	}
3354	case CTL_PORT_LIST: {
3355		struct sbuf *sb;
3356		struct ctl_port *port;
3357		struct ctl_lun_list *list;
3358		struct ctl_option *opt;
3359		int j;
3360
3361		list = (struct ctl_lun_list *)addr;
3362
3363		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3364		if (sb == NULL) {
3365			list->status = CTL_LUN_LIST_ERROR;
3366			snprintf(list->error_str, sizeof(list->error_str),
3367				 "Unable to allocate %d bytes for LUN list",
3368				 list->alloc_len);
3369			break;
3370		}
3371
3372		sbuf_printf(sb, "<ctlportlist>\n");
3373
3374		mtx_lock(&softc->ctl_lock);
3375		STAILQ_FOREACH(port, &softc->port_list, links) {
3376			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3377					     (uintmax_t)port->targ_port);
3378
3379			/*
3380			 * Bail out as soon as we see that we've overfilled
3381			 * the buffer.
3382			 */
3383			if (retval != 0)
3384				break;
3385
3386			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3387			    "</frontend_type>\n", port->frontend->name);
3388			if (retval != 0)
3389				break;
3390
3391			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3392					     port->port_type);
3393			if (retval != 0)
3394				break;
3395
3396			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3397			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3398			if (retval != 0)
3399				break;
3400
3401			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3402			    port->port_name);
3403			if (retval != 0)
3404				break;
3405
3406			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3407			    port->physical_port);
3408			if (retval != 0)
3409				break;
3410
3411			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3412			    port->virtual_port);
3413			if (retval != 0)
3414				break;
3415
3416			if (port->target_devid != NULL) {
3417				sbuf_printf(sb, "\t<target>");
3418				ctl_id_sbuf(port->target_devid, sb);
3419				sbuf_printf(sb, "</target>\n");
3420			}
3421
3422			if (port->port_devid != NULL) {
3423				sbuf_printf(sb, "\t<port>");
3424				ctl_id_sbuf(port->port_devid, sb);
3425				sbuf_printf(sb, "</port>\n");
3426			}
3427
3428			if (port->port_info != NULL) {
3429				retval = port->port_info(port->onoff_arg, sb);
3430				if (retval != 0)
3431					break;
3432			}
3433			STAILQ_FOREACH(opt, &port->options, links) {
3434				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3435				    opt->name, opt->value, opt->name);
3436				if (retval != 0)
3437					break;
3438			}
3439
3440			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3441				if (port->wwpn_iid[j].in_use == 0 ||
3442				    (port->wwpn_iid[j].wwpn == 0 &&
3443				     port->wwpn_iid[j].name == NULL))
3444					continue;
3445
3446				if (port->wwpn_iid[j].name != NULL)
3447					retval = sbuf_printf(sb,
3448					    "\t<initiator>%u %s</initiator>\n",
3449					    j, port->wwpn_iid[j].name);
3450				else
3451					retval = sbuf_printf(sb,
3452					    "\t<initiator>%u naa.%08jx</initiator>\n",
3453					    j, port->wwpn_iid[j].wwpn);
3454				if (retval != 0)
3455					break;
3456			}
3457			if (retval != 0)
3458				break;
3459
3460			retval = sbuf_printf(sb, "</targ_port>\n");
3461			if (retval != 0)
3462				break;
3463		}
3464		mtx_unlock(&softc->ctl_lock);
3465
3466		if ((retval != 0)
3467		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3468			retval = 0;
3469			sbuf_delete(sb);
3470			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3471			snprintf(list->error_str, sizeof(list->error_str),
3472				 "Out of space, %d bytes is too small",
3473				 list->alloc_len);
3474			break;
3475		}
3476
3477		sbuf_finish(sb);
3478
3479		retval = copyout(sbuf_data(sb), list->lun_xml,
3480				 sbuf_len(sb) + 1);
3481
3482		list->fill_len = sbuf_len(sb) + 1;
3483		list->status = CTL_LUN_LIST_OK;
3484		sbuf_delete(sb);
3485		break;
3486	}
3487	default: {
3488		/* XXX KDM should we fix this? */
3489#if 0
3490		struct ctl_backend_driver *backend;
3491		unsigned int type;
3492		int found;
3493
3494		found = 0;
3495
3496		/*
3497		 * We encode the backend type as the ioctl type for backend
3498		 * ioctls.  So parse it out here, and then search for a
3499		 * backend of this type.
3500		 */
3501		type = _IOC_TYPE(cmd);
3502
3503		STAILQ_FOREACH(backend, &softc->be_list, links) {
3504			if (backend->type == type) {
3505				found = 1;
3506				break;
3507			}
3508		}
3509		if (found == 0) {
3510			printf("ctl: unknown ioctl command %#lx or backend "
3511			       "%d\n", cmd, type);
3512			retval = EINVAL;
3513			break;
3514		}
3515		retval = backend->ioctl(dev, cmd, addr, flag, td);
3516#endif
3517		retval = ENOTTY;
3518		break;
3519	}
3520	}
3521	return (retval);
3522}
3523
3524uint32_t
3525ctl_get_initindex(struct ctl_nexus *nexus)
3526{
3527	if (nexus->targ_port < CTL_MAX_PORTS)
3528		return (nexus->initid.id +
3529			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3530	else
3531		return (nexus->initid.id +
3532		       ((nexus->targ_port - CTL_MAX_PORTS) *
3533			CTL_MAX_INIT_PER_PORT));
3534}
3535
3536uint32_t
3537ctl_get_resindex(struct ctl_nexus *nexus)
3538{
3539	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3540}
3541
3542uint32_t
3543ctl_port_idx(int port_num)
3544{
3545	if (port_num < CTL_MAX_PORTS)
3546		return(port_num);
3547	else
3548		return(port_num - CTL_MAX_PORTS);
3549}
3550
3551static uint32_t
3552ctl_map_lun(int port_num, uint32_t lun_id)
3553{
3554	struct ctl_port *port;
3555
3556	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3557	if (port == NULL)
3558		return (UINT32_MAX);
3559	if (port->lun_map == NULL)
3560		return (lun_id);
3561	return (port->lun_map(port->targ_lun_arg, lun_id));
3562}
3563
3564static uint32_t
3565ctl_map_lun_back(int port_num, uint32_t lun_id)
3566{
3567	struct ctl_port *port;
3568	uint32_t i;
3569
3570	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3571	if (port->lun_map == NULL)
3572		return (lun_id);
3573	for (i = 0; i < CTL_MAX_LUNS; i++) {
3574		if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3575			return (i);
3576	}
3577	return (UINT32_MAX);
3578}
3579
3580/*
3581 * Note:  This only works for bitmask sizes that are at least 32 bits, and
3582 * that are a power of 2.
3583 */
3584int
3585ctl_ffz(uint32_t *mask, uint32_t size)
3586{
3587	uint32_t num_chunks, num_pieces;
3588	int i, j;
3589
3590	num_chunks = (size >> 5);
3591	if (num_chunks == 0)
3592		num_chunks++;
3593	num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3594
3595	for (i = 0; i < num_chunks; i++) {
3596		for (j = 0; j < num_pieces; j++) {
3597			if ((mask[i] & (1 << j)) == 0)
3598				return ((i << 5) + j);
3599		}
3600	}
3601
3602	return (-1);
3603}
3604
3605int
3606ctl_set_mask(uint32_t *mask, uint32_t bit)
3607{
3608	uint32_t chunk, piece;
3609
3610	chunk = bit >> 5;
3611	piece = bit % (sizeof(uint32_t) * 8);
3612
3613	if ((mask[chunk] & (1 << piece)) != 0)
3614		return (-1);
3615	else
3616		mask[chunk] |= (1 << piece);
3617
3618	return (0);
3619}
3620
3621int
3622ctl_clear_mask(uint32_t *mask, uint32_t bit)
3623{
3624	uint32_t chunk, piece;
3625
3626	chunk = bit >> 5;
3627	piece = bit % (sizeof(uint32_t) * 8);
3628
3629	if ((mask[chunk] & (1 << piece)) == 0)
3630		return (-1);
3631	else
3632		mask[chunk] &= ~(1 << piece);
3633
3634	return (0);
3635}
3636
3637int
3638ctl_is_set(uint32_t *mask, uint32_t bit)
3639{
3640	uint32_t chunk, piece;
3641
3642	chunk = bit >> 5;
3643	piece = bit % (sizeof(uint32_t) * 8);
3644
3645	if ((mask[chunk] & (1 << piece)) == 0)
3646		return (0);
3647	else
3648		return (1);
3649}
3650
3651#ifdef unused
3652/*
3653 * The bus, target and lun are optional, they can be filled in later.
3654 * can_wait is used to determine whether we can wait on the malloc or not.
3655 */
3656union ctl_io*
3657ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3658	      uint32_t targ_lun, int can_wait)
3659{
3660	union ctl_io *io;
3661
3662	if (can_wait)
3663		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3664	else
3665		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3666
3667	if (io != NULL) {
3668		io->io_hdr.io_type = io_type;
3669		io->io_hdr.targ_port = targ_port;
3670		/*
3671		 * XXX KDM this needs to change/go away.  We need to move
3672		 * to a preallocated pool of ctl_scsiio structures.
3673		 */
3674		io->io_hdr.nexus.targ_target.id = targ_target;
3675		io->io_hdr.nexus.targ_lun = targ_lun;
3676	}
3677
3678	return (io);
3679}
3680
3681void
3682ctl_kfree_io(union ctl_io *io)
3683{
3684	free(io, M_CTL);
3685}
3686#endif /* unused */
3687
3688/*
3689 * ctl_softc, pool_name, total_ctl_io are passed in.
3690 * npool is passed out.
3691 */
3692int
3693ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3694		uint32_t total_ctl_io, void **npool)
3695{
3696#ifdef IO_POOLS
3697	struct ctl_io_pool *pool;
3698
3699	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3700					    M_NOWAIT | M_ZERO);
3701	if (pool == NULL)
3702		return (ENOMEM);
3703
3704	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3705	pool->ctl_softc = ctl_softc;
3706	pool->zone = uma_zsecond_create(pool->name, NULL,
3707	    NULL, NULL, NULL, ctl_softc->io_zone);
3708	/* uma_prealloc(pool->zone, total_ctl_io); */
3709
3710	*npool = pool;
3711#else
3712	*npool = ctl_softc->io_zone;
3713#endif
3714	return (0);
3715}
3716
3717void
3718ctl_pool_free(struct ctl_io_pool *pool)
3719{
3720
3721	if (pool == NULL)
3722		return;
3723
3724#ifdef IO_POOLS
3725	uma_zdestroy(pool->zone);
3726	free(pool, M_CTL);
3727#endif
3728}
3729
3730union ctl_io *
3731ctl_alloc_io(void *pool_ref)
3732{
3733	union ctl_io *io;
3734#ifdef IO_POOLS
3735	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3736
3737	io = uma_zalloc(pool->zone, M_WAITOK);
3738#else
3739	io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3740#endif
3741	if (io != NULL)
3742		io->io_hdr.pool = pool_ref;
3743	return (io);
3744}
3745
3746union ctl_io *
3747ctl_alloc_io_nowait(void *pool_ref)
3748{
3749	union ctl_io *io;
3750#ifdef IO_POOLS
3751	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3752
3753	io = uma_zalloc(pool->zone, M_NOWAIT);
3754#else
3755	io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3756#endif
3757	if (io != NULL)
3758		io->io_hdr.pool = pool_ref;
3759	return (io);
3760}
3761
3762void
3763ctl_free_io(union ctl_io *io)
3764{
3765#ifdef IO_POOLS
3766	struct ctl_io_pool *pool;
3767#endif
3768
3769	if (io == NULL)
3770		return;
3771
3772#ifdef IO_POOLS
3773	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3774	uma_zfree(pool->zone, io);
3775#else
3776	uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3777#endif
3778}
3779
3780void
3781ctl_zero_io(union ctl_io *io)
3782{
3783	void *pool_ref;
3784
3785	if (io == NULL)
3786		return;
3787
3788	/*
3789	 * May need to preserve linked list pointers at some point too.
3790	 */
3791	pool_ref = io->io_hdr.pool;
3792	memset(io, 0, sizeof(*io));
3793	io->io_hdr.pool = pool_ref;
3794}
3795
3796/*
3797 * This routine is currently used for internal copies of ctl_ios that need
3798 * to persist for some reason after we've already returned status to the
3799 * FETD.  (Thus the flag set.)
3800 *
3801 * XXX XXX
3802 * Note that this makes a blind copy of all fields in the ctl_io, except
3803 * for the pool reference.  This includes any memory that has been
3804 * allocated!  That memory will no longer be valid after done has been
3805 * called, so this would be VERY DANGEROUS for command that actually does
3806 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3807 * start and stop commands, which don't transfer any data, so this is not a
3808 * problem.  If it is used for anything else, the caller would also need to
3809 * allocate data buffer space and this routine would need to be modified to
3810 * copy the data buffer(s) as well.
3811 */
3812void
3813ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3814{
3815	void *pool_ref;
3816
3817	if ((src == NULL)
3818	 || (dest == NULL))
3819		return;
3820
3821	/*
3822	 * May need to preserve linked list pointers at some point too.
3823	 */
3824	pool_ref = dest->io_hdr.pool;
3825
3826	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3827
3828	dest->io_hdr.pool = pool_ref;
3829	/*
3830	 * We need to know that this is an internal copy, and doesn't need
3831	 * to get passed back to the FETD that allocated it.
3832	 */
3833	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3834}
3835
3836static int
3837ctl_expand_number(const char *buf, uint64_t *num)
3838{
3839	char *endptr;
3840	uint64_t number;
3841	unsigned shift;
3842
3843	number = strtoq(buf, &endptr, 0);
3844
3845	switch (tolower((unsigned char)*endptr)) {
3846	case 'e':
3847		shift = 60;
3848		break;
3849	case 'p':
3850		shift = 50;
3851		break;
3852	case 't':
3853		shift = 40;
3854		break;
3855	case 'g':
3856		shift = 30;
3857		break;
3858	case 'm':
3859		shift = 20;
3860		break;
3861	case 'k':
3862		shift = 10;
3863		break;
3864	case 'b':
3865	case '\0': /* No unit. */
3866		*num = number;
3867		return (0);
3868	default:
3869		/* Unrecognized unit. */
3870		return (-1);
3871	}
3872
3873	if ((number << shift) >> shift != number) {
3874		/* Overflow */
3875		return (-1);
3876	}
3877	*num = number << shift;
3878	return (0);
3879}
3880
3881
3882/*
3883 * This routine could be used in the future to load default and/or saved
3884 * mode page parameters for a particuar lun.
3885 */
3886static int
3887ctl_init_page_index(struct ctl_lun *lun)
3888{
3889	int i;
3890	struct ctl_page_index *page_index;
3891	const char *value;
3892	uint64_t ival;
3893
3894	memcpy(&lun->mode_pages.index, page_index_template,
3895	       sizeof(page_index_template));
3896
3897	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3898
3899		page_index = &lun->mode_pages.index[i];
3900		/*
3901		 * If this is a disk-only mode page, there's no point in
3902		 * setting it up.  For some pages, we have to have some
3903		 * basic information about the disk in order to calculate the
3904		 * mode page data.
3905		 */
3906		if ((lun->be_lun->lun_type != T_DIRECT)
3907		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3908			continue;
3909
3910		switch (page_index->page_code & SMPH_PC_MASK) {
3911		case SMS_RW_ERROR_RECOVERY_PAGE: {
3912			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3913				panic("subpage is incorrect!");
3914			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3915			       &rw_er_page_default,
3916			       sizeof(rw_er_page_default));
3917			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3918			       &rw_er_page_changeable,
3919			       sizeof(rw_er_page_changeable));
3920			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3921			       &rw_er_page_default,
3922			       sizeof(rw_er_page_default));
3923			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3924			       &rw_er_page_default,
3925			       sizeof(rw_er_page_default));
3926			page_index->page_data =
3927				(uint8_t *)lun->mode_pages.rw_er_page;
3928			break;
3929		}
3930		case SMS_FORMAT_DEVICE_PAGE: {
3931			struct scsi_format_page *format_page;
3932
3933			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3934				panic("subpage is incorrect!");
3935
3936			/*
3937			 * Sectors per track are set above.  Bytes per
3938			 * sector need to be set here on a per-LUN basis.
3939			 */
3940			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3941			       &format_page_default,
3942			       sizeof(format_page_default));
3943			memcpy(&lun->mode_pages.format_page[
3944			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
3945			       sizeof(format_page_changeable));
3946			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3947			       &format_page_default,
3948			       sizeof(format_page_default));
3949			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3950			       &format_page_default,
3951			       sizeof(format_page_default));
3952
3953			format_page = &lun->mode_pages.format_page[
3954				CTL_PAGE_CURRENT];
3955			scsi_ulto2b(lun->be_lun->blocksize,
3956				    format_page->bytes_per_sector);
3957
3958			format_page = &lun->mode_pages.format_page[
3959				CTL_PAGE_DEFAULT];
3960			scsi_ulto2b(lun->be_lun->blocksize,
3961				    format_page->bytes_per_sector);
3962
3963			format_page = &lun->mode_pages.format_page[
3964				CTL_PAGE_SAVED];
3965			scsi_ulto2b(lun->be_lun->blocksize,
3966				    format_page->bytes_per_sector);
3967
3968			page_index->page_data =
3969				(uint8_t *)lun->mode_pages.format_page;
3970			break;
3971		}
3972		case SMS_RIGID_DISK_PAGE: {
3973			struct scsi_rigid_disk_page *rigid_disk_page;
3974			uint32_t sectors_per_cylinder;
3975			uint64_t cylinders;
3976#ifndef	__XSCALE__
3977			int shift;
3978#endif /* !__XSCALE__ */
3979
3980			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3981				panic("invalid subpage value %d",
3982				      page_index->subpage);
3983
3984			/*
3985			 * Rotation rate and sectors per track are set
3986			 * above.  We calculate the cylinders here based on
3987			 * capacity.  Due to the number of heads and
3988			 * sectors per track we're using, smaller arrays
3989			 * may turn out to have 0 cylinders.  Linux and
3990			 * FreeBSD don't pay attention to these mode pages
3991			 * to figure out capacity, but Solaris does.  It
3992			 * seems to deal with 0 cylinders just fine, and
3993			 * works out a fake geometry based on the capacity.
3994			 */
3995			memcpy(&lun->mode_pages.rigid_disk_page[
3996			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
3997			       sizeof(rigid_disk_page_default));
3998			memcpy(&lun->mode_pages.rigid_disk_page[
3999			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4000			       sizeof(rigid_disk_page_changeable));
4001
4002			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4003				CTL_DEFAULT_HEADS;
4004
4005			/*
4006			 * The divide method here will be more accurate,
4007			 * probably, but results in floating point being
4008			 * used in the kernel on i386 (__udivdi3()).  On the
4009			 * XScale, though, __udivdi3() is implemented in
4010			 * software.
4011			 *
4012			 * The shift method for cylinder calculation is
4013			 * accurate if sectors_per_cylinder is a power of
4014			 * 2.  Otherwise it might be slightly off -- you
4015			 * might have a bit of a truncation problem.
4016			 */
4017#ifdef	__XSCALE__
4018			cylinders = (lun->be_lun->maxlba + 1) /
4019				sectors_per_cylinder;
4020#else
4021			for (shift = 31; shift > 0; shift--) {
4022				if (sectors_per_cylinder & (1 << shift))
4023					break;
4024			}
4025			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4026#endif
4027
4028			/*
4029			 * We've basically got 3 bytes, or 24 bits for the
4030			 * cylinder size in the mode page.  If we're over,
4031			 * just round down to 2^24.
4032			 */
4033			if (cylinders > 0xffffff)
4034				cylinders = 0xffffff;
4035
4036			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4037				CTL_PAGE_DEFAULT];
4038			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4039
4040			if ((value = ctl_get_opt(&lun->be_lun->options,
4041			    "rpm")) != NULL) {
4042				scsi_ulto2b(strtol(value, NULL, 0),
4043				     rigid_disk_page->rotation_rate);
4044			}
4045
4046			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4047			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4048			       sizeof(rigid_disk_page_default));
4049			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4050			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4051			       sizeof(rigid_disk_page_default));
4052
4053			page_index->page_data =
4054				(uint8_t *)lun->mode_pages.rigid_disk_page;
4055			break;
4056		}
4057		case SMS_CACHING_PAGE: {
4058			struct scsi_caching_page *caching_page;
4059
4060			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4061				panic("invalid subpage value %d",
4062				      page_index->subpage);
4063			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4064			       &caching_page_default,
4065			       sizeof(caching_page_default));
4066			memcpy(&lun->mode_pages.caching_page[
4067			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4068			       sizeof(caching_page_changeable));
4069			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4070			       &caching_page_default,
4071			       sizeof(caching_page_default));
4072			caching_page = &lun->mode_pages.caching_page[
4073			    CTL_PAGE_SAVED];
4074			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4075			if (value != NULL && strcmp(value, "off") == 0)
4076				caching_page->flags1 &= ~SCP_WCE;
4077			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4078			if (value != NULL && strcmp(value, "off") == 0)
4079				caching_page->flags1 |= SCP_RCD;
4080			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4081			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4082			       sizeof(caching_page_default));
4083			page_index->page_data =
4084				(uint8_t *)lun->mode_pages.caching_page;
4085			break;
4086		}
4087		case SMS_CONTROL_MODE_PAGE: {
4088			struct scsi_control_page *control_page;
4089
4090			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4091				panic("invalid subpage value %d",
4092				      page_index->subpage);
4093
4094			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4095			       &control_page_default,
4096			       sizeof(control_page_default));
4097			memcpy(&lun->mode_pages.control_page[
4098			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4099			       sizeof(control_page_changeable));
4100			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4101			       &control_page_default,
4102			       sizeof(control_page_default));
4103			control_page = &lun->mode_pages.control_page[
4104			    CTL_PAGE_SAVED];
4105			value = ctl_get_opt(&lun->be_lun->options, "reordering");
4106			if (value != NULL && strcmp(value, "unrestricted") == 0) {
4107				control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4108				control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4109			}
4110			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4111			       &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4112			       sizeof(control_page_default));
4113			page_index->page_data =
4114				(uint8_t *)lun->mode_pages.control_page;
4115			break;
4116
4117		}
4118		case SMS_INFO_EXCEPTIONS_PAGE: {
4119			switch (page_index->subpage) {
4120			case SMS_SUBPAGE_PAGE_0:
4121				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4122				       &ie_page_default,
4123				       sizeof(ie_page_default));
4124				memcpy(&lun->mode_pages.ie_page[
4125				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4126				       sizeof(ie_page_changeable));
4127				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4128				       &ie_page_default,
4129				       sizeof(ie_page_default));
4130				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4131				       &ie_page_default,
4132				       sizeof(ie_page_default));
4133				page_index->page_data =
4134					(uint8_t *)lun->mode_pages.ie_page;
4135				break;
4136			case 0x02: {
4137				struct ctl_logical_block_provisioning_page *page;
4138
4139				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4140				       &lbp_page_default,
4141				       sizeof(lbp_page_default));
4142				memcpy(&lun->mode_pages.lbp_page[
4143				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4144				       sizeof(lbp_page_changeable));
4145				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4146				       &lbp_page_default,
4147				       sizeof(lbp_page_default));
4148				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4149				value = ctl_get_opt(&lun->be_lun->options,
4150				    "avail-threshold");
4151				if (value != NULL &&
4152				    ctl_expand_number(value, &ival) == 0) {
4153					page->descr[0].flags |= SLBPPD_ENABLED |
4154					    SLBPPD_ARMING_DEC;
4155					if (lun->be_lun->blocksize)
4156						ival /= lun->be_lun->blocksize;
4157					else
4158						ival /= 512;
4159					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4160					    page->descr[0].count);
4161				}
4162				value = ctl_get_opt(&lun->be_lun->options,
4163				    "used-threshold");
4164				if (value != NULL &&
4165				    ctl_expand_number(value, &ival) == 0) {
4166					page->descr[1].flags |= SLBPPD_ENABLED |
4167					    SLBPPD_ARMING_INC;
4168					if (lun->be_lun->blocksize)
4169						ival /= lun->be_lun->blocksize;
4170					else
4171						ival /= 512;
4172					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4173					    page->descr[1].count);
4174				}
4175				value = ctl_get_opt(&lun->be_lun->options,
4176				    "pool-avail-threshold");
4177				if (value != NULL &&
4178				    ctl_expand_number(value, &ival) == 0) {
4179					page->descr[2].flags |= SLBPPD_ENABLED |
4180					    SLBPPD_ARMING_DEC;
4181					if (lun->be_lun->blocksize)
4182						ival /= lun->be_lun->blocksize;
4183					else
4184						ival /= 512;
4185					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4186					    page->descr[2].count);
4187				}
4188				value = ctl_get_opt(&lun->be_lun->options,
4189				    "pool-used-threshold");
4190				if (value != NULL &&
4191				    ctl_expand_number(value, &ival) == 0) {
4192					page->descr[3].flags |= SLBPPD_ENABLED |
4193					    SLBPPD_ARMING_INC;
4194					if (lun->be_lun->blocksize)
4195						ival /= lun->be_lun->blocksize;
4196					else
4197						ival /= 512;
4198					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4199					    page->descr[3].count);
4200				}
4201				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4202				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4203				       sizeof(lbp_page_default));
4204				page_index->page_data =
4205					(uint8_t *)lun->mode_pages.lbp_page;
4206			}}
4207			break;
4208		}
4209		case SMS_VENDOR_SPECIFIC_PAGE:{
4210			switch (page_index->subpage) {
4211			case DBGCNF_SUBPAGE_CODE: {
4212				struct copan_debugconf_subpage *current_page,
4213							       *saved_page;
4214
4215				memcpy(&lun->mode_pages.debugconf_subpage[
4216				       CTL_PAGE_CURRENT],
4217				       &debugconf_page_default,
4218				       sizeof(debugconf_page_default));
4219				memcpy(&lun->mode_pages.debugconf_subpage[
4220				       CTL_PAGE_CHANGEABLE],
4221				       &debugconf_page_changeable,
4222				       sizeof(debugconf_page_changeable));
4223				memcpy(&lun->mode_pages.debugconf_subpage[
4224				       CTL_PAGE_DEFAULT],
4225				       &debugconf_page_default,
4226				       sizeof(debugconf_page_default));
4227				memcpy(&lun->mode_pages.debugconf_subpage[
4228				       CTL_PAGE_SAVED],
4229				       &debugconf_page_default,
4230				       sizeof(debugconf_page_default));
4231				page_index->page_data =
4232					(uint8_t *)lun->mode_pages.debugconf_subpage;
4233
4234				current_page = (struct copan_debugconf_subpage *)
4235					(page_index->page_data +
4236					 (page_index->page_len *
4237					  CTL_PAGE_CURRENT));
4238				saved_page = (struct copan_debugconf_subpage *)
4239					(page_index->page_data +
4240					 (page_index->page_len *
4241					  CTL_PAGE_SAVED));
4242				break;
4243			}
4244			default:
4245				panic("invalid subpage value %d",
4246				      page_index->subpage);
4247				break;
4248			}
4249   			break;
4250		}
4251		default:
4252			panic("invalid page value %d",
4253			      page_index->page_code & SMPH_PC_MASK);
4254			break;
4255    	}
4256	}
4257
4258	return (CTL_RETVAL_COMPLETE);
4259}
4260
4261static int
4262ctl_init_log_page_index(struct ctl_lun *lun)
4263{
4264	struct ctl_page_index *page_index;
4265	int i, j, k, prev;
4266
4267	memcpy(&lun->log_pages.index, log_page_index_template,
4268	       sizeof(log_page_index_template));
4269
4270	prev = -1;
4271	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4272
4273		page_index = &lun->log_pages.index[i];
4274		/*
4275		 * If this is a disk-only mode page, there's no point in
4276		 * setting it up.  For some pages, we have to have some
4277		 * basic information about the disk in order to calculate the
4278		 * mode page data.
4279		 */
4280		if ((lun->be_lun->lun_type != T_DIRECT)
4281		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4282			continue;
4283
4284		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4285		    ((lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) == 0 ||
4286		     lun->backend->lun_attr == NULL))
4287			continue;
4288
4289		if (page_index->page_code != prev) {
4290			lun->log_pages.pages_page[j] = page_index->page_code;
4291			prev = page_index->page_code;
4292			j++;
4293		}
4294		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4295		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4296		k++;
4297	}
4298	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4299	lun->log_pages.index[0].page_len = j;
4300	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4301	lun->log_pages.index[1].page_len = k * 2;
4302	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4303	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4304
4305	return (CTL_RETVAL_COMPLETE);
4306}
4307
4308static int
4309hex2bin(const char *str, uint8_t *buf, int buf_size)
4310{
4311	int i;
4312	u_char c;
4313
4314	memset(buf, 0, buf_size);
4315	while (isspace(str[0]))
4316		str++;
4317	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4318		str += 2;
4319	buf_size *= 2;
4320	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4321		c = str[i];
4322		if (isdigit(c))
4323			c -= '0';
4324		else if (isalpha(c))
4325			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4326		else
4327			break;
4328		if (c >= 16)
4329			break;
4330		if ((i & 1) == 0)
4331			buf[i / 2] |= (c << 4);
4332		else
4333			buf[i / 2] |= c;
4334	}
4335	return ((i + 1) / 2);
4336}
4337
4338/*
4339 * LUN allocation.
4340 *
4341 * Requirements:
4342 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4343 *   wants us to allocate the LUN and he can block.
4344 * - ctl_softc is always set
4345 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4346 *
4347 * Returns 0 for success, non-zero (errno) for failure.
4348 */
4349static int
4350ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4351	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4352{
4353	struct ctl_lun *nlun, *lun;
4354	struct ctl_port *port;
4355	struct scsi_vpd_id_descriptor *desc;
4356	struct scsi_vpd_id_t10 *t10id;
4357	const char *eui, *naa, *scsiname, *vendor, *value;
4358	int lun_number, i, lun_malloced;
4359	int devidlen, idlen1, idlen2 = 0, len;
4360
4361	if (be_lun == NULL)
4362		return (EINVAL);
4363
4364	/*
4365	 * We currently only support Direct Access or Processor LUN types.
4366	 */
4367	switch (be_lun->lun_type) {
4368	case T_DIRECT:
4369		break;
4370	case T_PROCESSOR:
4371		break;
4372	case T_SEQUENTIAL:
4373	case T_CHANGER:
4374	default:
4375		be_lun->lun_config_status(be_lun->be_lun,
4376					  CTL_LUN_CONFIG_FAILURE);
4377		break;
4378	}
4379	if (ctl_lun == NULL) {
4380		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4381		lun_malloced = 1;
4382	} else {
4383		lun_malloced = 0;
4384		lun = ctl_lun;
4385	}
4386
4387	memset(lun, 0, sizeof(*lun));
4388	if (lun_malloced)
4389		lun->flags = CTL_LUN_MALLOCED;
4390
4391	/* Generate LUN ID. */
4392	devidlen = max(CTL_DEVID_MIN_LEN,
4393	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4394	idlen1 = sizeof(*t10id) + devidlen;
4395	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4396	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4397	if (scsiname != NULL) {
4398		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4399		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4400	}
4401	eui = ctl_get_opt(&be_lun->options, "eui");
4402	if (eui != NULL) {
4403		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4404	}
4405	naa = ctl_get_opt(&be_lun->options, "naa");
4406	if (naa != NULL) {
4407		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4408	}
4409	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4410	    M_CTL, M_WAITOK | M_ZERO);
4411	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4412	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4413	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4414	desc->length = idlen1;
4415	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4416	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4417	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4418		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4419	} else {
4420		strncpy(t10id->vendor, vendor,
4421		    min(sizeof(t10id->vendor), strlen(vendor)));
4422	}
4423	strncpy((char *)t10id->vendor_spec_id,
4424	    (char *)be_lun->device_id, devidlen);
4425	if (scsiname != NULL) {
4426		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4427		    desc->length);
4428		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4429		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4430		    SVPD_ID_TYPE_SCSI_NAME;
4431		desc->length = idlen2;
4432		strlcpy(desc->identifier, scsiname, idlen2);
4433	}
4434	if (eui != NULL) {
4435		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4436		    desc->length);
4437		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4438		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4439		    SVPD_ID_TYPE_EUI64;
4440		desc->length = hex2bin(eui, desc->identifier, 16);
4441		desc->length = desc->length > 12 ? 16 :
4442		    (desc->length > 8 ? 12 : 8);
4443		len -= 16 - desc->length;
4444	}
4445	if (naa != NULL) {
4446		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4447		    desc->length);
4448		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4449		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4450		    SVPD_ID_TYPE_NAA;
4451		desc->length = hex2bin(naa, desc->identifier, 16);
4452		desc->length = desc->length > 8 ? 16 : 8;
4453		len -= 16 - desc->length;
4454	}
4455	lun->lun_devid->len = len;
4456
4457	mtx_lock(&ctl_softc->ctl_lock);
4458	/*
4459	 * See if the caller requested a particular LUN number.  If so, see
4460	 * if it is available.  Otherwise, allocate the first available LUN.
4461	 */
4462	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4463		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4464		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4465			mtx_unlock(&ctl_softc->ctl_lock);
4466			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4467				printf("ctl: requested LUN ID %d is higher "
4468				       "than CTL_MAX_LUNS - 1 (%d)\n",
4469				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4470			} else {
4471				/*
4472				 * XXX KDM return an error, or just assign
4473				 * another LUN ID in this case??
4474				 */
4475				printf("ctl: requested LUN ID %d is already "
4476				       "in use\n", be_lun->req_lun_id);
4477			}
4478			if (lun->flags & CTL_LUN_MALLOCED)
4479				free(lun, M_CTL);
4480			be_lun->lun_config_status(be_lun->be_lun,
4481						  CTL_LUN_CONFIG_FAILURE);
4482			return (ENOSPC);
4483		}
4484		lun_number = be_lun->req_lun_id;
4485	} else {
4486		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4487		if (lun_number == -1) {
4488			mtx_unlock(&ctl_softc->ctl_lock);
4489			printf("ctl: can't allocate LUN on target %ju, out of "
4490			       "LUNs\n", (uintmax_t)target_id.id);
4491			if (lun->flags & CTL_LUN_MALLOCED)
4492				free(lun, M_CTL);
4493			be_lun->lun_config_status(be_lun->be_lun,
4494						  CTL_LUN_CONFIG_FAILURE);
4495			return (ENOSPC);
4496		}
4497	}
4498	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4499
4500	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4501	lun->target = target_id;
4502	lun->lun = lun_number;
4503	lun->be_lun = be_lun;
4504	/*
4505	 * The processor LUN is always enabled.  Disk LUNs come on line
4506	 * disabled, and must be enabled by the backend.
4507	 */
4508	lun->flags |= CTL_LUN_DISABLED;
4509	lun->backend = be_lun->be;
4510	be_lun->ctl_lun = lun;
4511	be_lun->lun_id = lun_number;
4512	atomic_add_int(&be_lun->be->num_luns, 1);
4513	if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4514		lun->flags |= CTL_LUN_OFFLINE;
4515
4516	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4517		lun->flags |= CTL_LUN_STOPPED;
4518
4519	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4520		lun->flags |= CTL_LUN_INOPERABLE;
4521
4522	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4523		lun->flags |= CTL_LUN_PRIMARY_SC;
4524
4525	value = ctl_get_opt(&be_lun->options, "readonly");
4526	if (value != NULL && strcmp(value, "on") == 0)
4527		lun->flags |= CTL_LUN_READONLY;
4528
4529	lun->ctl_softc = ctl_softc;
4530	TAILQ_INIT(&lun->ooa_queue);
4531	TAILQ_INIT(&lun->blocked_queue);
4532	STAILQ_INIT(&lun->error_list);
4533	ctl_tpc_lun_init(lun);
4534
4535	/*
4536	 * Initialize the mode and log page index.
4537	 */
4538	ctl_init_page_index(lun);
4539	ctl_init_log_page_index(lun);
4540
4541	/*
4542	 * Set the poweron UA for all initiators on this LUN only.
4543	 */
4544	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4545		lun->pending_ua[i] = CTL_UA_POWERON;
4546
4547	/*
4548	 * Now, before we insert this lun on the lun list, set the lun
4549	 * inventory changed UA for all other luns.
4550	 */
4551	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4552		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4553			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4554		}
4555	}
4556
4557	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4558
4559	ctl_softc->ctl_luns[lun_number] = lun;
4560
4561	ctl_softc->num_luns++;
4562
4563	/* Setup statistics gathering */
4564	lun->stats.device_type = be_lun->lun_type;
4565	lun->stats.lun_number = lun_number;
4566	if (lun->stats.device_type == T_DIRECT)
4567		lun->stats.blocksize = be_lun->blocksize;
4568	else
4569		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4570	for (i = 0;i < CTL_MAX_PORTS;i++)
4571		lun->stats.ports[i].targ_port = i;
4572
4573	mtx_unlock(&ctl_softc->ctl_lock);
4574
4575	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4576
4577	/*
4578	 * Run through each registered FETD and bring it online if it isn't
4579	 * already.  Enable the target ID if it hasn't been enabled, and
4580	 * enable this particular LUN.
4581	 */
4582	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4583		int retval;
4584
4585		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4586		if (retval != 0) {
4587			printf("ctl_alloc_lun: FETD %s port %d returned error "
4588			       "%d for lun_enable on target %ju lun %d\n",
4589			       port->port_name, port->targ_port, retval,
4590			       (uintmax_t)target_id.id, lun_number);
4591		} else
4592			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4593	}
4594	return (0);
4595}
4596
4597/*
4598 * Delete a LUN.
4599 * Assumptions:
4600 * - LUN has already been marked invalid and any pending I/O has been taken
4601 *   care of.
4602 */
4603static int
4604ctl_free_lun(struct ctl_lun *lun)
4605{
4606	struct ctl_softc *softc;
4607#if 0
4608	struct ctl_port *port;
4609#endif
4610	struct ctl_lun *nlun;
4611	int i;
4612
4613	softc = lun->ctl_softc;
4614
4615	mtx_assert(&softc->ctl_lock, MA_OWNED);
4616
4617	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4618
4619	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4620
4621	softc->ctl_luns[lun->lun] = NULL;
4622
4623	if (!TAILQ_EMPTY(&lun->ooa_queue))
4624		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4625
4626	softc->num_luns--;
4627
4628	/*
4629	 * XXX KDM this scheme only works for a single target/multiple LUN
4630	 * setup.  It needs to be revamped for a multiple target scheme.
4631	 *
4632	 * XXX KDM this results in port->lun_disable() getting called twice,
4633	 * once when ctl_disable_lun() is called, and a second time here.
4634	 * We really need to re-think the LUN disable semantics.  There
4635	 * should probably be several steps/levels to LUN removal:
4636	 *  - disable
4637	 *  - invalidate
4638	 *  - free
4639 	 *
4640	 * Right now we only have a disable method when communicating to
4641	 * the front end ports, at least for individual LUNs.
4642	 */
4643#if 0
4644	STAILQ_FOREACH(port, &softc->port_list, links) {
4645		int retval;
4646
4647		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4648					 lun->lun);
4649		if (retval != 0) {
4650			printf("ctl_free_lun: FETD %s port %d returned error "
4651			       "%d for lun_disable on target %ju lun %jd\n",
4652			       port->port_name, port->targ_port, retval,
4653			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4654		}
4655
4656		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4657			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4658
4659			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4660			if (retval != 0) {
4661				printf("ctl_free_lun: FETD %s port %d "
4662				       "returned error %d for targ_disable on "
4663				       "target %ju\n", port->port_name,
4664				       port->targ_port, retval,
4665				       (uintmax_t)lun->target.id);
4666			} else
4667				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4668
4669			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4670				continue;
4671
4672#if 0
4673			port->port_offline(port->onoff_arg);
4674			port->status &= ~CTL_PORT_STATUS_ONLINE;
4675#endif
4676		}
4677	}
4678#endif
4679
4680	/*
4681	 * Tell the backend to free resources, if this LUN has a backend.
4682	 */
4683	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4684	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4685
4686	ctl_tpc_lun_shutdown(lun);
4687	mtx_destroy(&lun->lun_lock);
4688	free(lun->lun_devid, M_CTL);
4689	free(lun->write_buffer, M_CTL);
4690	if (lun->flags & CTL_LUN_MALLOCED)
4691		free(lun, M_CTL);
4692
4693	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4694		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4695			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4696		}
4697	}
4698
4699	return (0);
4700}
4701
4702static void
4703ctl_create_lun(struct ctl_be_lun *be_lun)
4704{
4705	struct ctl_softc *ctl_softc;
4706
4707	ctl_softc = control_softc;
4708
4709	/*
4710	 * ctl_alloc_lun() should handle all potential failure cases.
4711	 */
4712	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4713}
4714
4715int
4716ctl_add_lun(struct ctl_be_lun *be_lun)
4717{
4718	struct ctl_softc *ctl_softc = control_softc;
4719
4720	mtx_lock(&ctl_softc->ctl_lock);
4721	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4722	mtx_unlock(&ctl_softc->ctl_lock);
4723	wakeup(&ctl_softc->pending_lun_queue);
4724
4725	return (0);
4726}
4727
4728int
4729ctl_enable_lun(struct ctl_be_lun *be_lun)
4730{
4731	struct ctl_softc *ctl_softc;
4732	struct ctl_port *port, *nport;
4733	struct ctl_lun *lun;
4734	int retval;
4735
4736	ctl_softc = control_softc;
4737
4738	lun = (struct ctl_lun *)be_lun->ctl_lun;
4739
4740	mtx_lock(&ctl_softc->ctl_lock);
4741	mtx_lock(&lun->lun_lock);
4742	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4743		/*
4744		 * eh?  Why did we get called if the LUN is already
4745		 * enabled?
4746		 */
4747		mtx_unlock(&lun->lun_lock);
4748		mtx_unlock(&ctl_softc->ctl_lock);
4749		return (0);
4750	}
4751	lun->flags &= ~CTL_LUN_DISABLED;
4752	mtx_unlock(&lun->lun_lock);
4753
4754	for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4755		nport = STAILQ_NEXT(port, links);
4756
4757		/*
4758		 * Drop the lock while we call the FETD's enable routine.
4759		 * This can lead to a callback into CTL (at least in the
4760		 * case of the internal initiator frontend.
4761		 */
4762		mtx_unlock(&ctl_softc->ctl_lock);
4763		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4764		mtx_lock(&ctl_softc->ctl_lock);
4765		if (retval != 0) {
4766			printf("%s: FETD %s port %d returned error "
4767			       "%d for lun_enable on target %ju lun %jd\n",
4768			       __func__, port->port_name, port->targ_port, retval,
4769			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4770		}
4771#if 0
4772		 else {
4773            /* NOTE:  TODO:  why does lun enable affect port status? */
4774			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4775		}
4776#endif
4777	}
4778
4779	mtx_unlock(&ctl_softc->ctl_lock);
4780
4781	return (0);
4782}
4783
4784int
4785ctl_disable_lun(struct ctl_be_lun *be_lun)
4786{
4787	struct ctl_softc *ctl_softc;
4788	struct ctl_port *port;
4789	struct ctl_lun *lun;
4790	int retval;
4791
4792	ctl_softc = control_softc;
4793
4794	lun = (struct ctl_lun *)be_lun->ctl_lun;
4795
4796	mtx_lock(&ctl_softc->ctl_lock);
4797	mtx_lock(&lun->lun_lock);
4798	if (lun->flags & CTL_LUN_DISABLED) {
4799		mtx_unlock(&lun->lun_lock);
4800		mtx_unlock(&ctl_softc->ctl_lock);
4801		return (0);
4802	}
4803	lun->flags |= CTL_LUN_DISABLED;
4804	mtx_unlock(&lun->lun_lock);
4805
4806	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4807		mtx_unlock(&ctl_softc->ctl_lock);
4808		/*
4809		 * Drop the lock before we call the frontend's disable
4810		 * routine, to avoid lock order reversals.
4811		 *
4812		 * XXX KDM what happens if the frontend list changes while
4813		 * we're traversing it?  It's unlikely, but should be handled.
4814		 */
4815		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4816					 lun->lun);
4817		mtx_lock(&ctl_softc->ctl_lock);
4818		if (retval != 0) {
4819			printf("ctl_alloc_lun: FETD %s port %d returned error "
4820			       "%d for lun_disable on target %ju lun %jd\n",
4821			       port->port_name, port->targ_port, retval,
4822			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4823		}
4824	}
4825
4826	mtx_unlock(&ctl_softc->ctl_lock);
4827
4828	return (0);
4829}
4830
4831int
4832ctl_start_lun(struct ctl_be_lun *be_lun)
4833{
4834	struct ctl_softc *ctl_softc;
4835	struct ctl_lun *lun;
4836
4837	ctl_softc = control_softc;
4838
4839	lun = (struct ctl_lun *)be_lun->ctl_lun;
4840
4841	mtx_lock(&lun->lun_lock);
4842	lun->flags &= ~CTL_LUN_STOPPED;
4843	mtx_unlock(&lun->lun_lock);
4844
4845	return (0);
4846}
4847
4848int
4849ctl_stop_lun(struct ctl_be_lun *be_lun)
4850{
4851	struct ctl_softc *ctl_softc;
4852	struct ctl_lun *lun;
4853
4854	ctl_softc = control_softc;
4855
4856	lun = (struct ctl_lun *)be_lun->ctl_lun;
4857
4858	mtx_lock(&lun->lun_lock);
4859	lun->flags |= CTL_LUN_STOPPED;
4860	mtx_unlock(&lun->lun_lock);
4861
4862	return (0);
4863}
4864
4865int
4866ctl_lun_offline(struct ctl_be_lun *be_lun)
4867{
4868	struct ctl_softc *ctl_softc;
4869	struct ctl_lun *lun;
4870
4871	ctl_softc = control_softc;
4872
4873	lun = (struct ctl_lun *)be_lun->ctl_lun;
4874
4875	mtx_lock(&lun->lun_lock);
4876	lun->flags |= CTL_LUN_OFFLINE;
4877	mtx_unlock(&lun->lun_lock);
4878
4879	return (0);
4880}
4881
4882int
4883ctl_lun_online(struct ctl_be_lun *be_lun)
4884{
4885	struct ctl_softc *ctl_softc;
4886	struct ctl_lun *lun;
4887
4888	ctl_softc = control_softc;
4889
4890	lun = (struct ctl_lun *)be_lun->ctl_lun;
4891
4892	mtx_lock(&lun->lun_lock);
4893	lun->flags &= ~CTL_LUN_OFFLINE;
4894	mtx_unlock(&lun->lun_lock);
4895
4896	return (0);
4897}
4898
4899int
4900ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4901{
4902	struct ctl_softc *ctl_softc;
4903	struct ctl_lun *lun;
4904
4905	ctl_softc = control_softc;
4906
4907	lun = (struct ctl_lun *)be_lun->ctl_lun;
4908
4909	mtx_lock(&lun->lun_lock);
4910
4911	/*
4912	 * The LUN needs to be disabled before it can be marked invalid.
4913	 */
4914	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4915		mtx_unlock(&lun->lun_lock);
4916		return (-1);
4917	}
4918	/*
4919	 * Mark the LUN invalid.
4920	 */
4921	lun->flags |= CTL_LUN_INVALID;
4922
4923	/*
4924	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4925	 * If we have something in the OOA queue, we'll free it when the
4926	 * last I/O completes.
4927	 */
4928	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4929		mtx_unlock(&lun->lun_lock);
4930		mtx_lock(&ctl_softc->ctl_lock);
4931		ctl_free_lun(lun);
4932		mtx_unlock(&ctl_softc->ctl_lock);
4933	} else
4934		mtx_unlock(&lun->lun_lock);
4935
4936	return (0);
4937}
4938
4939int
4940ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4941{
4942	struct ctl_softc *ctl_softc;
4943	struct ctl_lun *lun;
4944
4945	ctl_softc = control_softc;
4946	lun = (struct ctl_lun *)be_lun->ctl_lun;
4947
4948	mtx_lock(&lun->lun_lock);
4949	lun->flags |= CTL_LUN_INOPERABLE;
4950	mtx_unlock(&lun->lun_lock);
4951
4952	return (0);
4953}
4954
4955int
4956ctl_lun_operable(struct ctl_be_lun *be_lun)
4957{
4958	struct ctl_softc *ctl_softc;
4959	struct ctl_lun *lun;
4960
4961	ctl_softc = control_softc;
4962	lun = (struct ctl_lun *)be_lun->ctl_lun;
4963
4964	mtx_lock(&lun->lun_lock);
4965	lun->flags &= ~CTL_LUN_INOPERABLE;
4966	mtx_unlock(&lun->lun_lock);
4967
4968	return (0);
4969}
4970
4971void
4972ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4973{
4974	struct ctl_lun *lun;
4975	struct ctl_softc *softc;
4976	int i;
4977
4978	softc = control_softc;
4979
4980	lun = (struct ctl_lun *)be_lun->ctl_lun;
4981
4982	mtx_lock(&lun->lun_lock);
4983
4984	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4985		lun->pending_ua[i] |= CTL_UA_CAPACITY_CHANGED;
4986
4987	mtx_unlock(&lun->lun_lock);
4988}
4989
4990/*
4991 * Backend "memory move is complete" callback for requests that never
4992 * make it down to say RAIDCore's configuration code.
4993 */
4994int
4995ctl_config_move_done(union ctl_io *io)
4996{
4997	int retval;
4998
4999	retval = CTL_RETVAL_COMPLETE;
5000
5001
5002	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5003	/*
5004	 * XXX KDM this shouldn't happen, but what if it does?
5005	 */
5006	if (io->io_hdr.io_type != CTL_IO_SCSI)
5007		panic("I/O type isn't CTL_IO_SCSI!");
5008
5009	if ((io->io_hdr.port_status == 0)
5010	 && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5011	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
5012		io->io_hdr.status = CTL_SUCCESS;
5013	else if ((io->io_hdr.port_status != 0)
5014	      && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5015	      && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
5016		/*
5017		 * For hardware error sense keys, the sense key
5018		 * specific value is defined to be a retry count,
5019		 * but we use it to pass back an internal FETD
5020		 * error code.  XXX KDM  Hopefully the FETD is only
5021		 * using 16 bits for an error code, since that's
5022		 * all the space we have in the sks field.
5023		 */
5024		ctl_set_internal_failure(&io->scsiio,
5025					 /*sks_valid*/ 1,
5026					 /*retry_count*/
5027					 io->io_hdr.port_status);
5028		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5029			free(io->scsiio.kern_data_ptr, M_CTL);
5030		ctl_done(io);
5031		goto bailout;
5032	}
5033
5034	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
5035	 || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
5036	 || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5037		/*
5038		 * XXX KDM just assuming a single pointer here, and not a
5039		 * S/G list.  If we start using S/G lists for config data,
5040		 * we'll need to know how to clean them up here as well.
5041		 */
5042		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5043			free(io->scsiio.kern_data_ptr, M_CTL);
5044		/* Hopefully the user has already set the status... */
5045		ctl_done(io);
5046	} else {
5047		/*
5048		 * XXX KDM now we need to continue data movement.  Some
5049		 * options:
5050		 * - call ctl_scsiio() again?  We don't do this for data
5051		 *   writes, because for those at least we know ahead of
5052		 *   time where the write will go and how long it is.  For
5053		 *   config writes, though, that information is largely
5054		 *   contained within the write itself, thus we need to
5055		 *   parse out the data again.
5056		 *
5057		 * - Call some other function once the data is in?
5058		 */
5059		if (ctl_debug & CTL_DEBUG_CDB_DATA)
5060			ctl_data_print(io);
5061
5062		/*
5063		 * XXX KDM call ctl_scsiio() again for now, and check flag
5064		 * bits to see whether we're allocated or not.
5065		 */
5066		retval = ctl_scsiio(&io->scsiio);
5067	}
5068bailout:
5069	return (retval);
5070}
5071
5072/*
5073 * This gets called by a backend driver when it is done with a
5074 * data_submit method.
5075 */
5076void
5077ctl_data_submit_done(union ctl_io *io)
5078{
5079	/*
5080	 * If the IO_CONT flag is set, we need to call the supplied
5081	 * function to continue processing the I/O, instead of completing
5082	 * the I/O just yet.
5083	 *
5084	 * If there is an error, though, we don't want to keep processing.
5085	 * Instead, just send status back to the initiator.
5086	 */
5087	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5088	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5089	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5090	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5091		io->scsiio.io_cont(io);
5092		return;
5093	}
5094	ctl_done(io);
5095}
5096
5097/*
5098 * This gets called by a backend driver when it is done with a
5099 * configuration write.
5100 */
5101void
5102ctl_config_write_done(union ctl_io *io)
5103{
5104	uint8_t *buf;
5105
5106	/*
5107	 * If the IO_CONT flag is set, we need to call the supplied
5108	 * function to continue processing the I/O, instead of completing
5109	 * the I/O just yet.
5110	 *
5111	 * If there is an error, though, we don't want to keep processing.
5112	 * Instead, just send status back to the initiator.
5113	 */
5114	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5115	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5116	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5117	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5118		io->scsiio.io_cont(io);
5119		return;
5120	}
5121	/*
5122	 * Since a configuration write can be done for commands that actually
5123	 * have data allocated, like write buffer, and commands that have
5124	 * no data, like start/stop unit, we need to check here.
5125	 */
5126	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5127		buf = io->scsiio.kern_data_ptr;
5128	else
5129		buf = NULL;
5130	ctl_done(io);
5131	if (buf)
5132		free(buf, M_CTL);
5133}
5134
5135/*
5136 * SCSI release command.
5137 */
5138int
5139ctl_scsi_release(struct ctl_scsiio *ctsio)
5140{
5141	int length, longid, thirdparty_id, resv_id;
5142	struct ctl_softc *ctl_softc;
5143	struct ctl_lun *lun;
5144	uint32_t residx;
5145
5146	length = 0;
5147	resv_id = 0;
5148
5149	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5150
5151	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5152	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5153	ctl_softc = control_softc;
5154
5155	switch (ctsio->cdb[0]) {
5156	case RELEASE_10: {
5157		struct scsi_release_10 *cdb;
5158
5159		cdb = (struct scsi_release_10 *)ctsio->cdb;
5160
5161		if (cdb->byte2 & SR10_LONGID)
5162			longid = 1;
5163		else
5164			thirdparty_id = cdb->thirdparty_id;
5165
5166		resv_id = cdb->resv_id;
5167		length = scsi_2btoul(cdb->length);
5168		break;
5169	}
5170	}
5171
5172
5173	/*
5174	 * XXX KDM right now, we only support LUN reservation.  We don't
5175	 * support 3rd party reservations, or extent reservations, which
5176	 * might actually need the parameter list.  If we've gotten this
5177	 * far, we've got a LUN reservation.  Anything else got kicked out
5178	 * above.  So, according to SPC, ignore the length.
5179	 */
5180	length = 0;
5181
5182	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5183	 && (length > 0)) {
5184		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5185		ctsio->kern_data_len = length;
5186		ctsio->kern_total_len = length;
5187		ctsio->kern_data_resid = 0;
5188		ctsio->kern_rel_offset = 0;
5189		ctsio->kern_sg_entries = 0;
5190		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5191		ctsio->be_move_done = ctl_config_move_done;
5192		ctl_datamove((union ctl_io *)ctsio);
5193
5194		return (CTL_RETVAL_COMPLETE);
5195	}
5196
5197	if (length > 0)
5198		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5199
5200	mtx_lock(&lun->lun_lock);
5201
5202	/*
5203	 * According to SPC, it is not an error for an intiator to attempt
5204	 * to release a reservation on a LUN that isn't reserved, or that
5205	 * is reserved by another initiator.  The reservation can only be
5206	 * released, though, by the initiator who made it or by one of
5207	 * several reset type events.
5208	 */
5209	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5210			lun->flags &= ~CTL_LUN_RESERVED;
5211
5212	mtx_unlock(&lun->lun_lock);
5213
5214	ctl_set_success(ctsio);
5215
5216	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5217		free(ctsio->kern_data_ptr, M_CTL);
5218		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5219	}
5220
5221	ctl_done((union ctl_io *)ctsio);
5222	return (CTL_RETVAL_COMPLETE);
5223}
5224
5225int
5226ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5227{
5228	int extent, thirdparty, longid;
5229	int resv_id, length;
5230	uint64_t thirdparty_id;
5231	struct ctl_softc *ctl_softc;
5232	struct ctl_lun *lun;
5233	uint32_t residx;
5234
5235	extent = 0;
5236	thirdparty = 0;
5237	longid = 0;
5238	resv_id = 0;
5239	length = 0;
5240	thirdparty_id = 0;
5241
5242	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5243
5244	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5245	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5246	ctl_softc = control_softc;
5247
5248	switch (ctsio->cdb[0]) {
5249	case RESERVE_10: {
5250		struct scsi_reserve_10 *cdb;
5251
5252		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5253
5254		if (cdb->byte2 & SR10_LONGID)
5255			longid = 1;
5256		else
5257			thirdparty_id = cdb->thirdparty_id;
5258
5259		resv_id = cdb->resv_id;
5260		length = scsi_2btoul(cdb->length);
5261		break;
5262	}
5263	}
5264
5265	/*
5266	 * XXX KDM right now, we only support LUN reservation.  We don't
5267	 * support 3rd party reservations, or extent reservations, which
5268	 * might actually need the parameter list.  If we've gotten this
5269	 * far, we've got a LUN reservation.  Anything else got kicked out
5270	 * above.  So, according to SPC, ignore the length.
5271	 */
5272	length = 0;
5273
5274	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5275	 && (length > 0)) {
5276		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5277		ctsio->kern_data_len = length;
5278		ctsio->kern_total_len = length;
5279		ctsio->kern_data_resid = 0;
5280		ctsio->kern_rel_offset = 0;
5281		ctsio->kern_sg_entries = 0;
5282		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5283		ctsio->be_move_done = ctl_config_move_done;
5284		ctl_datamove((union ctl_io *)ctsio);
5285
5286		return (CTL_RETVAL_COMPLETE);
5287	}
5288
5289	if (length > 0)
5290		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5291
5292	mtx_lock(&lun->lun_lock);
5293	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5294		ctl_set_reservation_conflict(ctsio);
5295		goto bailout;
5296	}
5297
5298	lun->flags |= CTL_LUN_RESERVED;
5299	lun->res_idx = residx;
5300
5301	ctl_set_success(ctsio);
5302
5303bailout:
5304	mtx_unlock(&lun->lun_lock);
5305
5306	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5307		free(ctsio->kern_data_ptr, M_CTL);
5308		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5309	}
5310
5311	ctl_done((union ctl_io *)ctsio);
5312	return (CTL_RETVAL_COMPLETE);
5313}
5314
5315int
5316ctl_start_stop(struct ctl_scsiio *ctsio)
5317{
5318	struct scsi_start_stop_unit *cdb;
5319	struct ctl_lun *lun;
5320	struct ctl_softc *ctl_softc;
5321	int retval;
5322
5323	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5324
5325	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5326	ctl_softc = control_softc;
5327	retval = 0;
5328
5329	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5330
5331	/*
5332	 * XXX KDM
5333	 * We don't support the immediate bit on a stop unit.  In order to
5334	 * do that, we would need to code up a way to know that a stop is
5335	 * pending, and hold off any new commands until it completes, one
5336	 * way or another.  Then we could accept or reject those commands
5337	 * depending on its status.  We would almost need to do the reverse
5338	 * of what we do below for an immediate start -- return the copy of
5339	 * the ctl_io to the FETD with status to send to the host (and to
5340	 * free the copy!) and then free the original I/O once the stop
5341	 * actually completes.  That way, the OOA queue mechanism can work
5342	 * to block commands that shouldn't proceed.  Another alternative
5343	 * would be to put the copy in the queue in place of the original,
5344	 * and return the original back to the caller.  That could be
5345	 * slightly safer..
5346	 */
5347	if ((cdb->byte2 & SSS_IMMED)
5348	 && ((cdb->how & SSS_START) == 0)) {
5349		ctl_set_invalid_field(ctsio,
5350				      /*sks_valid*/ 1,
5351				      /*command*/ 1,
5352				      /*field*/ 1,
5353				      /*bit_valid*/ 1,
5354				      /*bit*/ 0);
5355		ctl_done((union ctl_io *)ctsio);
5356		return (CTL_RETVAL_COMPLETE);
5357	}
5358
5359	if ((lun->flags & CTL_LUN_PR_RESERVED)
5360	 && ((cdb->how & SSS_START)==0)) {
5361		uint32_t residx;
5362
5363		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5364		if (lun->pr_keys[residx] == 0
5365		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5366
5367			ctl_set_reservation_conflict(ctsio);
5368			ctl_done((union ctl_io *)ctsio);
5369			return (CTL_RETVAL_COMPLETE);
5370		}
5371	}
5372
5373	/*
5374	 * If there is no backend on this device, we can't start or stop
5375	 * it.  In theory we shouldn't get any start/stop commands in the
5376	 * first place at this level if the LUN doesn't have a backend.
5377	 * That should get stopped by the command decode code.
5378	 */
5379	if (lun->backend == NULL) {
5380		ctl_set_invalid_opcode(ctsio);
5381		ctl_done((union ctl_io *)ctsio);
5382		return (CTL_RETVAL_COMPLETE);
5383	}
5384
5385	/*
5386	 * XXX KDM Copan-specific offline behavior.
5387	 * Figure out a reasonable way to port this?
5388	 */
5389#ifdef NEEDTOPORT
5390	mtx_lock(&lun->lun_lock);
5391
5392	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5393	 && (lun->flags & CTL_LUN_OFFLINE)) {
5394		/*
5395		 * If the LUN is offline, and the on/offline bit isn't set,
5396		 * reject the start or stop.  Otherwise, let it through.
5397		 */
5398		mtx_unlock(&lun->lun_lock);
5399		ctl_set_lun_not_ready(ctsio);
5400		ctl_done((union ctl_io *)ctsio);
5401	} else {
5402		mtx_unlock(&lun->lun_lock);
5403#endif /* NEEDTOPORT */
5404		/*
5405		 * This could be a start or a stop when we're online,
5406		 * or a stop/offline or start/online.  A start or stop when
5407		 * we're offline is covered in the case above.
5408		 */
5409		/*
5410		 * In the non-immediate case, we send the request to
5411		 * the backend and return status to the user when
5412		 * it is done.
5413		 *
5414		 * In the immediate case, we allocate a new ctl_io
5415		 * to hold a copy of the request, and send that to
5416		 * the backend.  We then set good status on the
5417		 * user's request and return it immediately.
5418		 */
5419		if (cdb->byte2 & SSS_IMMED) {
5420			union ctl_io *new_io;
5421
5422			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5423			ctl_copy_io((union ctl_io *)ctsio, new_io);
5424			retval = lun->backend->config_write(new_io);
5425			ctl_set_success(ctsio);
5426			ctl_done((union ctl_io *)ctsio);
5427		} else {
5428			retval = lun->backend->config_write(
5429				(union ctl_io *)ctsio);
5430		}
5431#ifdef NEEDTOPORT
5432	}
5433#endif
5434	return (retval);
5435}
5436
5437/*
5438 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5439 * we don't really do anything with the LBA and length fields if the user
5440 * passes them in.  Instead we'll just flush out the cache for the entire
5441 * LUN.
5442 */
5443int
5444ctl_sync_cache(struct ctl_scsiio *ctsio)
5445{
5446	struct ctl_lun *lun;
5447	struct ctl_softc *ctl_softc;
5448	uint64_t starting_lba;
5449	uint32_t block_count;
5450	int retval;
5451
5452	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5453
5454	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5455	ctl_softc = control_softc;
5456	retval = 0;
5457
5458	switch (ctsio->cdb[0]) {
5459	case SYNCHRONIZE_CACHE: {
5460		struct scsi_sync_cache *cdb;
5461		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5462
5463		starting_lba = scsi_4btoul(cdb->begin_lba);
5464		block_count = scsi_2btoul(cdb->lb_count);
5465		break;
5466	}
5467	case SYNCHRONIZE_CACHE_16: {
5468		struct scsi_sync_cache_16 *cdb;
5469		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5470
5471		starting_lba = scsi_8btou64(cdb->begin_lba);
5472		block_count = scsi_4btoul(cdb->lb_count);
5473		break;
5474	}
5475	default:
5476		ctl_set_invalid_opcode(ctsio);
5477		ctl_done((union ctl_io *)ctsio);
5478		goto bailout;
5479		break; /* NOTREACHED */
5480	}
5481
5482	/*
5483	 * We check the LBA and length, but don't do anything with them.
5484	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5485	 * get flushed.  This check will just help satisfy anyone who wants
5486	 * to see an error for an out of range LBA.
5487	 */
5488	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5489		ctl_set_lba_out_of_range(ctsio);
5490		ctl_done((union ctl_io *)ctsio);
5491		goto bailout;
5492	}
5493
5494	/*
5495	 * If this LUN has no backend, we can't flush the cache anyway.
5496	 */
5497	if (lun->backend == NULL) {
5498		ctl_set_invalid_opcode(ctsio);
5499		ctl_done((union ctl_io *)ctsio);
5500		goto bailout;
5501	}
5502
5503	/*
5504	 * Check to see whether we're configured to send the SYNCHRONIZE
5505	 * CACHE command directly to the back end.
5506	 */
5507	mtx_lock(&lun->lun_lock);
5508	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5509	 && (++(lun->sync_count) >= lun->sync_interval)) {
5510		lun->sync_count = 0;
5511		mtx_unlock(&lun->lun_lock);
5512		retval = lun->backend->config_write((union ctl_io *)ctsio);
5513	} else {
5514		mtx_unlock(&lun->lun_lock);
5515		ctl_set_success(ctsio);
5516		ctl_done((union ctl_io *)ctsio);
5517	}
5518
5519bailout:
5520
5521	return (retval);
5522}
5523
5524int
5525ctl_format(struct ctl_scsiio *ctsio)
5526{
5527	struct scsi_format *cdb;
5528	struct ctl_lun *lun;
5529	struct ctl_softc *ctl_softc;
5530	int length, defect_list_len;
5531
5532	CTL_DEBUG_PRINT(("ctl_format\n"));
5533
5534	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5535	ctl_softc = control_softc;
5536
5537	cdb = (struct scsi_format *)ctsio->cdb;
5538
5539	length = 0;
5540	if (cdb->byte2 & SF_FMTDATA) {
5541		if (cdb->byte2 & SF_LONGLIST)
5542			length = sizeof(struct scsi_format_header_long);
5543		else
5544			length = sizeof(struct scsi_format_header_short);
5545	}
5546
5547	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5548	 && (length > 0)) {
5549		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5550		ctsio->kern_data_len = length;
5551		ctsio->kern_total_len = length;
5552		ctsio->kern_data_resid = 0;
5553		ctsio->kern_rel_offset = 0;
5554		ctsio->kern_sg_entries = 0;
5555		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5556		ctsio->be_move_done = ctl_config_move_done;
5557		ctl_datamove((union ctl_io *)ctsio);
5558
5559		return (CTL_RETVAL_COMPLETE);
5560	}
5561
5562	defect_list_len = 0;
5563
5564	if (cdb->byte2 & SF_FMTDATA) {
5565		if (cdb->byte2 & SF_LONGLIST) {
5566			struct scsi_format_header_long *header;
5567
5568			header = (struct scsi_format_header_long *)
5569				ctsio->kern_data_ptr;
5570
5571			defect_list_len = scsi_4btoul(header->defect_list_len);
5572			if (defect_list_len != 0) {
5573				ctl_set_invalid_field(ctsio,
5574						      /*sks_valid*/ 1,
5575						      /*command*/ 0,
5576						      /*field*/ 2,
5577						      /*bit_valid*/ 0,
5578						      /*bit*/ 0);
5579				goto bailout;
5580			}
5581		} else {
5582			struct scsi_format_header_short *header;
5583
5584			header = (struct scsi_format_header_short *)
5585				ctsio->kern_data_ptr;
5586
5587			defect_list_len = scsi_2btoul(header->defect_list_len);
5588			if (defect_list_len != 0) {
5589				ctl_set_invalid_field(ctsio,
5590						      /*sks_valid*/ 1,
5591						      /*command*/ 0,
5592						      /*field*/ 2,
5593						      /*bit_valid*/ 0,
5594						      /*bit*/ 0);
5595				goto bailout;
5596			}
5597		}
5598	}
5599
5600	/*
5601	 * The format command will clear out the "Medium format corrupted"
5602	 * status if set by the configuration code.  That status is really
5603	 * just a way to notify the host that we have lost the media, and
5604	 * get them to issue a command that will basically make them think
5605	 * they're blowing away the media.
5606	 */
5607	mtx_lock(&lun->lun_lock);
5608	lun->flags &= ~CTL_LUN_INOPERABLE;
5609	mtx_unlock(&lun->lun_lock);
5610
5611	ctl_set_success(ctsio);
5612bailout:
5613
5614	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5615		free(ctsio->kern_data_ptr, M_CTL);
5616		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5617	}
5618
5619	ctl_done((union ctl_io *)ctsio);
5620	return (CTL_RETVAL_COMPLETE);
5621}
5622
5623int
5624ctl_read_buffer(struct ctl_scsiio *ctsio)
5625{
5626	struct scsi_read_buffer *cdb;
5627	struct ctl_lun *lun;
5628	int buffer_offset, len;
5629	static uint8_t descr[4];
5630	static uint8_t echo_descr[4] = { 0 };
5631
5632	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5633
5634	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5635	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5636
5637	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5638	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5639	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5640		ctl_set_invalid_field(ctsio,
5641				      /*sks_valid*/ 1,
5642				      /*command*/ 1,
5643				      /*field*/ 1,
5644				      /*bit_valid*/ 1,
5645				      /*bit*/ 4);
5646		ctl_done((union ctl_io *)ctsio);
5647		return (CTL_RETVAL_COMPLETE);
5648	}
5649
5650	len = scsi_3btoul(cdb->length);
5651	buffer_offset = scsi_3btoul(cdb->offset);
5652
5653	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5654		ctl_set_invalid_field(ctsio,
5655				      /*sks_valid*/ 1,
5656				      /*command*/ 1,
5657				      /*field*/ 6,
5658				      /*bit_valid*/ 0,
5659				      /*bit*/ 0);
5660		ctl_done((union ctl_io *)ctsio);
5661		return (CTL_RETVAL_COMPLETE);
5662	}
5663
5664	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5665		descr[0] = 0;
5666		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5667		ctsio->kern_data_ptr = descr;
5668		len = min(len, sizeof(descr));
5669	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5670		ctsio->kern_data_ptr = echo_descr;
5671		len = min(len, sizeof(echo_descr));
5672	} else {
5673		if (lun->write_buffer == NULL) {
5674			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5675			    M_CTL, M_WAITOK);
5676		}
5677		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5678	}
5679	ctsio->kern_data_len = len;
5680	ctsio->kern_total_len = len;
5681	ctsio->kern_data_resid = 0;
5682	ctsio->kern_rel_offset = 0;
5683	ctsio->kern_sg_entries = 0;
5684	ctsio->be_move_done = ctl_config_move_done;
5685	ctl_datamove((union ctl_io *)ctsio);
5686
5687	return (CTL_RETVAL_COMPLETE);
5688}
5689
5690int
5691ctl_write_buffer(struct ctl_scsiio *ctsio)
5692{
5693	struct scsi_write_buffer *cdb;
5694	struct ctl_lun *lun;
5695	int buffer_offset, len;
5696
5697	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5698
5699	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5700	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5701
5702	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5703		ctl_set_invalid_field(ctsio,
5704				      /*sks_valid*/ 1,
5705				      /*command*/ 1,
5706				      /*field*/ 1,
5707				      /*bit_valid*/ 1,
5708				      /*bit*/ 4);
5709		ctl_done((union ctl_io *)ctsio);
5710		return (CTL_RETVAL_COMPLETE);
5711	}
5712
5713	len = scsi_3btoul(cdb->length);
5714	buffer_offset = scsi_3btoul(cdb->offset);
5715
5716	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5717		ctl_set_invalid_field(ctsio,
5718				      /*sks_valid*/ 1,
5719				      /*command*/ 1,
5720				      /*field*/ 6,
5721				      /*bit_valid*/ 0,
5722				      /*bit*/ 0);
5723		ctl_done((union ctl_io *)ctsio);
5724		return (CTL_RETVAL_COMPLETE);
5725	}
5726
5727	/*
5728	 * If we've got a kernel request that hasn't been malloced yet,
5729	 * malloc it and tell the caller the data buffer is here.
5730	 */
5731	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5732		if (lun->write_buffer == NULL) {
5733			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5734			    M_CTL, M_WAITOK);
5735		}
5736		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5737		ctsio->kern_data_len = len;
5738		ctsio->kern_total_len = len;
5739		ctsio->kern_data_resid = 0;
5740		ctsio->kern_rel_offset = 0;
5741		ctsio->kern_sg_entries = 0;
5742		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5743		ctsio->be_move_done = ctl_config_move_done;
5744		ctl_datamove((union ctl_io *)ctsio);
5745
5746		return (CTL_RETVAL_COMPLETE);
5747	}
5748
5749	ctl_done((union ctl_io *)ctsio);
5750
5751	return (CTL_RETVAL_COMPLETE);
5752}
5753
5754int
5755ctl_write_same(struct ctl_scsiio *ctsio)
5756{
5757	struct ctl_lun *lun;
5758	struct ctl_lba_len_flags *lbalen;
5759	uint64_t lba;
5760	uint32_t num_blocks;
5761	int len, retval;
5762	uint8_t byte2;
5763
5764	retval = CTL_RETVAL_COMPLETE;
5765
5766	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5767
5768	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5769
5770	switch (ctsio->cdb[0]) {
5771	case WRITE_SAME_10: {
5772		struct scsi_write_same_10 *cdb;
5773
5774		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5775
5776		lba = scsi_4btoul(cdb->addr);
5777		num_blocks = scsi_2btoul(cdb->length);
5778		byte2 = cdb->byte2;
5779		break;
5780	}
5781	case WRITE_SAME_16: {
5782		struct scsi_write_same_16 *cdb;
5783
5784		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5785
5786		lba = scsi_8btou64(cdb->addr);
5787		num_blocks = scsi_4btoul(cdb->length);
5788		byte2 = cdb->byte2;
5789		break;
5790	}
5791	default:
5792		/*
5793		 * We got a command we don't support.  This shouldn't
5794		 * happen, commands should be filtered out above us.
5795		 */
5796		ctl_set_invalid_opcode(ctsio);
5797		ctl_done((union ctl_io *)ctsio);
5798
5799		return (CTL_RETVAL_COMPLETE);
5800		break; /* NOTREACHED */
5801	}
5802
5803	/* NDOB and ANCHOR flags can be used only together with UNMAP */
5804	if ((byte2 & SWS_UNMAP) == 0 &&
5805	    (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5806		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5807		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5808		ctl_done((union ctl_io *)ctsio);
5809		return (CTL_RETVAL_COMPLETE);
5810	}
5811
5812	/*
5813	 * The first check is to make sure we're in bounds, the second
5814	 * check is to catch wrap-around problems.  If the lba + num blocks
5815	 * is less than the lba, then we've wrapped around and the block
5816	 * range is invalid anyway.
5817	 */
5818	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5819	 || ((lba + num_blocks) < lba)) {
5820		ctl_set_lba_out_of_range(ctsio);
5821		ctl_done((union ctl_io *)ctsio);
5822		return (CTL_RETVAL_COMPLETE);
5823	}
5824
5825	/* Zero number of blocks means "to the last logical block" */
5826	if (num_blocks == 0) {
5827		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5828			ctl_set_invalid_field(ctsio,
5829					      /*sks_valid*/ 0,
5830					      /*command*/ 1,
5831					      /*field*/ 0,
5832					      /*bit_valid*/ 0,
5833					      /*bit*/ 0);
5834			ctl_done((union ctl_io *)ctsio);
5835			return (CTL_RETVAL_COMPLETE);
5836		}
5837		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5838	}
5839
5840	len = lun->be_lun->blocksize;
5841
5842	/*
5843	 * If we've got a kernel request that hasn't been malloced yet,
5844	 * malloc it and tell the caller the data buffer is here.
5845	 */
5846	if ((byte2 & SWS_NDOB) == 0 &&
5847	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5848		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5849		ctsio->kern_data_len = len;
5850		ctsio->kern_total_len = len;
5851		ctsio->kern_data_resid = 0;
5852		ctsio->kern_rel_offset = 0;
5853		ctsio->kern_sg_entries = 0;
5854		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5855		ctsio->be_move_done = ctl_config_move_done;
5856		ctl_datamove((union ctl_io *)ctsio);
5857
5858		return (CTL_RETVAL_COMPLETE);
5859	}
5860
5861	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5862	lbalen->lba = lba;
5863	lbalen->len = num_blocks;
5864	lbalen->flags = byte2;
5865	retval = lun->backend->config_write((union ctl_io *)ctsio);
5866
5867	return (retval);
5868}
5869
5870int
5871ctl_unmap(struct ctl_scsiio *ctsio)
5872{
5873	struct ctl_lun *lun;
5874	struct scsi_unmap *cdb;
5875	struct ctl_ptr_len_flags *ptrlen;
5876	struct scsi_unmap_header *hdr;
5877	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5878	uint64_t lba;
5879	uint32_t num_blocks;
5880	int len, retval;
5881	uint8_t byte2;
5882
5883	retval = CTL_RETVAL_COMPLETE;
5884
5885	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5886
5887	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5888	cdb = (struct scsi_unmap *)ctsio->cdb;
5889
5890	len = scsi_2btoul(cdb->length);
5891	byte2 = cdb->byte2;
5892
5893	/*
5894	 * If we've got a kernel request that hasn't been malloced yet,
5895	 * malloc it and tell the caller the data buffer is here.
5896	 */
5897	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5898		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5899		ctsio->kern_data_len = len;
5900		ctsio->kern_total_len = len;
5901		ctsio->kern_data_resid = 0;
5902		ctsio->kern_rel_offset = 0;
5903		ctsio->kern_sg_entries = 0;
5904		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5905		ctsio->be_move_done = ctl_config_move_done;
5906		ctl_datamove((union ctl_io *)ctsio);
5907
5908		return (CTL_RETVAL_COMPLETE);
5909	}
5910
5911	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5912	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5913	if (len < sizeof (*hdr) ||
5914	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5915	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5916	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5917		ctl_set_invalid_field(ctsio,
5918				      /*sks_valid*/ 0,
5919				      /*command*/ 0,
5920				      /*field*/ 0,
5921				      /*bit_valid*/ 0,
5922				      /*bit*/ 0);
5923		ctl_done((union ctl_io *)ctsio);
5924		return (CTL_RETVAL_COMPLETE);
5925	}
5926	len = scsi_2btoul(hdr->desc_length);
5927	buf = (struct scsi_unmap_desc *)(hdr + 1);
5928	end = buf + len / sizeof(*buf);
5929
5930	endnz = buf;
5931	for (range = buf; range < end; range++) {
5932		lba = scsi_8btou64(range->lba);
5933		num_blocks = scsi_4btoul(range->length);
5934		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5935		 || ((lba + num_blocks) < lba)) {
5936			ctl_set_lba_out_of_range(ctsio);
5937			ctl_done((union ctl_io *)ctsio);
5938			return (CTL_RETVAL_COMPLETE);
5939		}
5940		if (num_blocks != 0)
5941			endnz = range + 1;
5942	}
5943
5944	/*
5945	 * Block backend can not handle zero last range.
5946	 * Filter it out and return if there is nothing left.
5947	 */
5948	len = (uint8_t *)endnz - (uint8_t *)buf;
5949	if (len == 0) {
5950		ctl_set_success(ctsio);
5951		ctl_done((union ctl_io *)ctsio);
5952		return (CTL_RETVAL_COMPLETE);
5953	}
5954
5955	mtx_lock(&lun->lun_lock);
5956	ptrlen = (struct ctl_ptr_len_flags *)
5957	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5958	ptrlen->ptr = (void *)buf;
5959	ptrlen->len = len;
5960	ptrlen->flags = byte2;
5961	ctl_check_blocked(lun);
5962	mtx_unlock(&lun->lun_lock);
5963
5964	retval = lun->backend->config_write((union ctl_io *)ctsio);
5965	return (retval);
5966}
5967
5968/*
5969 * Note that this function currently doesn't actually do anything inside
5970 * CTL to enforce things if the DQue bit is turned on.
5971 *
5972 * Also note that this function can't be used in the default case, because
5973 * the DQue bit isn't set in the changeable mask for the control mode page
5974 * anyway.  This is just here as an example for how to implement a page
5975 * handler, and a placeholder in case we want to allow the user to turn
5976 * tagged queueing on and off.
5977 *
5978 * The D_SENSE bit handling is functional, however, and will turn
5979 * descriptor sense on and off for a given LUN.
5980 */
5981int
5982ctl_control_page_handler(struct ctl_scsiio *ctsio,
5983			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5984{
5985	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5986	struct ctl_lun *lun;
5987	struct ctl_softc *softc;
5988	int set_ua;
5989	uint32_t initidx;
5990
5991	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5992	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5993	set_ua = 0;
5994
5995	user_cp = (struct scsi_control_page *)page_ptr;
5996	current_cp = (struct scsi_control_page *)
5997		(page_index->page_data + (page_index->page_len *
5998		CTL_PAGE_CURRENT));
5999	saved_cp = (struct scsi_control_page *)
6000		(page_index->page_data + (page_index->page_len *
6001		CTL_PAGE_SAVED));
6002
6003	softc = control_softc;
6004
6005	mtx_lock(&lun->lun_lock);
6006	if (((current_cp->rlec & SCP_DSENSE) == 0)
6007	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6008		/*
6009		 * Descriptor sense is currently turned off and the user
6010		 * wants to turn it on.
6011		 */
6012		current_cp->rlec |= SCP_DSENSE;
6013		saved_cp->rlec |= SCP_DSENSE;
6014		lun->flags |= CTL_LUN_SENSE_DESC;
6015		set_ua = 1;
6016	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6017		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6018		/*
6019		 * Descriptor sense is currently turned on, and the user
6020		 * wants to turn it off.
6021		 */
6022		current_cp->rlec &= ~SCP_DSENSE;
6023		saved_cp->rlec &= ~SCP_DSENSE;
6024		lun->flags &= ~CTL_LUN_SENSE_DESC;
6025		set_ua = 1;
6026	}
6027	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6028	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6029		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6030		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6031		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6032		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6033		set_ua = 1;
6034	}
6035	if ((current_cp->eca_and_aen & SCP_SWP) !=
6036	    (user_cp->eca_and_aen & SCP_SWP)) {
6037		current_cp->eca_and_aen &= ~SCP_SWP;
6038		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6039		saved_cp->eca_and_aen &= ~SCP_SWP;
6040		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6041		set_ua = 1;
6042	}
6043	if (set_ua != 0) {
6044		int i;
6045		/*
6046		 * Let other initiators know that the mode
6047		 * parameters for this LUN have changed.
6048		 */
6049		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6050			if (i == initidx)
6051				continue;
6052
6053			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6054		}
6055	}
6056	mtx_unlock(&lun->lun_lock);
6057
6058	return (0);
6059}
6060
6061int
6062ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6063		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6064{
6065	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6066	struct ctl_lun *lun;
6067	int set_ua;
6068	uint32_t initidx;
6069
6070	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6071	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6072	set_ua = 0;
6073
6074	user_cp = (struct scsi_caching_page *)page_ptr;
6075	current_cp = (struct scsi_caching_page *)
6076		(page_index->page_data + (page_index->page_len *
6077		CTL_PAGE_CURRENT));
6078	saved_cp = (struct scsi_caching_page *)
6079		(page_index->page_data + (page_index->page_len *
6080		CTL_PAGE_SAVED));
6081
6082	mtx_lock(&lun->lun_lock);
6083	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6084	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6085		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6086		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6087		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6088		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6089		set_ua = 1;
6090	}
6091	if (set_ua != 0) {
6092		int i;
6093		/*
6094		 * Let other initiators know that the mode
6095		 * parameters for this LUN have changed.
6096		 */
6097		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6098			if (i == initidx)
6099				continue;
6100
6101			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6102		}
6103	}
6104	mtx_unlock(&lun->lun_lock);
6105
6106	return (0);
6107}
6108
6109int
6110ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6111				struct ctl_page_index *page_index,
6112				uint8_t *page_ptr)
6113{
6114	uint8_t *c;
6115	int i;
6116
6117	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6118	ctl_time_io_secs =
6119		(c[0] << 8) |
6120		(c[1] << 0) |
6121		0;
6122	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6123	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6124	printf("page data:");
6125	for (i=0; i<8; i++)
6126		printf(" %.2x",page_ptr[i]);
6127	printf("\n");
6128	return (0);
6129}
6130
6131int
6132ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6133			       struct ctl_page_index *page_index,
6134			       int pc)
6135{
6136	struct copan_debugconf_subpage *page;
6137
6138	page = (struct copan_debugconf_subpage *)page_index->page_data +
6139		(page_index->page_len * pc);
6140
6141	switch (pc) {
6142	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6143	case SMS_PAGE_CTRL_DEFAULT >> 6:
6144	case SMS_PAGE_CTRL_SAVED >> 6:
6145		/*
6146		 * We don't update the changable or default bits for this page.
6147		 */
6148		break;
6149	case SMS_PAGE_CTRL_CURRENT >> 6:
6150		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6151		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6152		break;
6153	default:
6154#ifdef NEEDTOPORT
6155		EPRINT(0, "Invalid PC %d!!", pc);
6156#endif /* NEEDTOPORT */
6157		break;
6158	}
6159	return (0);
6160}
6161
6162
6163static int
6164ctl_do_mode_select(union ctl_io *io)
6165{
6166	struct scsi_mode_page_header *page_header;
6167	struct ctl_page_index *page_index;
6168	struct ctl_scsiio *ctsio;
6169	int control_dev, page_len;
6170	int page_len_offset, page_len_size;
6171	union ctl_modepage_info *modepage_info;
6172	struct ctl_lun *lun;
6173	int *len_left, *len_used;
6174	int retval, i;
6175
6176	ctsio = &io->scsiio;
6177	page_index = NULL;
6178	page_len = 0;
6179	retval = CTL_RETVAL_COMPLETE;
6180
6181	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6182
6183	if (lun->be_lun->lun_type != T_DIRECT)
6184		control_dev = 1;
6185	else
6186		control_dev = 0;
6187
6188	modepage_info = (union ctl_modepage_info *)
6189		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6190	len_left = &modepage_info->header.len_left;
6191	len_used = &modepage_info->header.len_used;
6192
6193do_next_page:
6194
6195	page_header = (struct scsi_mode_page_header *)
6196		(ctsio->kern_data_ptr + *len_used);
6197
6198	if (*len_left == 0) {
6199		free(ctsio->kern_data_ptr, M_CTL);
6200		ctl_set_success(ctsio);
6201		ctl_done((union ctl_io *)ctsio);
6202		return (CTL_RETVAL_COMPLETE);
6203	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6204
6205		free(ctsio->kern_data_ptr, M_CTL);
6206		ctl_set_param_len_error(ctsio);
6207		ctl_done((union ctl_io *)ctsio);
6208		return (CTL_RETVAL_COMPLETE);
6209
6210	} else if ((page_header->page_code & SMPH_SPF)
6211		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6212
6213		free(ctsio->kern_data_ptr, M_CTL);
6214		ctl_set_param_len_error(ctsio);
6215		ctl_done((union ctl_io *)ctsio);
6216		return (CTL_RETVAL_COMPLETE);
6217	}
6218
6219
6220	/*
6221	 * XXX KDM should we do something with the block descriptor?
6222	 */
6223	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6224
6225		if ((control_dev != 0)
6226		 && (lun->mode_pages.index[i].page_flags &
6227		     CTL_PAGE_FLAG_DISK_ONLY))
6228			continue;
6229
6230		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6231		    (page_header->page_code & SMPH_PC_MASK))
6232			continue;
6233
6234		/*
6235		 * If neither page has a subpage code, then we've got a
6236		 * match.
6237		 */
6238		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6239		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6240			page_index = &lun->mode_pages.index[i];
6241			page_len = page_header->page_length;
6242			break;
6243		}
6244
6245		/*
6246		 * If both pages have subpages, then the subpage numbers
6247		 * have to match.
6248		 */
6249		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6250		  && (page_header->page_code & SMPH_SPF)) {
6251			struct scsi_mode_page_header_sp *sph;
6252
6253			sph = (struct scsi_mode_page_header_sp *)page_header;
6254
6255			if (lun->mode_pages.index[i].subpage ==
6256			    sph->subpage) {
6257				page_index = &lun->mode_pages.index[i];
6258				page_len = scsi_2btoul(sph->page_length);
6259				break;
6260			}
6261		}
6262	}
6263
6264	/*
6265	 * If we couldn't find the page, or if we don't have a mode select
6266	 * handler for it, send back an error to the user.
6267	 */
6268	if ((page_index == NULL)
6269	 || (page_index->select_handler == NULL)) {
6270		ctl_set_invalid_field(ctsio,
6271				      /*sks_valid*/ 1,
6272				      /*command*/ 0,
6273				      /*field*/ *len_used,
6274				      /*bit_valid*/ 0,
6275				      /*bit*/ 0);
6276		free(ctsio->kern_data_ptr, M_CTL);
6277		ctl_done((union ctl_io *)ctsio);
6278		return (CTL_RETVAL_COMPLETE);
6279	}
6280
6281	if (page_index->page_code & SMPH_SPF) {
6282		page_len_offset = 2;
6283		page_len_size = 2;
6284	} else {
6285		page_len_size = 1;
6286		page_len_offset = 1;
6287	}
6288
6289	/*
6290	 * If the length the initiator gives us isn't the one we specify in
6291	 * the mode page header, or if they didn't specify enough data in
6292	 * the CDB to avoid truncating this page, kick out the request.
6293	 */
6294	if ((page_len != (page_index->page_len - page_len_offset -
6295			  page_len_size))
6296	 || (*len_left < page_index->page_len)) {
6297
6298
6299		ctl_set_invalid_field(ctsio,
6300				      /*sks_valid*/ 1,
6301				      /*command*/ 0,
6302				      /*field*/ *len_used + page_len_offset,
6303				      /*bit_valid*/ 0,
6304				      /*bit*/ 0);
6305		free(ctsio->kern_data_ptr, M_CTL);
6306		ctl_done((union ctl_io *)ctsio);
6307		return (CTL_RETVAL_COMPLETE);
6308	}
6309
6310	/*
6311	 * Run through the mode page, checking to make sure that the bits
6312	 * the user changed are actually legal for him to change.
6313	 */
6314	for (i = 0; i < page_index->page_len; i++) {
6315		uint8_t *user_byte, *change_mask, *current_byte;
6316		int bad_bit;
6317		int j;
6318
6319		user_byte = (uint8_t *)page_header + i;
6320		change_mask = page_index->page_data +
6321			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6322		current_byte = page_index->page_data +
6323			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6324
6325		/*
6326		 * Check to see whether the user set any bits in this byte
6327		 * that he is not allowed to set.
6328		 */
6329		if ((*user_byte & ~(*change_mask)) ==
6330		    (*current_byte & ~(*change_mask)))
6331			continue;
6332
6333		/*
6334		 * Go through bit by bit to determine which one is illegal.
6335		 */
6336		bad_bit = 0;
6337		for (j = 7; j >= 0; j--) {
6338			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6339			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6340				bad_bit = i;
6341				break;
6342			}
6343		}
6344		ctl_set_invalid_field(ctsio,
6345				      /*sks_valid*/ 1,
6346				      /*command*/ 0,
6347				      /*field*/ *len_used + i,
6348				      /*bit_valid*/ 1,
6349				      /*bit*/ bad_bit);
6350		free(ctsio->kern_data_ptr, M_CTL);
6351		ctl_done((union ctl_io *)ctsio);
6352		return (CTL_RETVAL_COMPLETE);
6353	}
6354
6355	/*
6356	 * Decrement these before we call the page handler, since we may
6357	 * end up getting called back one way or another before the handler
6358	 * returns to this context.
6359	 */
6360	*len_left -= page_index->page_len;
6361	*len_used += page_index->page_len;
6362
6363	retval = page_index->select_handler(ctsio, page_index,
6364					    (uint8_t *)page_header);
6365
6366	/*
6367	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6368	 * wait until this queued command completes to finish processing
6369	 * the mode page.  If it returns anything other than
6370	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6371	 * already set the sense information, freed the data pointer, and
6372	 * completed the io for us.
6373	 */
6374	if (retval != CTL_RETVAL_COMPLETE)
6375		goto bailout_no_done;
6376
6377	/*
6378	 * If the initiator sent us more than one page, parse the next one.
6379	 */
6380	if (*len_left > 0)
6381		goto do_next_page;
6382
6383	ctl_set_success(ctsio);
6384	free(ctsio->kern_data_ptr, M_CTL);
6385	ctl_done((union ctl_io *)ctsio);
6386
6387bailout_no_done:
6388
6389	return (CTL_RETVAL_COMPLETE);
6390
6391}
6392
6393int
6394ctl_mode_select(struct ctl_scsiio *ctsio)
6395{
6396	int param_len, pf, sp;
6397	int header_size, bd_len;
6398	int len_left, len_used;
6399	struct ctl_page_index *page_index;
6400	struct ctl_lun *lun;
6401	int control_dev, page_len;
6402	union ctl_modepage_info *modepage_info;
6403	int retval;
6404
6405	pf = 0;
6406	sp = 0;
6407	page_len = 0;
6408	len_used = 0;
6409	len_left = 0;
6410	retval = 0;
6411	bd_len = 0;
6412	page_index = NULL;
6413
6414	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6415
6416	if (lun->be_lun->lun_type != T_DIRECT)
6417		control_dev = 1;
6418	else
6419		control_dev = 0;
6420
6421	switch (ctsio->cdb[0]) {
6422	case MODE_SELECT_6: {
6423		struct scsi_mode_select_6 *cdb;
6424
6425		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6426
6427		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6428		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6429
6430		param_len = cdb->length;
6431		header_size = sizeof(struct scsi_mode_header_6);
6432		break;
6433	}
6434	case MODE_SELECT_10: {
6435		struct scsi_mode_select_10 *cdb;
6436
6437		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6438
6439		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6440		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6441
6442		param_len = scsi_2btoul(cdb->length);
6443		header_size = sizeof(struct scsi_mode_header_10);
6444		break;
6445	}
6446	default:
6447		ctl_set_invalid_opcode(ctsio);
6448		ctl_done((union ctl_io *)ctsio);
6449		return (CTL_RETVAL_COMPLETE);
6450		break; /* NOTREACHED */
6451	}
6452
6453	/*
6454	 * From SPC-3:
6455	 * "A parameter list length of zero indicates that the Data-Out Buffer
6456	 * shall be empty. This condition shall not be considered as an error."
6457	 */
6458	if (param_len == 0) {
6459		ctl_set_success(ctsio);
6460		ctl_done((union ctl_io *)ctsio);
6461		return (CTL_RETVAL_COMPLETE);
6462	}
6463
6464	/*
6465	 * Since we'll hit this the first time through, prior to
6466	 * allocation, we don't need to free a data buffer here.
6467	 */
6468	if (param_len < header_size) {
6469		ctl_set_param_len_error(ctsio);
6470		ctl_done((union ctl_io *)ctsio);
6471		return (CTL_RETVAL_COMPLETE);
6472	}
6473
6474	/*
6475	 * Allocate the data buffer and grab the user's data.  In theory,
6476	 * we shouldn't have to sanity check the parameter list length here
6477	 * because the maximum size is 64K.  We should be able to malloc
6478	 * that much without too many problems.
6479	 */
6480	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6481		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6482		ctsio->kern_data_len = param_len;
6483		ctsio->kern_total_len = param_len;
6484		ctsio->kern_data_resid = 0;
6485		ctsio->kern_rel_offset = 0;
6486		ctsio->kern_sg_entries = 0;
6487		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6488		ctsio->be_move_done = ctl_config_move_done;
6489		ctl_datamove((union ctl_io *)ctsio);
6490
6491		return (CTL_RETVAL_COMPLETE);
6492	}
6493
6494	switch (ctsio->cdb[0]) {
6495	case MODE_SELECT_6: {
6496		struct scsi_mode_header_6 *mh6;
6497
6498		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6499		bd_len = mh6->blk_desc_len;
6500		break;
6501	}
6502	case MODE_SELECT_10: {
6503		struct scsi_mode_header_10 *mh10;
6504
6505		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6506		bd_len = scsi_2btoul(mh10->blk_desc_len);
6507		break;
6508	}
6509	default:
6510		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6511		break;
6512	}
6513
6514	if (param_len < (header_size + bd_len)) {
6515		free(ctsio->kern_data_ptr, M_CTL);
6516		ctl_set_param_len_error(ctsio);
6517		ctl_done((union ctl_io *)ctsio);
6518		return (CTL_RETVAL_COMPLETE);
6519	}
6520
6521	/*
6522	 * Set the IO_CONT flag, so that if this I/O gets passed to
6523	 * ctl_config_write_done(), it'll get passed back to
6524	 * ctl_do_mode_select() for further processing, or completion if
6525	 * we're all done.
6526	 */
6527	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6528	ctsio->io_cont = ctl_do_mode_select;
6529
6530	modepage_info = (union ctl_modepage_info *)
6531		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6532
6533	memset(modepage_info, 0, sizeof(*modepage_info));
6534
6535	len_left = param_len - header_size - bd_len;
6536	len_used = header_size + bd_len;
6537
6538	modepage_info->header.len_left = len_left;
6539	modepage_info->header.len_used = len_used;
6540
6541	return (ctl_do_mode_select((union ctl_io *)ctsio));
6542}
6543
6544int
6545ctl_mode_sense(struct ctl_scsiio *ctsio)
6546{
6547	struct ctl_lun *lun;
6548	int pc, page_code, dbd, llba, subpage;
6549	int alloc_len, page_len, header_len, total_len;
6550	struct scsi_mode_block_descr *block_desc;
6551	struct ctl_page_index *page_index;
6552	int control_dev;
6553
6554	dbd = 0;
6555	llba = 0;
6556	block_desc = NULL;
6557	page_index = NULL;
6558
6559	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6560
6561	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6562
6563	if (lun->be_lun->lun_type != T_DIRECT)
6564		control_dev = 1;
6565	else
6566		control_dev = 0;
6567
6568	switch (ctsio->cdb[0]) {
6569	case MODE_SENSE_6: {
6570		struct scsi_mode_sense_6 *cdb;
6571
6572		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6573
6574		header_len = sizeof(struct scsi_mode_hdr_6);
6575		if (cdb->byte2 & SMS_DBD)
6576			dbd = 1;
6577		else
6578			header_len += sizeof(struct scsi_mode_block_descr);
6579
6580		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6581		page_code = cdb->page & SMS_PAGE_CODE;
6582		subpage = cdb->subpage;
6583		alloc_len = cdb->length;
6584		break;
6585	}
6586	case MODE_SENSE_10: {
6587		struct scsi_mode_sense_10 *cdb;
6588
6589		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6590
6591		header_len = sizeof(struct scsi_mode_hdr_10);
6592
6593		if (cdb->byte2 & SMS_DBD)
6594			dbd = 1;
6595		else
6596			header_len += sizeof(struct scsi_mode_block_descr);
6597		if (cdb->byte2 & SMS10_LLBAA)
6598			llba = 1;
6599		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6600		page_code = cdb->page & SMS_PAGE_CODE;
6601		subpage = cdb->subpage;
6602		alloc_len = scsi_2btoul(cdb->length);
6603		break;
6604	}
6605	default:
6606		ctl_set_invalid_opcode(ctsio);
6607		ctl_done((union ctl_io *)ctsio);
6608		return (CTL_RETVAL_COMPLETE);
6609		break; /* NOTREACHED */
6610	}
6611
6612	/*
6613	 * We have to make a first pass through to calculate the size of
6614	 * the pages that match the user's query.  Then we allocate enough
6615	 * memory to hold it, and actually copy the data into the buffer.
6616	 */
6617	switch (page_code) {
6618	case SMS_ALL_PAGES_PAGE: {
6619		int i;
6620
6621		page_len = 0;
6622
6623		/*
6624		 * At the moment, values other than 0 and 0xff here are
6625		 * reserved according to SPC-3.
6626		 */
6627		if ((subpage != SMS_SUBPAGE_PAGE_0)
6628		 && (subpage != SMS_SUBPAGE_ALL)) {
6629			ctl_set_invalid_field(ctsio,
6630					      /*sks_valid*/ 1,
6631					      /*command*/ 1,
6632					      /*field*/ 3,
6633					      /*bit_valid*/ 0,
6634					      /*bit*/ 0);
6635			ctl_done((union ctl_io *)ctsio);
6636			return (CTL_RETVAL_COMPLETE);
6637		}
6638
6639		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6640			if ((control_dev != 0)
6641			 && (lun->mode_pages.index[i].page_flags &
6642			     CTL_PAGE_FLAG_DISK_ONLY))
6643				continue;
6644
6645			/*
6646			 * We don't use this subpage if the user didn't
6647			 * request all subpages.
6648			 */
6649			if ((lun->mode_pages.index[i].subpage != 0)
6650			 && (subpage == SMS_SUBPAGE_PAGE_0))
6651				continue;
6652
6653#if 0
6654			printf("found page %#x len %d\n",
6655			       lun->mode_pages.index[i].page_code &
6656			       SMPH_PC_MASK,
6657			       lun->mode_pages.index[i].page_len);
6658#endif
6659			page_len += lun->mode_pages.index[i].page_len;
6660		}
6661		break;
6662	}
6663	default: {
6664		int i;
6665
6666		page_len = 0;
6667
6668		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6669			/* Look for the right page code */
6670			if ((lun->mode_pages.index[i].page_code &
6671			     SMPH_PC_MASK) != page_code)
6672				continue;
6673
6674			/* Look for the right subpage or the subpage wildcard*/
6675			if ((lun->mode_pages.index[i].subpage != subpage)
6676			 && (subpage != SMS_SUBPAGE_ALL))
6677				continue;
6678
6679			/* Make sure the page is supported for this dev type */
6680			if ((control_dev != 0)
6681			 && (lun->mode_pages.index[i].page_flags &
6682			     CTL_PAGE_FLAG_DISK_ONLY))
6683				continue;
6684
6685#if 0
6686			printf("found page %#x len %d\n",
6687			       lun->mode_pages.index[i].page_code &
6688			       SMPH_PC_MASK,
6689			       lun->mode_pages.index[i].page_len);
6690#endif
6691
6692			page_len += lun->mode_pages.index[i].page_len;
6693		}
6694
6695		if (page_len == 0) {
6696			ctl_set_invalid_field(ctsio,
6697					      /*sks_valid*/ 1,
6698					      /*command*/ 1,
6699					      /*field*/ 2,
6700					      /*bit_valid*/ 1,
6701					      /*bit*/ 5);
6702			ctl_done((union ctl_io *)ctsio);
6703			return (CTL_RETVAL_COMPLETE);
6704		}
6705		break;
6706	}
6707	}
6708
6709	total_len = header_len + page_len;
6710#if 0
6711	printf("header_len = %d, page_len = %d, total_len = %d\n",
6712	       header_len, page_len, total_len);
6713#endif
6714
6715	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6716	ctsio->kern_sg_entries = 0;
6717	ctsio->kern_data_resid = 0;
6718	ctsio->kern_rel_offset = 0;
6719	if (total_len < alloc_len) {
6720		ctsio->residual = alloc_len - total_len;
6721		ctsio->kern_data_len = total_len;
6722		ctsio->kern_total_len = total_len;
6723	} else {
6724		ctsio->residual = 0;
6725		ctsio->kern_data_len = alloc_len;
6726		ctsio->kern_total_len = alloc_len;
6727	}
6728
6729	switch (ctsio->cdb[0]) {
6730	case MODE_SENSE_6: {
6731		struct scsi_mode_hdr_6 *header;
6732
6733		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6734
6735		header->datalen = ctl_min(total_len - 1, 254);
6736		if (control_dev == 0) {
6737			header->dev_specific = 0x10; /* DPOFUA */
6738			if ((lun->flags & CTL_LUN_READONLY) ||
6739			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6740			    .eca_and_aen & SCP_SWP) != 0)
6741				    header->dev_specific |= 0x80; /* WP */
6742		}
6743		if (dbd)
6744			header->block_descr_len = 0;
6745		else
6746			header->block_descr_len =
6747				sizeof(struct scsi_mode_block_descr);
6748		block_desc = (struct scsi_mode_block_descr *)&header[1];
6749		break;
6750	}
6751	case MODE_SENSE_10: {
6752		struct scsi_mode_hdr_10 *header;
6753		int datalen;
6754
6755		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6756
6757		datalen = ctl_min(total_len - 2, 65533);
6758		scsi_ulto2b(datalen, header->datalen);
6759		if (control_dev == 0) {
6760			header->dev_specific = 0x10; /* DPOFUA */
6761			if ((lun->flags & CTL_LUN_READONLY) ||
6762			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6763			    .eca_and_aen & SCP_SWP) != 0)
6764				    header->dev_specific |= 0x80; /* WP */
6765		}
6766		if (dbd)
6767			scsi_ulto2b(0, header->block_descr_len);
6768		else
6769			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6770				    header->block_descr_len);
6771		block_desc = (struct scsi_mode_block_descr *)&header[1];
6772		break;
6773	}
6774	default:
6775		panic("invalid CDB type %#x", ctsio->cdb[0]);
6776		break; /* NOTREACHED */
6777	}
6778
6779	/*
6780	 * If we've got a disk, use its blocksize in the block
6781	 * descriptor.  Otherwise, just set it to 0.
6782	 */
6783	if (dbd == 0) {
6784		if (control_dev == 0)
6785			scsi_ulto3b(lun->be_lun->blocksize,
6786				    block_desc->block_len);
6787		else
6788			scsi_ulto3b(0, block_desc->block_len);
6789	}
6790
6791	switch (page_code) {
6792	case SMS_ALL_PAGES_PAGE: {
6793		int i, data_used;
6794
6795		data_used = header_len;
6796		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6797			struct ctl_page_index *page_index;
6798
6799			page_index = &lun->mode_pages.index[i];
6800
6801			if ((control_dev != 0)
6802			 && (page_index->page_flags &
6803			    CTL_PAGE_FLAG_DISK_ONLY))
6804				continue;
6805
6806			/*
6807			 * We don't use this subpage if the user didn't
6808			 * request all subpages.  We already checked (above)
6809			 * to make sure the user only specified a subpage
6810			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6811			 */
6812			if ((page_index->subpage != 0)
6813			 && (subpage == SMS_SUBPAGE_PAGE_0))
6814				continue;
6815
6816			/*
6817			 * Call the handler, if it exists, to update the
6818			 * page to the latest values.
6819			 */
6820			if (page_index->sense_handler != NULL)
6821				page_index->sense_handler(ctsio, page_index,pc);
6822
6823			memcpy(ctsio->kern_data_ptr + data_used,
6824			       page_index->page_data +
6825			       (page_index->page_len * pc),
6826			       page_index->page_len);
6827			data_used += page_index->page_len;
6828		}
6829		break;
6830	}
6831	default: {
6832		int i, data_used;
6833
6834		data_used = header_len;
6835
6836		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6837			struct ctl_page_index *page_index;
6838
6839			page_index = &lun->mode_pages.index[i];
6840
6841			/* Look for the right page code */
6842			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6843				continue;
6844
6845			/* Look for the right subpage or the subpage wildcard*/
6846			if ((page_index->subpage != subpage)
6847			 && (subpage != SMS_SUBPAGE_ALL))
6848				continue;
6849
6850			/* Make sure the page is supported for this dev type */
6851			if ((control_dev != 0)
6852			 && (page_index->page_flags &
6853			     CTL_PAGE_FLAG_DISK_ONLY))
6854				continue;
6855
6856			/*
6857			 * Call the handler, if it exists, to update the
6858			 * page to the latest values.
6859			 */
6860			if (page_index->sense_handler != NULL)
6861				page_index->sense_handler(ctsio, page_index,pc);
6862
6863			memcpy(ctsio->kern_data_ptr + data_used,
6864			       page_index->page_data +
6865			       (page_index->page_len * pc),
6866			       page_index->page_len);
6867			data_used += page_index->page_len;
6868		}
6869		break;
6870	}
6871	}
6872
6873	ctsio->scsi_status = SCSI_STATUS_OK;
6874
6875	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6876	ctsio->be_move_done = ctl_config_move_done;
6877	ctl_datamove((union ctl_io *)ctsio);
6878
6879	return (CTL_RETVAL_COMPLETE);
6880}
6881
6882int
6883ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6884			       struct ctl_page_index *page_index,
6885			       int pc)
6886{
6887	struct ctl_lun *lun;
6888	struct scsi_log_param_header *phdr;
6889	uint8_t *data;
6890	uint64_t val;
6891
6892	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6893	data = page_index->page_data;
6894
6895	if (lun->backend->lun_attr != NULL &&
6896	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6897	     != UINT64_MAX) {
6898		phdr = (struct scsi_log_param_header *)data;
6899		scsi_ulto2b(0x0001, phdr->param_code);
6900		phdr->param_control = SLP_LBIN | SLP_LP;
6901		phdr->param_len = 8;
6902		data = (uint8_t *)(phdr + 1);
6903		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6904		data[4] = 0x01; /* per-LUN */
6905		data += phdr->param_len;
6906	}
6907
6908	if (lun->backend->lun_attr != NULL &&
6909	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6910	     != UINT64_MAX) {
6911		phdr = (struct scsi_log_param_header *)data;
6912		scsi_ulto2b(0x0002, phdr->param_code);
6913		phdr->param_control = SLP_LBIN | SLP_LP;
6914		phdr->param_len = 8;
6915		data = (uint8_t *)(phdr + 1);
6916		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6917		data[4] = 0x02; /* per-pool */
6918		data += phdr->param_len;
6919	}
6920
6921	if (lun->backend->lun_attr != NULL &&
6922	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6923	     != UINT64_MAX) {
6924		phdr = (struct scsi_log_param_header *)data;
6925		scsi_ulto2b(0x00f1, phdr->param_code);
6926		phdr->param_control = SLP_LBIN | SLP_LP;
6927		phdr->param_len = 8;
6928		data = (uint8_t *)(phdr + 1);
6929		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6930		data[4] = 0x02; /* per-pool */
6931		data += phdr->param_len;
6932	}
6933
6934	if (lun->backend->lun_attr != NULL &&
6935	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6936	     != UINT64_MAX) {
6937		phdr = (struct scsi_log_param_header *)data;
6938		scsi_ulto2b(0x00f2, phdr->param_code);
6939		phdr->param_control = SLP_LBIN | SLP_LP;
6940		phdr->param_len = 8;
6941		data = (uint8_t *)(phdr + 1);
6942		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6943		data[4] = 0x02; /* per-pool */
6944		data += phdr->param_len;
6945	}
6946
6947	page_index->page_len = data - page_index->page_data;
6948	return (0);
6949}
6950
6951int
6952ctl_log_sense(struct ctl_scsiio *ctsio)
6953{
6954	struct ctl_lun *lun;
6955	int i, pc, page_code, subpage;
6956	int alloc_len, total_len;
6957	struct ctl_page_index *page_index;
6958	struct scsi_log_sense *cdb;
6959	struct scsi_log_header *header;
6960
6961	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6962
6963	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6964	cdb = (struct scsi_log_sense *)ctsio->cdb;
6965	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6966	page_code = cdb->page & SLS_PAGE_CODE;
6967	subpage = cdb->subpage;
6968	alloc_len = scsi_2btoul(cdb->length);
6969
6970	page_index = NULL;
6971	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6972		page_index = &lun->log_pages.index[i];
6973
6974		/* Look for the right page code */
6975		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6976			continue;
6977
6978		/* Look for the right subpage or the subpage wildcard*/
6979		if (page_index->subpage != subpage)
6980			continue;
6981
6982		break;
6983	}
6984	if (i >= CTL_NUM_LOG_PAGES) {
6985		ctl_set_invalid_field(ctsio,
6986				      /*sks_valid*/ 1,
6987				      /*command*/ 1,
6988				      /*field*/ 2,
6989				      /*bit_valid*/ 0,
6990				      /*bit*/ 0);
6991		ctl_done((union ctl_io *)ctsio);
6992		return (CTL_RETVAL_COMPLETE);
6993	}
6994
6995	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6996
6997	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6998	ctsio->kern_sg_entries = 0;
6999	ctsio->kern_data_resid = 0;
7000	ctsio->kern_rel_offset = 0;
7001	if (total_len < alloc_len) {
7002		ctsio->residual = alloc_len - total_len;
7003		ctsio->kern_data_len = total_len;
7004		ctsio->kern_total_len = total_len;
7005	} else {
7006		ctsio->residual = 0;
7007		ctsio->kern_data_len = alloc_len;
7008		ctsio->kern_total_len = alloc_len;
7009	}
7010
7011	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7012	header->page = page_index->page_code;
7013	if (page_index->subpage) {
7014		header->page |= SL_SPF;
7015		header->subpage = page_index->subpage;
7016	}
7017	scsi_ulto2b(page_index->page_len, header->datalen);
7018
7019	/*
7020	 * Call the handler, if it exists, to update the
7021	 * page to the latest values.
7022	 */
7023	if (page_index->sense_handler != NULL)
7024		page_index->sense_handler(ctsio, page_index, pc);
7025
7026	memcpy(header + 1, page_index->page_data, page_index->page_len);
7027
7028	ctsio->scsi_status = SCSI_STATUS_OK;
7029	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7030	ctsio->be_move_done = ctl_config_move_done;
7031	ctl_datamove((union ctl_io *)ctsio);
7032
7033	return (CTL_RETVAL_COMPLETE);
7034}
7035
7036int
7037ctl_read_capacity(struct ctl_scsiio *ctsio)
7038{
7039	struct scsi_read_capacity *cdb;
7040	struct scsi_read_capacity_data *data;
7041	struct ctl_lun *lun;
7042	uint32_t lba;
7043
7044	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7045
7046	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7047
7048	lba = scsi_4btoul(cdb->addr);
7049	if (((cdb->pmi & SRC_PMI) == 0)
7050	 && (lba != 0)) {
7051		ctl_set_invalid_field(/*ctsio*/ ctsio,
7052				      /*sks_valid*/ 1,
7053				      /*command*/ 1,
7054				      /*field*/ 2,
7055				      /*bit_valid*/ 0,
7056				      /*bit*/ 0);
7057		ctl_done((union ctl_io *)ctsio);
7058		return (CTL_RETVAL_COMPLETE);
7059	}
7060
7061	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7062
7063	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7064	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7065	ctsio->residual = 0;
7066	ctsio->kern_data_len = sizeof(*data);
7067	ctsio->kern_total_len = sizeof(*data);
7068	ctsio->kern_data_resid = 0;
7069	ctsio->kern_rel_offset = 0;
7070	ctsio->kern_sg_entries = 0;
7071
7072	/*
7073	 * If the maximum LBA is greater than 0xfffffffe, the user must
7074	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7075	 * serivce action set.
7076	 */
7077	if (lun->be_lun->maxlba > 0xfffffffe)
7078		scsi_ulto4b(0xffffffff, data->addr);
7079	else
7080		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7081
7082	/*
7083	 * XXX KDM this may not be 512 bytes...
7084	 */
7085	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7086
7087	ctsio->scsi_status = SCSI_STATUS_OK;
7088
7089	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7090	ctsio->be_move_done = ctl_config_move_done;
7091	ctl_datamove((union ctl_io *)ctsio);
7092
7093	return (CTL_RETVAL_COMPLETE);
7094}
7095
7096int
7097ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7098{
7099	struct scsi_read_capacity_16 *cdb;
7100	struct scsi_read_capacity_data_long *data;
7101	struct ctl_lun *lun;
7102	uint64_t lba;
7103	uint32_t alloc_len;
7104
7105	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7106
7107	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7108
7109	alloc_len = scsi_4btoul(cdb->alloc_len);
7110	lba = scsi_8btou64(cdb->addr);
7111
7112	if ((cdb->reladr & SRC16_PMI)
7113	 && (lba != 0)) {
7114		ctl_set_invalid_field(/*ctsio*/ ctsio,
7115				      /*sks_valid*/ 1,
7116				      /*command*/ 1,
7117				      /*field*/ 2,
7118				      /*bit_valid*/ 0,
7119				      /*bit*/ 0);
7120		ctl_done((union ctl_io *)ctsio);
7121		return (CTL_RETVAL_COMPLETE);
7122	}
7123
7124	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7125
7126	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7127	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7128
7129	if (sizeof(*data) < alloc_len) {
7130		ctsio->residual = alloc_len - sizeof(*data);
7131		ctsio->kern_data_len = sizeof(*data);
7132		ctsio->kern_total_len = sizeof(*data);
7133	} else {
7134		ctsio->residual = 0;
7135		ctsio->kern_data_len = alloc_len;
7136		ctsio->kern_total_len = alloc_len;
7137	}
7138	ctsio->kern_data_resid = 0;
7139	ctsio->kern_rel_offset = 0;
7140	ctsio->kern_sg_entries = 0;
7141
7142	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7143	/* XXX KDM this may not be 512 bytes... */
7144	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7145	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7146	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7147	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7148		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7149
7150	ctsio->scsi_status = SCSI_STATUS_OK;
7151
7152	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7153	ctsio->be_move_done = ctl_config_move_done;
7154	ctl_datamove((union ctl_io *)ctsio);
7155
7156	return (CTL_RETVAL_COMPLETE);
7157}
7158
7159int
7160ctl_read_defect(struct ctl_scsiio *ctsio)
7161{
7162	struct scsi_read_defect_data_10 *ccb10;
7163	struct scsi_read_defect_data_12 *ccb12;
7164	struct scsi_read_defect_data_hdr_10 *data10;
7165	struct scsi_read_defect_data_hdr_12 *data12;
7166	uint32_t alloc_len, data_len;
7167	uint8_t format;
7168
7169	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7170
7171	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7172		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7173		format = ccb10->format;
7174		alloc_len = scsi_2btoul(ccb10->alloc_length);
7175		data_len = sizeof(*data10);
7176	} else {
7177		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7178		format = ccb12->format;
7179		alloc_len = scsi_4btoul(ccb12->alloc_length);
7180		data_len = sizeof(*data12);
7181	}
7182	if (alloc_len == 0) {
7183		ctl_set_success(ctsio);
7184		ctl_done((union ctl_io *)ctsio);
7185		return (CTL_RETVAL_COMPLETE);
7186	}
7187
7188	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7189	if (data_len < alloc_len) {
7190		ctsio->residual = alloc_len - data_len;
7191		ctsio->kern_data_len = data_len;
7192		ctsio->kern_total_len = data_len;
7193	} else {
7194		ctsio->residual = 0;
7195		ctsio->kern_data_len = alloc_len;
7196		ctsio->kern_total_len = alloc_len;
7197	}
7198	ctsio->kern_data_resid = 0;
7199	ctsio->kern_rel_offset = 0;
7200	ctsio->kern_sg_entries = 0;
7201
7202	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7203		data10 = (struct scsi_read_defect_data_hdr_10 *)
7204		    ctsio->kern_data_ptr;
7205		data10->format = format;
7206		scsi_ulto2b(0, data10->length);
7207	} else {
7208		data12 = (struct scsi_read_defect_data_hdr_12 *)
7209		    ctsio->kern_data_ptr;
7210		data12->format = format;
7211		scsi_ulto2b(0, data12->generation);
7212		scsi_ulto4b(0, data12->length);
7213	}
7214
7215	ctsio->scsi_status = SCSI_STATUS_OK;
7216	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7217	ctsio->be_move_done = ctl_config_move_done;
7218	ctl_datamove((union ctl_io *)ctsio);
7219	return (CTL_RETVAL_COMPLETE);
7220}
7221
7222int
7223ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7224{
7225	struct scsi_maintenance_in *cdb;
7226	int retval;
7227	int alloc_len, ext, total_len = 0, g, p, pc, pg, gs, os;
7228	int num_target_port_groups, num_target_ports;
7229	struct ctl_lun *lun;
7230	struct ctl_softc *softc;
7231	struct ctl_port *port;
7232	struct scsi_target_group_data *rtg_ptr;
7233	struct scsi_target_group_data_extended *rtg_ext_ptr;
7234	struct scsi_target_port_group_descriptor *tpg_desc;
7235
7236	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7237
7238	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7239	softc = control_softc;
7240	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7241
7242	retval = CTL_RETVAL_COMPLETE;
7243
7244	switch (cdb->byte2 & STG_PDF_MASK) {
7245	case STG_PDF_LENGTH:
7246		ext = 0;
7247		break;
7248	case STG_PDF_EXTENDED:
7249		ext = 1;
7250		break;
7251	default:
7252		ctl_set_invalid_field(/*ctsio*/ ctsio,
7253				      /*sks_valid*/ 1,
7254				      /*command*/ 1,
7255				      /*field*/ 2,
7256				      /*bit_valid*/ 1,
7257				      /*bit*/ 5);
7258		ctl_done((union ctl_io *)ctsio);
7259		return(retval);
7260	}
7261
7262	if (softc->is_single)
7263		num_target_port_groups = 1;
7264	else
7265		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7266	num_target_ports = 0;
7267	mtx_lock(&softc->ctl_lock);
7268	STAILQ_FOREACH(port, &softc->port_list, links) {
7269		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7270			continue;
7271		if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7272			continue;
7273		num_target_ports++;
7274	}
7275	mtx_unlock(&softc->ctl_lock);
7276
7277	if (ext)
7278		total_len = sizeof(struct scsi_target_group_data_extended);
7279	else
7280		total_len = sizeof(struct scsi_target_group_data);
7281	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7282		num_target_port_groups +
7283	    sizeof(struct scsi_target_port_descriptor) *
7284		num_target_ports * num_target_port_groups;
7285
7286	alloc_len = scsi_4btoul(cdb->length);
7287
7288	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7289
7290	ctsio->kern_sg_entries = 0;
7291
7292	if (total_len < alloc_len) {
7293		ctsio->residual = alloc_len - total_len;
7294		ctsio->kern_data_len = total_len;
7295		ctsio->kern_total_len = total_len;
7296	} else {
7297		ctsio->residual = 0;
7298		ctsio->kern_data_len = alloc_len;
7299		ctsio->kern_total_len = alloc_len;
7300	}
7301	ctsio->kern_data_resid = 0;
7302	ctsio->kern_rel_offset = 0;
7303
7304	if (ext) {
7305		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7306		    ctsio->kern_data_ptr;
7307		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7308		rtg_ext_ptr->format_type = 0x10;
7309		rtg_ext_ptr->implicit_transition_time = 0;
7310		tpg_desc = &rtg_ext_ptr->groups[0];
7311	} else {
7312		rtg_ptr = (struct scsi_target_group_data *)
7313		    ctsio->kern_data_ptr;
7314		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7315		tpg_desc = &rtg_ptr->groups[0];
7316	}
7317
7318	mtx_lock(&softc->ctl_lock);
7319	pg = softc->port_offset / CTL_MAX_PORTS;
7320	if (softc->flags & CTL_FLAG_ACTIVE_SHELF) {
7321		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY) {
7322			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7323			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7324		} else if (lun->flags & CTL_LUN_PRIMARY_SC) {
7325			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7326			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7327		} else {
7328			gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7329			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7330		}
7331	} else {
7332		gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7333		os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7334	}
7335	for (g = 0; g < num_target_port_groups; g++) {
7336		tpg_desc->pref_state = (g == pg) ? gs : os;
7337		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP;
7338		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7339		tpg_desc->status = TPG_IMPLICIT;
7340		pc = 0;
7341		STAILQ_FOREACH(port, &softc->port_list, links) {
7342			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7343				continue;
7344			if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7345			    CTL_MAX_LUNS)
7346				continue;
7347			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7348			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7349			    relative_target_port_identifier);
7350			pc++;
7351		}
7352		tpg_desc->target_port_count = pc;
7353		tpg_desc = (struct scsi_target_port_group_descriptor *)
7354		    &tpg_desc->descriptors[pc];
7355	}
7356	mtx_unlock(&softc->ctl_lock);
7357
7358	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7359	ctsio->be_move_done = ctl_config_move_done;
7360
7361	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7362			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7363			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7364			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7365			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7366
7367	ctl_datamove((union ctl_io *)ctsio);
7368	return(retval);
7369}
7370
7371int
7372ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7373{
7374	struct ctl_lun *lun;
7375	struct scsi_report_supported_opcodes *cdb;
7376	const struct ctl_cmd_entry *entry, *sentry;
7377	struct scsi_report_supported_opcodes_all *all;
7378	struct scsi_report_supported_opcodes_descr *descr;
7379	struct scsi_report_supported_opcodes_one *one;
7380	int retval;
7381	int alloc_len, total_len;
7382	int opcode, service_action, i, j, num;
7383
7384	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7385
7386	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7387	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7388
7389	retval = CTL_RETVAL_COMPLETE;
7390
7391	opcode = cdb->requested_opcode;
7392	service_action = scsi_2btoul(cdb->requested_service_action);
7393	switch (cdb->options & RSO_OPTIONS_MASK) {
7394	case RSO_OPTIONS_ALL:
7395		num = 0;
7396		for (i = 0; i < 256; i++) {
7397			entry = &ctl_cmd_table[i];
7398			if (entry->flags & CTL_CMD_FLAG_SA5) {
7399				for (j = 0; j < 32; j++) {
7400					sentry = &((const struct ctl_cmd_entry *)
7401					    entry->execute)[j];
7402					if (ctl_cmd_applicable(
7403					    lun->be_lun->lun_type, sentry))
7404						num++;
7405				}
7406			} else {
7407				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7408				    entry))
7409					num++;
7410			}
7411		}
7412		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7413		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7414		break;
7415	case RSO_OPTIONS_OC:
7416		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7417			ctl_set_invalid_field(/*ctsio*/ ctsio,
7418					      /*sks_valid*/ 1,
7419					      /*command*/ 1,
7420					      /*field*/ 2,
7421					      /*bit_valid*/ 1,
7422					      /*bit*/ 2);
7423			ctl_done((union ctl_io *)ctsio);
7424			return (CTL_RETVAL_COMPLETE);
7425		}
7426		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7427		break;
7428	case RSO_OPTIONS_OC_SA:
7429		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7430		    service_action >= 32) {
7431			ctl_set_invalid_field(/*ctsio*/ ctsio,
7432					      /*sks_valid*/ 1,
7433					      /*command*/ 1,
7434					      /*field*/ 2,
7435					      /*bit_valid*/ 1,
7436					      /*bit*/ 2);
7437			ctl_done((union ctl_io *)ctsio);
7438			return (CTL_RETVAL_COMPLETE);
7439		}
7440		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7441		break;
7442	default:
7443		ctl_set_invalid_field(/*ctsio*/ ctsio,
7444				      /*sks_valid*/ 1,
7445				      /*command*/ 1,
7446				      /*field*/ 2,
7447				      /*bit_valid*/ 1,
7448				      /*bit*/ 2);
7449		ctl_done((union ctl_io *)ctsio);
7450		return (CTL_RETVAL_COMPLETE);
7451	}
7452
7453	alloc_len = scsi_4btoul(cdb->length);
7454
7455	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7456
7457	ctsio->kern_sg_entries = 0;
7458
7459	if (total_len < alloc_len) {
7460		ctsio->residual = alloc_len - total_len;
7461		ctsio->kern_data_len = total_len;
7462		ctsio->kern_total_len = total_len;
7463	} else {
7464		ctsio->residual = 0;
7465		ctsio->kern_data_len = alloc_len;
7466		ctsio->kern_total_len = alloc_len;
7467	}
7468	ctsio->kern_data_resid = 0;
7469	ctsio->kern_rel_offset = 0;
7470
7471	switch (cdb->options & RSO_OPTIONS_MASK) {
7472	case RSO_OPTIONS_ALL:
7473		all = (struct scsi_report_supported_opcodes_all *)
7474		    ctsio->kern_data_ptr;
7475		num = 0;
7476		for (i = 0; i < 256; i++) {
7477			entry = &ctl_cmd_table[i];
7478			if (entry->flags & CTL_CMD_FLAG_SA5) {
7479				for (j = 0; j < 32; j++) {
7480					sentry = &((const struct ctl_cmd_entry *)
7481					    entry->execute)[j];
7482					if (!ctl_cmd_applicable(
7483					    lun->be_lun->lun_type, sentry))
7484						continue;
7485					descr = &all->descr[num++];
7486					descr->opcode = i;
7487					scsi_ulto2b(j, descr->service_action);
7488					descr->flags = RSO_SERVACTV;
7489					scsi_ulto2b(sentry->length,
7490					    descr->cdb_length);
7491				}
7492			} else {
7493				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7494				    entry))
7495					continue;
7496				descr = &all->descr[num++];
7497				descr->opcode = i;
7498				scsi_ulto2b(0, descr->service_action);
7499				descr->flags = 0;
7500				scsi_ulto2b(entry->length, descr->cdb_length);
7501			}
7502		}
7503		scsi_ulto4b(
7504		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7505		    all->length);
7506		break;
7507	case RSO_OPTIONS_OC:
7508		one = (struct scsi_report_supported_opcodes_one *)
7509		    ctsio->kern_data_ptr;
7510		entry = &ctl_cmd_table[opcode];
7511		goto fill_one;
7512	case RSO_OPTIONS_OC_SA:
7513		one = (struct scsi_report_supported_opcodes_one *)
7514		    ctsio->kern_data_ptr;
7515		entry = &ctl_cmd_table[opcode];
7516		entry = &((const struct ctl_cmd_entry *)
7517		    entry->execute)[service_action];
7518fill_one:
7519		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7520			one->support = 3;
7521			scsi_ulto2b(entry->length, one->cdb_length);
7522			one->cdb_usage[0] = opcode;
7523			memcpy(&one->cdb_usage[1], entry->usage,
7524			    entry->length - 1);
7525		} else
7526			one->support = 1;
7527		break;
7528	}
7529
7530	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7531	ctsio->be_move_done = ctl_config_move_done;
7532
7533	ctl_datamove((union ctl_io *)ctsio);
7534	return(retval);
7535}
7536
7537int
7538ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7539{
7540	struct scsi_report_supported_tmf *cdb;
7541	struct scsi_report_supported_tmf_data *data;
7542	int retval;
7543	int alloc_len, total_len;
7544
7545	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7546
7547	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7548
7549	retval = CTL_RETVAL_COMPLETE;
7550
7551	total_len = sizeof(struct scsi_report_supported_tmf_data);
7552	alloc_len = scsi_4btoul(cdb->length);
7553
7554	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7555
7556	ctsio->kern_sg_entries = 0;
7557
7558	if (total_len < alloc_len) {
7559		ctsio->residual = alloc_len - total_len;
7560		ctsio->kern_data_len = total_len;
7561		ctsio->kern_total_len = total_len;
7562	} else {
7563		ctsio->residual = 0;
7564		ctsio->kern_data_len = alloc_len;
7565		ctsio->kern_total_len = alloc_len;
7566	}
7567	ctsio->kern_data_resid = 0;
7568	ctsio->kern_rel_offset = 0;
7569
7570	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7571	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7572	data->byte2 |= RST_ITNRS;
7573
7574	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7575	ctsio->be_move_done = ctl_config_move_done;
7576
7577	ctl_datamove((union ctl_io *)ctsio);
7578	return (retval);
7579}
7580
7581int
7582ctl_report_timestamp(struct ctl_scsiio *ctsio)
7583{
7584	struct scsi_report_timestamp *cdb;
7585	struct scsi_report_timestamp_data *data;
7586	struct timeval tv;
7587	int64_t timestamp;
7588	int retval;
7589	int alloc_len, total_len;
7590
7591	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7592
7593	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7594
7595	retval = CTL_RETVAL_COMPLETE;
7596
7597	total_len = sizeof(struct scsi_report_timestamp_data);
7598	alloc_len = scsi_4btoul(cdb->length);
7599
7600	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7601
7602	ctsio->kern_sg_entries = 0;
7603
7604	if (total_len < alloc_len) {
7605		ctsio->residual = alloc_len - total_len;
7606		ctsio->kern_data_len = total_len;
7607		ctsio->kern_total_len = total_len;
7608	} else {
7609		ctsio->residual = 0;
7610		ctsio->kern_data_len = alloc_len;
7611		ctsio->kern_total_len = alloc_len;
7612	}
7613	ctsio->kern_data_resid = 0;
7614	ctsio->kern_rel_offset = 0;
7615
7616	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7617	scsi_ulto2b(sizeof(*data) - 2, data->length);
7618	data->origin = RTS_ORIG_OUTSIDE;
7619	getmicrotime(&tv);
7620	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7621	scsi_ulto4b(timestamp >> 16, data->timestamp);
7622	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7623
7624	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7625	ctsio->be_move_done = ctl_config_move_done;
7626
7627	ctl_datamove((union ctl_io *)ctsio);
7628	return (retval);
7629}
7630
7631int
7632ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7633{
7634	struct scsi_per_res_in *cdb;
7635	int alloc_len, total_len = 0;
7636	/* struct scsi_per_res_in_rsrv in_data; */
7637	struct ctl_lun *lun;
7638	struct ctl_softc *softc;
7639
7640	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7641
7642	softc = control_softc;
7643
7644	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7645
7646	alloc_len = scsi_2btoul(cdb->length);
7647
7648	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7649
7650retry:
7651	mtx_lock(&lun->lun_lock);
7652	switch (cdb->action) {
7653	case SPRI_RK: /* read keys */
7654		total_len = sizeof(struct scsi_per_res_in_keys) +
7655			lun->pr_key_count *
7656			sizeof(struct scsi_per_res_key);
7657		break;
7658	case SPRI_RR: /* read reservation */
7659		if (lun->flags & CTL_LUN_PR_RESERVED)
7660			total_len = sizeof(struct scsi_per_res_in_rsrv);
7661		else
7662			total_len = sizeof(struct scsi_per_res_in_header);
7663		break;
7664	case SPRI_RC: /* report capabilities */
7665		total_len = sizeof(struct scsi_per_res_cap);
7666		break;
7667	case SPRI_RS: /* read full status */
7668		total_len = sizeof(struct scsi_per_res_in_header) +
7669		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7670		    lun->pr_key_count;
7671		break;
7672	default:
7673		panic("Invalid PR type %x", cdb->action);
7674	}
7675	mtx_unlock(&lun->lun_lock);
7676
7677	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7678
7679	if (total_len < alloc_len) {
7680		ctsio->residual = alloc_len - total_len;
7681		ctsio->kern_data_len = total_len;
7682		ctsio->kern_total_len = total_len;
7683	} else {
7684		ctsio->residual = 0;
7685		ctsio->kern_data_len = alloc_len;
7686		ctsio->kern_total_len = alloc_len;
7687	}
7688
7689	ctsio->kern_data_resid = 0;
7690	ctsio->kern_rel_offset = 0;
7691	ctsio->kern_sg_entries = 0;
7692
7693	mtx_lock(&lun->lun_lock);
7694	switch (cdb->action) {
7695	case SPRI_RK: { // read keys
7696        struct scsi_per_res_in_keys *res_keys;
7697		int i, key_count;
7698
7699		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7700
7701		/*
7702		 * We had to drop the lock to allocate our buffer, which
7703		 * leaves time for someone to come in with another
7704		 * persistent reservation.  (That is unlikely, though,
7705		 * since this should be the only persistent reservation
7706		 * command active right now.)
7707		 */
7708		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7709		    (lun->pr_key_count *
7710		     sizeof(struct scsi_per_res_key)))){
7711			mtx_unlock(&lun->lun_lock);
7712			free(ctsio->kern_data_ptr, M_CTL);
7713			printf("%s: reservation length changed, retrying\n",
7714			       __func__);
7715			goto retry;
7716		}
7717
7718		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7719
7720		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7721			     lun->pr_key_count, res_keys->header.length);
7722
7723		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7724			if (lun->pr_keys[i] == 0)
7725				continue;
7726
7727			/*
7728			 * We used lun->pr_key_count to calculate the
7729			 * size to allocate.  If it turns out the number of
7730			 * initiators with the registered flag set is
7731			 * larger than that (i.e. they haven't been kept in
7732			 * sync), we've got a problem.
7733			 */
7734			if (key_count >= lun->pr_key_count) {
7735#ifdef NEEDTOPORT
7736				csevent_log(CSC_CTL | CSC_SHELF_SW |
7737					    CTL_PR_ERROR,
7738					    csevent_LogType_Fault,
7739					    csevent_AlertLevel_Yellow,
7740					    csevent_FRU_ShelfController,
7741					    csevent_FRU_Firmware,
7742				        csevent_FRU_Unknown,
7743					    "registered keys %d >= key "
7744					    "count %d", key_count,
7745					    lun->pr_key_count);
7746#endif
7747				key_count++;
7748				continue;
7749			}
7750			scsi_u64to8b(lun->pr_keys[i],
7751			    res_keys->keys[key_count].key);
7752			key_count++;
7753		}
7754		break;
7755	}
7756	case SPRI_RR: { // read reservation
7757		struct scsi_per_res_in_rsrv *res;
7758		int tmp_len, header_only;
7759
7760		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7761
7762		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7763
7764		if (lun->flags & CTL_LUN_PR_RESERVED)
7765		{
7766			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7767			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7768				    res->header.length);
7769			header_only = 0;
7770		} else {
7771			tmp_len = sizeof(struct scsi_per_res_in_header);
7772			scsi_ulto4b(0, res->header.length);
7773			header_only = 1;
7774		}
7775
7776		/*
7777		 * We had to drop the lock to allocate our buffer, which
7778		 * leaves time for someone to come in with another
7779		 * persistent reservation.  (That is unlikely, though,
7780		 * since this should be the only persistent reservation
7781		 * command active right now.)
7782		 */
7783		if (tmp_len != total_len) {
7784			mtx_unlock(&lun->lun_lock);
7785			free(ctsio->kern_data_ptr, M_CTL);
7786			printf("%s: reservation status changed, retrying\n",
7787			       __func__);
7788			goto retry;
7789		}
7790
7791		/*
7792		 * No reservation held, so we're done.
7793		 */
7794		if (header_only != 0)
7795			break;
7796
7797		/*
7798		 * If the registration is an All Registrants type, the key
7799		 * is 0, since it doesn't really matter.
7800		 */
7801		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7802			scsi_u64to8b(lun->pr_keys[lun->pr_res_idx],
7803			    res->data.reservation);
7804		}
7805		res->data.scopetype = lun->res_type;
7806		break;
7807	}
7808	case SPRI_RC:     //report capabilities
7809	{
7810		struct scsi_per_res_cap *res_cap;
7811		uint16_t type_mask;
7812
7813		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7814		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7815		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7816		type_mask = SPRI_TM_WR_EX_AR |
7817			    SPRI_TM_EX_AC_RO |
7818			    SPRI_TM_WR_EX_RO |
7819			    SPRI_TM_EX_AC |
7820			    SPRI_TM_WR_EX |
7821			    SPRI_TM_EX_AC_AR;
7822		scsi_ulto2b(type_mask, res_cap->type_mask);
7823		break;
7824	}
7825	case SPRI_RS: { // read full status
7826		struct scsi_per_res_in_full *res_status;
7827		struct scsi_per_res_in_full_desc *res_desc;
7828		struct ctl_port *port;
7829		int i, len;
7830
7831		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7832
7833		/*
7834		 * We had to drop the lock to allocate our buffer, which
7835		 * leaves time for someone to come in with another
7836		 * persistent reservation.  (That is unlikely, though,
7837		 * since this should be the only persistent reservation
7838		 * command active right now.)
7839		 */
7840		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7841		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7842		     lun->pr_key_count)){
7843			mtx_unlock(&lun->lun_lock);
7844			free(ctsio->kern_data_ptr, M_CTL);
7845			printf("%s: reservation length changed, retrying\n",
7846			       __func__);
7847			goto retry;
7848		}
7849
7850		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7851
7852		res_desc = &res_status->desc[0];
7853		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7854			if (lun->pr_keys[i] == 0)
7855				continue;
7856
7857			scsi_u64to8b(lun->pr_keys[i], res_desc->res_key.key);
7858			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7859			    (lun->pr_res_idx == i ||
7860			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7861				res_desc->flags = SPRI_FULL_R_HOLDER;
7862				res_desc->scopetype = lun->res_type;
7863			}
7864			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7865			    res_desc->rel_trgt_port_id);
7866			len = 0;
7867			port = softc->ctl_ports[
7868			    ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
7869			if (port != NULL)
7870				len = ctl_create_iid(port,
7871				    i % CTL_MAX_INIT_PER_PORT,
7872				    res_desc->transport_id);
7873			scsi_ulto4b(len, res_desc->additional_length);
7874			res_desc = (struct scsi_per_res_in_full_desc *)
7875			    &res_desc->transport_id[len];
7876		}
7877		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7878		    res_status->header.length);
7879		break;
7880	}
7881	default:
7882		/*
7883		 * This is a bug, because we just checked for this above,
7884		 * and should have returned an error.
7885		 */
7886		panic("Invalid PR type %x", cdb->action);
7887		break; /* NOTREACHED */
7888	}
7889	mtx_unlock(&lun->lun_lock);
7890
7891	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7892	ctsio->be_move_done = ctl_config_move_done;
7893
7894	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7895			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7896			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7897			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7898			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7899
7900	ctl_datamove((union ctl_io *)ctsio);
7901
7902	return (CTL_RETVAL_COMPLETE);
7903}
7904
7905/*
7906 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7907 * it should return.
7908 */
7909static int
7910ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7911		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7912		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7913		struct scsi_per_res_out_parms* param)
7914{
7915	union ctl_ha_msg persis_io;
7916	int retval, i;
7917	int isc_retval;
7918
7919	retval = 0;
7920
7921	mtx_lock(&lun->lun_lock);
7922	if (sa_res_key == 0) {
7923		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7924			/* validate scope and type */
7925			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7926			     SPR_LU_SCOPE) {
7927				mtx_unlock(&lun->lun_lock);
7928				ctl_set_invalid_field(/*ctsio*/ ctsio,
7929						      /*sks_valid*/ 1,
7930						      /*command*/ 1,
7931						      /*field*/ 2,
7932						      /*bit_valid*/ 1,
7933						      /*bit*/ 4);
7934				ctl_done((union ctl_io *)ctsio);
7935				return (1);
7936			}
7937
7938		        if (type>8 || type==2 || type==4 || type==0) {
7939				mtx_unlock(&lun->lun_lock);
7940				ctl_set_invalid_field(/*ctsio*/ ctsio,
7941       	           				      /*sks_valid*/ 1,
7942						      /*command*/ 1,
7943						      /*field*/ 2,
7944						      /*bit_valid*/ 1,
7945						      /*bit*/ 0);
7946				ctl_done((union ctl_io *)ctsio);
7947				return (1);
7948		        }
7949
7950			/*
7951			 * Unregister everybody else and build UA for
7952			 * them
7953			 */
7954			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7955				if (i == residx || lun->pr_keys[i] == 0)
7956					continue;
7957
7958				if (!persis_offset
7959				 && i <CTL_MAX_INITIATORS)
7960					lun->pending_ua[i] |=
7961						CTL_UA_REG_PREEMPT;
7962				else if (persis_offset
7963				      && i >= persis_offset)
7964					lun->pending_ua[i-persis_offset] |=
7965						CTL_UA_REG_PREEMPT;
7966				lun->pr_keys[i] = 0;
7967			}
7968			lun->pr_key_count = 1;
7969			lun->res_type = type;
7970			if (lun->res_type != SPR_TYPE_WR_EX_AR
7971			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7972				lun->pr_res_idx = residx;
7973
7974			/* send msg to other side */
7975			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7976			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7977			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7978			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7979			persis_io.pr.pr_info.res_type = type;
7980			memcpy(persis_io.pr.pr_info.sa_res_key,
7981			       param->serv_act_res_key,
7982			       sizeof(param->serv_act_res_key));
7983			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7984			     &persis_io, sizeof(persis_io), 0)) >
7985			     CTL_HA_STATUS_SUCCESS) {
7986				printf("CTL:Persis Out error returned "
7987				       "from ctl_ha_msg_send %d\n",
7988				       isc_retval);
7989			}
7990		} else {
7991			/* not all registrants */
7992			mtx_unlock(&lun->lun_lock);
7993			free(ctsio->kern_data_ptr, M_CTL);
7994			ctl_set_invalid_field(ctsio,
7995					      /*sks_valid*/ 1,
7996					      /*command*/ 0,
7997					      /*field*/ 8,
7998					      /*bit_valid*/ 0,
7999					      /*bit*/ 0);
8000			ctl_done((union ctl_io *)ctsio);
8001			return (1);
8002		}
8003	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8004		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8005		int found = 0;
8006
8007		if (res_key == sa_res_key) {
8008			/* special case */
8009			/*
8010			 * The spec implies this is not good but doesn't
8011			 * say what to do. There are two choices either
8012			 * generate a res conflict or check condition
8013			 * with illegal field in parameter data. Since
8014			 * that is what is done when the sa_res_key is
8015			 * zero I'll take that approach since this has
8016			 * to do with the sa_res_key.
8017			 */
8018			mtx_unlock(&lun->lun_lock);
8019			free(ctsio->kern_data_ptr, M_CTL);
8020			ctl_set_invalid_field(ctsio,
8021					      /*sks_valid*/ 1,
8022					      /*command*/ 0,
8023					      /*field*/ 8,
8024					      /*bit_valid*/ 0,
8025					      /*bit*/ 0);
8026			ctl_done((union ctl_io *)ctsio);
8027			return (1);
8028		}
8029
8030		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8031			if (lun->pr_keys[i] != sa_res_key)
8032				continue;
8033
8034			found = 1;
8035			lun->pr_keys[i] = 0;
8036			lun->pr_key_count--;
8037
8038			if (!persis_offset && i < CTL_MAX_INITIATORS)
8039				lun->pending_ua[i] |= CTL_UA_REG_PREEMPT;
8040			else if (persis_offset && i >= persis_offset)
8041				lun->pending_ua[i-persis_offset] |=
8042					CTL_UA_REG_PREEMPT;
8043		}
8044		if (!found) {
8045			mtx_unlock(&lun->lun_lock);
8046			free(ctsio->kern_data_ptr, M_CTL);
8047			ctl_set_reservation_conflict(ctsio);
8048			ctl_done((union ctl_io *)ctsio);
8049			return (CTL_RETVAL_COMPLETE);
8050		}
8051		/* send msg to other side */
8052		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8053		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8054		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8055		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8056		persis_io.pr.pr_info.res_type = type;
8057		memcpy(persis_io.pr.pr_info.sa_res_key,
8058		       param->serv_act_res_key,
8059		       sizeof(param->serv_act_res_key));
8060		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8061		     &persis_io, sizeof(persis_io), 0)) >
8062		     CTL_HA_STATUS_SUCCESS) {
8063			printf("CTL:Persis Out error returned from "
8064			       "ctl_ha_msg_send %d\n", isc_retval);
8065		}
8066	} else {
8067		/* Reserved but not all registrants */
8068		/* sa_res_key is res holder */
8069		if (sa_res_key == lun->pr_keys[lun->pr_res_idx]) {
8070			/* validate scope and type */
8071			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8072			     SPR_LU_SCOPE) {
8073				mtx_unlock(&lun->lun_lock);
8074				ctl_set_invalid_field(/*ctsio*/ ctsio,
8075						      /*sks_valid*/ 1,
8076						      /*command*/ 1,
8077						      /*field*/ 2,
8078						      /*bit_valid*/ 1,
8079						      /*bit*/ 4);
8080				ctl_done((union ctl_io *)ctsio);
8081				return (1);
8082			}
8083
8084			if (type>8 || type==2 || type==4 || type==0) {
8085				mtx_unlock(&lun->lun_lock);
8086				ctl_set_invalid_field(/*ctsio*/ ctsio,
8087						      /*sks_valid*/ 1,
8088						      /*command*/ 1,
8089						      /*field*/ 2,
8090						      /*bit_valid*/ 1,
8091						      /*bit*/ 0);
8092				ctl_done((union ctl_io *)ctsio);
8093				return (1);
8094			}
8095
8096			/*
8097			 * Do the following:
8098			 * if sa_res_key != res_key remove all
8099			 * registrants w/sa_res_key and generate UA
8100			 * for these registrants(Registrations
8101			 * Preempted) if it wasn't an exclusive
8102			 * reservation generate UA(Reservations
8103			 * Preempted) for all other registered nexuses
8104			 * if the type has changed. Establish the new
8105			 * reservation and holder. If res_key and
8106			 * sa_res_key are the same do the above
8107			 * except don't unregister the res holder.
8108			 */
8109
8110			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8111				if (i == residx || lun->pr_keys[i] == 0)
8112					continue;
8113
8114				if (sa_res_key == lun->pr_keys[i]) {
8115					lun->pr_keys[i] = 0;
8116					lun->pr_key_count--;
8117
8118					if (!persis_offset
8119					 && i < CTL_MAX_INITIATORS)
8120						lun->pending_ua[i] |=
8121							CTL_UA_REG_PREEMPT;
8122					else if (persis_offset
8123					      && i >= persis_offset)
8124						lun->pending_ua[i-persis_offset] |=
8125						  CTL_UA_REG_PREEMPT;
8126				} else if (type != lun->res_type
8127					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8128					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8129						if (!persis_offset
8130						 && i < CTL_MAX_INITIATORS)
8131							lun->pending_ua[i] |=
8132							CTL_UA_RES_RELEASE;
8133						else if (persis_offset
8134						      && i >= persis_offset)
8135							lun->pending_ua[
8136							i-persis_offset] |=
8137							CTL_UA_RES_RELEASE;
8138				}
8139			}
8140			lun->res_type = type;
8141			if (lun->res_type != SPR_TYPE_WR_EX_AR
8142			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8143				lun->pr_res_idx = residx;
8144			else
8145				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8146
8147			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8148			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8149			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8150			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8151			persis_io.pr.pr_info.res_type = type;
8152			memcpy(persis_io.pr.pr_info.sa_res_key,
8153			       param->serv_act_res_key,
8154			       sizeof(param->serv_act_res_key));
8155			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8156			     &persis_io, sizeof(persis_io), 0)) >
8157			     CTL_HA_STATUS_SUCCESS) {
8158				printf("CTL:Persis Out error returned "
8159				       "from ctl_ha_msg_send %d\n",
8160				       isc_retval);
8161			}
8162		} else {
8163			/*
8164			 * sa_res_key is not the res holder just
8165			 * remove registrants
8166			 */
8167			int found=0;
8168
8169			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8170				if (sa_res_key != lun->pr_keys[i])
8171					continue;
8172
8173				found = 1;
8174				lun->pr_keys[i] = 0;
8175				lun->pr_key_count--;
8176
8177				if (!persis_offset
8178				 && i < CTL_MAX_INITIATORS)
8179					lun->pending_ua[i] |=
8180						CTL_UA_REG_PREEMPT;
8181				else if (persis_offset
8182				      && i >= persis_offset)
8183					lun->pending_ua[i-persis_offset] |=
8184						CTL_UA_REG_PREEMPT;
8185			}
8186
8187			if (!found) {
8188				mtx_unlock(&lun->lun_lock);
8189				free(ctsio->kern_data_ptr, M_CTL);
8190				ctl_set_reservation_conflict(ctsio);
8191				ctl_done((union ctl_io *)ctsio);
8192		        	return (1);
8193			}
8194			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8195			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8196			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8197			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8198			persis_io.pr.pr_info.res_type = type;
8199			memcpy(persis_io.pr.pr_info.sa_res_key,
8200			       param->serv_act_res_key,
8201			       sizeof(param->serv_act_res_key));
8202			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8203			     &persis_io, sizeof(persis_io), 0)) >
8204			     CTL_HA_STATUS_SUCCESS) {
8205				printf("CTL:Persis Out error returned "
8206				       "from ctl_ha_msg_send %d\n",
8207				isc_retval);
8208			}
8209		}
8210	}
8211
8212	lun->PRGeneration++;
8213	mtx_unlock(&lun->lun_lock);
8214
8215	return (retval);
8216}
8217
8218static void
8219ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8220{
8221	uint64_t sa_res_key;
8222	int i;
8223
8224	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8225
8226	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8227	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8228	 || sa_res_key != lun->pr_keys[lun->pr_res_idx]) {
8229		if (sa_res_key == 0) {
8230			/*
8231			 * Unregister everybody else and build UA for
8232			 * them
8233			 */
8234			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8235				if (i == msg->pr.pr_info.residx ||
8236				    lun->pr_keys[i] == 0)
8237					continue;
8238
8239				if (!persis_offset
8240				 && i < CTL_MAX_INITIATORS)
8241					lun->pending_ua[i] |=
8242						CTL_UA_REG_PREEMPT;
8243				else if (persis_offset && i >= persis_offset)
8244					lun->pending_ua[i - persis_offset] |=
8245						CTL_UA_REG_PREEMPT;
8246				lun->pr_keys[i] = 0;
8247			}
8248
8249			lun->pr_key_count = 1;
8250			lun->res_type = msg->pr.pr_info.res_type;
8251			if (lun->res_type != SPR_TYPE_WR_EX_AR
8252			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8253				lun->pr_res_idx = msg->pr.pr_info.residx;
8254		} else {
8255		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8256				if (sa_res_key == lun->pr_keys[i])
8257					continue;
8258
8259				lun->pr_keys[i] = 0;
8260				lun->pr_key_count--;
8261
8262				if (!persis_offset
8263				 && i < persis_offset)
8264					lun->pending_ua[i] |=
8265						CTL_UA_REG_PREEMPT;
8266				else if (persis_offset
8267				      && i >= persis_offset)
8268					lun->pending_ua[i - persis_offset] |=
8269						CTL_UA_REG_PREEMPT;
8270			}
8271		}
8272	} else {
8273		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8274			if (i == msg->pr.pr_info.residx ||
8275			    lun->pr_keys[i] == 0)
8276				continue;
8277
8278			if (sa_res_key == lun->pr_keys[i]) {
8279				lun->pr_keys[i] = 0;
8280				lun->pr_key_count--;
8281				if (!persis_offset
8282				 && i < CTL_MAX_INITIATORS)
8283					lun->pending_ua[i] |=
8284						CTL_UA_REG_PREEMPT;
8285				else if (persis_offset
8286				      && i >= persis_offset)
8287					lun->pending_ua[i - persis_offset] |=
8288						CTL_UA_REG_PREEMPT;
8289			} else if (msg->pr.pr_info.res_type != lun->res_type
8290				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8291				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8292					if (!persis_offset
8293					 && i < persis_offset)
8294						lun->pending_ua[i] |=
8295							CTL_UA_RES_RELEASE;
8296					else if (persis_offset
8297					      && i >= persis_offset)
8298					lun->pending_ua[i - persis_offset] |=
8299						CTL_UA_RES_RELEASE;
8300			}
8301		}
8302		lun->res_type = msg->pr.pr_info.res_type;
8303		if (lun->res_type != SPR_TYPE_WR_EX_AR
8304		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8305			lun->pr_res_idx = msg->pr.pr_info.residx;
8306		else
8307			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8308	}
8309	lun->PRGeneration++;
8310
8311}
8312
8313
8314int
8315ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8316{
8317	int retval;
8318	int isc_retval;
8319	u_int32_t param_len;
8320	struct scsi_per_res_out *cdb;
8321	struct ctl_lun *lun;
8322	struct scsi_per_res_out_parms* param;
8323	struct ctl_softc *softc;
8324	uint32_t residx;
8325	uint64_t res_key, sa_res_key;
8326	uint8_t type;
8327	union ctl_ha_msg persis_io;
8328	int    i;
8329
8330	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8331
8332	retval = CTL_RETVAL_COMPLETE;
8333
8334	softc = control_softc;
8335
8336	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8337	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8338
8339	/*
8340	 * We only support whole-LUN scope.  The scope & type are ignored for
8341	 * register, register and ignore existing key and clear.
8342	 * We sometimes ignore scope and type on preempts too!!
8343	 * Verify reservation type here as well.
8344	 */
8345	type = cdb->scope_type & SPR_TYPE_MASK;
8346	if ((cdb->action == SPRO_RESERVE)
8347	 || (cdb->action == SPRO_RELEASE)) {
8348		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8349			ctl_set_invalid_field(/*ctsio*/ ctsio,
8350					      /*sks_valid*/ 1,
8351					      /*command*/ 1,
8352					      /*field*/ 2,
8353					      /*bit_valid*/ 1,
8354					      /*bit*/ 4);
8355			ctl_done((union ctl_io *)ctsio);
8356			return (CTL_RETVAL_COMPLETE);
8357		}
8358
8359		if (type>8 || type==2 || type==4 || type==0) {
8360			ctl_set_invalid_field(/*ctsio*/ ctsio,
8361					      /*sks_valid*/ 1,
8362					      /*command*/ 1,
8363					      /*field*/ 2,
8364					      /*bit_valid*/ 1,
8365					      /*bit*/ 0);
8366			ctl_done((union ctl_io *)ctsio);
8367			return (CTL_RETVAL_COMPLETE);
8368		}
8369	}
8370
8371	param_len = scsi_4btoul(cdb->length);
8372
8373	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8374		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8375		ctsio->kern_data_len = param_len;
8376		ctsio->kern_total_len = param_len;
8377		ctsio->kern_data_resid = 0;
8378		ctsio->kern_rel_offset = 0;
8379		ctsio->kern_sg_entries = 0;
8380		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8381		ctsio->be_move_done = ctl_config_move_done;
8382		ctl_datamove((union ctl_io *)ctsio);
8383
8384		return (CTL_RETVAL_COMPLETE);
8385	}
8386
8387	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8388
8389	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8390	res_key = scsi_8btou64(param->res_key.key);
8391	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8392
8393	/*
8394	 * Validate the reservation key here except for SPRO_REG_IGNO
8395	 * This must be done for all other service actions
8396	 */
8397	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8398		mtx_lock(&lun->lun_lock);
8399		if (lun->pr_keys[residx] != 0) {
8400		    if (res_key != lun->pr_keys[residx]) {
8401				/*
8402				 * The current key passed in doesn't match
8403				 * the one the initiator previously
8404				 * registered.
8405				 */
8406				mtx_unlock(&lun->lun_lock);
8407				free(ctsio->kern_data_ptr, M_CTL);
8408				ctl_set_reservation_conflict(ctsio);
8409				ctl_done((union ctl_io *)ctsio);
8410				return (CTL_RETVAL_COMPLETE);
8411			}
8412		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8413			/*
8414			 * We are not registered
8415			 */
8416			mtx_unlock(&lun->lun_lock);
8417			free(ctsio->kern_data_ptr, M_CTL);
8418			ctl_set_reservation_conflict(ctsio);
8419			ctl_done((union ctl_io *)ctsio);
8420			return (CTL_RETVAL_COMPLETE);
8421		} else if (res_key != 0) {
8422			/*
8423			 * We are not registered and trying to register but
8424			 * the register key isn't zero.
8425			 */
8426			mtx_unlock(&lun->lun_lock);
8427			free(ctsio->kern_data_ptr, M_CTL);
8428			ctl_set_reservation_conflict(ctsio);
8429			ctl_done((union ctl_io *)ctsio);
8430			return (CTL_RETVAL_COMPLETE);
8431		}
8432		mtx_unlock(&lun->lun_lock);
8433	}
8434
8435	switch (cdb->action & SPRO_ACTION_MASK) {
8436	case SPRO_REGISTER:
8437	case SPRO_REG_IGNO: {
8438
8439#if 0
8440		printf("Registration received\n");
8441#endif
8442
8443		/*
8444		 * We don't support any of these options, as we report in
8445		 * the read capabilities request (see
8446		 * ctl_persistent_reserve_in(), above).
8447		 */
8448		if ((param->flags & SPR_SPEC_I_PT)
8449		 || (param->flags & SPR_ALL_TG_PT)
8450		 || (param->flags & SPR_APTPL)) {
8451			int bit_ptr;
8452
8453			if (param->flags & SPR_APTPL)
8454				bit_ptr = 0;
8455			else if (param->flags & SPR_ALL_TG_PT)
8456				bit_ptr = 2;
8457			else /* SPR_SPEC_I_PT */
8458				bit_ptr = 3;
8459
8460			free(ctsio->kern_data_ptr, M_CTL);
8461			ctl_set_invalid_field(ctsio,
8462					      /*sks_valid*/ 1,
8463					      /*command*/ 0,
8464					      /*field*/ 20,
8465					      /*bit_valid*/ 1,
8466					      /*bit*/ bit_ptr);
8467			ctl_done((union ctl_io *)ctsio);
8468			return (CTL_RETVAL_COMPLETE);
8469		}
8470
8471		mtx_lock(&lun->lun_lock);
8472
8473		/*
8474		 * The initiator wants to clear the
8475		 * key/unregister.
8476		 */
8477		if (sa_res_key == 0) {
8478			if ((res_key == 0
8479			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8480			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8481			  && lun->pr_keys[residx] == 0)) {
8482				mtx_unlock(&lun->lun_lock);
8483				goto done;
8484			}
8485
8486			lun->pr_keys[residx] = 0;
8487			lun->pr_key_count--;
8488
8489			if (residx == lun->pr_res_idx) {
8490				lun->flags &= ~CTL_LUN_PR_RESERVED;
8491				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8492
8493				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8494				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8495				 && lun->pr_key_count) {
8496					/*
8497					 * If the reservation is a registrants
8498					 * only type we need to generate a UA
8499					 * for other registered inits.  The
8500					 * sense code should be RESERVATIONS
8501					 * RELEASED
8502					 */
8503
8504					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8505						if (lun->pr_keys[
8506						    i + persis_offset] == 0)
8507							continue;
8508						lun->pending_ua[i] |=
8509							CTL_UA_RES_RELEASE;
8510					}
8511				}
8512				lun->res_type = 0;
8513			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8514				if (lun->pr_key_count==0) {
8515					lun->flags &= ~CTL_LUN_PR_RESERVED;
8516					lun->res_type = 0;
8517					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8518				}
8519			}
8520			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8521			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8522			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8523			persis_io.pr.pr_info.residx = residx;
8524			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8525			     &persis_io, sizeof(persis_io), 0 )) >
8526			     CTL_HA_STATUS_SUCCESS) {
8527				printf("CTL:Persis Out error returned from "
8528				       "ctl_ha_msg_send %d\n", isc_retval);
8529			}
8530		} else /* sa_res_key != 0 */ {
8531
8532			/*
8533			 * If we aren't registered currently then increment
8534			 * the key count and set the registered flag.
8535			 */
8536			if (lun->pr_keys[residx] == 0)
8537				lun->pr_key_count++;
8538			lun->pr_keys[residx] = sa_res_key;
8539
8540			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8541			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8542			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8543			persis_io.pr.pr_info.residx = residx;
8544			memcpy(persis_io.pr.pr_info.sa_res_key,
8545			       param->serv_act_res_key,
8546			       sizeof(param->serv_act_res_key));
8547			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8548			     &persis_io, sizeof(persis_io), 0)) >
8549			     CTL_HA_STATUS_SUCCESS) {
8550				printf("CTL:Persis Out error returned from "
8551				       "ctl_ha_msg_send %d\n", isc_retval);
8552			}
8553		}
8554		lun->PRGeneration++;
8555		mtx_unlock(&lun->lun_lock);
8556
8557		break;
8558	}
8559	case SPRO_RESERVE:
8560#if 0
8561                printf("Reserve executed type %d\n", type);
8562#endif
8563		mtx_lock(&lun->lun_lock);
8564		if (lun->flags & CTL_LUN_PR_RESERVED) {
8565			/*
8566			 * if this isn't the reservation holder and it's
8567			 * not a "all registrants" type or if the type is
8568			 * different then we have a conflict
8569			 */
8570			if ((lun->pr_res_idx != residx
8571			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8572			 || lun->res_type != type) {
8573				mtx_unlock(&lun->lun_lock);
8574				free(ctsio->kern_data_ptr, M_CTL);
8575				ctl_set_reservation_conflict(ctsio);
8576				ctl_done((union ctl_io *)ctsio);
8577				return (CTL_RETVAL_COMPLETE);
8578			}
8579			mtx_unlock(&lun->lun_lock);
8580		} else /* create a reservation */ {
8581			/*
8582			 * If it's not an "all registrants" type record
8583			 * reservation holder
8584			 */
8585			if (type != SPR_TYPE_WR_EX_AR
8586			 && type != SPR_TYPE_EX_AC_AR)
8587				lun->pr_res_idx = residx; /* Res holder */
8588			else
8589				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8590
8591			lun->flags |= CTL_LUN_PR_RESERVED;
8592			lun->res_type = type;
8593
8594			mtx_unlock(&lun->lun_lock);
8595
8596			/* send msg to other side */
8597			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8598			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8599			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8600			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8601			persis_io.pr.pr_info.res_type = type;
8602			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8603			     &persis_io, sizeof(persis_io), 0)) >
8604			     CTL_HA_STATUS_SUCCESS) {
8605				printf("CTL:Persis Out error returned from "
8606				       "ctl_ha_msg_send %d\n", isc_retval);
8607			}
8608		}
8609		break;
8610
8611	case SPRO_RELEASE:
8612		mtx_lock(&lun->lun_lock);
8613		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8614			/* No reservation exists return good status */
8615			mtx_unlock(&lun->lun_lock);
8616			goto done;
8617		}
8618		/*
8619		 * Is this nexus a reservation holder?
8620		 */
8621		if (lun->pr_res_idx != residx
8622		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8623			/*
8624			 * not a res holder return good status but
8625			 * do nothing
8626			 */
8627			mtx_unlock(&lun->lun_lock);
8628			goto done;
8629		}
8630
8631		if (lun->res_type != type) {
8632			mtx_unlock(&lun->lun_lock);
8633			free(ctsio->kern_data_ptr, M_CTL);
8634			ctl_set_illegal_pr_release(ctsio);
8635			ctl_done((union ctl_io *)ctsio);
8636			return (CTL_RETVAL_COMPLETE);
8637		}
8638
8639		/* okay to release */
8640		lun->flags &= ~CTL_LUN_PR_RESERVED;
8641		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8642		lun->res_type = 0;
8643
8644		/*
8645		 * if this isn't an exclusive access
8646		 * res generate UA for all other
8647		 * registrants.
8648		 */
8649		if (type != SPR_TYPE_EX_AC
8650		 && type != SPR_TYPE_WR_EX) {
8651			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8652				if (i == residx ||
8653				    lun->pr_keys[i + persis_offset] == 0)
8654					continue;
8655				lun->pending_ua[i] |= CTL_UA_RES_RELEASE;
8656			}
8657		}
8658		mtx_unlock(&lun->lun_lock);
8659		/* Send msg to other side */
8660		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8661		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8662		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8663		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8664		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8665			printf("CTL:Persis Out error returned from "
8666			       "ctl_ha_msg_send %d\n", isc_retval);
8667		}
8668		break;
8669
8670	case SPRO_CLEAR:
8671		/* send msg to other side */
8672
8673		mtx_lock(&lun->lun_lock);
8674		lun->flags &= ~CTL_LUN_PR_RESERVED;
8675		lun->res_type = 0;
8676		lun->pr_key_count = 0;
8677		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8678
8679		lun->pr_keys[residx] = 0;
8680
8681		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8682			if (lun->pr_keys[i] != 0) {
8683				if (!persis_offset && i < CTL_MAX_INITIATORS)
8684					lun->pending_ua[i] |=
8685						CTL_UA_RES_PREEMPT;
8686				else if (persis_offset && i >= persis_offset)
8687					lun->pending_ua[i-persis_offset] |=
8688					    CTL_UA_RES_PREEMPT;
8689
8690				lun->pr_keys[i] = 0;
8691			}
8692		lun->PRGeneration++;
8693		mtx_unlock(&lun->lun_lock);
8694		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8695		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8696		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8697		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8698		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8699			printf("CTL:Persis Out error returned from "
8700			       "ctl_ha_msg_send %d\n", isc_retval);
8701		}
8702		break;
8703
8704	case SPRO_PREEMPT:
8705	case SPRO_PRE_ABO: {
8706		int nretval;
8707
8708		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8709					  residx, ctsio, cdb, param);
8710		if (nretval != 0)
8711			return (CTL_RETVAL_COMPLETE);
8712		break;
8713	}
8714	default:
8715		panic("Invalid PR type %x", cdb->action);
8716	}
8717
8718done:
8719	free(ctsio->kern_data_ptr, M_CTL);
8720	ctl_set_success(ctsio);
8721	ctl_done((union ctl_io *)ctsio);
8722
8723	return (retval);
8724}
8725
8726/*
8727 * This routine is for handling a message from the other SC pertaining to
8728 * persistent reserve out. All the error checking will have been done
8729 * so only perorming the action need be done here to keep the two
8730 * in sync.
8731 */
8732static void
8733ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8734{
8735	struct ctl_lun *lun;
8736	struct ctl_softc *softc;
8737	int i;
8738	uint32_t targ_lun;
8739
8740	softc = control_softc;
8741
8742	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8743	lun = softc->ctl_luns[targ_lun];
8744	mtx_lock(&lun->lun_lock);
8745	switch(msg->pr.pr_info.action) {
8746	case CTL_PR_REG_KEY:
8747		if (lun->pr_keys[msg->pr.pr_info.residx] == 0)
8748			lun->pr_key_count++;
8749		lun->pr_keys[msg->pr.pr_info.residx] =
8750		    scsi_8btou64(msg->pr.pr_info.sa_res_key);
8751		lun->PRGeneration++;
8752		break;
8753
8754	case CTL_PR_UNREG_KEY:
8755		lun->pr_keys[msg->pr.pr_info.residx] = 0;
8756		lun->pr_key_count--;
8757
8758		/* XXX Need to see if the reservation has been released */
8759		/* if so do we need to generate UA? */
8760		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8761			lun->flags &= ~CTL_LUN_PR_RESERVED;
8762			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8763
8764			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8765			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8766			 && lun->pr_key_count) {
8767				/*
8768				 * If the reservation is a registrants
8769				 * only type we need to generate a UA
8770				 * for other registered inits.  The
8771				 * sense code should be RESERVATIONS
8772				 * RELEASED
8773				 */
8774
8775				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8776					if (lun->pr_keys[i+
8777					    persis_offset] == 0)
8778						continue;
8779
8780					lun->pending_ua[i] |=
8781						CTL_UA_RES_RELEASE;
8782				}
8783			}
8784			lun->res_type = 0;
8785		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8786			if (lun->pr_key_count==0) {
8787				lun->flags &= ~CTL_LUN_PR_RESERVED;
8788				lun->res_type = 0;
8789				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8790			}
8791		}
8792		lun->PRGeneration++;
8793		break;
8794
8795	case CTL_PR_RESERVE:
8796		lun->flags |= CTL_LUN_PR_RESERVED;
8797		lun->res_type = msg->pr.pr_info.res_type;
8798		lun->pr_res_idx = msg->pr.pr_info.residx;
8799
8800		break;
8801
8802	case CTL_PR_RELEASE:
8803		/*
8804		 * if this isn't an exclusive access res generate UA for all
8805		 * other registrants.
8806		 */
8807		if (lun->res_type != SPR_TYPE_EX_AC
8808		 && lun->res_type != SPR_TYPE_WR_EX) {
8809			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8810				if (lun->pr_keys[i+persis_offset] != 0)
8811					lun->pending_ua[i] |=
8812						CTL_UA_RES_RELEASE;
8813		}
8814
8815		lun->flags &= ~CTL_LUN_PR_RESERVED;
8816		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8817		lun->res_type = 0;
8818		break;
8819
8820	case CTL_PR_PREEMPT:
8821		ctl_pro_preempt_other(lun, msg);
8822		break;
8823	case CTL_PR_CLEAR:
8824		lun->flags &= ~CTL_LUN_PR_RESERVED;
8825		lun->res_type = 0;
8826		lun->pr_key_count = 0;
8827		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8828
8829		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8830			if (lun->pr_keys[i] == 0)
8831				continue;
8832			if (!persis_offset
8833			 && i < CTL_MAX_INITIATORS)
8834				lun->pending_ua[i] |= CTL_UA_RES_PREEMPT;
8835			else if (persis_offset
8836			      && i >= persis_offset)
8837				lun->pending_ua[i-persis_offset] |=
8838					CTL_UA_RES_PREEMPT;
8839			lun->pr_keys[i] = 0;
8840		}
8841		lun->PRGeneration++;
8842		break;
8843	}
8844
8845	mtx_unlock(&lun->lun_lock);
8846}
8847
8848int
8849ctl_read_write(struct ctl_scsiio *ctsio)
8850{
8851	struct ctl_lun *lun;
8852	struct ctl_lba_len_flags *lbalen;
8853	uint64_t lba;
8854	uint32_t num_blocks;
8855	int flags, retval;
8856	int isread;
8857
8858	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8859
8860	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8861
8862	flags = 0;
8863	retval = CTL_RETVAL_COMPLETE;
8864
8865	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8866	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8867	switch (ctsio->cdb[0]) {
8868	case READ_6:
8869	case WRITE_6: {
8870		struct scsi_rw_6 *cdb;
8871
8872		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8873
8874		lba = scsi_3btoul(cdb->addr);
8875		/* only 5 bits are valid in the most significant address byte */
8876		lba &= 0x1fffff;
8877		num_blocks = cdb->length;
8878		/*
8879		 * This is correct according to SBC-2.
8880		 */
8881		if (num_blocks == 0)
8882			num_blocks = 256;
8883		break;
8884	}
8885	case READ_10:
8886	case WRITE_10: {
8887		struct scsi_rw_10 *cdb;
8888
8889		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8890		if (cdb->byte2 & SRW10_FUA)
8891			flags |= CTL_LLF_FUA;
8892		if (cdb->byte2 & SRW10_DPO)
8893			flags |= CTL_LLF_DPO;
8894		lba = scsi_4btoul(cdb->addr);
8895		num_blocks = scsi_2btoul(cdb->length);
8896		break;
8897	}
8898	case WRITE_VERIFY_10: {
8899		struct scsi_write_verify_10 *cdb;
8900
8901		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8902		flags |= CTL_LLF_FUA;
8903		if (cdb->byte2 & SWV_DPO)
8904			flags |= CTL_LLF_DPO;
8905		lba = scsi_4btoul(cdb->addr);
8906		num_blocks = scsi_2btoul(cdb->length);
8907		break;
8908	}
8909	case READ_12:
8910	case WRITE_12: {
8911		struct scsi_rw_12 *cdb;
8912
8913		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8914		if (cdb->byte2 & SRW12_FUA)
8915			flags |= CTL_LLF_FUA;
8916		if (cdb->byte2 & SRW12_DPO)
8917			flags |= CTL_LLF_DPO;
8918		lba = scsi_4btoul(cdb->addr);
8919		num_blocks = scsi_4btoul(cdb->length);
8920		break;
8921	}
8922	case WRITE_VERIFY_12: {
8923		struct scsi_write_verify_12 *cdb;
8924
8925		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8926		flags |= CTL_LLF_FUA;
8927		if (cdb->byte2 & SWV_DPO)
8928			flags |= CTL_LLF_DPO;
8929		lba = scsi_4btoul(cdb->addr);
8930		num_blocks = scsi_4btoul(cdb->length);
8931		break;
8932	}
8933	case READ_16:
8934	case WRITE_16: {
8935		struct scsi_rw_16 *cdb;
8936
8937		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8938		if (cdb->byte2 & SRW12_FUA)
8939			flags |= CTL_LLF_FUA;
8940		if (cdb->byte2 & SRW12_DPO)
8941			flags |= CTL_LLF_DPO;
8942		lba = scsi_8btou64(cdb->addr);
8943		num_blocks = scsi_4btoul(cdb->length);
8944		break;
8945	}
8946	case WRITE_ATOMIC_16: {
8947		struct scsi_rw_16 *cdb;
8948
8949		if (lun->be_lun->atomicblock == 0) {
8950			ctl_set_invalid_opcode(ctsio);
8951			ctl_done((union ctl_io *)ctsio);
8952			return (CTL_RETVAL_COMPLETE);
8953		}
8954
8955		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8956		if (cdb->byte2 & SRW12_FUA)
8957			flags |= CTL_LLF_FUA;
8958		if (cdb->byte2 & SRW12_DPO)
8959			flags |= CTL_LLF_DPO;
8960		lba = scsi_8btou64(cdb->addr);
8961		num_blocks = scsi_4btoul(cdb->length);
8962		if (num_blocks > lun->be_lun->atomicblock) {
8963			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8964			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8965			    /*bit*/ 0);
8966			ctl_done((union ctl_io *)ctsio);
8967			return (CTL_RETVAL_COMPLETE);
8968		}
8969		break;
8970	}
8971	case WRITE_VERIFY_16: {
8972		struct scsi_write_verify_16 *cdb;
8973
8974		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8975		flags |= CTL_LLF_FUA;
8976		if (cdb->byte2 & SWV_DPO)
8977			flags |= CTL_LLF_DPO;
8978		lba = scsi_8btou64(cdb->addr);
8979		num_blocks = scsi_4btoul(cdb->length);
8980		break;
8981	}
8982	default:
8983		/*
8984		 * We got a command we don't support.  This shouldn't
8985		 * happen, commands should be filtered out above us.
8986		 */
8987		ctl_set_invalid_opcode(ctsio);
8988		ctl_done((union ctl_io *)ctsio);
8989
8990		return (CTL_RETVAL_COMPLETE);
8991		break; /* NOTREACHED */
8992	}
8993
8994	/*
8995	 * The first check is to make sure we're in bounds, the second
8996	 * check is to catch wrap-around problems.  If the lba + num blocks
8997	 * is less than the lba, then we've wrapped around and the block
8998	 * range is invalid anyway.
8999	 */
9000	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9001	 || ((lba + num_blocks) < lba)) {
9002		ctl_set_lba_out_of_range(ctsio);
9003		ctl_done((union ctl_io *)ctsio);
9004		return (CTL_RETVAL_COMPLETE);
9005	}
9006
9007	/*
9008	 * According to SBC-3, a transfer length of 0 is not an error.
9009	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
9010	 * translates to 256 blocks for those commands.
9011	 */
9012	if (num_blocks == 0) {
9013		ctl_set_success(ctsio);
9014		ctl_done((union ctl_io *)ctsio);
9015		return (CTL_RETVAL_COMPLETE);
9016	}
9017
9018	/* Set FUA and/or DPO if caches are disabled. */
9019	if (isread) {
9020		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9021		    SCP_RCD) != 0)
9022			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9023	} else {
9024		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9025		    SCP_WCE) == 0)
9026			flags |= CTL_LLF_FUA;
9027	}
9028
9029	lbalen = (struct ctl_lba_len_flags *)
9030	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9031	lbalen->lba = lba;
9032	lbalen->len = num_blocks;
9033	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9034
9035	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9036	ctsio->kern_rel_offset = 0;
9037
9038	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9039
9040	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9041
9042	return (retval);
9043}
9044
9045static int
9046ctl_cnw_cont(union ctl_io *io)
9047{
9048	struct ctl_scsiio *ctsio;
9049	struct ctl_lun *lun;
9050	struct ctl_lba_len_flags *lbalen;
9051	int retval;
9052
9053	ctsio = &io->scsiio;
9054	ctsio->io_hdr.status = CTL_STATUS_NONE;
9055	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9056	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9057	lbalen = (struct ctl_lba_len_flags *)
9058	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9059	lbalen->flags &= ~CTL_LLF_COMPARE;
9060	lbalen->flags |= CTL_LLF_WRITE;
9061
9062	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9063	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9064	return (retval);
9065}
9066
9067int
9068ctl_cnw(struct ctl_scsiio *ctsio)
9069{
9070	struct ctl_lun *lun;
9071	struct ctl_lba_len_flags *lbalen;
9072	uint64_t lba;
9073	uint32_t num_blocks;
9074	int flags, retval;
9075
9076	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9077
9078	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9079
9080	flags = 0;
9081	retval = CTL_RETVAL_COMPLETE;
9082
9083	switch (ctsio->cdb[0]) {
9084	case COMPARE_AND_WRITE: {
9085		struct scsi_compare_and_write *cdb;
9086
9087		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9088		if (cdb->byte2 & SRW10_FUA)
9089			flags |= CTL_LLF_FUA;
9090		if (cdb->byte2 & SRW10_DPO)
9091			flags |= CTL_LLF_DPO;
9092		lba = scsi_8btou64(cdb->addr);
9093		num_blocks = cdb->length;
9094		break;
9095	}
9096	default:
9097		/*
9098		 * We got a command we don't support.  This shouldn't
9099		 * happen, commands should be filtered out above us.
9100		 */
9101		ctl_set_invalid_opcode(ctsio);
9102		ctl_done((union ctl_io *)ctsio);
9103
9104		return (CTL_RETVAL_COMPLETE);
9105		break; /* NOTREACHED */
9106	}
9107
9108	/*
9109	 * The first check is to make sure we're in bounds, the second
9110	 * check is to catch wrap-around problems.  If the lba + num blocks
9111	 * is less than the lba, then we've wrapped around and the block
9112	 * range is invalid anyway.
9113	 */
9114	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9115	 || ((lba + num_blocks) < lba)) {
9116		ctl_set_lba_out_of_range(ctsio);
9117		ctl_done((union ctl_io *)ctsio);
9118		return (CTL_RETVAL_COMPLETE);
9119	}
9120
9121	/*
9122	 * According to SBC-3, a transfer length of 0 is not an error.
9123	 */
9124	if (num_blocks == 0) {
9125		ctl_set_success(ctsio);
9126		ctl_done((union ctl_io *)ctsio);
9127		return (CTL_RETVAL_COMPLETE);
9128	}
9129
9130	/* Set FUA if write cache is disabled. */
9131	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9132	    SCP_WCE) == 0)
9133		flags |= CTL_LLF_FUA;
9134
9135	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9136	ctsio->kern_rel_offset = 0;
9137
9138	/*
9139	 * Set the IO_CONT flag, so that if this I/O gets passed to
9140	 * ctl_data_submit_done(), it'll get passed back to
9141	 * ctl_ctl_cnw_cont() for further processing.
9142	 */
9143	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9144	ctsio->io_cont = ctl_cnw_cont;
9145
9146	lbalen = (struct ctl_lba_len_flags *)
9147	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9148	lbalen->lba = lba;
9149	lbalen->len = num_blocks;
9150	lbalen->flags = CTL_LLF_COMPARE | flags;
9151
9152	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9153	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9154	return (retval);
9155}
9156
9157int
9158ctl_verify(struct ctl_scsiio *ctsio)
9159{
9160	struct ctl_lun *lun;
9161	struct ctl_lba_len_flags *lbalen;
9162	uint64_t lba;
9163	uint32_t num_blocks;
9164	int bytchk, flags;
9165	int retval;
9166
9167	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9168
9169	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9170
9171	bytchk = 0;
9172	flags = CTL_LLF_FUA;
9173	retval = CTL_RETVAL_COMPLETE;
9174
9175	switch (ctsio->cdb[0]) {
9176	case VERIFY_10: {
9177		struct scsi_verify_10 *cdb;
9178
9179		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9180		if (cdb->byte2 & SVFY_BYTCHK)
9181			bytchk = 1;
9182		if (cdb->byte2 & SVFY_DPO)
9183			flags |= CTL_LLF_DPO;
9184		lba = scsi_4btoul(cdb->addr);
9185		num_blocks = scsi_2btoul(cdb->length);
9186		break;
9187	}
9188	case VERIFY_12: {
9189		struct scsi_verify_12 *cdb;
9190
9191		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9192		if (cdb->byte2 & SVFY_BYTCHK)
9193			bytchk = 1;
9194		if (cdb->byte2 & SVFY_DPO)
9195			flags |= CTL_LLF_DPO;
9196		lba = scsi_4btoul(cdb->addr);
9197		num_blocks = scsi_4btoul(cdb->length);
9198		break;
9199	}
9200	case VERIFY_16: {
9201		struct scsi_rw_16 *cdb;
9202
9203		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9204		if (cdb->byte2 & SVFY_BYTCHK)
9205			bytchk = 1;
9206		if (cdb->byte2 & SVFY_DPO)
9207			flags |= CTL_LLF_DPO;
9208		lba = scsi_8btou64(cdb->addr);
9209		num_blocks = scsi_4btoul(cdb->length);
9210		break;
9211	}
9212	default:
9213		/*
9214		 * We got a command we don't support.  This shouldn't
9215		 * happen, commands should be filtered out above us.
9216		 */
9217		ctl_set_invalid_opcode(ctsio);
9218		ctl_done((union ctl_io *)ctsio);
9219		return (CTL_RETVAL_COMPLETE);
9220	}
9221
9222	/*
9223	 * The first check is to make sure we're in bounds, the second
9224	 * check is to catch wrap-around problems.  If the lba + num blocks
9225	 * is less than the lba, then we've wrapped around and the block
9226	 * range is invalid anyway.
9227	 */
9228	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9229	 || ((lba + num_blocks) < lba)) {
9230		ctl_set_lba_out_of_range(ctsio);
9231		ctl_done((union ctl_io *)ctsio);
9232		return (CTL_RETVAL_COMPLETE);
9233	}
9234
9235	/*
9236	 * According to SBC-3, a transfer length of 0 is not an error.
9237	 */
9238	if (num_blocks == 0) {
9239		ctl_set_success(ctsio);
9240		ctl_done((union ctl_io *)ctsio);
9241		return (CTL_RETVAL_COMPLETE);
9242	}
9243
9244	lbalen = (struct ctl_lba_len_flags *)
9245	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9246	lbalen->lba = lba;
9247	lbalen->len = num_blocks;
9248	if (bytchk) {
9249		lbalen->flags = CTL_LLF_COMPARE | flags;
9250		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9251	} else {
9252		lbalen->flags = CTL_LLF_VERIFY | flags;
9253		ctsio->kern_total_len = 0;
9254	}
9255	ctsio->kern_rel_offset = 0;
9256
9257	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9258	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9259	return (retval);
9260}
9261
9262int
9263ctl_report_luns(struct ctl_scsiio *ctsio)
9264{
9265	struct scsi_report_luns *cdb;
9266	struct scsi_report_luns_data *lun_data;
9267	struct ctl_lun *lun, *request_lun;
9268	int num_luns, retval;
9269	uint32_t alloc_len, lun_datalen;
9270	int num_filled, well_known;
9271	uint32_t initidx, targ_lun_id, lun_id;
9272
9273	retval = CTL_RETVAL_COMPLETE;
9274	well_known = 0;
9275
9276	cdb = (struct scsi_report_luns *)ctsio->cdb;
9277
9278	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9279
9280	mtx_lock(&control_softc->ctl_lock);
9281	num_luns = control_softc->num_luns;
9282	mtx_unlock(&control_softc->ctl_lock);
9283
9284	switch (cdb->select_report) {
9285	case RPL_REPORT_DEFAULT:
9286	case RPL_REPORT_ALL:
9287		break;
9288	case RPL_REPORT_WELLKNOWN:
9289		well_known = 1;
9290		num_luns = 0;
9291		break;
9292	default:
9293		ctl_set_invalid_field(ctsio,
9294				      /*sks_valid*/ 1,
9295				      /*command*/ 1,
9296				      /*field*/ 2,
9297				      /*bit_valid*/ 0,
9298				      /*bit*/ 0);
9299		ctl_done((union ctl_io *)ctsio);
9300		return (retval);
9301		break; /* NOTREACHED */
9302	}
9303
9304	alloc_len = scsi_4btoul(cdb->length);
9305	/*
9306	 * The initiator has to allocate at least 16 bytes for this request,
9307	 * so he can at least get the header and the first LUN.  Otherwise
9308	 * we reject the request (per SPC-3 rev 14, section 6.21).
9309	 */
9310	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9311	    sizeof(struct scsi_report_luns_lundata))) {
9312		ctl_set_invalid_field(ctsio,
9313				      /*sks_valid*/ 1,
9314				      /*command*/ 1,
9315				      /*field*/ 6,
9316				      /*bit_valid*/ 0,
9317				      /*bit*/ 0);
9318		ctl_done((union ctl_io *)ctsio);
9319		return (retval);
9320	}
9321
9322	request_lun = (struct ctl_lun *)
9323		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9324
9325	lun_datalen = sizeof(*lun_data) +
9326		(num_luns * sizeof(struct scsi_report_luns_lundata));
9327
9328	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9329	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9330	ctsio->kern_sg_entries = 0;
9331
9332	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9333
9334	mtx_lock(&control_softc->ctl_lock);
9335	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9336		lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9337		if (lun_id >= CTL_MAX_LUNS)
9338			continue;
9339		lun = control_softc->ctl_luns[lun_id];
9340		if (lun == NULL)
9341			continue;
9342
9343		if (targ_lun_id <= 0xff) {
9344			/*
9345			 * Peripheral addressing method, bus number 0.
9346			 */
9347			lun_data->luns[num_filled].lundata[0] =
9348				RPL_LUNDATA_ATYP_PERIPH;
9349			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9350			num_filled++;
9351		} else if (targ_lun_id <= 0x3fff) {
9352			/*
9353			 * Flat addressing method.
9354			 */
9355			lun_data->luns[num_filled].lundata[0] =
9356				RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9357			lun_data->luns[num_filled].lundata[1] =
9358				(targ_lun_id & 0xff);
9359			num_filled++;
9360		} else if (targ_lun_id <= 0xffffff) {
9361			/*
9362			 * Extended flat addressing method.
9363			 */
9364			lun_data->luns[num_filled].lundata[0] =
9365			    RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9366			scsi_ulto3b(targ_lun_id,
9367			    &lun_data->luns[num_filled].lundata[1]);
9368			num_filled++;
9369		} else {
9370			printf("ctl_report_luns: bogus LUN number %jd, "
9371			       "skipping\n", (intmax_t)targ_lun_id);
9372		}
9373		/*
9374		 * According to SPC-3, rev 14 section 6.21:
9375		 *
9376		 * "The execution of a REPORT LUNS command to any valid and
9377		 * installed logical unit shall clear the REPORTED LUNS DATA
9378		 * HAS CHANGED unit attention condition for all logical
9379		 * units of that target with respect to the requesting
9380		 * initiator. A valid and installed logical unit is one
9381		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9382		 * INQUIRY data (see 6.4.2)."
9383		 *
9384		 * If request_lun is NULL, the LUN this report luns command
9385		 * was issued to is either disabled or doesn't exist. In that
9386		 * case, we shouldn't clear any pending lun change unit
9387		 * attention.
9388		 */
9389		if (request_lun != NULL) {
9390			mtx_lock(&lun->lun_lock);
9391			lun->pending_ua[initidx] &= ~CTL_UA_LUN_CHANGE;
9392			mtx_unlock(&lun->lun_lock);
9393		}
9394	}
9395	mtx_unlock(&control_softc->ctl_lock);
9396
9397	/*
9398	 * It's quite possible that we've returned fewer LUNs than we allocated
9399	 * space for.  Trim it.
9400	 */
9401	lun_datalen = sizeof(*lun_data) +
9402		(num_filled * sizeof(struct scsi_report_luns_lundata));
9403
9404	if (lun_datalen < alloc_len) {
9405		ctsio->residual = alloc_len - lun_datalen;
9406		ctsio->kern_data_len = lun_datalen;
9407		ctsio->kern_total_len = lun_datalen;
9408	} else {
9409		ctsio->residual = 0;
9410		ctsio->kern_data_len = alloc_len;
9411		ctsio->kern_total_len = alloc_len;
9412	}
9413	ctsio->kern_data_resid = 0;
9414	ctsio->kern_rel_offset = 0;
9415	ctsio->kern_sg_entries = 0;
9416
9417	/*
9418	 * We set this to the actual data length, regardless of how much
9419	 * space we actually have to return results.  If the user looks at
9420	 * this value, he'll know whether or not he allocated enough space
9421	 * and reissue the command if necessary.  We don't support well
9422	 * known logical units, so if the user asks for that, return none.
9423	 */
9424	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9425
9426	/*
9427	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9428	 * this request.
9429	 */
9430	ctsio->scsi_status = SCSI_STATUS_OK;
9431
9432	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9433	ctsio->be_move_done = ctl_config_move_done;
9434	ctl_datamove((union ctl_io *)ctsio);
9435
9436	return (retval);
9437}
9438
9439int
9440ctl_request_sense(struct ctl_scsiio *ctsio)
9441{
9442	struct scsi_request_sense *cdb;
9443	struct scsi_sense_data *sense_ptr;
9444	struct ctl_lun *lun;
9445	uint32_t initidx;
9446	int have_error;
9447	scsi_sense_data_type sense_format;
9448
9449	cdb = (struct scsi_request_sense *)ctsio->cdb;
9450
9451	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9452
9453	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9454
9455	/*
9456	 * Determine which sense format the user wants.
9457	 */
9458	if (cdb->byte2 & SRS_DESC)
9459		sense_format = SSD_TYPE_DESC;
9460	else
9461		sense_format = SSD_TYPE_FIXED;
9462
9463	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9464	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9465	ctsio->kern_sg_entries = 0;
9466
9467	/*
9468	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9469	 * larger than the largest allowed value for the length field in the
9470	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9471	 */
9472	ctsio->residual = 0;
9473	ctsio->kern_data_len = cdb->length;
9474	ctsio->kern_total_len = cdb->length;
9475
9476	ctsio->kern_data_resid = 0;
9477	ctsio->kern_rel_offset = 0;
9478	ctsio->kern_sg_entries = 0;
9479
9480	/*
9481	 * If we don't have a LUN, we don't have any pending sense.
9482	 */
9483	if (lun == NULL)
9484		goto no_sense;
9485
9486	have_error = 0;
9487	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9488	/*
9489	 * Check for pending sense, and then for pending unit attentions.
9490	 * Pending sense gets returned first, then pending unit attentions.
9491	 */
9492	mtx_lock(&lun->lun_lock);
9493#ifdef CTL_WITH_CA
9494	if (ctl_is_set(lun->have_ca, initidx)) {
9495		scsi_sense_data_type stored_format;
9496
9497		/*
9498		 * Check to see which sense format was used for the stored
9499		 * sense data.
9500		 */
9501		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9502
9503		/*
9504		 * If the user requested a different sense format than the
9505		 * one we stored, then we need to convert it to the other
9506		 * format.  If we're going from descriptor to fixed format
9507		 * sense data, we may lose things in translation, depending
9508		 * on what options were used.
9509		 *
9510		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9511		 * for some reason we'll just copy it out as-is.
9512		 */
9513		if ((stored_format == SSD_TYPE_FIXED)
9514		 && (sense_format == SSD_TYPE_DESC))
9515			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9516			    &lun->pending_sense[initidx],
9517			    (struct scsi_sense_data_desc *)sense_ptr);
9518		else if ((stored_format == SSD_TYPE_DESC)
9519		      && (sense_format == SSD_TYPE_FIXED))
9520			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9521			    &lun->pending_sense[initidx],
9522			    (struct scsi_sense_data_fixed *)sense_ptr);
9523		else
9524			memcpy(sense_ptr, &lun->pending_sense[initidx],
9525			       ctl_min(sizeof(*sense_ptr),
9526			       sizeof(lun->pending_sense[initidx])));
9527
9528		ctl_clear_mask(lun->have_ca, initidx);
9529		have_error = 1;
9530	} else
9531#endif
9532	if (lun->pending_ua[initidx] != CTL_UA_NONE) {
9533		ctl_ua_type ua_type;
9534
9535		ua_type = ctl_build_ua(&lun->pending_ua[initidx],
9536				       sense_ptr, sense_format);
9537		if (ua_type != CTL_UA_NONE)
9538			have_error = 1;
9539	}
9540	mtx_unlock(&lun->lun_lock);
9541
9542	/*
9543	 * We already have a pending error, return it.
9544	 */
9545	if (have_error != 0) {
9546		/*
9547		 * We report the SCSI status as OK, since the status of the
9548		 * request sense command itself is OK.
9549		 */
9550		ctsio->scsi_status = SCSI_STATUS_OK;
9551
9552		/*
9553		 * We report 0 for the sense length, because we aren't doing
9554		 * autosense in this case.  We're reporting sense as
9555		 * parameter data.
9556		 */
9557		ctsio->sense_len = 0;
9558		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9559		ctsio->be_move_done = ctl_config_move_done;
9560		ctl_datamove((union ctl_io *)ctsio);
9561
9562		return (CTL_RETVAL_COMPLETE);
9563	}
9564
9565no_sense:
9566
9567	/*
9568	 * No sense information to report, so we report that everything is
9569	 * okay.
9570	 */
9571	ctl_set_sense_data(sense_ptr,
9572			   lun,
9573			   sense_format,
9574			   /*current_error*/ 1,
9575			   /*sense_key*/ SSD_KEY_NO_SENSE,
9576			   /*asc*/ 0x00,
9577			   /*ascq*/ 0x00,
9578			   SSD_ELEM_NONE);
9579
9580	ctsio->scsi_status = SCSI_STATUS_OK;
9581
9582	/*
9583	 * We report 0 for the sense length, because we aren't doing
9584	 * autosense in this case.  We're reporting sense as parameter data.
9585	 */
9586	ctsio->sense_len = 0;
9587	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9588	ctsio->be_move_done = ctl_config_move_done;
9589	ctl_datamove((union ctl_io *)ctsio);
9590
9591	return (CTL_RETVAL_COMPLETE);
9592}
9593
9594int
9595ctl_tur(struct ctl_scsiio *ctsio)
9596{
9597
9598	CTL_DEBUG_PRINT(("ctl_tur\n"));
9599
9600	ctl_set_success(ctsio);
9601	ctl_done((union ctl_io *)ctsio);
9602
9603	return (CTL_RETVAL_COMPLETE);
9604}
9605
9606#ifdef notyet
9607static int
9608ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9609{
9610
9611}
9612#endif
9613
9614static int
9615ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9616{
9617	struct scsi_vpd_supported_pages *pages;
9618	int sup_page_size;
9619	struct ctl_lun *lun;
9620
9621	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9622
9623	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9624	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9625	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9626	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9627	ctsio->kern_sg_entries = 0;
9628
9629	if (sup_page_size < alloc_len) {
9630		ctsio->residual = alloc_len - sup_page_size;
9631		ctsio->kern_data_len = sup_page_size;
9632		ctsio->kern_total_len = sup_page_size;
9633	} else {
9634		ctsio->residual = 0;
9635		ctsio->kern_data_len = alloc_len;
9636		ctsio->kern_total_len = alloc_len;
9637	}
9638	ctsio->kern_data_resid = 0;
9639	ctsio->kern_rel_offset = 0;
9640	ctsio->kern_sg_entries = 0;
9641
9642	/*
9643	 * The control device is always connected.  The disk device, on the
9644	 * other hand, may not be online all the time.  Need to change this
9645	 * to figure out whether the disk device is actually online or not.
9646	 */
9647	if (lun != NULL)
9648		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9649				lun->be_lun->lun_type;
9650	else
9651		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9652
9653	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9654	/* Supported VPD pages */
9655	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9656	/* Serial Number */
9657	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9658	/* Device Identification */
9659	pages->page_list[2] = SVPD_DEVICE_ID;
9660	/* Extended INQUIRY Data */
9661	pages->page_list[3] = SVPD_EXTENDED_INQUIRY_DATA;
9662	/* Mode Page Policy */
9663	pages->page_list[4] = SVPD_MODE_PAGE_POLICY;
9664	/* SCSI Ports */
9665	pages->page_list[5] = SVPD_SCSI_PORTS;
9666	/* Third-party Copy */
9667	pages->page_list[6] = SVPD_SCSI_TPC;
9668	/* Block limits */
9669	pages->page_list[7] = SVPD_BLOCK_LIMITS;
9670	/* Block Device Characteristics */
9671	pages->page_list[8] = SVPD_BDC;
9672	/* Logical Block Provisioning */
9673	pages->page_list[9] = SVPD_LBP;
9674
9675	ctsio->scsi_status = SCSI_STATUS_OK;
9676
9677	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9678	ctsio->be_move_done = ctl_config_move_done;
9679	ctl_datamove((union ctl_io *)ctsio);
9680
9681	return (CTL_RETVAL_COMPLETE);
9682}
9683
9684static int
9685ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9686{
9687	struct scsi_vpd_unit_serial_number *sn_ptr;
9688	struct ctl_lun *lun;
9689	int data_len;
9690
9691	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9692
9693	data_len = 4 + CTL_SN_LEN;
9694	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9695	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9696	if (data_len < alloc_len) {
9697		ctsio->residual = alloc_len - data_len;
9698		ctsio->kern_data_len = data_len;
9699		ctsio->kern_total_len = data_len;
9700	} else {
9701		ctsio->residual = 0;
9702		ctsio->kern_data_len = alloc_len;
9703		ctsio->kern_total_len = alloc_len;
9704	}
9705	ctsio->kern_data_resid = 0;
9706	ctsio->kern_rel_offset = 0;
9707	ctsio->kern_sg_entries = 0;
9708
9709	/*
9710	 * The control device is always connected.  The disk device, on the
9711	 * other hand, may not be online all the time.  Need to change this
9712	 * to figure out whether the disk device is actually online or not.
9713	 */
9714	if (lun != NULL)
9715		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9716				  lun->be_lun->lun_type;
9717	else
9718		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9719
9720	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9721	sn_ptr->length = CTL_SN_LEN;
9722	/*
9723	 * If we don't have a LUN, we just leave the serial number as
9724	 * all spaces.
9725	 */
9726	if (lun != NULL) {
9727		strncpy((char *)sn_ptr->serial_num,
9728			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9729	} else
9730		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9731	ctsio->scsi_status = SCSI_STATUS_OK;
9732
9733	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9734	ctsio->be_move_done = ctl_config_move_done;
9735	ctl_datamove((union ctl_io *)ctsio);
9736
9737	return (CTL_RETVAL_COMPLETE);
9738}
9739
9740
9741static int
9742ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9743{
9744	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9745	struct ctl_lun *lun;
9746	int data_len;
9747
9748	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9749
9750	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9751	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9752	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9753	ctsio->kern_sg_entries = 0;
9754
9755	if (data_len < alloc_len) {
9756		ctsio->residual = alloc_len - data_len;
9757		ctsio->kern_data_len = data_len;
9758		ctsio->kern_total_len = data_len;
9759	} else {
9760		ctsio->residual = 0;
9761		ctsio->kern_data_len = alloc_len;
9762		ctsio->kern_total_len = alloc_len;
9763	}
9764	ctsio->kern_data_resid = 0;
9765	ctsio->kern_rel_offset = 0;
9766	ctsio->kern_sg_entries = 0;
9767
9768	/*
9769	 * The control device is always connected.  The disk device, on the
9770	 * other hand, may not be online all the time.
9771	 */
9772	if (lun != NULL)
9773		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9774				     lun->be_lun->lun_type;
9775	else
9776		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9777	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9778	eid_ptr->page_length = data_len - 4;
9779	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9780	eid_ptr->flags3 = SVPD_EID_V_SUP;
9781
9782	ctsio->scsi_status = SCSI_STATUS_OK;
9783	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9784	ctsio->be_move_done = ctl_config_move_done;
9785	ctl_datamove((union ctl_io *)ctsio);
9786
9787	return (CTL_RETVAL_COMPLETE);
9788}
9789
9790static int
9791ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9792{
9793	struct scsi_vpd_mode_page_policy *mpp_ptr;
9794	struct ctl_lun *lun;
9795	int data_len;
9796
9797	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9798
9799	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9800	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9801
9802	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9803	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9804	ctsio->kern_sg_entries = 0;
9805
9806	if (data_len < alloc_len) {
9807		ctsio->residual = alloc_len - data_len;
9808		ctsio->kern_data_len = data_len;
9809		ctsio->kern_total_len = data_len;
9810	} else {
9811		ctsio->residual = 0;
9812		ctsio->kern_data_len = alloc_len;
9813		ctsio->kern_total_len = alloc_len;
9814	}
9815	ctsio->kern_data_resid = 0;
9816	ctsio->kern_rel_offset = 0;
9817	ctsio->kern_sg_entries = 0;
9818
9819	/*
9820	 * The control device is always connected.  The disk device, on the
9821	 * other hand, may not be online all the time.
9822	 */
9823	if (lun != NULL)
9824		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9825				     lun->be_lun->lun_type;
9826	else
9827		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9828	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9829	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9830	mpp_ptr->descr[0].page_code = 0x3f;
9831	mpp_ptr->descr[0].subpage_code = 0xff;
9832	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9833
9834	ctsio->scsi_status = SCSI_STATUS_OK;
9835	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9836	ctsio->be_move_done = ctl_config_move_done;
9837	ctl_datamove((union ctl_io *)ctsio);
9838
9839	return (CTL_RETVAL_COMPLETE);
9840}
9841
9842static int
9843ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9844{
9845	struct scsi_vpd_device_id *devid_ptr;
9846	struct scsi_vpd_id_descriptor *desc;
9847	struct ctl_softc *ctl_softc;
9848	struct ctl_lun *lun;
9849	struct ctl_port *port;
9850	int data_len;
9851	uint8_t proto;
9852
9853	ctl_softc = control_softc;
9854
9855	port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9856	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9857
9858	data_len = sizeof(struct scsi_vpd_device_id) +
9859	    sizeof(struct scsi_vpd_id_descriptor) +
9860		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9861	    sizeof(struct scsi_vpd_id_descriptor) +
9862		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9863	if (lun && lun->lun_devid)
9864		data_len += lun->lun_devid->len;
9865	if (port->port_devid)
9866		data_len += port->port_devid->len;
9867	if (port->target_devid)
9868		data_len += port->target_devid->len;
9869
9870	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9871	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9872	ctsio->kern_sg_entries = 0;
9873
9874	if (data_len < alloc_len) {
9875		ctsio->residual = alloc_len - data_len;
9876		ctsio->kern_data_len = data_len;
9877		ctsio->kern_total_len = data_len;
9878	} else {
9879		ctsio->residual = 0;
9880		ctsio->kern_data_len = alloc_len;
9881		ctsio->kern_total_len = alloc_len;
9882	}
9883	ctsio->kern_data_resid = 0;
9884	ctsio->kern_rel_offset = 0;
9885	ctsio->kern_sg_entries = 0;
9886
9887	/*
9888	 * The control device is always connected.  The disk device, on the
9889	 * other hand, may not be online all the time.
9890	 */
9891	if (lun != NULL)
9892		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9893				     lun->be_lun->lun_type;
9894	else
9895		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9896	devid_ptr->page_code = SVPD_DEVICE_ID;
9897	scsi_ulto2b(data_len - 4, devid_ptr->length);
9898
9899	if (port->port_type == CTL_PORT_FC)
9900		proto = SCSI_PROTO_FC << 4;
9901	else if (port->port_type == CTL_PORT_ISCSI)
9902		proto = SCSI_PROTO_ISCSI << 4;
9903	else
9904		proto = SCSI_PROTO_SPI << 4;
9905	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9906
9907	/*
9908	 * We're using a LUN association here.  i.e., this device ID is a
9909	 * per-LUN identifier.
9910	 */
9911	if (lun && lun->lun_devid) {
9912		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9913		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9914		    lun->lun_devid->len);
9915	}
9916
9917	/*
9918	 * This is for the WWPN which is a port association.
9919	 */
9920	if (port->port_devid) {
9921		memcpy(desc, port->port_devid->data, port->port_devid->len);
9922		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9923		    port->port_devid->len);
9924	}
9925
9926	/*
9927	 * This is for the Relative Target Port(type 4h) identifier
9928	 */
9929	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9930	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9931	    SVPD_ID_TYPE_RELTARG;
9932	desc->length = 4;
9933	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9934	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9935	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9936
9937	/*
9938	 * This is for the Target Port Group(type 5h) identifier
9939	 */
9940	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9941	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9942	    SVPD_ID_TYPE_TPORTGRP;
9943	desc->length = 4;
9944	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
9945	    &desc->identifier[2]);
9946	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9947	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9948
9949	/*
9950	 * This is for the Target identifier
9951	 */
9952	if (port->target_devid) {
9953		memcpy(desc, port->target_devid->data, port->target_devid->len);
9954	}
9955
9956	ctsio->scsi_status = SCSI_STATUS_OK;
9957	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9958	ctsio->be_move_done = ctl_config_move_done;
9959	ctl_datamove((union ctl_io *)ctsio);
9960
9961	return (CTL_RETVAL_COMPLETE);
9962}
9963
9964static int
9965ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9966{
9967	struct ctl_softc *softc = control_softc;
9968	struct scsi_vpd_scsi_ports *sp;
9969	struct scsi_vpd_port_designation *pd;
9970	struct scsi_vpd_port_designation_cont *pdc;
9971	struct ctl_lun *lun;
9972	struct ctl_port *port;
9973	int data_len, num_target_ports, iid_len, id_len, g, pg, p;
9974	int num_target_port_groups;
9975
9976	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9977
9978	if (softc->is_single)
9979		num_target_port_groups = 1;
9980	else
9981		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
9982	num_target_ports = 0;
9983	iid_len = 0;
9984	id_len = 0;
9985	mtx_lock(&softc->ctl_lock);
9986	STAILQ_FOREACH(port, &softc->port_list, links) {
9987		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9988			continue;
9989		if (lun != NULL &&
9990		    ctl_map_lun_back(port->targ_port, lun->lun) >=
9991		    CTL_MAX_LUNS)
9992			continue;
9993		num_target_ports++;
9994		if (port->init_devid)
9995			iid_len += port->init_devid->len;
9996		if (port->port_devid)
9997			id_len += port->port_devid->len;
9998	}
9999	mtx_unlock(&softc->ctl_lock);
10000
10001	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10002	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10003	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10004	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10005	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10006	ctsio->kern_sg_entries = 0;
10007
10008	if (data_len < alloc_len) {
10009		ctsio->residual = alloc_len - data_len;
10010		ctsio->kern_data_len = data_len;
10011		ctsio->kern_total_len = data_len;
10012	} else {
10013		ctsio->residual = 0;
10014		ctsio->kern_data_len = alloc_len;
10015		ctsio->kern_total_len = alloc_len;
10016	}
10017	ctsio->kern_data_resid = 0;
10018	ctsio->kern_rel_offset = 0;
10019	ctsio->kern_sg_entries = 0;
10020
10021	/*
10022	 * The control device is always connected.  The disk device, on the
10023	 * other hand, may not be online all the time.  Need to change this
10024	 * to figure out whether the disk device is actually online or not.
10025	 */
10026	if (lun != NULL)
10027		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10028				  lun->be_lun->lun_type;
10029	else
10030		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10031
10032	sp->page_code = SVPD_SCSI_PORTS;
10033	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10034	    sp->page_length);
10035	pd = &sp->design[0];
10036
10037	mtx_lock(&softc->ctl_lock);
10038	pg = softc->port_offset / CTL_MAX_PORTS;
10039	for (g = 0; g < num_target_port_groups; g++) {
10040		STAILQ_FOREACH(port, &softc->port_list, links) {
10041			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10042				continue;
10043			if (lun != NULL &&
10044			    ctl_map_lun_back(port->targ_port, lun->lun) >=
10045			    CTL_MAX_LUNS)
10046				continue;
10047			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10048			scsi_ulto2b(p, pd->relative_port_id);
10049			if (port->init_devid && g == pg) {
10050				iid_len = port->init_devid->len;
10051				memcpy(pd->initiator_transportid,
10052				    port->init_devid->data, port->init_devid->len);
10053			} else
10054				iid_len = 0;
10055			scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10056			pdc = (struct scsi_vpd_port_designation_cont *)
10057			    (&pd->initiator_transportid[iid_len]);
10058			if (port->port_devid && g == pg) {
10059				id_len = port->port_devid->len;
10060				memcpy(pdc->target_port_descriptors,
10061				    port->port_devid->data, port->port_devid->len);
10062			} else
10063				id_len = 0;
10064			scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10065			pd = (struct scsi_vpd_port_designation *)
10066			    ((uint8_t *)pdc->target_port_descriptors + id_len);
10067		}
10068	}
10069	mtx_unlock(&softc->ctl_lock);
10070
10071	ctsio->scsi_status = SCSI_STATUS_OK;
10072	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10073	ctsio->be_move_done = ctl_config_move_done;
10074	ctl_datamove((union ctl_io *)ctsio);
10075
10076	return (CTL_RETVAL_COMPLETE);
10077}
10078
10079static int
10080ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10081{
10082	struct scsi_vpd_block_limits *bl_ptr;
10083	struct ctl_lun *lun;
10084	int bs;
10085
10086	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10087
10088	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10089	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10090	ctsio->kern_sg_entries = 0;
10091
10092	if (sizeof(*bl_ptr) < alloc_len) {
10093		ctsio->residual = alloc_len - sizeof(*bl_ptr);
10094		ctsio->kern_data_len = sizeof(*bl_ptr);
10095		ctsio->kern_total_len = sizeof(*bl_ptr);
10096	} else {
10097		ctsio->residual = 0;
10098		ctsio->kern_data_len = alloc_len;
10099		ctsio->kern_total_len = alloc_len;
10100	}
10101	ctsio->kern_data_resid = 0;
10102	ctsio->kern_rel_offset = 0;
10103	ctsio->kern_sg_entries = 0;
10104
10105	/*
10106	 * The control device is always connected.  The disk device, on the
10107	 * other hand, may not be online all the time.  Need to change this
10108	 * to figure out whether the disk device is actually online or not.
10109	 */
10110	if (lun != NULL)
10111		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10112				  lun->be_lun->lun_type;
10113	else
10114		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10115
10116	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10117	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10118	bl_ptr->max_cmp_write_len = 0xff;
10119	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10120	if (lun != NULL) {
10121		bs = lun->be_lun->blocksize;
10122		scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10123		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10124			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10125			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10126			if (lun->be_lun->pblockexp != 0) {
10127				scsi_ulto4b((1 << lun->be_lun->pblockexp),
10128				    bl_ptr->opt_unmap_grain);
10129				scsi_ulto4b(0x80000000 | lun->be_lun->pblockoff,
10130				    bl_ptr->unmap_grain_align);
10131			}
10132		}
10133		scsi_ulto4b(lun->be_lun->atomicblock,
10134		    bl_ptr->max_atomic_transfer_length);
10135		scsi_ulto4b(0, bl_ptr->atomic_alignment);
10136		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10137	}
10138	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10139
10140	ctsio->scsi_status = SCSI_STATUS_OK;
10141	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10142	ctsio->be_move_done = ctl_config_move_done;
10143	ctl_datamove((union ctl_io *)ctsio);
10144
10145	return (CTL_RETVAL_COMPLETE);
10146}
10147
10148static int
10149ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10150{
10151	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10152	struct ctl_lun *lun;
10153	const char *value;
10154	u_int i;
10155
10156	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10157
10158	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10159	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10160	ctsio->kern_sg_entries = 0;
10161
10162	if (sizeof(*bdc_ptr) < alloc_len) {
10163		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10164		ctsio->kern_data_len = sizeof(*bdc_ptr);
10165		ctsio->kern_total_len = sizeof(*bdc_ptr);
10166	} else {
10167		ctsio->residual = 0;
10168		ctsio->kern_data_len = alloc_len;
10169		ctsio->kern_total_len = alloc_len;
10170	}
10171	ctsio->kern_data_resid = 0;
10172	ctsio->kern_rel_offset = 0;
10173	ctsio->kern_sg_entries = 0;
10174
10175	/*
10176	 * The control device is always connected.  The disk device, on the
10177	 * other hand, may not be online all the time.  Need to change this
10178	 * to figure out whether the disk device is actually online or not.
10179	 */
10180	if (lun != NULL)
10181		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10182				  lun->be_lun->lun_type;
10183	else
10184		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10185	bdc_ptr->page_code = SVPD_BDC;
10186	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10187	if (lun != NULL &&
10188	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10189		i = strtol(value, NULL, 0);
10190	else
10191		i = CTL_DEFAULT_ROTATION_RATE;
10192	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10193	if (lun != NULL &&
10194	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10195		i = strtol(value, NULL, 0);
10196	else
10197		i = 0;
10198	bdc_ptr->wab_wac_ff = (i & 0x0f);
10199	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10200
10201	ctsio->scsi_status = SCSI_STATUS_OK;
10202	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10203	ctsio->be_move_done = ctl_config_move_done;
10204	ctl_datamove((union ctl_io *)ctsio);
10205
10206	return (CTL_RETVAL_COMPLETE);
10207}
10208
10209static int
10210ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10211{
10212	struct scsi_vpd_logical_block_prov *lbp_ptr;
10213	struct ctl_lun *lun;
10214
10215	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10216
10217	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10218	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10219	ctsio->kern_sg_entries = 0;
10220
10221	if (sizeof(*lbp_ptr) < alloc_len) {
10222		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10223		ctsio->kern_data_len = sizeof(*lbp_ptr);
10224		ctsio->kern_total_len = sizeof(*lbp_ptr);
10225	} else {
10226		ctsio->residual = 0;
10227		ctsio->kern_data_len = alloc_len;
10228		ctsio->kern_total_len = alloc_len;
10229	}
10230	ctsio->kern_data_resid = 0;
10231	ctsio->kern_rel_offset = 0;
10232	ctsio->kern_sg_entries = 0;
10233
10234	/*
10235	 * The control device is always connected.  The disk device, on the
10236	 * other hand, may not be online all the time.  Need to change this
10237	 * to figure out whether the disk device is actually online or not.
10238	 */
10239	if (lun != NULL)
10240		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10241				  lun->be_lun->lun_type;
10242	else
10243		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10244
10245	lbp_ptr->page_code = SVPD_LBP;
10246	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10247	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10248		lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10249		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10250		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10251		lbp_ptr->prov_type = SVPD_LBP_THIN;
10252	}
10253
10254	ctsio->scsi_status = SCSI_STATUS_OK;
10255	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10256	ctsio->be_move_done = ctl_config_move_done;
10257	ctl_datamove((union ctl_io *)ctsio);
10258
10259	return (CTL_RETVAL_COMPLETE);
10260}
10261
10262static int
10263ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10264{
10265	struct scsi_inquiry *cdb;
10266	int alloc_len, retval;
10267
10268	cdb = (struct scsi_inquiry *)ctsio->cdb;
10269
10270	retval = CTL_RETVAL_COMPLETE;
10271
10272	alloc_len = scsi_2btoul(cdb->length);
10273
10274	switch (cdb->page_code) {
10275	case SVPD_SUPPORTED_PAGES:
10276		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10277		break;
10278	case SVPD_UNIT_SERIAL_NUMBER:
10279		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10280		break;
10281	case SVPD_DEVICE_ID:
10282		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10283		break;
10284	case SVPD_EXTENDED_INQUIRY_DATA:
10285		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10286		break;
10287	case SVPD_MODE_PAGE_POLICY:
10288		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10289		break;
10290	case SVPD_SCSI_PORTS:
10291		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10292		break;
10293	case SVPD_SCSI_TPC:
10294		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10295		break;
10296	case SVPD_BLOCK_LIMITS:
10297		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10298		break;
10299	case SVPD_BDC:
10300		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10301		break;
10302	case SVPD_LBP:
10303		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10304		break;
10305	default:
10306		ctl_set_invalid_field(ctsio,
10307				      /*sks_valid*/ 1,
10308				      /*command*/ 1,
10309				      /*field*/ 2,
10310				      /*bit_valid*/ 0,
10311				      /*bit*/ 0);
10312		ctl_done((union ctl_io *)ctsio);
10313		retval = CTL_RETVAL_COMPLETE;
10314		break;
10315	}
10316
10317	return (retval);
10318}
10319
10320static int
10321ctl_inquiry_std(struct ctl_scsiio *ctsio)
10322{
10323	struct scsi_inquiry_data *inq_ptr;
10324	struct scsi_inquiry *cdb;
10325	struct ctl_softc *ctl_softc;
10326	struct ctl_lun *lun;
10327	char *val;
10328	uint32_t alloc_len, data_len;
10329	ctl_port_type port_type;
10330
10331	ctl_softc = control_softc;
10332
10333	/*
10334	 * Figure out whether we're talking to a Fibre Channel port or not.
10335	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10336	 * SCSI front ends.
10337	 */
10338	port_type = ctl_softc->ctl_ports[
10339	    ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10340	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10341		port_type = CTL_PORT_SCSI;
10342
10343	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10344	cdb = (struct scsi_inquiry *)ctsio->cdb;
10345	alloc_len = scsi_2btoul(cdb->length);
10346
10347	/*
10348	 * We malloc the full inquiry data size here and fill it
10349	 * in.  If the user only asks for less, we'll give him
10350	 * that much.
10351	 */
10352	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10353	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10354	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10355	ctsio->kern_sg_entries = 0;
10356	ctsio->kern_data_resid = 0;
10357	ctsio->kern_rel_offset = 0;
10358
10359	if (data_len < alloc_len) {
10360		ctsio->residual = alloc_len - data_len;
10361		ctsio->kern_data_len = data_len;
10362		ctsio->kern_total_len = data_len;
10363	} else {
10364		ctsio->residual = 0;
10365		ctsio->kern_data_len = alloc_len;
10366		ctsio->kern_total_len = alloc_len;
10367	}
10368
10369	/*
10370	 * If we have a LUN configured, report it as connected.  Otherwise,
10371	 * report that it is offline or no device is supported, depending
10372	 * on the value of inquiry_pq_no_lun.
10373	 *
10374	 * According to the spec (SPC-4 r34), the peripheral qualifier
10375	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10376	 *
10377	 * "A peripheral device having the specified peripheral device type
10378	 * is not connected to this logical unit. However, the device
10379	 * server is capable of supporting the specified peripheral device
10380	 * type on this logical unit."
10381	 *
10382	 * According to the same spec, the peripheral qualifier
10383	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10384	 *
10385	 * "The device server is not capable of supporting a peripheral
10386	 * device on this logical unit. For this peripheral qualifier the
10387	 * peripheral device type shall be set to 1Fh. All other peripheral
10388	 * device type values are reserved for this peripheral qualifier."
10389	 *
10390	 * Given the text, it would seem that we probably want to report that
10391	 * the LUN is offline here.  There is no LUN connected, but we can
10392	 * support a LUN at the given LUN number.
10393	 *
10394	 * In the real world, though, it sounds like things are a little
10395	 * different:
10396	 *
10397	 * - Linux, when presented with a LUN with the offline peripheral
10398	 *   qualifier, will create an sg driver instance for it.  So when
10399	 *   you attach it to CTL, you wind up with a ton of sg driver
10400	 *   instances.  (One for every LUN that Linux bothered to probe.)
10401	 *   Linux does this despite the fact that it issues a REPORT LUNs
10402	 *   to LUN 0 to get the inventory of supported LUNs.
10403	 *
10404	 * - There is other anecdotal evidence (from Emulex folks) about
10405	 *   arrays that use the offline peripheral qualifier for LUNs that
10406	 *   are on the "passive" path in an active/passive array.
10407	 *
10408	 * So the solution is provide a hopefully reasonable default
10409	 * (return bad/no LUN) and allow the user to change the behavior
10410	 * with a tunable/sysctl variable.
10411	 */
10412	if (lun != NULL)
10413		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10414				  lun->be_lun->lun_type;
10415	else if (ctl_softc->inquiry_pq_no_lun == 0)
10416		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10417	else
10418		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10419
10420	/* RMB in byte 2 is 0 */
10421	inq_ptr->version = SCSI_REV_SPC4;
10422
10423	/*
10424	 * According to SAM-3, even if a device only supports a single
10425	 * level of LUN addressing, it should still set the HISUP bit:
10426	 *
10427	 * 4.9.1 Logical unit numbers overview
10428	 *
10429	 * All logical unit number formats described in this standard are
10430	 * hierarchical in structure even when only a single level in that
10431	 * hierarchy is used. The HISUP bit shall be set to one in the
10432	 * standard INQUIRY data (see SPC-2) when any logical unit number
10433	 * format described in this standard is used.  Non-hierarchical
10434	 * formats are outside the scope of this standard.
10435	 *
10436	 * Therefore we set the HiSup bit here.
10437	 *
10438	 * The reponse format is 2, per SPC-3.
10439	 */
10440	inq_ptr->response_format = SID_HiSup | 2;
10441
10442	inq_ptr->additional_length = data_len -
10443	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10444	CTL_DEBUG_PRINT(("additional_length = %d\n",
10445			 inq_ptr->additional_length));
10446
10447	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10448	/* 16 bit addressing */
10449	if (port_type == CTL_PORT_SCSI)
10450		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10451	/* XXX set the SID_MultiP bit here if we're actually going to
10452	   respond on multiple ports */
10453	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10454
10455	/* 16 bit data bus, synchronous transfers */
10456	if (port_type == CTL_PORT_SCSI)
10457		inq_ptr->flags = SID_WBus16 | SID_Sync;
10458	/*
10459	 * XXX KDM do we want to support tagged queueing on the control
10460	 * device at all?
10461	 */
10462	if ((lun == NULL)
10463	 || (lun->be_lun->lun_type != T_PROCESSOR))
10464		inq_ptr->flags |= SID_CmdQue;
10465	/*
10466	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10467	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10468	 * name and 4 bytes for the revision.
10469	 */
10470	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10471	    "vendor")) == NULL) {
10472		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10473	} else {
10474		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10475		strncpy(inq_ptr->vendor, val,
10476		    min(sizeof(inq_ptr->vendor), strlen(val)));
10477	}
10478	if (lun == NULL) {
10479		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10480		    sizeof(inq_ptr->product));
10481	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10482		switch (lun->be_lun->lun_type) {
10483		case T_DIRECT:
10484			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10485			    sizeof(inq_ptr->product));
10486			break;
10487		case T_PROCESSOR:
10488			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10489			    sizeof(inq_ptr->product));
10490			break;
10491		default:
10492			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10493			    sizeof(inq_ptr->product));
10494			break;
10495		}
10496	} else {
10497		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10498		strncpy(inq_ptr->product, val,
10499		    min(sizeof(inq_ptr->product), strlen(val)));
10500	}
10501
10502	/*
10503	 * XXX make this a macro somewhere so it automatically gets
10504	 * incremented when we make changes.
10505	 */
10506	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10507	    "revision")) == NULL) {
10508		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10509	} else {
10510		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10511		strncpy(inq_ptr->revision, val,
10512		    min(sizeof(inq_ptr->revision), strlen(val)));
10513	}
10514
10515	/*
10516	 * For parallel SCSI, we support double transition and single
10517	 * transition clocking.  We also support QAS (Quick Arbitration
10518	 * and Selection) and Information Unit transfers on both the
10519	 * control and array devices.
10520	 */
10521	if (port_type == CTL_PORT_SCSI)
10522		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10523				    SID_SPI_IUS;
10524
10525	/* SAM-5 (no version claimed) */
10526	scsi_ulto2b(0x00A0, inq_ptr->version1);
10527	/* SPC-4 (no version claimed) */
10528	scsi_ulto2b(0x0460, inq_ptr->version2);
10529	if (port_type == CTL_PORT_FC) {
10530		/* FCP-2 ANSI INCITS.350:2003 */
10531		scsi_ulto2b(0x0917, inq_ptr->version3);
10532	} else if (port_type == CTL_PORT_SCSI) {
10533		/* SPI-4 ANSI INCITS.362:200x */
10534		scsi_ulto2b(0x0B56, inq_ptr->version3);
10535	} else if (port_type == CTL_PORT_ISCSI) {
10536		/* iSCSI (no version claimed) */
10537		scsi_ulto2b(0x0960, inq_ptr->version3);
10538	} else if (port_type == CTL_PORT_SAS) {
10539		/* SAS (no version claimed) */
10540		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10541	}
10542
10543	if (lun == NULL) {
10544		/* SBC-4 (no version claimed) */
10545		scsi_ulto2b(0x0600, inq_ptr->version4);
10546	} else {
10547		switch (lun->be_lun->lun_type) {
10548		case T_DIRECT:
10549			/* SBC-4 (no version claimed) */
10550			scsi_ulto2b(0x0600, inq_ptr->version4);
10551			break;
10552		case T_PROCESSOR:
10553		default:
10554			break;
10555		}
10556	}
10557
10558	ctsio->scsi_status = SCSI_STATUS_OK;
10559	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10560	ctsio->be_move_done = ctl_config_move_done;
10561	ctl_datamove((union ctl_io *)ctsio);
10562	return (CTL_RETVAL_COMPLETE);
10563}
10564
10565int
10566ctl_inquiry(struct ctl_scsiio *ctsio)
10567{
10568	struct scsi_inquiry *cdb;
10569	int retval;
10570
10571	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10572
10573	cdb = (struct scsi_inquiry *)ctsio->cdb;
10574	if (cdb->byte2 & SI_EVPD)
10575		retval = ctl_inquiry_evpd(ctsio);
10576	else if (cdb->page_code == 0)
10577		retval = ctl_inquiry_std(ctsio);
10578	else {
10579		ctl_set_invalid_field(ctsio,
10580				      /*sks_valid*/ 1,
10581				      /*command*/ 1,
10582				      /*field*/ 2,
10583				      /*bit_valid*/ 0,
10584				      /*bit*/ 0);
10585		ctl_done((union ctl_io *)ctsio);
10586		return (CTL_RETVAL_COMPLETE);
10587	}
10588
10589	return (retval);
10590}
10591
10592/*
10593 * For known CDB types, parse the LBA and length.
10594 */
10595static int
10596ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10597{
10598	if (io->io_hdr.io_type != CTL_IO_SCSI)
10599		return (1);
10600
10601	switch (io->scsiio.cdb[0]) {
10602	case COMPARE_AND_WRITE: {
10603		struct scsi_compare_and_write *cdb;
10604
10605		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10606
10607		*lba = scsi_8btou64(cdb->addr);
10608		*len = cdb->length;
10609		break;
10610	}
10611	case READ_6:
10612	case WRITE_6: {
10613		struct scsi_rw_6 *cdb;
10614
10615		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10616
10617		*lba = scsi_3btoul(cdb->addr);
10618		/* only 5 bits are valid in the most significant address byte */
10619		*lba &= 0x1fffff;
10620		*len = cdb->length;
10621		break;
10622	}
10623	case READ_10:
10624	case WRITE_10: {
10625		struct scsi_rw_10 *cdb;
10626
10627		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10628
10629		*lba = scsi_4btoul(cdb->addr);
10630		*len = scsi_2btoul(cdb->length);
10631		break;
10632	}
10633	case WRITE_VERIFY_10: {
10634		struct scsi_write_verify_10 *cdb;
10635
10636		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10637
10638		*lba = scsi_4btoul(cdb->addr);
10639		*len = scsi_2btoul(cdb->length);
10640		break;
10641	}
10642	case READ_12:
10643	case WRITE_12: {
10644		struct scsi_rw_12 *cdb;
10645
10646		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10647
10648		*lba = scsi_4btoul(cdb->addr);
10649		*len = scsi_4btoul(cdb->length);
10650		break;
10651	}
10652	case WRITE_VERIFY_12: {
10653		struct scsi_write_verify_12 *cdb;
10654
10655		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10656
10657		*lba = scsi_4btoul(cdb->addr);
10658		*len = scsi_4btoul(cdb->length);
10659		break;
10660	}
10661	case READ_16:
10662	case WRITE_16:
10663	case WRITE_ATOMIC_16: {
10664		struct scsi_rw_16 *cdb;
10665
10666		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10667
10668		*lba = scsi_8btou64(cdb->addr);
10669		*len = scsi_4btoul(cdb->length);
10670		break;
10671	}
10672	case WRITE_VERIFY_16: {
10673		struct scsi_write_verify_16 *cdb;
10674
10675		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10676
10677		*lba = scsi_8btou64(cdb->addr);
10678		*len = scsi_4btoul(cdb->length);
10679		break;
10680	}
10681	case WRITE_SAME_10: {
10682		struct scsi_write_same_10 *cdb;
10683
10684		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10685
10686		*lba = scsi_4btoul(cdb->addr);
10687		*len = scsi_2btoul(cdb->length);
10688		break;
10689	}
10690	case WRITE_SAME_16: {
10691		struct scsi_write_same_16 *cdb;
10692
10693		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10694
10695		*lba = scsi_8btou64(cdb->addr);
10696		*len = scsi_4btoul(cdb->length);
10697		break;
10698	}
10699	case VERIFY_10: {
10700		struct scsi_verify_10 *cdb;
10701
10702		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10703
10704		*lba = scsi_4btoul(cdb->addr);
10705		*len = scsi_2btoul(cdb->length);
10706		break;
10707	}
10708	case VERIFY_12: {
10709		struct scsi_verify_12 *cdb;
10710
10711		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10712
10713		*lba = scsi_4btoul(cdb->addr);
10714		*len = scsi_4btoul(cdb->length);
10715		break;
10716	}
10717	case VERIFY_16: {
10718		struct scsi_verify_16 *cdb;
10719
10720		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10721
10722		*lba = scsi_8btou64(cdb->addr);
10723		*len = scsi_4btoul(cdb->length);
10724		break;
10725	}
10726	case UNMAP: {
10727		*lba = 0;
10728		*len = UINT64_MAX;
10729		break;
10730	}
10731	default:
10732		return (1);
10733		break; /* NOTREACHED */
10734	}
10735
10736	return (0);
10737}
10738
10739static ctl_action
10740ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2)
10741{
10742	uint64_t endlba1, endlba2;
10743
10744	endlba1 = lba1 + len1 - 1;
10745	endlba2 = lba2 + len2 - 1;
10746
10747	if ((endlba1 < lba2)
10748	 || (endlba2 < lba1))
10749		return (CTL_ACTION_PASS);
10750	else
10751		return (CTL_ACTION_BLOCK);
10752}
10753
10754static int
10755ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10756{
10757	struct ctl_ptr_len_flags *ptrlen;
10758	struct scsi_unmap_desc *buf, *end, *range;
10759	uint64_t lba;
10760	uint32_t len;
10761
10762	/* If not UNMAP -- go other way. */
10763	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10764	    io->scsiio.cdb[0] != UNMAP)
10765		return (CTL_ACTION_ERROR);
10766
10767	/* If UNMAP without data -- block and wait for data. */
10768	ptrlen = (struct ctl_ptr_len_flags *)
10769	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10770	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10771	    ptrlen->ptr == NULL)
10772		return (CTL_ACTION_BLOCK);
10773
10774	/* UNMAP with data -- check for collision. */
10775	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10776	end = buf + ptrlen->len / sizeof(*buf);
10777	for (range = buf; range < end; range++) {
10778		lba = scsi_8btou64(range->lba);
10779		len = scsi_4btoul(range->length);
10780		if ((lba < lba2 + len2) && (lba + len > lba2))
10781			return (CTL_ACTION_BLOCK);
10782	}
10783	return (CTL_ACTION_PASS);
10784}
10785
10786static ctl_action
10787ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10788{
10789	uint64_t lba1, lba2;
10790	uint64_t len1, len2;
10791	int retval;
10792
10793	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10794		return (CTL_ACTION_ERROR);
10795
10796	retval = ctl_extent_check_unmap(io2, lba1, len1);
10797	if (retval != CTL_ACTION_ERROR)
10798		return (retval);
10799
10800	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10801		return (CTL_ACTION_ERROR);
10802
10803	return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10804}
10805
10806static ctl_action
10807ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10808    union ctl_io *ooa_io)
10809{
10810	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10811	ctl_serialize_action *serialize_row;
10812
10813	/*
10814	 * The initiator attempted multiple untagged commands at the same
10815	 * time.  Can't do that.
10816	 */
10817	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10818	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10819	 && ((pending_io->io_hdr.nexus.targ_port ==
10820	      ooa_io->io_hdr.nexus.targ_port)
10821	  && (pending_io->io_hdr.nexus.initid.id ==
10822	      ooa_io->io_hdr.nexus.initid.id))
10823	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10824		return (CTL_ACTION_OVERLAP);
10825
10826	/*
10827	 * The initiator attempted to send multiple tagged commands with
10828	 * the same ID.  (It's fine if different initiators have the same
10829	 * tag ID.)
10830	 *
10831	 * Even if all of those conditions are true, we don't kill the I/O
10832	 * if the command ahead of us has been aborted.  We won't end up
10833	 * sending it to the FETD, and it's perfectly legal to resend a
10834	 * command with the same tag number as long as the previous
10835	 * instance of this tag number has been aborted somehow.
10836	 */
10837	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10838	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10839	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10840	 && ((pending_io->io_hdr.nexus.targ_port ==
10841	      ooa_io->io_hdr.nexus.targ_port)
10842	  && (pending_io->io_hdr.nexus.initid.id ==
10843	      ooa_io->io_hdr.nexus.initid.id))
10844	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10845		return (CTL_ACTION_OVERLAP_TAG);
10846
10847	/*
10848	 * If we get a head of queue tag, SAM-3 says that we should
10849	 * immediately execute it.
10850	 *
10851	 * What happens if this command would normally block for some other
10852	 * reason?  e.g. a request sense with a head of queue tag
10853	 * immediately after a write.  Normally that would block, but this
10854	 * will result in its getting executed immediately...
10855	 *
10856	 * We currently return "pass" instead of "skip", so we'll end up
10857	 * going through the rest of the queue to check for overlapped tags.
10858	 *
10859	 * XXX KDM check for other types of blockage first??
10860	 */
10861	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10862		return (CTL_ACTION_PASS);
10863
10864	/*
10865	 * Ordered tags have to block until all items ahead of them
10866	 * have completed.  If we get called with an ordered tag, we always
10867	 * block, if something else is ahead of us in the queue.
10868	 */
10869	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10870		return (CTL_ACTION_BLOCK);
10871
10872	/*
10873	 * Simple tags get blocked until all head of queue and ordered tags
10874	 * ahead of them have completed.  I'm lumping untagged commands in
10875	 * with simple tags here.  XXX KDM is that the right thing to do?
10876	 */
10877	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10878	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10879	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10880	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10881		return (CTL_ACTION_BLOCK);
10882
10883	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10884	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10885
10886	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10887
10888	switch (serialize_row[pending_entry->seridx]) {
10889	case CTL_SER_BLOCK:
10890		return (CTL_ACTION_BLOCK);
10891	case CTL_SER_EXTENT:
10892		return (ctl_extent_check(pending_io, ooa_io));
10893	case CTL_SER_EXTENTOPT:
10894		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10895		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10896			return (ctl_extent_check(pending_io, ooa_io));
10897		/* FALLTHROUGH */
10898	case CTL_SER_PASS:
10899		return (CTL_ACTION_PASS);
10900	case CTL_SER_BLOCKOPT:
10901		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10902		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10903			return (CTL_ACTION_BLOCK);
10904		return (CTL_ACTION_PASS);
10905	case CTL_SER_SKIP:
10906		return (CTL_ACTION_SKIP);
10907	default:
10908		panic("invalid serialization value %d",
10909		      serialize_row[pending_entry->seridx]);
10910	}
10911
10912	return (CTL_ACTION_ERROR);
10913}
10914
10915/*
10916 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10917 * Assumptions:
10918 * - pending_io is generally either incoming, or on the blocked queue
10919 * - starting I/O is the I/O we want to start the check with.
10920 */
10921static ctl_action
10922ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10923	      union ctl_io *starting_io)
10924{
10925	union ctl_io *ooa_io;
10926	ctl_action action;
10927
10928	mtx_assert(&lun->lun_lock, MA_OWNED);
10929
10930	/*
10931	 * Run back along the OOA queue, starting with the current
10932	 * blocked I/O and going through every I/O before it on the
10933	 * queue.  If starting_io is NULL, we'll just end up returning
10934	 * CTL_ACTION_PASS.
10935	 */
10936	for (ooa_io = starting_io; ooa_io != NULL;
10937	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10938	     ooa_links)){
10939
10940		/*
10941		 * This routine just checks to see whether
10942		 * cur_blocked is blocked by ooa_io, which is ahead
10943		 * of it in the queue.  It doesn't queue/dequeue
10944		 * cur_blocked.
10945		 */
10946		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10947		switch (action) {
10948		case CTL_ACTION_BLOCK:
10949		case CTL_ACTION_OVERLAP:
10950		case CTL_ACTION_OVERLAP_TAG:
10951		case CTL_ACTION_SKIP:
10952		case CTL_ACTION_ERROR:
10953			return (action);
10954			break; /* NOTREACHED */
10955		case CTL_ACTION_PASS:
10956			break;
10957		default:
10958			panic("invalid action %d", action);
10959			break;  /* NOTREACHED */
10960		}
10961	}
10962
10963	return (CTL_ACTION_PASS);
10964}
10965
10966/*
10967 * Assumptions:
10968 * - An I/O has just completed, and has been removed from the per-LUN OOA
10969 *   queue, so some items on the blocked queue may now be unblocked.
10970 */
10971static int
10972ctl_check_blocked(struct ctl_lun *lun)
10973{
10974	union ctl_io *cur_blocked, *next_blocked;
10975
10976	mtx_assert(&lun->lun_lock, MA_OWNED);
10977
10978	/*
10979	 * Run forward from the head of the blocked queue, checking each
10980	 * entry against the I/Os prior to it on the OOA queue to see if
10981	 * there is still any blockage.
10982	 *
10983	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10984	 * with our removing a variable on it while it is traversing the
10985	 * list.
10986	 */
10987	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10988	     cur_blocked != NULL; cur_blocked = next_blocked) {
10989		union ctl_io *prev_ooa;
10990		ctl_action action;
10991
10992		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10993							  blocked_links);
10994
10995		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10996						      ctl_ooaq, ooa_links);
10997
10998		/*
10999		 * If cur_blocked happens to be the first item in the OOA
11000		 * queue now, prev_ooa will be NULL, and the action
11001		 * returned will just be CTL_ACTION_PASS.
11002		 */
11003		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11004
11005		switch (action) {
11006		case CTL_ACTION_BLOCK:
11007			/* Nothing to do here, still blocked */
11008			break;
11009		case CTL_ACTION_OVERLAP:
11010		case CTL_ACTION_OVERLAP_TAG:
11011			/*
11012			 * This shouldn't happen!  In theory we've already
11013			 * checked this command for overlap...
11014			 */
11015			break;
11016		case CTL_ACTION_PASS:
11017		case CTL_ACTION_SKIP: {
11018			struct ctl_softc *softc;
11019			const struct ctl_cmd_entry *entry;
11020			uint32_t initidx;
11021			int isc_retval;
11022
11023			/*
11024			 * The skip case shouldn't happen, this transaction
11025			 * should have never made it onto the blocked queue.
11026			 */
11027			/*
11028			 * This I/O is no longer blocked, we can remove it
11029			 * from the blocked queue.  Since this is a TAILQ
11030			 * (doubly linked list), we can do O(1) removals
11031			 * from any place on the list.
11032			 */
11033			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11034				     blocked_links);
11035			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11036
11037			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11038				/*
11039				 * Need to send IO back to original side to
11040				 * run
11041				 */
11042				union ctl_ha_msg msg_info;
11043
11044				msg_info.hdr.original_sc =
11045					cur_blocked->io_hdr.original_sc;
11046				msg_info.hdr.serializing_sc = cur_blocked;
11047				msg_info.hdr.msg_type = CTL_MSG_R2R;
11048				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11049				     &msg_info, sizeof(msg_info), 0)) >
11050				     CTL_HA_STATUS_SUCCESS) {
11051					printf("CTL:Check Blocked error from "
11052					       "ctl_ha_msg_send %d\n",
11053					       isc_retval);
11054				}
11055				break;
11056			}
11057			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11058			softc = control_softc;
11059
11060			initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
11061
11062			/*
11063			 * Check this I/O for LUN state changes that may
11064			 * have happened while this command was blocked.
11065			 * The LUN state may have been changed by a command
11066			 * ahead of us in the queue, so we need to re-check
11067			 * for any states that can be caused by SCSI
11068			 * commands.
11069			 */
11070			if (ctl_scsiio_lun_check(softc, lun, entry,
11071						 &cur_blocked->scsiio) == 0) {
11072				cur_blocked->io_hdr.flags |=
11073				                      CTL_FLAG_IS_WAS_ON_RTR;
11074				ctl_enqueue_rtr(cur_blocked);
11075			} else
11076				ctl_done(cur_blocked);
11077			break;
11078		}
11079		default:
11080			/*
11081			 * This probably shouldn't happen -- we shouldn't
11082			 * get CTL_ACTION_ERROR, or anything else.
11083			 */
11084			break;
11085		}
11086	}
11087
11088	return (CTL_RETVAL_COMPLETE);
11089}
11090
11091/*
11092 * This routine (with one exception) checks LUN flags that can be set by
11093 * commands ahead of us in the OOA queue.  These flags have to be checked
11094 * when a command initially comes in, and when we pull a command off the
11095 * blocked queue and are preparing to execute it.  The reason we have to
11096 * check these flags for commands on the blocked queue is that the LUN
11097 * state may have been changed by a command ahead of us while we're on the
11098 * blocked queue.
11099 *
11100 * Ordering is somewhat important with these checks, so please pay
11101 * careful attention to the placement of any new checks.
11102 */
11103static int
11104ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11105    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11106{
11107	int retval;
11108	uint32_t residx;
11109
11110	retval = 0;
11111
11112	mtx_assert(&lun->lun_lock, MA_OWNED);
11113
11114	/*
11115	 * If this shelf is a secondary shelf controller, we have to reject
11116	 * any media access commands.
11117	 */
11118	if ((ctl_softc->flags & CTL_FLAG_ACTIVE_SHELF) == 0 &&
11119	    (entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0) {
11120		ctl_set_lun_standby(ctsio);
11121		retval = 1;
11122		goto bailout;
11123	}
11124
11125	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11126		if (lun->flags & CTL_LUN_READONLY) {
11127			ctl_set_sense(ctsio, /*current_error*/ 1,
11128			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11129			    /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11130			retval = 1;
11131			goto bailout;
11132		}
11133		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11134		    .eca_and_aen & SCP_SWP) != 0) {
11135			ctl_set_sense(ctsio, /*current_error*/ 1,
11136			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11137			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11138			retval = 1;
11139			goto bailout;
11140		}
11141	}
11142
11143	/*
11144	 * Check for a reservation conflict.  If this command isn't allowed
11145	 * even on reserved LUNs, and if this initiator isn't the one who
11146	 * reserved us, reject the command with a reservation conflict.
11147	 */
11148	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11149	if ((lun->flags & CTL_LUN_RESERVED)
11150	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11151		if (lun->res_idx != residx) {
11152			ctl_set_reservation_conflict(ctsio);
11153			retval = 1;
11154			goto bailout;
11155		}
11156	}
11157
11158	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11159	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11160		/* No reservation or command is allowed. */;
11161	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11162	    (lun->res_type == SPR_TYPE_WR_EX ||
11163	     lun->res_type == SPR_TYPE_WR_EX_RO ||
11164	     lun->res_type == SPR_TYPE_WR_EX_AR)) {
11165		/* The command is allowed for Write Exclusive resv. */;
11166	} else {
11167		/*
11168		 * if we aren't registered or it's a res holder type
11169		 * reservation and this isn't the res holder then set a
11170		 * conflict.
11171		 */
11172		if (lun->pr_keys[residx] == 0
11173		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11174			ctl_set_reservation_conflict(ctsio);
11175			retval = 1;
11176			goto bailout;
11177		}
11178
11179	}
11180
11181	if ((lun->flags & CTL_LUN_OFFLINE)
11182	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11183		ctl_set_lun_not_ready(ctsio);
11184		retval = 1;
11185		goto bailout;
11186	}
11187
11188	/*
11189	 * If the LUN is stopped, see if this particular command is allowed
11190	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11191	 */
11192	if ((lun->flags & CTL_LUN_STOPPED)
11193	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11194		/* "Logical unit not ready, initializing cmd. required" */
11195		ctl_set_lun_stopped(ctsio);
11196		retval = 1;
11197		goto bailout;
11198	}
11199
11200	if ((lun->flags & CTL_LUN_INOPERABLE)
11201	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11202		/* "Medium format corrupted" */
11203		ctl_set_medium_format_corrupted(ctsio);
11204		retval = 1;
11205		goto bailout;
11206	}
11207
11208bailout:
11209	return (retval);
11210
11211}
11212
11213static void
11214ctl_failover_io(union ctl_io *io, int have_lock)
11215{
11216	ctl_set_busy(&io->scsiio);
11217	ctl_done(io);
11218}
11219
11220static void
11221ctl_failover(void)
11222{
11223	struct ctl_lun *lun;
11224	struct ctl_softc *ctl_softc;
11225	union ctl_io *next_io, *pending_io;
11226	union ctl_io *io;
11227	int lun_idx;
11228	int i;
11229
11230	ctl_softc = control_softc;
11231
11232	mtx_lock(&ctl_softc->ctl_lock);
11233	/*
11234	 * Remove any cmds from the other SC from the rtr queue.  These
11235	 * will obviously only be for LUNs for which we're the primary.
11236	 * We can't send status or get/send data for these commands.
11237	 * Since they haven't been executed yet, we can just remove them.
11238	 * We'll either abort them or delete them below, depending on
11239	 * which HA mode we're in.
11240	 */
11241#ifdef notyet
11242	mtx_lock(&ctl_softc->queue_lock);
11243	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11244	     io != NULL; io = next_io) {
11245		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11246		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11247			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11248				      ctl_io_hdr, links);
11249	}
11250	mtx_unlock(&ctl_softc->queue_lock);
11251#endif
11252
11253	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11254		lun = ctl_softc->ctl_luns[lun_idx];
11255		if (lun==NULL)
11256			continue;
11257
11258		/*
11259		 * Processor LUNs are primary on both sides.
11260		 * XXX will this always be true?
11261		 */
11262		if (lun->be_lun->lun_type == T_PROCESSOR)
11263			continue;
11264
11265		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11266		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11267			printf("FAILOVER: primary lun %d\n", lun_idx);
11268		        /*
11269			 * Remove all commands from the other SC. First from the
11270			 * blocked queue then from the ooa queue. Once we have
11271			 * removed them. Call ctl_check_blocked to see if there
11272			 * is anything that can run.
11273			 */
11274			for (io = (union ctl_io *)TAILQ_FIRST(
11275			     &lun->blocked_queue); io != NULL; io = next_io) {
11276
11277		        	next_io = (union ctl_io *)TAILQ_NEXT(
11278				    &io->io_hdr, blocked_links);
11279
11280				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11281					TAILQ_REMOVE(&lun->blocked_queue,
11282						     &io->io_hdr,blocked_links);
11283					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11284					TAILQ_REMOVE(&lun->ooa_queue,
11285						     &io->io_hdr, ooa_links);
11286
11287					ctl_free_io(io);
11288				}
11289			}
11290
11291			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11292	     		     io != NULL; io = next_io) {
11293
11294		        	next_io = (union ctl_io *)TAILQ_NEXT(
11295				    &io->io_hdr, ooa_links);
11296
11297				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11298
11299					TAILQ_REMOVE(&lun->ooa_queue,
11300						&io->io_hdr,
11301					     	ooa_links);
11302
11303					ctl_free_io(io);
11304				}
11305			}
11306			ctl_check_blocked(lun);
11307		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11308			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11309
11310			printf("FAILOVER: primary lun %d\n", lun_idx);
11311			/*
11312			 * Abort all commands from the other SC.  We can't
11313			 * send status back for them now.  These should get
11314			 * cleaned up when they are completed or come out
11315			 * for a datamove operation.
11316			 */
11317			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11318	     		     io != NULL; io = next_io) {
11319		        	next_io = (union ctl_io *)TAILQ_NEXT(
11320					&io->io_hdr, ooa_links);
11321
11322				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11323					io->io_hdr.flags |= CTL_FLAG_ABORT;
11324			}
11325		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11326			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11327
11328			printf("FAILOVER: secondary lun %d\n", lun_idx);
11329
11330			lun->flags |= CTL_LUN_PRIMARY_SC;
11331
11332			/*
11333			 * We send all I/O that was sent to this controller
11334			 * and redirected to the other side back with
11335			 * busy status, and have the initiator retry it.
11336			 * Figuring out how much data has been transferred,
11337			 * etc. and picking up where we left off would be
11338			 * very tricky.
11339			 *
11340			 * XXX KDM need to remove I/O from the blocked
11341			 * queue as well!
11342			 */
11343			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11344			     &lun->ooa_queue); pending_io != NULL;
11345			     pending_io = next_io) {
11346
11347				next_io =  (union ctl_io *)TAILQ_NEXT(
11348					&pending_io->io_hdr, ooa_links);
11349
11350				pending_io->io_hdr.flags &=
11351					~CTL_FLAG_SENT_2OTHER_SC;
11352
11353				if (pending_io->io_hdr.flags &
11354				    CTL_FLAG_IO_ACTIVE) {
11355					pending_io->io_hdr.flags |=
11356						CTL_FLAG_FAILOVER;
11357				} else {
11358					ctl_set_busy(&pending_io->scsiio);
11359					ctl_done(pending_io);
11360				}
11361			}
11362
11363			/*
11364			 * Build Unit Attention
11365			 */
11366			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11367				lun->pending_ua[i] |=
11368				                     CTL_UA_ASYM_ACC_CHANGE;
11369			}
11370		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11371			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11372			printf("FAILOVER: secondary lun %d\n", lun_idx);
11373			/*
11374			 * if the first io on the OOA is not on the RtR queue
11375			 * add it.
11376			 */
11377			lun->flags |= CTL_LUN_PRIMARY_SC;
11378
11379			pending_io = (union ctl_io *)TAILQ_FIRST(
11380			    &lun->ooa_queue);
11381			if (pending_io==NULL) {
11382				printf("Nothing on OOA queue\n");
11383				continue;
11384			}
11385
11386			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11387			if ((pending_io->io_hdr.flags &
11388			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11389				pending_io->io_hdr.flags |=
11390				    CTL_FLAG_IS_WAS_ON_RTR;
11391				ctl_enqueue_rtr(pending_io);
11392			}
11393#if 0
11394			else
11395			{
11396				printf("Tag 0x%04x is running\n",
11397				      pending_io->scsiio.tag_num);
11398			}
11399#endif
11400
11401			next_io = (union ctl_io *)TAILQ_NEXT(
11402			    &pending_io->io_hdr, ooa_links);
11403			for (pending_io=next_io; pending_io != NULL;
11404			     pending_io = next_io) {
11405				pending_io->io_hdr.flags &=
11406				    ~CTL_FLAG_SENT_2OTHER_SC;
11407				next_io = (union ctl_io *)TAILQ_NEXT(
11408					&pending_io->io_hdr, ooa_links);
11409				if (pending_io->io_hdr.flags &
11410				    CTL_FLAG_IS_WAS_ON_RTR) {
11411#if 0
11412				        printf("Tag 0x%04x is running\n",
11413				      		pending_io->scsiio.tag_num);
11414#endif
11415					continue;
11416				}
11417
11418				switch (ctl_check_ooa(lun, pending_io,
11419			            (union ctl_io *)TAILQ_PREV(
11420				    &pending_io->io_hdr, ctl_ooaq,
11421				    ooa_links))) {
11422
11423				case CTL_ACTION_BLOCK:
11424					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11425							  &pending_io->io_hdr,
11426							  blocked_links);
11427					pending_io->io_hdr.flags |=
11428					    CTL_FLAG_BLOCKED;
11429					break;
11430				case CTL_ACTION_PASS:
11431				case CTL_ACTION_SKIP:
11432					pending_io->io_hdr.flags |=
11433					    CTL_FLAG_IS_WAS_ON_RTR;
11434					ctl_enqueue_rtr(pending_io);
11435					break;
11436				case CTL_ACTION_OVERLAP:
11437					ctl_set_overlapped_cmd(
11438					    (struct ctl_scsiio *)pending_io);
11439					ctl_done(pending_io);
11440					break;
11441				case CTL_ACTION_OVERLAP_TAG:
11442					ctl_set_overlapped_tag(
11443					    (struct ctl_scsiio *)pending_io,
11444					    pending_io->scsiio.tag_num & 0xff);
11445					ctl_done(pending_io);
11446					break;
11447				case CTL_ACTION_ERROR:
11448				default:
11449					ctl_set_internal_failure(
11450						(struct ctl_scsiio *)pending_io,
11451						0,  // sks_valid
11452						0); //retry count
11453					ctl_done(pending_io);
11454					break;
11455				}
11456			}
11457
11458			/*
11459			 * Build Unit Attention
11460			 */
11461			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11462				lun->pending_ua[i] |=
11463				                     CTL_UA_ASYM_ACC_CHANGE;
11464			}
11465		} else {
11466			panic("Unhandled HA mode failover, LUN flags = %#x, "
11467			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11468		}
11469	}
11470	ctl_pause_rtr = 0;
11471	mtx_unlock(&ctl_softc->ctl_lock);
11472}
11473
11474static int
11475ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11476{
11477	struct ctl_lun *lun;
11478	const struct ctl_cmd_entry *entry;
11479	uint32_t initidx, targ_lun;
11480	int retval;
11481
11482	retval = 0;
11483
11484	lun = NULL;
11485
11486	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11487	if ((targ_lun < CTL_MAX_LUNS)
11488	 && ((lun = ctl_softc->ctl_luns[targ_lun]) != NULL)) {
11489		/*
11490		 * If the LUN is invalid, pretend that it doesn't exist.
11491		 * It will go away as soon as all pending I/O has been
11492		 * completed.
11493		 */
11494		mtx_lock(&lun->lun_lock);
11495		if (lun->flags & CTL_LUN_DISABLED) {
11496			mtx_unlock(&lun->lun_lock);
11497			lun = NULL;
11498			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11499			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11500		} else {
11501			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11502			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11503				lun->be_lun;
11504			if (lun->be_lun->lun_type == T_PROCESSOR) {
11505				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11506			}
11507
11508			/*
11509			 * Every I/O goes into the OOA queue for a
11510			 * particular LUN, and stays there until completion.
11511			 */
11512			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11513			    ooa_links);
11514		}
11515	} else {
11516		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11517		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11518	}
11519
11520	/* Get command entry and return error if it is unsuppotyed. */
11521	entry = ctl_validate_command(ctsio);
11522	if (entry == NULL) {
11523		if (lun)
11524			mtx_unlock(&lun->lun_lock);
11525		return (retval);
11526	}
11527
11528	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11529	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11530
11531	/*
11532	 * Check to see whether we can send this command to LUNs that don't
11533	 * exist.  This should pretty much only be the case for inquiry
11534	 * and request sense.  Further checks, below, really require having
11535	 * a LUN, so we can't really check the command anymore.  Just put
11536	 * it on the rtr queue.
11537	 */
11538	if (lun == NULL) {
11539		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11540			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11541			ctl_enqueue_rtr((union ctl_io *)ctsio);
11542			return (retval);
11543		}
11544
11545		ctl_set_unsupported_lun(ctsio);
11546		ctl_done((union ctl_io *)ctsio);
11547		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11548		return (retval);
11549	} else {
11550		/*
11551		 * Make sure we support this particular command on this LUN.
11552		 * e.g., we don't support writes to the control LUN.
11553		 */
11554		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11555			mtx_unlock(&lun->lun_lock);
11556			ctl_set_invalid_opcode(ctsio);
11557			ctl_done((union ctl_io *)ctsio);
11558			return (retval);
11559		}
11560	}
11561
11562	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11563
11564#ifdef CTL_WITH_CA
11565	/*
11566	 * If we've got a request sense, it'll clear the contingent
11567	 * allegiance condition.  Otherwise, if we have a CA condition for
11568	 * this initiator, clear it, because it sent down a command other
11569	 * than request sense.
11570	 */
11571	if ((ctsio->cdb[0] != REQUEST_SENSE)
11572	 && (ctl_is_set(lun->have_ca, initidx)))
11573		ctl_clear_mask(lun->have_ca, initidx);
11574#endif
11575
11576	/*
11577	 * If the command has this flag set, it handles its own unit
11578	 * attention reporting, we shouldn't do anything.  Otherwise we
11579	 * check for any pending unit attentions, and send them back to the
11580	 * initiator.  We only do this when a command initially comes in,
11581	 * not when we pull it off the blocked queue.
11582	 *
11583	 * According to SAM-3, section 5.3.2, the order that things get
11584	 * presented back to the host is basically unit attentions caused
11585	 * by some sort of reset event, busy status, reservation conflicts
11586	 * or task set full, and finally any other status.
11587	 *
11588	 * One issue here is that some of the unit attentions we report
11589	 * don't fall into the "reset" category (e.g. "reported luns data
11590	 * has changed").  So reporting it here, before the reservation
11591	 * check, may be technically wrong.  I guess the only thing to do
11592	 * would be to check for and report the reset events here, and then
11593	 * check for the other unit attention types after we check for a
11594	 * reservation conflict.
11595	 *
11596	 * XXX KDM need to fix this
11597	 */
11598	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11599		ctl_ua_type ua_type;
11600
11601		if (lun->pending_ua[initidx] != CTL_UA_NONE) {
11602			scsi_sense_data_type sense_format;
11603
11604			if (lun != NULL)
11605				sense_format = (lun->flags &
11606				    CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11607				    SSD_TYPE_FIXED;
11608			else
11609				sense_format = SSD_TYPE_FIXED;
11610
11611			ua_type = ctl_build_ua(&lun->pending_ua[initidx],
11612			    &ctsio->sense_data, sense_format);
11613			if (ua_type != CTL_UA_NONE) {
11614				ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11615				ctsio->io_hdr.status = CTL_SCSI_ERROR |
11616						       CTL_AUTOSENSE;
11617				ctsio->sense_len = SSD_FULL_SIZE;
11618				mtx_unlock(&lun->lun_lock);
11619				ctl_done((union ctl_io *)ctsio);
11620				return (retval);
11621			}
11622		}
11623	}
11624
11625
11626	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11627		mtx_unlock(&lun->lun_lock);
11628		ctl_done((union ctl_io *)ctsio);
11629		return (retval);
11630	}
11631
11632	/*
11633	 * XXX CHD this is where we want to send IO to other side if
11634	 * this LUN is secondary on this SC. We will need to make a copy
11635	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11636	 * the copy we send as FROM_OTHER.
11637	 * We also need to stuff the address of the original IO so we can
11638	 * find it easily. Something similar will need be done on the other
11639	 * side so when we are done we can find the copy.
11640	 */
11641	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11642		union ctl_ha_msg msg_info;
11643		int isc_retval;
11644
11645		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11646
11647		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11648		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11649#if 0
11650		printf("1. ctsio %p\n", ctsio);
11651#endif
11652		msg_info.hdr.serializing_sc = NULL;
11653		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11654		msg_info.scsi.tag_num = ctsio->tag_num;
11655		msg_info.scsi.tag_type = ctsio->tag_type;
11656		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11657
11658		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11659
11660		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11661		    (void *)&msg_info, sizeof(msg_info), 0)) >
11662		    CTL_HA_STATUS_SUCCESS) {
11663			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11664			       isc_retval);
11665			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11666		} else {
11667#if 0
11668			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11669#endif
11670		}
11671
11672		/*
11673		 * XXX KDM this I/O is off the incoming queue, but hasn't
11674		 * been inserted on any other queue.  We may need to come
11675		 * up with a holding queue while we wait for serialization
11676		 * so that we have an idea of what we're waiting for from
11677		 * the other side.
11678		 */
11679		mtx_unlock(&lun->lun_lock);
11680		return (retval);
11681	}
11682
11683	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11684			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11685			      ctl_ooaq, ooa_links))) {
11686	case CTL_ACTION_BLOCK:
11687		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11688		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11689				  blocked_links);
11690		mtx_unlock(&lun->lun_lock);
11691		return (retval);
11692	case CTL_ACTION_PASS:
11693	case CTL_ACTION_SKIP:
11694		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11695		mtx_unlock(&lun->lun_lock);
11696		ctl_enqueue_rtr((union ctl_io *)ctsio);
11697		break;
11698	case CTL_ACTION_OVERLAP:
11699		mtx_unlock(&lun->lun_lock);
11700		ctl_set_overlapped_cmd(ctsio);
11701		ctl_done((union ctl_io *)ctsio);
11702		break;
11703	case CTL_ACTION_OVERLAP_TAG:
11704		mtx_unlock(&lun->lun_lock);
11705		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11706		ctl_done((union ctl_io *)ctsio);
11707		break;
11708	case CTL_ACTION_ERROR:
11709	default:
11710		mtx_unlock(&lun->lun_lock);
11711		ctl_set_internal_failure(ctsio,
11712					 /*sks_valid*/ 0,
11713					 /*retry_count*/ 0);
11714		ctl_done((union ctl_io *)ctsio);
11715		break;
11716	}
11717	return (retval);
11718}
11719
11720const struct ctl_cmd_entry *
11721ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11722{
11723	const struct ctl_cmd_entry *entry;
11724	int service_action;
11725
11726	entry = &ctl_cmd_table[ctsio->cdb[0]];
11727	if (sa)
11728		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11729	if (entry->flags & CTL_CMD_FLAG_SA5) {
11730		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11731		entry = &((const struct ctl_cmd_entry *)
11732		    entry->execute)[service_action];
11733	}
11734	return (entry);
11735}
11736
11737const struct ctl_cmd_entry *
11738ctl_validate_command(struct ctl_scsiio *ctsio)
11739{
11740	const struct ctl_cmd_entry *entry;
11741	int i, sa;
11742	uint8_t diff;
11743
11744	entry = ctl_get_cmd_entry(ctsio, &sa);
11745	if (entry->execute == NULL) {
11746		if (sa)
11747			ctl_set_invalid_field(ctsio,
11748					      /*sks_valid*/ 1,
11749					      /*command*/ 1,
11750					      /*field*/ 1,
11751					      /*bit_valid*/ 1,
11752					      /*bit*/ 4);
11753		else
11754			ctl_set_invalid_opcode(ctsio);
11755		ctl_done((union ctl_io *)ctsio);
11756		return (NULL);
11757	}
11758	KASSERT(entry->length > 0,
11759	    ("Not defined length for command 0x%02x/0x%02x",
11760	     ctsio->cdb[0], ctsio->cdb[1]));
11761	for (i = 1; i < entry->length; i++) {
11762		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11763		if (diff == 0)
11764			continue;
11765		ctl_set_invalid_field(ctsio,
11766				      /*sks_valid*/ 1,
11767				      /*command*/ 1,
11768				      /*field*/ i,
11769				      /*bit_valid*/ 1,
11770				      /*bit*/ fls(diff) - 1);
11771		ctl_done((union ctl_io *)ctsio);
11772		return (NULL);
11773	}
11774	return (entry);
11775}
11776
11777static int
11778ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11779{
11780
11781	switch (lun_type) {
11782	case T_PROCESSOR:
11783		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11784		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11785			return (0);
11786		break;
11787	case T_DIRECT:
11788		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11789		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11790			return (0);
11791		break;
11792	default:
11793		return (0);
11794	}
11795	return (1);
11796}
11797
11798static int
11799ctl_scsiio(struct ctl_scsiio *ctsio)
11800{
11801	int retval;
11802	const struct ctl_cmd_entry *entry;
11803
11804	retval = CTL_RETVAL_COMPLETE;
11805
11806	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11807
11808	entry = ctl_get_cmd_entry(ctsio, NULL);
11809
11810	/*
11811	 * If this I/O has been aborted, just send it straight to
11812	 * ctl_done() without executing it.
11813	 */
11814	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11815		ctl_done((union ctl_io *)ctsio);
11816		goto bailout;
11817	}
11818
11819	/*
11820	 * All the checks should have been handled by ctl_scsiio_precheck().
11821	 * We should be clear now to just execute the I/O.
11822	 */
11823	retval = entry->execute(ctsio);
11824
11825bailout:
11826	return (retval);
11827}
11828
11829/*
11830 * Since we only implement one target right now, a bus reset simply resets
11831 * our single target.
11832 */
11833static int
11834ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11835{
11836	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11837}
11838
11839static int
11840ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11841		 ctl_ua_type ua_type)
11842{
11843	struct ctl_lun *lun;
11844	int retval;
11845
11846	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11847		union ctl_ha_msg msg_info;
11848
11849		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11850		msg_info.hdr.nexus = io->io_hdr.nexus;
11851		if (ua_type==CTL_UA_TARG_RESET)
11852			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11853		else
11854			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11855		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11856		msg_info.hdr.original_sc = NULL;
11857		msg_info.hdr.serializing_sc = NULL;
11858		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11859		    (void *)&msg_info, sizeof(msg_info), 0)) {
11860		}
11861	}
11862	retval = 0;
11863
11864	mtx_lock(&ctl_softc->ctl_lock);
11865	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11866		retval += ctl_lun_reset(lun, io, ua_type);
11867	mtx_unlock(&ctl_softc->ctl_lock);
11868
11869	return (retval);
11870}
11871
11872/*
11873 * The LUN should always be set.  The I/O is optional, and is used to
11874 * distinguish between I/Os sent by this initiator, and by other
11875 * initiators.  We set unit attention for initiators other than this one.
11876 * SAM-3 is vague on this point.  It does say that a unit attention should
11877 * be established for other initiators when a LUN is reset (see section
11878 * 5.7.3), but it doesn't specifically say that the unit attention should
11879 * be established for this particular initiator when a LUN is reset.  Here
11880 * is the relevant text, from SAM-3 rev 8:
11881 *
11882 * 5.7.2 When a SCSI initiator port aborts its own tasks
11883 *
11884 * When a SCSI initiator port causes its own task(s) to be aborted, no
11885 * notification that the task(s) have been aborted shall be returned to
11886 * the SCSI initiator port other than the completion response for the
11887 * command or task management function action that caused the task(s) to
11888 * be aborted and notification(s) associated with related effects of the
11889 * action (e.g., a reset unit attention condition).
11890 *
11891 * XXX KDM for now, we're setting unit attention for all initiators.
11892 */
11893static int
11894ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11895{
11896	union ctl_io *xio;
11897#if 0
11898	uint32_t initindex;
11899#endif
11900	int i;
11901
11902	mtx_lock(&lun->lun_lock);
11903	/*
11904	 * Run through the OOA queue and abort each I/O.
11905	 */
11906#if 0
11907	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11908#endif
11909	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11910	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11911		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11912	}
11913
11914	/*
11915	 * This version sets unit attention for every
11916	 */
11917#if 0
11918	initindex = ctl_get_initindex(&io->io_hdr.nexus);
11919	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11920		if (initindex == i)
11921			continue;
11922		lun->pending_ua[i] |= ua_type;
11923	}
11924#endif
11925
11926	/*
11927	 * A reset (any kind, really) clears reservations established with
11928	 * RESERVE/RELEASE.  It does not clear reservations established
11929	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11930	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11931	 * reservations made with the RESERVE/RELEASE commands, because
11932	 * those commands are obsolete in SPC-3.
11933	 */
11934	lun->flags &= ~CTL_LUN_RESERVED;
11935
11936	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11937#ifdef CTL_WITH_CA
11938		ctl_clear_mask(lun->have_ca, i);
11939#endif
11940		lun->pending_ua[i] |= ua_type;
11941	}
11942	mtx_unlock(&lun->lun_lock);
11943
11944	return (0);
11945}
11946
11947static void
11948ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11949    int other_sc)
11950{
11951	union ctl_io *xio;
11952
11953	mtx_assert(&lun->lun_lock, MA_OWNED);
11954
11955	/*
11956	 * Run through the OOA queue and attempt to find the given I/O.
11957	 * The target port, initiator ID, tag type and tag number have to
11958	 * match the values that we got from the initiator.  If we have an
11959	 * untagged command to abort, simply abort the first untagged command
11960	 * we come to.  We only allow one untagged command at a time of course.
11961	 */
11962	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11963	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11964
11965		if ((targ_port == UINT32_MAX ||
11966		     targ_port == xio->io_hdr.nexus.targ_port) &&
11967		    (init_id == UINT32_MAX ||
11968		     init_id == xio->io_hdr.nexus.initid.id)) {
11969			if (targ_port != xio->io_hdr.nexus.targ_port ||
11970			    init_id != xio->io_hdr.nexus.initid.id)
11971				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11972			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11973			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11974				union ctl_ha_msg msg_info;
11975
11976				msg_info.hdr.nexus = xio->io_hdr.nexus;
11977				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11978				msg_info.task.tag_num = xio->scsiio.tag_num;
11979				msg_info.task.tag_type = xio->scsiio.tag_type;
11980				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11981				msg_info.hdr.original_sc = NULL;
11982				msg_info.hdr.serializing_sc = NULL;
11983				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11984				    (void *)&msg_info, sizeof(msg_info), 0);
11985			}
11986		}
11987	}
11988}
11989
11990static int
11991ctl_abort_task_set(union ctl_io *io)
11992{
11993	struct ctl_softc *softc = control_softc;
11994	struct ctl_lun *lun;
11995	uint32_t targ_lun;
11996
11997	/*
11998	 * Look up the LUN.
11999	 */
12000	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12001	mtx_lock(&softc->ctl_lock);
12002	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
12003		lun = softc->ctl_luns[targ_lun];
12004	else {
12005		mtx_unlock(&softc->ctl_lock);
12006		return (1);
12007	}
12008
12009	mtx_lock(&lun->lun_lock);
12010	mtx_unlock(&softc->ctl_lock);
12011	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12012		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12013		    io->io_hdr.nexus.initid.id,
12014		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12015	} else { /* CTL_TASK_CLEAR_TASK_SET */
12016		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12017		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12018	}
12019	mtx_unlock(&lun->lun_lock);
12020	return (0);
12021}
12022
12023static int
12024ctl_i_t_nexus_reset(union ctl_io *io)
12025{
12026	struct ctl_softc *softc = control_softc;
12027	struct ctl_lun *lun;
12028	uint32_t initindex, residx;
12029
12030	initindex = ctl_get_initindex(&io->io_hdr.nexus);
12031	residx = ctl_get_resindex(&io->io_hdr.nexus);
12032	mtx_lock(&softc->ctl_lock);
12033	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12034		mtx_lock(&lun->lun_lock);
12035		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12036		    io->io_hdr.nexus.initid.id,
12037		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12038#ifdef CTL_WITH_CA
12039		ctl_clear_mask(lun->have_ca, initindex);
12040#endif
12041		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
12042			lun->flags &= ~CTL_LUN_RESERVED;
12043		lun->pending_ua[initindex] |= CTL_UA_I_T_NEXUS_LOSS;
12044		mtx_unlock(&lun->lun_lock);
12045	}
12046	mtx_unlock(&softc->ctl_lock);
12047	return (0);
12048}
12049
12050static int
12051ctl_abort_task(union ctl_io *io)
12052{
12053	union ctl_io *xio;
12054	struct ctl_lun *lun;
12055	struct ctl_softc *ctl_softc;
12056#if 0
12057	struct sbuf sb;
12058	char printbuf[128];
12059#endif
12060	int found;
12061	uint32_t targ_lun;
12062
12063	ctl_softc = control_softc;
12064	found = 0;
12065
12066	/*
12067	 * Look up the LUN.
12068	 */
12069	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12070	mtx_lock(&ctl_softc->ctl_lock);
12071	if ((targ_lun < CTL_MAX_LUNS)
12072	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12073		lun = ctl_softc->ctl_luns[targ_lun];
12074	else {
12075		mtx_unlock(&ctl_softc->ctl_lock);
12076		return (1);
12077	}
12078
12079#if 0
12080	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12081	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12082#endif
12083
12084	mtx_lock(&lun->lun_lock);
12085	mtx_unlock(&ctl_softc->ctl_lock);
12086	/*
12087	 * Run through the OOA queue and attempt to find the given I/O.
12088	 * The target port, initiator ID, tag type and tag number have to
12089	 * match the values that we got from the initiator.  If we have an
12090	 * untagged command to abort, simply abort the first untagged command
12091	 * we come to.  We only allow one untagged command at a time of course.
12092	 */
12093#if 0
12094	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12095#endif
12096	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12097	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12098#if 0
12099		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12100
12101		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12102			    lun->lun, xio->scsiio.tag_num,
12103			    xio->scsiio.tag_type,
12104			    (xio->io_hdr.blocked_links.tqe_prev
12105			    == NULL) ? "" : " BLOCKED",
12106			    (xio->io_hdr.flags &
12107			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12108			    (xio->io_hdr.flags &
12109			    CTL_FLAG_ABORT) ? " ABORT" : "",
12110			    (xio->io_hdr.flags &
12111			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12112		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12113		sbuf_finish(&sb);
12114		printf("%s\n", sbuf_data(&sb));
12115#endif
12116
12117		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12118		 && (xio->io_hdr.nexus.initid.id ==
12119		     io->io_hdr.nexus.initid.id)) {
12120			/*
12121			 * If the abort says that the task is untagged, the
12122			 * task in the queue must be untagged.  Otherwise,
12123			 * we just check to see whether the tag numbers
12124			 * match.  This is because the QLogic firmware
12125			 * doesn't pass back the tag type in an abort
12126			 * request.
12127			 */
12128#if 0
12129			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12130			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12131			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12132#endif
12133			/*
12134			 * XXX KDM we've got problems with FC, because it
12135			 * doesn't send down a tag type with aborts.  So we
12136			 * can only really go by the tag number...
12137			 * This may cause problems with parallel SCSI.
12138			 * Need to figure that out!!
12139			 */
12140			if (xio->scsiio.tag_num == io->taskio.tag_num) {
12141				xio->io_hdr.flags |= CTL_FLAG_ABORT;
12142				found = 1;
12143				if ((io->io_hdr.flags &
12144				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
12145				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12146					union ctl_ha_msg msg_info;
12147
12148					io->io_hdr.flags |=
12149					                CTL_FLAG_SENT_2OTHER_SC;
12150					msg_info.hdr.nexus = io->io_hdr.nexus;
12151					msg_info.task.task_action =
12152						CTL_TASK_ABORT_TASK;
12153					msg_info.task.tag_num =
12154						io->taskio.tag_num;
12155					msg_info.task.tag_type =
12156						io->taskio.tag_type;
12157					msg_info.hdr.msg_type =
12158						CTL_MSG_MANAGE_TASKS;
12159					msg_info.hdr.original_sc = NULL;
12160					msg_info.hdr.serializing_sc = NULL;
12161#if 0
12162					printf("Sent Abort to other side\n");
12163#endif
12164					if (CTL_HA_STATUS_SUCCESS !=
12165					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12166		    				(void *)&msg_info,
12167						sizeof(msg_info), 0)) {
12168					}
12169				}
12170#if 0
12171				printf("ctl_abort_task: found I/O to abort\n");
12172#endif
12173				break;
12174			}
12175		}
12176	}
12177	mtx_unlock(&lun->lun_lock);
12178
12179	if (found == 0) {
12180		/*
12181		 * This isn't really an error.  It's entirely possible for
12182		 * the abort and command completion to cross on the wire.
12183		 * This is more of an informative/diagnostic error.
12184		 */
12185#if 0
12186		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12187		       "%d:%d:%d:%d tag %d type %d\n",
12188		       io->io_hdr.nexus.initid.id,
12189		       io->io_hdr.nexus.targ_port,
12190		       io->io_hdr.nexus.targ_target.id,
12191		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12192		       io->taskio.tag_type);
12193#endif
12194	}
12195	return (0);
12196}
12197
12198static void
12199ctl_run_task(union ctl_io *io)
12200{
12201	struct ctl_softc *ctl_softc = control_softc;
12202	int retval = 1;
12203	const char *task_desc;
12204
12205	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12206
12207	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12208	    ("ctl_run_task: Unextected io_type %d\n",
12209	     io->io_hdr.io_type));
12210
12211	task_desc = ctl_scsi_task_string(&io->taskio);
12212	if (task_desc != NULL) {
12213#ifdef NEEDTOPORT
12214		csevent_log(CSC_CTL | CSC_SHELF_SW |
12215			    CTL_TASK_REPORT,
12216			    csevent_LogType_Trace,
12217			    csevent_Severity_Information,
12218			    csevent_AlertLevel_Green,
12219			    csevent_FRU_Firmware,
12220			    csevent_FRU_Unknown,
12221			    "CTL: received task: %s",task_desc);
12222#endif
12223	} else {
12224#ifdef NEEDTOPORT
12225		csevent_log(CSC_CTL | CSC_SHELF_SW |
12226			    CTL_TASK_REPORT,
12227			    csevent_LogType_Trace,
12228			    csevent_Severity_Information,
12229			    csevent_AlertLevel_Green,
12230			    csevent_FRU_Firmware,
12231			    csevent_FRU_Unknown,
12232			    "CTL: received unknown task "
12233			    "type: %d (%#x)",
12234			    io->taskio.task_action,
12235			    io->taskio.task_action);
12236#endif
12237	}
12238	switch (io->taskio.task_action) {
12239	case CTL_TASK_ABORT_TASK:
12240		retval = ctl_abort_task(io);
12241		break;
12242	case CTL_TASK_ABORT_TASK_SET:
12243	case CTL_TASK_CLEAR_TASK_SET:
12244		retval = ctl_abort_task_set(io);
12245		break;
12246	case CTL_TASK_CLEAR_ACA:
12247		break;
12248	case CTL_TASK_I_T_NEXUS_RESET:
12249		retval = ctl_i_t_nexus_reset(io);
12250		break;
12251	case CTL_TASK_LUN_RESET: {
12252		struct ctl_lun *lun;
12253		uint32_t targ_lun;
12254
12255		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12256		mtx_lock(&ctl_softc->ctl_lock);
12257		if ((targ_lun < CTL_MAX_LUNS)
12258		 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12259			lun = ctl_softc->ctl_luns[targ_lun];
12260		else {
12261			mtx_unlock(&ctl_softc->ctl_lock);
12262			retval = 1;
12263			break;
12264		}
12265
12266		if (!(io->io_hdr.flags &
12267		    CTL_FLAG_FROM_OTHER_SC)) {
12268			union ctl_ha_msg msg_info;
12269
12270			io->io_hdr.flags |=
12271				CTL_FLAG_SENT_2OTHER_SC;
12272			msg_info.hdr.msg_type =
12273				CTL_MSG_MANAGE_TASKS;
12274			msg_info.hdr.nexus = io->io_hdr.nexus;
12275			msg_info.task.task_action =
12276				CTL_TASK_LUN_RESET;
12277			msg_info.hdr.original_sc = NULL;
12278			msg_info.hdr.serializing_sc = NULL;
12279			if (CTL_HA_STATUS_SUCCESS !=
12280			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12281			    (void *)&msg_info,
12282			    sizeof(msg_info), 0)) {
12283			}
12284		}
12285
12286		retval = ctl_lun_reset(lun, io,
12287				       CTL_UA_LUN_RESET);
12288		mtx_unlock(&ctl_softc->ctl_lock);
12289		break;
12290	}
12291	case CTL_TASK_TARGET_RESET:
12292		retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12293		break;
12294	case CTL_TASK_BUS_RESET:
12295		retval = ctl_bus_reset(ctl_softc, io);
12296		break;
12297	case CTL_TASK_PORT_LOGIN:
12298		break;
12299	case CTL_TASK_PORT_LOGOUT:
12300		break;
12301	default:
12302		printf("ctl_run_task: got unknown task management event %d\n",
12303		       io->taskio.task_action);
12304		break;
12305	}
12306	if (retval == 0)
12307		io->io_hdr.status = CTL_SUCCESS;
12308	else
12309		io->io_hdr.status = CTL_ERROR;
12310	ctl_done(io);
12311}
12312
12313/*
12314 * For HA operation.  Handle commands that come in from the other
12315 * controller.
12316 */
12317static void
12318ctl_handle_isc(union ctl_io *io)
12319{
12320	int free_io;
12321	struct ctl_lun *lun;
12322	struct ctl_softc *ctl_softc;
12323	uint32_t targ_lun;
12324
12325	ctl_softc = control_softc;
12326
12327	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12328	lun = ctl_softc->ctl_luns[targ_lun];
12329
12330	switch (io->io_hdr.msg_type) {
12331	case CTL_MSG_SERIALIZE:
12332		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12333		break;
12334	case CTL_MSG_R2R: {
12335		const struct ctl_cmd_entry *entry;
12336
12337		/*
12338		 * This is only used in SER_ONLY mode.
12339		 */
12340		free_io = 0;
12341		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12342		mtx_lock(&lun->lun_lock);
12343		if (ctl_scsiio_lun_check(ctl_softc, lun,
12344		    entry, (struct ctl_scsiio *)io) != 0) {
12345			mtx_unlock(&lun->lun_lock);
12346			ctl_done(io);
12347			break;
12348		}
12349		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12350		mtx_unlock(&lun->lun_lock);
12351		ctl_enqueue_rtr(io);
12352		break;
12353	}
12354	case CTL_MSG_FINISH_IO:
12355		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12356			free_io = 0;
12357			ctl_done(io);
12358		} else {
12359			free_io = 1;
12360			mtx_lock(&lun->lun_lock);
12361			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12362				     ooa_links);
12363			ctl_check_blocked(lun);
12364			mtx_unlock(&lun->lun_lock);
12365		}
12366		break;
12367	case CTL_MSG_PERS_ACTION:
12368		ctl_hndl_per_res_out_on_other_sc(
12369			(union ctl_ha_msg *)&io->presio.pr_msg);
12370		free_io = 1;
12371		break;
12372	case CTL_MSG_BAD_JUJU:
12373		free_io = 0;
12374		ctl_done(io);
12375		break;
12376	case CTL_MSG_DATAMOVE:
12377		/* Only used in XFER mode */
12378		free_io = 0;
12379		ctl_datamove_remote(io);
12380		break;
12381	case CTL_MSG_DATAMOVE_DONE:
12382		/* Only used in XFER mode */
12383		free_io = 0;
12384		io->scsiio.be_move_done(io);
12385		break;
12386	default:
12387		free_io = 1;
12388		printf("%s: Invalid message type %d\n",
12389		       __func__, io->io_hdr.msg_type);
12390		break;
12391	}
12392	if (free_io)
12393		ctl_free_io(io);
12394
12395}
12396
12397
12398/*
12399 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12400 * there is no match.
12401 */
12402static ctl_lun_error_pattern
12403ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12404{
12405	const struct ctl_cmd_entry *entry;
12406	ctl_lun_error_pattern filtered_pattern, pattern;
12407
12408	pattern = desc->error_pattern;
12409
12410	/*
12411	 * XXX KDM we need more data passed into this function to match a
12412	 * custom pattern, and we actually need to implement custom pattern
12413	 * matching.
12414	 */
12415	if (pattern & CTL_LUN_PAT_CMD)
12416		return (CTL_LUN_PAT_CMD);
12417
12418	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12419		return (CTL_LUN_PAT_ANY);
12420
12421	entry = ctl_get_cmd_entry(ctsio, NULL);
12422
12423	filtered_pattern = entry->pattern & pattern;
12424
12425	/*
12426	 * If the user requested specific flags in the pattern (e.g.
12427	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12428	 * flags.
12429	 *
12430	 * If the user did not specify any flags, it doesn't matter whether
12431	 * or not the command supports the flags.
12432	 */
12433	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12434	     (pattern & ~CTL_LUN_PAT_MASK))
12435		return (CTL_LUN_PAT_NONE);
12436
12437	/*
12438	 * If the user asked for a range check, see if the requested LBA
12439	 * range overlaps with this command's LBA range.
12440	 */
12441	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12442		uint64_t lba1;
12443		uint64_t len1;
12444		ctl_action action;
12445		int retval;
12446
12447		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12448		if (retval != 0)
12449			return (CTL_LUN_PAT_NONE);
12450
12451		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12452					      desc->lba_range.len);
12453		/*
12454		 * A "pass" means that the LBA ranges don't overlap, so
12455		 * this doesn't match the user's range criteria.
12456		 */
12457		if (action == CTL_ACTION_PASS)
12458			return (CTL_LUN_PAT_NONE);
12459	}
12460
12461	return (filtered_pattern);
12462}
12463
12464static void
12465ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12466{
12467	struct ctl_error_desc *desc, *desc2;
12468
12469	mtx_assert(&lun->lun_lock, MA_OWNED);
12470
12471	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12472		ctl_lun_error_pattern pattern;
12473		/*
12474		 * Check to see whether this particular command matches
12475		 * the pattern in the descriptor.
12476		 */
12477		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12478		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12479			continue;
12480
12481		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12482		case CTL_LUN_INJ_ABORTED:
12483			ctl_set_aborted(&io->scsiio);
12484			break;
12485		case CTL_LUN_INJ_MEDIUM_ERR:
12486			ctl_set_medium_error(&io->scsiio);
12487			break;
12488		case CTL_LUN_INJ_UA:
12489			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12490			 * OCCURRED */
12491			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12492			break;
12493		case CTL_LUN_INJ_CUSTOM:
12494			/*
12495			 * We're assuming the user knows what he is doing.
12496			 * Just copy the sense information without doing
12497			 * checks.
12498			 */
12499			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12500			      ctl_min(sizeof(desc->custom_sense),
12501				      sizeof(io->scsiio.sense_data)));
12502			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12503			io->scsiio.sense_len = SSD_FULL_SIZE;
12504			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12505			break;
12506		case CTL_LUN_INJ_NONE:
12507		default:
12508			/*
12509			 * If this is an error injection type we don't know
12510			 * about, clear the continuous flag (if it is set)
12511			 * so it will get deleted below.
12512			 */
12513			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12514			break;
12515		}
12516		/*
12517		 * By default, each error injection action is a one-shot
12518		 */
12519		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12520			continue;
12521
12522		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12523
12524		free(desc, M_CTL);
12525	}
12526}
12527
12528#ifdef CTL_IO_DELAY
12529static void
12530ctl_datamove_timer_wakeup(void *arg)
12531{
12532	union ctl_io *io;
12533
12534	io = (union ctl_io *)arg;
12535
12536	ctl_datamove(io);
12537}
12538#endif /* CTL_IO_DELAY */
12539
12540void
12541ctl_datamove(union ctl_io *io)
12542{
12543	void (*fe_datamove)(union ctl_io *io);
12544
12545	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12546
12547	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12548
12549#ifdef CTL_TIME_IO
12550	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12551		char str[256];
12552		char path_str[64];
12553		struct sbuf sb;
12554
12555		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12556		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12557
12558		sbuf_cat(&sb, path_str);
12559		switch (io->io_hdr.io_type) {
12560		case CTL_IO_SCSI:
12561			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12562			sbuf_printf(&sb, "\n");
12563			sbuf_cat(&sb, path_str);
12564			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12565				    io->scsiio.tag_num, io->scsiio.tag_type);
12566			break;
12567		case CTL_IO_TASK:
12568			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12569				    "Tag Type: %d\n", io->taskio.task_action,
12570				    io->taskio.tag_num, io->taskio.tag_type);
12571			break;
12572		default:
12573			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12574			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12575			break;
12576		}
12577		sbuf_cat(&sb, path_str);
12578		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12579			    (intmax_t)time_uptime - io->io_hdr.start_time);
12580		sbuf_finish(&sb);
12581		printf("%s", sbuf_data(&sb));
12582	}
12583#endif /* CTL_TIME_IO */
12584
12585#ifdef CTL_IO_DELAY
12586	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12587		struct ctl_lun *lun;
12588
12589		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12590
12591		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12592	} else {
12593		struct ctl_lun *lun;
12594
12595		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12596		if ((lun != NULL)
12597		 && (lun->delay_info.datamove_delay > 0)) {
12598			struct callout *callout;
12599
12600			callout = (struct callout *)&io->io_hdr.timer_bytes;
12601			callout_init(callout, /*mpsafe*/ 1);
12602			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12603			callout_reset(callout,
12604				      lun->delay_info.datamove_delay * hz,
12605				      ctl_datamove_timer_wakeup, io);
12606			if (lun->delay_info.datamove_type ==
12607			    CTL_DELAY_TYPE_ONESHOT)
12608				lun->delay_info.datamove_delay = 0;
12609			return;
12610		}
12611	}
12612#endif
12613
12614	/*
12615	 * This command has been aborted.  Set the port status, so we fail
12616	 * the data move.
12617	 */
12618	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12619		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12620		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12621		       io->io_hdr.nexus.targ_port,
12622		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12623		       io->io_hdr.nexus.targ_lun);
12624		io->io_hdr.port_status = 31337;
12625		/*
12626		 * Note that the backend, in this case, will get the
12627		 * callback in its context.  In other cases it may get
12628		 * called in the frontend's interrupt thread context.
12629		 */
12630		io->scsiio.be_move_done(io);
12631		return;
12632	}
12633
12634	/* Don't confuse frontend with zero length data move. */
12635	if (io->scsiio.kern_data_len == 0) {
12636		io->scsiio.be_move_done(io);
12637		return;
12638	}
12639
12640	/*
12641	 * If we're in XFER mode and this I/O is from the other shelf
12642	 * controller, we need to send the DMA to the other side to
12643	 * actually transfer the data to/from the host.  In serialize only
12644	 * mode the transfer happens below CTL and ctl_datamove() is only
12645	 * called on the machine that originally received the I/O.
12646	 */
12647	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12648	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12649		union ctl_ha_msg msg;
12650		uint32_t sg_entries_sent;
12651		int do_sg_copy;
12652		int i;
12653
12654		memset(&msg, 0, sizeof(msg));
12655		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12656		msg.hdr.original_sc = io->io_hdr.original_sc;
12657		msg.hdr.serializing_sc = io;
12658		msg.hdr.nexus = io->io_hdr.nexus;
12659		msg.dt.flags = io->io_hdr.flags;
12660		/*
12661		 * We convert everything into a S/G list here.  We can't
12662		 * pass by reference, only by value between controllers.
12663		 * So we can't pass a pointer to the S/G list, only as many
12664		 * S/G entries as we can fit in here.  If it's possible for
12665		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12666		 * then we need to break this up into multiple transfers.
12667		 */
12668		if (io->scsiio.kern_sg_entries == 0) {
12669			msg.dt.kern_sg_entries = 1;
12670			/*
12671			 * If this is in cached memory, flush the cache
12672			 * before we send the DMA request to the other
12673			 * controller.  We want to do this in either the
12674			 * read or the write case.  The read case is
12675			 * straightforward.  In the write case, we want to
12676			 * make sure nothing is in the local cache that
12677			 * could overwrite the DMAed data.
12678			 */
12679			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12680				/*
12681				 * XXX KDM use bus_dmamap_sync() here.
12682				 */
12683			}
12684
12685			/*
12686			 * Convert to a physical address if this is a
12687			 * virtual address.
12688			 */
12689			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12690				msg.dt.sg_list[0].addr =
12691					io->scsiio.kern_data_ptr;
12692			} else {
12693				/*
12694				 * XXX KDM use busdma here!
12695				 */
12696#if 0
12697				msg.dt.sg_list[0].addr = (void *)
12698					vtophys(io->scsiio.kern_data_ptr);
12699#endif
12700			}
12701
12702			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12703			do_sg_copy = 0;
12704		} else {
12705			struct ctl_sg_entry *sgl;
12706
12707			do_sg_copy = 1;
12708			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12709			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12710			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12711				/*
12712				 * XXX KDM use bus_dmamap_sync() here.
12713				 */
12714			}
12715		}
12716
12717		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12718		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12719		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12720		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12721		msg.dt.sg_sequence = 0;
12722
12723		/*
12724		 * Loop until we've sent all of the S/G entries.  On the
12725		 * other end, we'll recompose these S/G entries into one
12726		 * contiguous list before passing it to the
12727		 */
12728		for (sg_entries_sent = 0; sg_entries_sent <
12729		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12730			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12731				sizeof(msg.dt.sg_list[0])),
12732				msg.dt.kern_sg_entries - sg_entries_sent);
12733
12734			if (do_sg_copy != 0) {
12735				struct ctl_sg_entry *sgl;
12736				int j;
12737
12738				sgl = (struct ctl_sg_entry *)
12739					io->scsiio.kern_data_ptr;
12740				/*
12741				 * If this is in cached memory, flush the cache
12742				 * before we send the DMA request to the other
12743				 * controller.  We want to do this in either
12744				 * the * read or the write case.  The read
12745				 * case is straightforward.  In the write
12746				 * case, we want to make sure nothing is
12747				 * in the local cache that could overwrite
12748				 * the DMAed data.
12749				 */
12750
12751				for (i = sg_entries_sent, j = 0;
12752				     i < msg.dt.cur_sg_entries; i++, j++) {
12753					if ((io->io_hdr.flags &
12754					     CTL_FLAG_NO_DATASYNC) == 0) {
12755						/*
12756						 * XXX KDM use bus_dmamap_sync()
12757						 */
12758					}
12759					if ((io->io_hdr.flags &
12760					     CTL_FLAG_BUS_ADDR) == 0) {
12761						/*
12762						 * XXX KDM use busdma.
12763						 */
12764#if 0
12765						msg.dt.sg_list[j].addr =(void *)
12766						       vtophys(sgl[i].addr);
12767#endif
12768					} else {
12769						msg.dt.sg_list[j].addr =
12770							sgl[i].addr;
12771					}
12772					msg.dt.sg_list[j].len = sgl[i].len;
12773				}
12774			}
12775
12776			sg_entries_sent += msg.dt.cur_sg_entries;
12777			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12778				msg.dt.sg_last = 1;
12779			else
12780				msg.dt.sg_last = 0;
12781
12782			/*
12783			 * XXX KDM drop and reacquire the lock here?
12784			 */
12785			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12786			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12787				/*
12788				 * XXX do something here.
12789				 */
12790			}
12791
12792			msg.dt.sent_sg_entries = sg_entries_sent;
12793		}
12794		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12795		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12796			ctl_failover_io(io, /*have_lock*/ 0);
12797
12798	} else {
12799
12800		/*
12801		 * Lookup the fe_datamove() function for this particular
12802		 * front end.
12803		 */
12804		fe_datamove =
12805		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12806
12807		fe_datamove(io);
12808	}
12809}
12810
12811static void
12812ctl_send_datamove_done(union ctl_io *io, int have_lock)
12813{
12814	union ctl_ha_msg msg;
12815	int isc_status;
12816
12817	memset(&msg, 0, sizeof(msg));
12818
12819	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12820	msg.hdr.original_sc = io;
12821	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12822	msg.hdr.nexus = io->io_hdr.nexus;
12823	msg.hdr.status = io->io_hdr.status;
12824	msg.scsi.tag_num = io->scsiio.tag_num;
12825	msg.scsi.tag_type = io->scsiio.tag_type;
12826	msg.scsi.scsi_status = io->scsiio.scsi_status;
12827	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12828	       sizeof(io->scsiio.sense_data));
12829	msg.scsi.sense_len = io->scsiio.sense_len;
12830	msg.scsi.sense_residual = io->scsiio.sense_residual;
12831	msg.scsi.fetd_status = io->io_hdr.port_status;
12832	msg.scsi.residual = io->scsiio.residual;
12833	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12834
12835	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12836		ctl_failover_io(io, /*have_lock*/ have_lock);
12837		return;
12838	}
12839
12840	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12841	if (isc_status > CTL_HA_STATUS_SUCCESS) {
12842		/* XXX do something if this fails */
12843	}
12844
12845}
12846
12847/*
12848 * The DMA to the remote side is done, now we need to tell the other side
12849 * we're done so it can continue with its data movement.
12850 */
12851static void
12852ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12853{
12854	union ctl_io *io;
12855
12856	io = rq->context;
12857
12858	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12859		printf("%s: ISC DMA write failed with error %d", __func__,
12860		       rq->ret);
12861		ctl_set_internal_failure(&io->scsiio,
12862					 /*sks_valid*/ 1,
12863					 /*retry_count*/ rq->ret);
12864	}
12865
12866	ctl_dt_req_free(rq);
12867
12868	/*
12869	 * In this case, we had to malloc the memory locally.  Free it.
12870	 */
12871	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12872		int i;
12873		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12874			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12875	}
12876	/*
12877	 * The data is in local and remote memory, so now we need to send
12878	 * status (good or back) back to the other side.
12879	 */
12880	ctl_send_datamove_done(io, /*have_lock*/ 0);
12881}
12882
12883/*
12884 * We've moved the data from the host/controller into local memory.  Now we
12885 * need to push it over to the remote controller's memory.
12886 */
12887static int
12888ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12889{
12890	int retval;
12891
12892	retval = 0;
12893
12894	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12895					  ctl_datamove_remote_write_cb);
12896
12897	return (retval);
12898}
12899
12900static void
12901ctl_datamove_remote_write(union ctl_io *io)
12902{
12903	int retval;
12904	void (*fe_datamove)(union ctl_io *io);
12905
12906	/*
12907	 * - Get the data from the host/HBA into local memory.
12908	 * - DMA memory from the local controller to the remote controller.
12909	 * - Send status back to the remote controller.
12910	 */
12911
12912	retval = ctl_datamove_remote_sgl_setup(io);
12913	if (retval != 0)
12914		return;
12915
12916	/* Switch the pointer over so the FETD knows what to do */
12917	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12918
12919	/*
12920	 * Use a custom move done callback, since we need to send completion
12921	 * back to the other controller, not to the backend on this side.
12922	 */
12923	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12924
12925	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12926
12927	fe_datamove(io);
12928
12929	return;
12930
12931}
12932
12933static int
12934ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12935{
12936#if 0
12937	char str[256];
12938	char path_str[64];
12939	struct sbuf sb;
12940#endif
12941
12942	/*
12943	 * In this case, we had to malloc the memory locally.  Free it.
12944	 */
12945	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12946		int i;
12947		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12948			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12949	}
12950
12951#if 0
12952	scsi_path_string(io, path_str, sizeof(path_str));
12953	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12954	sbuf_cat(&sb, path_str);
12955	scsi_command_string(&io->scsiio, NULL, &sb);
12956	sbuf_printf(&sb, "\n");
12957	sbuf_cat(&sb, path_str);
12958	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12959		    io->scsiio.tag_num, io->scsiio.tag_type);
12960	sbuf_cat(&sb, path_str);
12961	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12962		    io->io_hdr.flags, io->io_hdr.status);
12963	sbuf_finish(&sb);
12964	printk("%s", sbuf_data(&sb));
12965#endif
12966
12967
12968	/*
12969	 * The read is done, now we need to send status (good or bad) back
12970	 * to the other side.
12971	 */
12972	ctl_send_datamove_done(io, /*have_lock*/ 0);
12973
12974	return (0);
12975}
12976
12977static void
12978ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12979{
12980	union ctl_io *io;
12981	void (*fe_datamove)(union ctl_io *io);
12982
12983	io = rq->context;
12984
12985	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12986		printf("%s: ISC DMA read failed with error %d", __func__,
12987		       rq->ret);
12988		ctl_set_internal_failure(&io->scsiio,
12989					 /*sks_valid*/ 1,
12990					 /*retry_count*/ rq->ret);
12991	}
12992
12993	ctl_dt_req_free(rq);
12994
12995	/* Switch the pointer over so the FETD knows what to do */
12996	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12997
12998	/*
12999	 * Use a custom move done callback, since we need to send completion
13000	 * back to the other controller, not to the backend on this side.
13001	 */
13002	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
13003
13004	/* XXX KDM add checks like the ones in ctl_datamove? */
13005
13006	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13007
13008	fe_datamove(io);
13009}
13010
13011static int
13012ctl_datamove_remote_sgl_setup(union ctl_io *io)
13013{
13014	struct ctl_sg_entry *local_sglist, *remote_sglist;
13015	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13016	struct ctl_softc *softc;
13017	int retval;
13018	int i;
13019
13020	retval = 0;
13021	softc = control_softc;
13022
13023	local_sglist = io->io_hdr.local_sglist;
13024	local_dma_sglist = io->io_hdr.local_dma_sglist;
13025	remote_sglist = io->io_hdr.remote_sglist;
13026	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13027
13028	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13029		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13030			local_sglist[i].len = remote_sglist[i].len;
13031
13032			/*
13033			 * XXX Detect the situation where the RS-level I/O
13034			 * redirector on the other side has already read the
13035			 * data off of the AOR RS on this side, and
13036			 * transferred it to remote (mirror) memory on the
13037			 * other side.  Since we already have the data in
13038			 * memory here, we just need to use it.
13039			 *
13040			 * XXX KDM this can probably be removed once we
13041			 * get the cache device code in and take the
13042			 * current AOR implementation out.
13043			 */
13044#ifdef NEEDTOPORT
13045			if ((remote_sglist[i].addr >=
13046			     (void *)vtophys(softc->mirr->addr))
13047			 && (remote_sglist[i].addr <
13048			     ((void *)vtophys(softc->mirr->addr) +
13049			     CacheMirrorOffset))) {
13050				local_sglist[i].addr = remote_sglist[i].addr -
13051					CacheMirrorOffset;
13052				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13053				     CTL_FLAG_DATA_IN)
13054					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13055			} else {
13056				local_sglist[i].addr = remote_sglist[i].addr +
13057					CacheMirrorOffset;
13058			}
13059#endif
13060#if 0
13061			printf("%s: local %p, remote %p, len %d\n",
13062			       __func__, local_sglist[i].addr,
13063			       remote_sglist[i].addr, local_sglist[i].len);
13064#endif
13065		}
13066	} else {
13067		uint32_t len_to_go;
13068
13069		/*
13070		 * In this case, we don't have automatically allocated
13071		 * memory for this I/O on this controller.  This typically
13072		 * happens with internal CTL I/O -- e.g. inquiry, mode
13073		 * sense, etc.  Anything coming from RAIDCore will have
13074		 * a mirror area available.
13075		 */
13076		len_to_go = io->scsiio.kern_data_len;
13077
13078		/*
13079		 * Clear the no datasync flag, we have to use malloced
13080		 * buffers.
13081		 */
13082		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13083
13084		/*
13085		 * The difficult thing here is that the size of the various
13086		 * S/G segments may be different than the size from the
13087		 * remote controller.  That'll make it harder when DMAing
13088		 * the data back to the other side.
13089		 */
13090		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13091		     sizeof(io->io_hdr.remote_sglist[0])) &&
13092		     (len_to_go > 0); i++) {
13093			local_sglist[i].len = ctl_min(len_to_go, 131072);
13094			CTL_SIZE_8B(local_dma_sglist[i].len,
13095				    local_sglist[i].len);
13096			local_sglist[i].addr =
13097				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13098
13099			local_dma_sglist[i].addr = local_sglist[i].addr;
13100
13101			if (local_sglist[i].addr == NULL) {
13102				int j;
13103
13104				printf("malloc failed for %zd bytes!",
13105				       local_dma_sglist[i].len);
13106				for (j = 0; j < i; j++) {
13107					free(local_sglist[j].addr, M_CTL);
13108				}
13109				ctl_set_internal_failure(&io->scsiio,
13110							 /*sks_valid*/ 1,
13111							 /*retry_count*/ 4857);
13112				retval = 1;
13113				goto bailout_error;
13114
13115			}
13116			/* XXX KDM do we need a sync here? */
13117
13118			len_to_go -= local_sglist[i].len;
13119		}
13120		/*
13121		 * Reset the number of S/G entries accordingly.  The
13122		 * original number of S/G entries is available in
13123		 * rem_sg_entries.
13124		 */
13125		io->scsiio.kern_sg_entries = i;
13126
13127#if 0
13128		printf("%s: kern_sg_entries = %d\n", __func__,
13129		       io->scsiio.kern_sg_entries);
13130		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13131			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13132			       local_sglist[i].addr, local_sglist[i].len,
13133			       local_dma_sglist[i].len);
13134#endif
13135	}
13136
13137
13138	return (retval);
13139
13140bailout_error:
13141
13142	ctl_send_datamove_done(io, /*have_lock*/ 0);
13143
13144	return (retval);
13145}
13146
13147static int
13148ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13149			 ctl_ha_dt_cb callback)
13150{
13151	struct ctl_ha_dt_req *rq;
13152	struct ctl_sg_entry *remote_sglist, *local_sglist;
13153	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13154	uint32_t local_used, remote_used, total_used;
13155	int retval;
13156	int i, j;
13157
13158	retval = 0;
13159
13160	rq = ctl_dt_req_alloc();
13161
13162	/*
13163	 * If we failed to allocate the request, and if the DMA didn't fail
13164	 * anyway, set busy status.  This is just a resource allocation
13165	 * failure.
13166	 */
13167	if ((rq == NULL)
13168	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13169		ctl_set_busy(&io->scsiio);
13170
13171	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13172
13173		if (rq != NULL)
13174			ctl_dt_req_free(rq);
13175
13176		/*
13177		 * The data move failed.  We need to return status back
13178		 * to the other controller.  No point in trying to DMA
13179		 * data to the remote controller.
13180		 */
13181
13182		ctl_send_datamove_done(io, /*have_lock*/ 0);
13183
13184		retval = 1;
13185
13186		goto bailout;
13187	}
13188
13189	local_sglist = io->io_hdr.local_sglist;
13190	local_dma_sglist = io->io_hdr.local_dma_sglist;
13191	remote_sglist = io->io_hdr.remote_sglist;
13192	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13193	local_used = 0;
13194	remote_used = 0;
13195	total_used = 0;
13196
13197	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13198		rq->ret = CTL_HA_STATUS_SUCCESS;
13199		rq->context = io;
13200		callback(rq);
13201		goto bailout;
13202	}
13203
13204	/*
13205	 * Pull/push the data over the wire from/to the other controller.
13206	 * This takes into account the possibility that the local and
13207	 * remote sglists may not be identical in terms of the size of
13208	 * the elements and the number of elements.
13209	 *
13210	 * One fundamental assumption here is that the length allocated for
13211	 * both the local and remote sglists is identical.  Otherwise, we've
13212	 * essentially got a coding error of some sort.
13213	 */
13214	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13215		int isc_ret;
13216		uint32_t cur_len, dma_length;
13217		uint8_t *tmp_ptr;
13218
13219		rq->id = CTL_HA_DATA_CTL;
13220		rq->command = command;
13221		rq->context = io;
13222
13223		/*
13224		 * Both pointers should be aligned.  But it is possible
13225		 * that the allocation length is not.  They should both
13226		 * also have enough slack left over at the end, though,
13227		 * to round up to the next 8 byte boundary.
13228		 */
13229		cur_len = ctl_min(local_sglist[i].len - local_used,
13230				  remote_sglist[j].len - remote_used);
13231
13232		/*
13233		 * In this case, we have a size issue and need to decrease
13234		 * the size, except in the case where we actually have less
13235		 * than 8 bytes left.  In that case, we need to increase
13236		 * the DMA length to get the last bit.
13237		 */
13238		if ((cur_len & 0x7) != 0) {
13239			if (cur_len > 0x7) {
13240				cur_len = cur_len - (cur_len & 0x7);
13241				dma_length = cur_len;
13242			} else {
13243				CTL_SIZE_8B(dma_length, cur_len);
13244			}
13245
13246		} else
13247			dma_length = cur_len;
13248
13249		/*
13250		 * If we had to allocate memory for this I/O, instead of using
13251		 * the non-cached mirror memory, we'll need to flush the cache
13252		 * before trying to DMA to the other controller.
13253		 *
13254		 * We could end up doing this multiple times for the same
13255		 * segment if we have a larger local segment than remote
13256		 * segment.  That shouldn't be an issue.
13257		 */
13258		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13259			/*
13260			 * XXX KDM use bus_dmamap_sync() here.
13261			 */
13262		}
13263
13264		rq->size = dma_length;
13265
13266		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13267		tmp_ptr += local_used;
13268
13269		/* Use physical addresses when talking to ISC hardware */
13270		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13271			/* XXX KDM use busdma */
13272#if 0
13273			rq->local = vtophys(tmp_ptr);
13274#endif
13275		} else
13276			rq->local = tmp_ptr;
13277
13278		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13279		tmp_ptr += remote_used;
13280		rq->remote = tmp_ptr;
13281
13282		rq->callback = NULL;
13283
13284		local_used += cur_len;
13285		if (local_used >= local_sglist[i].len) {
13286			i++;
13287			local_used = 0;
13288		}
13289
13290		remote_used += cur_len;
13291		if (remote_used >= remote_sglist[j].len) {
13292			j++;
13293			remote_used = 0;
13294		}
13295		total_used += cur_len;
13296
13297		if (total_used >= io->scsiio.kern_data_len)
13298			rq->callback = callback;
13299
13300		if ((rq->size & 0x7) != 0) {
13301			printf("%s: warning: size %d is not on 8b boundary\n",
13302			       __func__, rq->size);
13303		}
13304		if (((uintptr_t)rq->local & 0x7) != 0) {
13305			printf("%s: warning: local %p not on 8b boundary\n",
13306			       __func__, rq->local);
13307		}
13308		if (((uintptr_t)rq->remote & 0x7) != 0) {
13309			printf("%s: warning: remote %p not on 8b boundary\n",
13310			       __func__, rq->local);
13311		}
13312#if 0
13313		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13314		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13315		       rq->local, rq->remote, rq->size);
13316#endif
13317
13318		isc_ret = ctl_dt_single(rq);
13319		if (isc_ret == CTL_HA_STATUS_WAIT)
13320			continue;
13321
13322		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13323			rq->ret = CTL_HA_STATUS_SUCCESS;
13324		} else {
13325			rq->ret = isc_ret;
13326		}
13327		callback(rq);
13328		goto bailout;
13329	}
13330
13331bailout:
13332	return (retval);
13333
13334}
13335
13336static void
13337ctl_datamove_remote_read(union ctl_io *io)
13338{
13339	int retval;
13340	int i;
13341
13342	/*
13343	 * This will send an error to the other controller in the case of a
13344	 * failure.
13345	 */
13346	retval = ctl_datamove_remote_sgl_setup(io);
13347	if (retval != 0)
13348		return;
13349
13350	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13351					  ctl_datamove_remote_read_cb);
13352	if ((retval != 0)
13353	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13354		/*
13355		 * Make sure we free memory if there was an error..  The
13356		 * ctl_datamove_remote_xfer() function will send the
13357		 * datamove done message, or call the callback with an
13358		 * error if there is a problem.
13359		 */
13360		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13361			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13362	}
13363
13364	return;
13365}
13366
13367/*
13368 * Process a datamove request from the other controller.  This is used for
13369 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13370 * first.  Once that is complete, the data gets DMAed into the remote
13371 * controller's memory.  For reads, we DMA from the remote controller's
13372 * memory into our memory first, and then move it out to the FETD.
13373 */
13374static void
13375ctl_datamove_remote(union ctl_io *io)
13376{
13377	struct ctl_softc *softc;
13378
13379	softc = control_softc;
13380
13381	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13382
13383	/*
13384	 * Note that we look for an aborted I/O here, but don't do some of
13385	 * the other checks that ctl_datamove() normally does.
13386	 * We don't need to run the datamove delay code, since that should
13387	 * have been done if need be on the other controller.
13388	 */
13389	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13390		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13391		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13392		       io->io_hdr.nexus.targ_port,
13393		       io->io_hdr.nexus.targ_target.id,
13394		       io->io_hdr.nexus.targ_lun);
13395		io->io_hdr.port_status = 31338;
13396		ctl_send_datamove_done(io, /*have_lock*/ 0);
13397		return;
13398	}
13399
13400	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13401		ctl_datamove_remote_write(io);
13402	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13403		ctl_datamove_remote_read(io);
13404	} else {
13405		union ctl_ha_msg msg;
13406		struct scsi_sense_data *sense;
13407		uint8_t sks[3];
13408		int retry_count;
13409
13410		memset(&msg, 0, sizeof(msg));
13411
13412		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13413		msg.hdr.status = CTL_SCSI_ERROR;
13414		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13415
13416		retry_count = 4243;
13417
13418		sense = &msg.scsi.sense_data;
13419		sks[0] = SSD_SCS_VALID;
13420		sks[1] = (retry_count >> 8) & 0xff;
13421		sks[2] = retry_count & 0xff;
13422
13423		/* "Internal target failure" */
13424		scsi_set_sense_data(sense,
13425				    /*sense_format*/ SSD_TYPE_NONE,
13426				    /*current_error*/ 1,
13427				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13428				    /*asc*/ 0x44,
13429				    /*ascq*/ 0x00,
13430				    /*type*/ SSD_ELEM_SKS,
13431				    /*size*/ sizeof(sks),
13432				    /*data*/ sks,
13433				    SSD_ELEM_NONE);
13434
13435		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13436		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13437			ctl_failover_io(io, /*have_lock*/ 1);
13438			return;
13439		}
13440
13441		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13442		    CTL_HA_STATUS_SUCCESS) {
13443			/* XXX KDM what to do if this fails? */
13444		}
13445		return;
13446	}
13447
13448}
13449
13450static int
13451ctl_process_done(union ctl_io *io)
13452{
13453	struct ctl_lun *lun;
13454	struct ctl_softc *ctl_softc = control_softc;
13455	void (*fe_done)(union ctl_io *io);
13456	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13457
13458	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13459
13460	fe_done =
13461	    control_softc->ctl_ports[targ_port]->fe_done;
13462
13463#ifdef CTL_TIME_IO
13464	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13465		char str[256];
13466		char path_str[64];
13467		struct sbuf sb;
13468
13469		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13470		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13471
13472		sbuf_cat(&sb, path_str);
13473		switch (io->io_hdr.io_type) {
13474		case CTL_IO_SCSI:
13475			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13476			sbuf_printf(&sb, "\n");
13477			sbuf_cat(&sb, path_str);
13478			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13479				    io->scsiio.tag_num, io->scsiio.tag_type);
13480			break;
13481		case CTL_IO_TASK:
13482			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13483				    "Tag Type: %d\n", io->taskio.task_action,
13484				    io->taskio.tag_num, io->taskio.tag_type);
13485			break;
13486		default:
13487			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13488			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13489			break;
13490		}
13491		sbuf_cat(&sb, path_str);
13492		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13493			    (intmax_t)time_uptime - io->io_hdr.start_time);
13494		sbuf_finish(&sb);
13495		printf("%s", sbuf_data(&sb));
13496	}
13497#endif /* CTL_TIME_IO */
13498
13499	switch (io->io_hdr.io_type) {
13500	case CTL_IO_SCSI:
13501		break;
13502	case CTL_IO_TASK:
13503		if (bootverbose || (ctl_debug & CTL_DEBUG_INFO))
13504			ctl_io_error_print(io, NULL);
13505		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13506			ctl_free_io(io);
13507		else
13508			fe_done(io);
13509		return (CTL_RETVAL_COMPLETE);
13510	default:
13511		panic("ctl_process_done: invalid io type %d\n",
13512		      io->io_hdr.io_type);
13513		break; /* NOTREACHED */
13514	}
13515
13516	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13517	if (lun == NULL) {
13518		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13519				 io->io_hdr.nexus.targ_mapped_lun));
13520		goto bailout;
13521	}
13522
13523	mtx_lock(&lun->lun_lock);
13524
13525	/*
13526	 * Check to see if we have any errors to inject here.  We only
13527	 * inject errors for commands that don't already have errors set.
13528	 */
13529	if ((STAILQ_FIRST(&lun->error_list) != NULL)
13530	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
13531		ctl_inject_error(lun, io);
13532
13533	/*
13534	 * XXX KDM how do we treat commands that aren't completed
13535	 * successfully?
13536	 *
13537	 * XXX KDM should we also track I/O latency?
13538	 */
13539	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13540	    io->io_hdr.io_type == CTL_IO_SCSI) {
13541#ifdef CTL_TIME_IO
13542		struct bintime cur_bt;
13543#endif
13544		int type;
13545
13546		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13547		    CTL_FLAG_DATA_IN)
13548			type = CTL_STATS_READ;
13549		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13550		    CTL_FLAG_DATA_OUT)
13551			type = CTL_STATS_WRITE;
13552		else
13553			type = CTL_STATS_NO_IO;
13554
13555		lun->stats.ports[targ_port].bytes[type] +=
13556		    io->scsiio.kern_total_len;
13557		lun->stats.ports[targ_port].operations[type]++;
13558#ifdef CTL_TIME_IO
13559		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13560		   &io->io_hdr.dma_bt);
13561		lun->stats.ports[targ_port].num_dmas[type] +=
13562		    io->io_hdr.num_dmas;
13563		getbintime(&cur_bt);
13564		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13565		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13566#endif
13567	}
13568
13569	/*
13570	 * Remove this from the OOA queue.
13571	 */
13572	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13573
13574	/*
13575	 * Run through the blocked queue on this LUN and see if anything
13576	 * has become unblocked, now that this transaction is done.
13577	 */
13578	ctl_check_blocked(lun);
13579
13580	/*
13581	 * If the LUN has been invalidated, free it if there is nothing
13582	 * left on its OOA queue.
13583	 */
13584	if ((lun->flags & CTL_LUN_INVALID)
13585	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13586		mtx_unlock(&lun->lun_lock);
13587		mtx_lock(&ctl_softc->ctl_lock);
13588		ctl_free_lun(lun);
13589		mtx_unlock(&ctl_softc->ctl_lock);
13590	} else
13591		mtx_unlock(&lun->lun_lock);
13592
13593bailout:
13594
13595	/*
13596	 * If this command has been aborted, make sure we set the status
13597	 * properly.  The FETD is responsible for freeing the I/O and doing
13598	 * whatever it needs to do to clean up its state.
13599	 */
13600	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13601		ctl_set_task_aborted(&io->scsiio);
13602
13603	/*
13604	 * If enabled, print command error status.
13605	 * We don't print UAs unless debugging was enabled explicitly.
13606	 */
13607	do {
13608		if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)
13609			break;
13610		if (!bootverbose && (ctl_debug & CTL_DEBUG_INFO) == 0)
13611			break;
13612		if ((ctl_debug & CTL_DEBUG_INFO) == 0 &&
13613		    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR) &&
13614		     (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13615			int error_code, sense_key, asc, ascq;
13616
13617			scsi_extract_sense_len(&io->scsiio.sense_data,
13618			    io->scsiio.sense_len, &error_code, &sense_key,
13619			    &asc, &ascq, /*show_errors*/ 0);
13620			if (sense_key == SSD_KEY_UNIT_ATTENTION)
13621				break;
13622		}
13623
13624		ctl_io_error_print(io, NULL);
13625	} while (0);
13626
13627	/*
13628	 * Tell the FETD or the other shelf controller we're done with this
13629	 * command.  Note that only SCSI commands get to this point.  Task
13630	 * management commands are completed above.
13631	 *
13632	 * We only send status to the other controller if we're in XFER
13633	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13634	 * received the I/O (from CTL's perspective), and so the status is
13635	 * generated there.
13636	 *
13637	 * XXX KDM if we hold the lock here, we could cause a deadlock
13638	 * if the frontend comes back in in this context to queue
13639	 * something.
13640	 */
13641	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13642	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13643		union ctl_ha_msg msg;
13644
13645		memset(&msg, 0, sizeof(msg));
13646		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13647		msg.hdr.original_sc = io->io_hdr.original_sc;
13648		msg.hdr.nexus = io->io_hdr.nexus;
13649		msg.hdr.status = io->io_hdr.status;
13650		msg.scsi.scsi_status = io->scsiio.scsi_status;
13651		msg.scsi.tag_num = io->scsiio.tag_num;
13652		msg.scsi.tag_type = io->scsiio.tag_type;
13653		msg.scsi.sense_len = io->scsiio.sense_len;
13654		msg.scsi.sense_residual = io->scsiio.sense_residual;
13655		msg.scsi.residual = io->scsiio.residual;
13656		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13657		       sizeof(io->scsiio.sense_data));
13658		/*
13659		 * We copy this whether or not this is an I/O-related
13660		 * command.  Otherwise, we'd have to go and check to see
13661		 * whether it's a read/write command, and it really isn't
13662		 * worth it.
13663		 */
13664		memcpy(&msg.scsi.lbalen,
13665		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13666		       sizeof(msg.scsi.lbalen));
13667
13668		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13669				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13670			/* XXX do something here */
13671		}
13672
13673		ctl_free_io(io);
13674	} else
13675		fe_done(io);
13676
13677	return (CTL_RETVAL_COMPLETE);
13678}
13679
13680#ifdef CTL_WITH_CA
13681/*
13682 * Front end should call this if it doesn't do autosense.  When the request
13683 * sense comes back in from the initiator, we'll dequeue this and send it.
13684 */
13685int
13686ctl_queue_sense(union ctl_io *io)
13687{
13688	struct ctl_lun *lun;
13689	struct ctl_softc *ctl_softc;
13690	uint32_t initidx, targ_lun;
13691
13692	ctl_softc = control_softc;
13693
13694	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13695
13696	/*
13697	 * LUN lookup will likely move to the ctl_work_thread() once we
13698	 * have our new queueing infrastructure (that doesn't put things on
13699	 * a per-LUN queue initially).  That is so that we can handle
13700	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13701	 * can't deal with that right now.
13702	 */
13703	mtx_lock(&ctl_softc->ctl_lock);
13704
13705	/*
13706	 * If we don't have a LUN for this, just toss the sense
13707	 * information.
13708	 */
13709	targ_lun = io->io_hdr.nexus.targ_lun;
13710	targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13711	if ((targ_lun < CTL_MAX_LUNS)
13712	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
13713		lun = ctl_softc->ctl_luns[targ_lun];
13714	else
13715		goto bailout;
13716
13717	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13718
13719	mtx_lock(&lun->lun_lock);
13720	/*
13721	 * Already have CA set for this LUN...toss the sense information.
13722	 */
13723	if (ctl_is_set(lun->have_ca, initidx)) {
13724		mtx_unlock(&lun->lun_lock);
13725		goto bailout;
13726	}
13727
13728	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13729	       ctl_min(sizeof(lun->pending_sense[initidx]),
13730	       sizeof(io->scsiio.sense_data)));
13731	ctl_set_mask(lun->have_ca, initidx);
13732	mtx_unlock(&lun->lun_lock);
13733
13734bailout:
13735	mtx_unlock(&ctl_softc->ctl_lock);
13736
13737	ctl_free_io(io);
13738
13739	return (CTL_RETVAL_COMPLETE);
13740}
13741#endif
13742
13743/*
13744 * Primary command inlet from frontend ports.  All SCSI and task I/O
13745 * requests must go through this function.
13746 */
13747int
13748ctl_queue(union ctl_io *io)
13749{
13750	struct ctl_softc *ctl_softc;
13751
13752	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13753
13754	ctl_softc = control_softc;
13755
13756#ifdef CTL_TIME_IO
13757	io->io_hdr.start_time = time_uptime;
13758	getbintime(&io->io_hdr.start_bt);
13759#endif /* CTL_TIME_IO */
13760
13761	/* Map FE-specific LUN ID into global one. */
13762	io->io_hdr.nexus.targ_mapped_lun =
13763	    ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13764
13765	switch (io->io_hdr.io_type) {
13766	case CTL_IO_SCSI:
13767	case CTL_IO_TASK:
13768		if (ctl_debug & CTL_DEBUG_CDB)
13769			ctl_io_print(io);
13770		ctl_enqueue_incoming(io);
13771		break;
13772	default:
13773		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13774		return (EINVAL);
13775	}
13776
13777	return (CTL_RETVAL_COMPLETE);
13778}
13779
13780#ifdef CTL_IO_DELAY
13781static void
13782ctl_done_timer_wakeup(void *arg)
13783{
13784	union ctl_io *io;
13785
13786	io = (union ctl_io *)arg;
13787	ctl_done(io);
13788}
13789#endif /* CTL_IO_DELAY */
13790
13791void
13792ctl_done(union ctl_io *io)
13793{
13794	struct ctl_softc *ctl_softc;
13795
13796	ctl_softc = control_softc;
13797
13798	/*
13799	 * Enable this to catch duplicate completion issues.
13800	 */
13801#if 0
13802	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13803		printf("%s: type %d msg %d cdb %x iptl: "
13804		       "%d:%d:%d:%d tag 0x%04x "
13805		       "flag %#x status %x\n",
13806			__func__,
13807			io->io_hdr.io_type,
13808			io->io_hdr.msg_type,
13809			io->scsiio.cdb[0],
13810			io->io_hdr.nexus.initid.id,
13811			io->io_hdr.nexus.targ_port,
13812			io->io_hdr.nexus.targ_target.id,
13813			io->io_hdr.nexus.targ_lun,
13814			(io->io_hdr.io_type ==
13815			CTL_IO_TASK) ?
13816			io->taskio.tag_num :
13817			io->scsiio.tag_num,
13818		        io->io_hdr.flags,
13819			io->io_hdr.status);
13820	} else
13821		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13822#endif
13823
13824	/*
13825	 * This is an internal copy of an I/O, and should not go through
13826	 * the normal done processing logic.
13827	 */
13828	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13829		return;
13830
13831	/*
13832	 * We need to send a msg to the serializing shelf to finish the IO
13833	 * as well.  We don't send a finish message to the other shelf if
13834	 * this is a task management command.  Task management commands
13835	 * aren't serialized in the OOA queue, but rather just executed on
13836	 * both shelf controllers for commands that originated on that
13837	 * controller.
13838	 */
13839	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13840	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
13841		union ctl_ha_msg msg_io;
13842
13843		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13844		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13845		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13846		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13847		}
13848		/* continue on to finish IO */
13849	}
13850#ifdef CTL_IO_DELAY
13851	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13852		struct ctl_lun *lun;
13853
13854		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13855
13856		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13857	} else {
13858		struct ctl_lun *lun;
13859
13860		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13861
13862		if ((lun != NULL)
13863		 && (lun->delay_info.done_delay > 0)) {
13864			struct callout *callout;
13865
13866			callout = (struct callout *)&io->io_hdr.timer_bytes;
13867			callout_init(callout, /*mpsafe*/ 1);
13868			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13869			callout_reset(callout,
13870				      lun->delay_info.done_delay * hz,
13871				      ctl_done_timer_wakeup, io);
13872			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13873				lun->delay_info.done_delay = 0;
13874			return;
13875		}
13876	}
13877#endif /* CTL_IO_DELAY */
13878
13879	ctl_enqueue_done(io);
13880}
13881
13882int
13883ctl_isc(struct ctl_scsiio *ctsio)
13884{
13885	struct ctl_lun *lun;
13886	int retval;
13887
13888	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13889
13890	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13891
13892	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13893
13894	retval = lun->backend->data_submit((union ctl_io *)ctsio);
13895
13896	return (retval);
13897}
13898
13899
13900static void
13901ctl_work_thread(void *arg)
13902{
13903	struct ctl_thread *thr = (struct ctl_thread *)arg;
13904	struct ctl_softc *softc = thr->ctl_softc;
13905	union ctl_io *io;
13906	int retval;
13907
13908	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13909
13910	for (;;) {
13911		retval = 0;
13912
13913		/*
13914		 * We handle the queues in this order:
13915		 * - ISC
13916		 * - done queue (to free up resources, unblock other commands)
13917		 * - RtR queue
13918		 * - incoming queue
13919		 *
13920		 * If those queues are empty, we break out of the loop and
13921		 * go to sleep.
13922		 */
13923		mtx_lock(&thr->queue_lock);
13924		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13925		if (io != NULL) {
13926			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13927			mtx_unlock(&thr->queue_lock);
13928			ctl_handle_isc(io);
13929			continue;
13930		}
13931		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13932		if (io != NULL) {
13933			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13934			/* clear any blocked commands, call fe_done */
13935			mtx_unlock(&thr->queue_lock);
13936			retval = ctl_process_done(io);
13937			continue;
13938		}
13939		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13940		if (io != NULL) {
13941			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13942			mtx_unlock(&thr->queue_lock);
13943			if (io->io_hdr.io_type == CTL_IO_TASK)
13944				ctl_run_task(io);
13945			else
13946				ctl_scsiio_precheck(softc, &io->scsiio);
13947			continue;
13948		}
13949		if (!ctl_pause_rtr) {
13950			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13951			if (io != NULL) {
13952				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13953				mtx_unlock(&thr->queue_lock);
13954				retval = ctl_scsiio(&io->scsiio);
13955				if (retval != CTL_RETVAL_COMPLETE)
13956					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13957				continue;
13958			}
13959		}
13960
13961		/* Sleep until we have something to do. */
13962		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13963	}
13964}
13965
13966static void
13967ctl_lun_thread(void *arg)
13968{
13969	struct ctl_softc *softc = (struct ctl_softc *)arg;
13970	struct ctl_be_lun *be_lun;
13971	int retval;
13972
13973	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13974
13975	for (;;) {
13976		retval = 0;
13977		mtx_lock(&softc->ctl_lock);
13978		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13979		if (be_lun != NULL) {
13980			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13981			mtx_unlock(&softc->ctl_lock);
13982			ctl_create_lun(be_lun);
13983			continue;
13984		}
13985
13986		/* Sleep until we have something to do. */
13987		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13988		    PDROP | PRIBIO, "-", 0);
13989	}
13990}
13991
13992static void
13993ctl_thresh_thread(void *arg)
13994{
13995	struct ctl_softc *softc = (struct ctl_softc *)arg;
13996	struct ctl_lun *lun;
13997	struct ctl_be_lun *be_lun;
13998	struct scsi_da_rw_recovery_page *rwpage;
13999	struct ctl_logical_block_provisioning_page *page;
14000	const char *attr;
14001	uint64_t thres, val;
14002	int i, e;
14003
14004	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
14005
14006	for (;;) {
14007		mtx_lock(&softc->ctl_lock);
14008		STAILQ_FOREACH(lun, &softc->lun_list, links) {
14009			be_lun = lun->be_lun;
14010			if ((lun->flags & CTL_LUN_DISABLED) ||
14011			    (lun->flags & CTL_LUN_OFFLINE) ||
14012			    (be_lun->flags & CTL_LUN_FLAG_UNMAP) == 0 ||
14013			    lun->backend->lun_attr == NULL)
14014				continue;
14015			rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
14016			if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
14017				continue;
14018			e = 0;
14019			page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
14020			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
14021				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
14022					continue;
14023				thres = scsi_4btoul(page->descr[i].count);
14024				thres <<= CTL_LBP_EXPONENT;
14025				switch (page->descr[i].resource) {
14026				case 0x01:
14027					attr = "blocksavail";
14028					break;
14029				case 0x02:
14030					attr = "blocksused";
14031					break;
14032				case 0xf1:
14033					attr = "poolblocksavail";
14034					break;
14035				case 0xf2:
14036					attr = "poolblocksused";
14037					break;
14038				default:
14039					continue;
14040				}
14041				mtx_unlock(&softc->ctl_lock); // XXX
14042				val = lun->backend->lun_attr(
14043				    lun->be_lun->be_lun, attr);
14044				mtx_lock(&softc->ctl_lock);
14045				if (val == UINT64_MAX)
14046					continue;
14047				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
14048				    == SLBPPD_ARMING_INC)
14049					e |= (val >= thres);
14050				else
14051					e |= (val <= thres);
14052			}
14053			mtx_lock(&lun->lun_lock);
14054			if (e) {
14055				if (lun->lasttpt == 0 ||
14056				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
14057					lun->lasttpt = time_uptime;
14058					for (i = 0; i < CTL_MAX_INITIATORS; i++)
14059						lun->pending_ua[i] |=
14060						    CTL_UA_THIN_PROV_THRES;
14061				}
14062			} else {
14063				lun->lasttpt = 0;
14064				for (i = 0; i < CTL_MAX_INITIATORS; i++)
14065					lun->pending_ua[i] &= ~CTL_UA_THIN_PROV_THRES;
14066			}
14067			mtx_unlock(&lun->lun_lock);
14068		}
14069		mtx_unlock(&softc->ctl_lock);
14070		pause("-", CTL_LBP_PERIOD * hz);
14071	}
14072}
14073
14074static void
14075ctl_enqueue_incoming(union ctl_io *io)
14076{
14077	struct ctl_softc *softc = control_softc;
14078	struct ctl_thread *thr;
14079	u_int idx;
14080
14081	idx = (io->io_hdr.nexus.targ_port * 127 +
14082	       io->io_hdr.nexus.initid.id) % worker_threads;
14083	thr = &softc->threads[idx];
14084	mtx_lock(&thr->queue_lock);
14085	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14086	mtx_unlock(&thr->queue_lock);
14087	wakeup(thr);
14088}
14089
14090static void
14091ctl_enqueue_rtr(union ctl_io *io)
14092{
14093	struct ctl_softc *softc = control_softc;
14094	struct ctl_thread *thr;
14095
14096	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14097	mtx_lock(&thr->queue_lock);
14098	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14099	mtx_unlock(&thr->queue_lock);
14100	wakeup(thr);
14101}
14102
14103static void
14104ctl_enqueue_done(union ctl_io *io)
14105{
14106	struct ctl_softc *softc = control_softc;
14107	struct ctl_thread *thr;
14108
14109	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14110	mtx_lock(&thr->queue_lock);
14111	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14112	mtx_unlock(&thr->queue_lock);
14113	wakeup(thr);
14114}
14115
14116static void
14117ctl_enqueue_isc(union ctl_io *io)
14118{
14119	struct ctl_softc *softc = control_softc;
14120	struct ctl_thread *thr;
14121
14122	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14123	mtx_lock(&thr->queue_lock);
14124	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14125	mtx_unlock(&thr->queue_lock);
14126	wakeup(thr);
14127}
14128
14129/* Initialization and failover */
14130
14131void
14132ctl_init_isc_msg(void)
14133{
14134	printf("CTL: Still calling this thing\n");
14135}
14136
14137/*
14138 * Init component
14139 * 	Initializes component into configuration defined by bootMode
14140 *	(see hasc-sv.c)
14141 *  	returns hasc_Status:
14142 * 		OK
14143 *		ERROR - fatal error
14144 */
14145static ctl_ha_comp_status
14146ctl_isc_init(struct ctl_ha_component *c)
14147{
14148	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14149
14150	c->status = ret;
14151	return ret;
14152}
14153
14154/* Start component
14155 * 	Starts component in state requested. If component starts successfully,
14156 *	it must set its own state to the requestrd state
14157 *	When requested state is HASC_STATE_HA, the component may refine it
14158 * 	by adding _SLAVE or _MASTER flags.
14159 *	Currently allowed state transitions are:
14160 *	UNKNOWN->HA		- initial startup
14161 *	UNKNOWN->SINGLE - initial startup when no parter detected
14162 *	HA->SINGLE		- failover
14163 * returns ctl_ha_comp_status:
14164 * 		OK	- component successfully started in requested state
14165 *		FAILED  - could not start the requested state, failover may
14166 * 			  be possible
14167 *		ERROR	- fatal error detected, no future startup possible
14168 */
14169static ctl_ha_comp_status
14170ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14171{
14172	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14173
14174	printf("%s: go\n", __func__);
14175
14176	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14177	if (c->state == CTL_HA_STATE_UNKNOWN ) {
14178		control_softc->is_single = 0;
14179		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14180		    != CTL_HA_STATUS_SUCCESS) {
14181			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14182			ret = CTL_HA_COMP_STATUS_ERROR;
14183		}
14184	} else if (CTL_HA_STATE_IS_HA(c->state)
14185		&& CTL_HA_STATE_IS_SINGLE(state)){
14186		// HA->SINGLE transition
14187	        ctl_failover();
14188		control_softc->is_single = 1;
14189	} else {
14190		printf("ctl_isc_start:Invalid state transition %X->%X\n",
14191		       c->state, state);
14192		ret = CTL_HA_COMP_STATUS_ERROR;
14193	}
14194	if (CTL_HA_STATE_IS_SINGLE(state))
14195		control_softc->is_single = 1;
14196
14197	c->state = state;
14198	c->status = ret;
14199	return ret;
14200}
14201
14202/*
14203 * Quiesce component
14204 * The component must clear any error conditions (set status to OK) and
14205 * prepare itself to another Start call
14206 * returns ctl_ha_comp_status:
14207 * 	OK
14208 *	ERROR
14209 */
14210static ctl_ha_comp_status
14211ctl_isc_quiesce(struct ctl_ha_component *c)
14212{
14213	int ret = CTL_HA_COMP_STATUS_OK;
14214
14215	ctl_pause_rtr = 1;
14216	c->status = ret;
14217	return ret;
14218}
14219
14220struct ctl_ha_component ctl_ha_component_ctlisc =
14221{
14222	.name = "CTL ISC",
14223	.state = CTL_HA_STATE_UNKNOWN,
14224	.init = ctl_isc_init,
14225	.start = ctl_isc_start,
14226	.quiesce = ctl_isc_quiesce
14227};
14228
14229/*
14230 *  vim: ts=8
14231 */
14232