ctl.c revision 275447
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 275447 2014-12-03 09:05:53Z 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 uint8_t ctl_pause_rtr;
360
361SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
362static int worker_threads = -1;
363SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
364    &worker_threads, 1, "Number of worker threads");
365static int ctl_debug = CTL_DEBUG_NONE;
366SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
367    &ctl_debug, 0, "Enabled debug flags");
368
369/*
370 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
371 * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
372 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
373 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
374 */
375#define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
376
377static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
378				  int param);
379static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
380static int ctl_init(void);
381void ctl_shutdown(void);
382static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
383static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
384static void ctl_ioctl_online(void *arg);
385static void ctl_ioctl_offline(void *arg);
386static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
387static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
388static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
389static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
390static int ctl_ioctl_submit_wait(union ctl_io *io);
391static void ctl_ioctl_datamove(union ctl_io *io);
392static void ctl_ioctl_done(union ctl_io *io);
393static void ctl_ioctl_hard_startstop_callback(void *arg,
394					      struct cfi_metatask *metatask);
395static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
396static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
397			      struct ctl_ooa *ooa_hdr,
398			      struct ctl_ooa_entry *kern_entries);
399static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
400		     struct thread *td);
401static uint32_t ctl_map_lun(int port_num, uint32_t lun);
402static uint32_t ctl_map_lun_back(int port_num, uint32_t lun);
403#ifdef unused
404static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
405				   uint32_t targ_target, uint32_t targ_lun,
406				   int can_wait);
407static void ctl_kfree_io(union ctl_io *io);
408#endif /* unused */
409static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
410			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
411static int ctl_free_lun(struct ctl_lun *lun);
412static void ctl_create_lun(struct ctl_be_lun *be_lun);
413/**
414static void ctl_failover_change_pages(struct ctl_softc *softc,
415				      struct ctl_scsiio *ctsio, int master);
416**/
417
418static int ctl_do_mode_select(union ctl_io *io);
419static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
420			   uint64_t res_key, uint64_t sa_res_key,
421			   uint8_t type, uint32_t residx,
422			   struct ctl_scsiio *ctsio,
423			   struct scsi_per_res_out *cdb,
424			   struct scsi_per_res_out_parms* param);
425static void ctl_pro_preempt_other(struct ctl_lun *lun,
426				  union ctl_ha_msg *msg);
427static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
428static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
429static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
430static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
431static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
432static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
433static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
434					 int alloc_len);
435static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
436					 int alloc_len);
437static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
438static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
439static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
440static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
441static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
442static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
443static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
444    union ctl_io *pending_io, union ctl_io *ooa_io);
445static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
446				union ctl_io *starting_io);
447static int ctl_check_blocked(struct ctl_lun *lun);
448static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
449				struct ctl_lun *lun,
450				const struct ctl_cmd_entry *entry,
451				struct ctl_scsiio *ctsio);
452//static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
453static void ctl_failover(void);
454static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
455			       struct ctl_scsiio *ctsio);
456static int ctl_scsiio(struct ctl_scsiio *ctsio);
457
458static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
459static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
460			    ctl_ua_type ua_type);
461static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
462			 ctl_ua_type ua_type);
463static int ctl_abort_task(union ctl_io *io);
464static int ctl_abort_task_set(union ctl_io *io);
465static int ctl_i_t_nexus_reset(union ctl_io *io);
466static void ctl_run_task(union ctl_io *io);
467#ifdef CTL_IO_DELAY
468static void ctl_datamove_timer_wakeup(void *arg);
469static void ctl_done_timer_wakeup(void *arg);
470#endif /* CTL_IO_DELAY */
471
472static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
473static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
474static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
475static void ctl_datamove_remote_write(union ctl_io *io);
476static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
477static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
478static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
479static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
480				    ctl_ha_dt_cb callback);
481static void ctl_datamove_remote_read(union ctl_io *io);
482static void ctl_datamove_remote(union ctl_io *io);
483static int ctl_process_done(union ctl_io *io);
484static void ctl_lun_thread(void *arg);
485static void ctl_thresh_thread(void *arg);
486static void ctl_work_thread(void *arg);
487static void ctl_enqueue_incoming(union ctl_io *io);
488static void ctl_enqueue_rtr(union ctl_io *io);
489static void ctl_enqueue_done(union ctl_io *io);
490static void ctl_enqueue_isc(union ctl_io *io);
491static const struct ctl_cmd_entry *
492    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
493static const struct ctl_cmd_entry *
494    ctl_validate_command(struct ctl_scsiio *ctsio);
495static int ctl_cmd_applicable(uint8_t lun_type,
496    const struct ctl_cmd_entry *entry);
497
498/*
499 * Load the serialization table.  This isn't very pretty, but is probably
500 * the easiest way to do it.
501 */
502#include "ctl_ser_table.c"
503
504/*
505 * We only need to define open, close and ioctl routines for this driver.
506 */
507static struct cdevsw ctl_cdevsw = {
508	.d_version =	D_VERSION,
509	.d_flags =	0,
510	.d_open =	ctl_open,
511	.d_close =	ctl_close,
512	.d_ioctl =	ctl_ioctl,
513	.d_name =	"ctl",
514};
515
516
517MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
518MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
519
520static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
521
522static moduledata_t ctl_moduledata = {
523	"ctl",
524	ctl_module_event_handler,
525	NULL
526};
527
528DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
529MODULE_VERSION(ctl, 1);
530
531static struct ctl_frontend ioctl_frontend =
532{
533	.name = "ioctl",
534};
535
536static void
537ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
538			    union ctl_ha_msg *msg_info)
539{
540	struct ctl_scsiio *ctsio;
541
542	if (msg_info->hdr.original_sc == NULL) {
543		printf("%s: original_sc == NULL!\n", __func__);
544		/* XXX KDM now what? */
545		return;
546	}
547
548	ctsio = &msg_info->hdr.original_sc->scsiio;
549	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
550	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
551	ctsio->io_hdr.status = msg_info->hdr.status;
552	ctsio->scsi_status = msg_info->scsi.scsi_status;
553	ctsio->sense_len = msg_info->scsi.sense_len;
554	ctsio->sense_residual = msg_info->scsi.sense_residual;
555	ctsio->residual = msg_info->scsi.residual;
556	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
557	       sizeof(ctsio->sense_data));
558	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
559	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
560	ctl_enqueue_isc((union ctl_io *)ctsio);
561}
562
563static void
564ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
565				union ctl_ha_msg *msg_info)
566{
567	struct ctl_scsiio *ctsio;
568
569	if (msg_info->hdr.serializing_sc == NULL) {
570		printf("%s: serializing_sc == NULL!\n", __func__);
571		/* XXX KDM now what? */
572		return;
573	}
574
575	ctsio = &msg_info->hdr.serializing_sc->scsiio;
576#if 0
577	/*
578	 * Attempt to catch the situation where an I/O has
579	 * been freed, and we're using it again.
580	 */
581	if (ctsio->io_hdr.io_type == 0xff) {
582		union ctl_io *tmp_io;
583		tmp_io = (union ctl_io *)ctsio;
584		printf("%s: %p use after free!\n", __func__,
585		       ctsio);
586		printf("%s: type %d msg %d cdb %x iptl: "
587		       "%d:%d:%d:%d tag 0x%04x "
588		       "flag %#x status %x\n",
589			__func__,
590			tmp_io->io_hdr.io_type,
591			tmp_io->io_hdr.msg_type,
592			tmp_io->scsiio.cdb[0],
593			tmp_io->io_hdr.nexus.initid.id,
594			tmp_io->io_hdr.nexus.targ_port,
595			tmp_io->io_hdr.nexus.targ_target.id,
596			tmp_io->io_hdr.nexus.targ_lun,
597			(tmp_io->io_hdr.io_type ==
598			CTL_IO_TASK) ?
599			tmp_io->taskio.tag_num :
600			tmp_io->scsiio.tag_num,
601		        tmp_io->io_hdr.flags,
602			tmp_io->io_hdr.status);
603	}
604#endif
605	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
606	ctl_enqueue_isc((union ctl_io *)ctsio);
607}
608
609/*
610 * ISC (Inter Shelf Communication) event handler.  Events from the HA
611 * subsystem come in here.
612 */
613static void
614ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
615{
616	struct ctl_softc *ctl_softc;
617	union ctl_io *io;
618	struct ctl_prio *presio;
619	ctl_ha_status isc_status;
620
621	ctl_softc = control_softc;
622	io = NULL;
623
624
625#if 0
626	printf("CTL: Isc Msg event %d\n", event);
627#endif
628	if (event == CTL_HA_EVT_MSG_RECV) {
629		union ctl_ha_msg msg_info;
630
631		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
632					     sizeof(msg_info), /*wait*/ 0);
633#if 0
634		printf("CTL: msg_type %d\n", msg_info.msg_type);
635#endif
636		if (isc_status != 0) {
637			printf("Error receiving message, status = %d\n",
638			       isc_status);
639			return;
640		}
641
642		switch (msg_info.hdr.msg_type) {
643		case CTL_MSG_SERIALIZE:
644#if 0
645			printf("Serialize\n");
646#endif
647			io = ctl_alloc_io_nowait(ctl_softc->othersc_pool);
648			if (io == NULL) {
649				printf("ctl_isc_event_handler: can't allocate "
650				       "ctl_io!\n");
651				/* Bad Juju */
652				/* Need to set busy and send msg back */
653				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
654				msg_info.hdr.status = CTL_SCSI_ERROR;
655				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
656				msg_info.scsi.sense_len = 0;
657			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
658				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
659				}
660				goto bailout;
661			}
662			ctl_zero_io(io);
663			// populate ctsio from msg_info
664			io->io_hdr.io_type = CTL_IO_SCSI;
665			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
666			io->io_hdr.original_sc = msg_info.hdr.original_sc;
667#if 0
668			printf("pOrig %x\n", (int)msg_info.original_sc);
669#endif
670			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
671					    CTL_FLAG_IO_ACTIVE;
672			/*
673			 * If we're in serialization-only mode, we don't
674			 * want to go through full done processing.  Thus
675			 * the COPY flag.
676			 *
677			 * XXX KDM add another flag that is more specific.
678			 */
679			if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
680				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
681			io->io_hdr.nexus = msg_info.hdr.nexus;
682#if 0
683			printf("targ %d, port %d, iid %d, lun %d\n",
684			       io->io_hdr.nexus.targ_target.id,
685			       io->io_hdr.nexus.targ_port,
686			       io->io_hdr.nexus.initid.id,
687			       io->io_hdr.nexus.targ_lun);
688#endif
689			io->scsiio.tag_num = msg_info.scsi.tag_num;
690			io->scsiio.tag_type = msg_info.scsi.tag_type;
691			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
692			       CTL_MAX_CDBLEN);
693			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
694				const struct ctl_cmd_entry *entry;
695
696				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
697				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
698				io->io_hdr.flags |=
699					entry->flags & CTL_FLAG_DATA_MASK;
700			}
701			ctl_enqueue_isc(io);
702			break;
703
704		/* Performed on the Originating SC, XFER mode only */
705		case CTL_MSG_DATAMOVE: {
706			struct ctl_sg_entry *sgl;
707			int i, j;
708
709			io = msg_info.hdr.original_sc;
710			if (io == NULL) {
711				printf("%s: original_sc == NULL!\n", __func__);
712				/* XXX KDM do something here */
713				break;
714			}
715			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
716			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
717			/*
718			 * Keep track of this, we need to send it back over
719			 * when the datamove is complete.
720			 */
721			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
722
723			if (msg_info.dt.sg_sequence == 0) {
724				/*
725				 * XXX KDM we use the preallocated S/G list
726				 * here, but we'll need to change this to
727				 * dynamic allocation if we need larger S/G
728				 * lists.
729				 */
730				if (msg_info.dt.kern_sg_entries >
731				    sizeof(io->io_hdr.remote_sglist) /
732				    sizeof(io->io_hdr.remote_sglist[0])) {
733					printf("%s: number of S/G entries "
734					    "needed %u > allocated num %zd\n",
735					    __func__,
736					    msg_info.dt.kern_sg_entries,
737					    sizeof(io->io_hdr.remote_sglist)/
738					    sizeof(io->io_hdr.remote_sglist[0]));
739
740					/*
741					 * XXX KDM send a message back to
742					 * the other side to shut down the
743					 * DMA.  The error will come back
744					 * through via the normal channel.
745					 */
746					break;
747				}
748				sgl = io->io_hdr.remote_sglist;
749				memset(sgl, 0,
750				       sizeof(io->io_hdr.remote_sglist));
751
752				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
753
754				io->scsiio.kern_sg_entries =
755					msg_info.dt.kern_sg_entries;
756				io->scsiio.rem_sg_entries =
757					msg_info.dt.kern_sg_entries;
758				io->scsiio.kern_data_len =
759					msg_info.dt.kern_data_len;
760				io->scsiio.kern_total_len =
761					msg_info.dt.kern_total_len;
762				io->scsiio.kern_data_resid =
763					msg_info.dt.kern_data_resid;
764				io->scsiio.kern_rel_offset =
765					msg_info.dt.kern_rel_offset;
766				/*
767				 * Clear out per-DMA flags.
768				 */
769				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
770				/*
771				 * Add per-DMA flags that are set for this
772				 * particular DMA request.
773				 */
774				io->io_hdr.flags |= msg_info.dt.flags &
775						    CTL_FLAG_RDMA_MASK;
776			} else
777				sgl = (struct ctl_sg_entry *)
778					io->scsiio.kern_data_ptr;
779
780			for (i = msg_info.dt.sent_sg_entries, j = 0;
781			     i < (msg_info.dt.sent_sg_entries +
782			     msg_info.dt.cur_sg_entries); i++, j++) {
783				sgl[i].addr = msg_info.dt.sg_list[j].addr;
784				sgl[i].len = msg_info.dt.sg_list[j].len;
785
786#if 0
787				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
788				       __func__,
789				       msg_info.dt.sg_list[j].addr,
790				       msg_info.dt.sg_list[j].len,
791				       sgl[i].addr, sgl[i].len, j, i);
792#endif
793			}
794#if 0
795			memcpy(&sgl[msg_info.dt.sent_sg_entries],
796			       msg_info.dt.sg_list,
797			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
798#endif
799
800			/*
801			 * If this is the last piece of the I/O, we've got
802			 * the full S/G list.  Queue processing in the thread.
803			 * Otherwise wait for the next piece.
804			 */
805			if (msg_info.dt.sg_last != 0)
806				ctl_enqueue_isc(io);
807			break;
808		}
809		/* Performed on the Serializing (primary) SC, XFER mode only */
810		case CTL_MSG_DATAMOVE_DONE: {
811			if (msg_info.hdr.serializing_sc == NULL) {
812				printf("%s: serializing_sc == NULL!\n",
813				       __func__);
814				/* XXX KDM now what? */
815				break;
816			}
817			/*
818			 * We grab the sense information here in case
819			 * there was a failure, so we can return status
820			 * back to the initiator.
821			 */
822			io = msg_info.hdr.serializing_sc;
823			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
824			io->io_hdr.status = msg_info.hdr.status;
825			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
826			io->scsiio.sense_len = msg_info.scsi.sense_len;
827			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
828			io->io_hdr.port_status = msg_info.scsi.fetd_status;
829			io->scsiio.residual = msg_info.scsi.residual;
830			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
831			       sizeof(io->scsiio.sense_data));
832			ctl_enqueue_isc(io);
833			break;
834		}
835
836		/* Preformed on Originating SC, SER_ONLY mode */
837		case CTL_MSG_R2R:
838			io = msg_info.hdr.original_sc;
839			if (io == NULL) {
840				printf("%s: Major Bummer\n", __func__);
841				return;
842			} else {
843#if 0
844				printf("pOrig %x\n",(int) ctsio);
845#endif
846			}
847			io->io_hdr.msg_type = CTL_MSG_R2R;
848			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
849			ctl_enqueue_isc(io);
850			break;
851
852		/*
853		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
854		 * mode.
855		 * Performed on the Originating (i.e. secondary) SC in XFER
856		 * mode
857		 */
858		case CTL_MSG_FINISH_IO:
859			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
860				ctl_isc_handler_finish_xfer(ctl_softc,
861							    &msg_info);
862			else
863				ctl_isc_handler_finish_ser_only(ctl_softc,
864								&msg_info);
865			break;
866
867		/* Preformed on Originating SC */
868		case CTL_MSG_BAD_JUJU:
869			io = msg_info.hdr.original_sc;
870			if (io == NULL) {
871				printf("%s: Bad JUJU!, original_sc is NULL!\n",
872				       __func__);
873				break;
874			}
875			ctl_copy_sense_data(&msg_info, io);
876			/*
877			 * IO should have already been cleaned up on other
878			 * SC so clear this flag so we won't send a message
879			 * back to finish the IO there.
880			 */
881			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
882			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
883
884			/* io = msg_info.hdr.serializing_sc; */
885			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
886			ctl_enqueue_isc(io);
887			break;
888
889		/* Handle resets sent from the other side */
890		case CTL_MSG_MANAGE_TASKS: {
891			struct ctl_taskio *taskio;
892			taskio = (struct ctl_taskio *)ctl_alloc_io_nowait(
893			    ctl_softc->othersc_pool);
894			if (taskio == NULL) {
895				printf("ctl_isc_event_handler: can't allocate "
896				       "ctl_io!\n");
897				/* Bad Juju */
898				/* should I just call the proper reset func
899				   here??? */
900				goto bailout;
901			}
902			ctl_zero_io((union ctl_io *)taskio);
903			taskio->io_hdr.io_type = CTL_IO_TASK;
904			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
905			taskio->io_hdr.nexus = msg_info.hdr.nexus;
906			taskio->task_action = msg_info.task.task_action;
907			taskio->tag_num = msg_info.task.tag_num;
908			taskio->tag_type = msg_info.task.tag_type;
909#ifdef CTL_TIME_IO
910			taskio->io_hdr.start_time = time_uptime;
911			getbintime(&taskio->io_hdr.start_bt);
912#if 0
913			cs_prof_gettime(&taskio->io_hdr.start_ticks);
914#endif
915#endif /* CTL_TIME_IO */
916			ctl_run_task((union ctl_io *)taskio);
917			break;
918		}
919		/* Persistent Reserve action which needs attention */
920		case CTL_MSG_PERS_ACTION:
921			presio = (struct ctl_prio *)ctl_alloc_io_nowait(
922			    ctl_softc->othersc_pool);
923			if (presio == NULL) {
924				printf("ctl_isc_event_handler: can't allocate "
925				       "ctl_io!\n");
926				/* Bad Juju */
927				/* Need to set busy and send msg back */
928				goto bailout;
929			}
930			ctl_zero_io((union ctl_io *)presio);
931			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
932			presio->pr_msg = msg_info.pr;
933			ctl_enqueue_isc((union ctl_io *)presio);
934			break;
935		case CTL_MSG_SYNC_FE:
936			rcv_sync_msg = 1;
937			break;
938		default:
939		        printf("How did I get here?\n");
940		}
941	} else if (event == CTL_HA_EVT_MSG_SENT) {
942		if (param != CTL_HA_STATUS_SUCCESS) {
943			printf("Bad status from ctl_ha_msg_send status %d\n",
944			       param);
945		}
946		return;
947	} else if (event == CTL_HA_EVT_DISCONNECT) {
948		printf("CTL: Got a disconnect from Isc\n");
949		return;
950	} else {
951		printf("ctl_isc_event_handler: Unknown event %d\n", event);
952		return;
953	}
954
955bailout:
956	return;
957}
958
959static void
960ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
961{
962	struct scsi_sense_data *sense;
963
964	sense = &dest->scsiio.sense_data;
965	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
966	dest->scsiio.scsi_status = src->scsi.scsi_status;
967	dest->scsiio.sense_len = src->scsi.sense_len;
968	dest->io_hdr.status = src->hdr.status;
969}
970
971static int
972ctl_ha_state_sysctl(SYSCTL_HANDLER_ARGS)
973{
974	struct ctl_softc *softc = (struct ctl_softc *)arg1;
975	struct ctl_lun *lun;
976	int error, value, i;
977
978	if (softc->flags & CTL_FLAG_ACTIVE_SHELF)
979		value = 0;
980	else
981		value = 1;
982
983	error = sysctl_handle_int(oidp, &value, 0, req);
984	if ((error != 0) || (req->newptr == NULL))
985		return (error);
986
987	mtx_lock(&softc->ctl_lock);
988	if (value == 0)
989		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
990	else
991		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
992	STAILQ_FOREACH(lun, &softc->lun_list, links) {
993		mtx_lock(&lun->lun_lock);
994		for (i = 0; i < CTL_MAX_INITIATORS; i++)
995			lun->pending_ua[i] |= CTL_UA_ASYM_ACC_CHANGE;
996		mtx_unlock(&lun->lun_lock);
997	}
998	mtx_unlock(&softc->ctl_lock);
999	return (0);
1000}
1001
1002static int
1003ctl_init(void)
1004{
1005	struct ctl_softc *softc;
1006	void *other_pool;
1007	struct ctl_port *port;
1008	int i, error, retval;
1009	//int isc_retval;
1010
1011	retval = 0;
1012	ctl_pause_rtr = 0;
1013        rcv_sync_msg = 0;
1014
1015	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1016			       M_WAITOK | M_ZERO);
1017	softc = control_softc;
1018
1019	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1020			      "cam/ctl");
1021
1022	softc->dev->si_drv1 = softc;
1023
1024	/*
1025	 * By default, return a "bad LUN" peripheral qualifier for unknown
1026	 * LUNs.  The user can override this default using the tunable or
1027	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
1028	 */
1029	softc->inquiry_pq_no_lun = 1;
1030	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
1031			  &softc->inquiry_pq_no_lun);
1032	sysctl_ctx_init(&softc->sysctl_ctx);
1033	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1034		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1035		CTLFLAG_RD, 0, "CAM Target Layer");
1036
1037	if (softc->sysctl_tree == NULL) {
1038		printf("%s: unable to allocate sysctl tree\n", __func__);
1039		destroy_dev(softc->dev);
1040		free(control_softc, M_DEVBUF);
1041		control_softc = NULL;
1042		return (ENOMEM);
1043	}
1044
1045	SYSCTL_ADD_INT(&softc->sysctl_ctx,
1046		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1047		       "inquiry_pq_no_lun", CTLFLAG_RW,
1048		       &softc->inquiry_pq_no_lun, 0,
1049		       "Report no lun possible for invalid LUNs");
1050
1051	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1052	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1053	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1054	softc->open_count = 0;
1055
1056	/*
1057	 * Default to actually sending a SYNCHRONIZE CACHE command down to
1058	 * the drive.
1059	 */
1060	softc->flags = CTL_FLAG_REAL_SYNC;
1061
1062	/*
1063	 * In Copan's HA scheme, the "master" and "slave" roles are
1064	 * figured out through the slot the controller is in.  Although it
1065	 * is an active/active system, someone has to be in charge.
1066	 */
1067	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1068	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1069	    "HA head ID (0 - no HA)");
1070	if (softc->ha_id == 0) {
1071		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1072		softc->is_single = 1;
1073		softc->port_offset = 0;
1074	} else
1075		softc->port_offset = (softc->ha_id - 1) * CTL_MAX_PORTS;
1076	softc->persis_offset = softc->port_offset * CTL_MAX_INIT_PER_PORT;
1077
1078	/*
1079	 * XXX KDM need to figure out where we want to get our target ID
1080	 * and WWID.  Is it different on each port?
1081	 */
1082	softc->target.id = 0;
1083	softc->target.wwid[0] = 0x12345678;
1084	softc->target.wwid[1] = 0x87654321;
1085	STAILQ_INIT(&softc->lun_list);
1086	STAILQ_INIT(&softc->pending_lun_queue);
1087	STAILQ_INIT(&softc->fe_list);
1088	STAILQ_INIT(&softc->port_list);
1089	STAILQ_INIT(&softc->be_list);
1090	ctl_tpc_init(softc);
1091
1092	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1093	                    &other_pool) != 0)
1094	{
1095		printf("ctl: can't allocate %d entry other SC pool, "
1096		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1097		return (ENOMEM);
1098	}
1099	softc->othersc_pool = other_pool;
1100
1101	if (worker_threads <= 0)
1102		worker_threads = max(1, mp_ncpus / 4);
1103	if (worker_threads > CTL_MAX_THREADS)
1104		worker_threads = CTL_MAX_THREADS;
1105
1106	for (i = 0; i < worker_threads; i++) {
1107		struct ctl_thread *thr = &softc->threads[i];
1108
1109		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1110		thr->ctl_softc = softc;
1111		STAILQ_INIT(&thr->incoming_queue);
1112		STAILQ_INIT(&thr->rtr_queue);
1113		STAILQ_INIT(&thr->done_queue);
1114		STAILQ_INIT(&thr->isc_queue);
1115
1116		error = kproc_kthread_add(ctl_work_thread, thr,
1117		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1118		if (error != 0) {
1119			printf("error creating CTL work thread!\n");
1120			ctl_pool_free(other_pool);
1121			return (error);
1122		}
1123	}
1124	error = kproc_kthread_add(ctl_lun_thread, softc,
1125	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1126	if (error != 0) {
1127		printf("error creating CTL lun thread!\n");
1128		ctl_pool_free(other_pool);
1129		return (error);
1130	}
1131	error = kproc_kthread_add(ctl_thresh_thread, softc,
1132	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1133	if (error != 0) {
1134		printf("error creating CTL threshold thread!\n");
1135		ctl_pool_free(other_pool);
1136		return (error);
1137	}
1138	if (bootverbose)
1139		printf("ctl: CAM Target Layer loaded\n");
1140
1141	/*
1142	 * Initialize the ioctl front end.
1143	 */
1144	ctl_frontend_register(&ioctl_frontend);
1145	port = &softc->ioctl_info.port;
1146	port->frontend = &ioctl_frontend;
1147	sprintf(softc->ioctl_info.port_name, "ioctl");
1148	port->port_type = CTL_PORT_IOCTL;
1149	port->num_requested_ctl_io = 100;
1150	port->port_name = softc->ioctl_info.port_name;
1151	port->port_online = ctl_ioctl_online;
1152	port->port_offline = ctl_ioctl_offline;
1153	port->onoff_arg = &softc->ioctl_info;
1154	port->lun_enable = ctl_ioctl_lun_enable;
1155	port->lun_disable = ctl_ioctl_lun_disable;
1156	port->targ_lun_arg = &softc->ioctl_info;
1157	port->fe_datamove = ctl_ioctl_datamove;
1158	port->fe_done = ctl_ioctl_done;
1159	port->max_targets = 15;
1160	port->max_target_id = 15;
1161
1162	if (ctl_port_register(&softc->ioctl_info.port) != 0) {
1163		printf("ctl: ioctl front end registration failed, will "
1164		       "continue anyway\n");
1165	}
1166
1167	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1168	    OID_AUTO, "ha_state", CTLTYPE_INT | CTLFLAG_RWTUN,
1169	    softc, 0, ctl_ha_state_sysctl, "I", "HA state for this head");
1170
1171#ifdef CTL_IO_DELAY
1172	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1173		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1174		       sizeof(struct callout), CTL_TIMER_BYTES);
1175		return (EINVAL);
1176	}
1177#endif /* CTL_IO_DELAY */
1178
1179	return (0);
1180}
1181
1182void
1183ctl_shutdown(void)
1184{
1185	struct ctl_softc *softc;
1186	struct ctl_lun *lun, *next_lun;
1187
1188	softc = (struct ctl_softc *)control_softc;
1189
1190	if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1191		printf("ctl: ioctl front end deregistration failed\n");
1192
1193	mtx_lock(&softc->ctl_lock);
1194
1195	/*
1196	 * Free up each LUN.
1197	 */
1198	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1199		next_lun = STAILQ_NEXT(lun, links);
1200		ctl_free_lun(lun);
1201	}
1202
1203	mtx_unlock(&softc->ctl_lock);
1204
1205	ctl_frontend_deregister(&ioctl_frontend);
1206
1207#if 0
1208	ctl_shutdown_thread(softc->work_thread);
1209	mtx_destroy(&softc->queue_lock);
1210#endif
1211
1212	ctl_tpc_shutdown(softc);
1213	uma_zdestroy(softc->io_zone);
1214	mtx_destroy(&softc->ctl_lock);
1215
1216	destroy_dev(softc->dev);
1217
1218	sysctl_ctx_free(&softc->sysctl_ctx);
1219
1220	free(control_softc, M_DEVBUF);
1221	control_softc = NULL;
1222
1223	if (bootverbose)
1224		printf("ctl: CAM Target Layer unloaded\n");
1225}
1226
1227static int
1228ctl_module_event_handler(module_t mod, int what, void *arg)
1229{
1230
1231	switch (what) {
1232	case MOD_LOAD:
1233		return (ctl_init());
1234	case MOD_UNLOAD:
1235		return (EBUSY);
1236	default:
1237		return (EOPNOTSUPP);
1238	}
1239}
1240
1241/*
1242 * XXX KDM should we do some access checks here?  Bump a reference count to
1243 * prevent a CTL module from being unloaded while someone has it open?
1244 */
1245static int
1246ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1247{
1248	return (0);
1249}
1250
1251static int
1252ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1253{
1254	return (0);
1255}
1256
1257int
1258ctl_port_enable(ctl_port_type port_type)
1259{
1260	struct ctl_softc *softc = control_softc;
1261	struct ctl_port *port;
1262
1263	if (softc->is_single == 0) {
1264		union ctl_ha_msg msg_info;
1265		int isc_retval;
1266
1267#if 0
1268		printf("%s: HA mode, synchronizing frontend enable\n",
1269		        __func__);
1270#endif
1271		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1272	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1273		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1274			printf("Sync msg send error retval %d\n", isc_retval);
1275		}
1276		if (!rcv_sync_msg) {
1277			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1278			        sizeof(msg_info), 1);
1279		}
1280#if 0
1281        	printf("CTL:Frontend Enable\n");
1282	} else {
1283		printf("%s: single mode, skipping frontend synchronization\n",
1284		        __func__);
1285#endif
1286	}
1287
1288	STAILQ_FOREACH(port, &softc->port_list, links) {
1289		if (port_type & port->port_type)
1290		{
1291#if 0
1292			printf("port %d\n", port->targ_port);
1293#endif
1294			ctl_port_online(port);
1295		}
1296	}
1297
1298	return (0);
1299}
1300
1301int
1302ctl_port_disable(ctl_port_type port_type)
1303{
1304	struct ctl_softc *softc;
1305	struct ctl_port *port;
1306
1307	softc = control_softc;
1308
1309	STAILQ_FOREACH(port, &softc->port_list, links) {
1310		if (port_type & port->port_type)
1311			ctl_port_offline(port);
1312	}
1313
1314	return (0);
1315}
1316
1317/*
1318 * Returns 0 for success, 1 for failure.
1319 * Currently the only failure mode is if there aren't enough entries
1320 * allocated.  So, in case of a failure, look at num_entries_dropped,
1321 * reallocate and try again.
1322 */
1323int
1324ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1325	      int *num_entries_filled, int *num_entries_dropped,
1326	      ctl_port_type port_type, int no_virtual)
1327{
1328	struct ctl_softc *softc;
1329	struct ctl_port *port;
1330	int entries_dropped, entries_filled;
1331	int retval;
1332	int i;
1333
1334	softc = control_softc;
1335
1336	retval = 0;
1337	entries_filled = 0;
1338	entries_dropped = 0;
1339
1340	i = 0;
1341	mtx_lock(&softc->ctl_lock);
1342	STAILQ_FOREACH(port, &softc->port_list, links) {
1343		struct ctl_port_entry *entry;
1344
1345		if ((port->port_type & port_type) == 0)
1346			continue;
1347
1348		if ((no_virtual != 0)
1349		 && (port->virtual_port != 0))
1350			continue;
1351
1352		if (entries_filled >= num_entries_alloced) {
1353			entries_dropped++;
1354			continue;
1355		}
1356		entry = &entries[i];
1357
1358		entry->port_type = port->port_type;
1359		strlcpy(entry->port_name, port->port_name,
1360			sizeof(entry->port_name));
1361		entry->physical_port = port->physical_port;
1362		entry->virtual_port = port->virtual_port;
1363		entry->wwnn = port->wwnn;
1364		entry->wwpn = port->wwpn;
1365
1366		i++;
1367		entries_filled++;
1368	}
1369
1370	mtx_unlock(&softc->ctl_lock);
1371
1372	if (entries_dropped > 0)
1373		retval = 1;
1374
1375	*num_entries_dropped = entries_dropped;
1376	*num_entries_filled = entries_filled;
1377
1378	return (retval);
1379}
1380
1381static void
1382ctl_ioctl_online(void *arg)
1383{
1384	struct ctl_ioctl_info *ioctl_info;
1385
1386	ioctl_info = (struct ctl_ioctl_info *)arg;
1387
1388	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1389}
1390
1391static void
1392ctl_ioctl_offline(void *arg)
1393{
1394	struct ctl_ioctl_info *ioctl_info;
1395
1396	ioctl_info = (struct ctl_ioctl_info *)arg;
1397
1398	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1399}
1400
1401/*
1402 * Remove an initiator by port number and initiator ID.
1403 * Returns 0 for success, -1 for failure.
1404 */
1405int
1406ctl_remove_initiator(struct ctl_port *port, int iid)
1407{
1408	struct ctl_softc *softc = control_softc;
1409
1410	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1411
1412	if (iid > CTL_MAX_INIT_PER_PORT) {
1413		printf("%s: initiator ID %u > maximun %u!\n",
1414		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1415		return (-1);
1416	}
1417
1418	mtx_lock(&softc->ctl_lock);
1419	port->wwpn_iid[iid].in_use--;
1420	port->wwpn_iid[iid].last_use = time_uptime;
1421	mtx_unlock(&softc->ctl_lock);
1422
1423	return (0);
1424}
1425
1426/*
1427 * Add an initiator to the initiator map.
1428 * Returns iid for success, < 0 for failure.
1429 */
1430int
1431ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1432{
1433	struct ctl_softc *softc = control_softc;
1434	time_t best_time;
1435	int i, best;
1436
1437	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1438
1439	if (iid >= CTL_MAX_INIT_PER_PORT) {
1440		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1441		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1442		free(name, M_CTL);
1443		return (-1);
1444	}
1445
1446	mtx_lock(&softc->ctl_lock);
1447
1448	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1449		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1450			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1451				iid = i;
1452				break;
1453			}
1454			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1455			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1456				iid = i;
1457				break;
1458			}
1459		}
1460	}
1461
1462	if (iid < 0) {
1463		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1464			if (port->wwpn_iid[i].in_use == 0 &&
1465			    port->wwpn_iid[i].wwpn == 0 &&
1466			    port->wwpn_iid[i].name == NULL) {
1467				iid = i;
1468				break;
1469			}
1470		}
1471	}
1472
1473	if (iid < 0) {
1474		best = -1;
1475		best_time = INT32_MAX;
1476		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1477			if (port->wwpn_iid[i].in_use == 0) {
1478				if (port->wwpn_iid[i].last_use < best_time) {
1479					best = i;
1480					best_time = port->wwpn_iid[i].last_use;
1481				}
1482			}
1483		}
1484		iid = best;
1485	}
1486
1487	if (iid < 0) {
1488		mtx_unlock(&softc->ctl_lock);
1489		free(name, M_CTL);
1490		return (-2);
1491	}
1492
1493	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1494		/*
1495		 * This is not an error yet.
1496		 */
1497		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1498#if 0
1499			printf("%s: port %d iid %u WWPN %#jx arrived"
1500			    " again\n", __func__, port->targ_port,
1501			    iid, (uintmax_t)wwpn);
1502#endif
1503			goto take;
1504		}
1505		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1506		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1507#if 0
1508			printf("%s: port %d iid %u name '%s' arrived"
1509			    " again\n", __func__, port->targ_port,
1510			    iid, name);
1511#endif
1512			goto take;
1513		}
1514
1515		/*
1516		 * This is an error, but what do we do about it?  The
1517		 * driver is telling us we have a new WWPN for this
1518		 * initiator ID, so we pretty much need to use it.
1519		 */
1520		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1521		    " but WWPN %#jx '%s' is still at that address\n",
1522		    __func__, port->targ_port, iid, wwpn, name,
1523		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1524		    port->wwpn_iid[iid].name);
1525
1526		/*
1527		 * XXX KDM clear have_ca and ua_pending on each LUN for
1528		 * this initiator.
1529		 */
1530	}
1531take:
1532	free(port->wwpn_iid[iid].name, M_CTL);
1533	port->wwpn_iid[iid].name = name;
1534	port->wwpn_iid[iid].wwpn = wwpn;
1535	port->wwpn_iid[iid].in_use++;
1536	mtx_unlock(&softc->ctl_lock);
1537
1538	return (iid);
1539}
1540
1541static int
1542ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1543{
1544	int len;
1545
1546	switch (port->port_type) {
1547	case CTL_PORT_FC:
1548	{
1549		struct scsi_transportid_fcp *id =
1550		    (struct scsi_transportid_fcp *)buf;
1551		if (port->wwpn_iid[iid].wwpn == 0)
1552			return (0);
1553		memset(id, 0, sizeof(*id));
1554		id->format_protocol = SCSI_PROTO_FC;
1555		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1556		return (sizeof(*id));
1557	}
1558	case CTL_PORT_ISCSI:
1559	{
1560		struct scsi_transportid_iscsi_port *id =
1561		    (struct scsi_transportid_iscsi_port *)buf;
1562		if (port->wwpn_iid[iid].name == NULL)
1563			return (0);
1564		memset(id, 0, 256);
1565		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1566		    SCSI_PROTO_ISCSI;
1567		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1568		len = roundup2(min(len, 252), 4);
1569		scsi_ulto2b(len, id->additional_length);
1570		return (sizeof(*id) + len);
1571	}
1572	case CTL_PORT_SAS:
1573	{
1574		struct scsi_transportid_sas *id =
1575		    (struct scsi_transportid_sas *)buf;
1576		if (port->wwpn_iid[iid].wwpn == 0)
1577			return (0);
1578		memset(id, 0, sizeof(*id));
1579		id->format_protocol = SCSI_PROTO_SAS;
1580		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1581		return (sizeof(*id));
1582	}
1583	default:
1584	{
1585		struct scsi_transportid_spi *id =
1586		    (struct scsi_transportid_spi *)buf;
1587		memset(id, 0, sizeof(*id));
1588		id->format_protocol = SCSI_PROTO_SPI;
1589		scsi_ulto2b(iid, id->scsi_addr);
1590		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1591		return (sizeof(*id));
1592	}
1593	}
1594}
1595
1596static int
1597ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1598{
1599	return (0);
1600}
1601
1602static int
1603ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1604{
1605	return (0);
1606}
1607
1608/*
1609 * Data movement routine for the CTL ioctl frontend port.
1610 */
1611static int
1612ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1613{
1614	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1615	struct ctl_sg_entry ext_entry, kern_entry;
1616	int ext_sglen, ext_sg_entries, kern_sg_entries;
1617	int ext_sg_start, ext_offset;
1618	int len_to_copy, len_copied;
1619	int kern_watermark, ext_watermark;
1620	int ext_sglist_malloced;
1621	int i, j;
1622
1623	ext_sglist_malloced = 0;
1624	ext_sg_start = 0;
1625	ext_offset = 0;
1626
1627	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1628
1629	/*
1630	 * If this flag is set, fake the data transfer.
1631	 */
1632	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1633		ctsio->ext_data_filled = ctsio->ext_data_len;
1634		goto bailout;
1635	}
1636
1637	/*
1638	 * To simplify things here, if we have a single buffer, stick it in
1639	 * a S/G entry and just make it a single entry S/G list.
1640	 */
1641	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1642		int len_seen;
1643
1644		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1645
1646		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1647							   M_WAITOK);
1648		ext_sglist_malloced = 1;
1649		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1650				   ext_sglen) != 0) {
1651			ctl_set_internal_failure(ctsio,
1652						 /*sks_valid*/ 0,
1653						 /*retry_count*/ 0);
1654			goto bailout;
1655		}
1656		ext_sg_entries = ctsio->ext_sg_entries;
1657		len_seen = 0;
1658		for (i = 0; i < ext_sg_entries; i++) {
1659			if ((len_seen + ext_sglist[i].len) >=
1660			     ctsio->ext_data_filled) {
1661				ext_sg_start = i;
1662				ext_offset = ctsio->ext_data_filled - len_seen;
1663				break;
1664			}
1665			len_seen += ext_sglist[i].len;
1666		}
1667	} else {
1668		ext_sglist = &ext_entry;
1669		ext_sglist->addr = ctsio->ext_data_ptr;
1670		ext_sglist->len = ctsio->ext_data_len;
1671		ext_sg_entries = 1;
1672		ext_sg_start = 0;
1673		ext_offset = ctsio->ext_data_filled;
1674	}
1675
1676	if (ctsio->kern_sg_entries > 0) {
1677		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1678		kern_sg_entries = ctsio->kern_sg_entries;
1679	} else {
1680		kern_sglist = &kern_entry;
1681		kern_sglist->addr = ctsio->kern_data_ptr;
1682		kern_sglist->len = ctsio->kern_data_len;
1683		kern_sg_entries = 1;
1684	}
1685
1686
1687	kern_watermark = 0;
1688	ext_watermark = ext_offset;
1689	len_copied = 0;
1690	for (i = ext_sg_start, j = 0;
1691	     i < ext_sg_entries && j < kern_sg_entries;) {
1692		uint8_t *ext_ptr, *kern_ptr;
1693
1694		len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1695				      kern_sglist[j].len - kern_watermark);
1696
1697		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1698		ext_ptr = ext_ptr + ext_watermark;
1699		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1700			/*
1701			 * XXX KDM fix this!
1702			 */
1703			panic("need to implement bus address support");
1704#if 0
1705			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1706#endif
1707		} else
1708			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1709		kern_ptr = kern_ptr + kern_watermark;
1710
1711		kern_watermark += len_to_copy;
1712		ext_watermark += len_to_copy;
1713
1714		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1715		     CTL_FLAG_DATA_IN) {
1716			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1717					 "bytes to user\n", len_to_copy));
1718			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1719					 "to %p\n", kern_ptr, ext_ptr));
1720			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1721				ctl_set_internal_failure(ctsio,
1722							 /*sks_valid*/ 0,
1723							 /*retry_count*/ 0);
1724				goto bailout;
1725			}
1726		} else {
1727			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1728					 "bytes from user\n", len_to_copy));
1729			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1730					 "to %p\n", ext_ptr, kern_ptr));
1731			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1732				ctl_set_internal_failure(ctsio,
1733							 /*sks_valid*/ 0,
1734							 /*retry_count*/0);
1735				goto bailout;
1736			}
1737		}
1738
1739		len_copied += len_to_copy;
1740
1741		if (ext_sglist[i].len == ext_watermark) {
1742			i++;
1743			ext_watermark = 0;
1744		}
1745
1746		if (kern_sglist[j].len == kern_watermark) {
1747			j++;
1748			kern_watermark = 0;
1749		}
1750	}
1751
1752	ctsio->ext_data_filled += len_copied;
1753
1754	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1755			 "kern_sg_entries: %d\n", ext_sg_entries,
1756			 kern_sg_entries));
1757	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1758			 "kern_data_len = %d\n", ctsio->ext_data_len,
1759			 ctsio->kern_data_len));
1760
1761
1762	/* XXX KDM set residual?? */
1763bailout:
1764
1765	if (ext_sglist_malloced != 0)
1766		free(ext_sglist, M_CTL);
1767
1768	return (CTL_RETVAL_COMPLETE);
1769}
1770
1771/*
1772 * Serialize a command that went down the "wrong" side, and so was sent to
1773 * this controller for execution.  The logic is a little different than the
1774 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1775 * sent back to the other side, but in the success case, we execute the
1776 * command on this side (XFER mode) or tell the other side to execute it
1777 * (SER_ONLY mode).
1778 */
1779static int
1780ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1781{
1782	struct ctl_softc *ctl_softc;
1783	union ctl_ha_msg msg_info;
1784	struct ctl_lun *lun;
1785	int retval = 0;
1786	uint32_t targ_lun;
1787
1788	ctl_softc = control_softc;
1789
1790	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1791	lun = ctl_softc->ctl_luns[targ_lun];
1792	if (lun==NULL)
1793	{
1794		/*
1795		 * Why isn't LUN defined? The other side wouldn't
1796		 * send a cmd if the LUN is undefined.
1797		 */
1798		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1799
1800		/* "Logical unit not supported" */
1801		ctl_set_sense_data(&msg_info.scsi.sense_data,
1802				   lun,
1803				   /*sense_format*/SSD_TYPE_NONE,
1804				   /*current_error*/ 1,
1805				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1806				   /*asc*/ 0x25,
1807				   /*ascq*/ 0x00,
1808				   SSD_ELEM_NONE);
1809
1810		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1811		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1812		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1813		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1814		msg_info.hdr.serializing_sc = NULL;
1815		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1816	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1817				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1818		}
1819		return(1);
1820
1821	}
1822
1823	mtx_lock(&lun->lun_lock);
1824    	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1825
1826	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1827		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1828		 ooa_links))) {
1829	case CTL_ACTION_BLOCK:
1830		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1831		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1832				  blocked_links);
1833		break;
1834	case CTL_ACTION_PASS:
1835	case CTL_ACTION_SKIP:
1836		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1837			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1838			ctl_enqueue_rtr((union ctl_io *)ctsio);
1839		} else {
1840
1841			/* send msg back to other side */
1842			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1843			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1844			msg_info.hdr.msg_type = CTL_MSG_R2R;
1845#if 0
1846			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1847#endif
1848		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1849			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1850			}
1851		}
1852		break;
1853	case CTL_ACTION_OVERLAP:
1854		/* OVERLAPPED COMMANDS ATTEMPTED */
1855		ctl_set_sense_data(&msg_info.scsi.sense_data,
1856				   lun,
1857				   /*sense_format*/SSD_TYPE_NONE,
1858				   /*current_error*/ 1,
1859				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1860				   /*asc*/ 0x4E,
1861				   /*ascq*/ 0x00,
1862				   SSD_ELEM_NONE);
1863
1864		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1865		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1866		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1867		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1868		msg_info.hdr.serializing_sc = NULL;
1869		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1870#if 0
1871		printf("BAD JUJU:Major Bummer Overlap\n");
1872#endif
1873		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1874		retval = 1;
1875		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1876		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1877		}
1878		break;
1879	case CTL_ACTION_OVERLAP_TAG:
1880		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1881		ctl_set_sense_data(&msg_info.scsi.sense_data,
1882				   lun,
1883				   /*sense_format*/SSD_TYPE_NONE,
1884				   /*current_error*/ 1,
1885				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1886				   /*asc*/ 0x4D,
1887				   /*ascq*/ ctsio->tag_num & 0xff,
1888				   SSD_ELEM_NONE);
1889
1890		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1891		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1892		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1893		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1894		msg_info.hdr.serializing_sc = NULL;
1895		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1896#if 0
1897		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1898#endif
1899		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1900		retval = 1;
1901		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1902		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1903		}
1904		break;
1905	case CTL_ACTION_ERROR:
1906	default:
1907		/* "Internal target failure" */
1908		ctl_set_sense_data(&msg_info.scsi.sense_data,
1909				   lun,
1910				   /*sense_format*/SSD_TYPE_NONE,
1911				   /*current_error*/ 1,
1912				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1913				   /*asc*/ 0x44,
1914				   /*ascq*/ 0x00,
1915				   SSD_ELEM_NONE);
1916
1917		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1918		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1919		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1920		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1921		msg_info.hdr.serializing_sc = NULL;
1922		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1923#if 0
1924		printf("BAD JUJU:Major Bummer HW Error\n");
1925#endif
1926		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1927		retval = 1;
1928		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1929		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1930		}
1931		break;
1932	}
1933	mtx_unlock(&lun->lun_lock);
1934	return (retval);
1935}
1936
1937static int
1938ctl_ioctl_submit_wait(union ctl_io *io)
1939{
1940	struct ctl_fe_ioctl_params params;
1941	ctl_fe_ioctl_state last_state;
1942	int done, retval;
1943
1944	retval = 0;
1945
1946	bzero(&params, sizeof(params));
1947
1948	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1949	cv_init(&params.sem, "ctlioccv");
1950	params.state = CTL_IOCTL_INPROG;
1951	last_state = params.state;
1952
1953	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1954
1955	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1956
1957	/* This shouldn't happen */
1958	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1959		return (retval);
1960
1961	done = 0;
1962
1963	do {
1964		mtx_lock(&params.ioctl_mtx);
1965		/*
1966		 * Check the state here, and don't sleep if the state has
1967		 * already changed (i.e. wakeup has already occured, but we
1968		 * weren't waiting yet).
1969		 */
1970		if (params.state == last_state) {
1971			/* XXX KDM cv_wait_sig instead? */
1972			cv_wait(&params.sem, &params.ioctl_mtx);
1973		}
1974		last_state = params.state;
1975
1976		switch (params.state) {
1977		case CTL_IOCTL_INPROG:
1978			/* Why did we wake up? */
1979			/* XXX KDM error here? */
1980			mtx_unlock(&params.ioctl_mtx);
1981			break;
1982		case CTL_IOCTL_DATAMOVE:
1983			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1984
1985			/*
1986			 * change last_state back to INPROG to avoid
1987			 * deadlock on subsequent data moves.
1988			 */
1989			params.state = last_state = CTL_IOCTL_INPROG;
1990
1991			mtx_unlock(&params.ioctl_mtx);
1992			ctl_ioctl_do_datamove(&io->scsiio);
1993			/*
1994			 * Note that in some cases, most notably writes,
1995			 * this will queue the I/O and call us back later.
1996			 * In other cases, generally reads, this routine
1997			 * will immediately call back and wake us up,
1998			 * probably using our own context.
1999			 */
2000			io->scsiio.be_move_done(io);
2001			break;
2002		case CTL_IOCTL_DONE:
2003			mtx_unlock(&params.ioctl_mtx);
2004			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
2005			done = 1;
2006			break;
2007		default:
2008			mtx_unlock(&params.ioctl_mtx);
2009			/* XXX KDM error here? */
2010			break;
2011		}
2012	} while (done == 0);
2013
2014	mtx_destroy(&params.ioctl_mtx);
2015	cv_destroy(&params.sem);
2016
2017	return (CTL_RETVAL_COMPLETE);
2018}
2019
2020static void
2021ctl_ioctl_datamove(union ctl_io *io)
2022{
2023	struct ctl_fe_ioctl_params *params;
2024
2025	params = (struct ctl_fe_ioctl_params *)
2026		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2027
2028	mtx_lock(&params->ioctl_mtx);
2029	params->state = CTL_IOCTL_DATAMOVE;
2030	cv_broadcast(&params->sem);
2031	mtx_unlock(&params->ioctl_mtx);
2032}
2033
2034static void
2035ctl_ioctl_done(union ctl_io *io)
2036{
2037	struct ctl_fe_ioctl_params *params;
2038
2039	params = (struct ctl_fe_ioctl_params *)
2040		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2041
2042	mtx_lock(&params->ioctl_mtx);
2043	params->state = CTL_IOCTL_DONE;
2044	cv_broadcast(&params->sem);
2045	mtx_unlock(&params->ioctl_mtx);
2046}
2047
2048static void
2049ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2050{
2051	struct ctl_fe_ioctl_startstop_info *sd_info;
2052
2053	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2054
2055	sd_info->hs_info.status = metatask->status;
2056	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2057	sd_info->hs_info.luns_complete =
2058		metatask->taskinfo.startstop.luns_complete;
2059	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2060
2061	cv_broadcast(&sd_info->sem);
2062}
2063
2064static void
2065ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2066{
2067	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2068
2069	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2070
2071	mtx_lock(fe_bbr_info->lock);
2072	fe_bbr_info->bbr_info->status = metatask->status;
2073	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2074	fe_bbr_info->wakeup_done = 1;
2075	mtx_unlock(fe_bbr_info->lock);
2076
2077	cv_broadcast(&fe_bbr_info->sem);
2078}
2079
2080/*
2081 * Returns 0 for success, errno for failure.
2082 */
2083static int
2084ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2085		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2086{
2087	union ctl_io *io;
2088	int retval;
2089
2090	retval = 0;
2091
2092	mtx_lock(&lun->lun_lock);
2093	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2094	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2095	     ooa_links)) {
2096		struct ctl_ooa_entry *entry;
2097
2098		/*
2099		 * If we've got more than we can fit, just count the
2100		 * remaining entries.
2101		 */
2102		if (*cur_fill_num >= ooa_hdr->alloc_num)
2103			continue;
2104
2105		entry = &kern_entries[*cur_fill_num];
2106
2107		entry->tag_num = io->scsiio.tag_num;
2108		entry->lun_num = lun->lun;
2109#ifdef CTL_TIME_IO
2110		entry->start_bt = io->io_hdr.start_bt;
2111#endif
2112		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2113		entry->cdb_len = io->scsiio.cdb_len;
2114		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2115			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2116
2117		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2118			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2119
2120		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2121			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2122
2123		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2124			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2125
2126		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2127			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2128	}
2129	mtx_unlock(&lun->lun_lock);
2130
2131	return (retval);
2132}
2133
2134static void *
2135ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2136		 size_t error_str_len)
2137{
2138	void *kptr;
2139
2140	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2141
2142	if (copyin(user_addr, kptr, len) != 0) {
2143		snprintf(error_str, error_str_len, "Error copying %d bytes "
2144			 "from user address %p to kernel address %p", len,
2145			 user_addr, kptr);
2146		free(kptr, M_CTL);
2147		return (NULL);
2148	}
2149
2150	return (kptr);
2151}
2152
2153static void
2154ctl_free_args(int num_args, struct ctl_be_arg *args)
2155{
2156	int i;
2157
2158	if (args == NULL)
2159		return;
2160
2161	for (i = 0; i < num_args; i++) {
2162		free(args[i].kname, M_CTL);
2163		free(args[i].kvalue, M_CTL);
2164	}
2165
2166	free(args, M_CTL);
2167}
2168
2169static struct ctl_be_arg *
2170ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2171		char *error_str, size_t error_str_len)
2172{
2173	struct ctl_be_arg *args;
2174	int i;
2175
2176	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2177				error_str, error_str_len);
2178
2179	if (args == NULL)
2180		goto bailout;
2181
2182	for (i = 0; i < num_args; i++) {
2183		args[i].kname = NULL;
2184		args[i].kvalue = NULL;
2185	}
2186
2187	for (i = 0; i < num_args; i++) {
2188		uint8_t *tmpptr;
2189
2190		args[i].kname = ctl_copyin_alloc(args[i].name,
2191			args[i].namelen, error_str, error_str_len);
2192		if (args[i].kname == NULL)
2193			goto bailout;
2194
2195		if (args[i].kname[args[i].namelen - 1] != '\0') {
2196			snprintf(error_str, error_str_len, "Argument %d "
2197				 "name is not NUL-terminated", i);
2198			goto bailout;
2199		}
2200
2201		if (args[i].flags & CTL_BEARG_RD) {
2202			tmpptr = ctl_copyin_alloc(args[i].value,
2203				args[i].vallen, error_str, error_str_len);
2204			if (tmpptr == NULL)
2205				goto bailout;
2206			if ((args[i].flags & CTL_BEARG_ASCII)
2207			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2208				snprintf(error_str, error_str_len, "Argument "
2209				    "%d value is not NUL-terminated", i);
2210				goto bailout;
2211			}
2212			args[i].kvalue = tmpptr;
2213		} else {
2214			args[i].kvalue = malloc(args[i].vallen,
2215			    M_CTL, M_WAITOK | M_ZERO);
2216		}
2217	}
2218
2219	return (args);
2220bailout:
2221
2222	ctl_free_args(num_args, args);
2223
2224	return (NULL);
2225}
2226
2227static void
2228ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2229{
2230	int i;
2231
2232	for (i = 0; i < num_args; i++) {
2233		if (args[i].flags & CTL_BEARG_WR)
2234			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2235	}
2236}
2237
2238/*
2239 * Escape characters that are illegal or not recommended in XML.
2240 */
2241int
2242ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2243{
2244	char *end = str + size;
2245	int retval;
2246
2247	retval = 0;
2248
2249	for (; *str && str < end; str++) {
2250		switch (*str) {
2251		case '&':
2252			retval = sbuf_printf(sb, "&amp;");
2253			break;
2254		case '>':
2255			retval = sbuf_printf(sb, "&gt;");
2256			break;
2257		case '<':
2258			retval = sbuf_printf(sb, "&lt;");
2259			break;
2260		default:
2261			retval = sbuf_putc(sb, *str);
2262			break;
2263		}
2264
2265		if (retval != 0)
2266			break;
2267
2268	}
2269
2270	return (retval);
2271}
2272
2273static void
2274ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2275{
2276	struct scsi_vpd_id_descriptor *desc;
2277	int i;
2278
2279	if (id == NULL || id->len < 4)
2280		return;
2281	desc = (struct scsi_vpd_id_descriptor *)id->data;
2282	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2283	case SVPD_ID_TYPE_T10:
2284		sbuf_printf(sb, "t10.");
2285		break;
2286	case SVPD_ID_TYPE_EUI64:
2287		sbuf_printf(sb, "eui.");
2288		break;
2289	case SVPD_ID_TYPE_NAA:
2290		sbuf_printf(sb, "naa.");
2291		break;
2292	case SVPD_ID_TYPE_SCSI_NAME:
2293		break;
2294	}
2295	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2296	case SVPD_ID_CODESET_BINARY:
2297		for (i = 0; i < desc->length; i++)
2298			sbuf_printf(sb, "%02x", desc->identifier[i]);
2299		break;
2300	case SVPD_ID_CODESET_ASCII:
2301		sbuf_printf(sb, "%.*s", (int)desc->length,
2302		    (char *)desc->identifier);
2303		break;
2304	case SVPD_ID_CODESET_UTF8:
2305		sbuf_printf(sb, "%s", (char *)desc->identifier);
2306		break;
2307	}
2308}
2309
2310static int
2311ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2312	  struct thread *td)
2313{
2314	struct ctl_softc *softc;
2315	int retval;
2316
2317	softc = control_softc;
2318
2319	retval = 0;
2320
2321	switch (cmd) {
2322	case CTL_IO: {
2323		union ctl_io *io;
2324		void *pool_tmp;
2325
2326		/*
2327		 * If we haven't been "enabled", don't allow any SCSI I/O
2328		 * to this FETD.
2329		 */
2330		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2331			retval = EPERM;
2332			break;
2333		}
2334
2335		io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2336
2337		/*
2338		 * Need to save the pool reference so it doesn't get
2339		 * spammed by the user's ctl_io.
2340		 */
2341		pool_tmp = io->io_hdr.pool;
2342		memcpy(io, (void *)addr, sizeof(*io));
2343		io->io_hdr.pool = pool_tmp;
2344
2345		/*
2346		 * No status yet, so make sure the status is set properly.
2347		 */
2348		io->io_hdr.status = CTL_STATUS_NONE;
2349
2350		/*
2351		 * The user sets the initiator ID, target and LUN IDs.
2352		 */
2353		io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2354		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2355		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2356		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2357			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2358
2359		retval = ctl_ioctl_submit_wait(io);
2360
2361		if (retval != 0) {
2362			ctl_free_io(io);
2363			break;
2364		}
2365
2366		memcpy((void *)addr, io, sizeof(*io));
2367
2368		/* return this to our pool */
2369		ctl_free_io(io);
2370
2371		break;
2372	}
2373	case CTL_ENABLE_PORT:
2374	case CTL_DISABLE_PORT:
2375	case CTL_SET_PORT_WWNS: {
2376		struct ctl_port *port;
2377		struct ctl_port_entry *entry;
2378
2379		entry = (struct ctl_port_entry *)addr;
2380
2381		mtx_lock(&softc->ctl_lock);
2382		STAILQ_FOREACH(port, &softc->port_list, links) {
2383			int action, done;
2384
2385			action = 0;
2386			done = 0;
2387
2388			if ((entry->port_type == CTL_PORT_NONE)
2389			 && (entry->targ_port == port->targ_port)) {
2390				/*
2391				 * If the user only wants to enable or
2392				 * disable or set WWNs on a specific port,
2393				 * do the operation and we're done.
2394				 */
2395				action = 1;
2396				done = 1;
2397			} else if (entry->port_type & port->port_type) {
2398				/*
2399				 * Compare the user's type mask with the
2400				 * particular frontend type to see if we
2401				 * have a match.
2402				 */
2403				action = 1;
2404				done = 0;
2405
2406				/*
2407				 * Make sure the user isn't trying to set
2408				 * WWNs on multiple ports at the same time.
2409				 */
2410				if (cmd == CTL_SET_PORT_WWNS) {
2411					printf("%s: Can't set WWNs on "
2412					       "multiple ports\n", __func__);
2413					retval = EINVAL;
2414					break;
2415				}
2416			}
2417			if (action != 0) {
2418				/*
2419				 * XXX KDM we have to drop the lock here,
2420				 * because the online/offline operations
2421				 * can potentially block.  We need to
2422				 * reference count the frontends so they
2423				 * can't go away,
2424				 */
2425				mtx_unlock(&softc->ctl_lock);
2426
2427				if (cmd == CTL_ENABLE_PORT) {
2428					struct ctl_lun *lun;
2429
2430					STAILQ_FOREACH(lun, &softc->lun_list,
2431						       links) {
2432						port->lun_enable(port->targ_lun_arg,
2433						    lun->target,
2434						    lun->lun);
2435					}
2436
2437					ctl_port_online(port);
2438				} else if (cmd == CTL_DISABLE_PORT) {
2439					struct ctl_lun *lun;
2440
2441					ctl_port_offline(port);
2442
2443					STAILQ_FOREACH(lun, &softc->lun_list,
2444						       links) {
2445						port->lun_disable(
2446						    port->targ_lun_arg,
2447						    lun->target,
2448						    lun->lun);
2449					}
2450				}
2451
2452				mtx_lock(&softc->ctl_lock);
2453
2454				if (cmd == CTL_SET_PORT_WWNS)
2455					ctl_port_set_wwns(port,
2456					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2457					    1 : 0, entry->wwnn,
2458					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2459					    1 : 0, entry->wwpn);
2460			}
2461			if (done != 0)
2462				break;
2463		}
2464		mtx_unlock(&softc->ctl_lock);
2465		break;
2466	}
2467	case CTL_GET_PORT_LIST: {
2468		struct ctl_port *port;
2469		struct ctl_port_list *list;
2470		int i;
2471
2472		list = (struct ctl_port_list *)addr;
2473
2474		if (list->alloc_len != (list->alloc_num *
2475		    sizeof(struct ctl_port_entry))) {
2476			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2477			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2478			       "%zu\n", __func__, list->alloc_len,
2479			       list->alloc_num, sizeof(struct ctl_port_entry));
2480			retval = EINVAL;
2481			break;
2482		}
2483		list->fill_len = 0;
2484		list->fill_num = 0;
2485		list->dropped_num = 0;
2486		i = 0;
2487		mtx_lock(&softc->ctl_lock);
2488		STAILQ_FOREACH(port, &softc->port_list, links) {
2489			struct ctl_port_entry entry, *list_entry;
2490
2491			if (list->fill_num >= list->alloc_num) {
2492				list->dropped_num++;
2493				continue;
2494			}
2495
2496			entry.port_type = port->port_type;
2497			strlcpy(entry.port_name, port->port_name,
2498				sizeof(entry.port_name));
2499			entry.targ_port = port->targ_port;
2500			entry.physical_port = port->physical_port;
2501			entry.virtual_port = port->virtual_port;
2502			entry.wwnn = port->wwnn;
2503			entry.wwpn = port->wwpn;
2504			if (port->status & CTL_PORT_STATUS_ONLINE)
2505				entry.online = 1;
2506			else
2507				entry.online = 0;
2508
2509			list_entry = &list->entries[i];
2510
2511			retval = copyout(&entry, list_entry, sizeof(entry));
2512			if (retval != 0) {
2513				printf("%s: CTL_GET_PORT_LIST: copyout "
2514				       "returned %d\n", __func__, retval);
2515				break;
2516			}
2517			i++;
2518			list->fill_num++;
2519			list->fill_len += sizeof(entry);
2520		}
2521		mtx_unlock(&softc->ctl_lock);
2522
2523		/*
2524		 * If this is non-zero, we had a copyout fault, so there's
2525		 * probably no point in attempting to set the status inside
2526		 * the structure.
2527		 */
2528		if (retval != 0)
2529			break;
2530
2531		if (list->dropped_num > 0)
2532			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2533		else
2534			list->status = CTL_PORT_LIST_OK;
2535		break;
2536	}
2537	case CTL_DUMP_OOA: {
2538		struct ctl_lun *lun;
2539		union ctl_io *io;
2540		char printbuf[128];
2541		struct sbuf sb;
2542
2543		mtx_lock(&softc->ctl_lock);
2544		printf("Dumping OOA queues:\n");
2545		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2546			mtx_lock(&lun->lun_lock);
2547			for (io = (union ctl_io *)TAILQ_FIRST(
2548			     &lun->ooa_queue); io != NULL;
2549			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2550			     ooa_links)) {
2551				sbuf_new(&sb, printbuf, sizeof(printbuf),
2552					 SBUF_FIXEDLEN);
2553				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2554					    (intmax_t)lun->lun,
2555					    io->scsiio.tag_num,
2556					    (io->io_hdr.flags &
2557					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2558					    (io->io_hdr.flags &
2559					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2560					    (io->io_hdr.flags &
2561					    CTL_FLAG_ABORT) ? " ABORT" : "",
2562			                    (io->io_hdr.flags &
2563		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2564				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2565				sbuf_finish(&sb);
2566				printf("%s\n", sbuf_data(&sb));
2567			}
2568			mtx_unlock(&lun->lun_lock);
2569		}
2570		printf("OOA queues dump done\n");
2571		mtx_unlock(&softc->ctl_lock);
2572		break;
2573	}
2574	case CTL_GET_OOA: {
2575		struct ctl_lun *lun;
2576		struct ctl_ooa *ooa_hdr;
2577		struct ctl_ooa_entry *entries;
2578		uint32_t cur_fill_num;
2579
2580		ooa_hdr = (struct ctl_ooa *)addr;
2581
2582		if ((ooa_hdr->alloc_len == 0)
2583		 || (ooa_hdr->alloc_num == 0)) {
2584			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2585			       "must be non-zero\n", __func__,
2586			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2587			retval = EINVAL;
2588			break;
2589		}
2590
2591		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2592		    sizeof(struct ctl_ooa_entry))) {
2593			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2594			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2595			       __func__, ooa_hdr->alloc_len,
2596			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2597			retval = EINVAL;
2598			break;
2599		}
2600
2601		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2602		if (entries == NULL) {
2603			printf("%s: could not allocate %d bytes for OOA "
2604			       "dump\n", __func__, ooa_hdr->alloc_len);
2605			retval = ENOMEM;
2606			break;
2607		}
2608
2609		mtx_lock(&softc->ctl_lock);
2610		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2611		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2612		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2613			mtx_unlock(&softc->ctl_lock);
2614			free(entries, M_CTL);
2615			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2616			       __func__, (uintmax_t)ooa_hdr->lun_num);
2617			retval = EINVAL;
2618			break;
2619		}
2620
2621		cur_fill_num = 0;
2622
2623		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2624			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2625				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2626					ooa_hdr, entries);
2627				if (retval != 0)
2628					break;
2629			}
2630			if (retval != 0) {
2631				mtx_unlock(&softc->ctl_lock);
2632				free(entries, M_CTL);
2633				break;
2634			}
2635		} else {
2636			lun = softc->ctl_luns[ooa_hdr->lun_num];
2637
2638			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2639						    entries);
2640		}
2641		mtx_unlock(&softc->ctl_lock);
2642
2643		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2644		ooa_hdr->fill_len = ooa_hdr->fill_num *
2645			sizeof(struct ctl_ooa_entry);
2646		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2647		if (retval != 0) {
2648			printf("%s: error copying out %d bytes for OOA dump\n",
2649			       __func__, ooa_hdr->fill_len);
2650		}
2651
2652		getbintime(&ooa_hdr->cur_bt);
2653
2654		if (cur_fill_num > ooa_hdr->alloc_num) {
2655			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2656			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2657		} else {
2658			ooa_hdr->dropped_num = 0;
2659			ooa_hdr->status = CTL_OOA_OK;
2660		}
2661
2662		free(entries, M_CTL);
2663		break;
2664	}
2665	case CTL_CHECK_OOA: {
2666		union ctl_io *io;
2667		struct ctl_lun *lun;
2668		struct ctl_ooa_info *ooa_info;
2669
2670
2671		ooa_info = (struct ctl_ooa_info *)addr;
2672
2673		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2674			ooa_info->status = CTL_OOA_INVALID_LUN;
2675			break;
2676		}
2677		mtx_lock(&softc->ctl_lock);
2678		lun = softc->ctl_luns[ooa_info->lun_id];
2679		if (lun == NULL) {
2680			mtx_unlock(&softc->ctl_lock);
2681			ooa_info->status = CTL_OOA_INVALID_LUN;
2682			break;
2683		}
2684		mtx_lock(&lun->lun_lock);
2685		mtx_unlock(&softc->ctl_lock);
2686		ooa_info->num_entries = 0;
2687		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2688		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2689		     &io->io_hdr, ooa_links)) {
2690			ooa_info->num_entries++;
2691		}
2692		mtx_unlock(&lun->lun_lock);
2693
2694		ooa_info->status = CTL_OOA_SUCCESS;
2695
2696		break;
2697	}
2698	case CTL_HARD_START:
2699	case CTL_HARD_STOP: {
2700		struct ctl_fe_ioctl_startstop_info ss_info;
2701		struct cfi_metatask *metatask;
2702		struct mtx hs_mtx;
2703
2704		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2705
2706		cv_init(&ss_info.sem, "hard start/stop cv" );
2707
2708		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2709		if (metatask == NULL) {
2710			retval = ENOMEM;
2711			mtx_destroy(&hs_mtx);
2712			break;
2713		}
2714
2715		if (cmd == CTL_HARD_START)
2716			metatask->tasktype = CFI_TASK_STARTUP;
2717		else
2718			metatask->tasktype = CFI_TASK_SHUTDOWN;
2719
2720		metatask->callback = ctl_ioctl_hard_startstop_callback;
2721		metatask->callback_arg = &ss_info;
2722
2723		cfi_action(metatask);
2724
2725		/* Wait for the callback */
2726		mtx_lock(&hs_mtx);
2727		cv_wait_sig(&ss_info.sem, &hs_mtx);
2728		mtx_unlock(&hs_mtx);
2729
2730		/*
2731		 * All information has been copied from the metatask by the
2732		 * time cv_broadcast() is called, so we free the metatask here.
2733		 */
2734		cfi_free_metatask(metatask);
2735
2736		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2737
2738		mtx_destroy(&hs_mtx);
2739		break;
2740	}
2741	case CTL_BBRREAD: {
2742		struct ctl_bbrread_info *bbr_info;
2743		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2744		struct mtx bbr_mtx;
2745		struct cfi_metatask *metatask;
2746
2747		bbr_info = (struct ctl_bbrread_info *)addr;
2748
2749		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2750
2751		bzero(&bbr_mtx, sizeof(bbr_mtx));
2752		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2753
2754		fe_bbr_info.bbr_info = bbr_info;
2755		fe_bbr_info.lock = &bbr_mtx;
2756
2757		cv_init(&fe_bbr_info.sem, "BBR read cv");
2758		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2759
2760		if (metatask == NULL) {
2761			mtx_destroy(&bbr_mtx);
2762			cv_destroy(&fe_bbr_info.sem);
2763			retval = ENOMEM;
2764			break;
2765		}
2766		metatask->tasktype = CFI_TASK_BBRREAD;
2767		metatask->callback = ctl_ioctl_bbrread_callback;
2768		metatask->callback_arg = &fe_bbr_info;
2769		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2770		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2771		metatask->taskinfo.bbrread.len = bbr_info->len;
2772
2773		cfi_action(metatask);
2774
2775		mtx_lock(&bbr_mtx);
2776		while (fe_bbr_info.wakeup_done == 0)
2777			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2778		mtx_unlock(&bbr_mtx);
2779
2780		bbr_info->status = metatask->status;
2781		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2782		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2783		memcpy(&bbr_info->sense_data,
2784		       &metatask->taskinfo.bbrread.sense_data,
2785		       ctl_min(sizeof(bbr_info->sense_data),
2786			       sizeof(metatask->taskinfo.bbrread.sense_data)));
2787
2788		cfi_free_metatask(metatask);
2789
2790		mtx_destroy(&bbr_mtx);
2791		cv_destroy(&fe_bbr_info.sem);
2792
2793		break;
2794	}
2795	case CTL_DELAY_IO: {
2796		struct ctl_io_delay_info *delay_info;
2797#ifdef CTL_IO_DELAY
2798		struct ctl_lun *lun;
2799#endif /* CTL_IO_DELAY */
2800
2801		delay_info = (struct ctl_io_delay_info *)addr;
2802
2803#ifdef CTL_IO_DELAY
2804		mtx_lock(&softc->ctl_lock);
2805
2806		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2807		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2808			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2809		} else {
2810			lun = softc->ctl_luns[delay_info->lun_id];
2811			mtx_lock(&lun->lun_lock);
2812
2813			delay_info->status = CTL_DELAY_STATUS_OK;
2814
2815			switch (delay_info->delay_type) {
2816			case CTL_DELAY_TYPE_CONT:
2817				break;
2818			case CTL_DELAY_TYPE_ONESHOT:
2819				break;
2820			default:
2821				delay_info->status =
2822					CTL_DELAY_STATUS_INVALID_TYPE;
2823				break;
2824			}
2825
2826			switch (delay_info->delay_loc) {
2827			case CTL_DELAY_LOC_DATAMOVE:
2828				lun->delay_info.datamove_type =
2829					delay_info->delay_type;
2830				lun->delay_info.datamove_delay =
2831					delay_info->delay_secs;
2832				break;
2833			case CTL_DELAY_LOC_DONE:
2834				lun->delay_info.done_type =
2835					delay_info->delay_type;
2836				lun->delay_info.done_delay =
2837					delay_info->delay_secs;
2838				break;
2839			default:
2840				delay_info->status =
2841					CTL_DELAY_STATUS_INVALID_LOC;
2842				break;
2843			}
2844			mtx_unlock(&lun->lun_lock);
2845		}
2846
2847		mtx_unlock(&softc->ctl_lock);
2848#else
2849		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2850#endif /* CTL_IO_DELAY */
2851		break;
2852	}
2853	case CTL_REALSYNC_SET: {
2854		int *syncstate;
2855
2856		syncstate = (int *)addr;
2857
2858		mtx_lock(&softc->ctl_lock);
2859		switch (*syncstate) {
2860		case 0:
2861			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2862			break;
2863		case 1:
2864			softc->flags |= CTL_FLAG_REAL_SYNC;
2865			break;
2866		default:
2867			retval = EINVAL;
2868			break;
2869		}
2870		mtx_unlock(&softc->ctl_lock);
2871		break;
2872	}
2873	case CTL_REALSYNC_GET: {
2874		int *syncstate;
2875
2876		syncstate = (int*)addr;
2877
2878		mtx_lock(&softc->ctl_lock);
2879		if (softc->flags & CTL_FLAG_REAL_SYNC)
2880			*syncstate = 1;
2881		else
2882			*syncstate = 0;
2883		mtx_unlock(&softc->ctl_lock);
2884
2885		break;
2886	}
2887	case CTL_SETSYNC:
2888	case CTL_GETSYNC: {
2889		struct ctl_sync_info *sync_info;
2890		struct ctl_lun *lun;
2891
2892		sync_info = (struct ctl_sync_info *)addr;
2893
2894		mtx_lock(&softc->ctl_lock);
2895		lun = softc->ctl_luns[sync_info->lun_id];
2896		if (lun == NULL) {
2897			mtx_unlock(&softc->ctl_lock);
2898			sync_info->status = CTL_GS_SYNC_NO_LUN;
2899		}
2900		/*
2901		 * Get or set the sync interval.  We're not bounds checking
2902		 * in the set case, hopefully the user won't do something
2903		 * silly.
2904		 */
2905		mtx_lock(&lun->lun_lock);
2906		mtx_unlock(&softc->ctl_lock);
2907		if (cmd == CTL_GETSYNC)
2908			sync_info->sync_interval = lun->sync_interval;
2909		else
2910			lun->sync_interval = sync_info->sync_interval;
2911		mtx_unlock(&lun->lun_lock);
2912
2913		sync_info->status = CTL_GS_SYNC_OK;
2914
2915		break;
2916	}
2917	case CTL_GETSTATS: {
2918		struct ctl_stats *stats;
2919		struct ctl_lun *lun;
2920		int i;
2921
2922		stats = (struct ctl_stats *)addr;
2923
2924		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2925		     stats->alloc_len) {
2926			stats->status = CTL_SS_NEED_MORE_SPACE;
2927			stats->num_luns = softc->num_luns;
2928			break;
2929		}
2930		/*
2931		 * XXX KDM no locking here.  If the LUN list changes,
2932		 * things can blow up.
2933		 */
2934		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2935		     i++, lun = STAILQ_NEXT(lun, links)) {
2936			retval = copyout(&lun->stats, &stats->lun_stats[i],
2937					 sizeof(lun->stats));
2938			if (retval != 0)
2939				break;
2940		}
2941		stats->num_luns = softc->num_luns;
2942		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2943				 softc->num_luns;
2944		stats->status = CTL_SS_OK;
2945#ifdef CTL_TIME_IO
2946		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2947#else
2948		stats->flags = CTL_STATS_FLAG_NONE;
2949#endif
2950		getnanouptime(&stats->timestamp);
2951		break;
2952	}
2953	case CTL_ERROR_INJECT: {
2954		struct ctl_error_desc *err_desc, *new_err_desc;
2955		struct ctl_lun *lun;
2956
2957		err_desc = (struct ctl_error_desc *)addr;
2958
2959		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2960				      M_WAITOK | M_ZERO);
2961		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2962
2963		mtx_lock(&softc->ctl_lock);
2964		lun = softc->ctl_luns[err_desc->lun_id];
2965		if (lun == NULL) {
2966			mtx_unlock(&softc->ctl_lock);
2967			free(new_err_desc, M_CTL);
2968			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2969			       __func__, (uintmax_t)err_desc->lun_id);
2970			retval = EINVAL;
2971			break;
2972		}
2973		mtx_lock(&lun->lun_lock);
2974		mtx_unlock(&softc->ctl_lock);
2975
2976		/*
2977		 * We could do some checking here to verify the validity
2978		 * of the request, but given the complexity of error
2979		 * injection requests, the checking logic would be fairly
2980		 * complex.
2981		 *
2982		 * For now, if the request is invalid, it just won't get
2983		 * executed and might get deleted.
2984		 */
2985		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2986
2987		/*
2988		 * XXX KDM check to make sure the serial number is unique,
2989		 * in case we somehow manage to wrap.  That shouldn't
2990		 * happen for a very long time, but it's the right thing to
2991		 * do.
2992		 */
2993		new_err_desc->serial = lun->error_serial;
2994		err_desc->serial = lun->error_serial;
2995		lun->error_serial++;
2996
2997		mtx_unlock(&lun->lun_lock);
2998		break;
2999	}
3000	case CTL_ERROR_INJECT_DELETE: {
3001		struct ctl_error_desc *delete_desc, *desc, *desc2;
3002		struct ctl_lun *lun;
3003		int delete_done;
3004
3005		delete_desc = (struct ctl_error_desc *)addr;
3006		delete_done = 0;
3007
3008		mtx_lock(&softc->ctl_lock);
3009		lun = softc->ctl_luns[delete_desc->lun_id];
3010		if (lun == NULL) {
3011			mtx_unlock(&softc->ctl_lock);
3012			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
3013			       __func__, (uintmax_t)delete_desc->lun_id);
3014			retval = EINVAL;
3015			break;
3016		}
3017		mtx_lock(&lun->lun_lock);
3018		mtx_unlock(&softc->ctl_lock);
3019		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
3020			if (desc->serial != delete_desc->serial)
3021				continue;
3022
3023			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
3024				      links);
3025			free(desc, M_CTL);
3026			delete_done = 1;
3027		}
3028		mtx_unlock(&lun->lun_lock);
3029		if (delete_done == 0) {
3030			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
3031			       "error serial %ju on LUN %u\n", __func__,
3032			       delete_desc->serial, delete_desc->lun_id);
3033			retval = EINVAL;
3034			break;
3035		}
3036		break;
3037	}
3038	case CTL_DUMP_STRUCTS: {
3039		int i, j, k;
3040		struct ctl_port *port;
3041		struct ctl_frontend *fe;
3042
3043		mtx_lock(&softc->ctl_lock);
3044		printf("CTL Persistent Reservation information start:\n");
3045		for (i = 0; i < CTL_MAX_LUNS; i++) {
3046			struct ctl_lun *lun;
3047
3048			lun = softc->ctl_luns[i];
3049
3050			if ((lun == NULL)
3051			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
3052				continue;
3053
3054			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
3055				if (lun->pr_keys[j] == NULL)
3056					continue;
3057				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
3058					if (lun->pr_keys[j][k] == 0)
3059						continue;
3060					printf("  LUN %d port %d iid %d key "
3061					       "%#jx\n", i, j, k,
3062					       (uintmax_t)lun->pr_keys[j][k]);
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
3651static uint64_t
3652ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3653{
3654	uint64_t *t;
3655
3656	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3657	if (t == NULL)
3658		return (0);
3659	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3660}
3661
3662static void
3663ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3664{
3665	uint64_t *t;
3666
3667	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3668	if (t == NULL)
3669		return;
3670	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3671}
3672
3673static void
3674ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3675{
3676	uint64_t *p;
3677	u_int i;
3678
3679	i = residx/CTL_MAX_INIT_PER_PORT;
3680	if (lun->pr_keys[i] != NULL)
3681		return;
3682	mtx_unlock(&lun->lun_lock);
3683	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3684	    M_WAITOK | M_ZERO);
3685	mtx_lock(&lun->lun_lock);
3686	if (lun->pr_keys[i] == NULL)
3687		lun->pr_keys[i] = p;
3688	else
3689		free(p, M_CTL);
3690}
3691
3692static void
3693ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3694{
3695	uint64_t *t;
3696
3697	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3698	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3699	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3700}
3701
3702#ifdef unused
3703/*
3704 * The bus, target and lun are optional, they can be filled in later.
3705 * can_wait is used to determine whether we can wait on the malloc or not.
3706 */
3707union ctl_io*
3708ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3709	      uint32_t targ_lun, int can_wait)
3710{
3711	union ctl_io *io;
3712
3713	if (can_wait)
3714		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3715	else
3716		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3717
3718	if (io != NULL) {
3719		io->io_hdr.io_type = io_type;
3720		io->io_hdr.targ_port = targ_port;
3721		/*
3722		 * XXX KDM this needs to change/go away.  We need to move
3723		 * to a preallocated pool of ctl_scsiio structures.
3724		 */
3725		io->io_hdr.nexus.targ_target.id = targ_target;
3726		io->io_hdr.nexus.targ_lun = targ_lun;
3727	}
3728
3729	return (io);
3730}
3731
3732void
3733ctl_kfree_io(union ctl_io *io)
3734{
3735	free(io, M_CTL);
3736}
3737#endif /* unused */
3738
3739/*
3740 * ctl_softc, pool_name, total_ctl_io are passed in.
3741 * npool is passed out.
3742 */
3743int
3744ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3745		uint32_t total_ctl_io, void **npool)
3746{
3747#ifdef IO_POOLS
3748	struct ctl_io_pool *pool;
3749
3750	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3751					    M_NOWAIT | M_ZERO);
3752	if (pool == NULL)
3753		return (ENOMEM);
3754
3755	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3756	pool->ctl_softc = ctl_softc;
3757	pool->zone = uma_zsecond_create(pool->name, NULL,
3758	    NULL, NULL, NULL, ctl_softc->io_zone);
3759	/* uma_prealloc(pool->zone, total_ctl_io); */
3760
3761	*npool = pool;
3762#else
3763	*npool = ctl_softc->io_zone;
3764#endif
3765	return (0);
3766}
3767
3768void
3769ctl_pool_free(struct ctl_io_pool *pool)
3770{
3771
3772	if (pool == NULL)
3773		return;
3774
3775#ifdef IO_POOLS
3776	uma_zdestroy(pool->zone);
3777	free(pool, M_CTL);
3778#endif
3779}
3780
3781union ctl_io *
3782ctl_alloc_io(void *pool_ref)
3783{
3784	union ctl_io *io;
3785#ifdef IO_POOLS
3786	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3787
3788	io = uma_zalloc(pool->zone, M_WAITOK);
3789#else
3790	io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3791#endif
3792	if (io != NULL)
3793		io->io_hdr.pool = pool_ref;
3794	return (io);
3795}
3796
3797union ctl_io *
3798ctl_alloc_io_nowait(void *pool_ref)
3799{
3800	union ctl_io *io;
3801#ifdef IO_POOLS
3802	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3803
3804	io = uma_zalloc(pool->zone, M_NOWAIT);
3805#else
3806	io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3807#endif
3808	if (io != NULL)
3809		io->io_hdr.pool = pool_ref;
3810	return (io);
3811}
3812
3813void
3814ctl_free_io(union ctl_io *io)
3815{
3816#ifdef IO_POOLS
3817	struct ctl_io_pool *pool;
3818#endif
3819
3820	if (io == NULL)
3821		return;
3822
3823#ifdef IO_POOLS
3824	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3825	uma_zfree(pool->zone, io);
3826#else
3827	uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3828#endif
3829}
3830
3831void
3832ctl_zero_io(union ctl_io *io)
3833{
3834	void *pool_ref;
3835
3836	if (io == NULL)
3837		return;
3838
3839	/*
3840	 * May need to preserve linked list pointers at some point too.
3841	 */
3842	pool_ref = io->io_hdr.pool;
3843	memset(io, 0, sizeof(*io));
3844	io->io_hdr.pool = pool_ref;
3845}
3846
3847/*
3848 * This routine is currently used for internal copies of ctl_ios that need
3849 * to persist for some reason after we've already returned status to the
3850 * FETD.  (Thus the flag set.)
3851 *
3852 * XXX XXX
3853 * Note that this makes a blind copy of all fields in the ctl_io, except
3854 * for the pool reference.  This includes any memory that has been
3855 * allocated!  That memory will no longer be valid after done has been
3856 * called, so this would be VERY DANGEROUS for command that actually does
3857 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3858 * start and stop commands, which don't transfer any data, so this is not a
3859 * problem.  If it is used for anything else, the caller would also need to
3860 * allocate data buffer space and this routine would need to be modified to
3861 * copy the data buffer(s) as well.
3862 */
3863void
3864ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3865{
3866	void *pool_ref;
3867
3868	if ((src == NULL)
3869	 || (dest == NULL))
3870		return;
3871
3872	/*
3873	 * May need to preserve linked list pointers at some point too.
3874	 */
3875	pool_ref = dest->io_hdr.pool;
3876
3877	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3878
3879	dest->io_hdr.pool = pool_ref;
3880	/*
3881	 * We need to know that this is an internal copy, and doesn't need
3882	 * to get passed back to the FETD that allocated it.
3883	 */
3884	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3885}
3886
3887static int
3888ctl_expand_number(const char *buf, uint64_t *num)
3889{
3890	char *endptr;
3891	uint64_t number;
3892	unsigned shift;
3893
3894	number = strtoq(buf, &endptr, 0);
3895
3896	switch (tolower((unsigned char)*endptr)) {
3897	case 'e':
3898		shift = 60;
3899		break;
3900	case 'p':
3901		shift = 50;
3902		break;
3903	case 't':
3904		shift = 40;
3905		break;
3906	case 'g':
3907		shift = 30;
3908		break;
3909	case 'm':
3910		shift = 20;
3911		break;
3912	case 'k':
3913		shift = 10;
3914		break;
3915	case 'b':
3916	case '\0': /* No unit. */
3917		*num = number;
3918		return (0);
3919	default:
3920		/* Unrecognized unit. */
3921		return (-1);
3922	}
3923
3924	if ((number << shift) >> shift != number) {
3925		/* Overflow */
3926		return (-1);
3927	}
3928	*num = number << shift;
3929	return (0);
3930}
3931
3932
3933/*
3934 * This routine could be used in the future to load default and/or saved
3935 * mode page parameters for a particuar lun.
3936 */
3937static int
3938ctl_init_page_index(struct ctl_lun *lun)
3939{
3940	int i;
3941	struct ctl_page_index *page_index;
3942	const char *value;
3943	uint64_t ival;
3944
3945	memcpy(&lun->mode_pages.index, page_index_template,
3946	       sizeof(page_index_template));
3947
3948	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3949
3950		page_index = &lun->mode_pages.index[i];
3951		/*
3952		 * If this is a disk-only mode page, there's no point in
3953		 * setting it up.  For some pages, we have to have some
3954		 * basic information about the disk in order to calculate the
3955		 * mode page data.
3956		 */
3957		if ((lun->be_lun->lun_type != T_DIRECT)
3958		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3959			continue;
3960
3961		switch (page_index->page_code & SMPH_PC_MASK) {
3962		case SMS_RW_ERROR_RECOVERY_PAGE: {
3963			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3964				panic("subpage is incorrect!");
3965			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3966			       &rw_er_page_default,
3967			       sizeof(rw_er_page_default));
3968			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3969			       &rw_er_page_changeable,
3970			       sizeof(rw_er_page_changeable));
3971			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3972			       &rw_er_page_default,
3973			       sizeof(rw_er_page_default));
3974			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3975			       &rw_er_page_default,
3976			       sizeof(rw_er_page_default));
3977			page_index->page_data =
3978				(uint8_t *)lun->mode_pages.rw_er_page;
3979			break;
3980		}
3981		case SMS_FORMAT_DEVICE_PAGE: {
3982			struct scsi_format_page *format_page;
3983
3984			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3985				panic("subpage is incorrect!");
3986
3987			/*
3988			 * Sectors per track are set above.  Bytes per
3989			 * sector need to be set here on a per-LUN basis.
3990			 */
3991			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3992			       &format_page_default,
3993			       sizeof(format_page_default));
3994			memcpy(&lun->mode_pages.format_page[
3995			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
3996			       sizeof(format_page_changeable));
3997			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3998			       &format_page_default,
3999			       sizeof(format_page_default));
4000			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4001			       &format_page_default,
4002			       sizeof(format_page_default));
4003
4004			format_page = &lun->mode_pages.format_page[
4005				CTL_PAGE_CURRENT];
4006			scsi_ulto2b(lun->be_lun->blocksize,
4007				    format_page->bytes_per_sector);
4008
4009			format_page = &lun->mode_pages.format_page[
4010				CTL_PAGE_DEFAULT];
4011			scsi_ulto2b(lun->be_lun->blocksize,
4012				    format_page->bytes_per_sector);
4013
4014			format_page = &lun->mode_pages.format_page[
4015				CTL_PAGE_SAVED];
4016			scsi_ulto2b(lun->be_lun->blocksize,
4017				    format_page->bytes_per_sector);
4018
4019			page_index->page_data =
4020				(uint8_t *)lun->mode_pages.format_page;
4021			break;
4022		}
4023		case SMS_RIGID_DISK_PAGE: {
4024			struct scsi_rigid_disk_page *rigid_disk_page;
4025			uint32_t sectors_per_cylinder;
4026			uint64_t cylinders;
4027#ifndef	__XSCALE__
4028			int shift;
4029#endif /* !__XSCALE__ */
4030
4031			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4032				panic("invalid subpage value %d",
4033				      page_index->subpage);
4034
4035			/*
4036			 * Rotation rate and sectors per track are set
4037			 * above.  We calculate the cylinders here based on
4038			 * capacity.  Due to the number of heads and
4039			 * sectors per track we're using, smaller arrays
4040			 * may turn out to have 0 cylinders.  Linux and
4041			 * FreeBSD don't pay attention to these mode pages
4042			 * to figure out capacity, but Solaris does.  It
4043			 * seems to deal with 0 cylinders just fine, and
4044			 * works out a fake geometry based on the capacity.
4045			 */
4046			memcpy(&lun->mode_pages.rigid_disk_page[
4047			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4048			       sizeof(rigid_disk_page_default));
4049			memcpy(&lun->mode_pages.rigid_disk_page[
4050			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4051			       sizeof(rigid_disk_page_changeable));
4052
4053			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4054				CTL_DEFAULT_HEADS;
4055
4056			/*
4057			 * The divide method here will be more accurate,
4058			 * probably, but results in floating point being
4059			 * used in the kernel on i386 (__udivdi3()).  On the
4060			 * XScale, though, __udivdi3() is implemented in
4061			 * software.
4062			 *
4063			 * The shift method for cylinder calculation is
4064			 * accurate if sectors_per_cylinder is a power of
4065			 * 2.  Otherwise it might be slightly off -- you
4066			 * might have a bit of a truncation problem.
4067			 */
4068#ifdef	__XSCALE__
4069			cylinders = (lun->be_lun->maxlba + 1) /
4070				sectors_per_cylinder;
4071#else
4072			for (shift = 31; shift > 0; shift--) {
4073				if (sectors_per_cylinder & (1 << shift))
4074					break;
4075			}
4076			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4077#endif
4078
4079			/*
4080			 * We've basically got 3 bytes, or 24 bits for the
4081			 * cylinder size in the mode page.  If we're over,
4082			 * just round down to 2^24.
4083			 */
4084			if (cylinders > 0xffffff)
4085				cylinders = 0xffffff;
4086
4087			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4088				CTL_PAGE_DEFAULT];
4089			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4090
4091			if ((value = ctl_get_opt(&lun->be_lun->options,
4092			    "rpm")) != NULL) {
4093				scsi_ulto2b(strtol(value, NULL, 0),
4094				     rigid_disk_page->rotation_rate);
4095			}
4096
4097			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4098			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4099			       sizeof(rigid_disk_page_default));
4100			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4101			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4102			       sizeof(rigid_disk_page_default));
4103
4104			page_index->page_data =
4105				(uint8_t *)lun->mode_pages.rigid_disk_page;
4106			break;
4107		}
4108		case SMS_CACHING_PAGE: {
4109			struct scsi_caching_page *caching_page;
4110
4111			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4112				panic("invalid subpage value %d",
4113				      page_index->subpage);
4114			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4115			       &caching_page_default,
4116			       sizeof(caching_page_default));
4117			memcpy(&lun->mode_pages.caching_page[
4118			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4119			       sizeof(caching_page_changeable));
4120			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4121			       &caching_page_default,
4122			       sizeof(caching_page_default));
4123			caching_page = &lun->mode_pages.caching_page[
4124			    CTL_PAGE_SAVED];
4125			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4126			if (value != NULL && strcmp(value, "off") == 0)
4127				caching_page->flags1 &= ~SCP_WCE;
4128			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4129			if (value != NULL && strcmp(value, "off") == 0)
4130				caching_page->flags1 |= SCP_RCD;
4131			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4132			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4133			       sizeof(caching_page_default));
4134			page_index->page_data =
4135				(uint8_t *)lun->mode_pages.caching_page;
4136			break;
4137		}
4138		case SMS_CONTROL_MODE_PAGE: {
4139			struct scsi_control_page *control_page;
4140
4141			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4142				panic("invalid subpage value %d",
4143				      page_index->subpage);
4144
4145			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4146			       &control_page_default,
4147			       sizeof(control_page_default));
4148			memcpy(&lun->mode_pages.control_page[
4149			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4150			       sizeof(control_page_changeable));
4151			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4152			       &control_page_default,
4153			       sizeof(control_page_default));
4154			control_page = &lun->mode_pages.control_page[
4155			    CTL_PAGE_SAVED];
4156			value = ctl_get_opt(&lun->be_lun->options, "reordering");
4157			if (value != NULL && strcmp(value, "unrestricted") == 0) {
4158				control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4159				control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4160			}
4161			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4162			       &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4163			       sizeof(control_page_default));
4164			page_index->page_data =
4165				(uint8_t *)lun->mode_pages.control_page;
4166			break;
4167
4168		}
4169		case SMS_INFO_EXCEPTIONS_PAGE: {
4170			switch (page_index->subpage) {
4171			case SMS_SUBPAGE_PAGE_0:
4172				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4173				       &ie_page_default,
4174				       sizeof(ie_page_default));
4175				memcpy(&lun->mode_pages.ie_page[
4176				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4177				       sizeof(ie_page_changeable));
4178				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4179				       &ie_page_default,
4180				       sizeof(ie_page_default));
4181				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4182				       &ie_page_default,
4183				       sizeof(ie_page_default));
4184				page_index->page_data =
4185					(uint8_t *)lun->mode_pages.ie_page;
4186				break;
4187			case 0x02: {
4188				struct ctl_logical_block_provisioning_page *page;
4189
4190				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4191				       &lbp_page_default,
4192				       sizeof(lbp_page_default));
4193				memcpy(&lun->mode_pages.lbp_page[
4194				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4195				       sizeof(lbp_page_changeable));
4196				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4197				       &lbp_page_default,
4198				       sizeof(lbp_page_default));
4199				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4200				value = ctl_get_opt(&lun->be_lun->options,
4201				    "avail-threshold");
4202				if (value != NULL &&
4203				    ctl_expand_number(value, &ival) == 0) {
4204					page->descr[0].flags |= SLBPPD_ENABLED |
4205					    SLBPPD_ARMING_DEC;
4206					if (lun->be_lun->blocksize)
4207						ival /= lun->be_lun->blocksize;
4208					else
4209						ival /= 512;
4210					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4211					    page->descr[0].count);
4212				}
4213				value = ctl_get_opt(&lun->be_lun->options,
4214				    "used-threshold");
4215				if (value != NULL &&
4216				    ctl_expand_number(value, &ival) == 0) {
4217					page->descr[1].flags |= SLBPPD_ENABLED |
4218					    SLBPPD_ARMING_INC;
4219					if (lun->be_lun->blocksize)
4220						ival /= lun->be_lun->blocksize;
4221					else
4222						ival /= 512;
4223					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4224					    page->descr[1].count);
4225				}
4226				value = ctl_get_opt(&lun->be_lun->options,
4227				    "pool-avail-threshold");
4228				if (value != NULL &&
4229				    ctl_expand_number(value, &ival) == 0) {
4230					page->descr[2].flags |= SLBPPD_ENABLED |
4231					    SLBPPD_ARMING_DEC;
4232					if (lun->be_lun->blocksize)
4233						ival /= lun->be_lun->blocksize;
4234					else
4235						ival /= 512;
4236					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4237					    page->descr[2].count);
4238				}
4239				value = ctl_get_opt(&lun->be_lun->options,
4240				    "pool-used-threshold");
4241				if (value != NULL &&
4242				    ctl_expand_number(value, &ival) == 0) {
4243					page->descr[3].flags |= SLBPPD_ENABLED |
4244					    SLBPPD_ARMING_INC;
4245					if (lun->be_lun->blocksize)
4246						ival /= lun->be_lun->blocksize;
4247					else
4248						ival /= 512;
4249					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4250					    page->descr[3].count);
4251				}
4252				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4253				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4254				       sizeof(lbp_page_default));
4255				page_index->page_data =
4256					(uint8_t *)lun->mode_pages.lbp_page;
4257			}}
4258			break;
4259		}
4260		case SMS_VENDOR_SPECIFIC_PAGE:{
4261			switch (page_index->subpage) {
4262			case DBGCNF_SUBPAGE_CODE: {
4263				struct copan_debugconf_subpage *current_page,
4264							       *saved_page;
4265
4266				memcpy(&lun->mode_pages.debugconf_subpage[
4267				       CTL_PAGE_CURRENT],
4268				       &debugconf_page_default,
4269				       sizeof(debugconf_page_default));
4270				memcpy(&lun->mode_pages.debugconf_subpage[
4271				       CTL_PAGE_CHANGEABLE],
4272				       &debugconf_page_changeable,
4273				       sizeof(debugconf_page_changeable));
4274				memcpy(&lun->mode_pages.debugconf_subpage[
4275				       CTL_PAGE_DEFAULT],
4276				       &debugconf_page_default,
4277				       sizeof(debugconf_page_default));
4278				memcpy(&lun->mode_pages.debugconf_subpage[
4279				       CTL_PAGE_SAVED],
4280				       &debugconf_page_default,
4281				       sizeof(debugconf_page_default));
4282				page_index->page_data =
4283					(uint8_t *)lun->mode_pages.debugconf_subpage;
4284
4285				current_page = (struct copan_debugconf_subpage *)
4286					(page_index->page_data +
4287					 (page_index->page_len *
4288					  CTL_PAGE_CURRENT));
4289				saved_page = (struct copan_debugconf_subpage *)
4290					(page_index->page_data +
4291					 (page_index->page_len *
4292					  CTL_PAGE_SAVED));
4293				break;
4294			}
4295			default:
4296				panic("invalid subpage value %d",
4297				      page_index->subpage);
4298				break;
4299			}
4300   			break;
4301		}
4302		default:
4303			panic("invalid page value %d",
4304			      page_index->page_code & SMPH_PC_MASK);
4305			break;
4306    	}
4307	}
4308
4309	return (CTL_RETVAL_COMPLETE);
4310}
4311
4312static int
4313ctl_init_log_page_index(struct ctl_lun *lun)
4314{
4315	struct ctl_page_index *page_index;
4316	int i, j, k, prev;
4317
4318	memcpy(&lun->log_pages.index, log_page_index_template,
4319	       sizeof(log_page_index_template));
4320
4321	prev = -1;
4322	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4323
4324		page_index = &lun->log_pages.index[i];
4325		/*
4326		 * If this is a disk-only mode page, there's no point in
4327		 * setting it up.  For some pages, we have to have some
4328		 * basic information about the disk in order to calculate the
4329		 * mode page data.
4330		 */
4331		if ((lun->be_lun->lun_type != T_DIRECT)
4332		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4333			continue;
4334
4335		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4336		    ((lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) == 0 ||
4337		     lun->backend->lun_attr == NULL))
4338			continue;
4339
4340		if (page_index->page_code != prev) {
4341			lun->log_pages.pages_page[j] = page_index->page_code;
4342			prev = page_index->page_code;
4343			j++;
4344		}
4345		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4346		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4347		k++;
4348	}
4349	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4350	lun->log_pages.index[0].page_len = j;
4351	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4352	lun->log_pages.index[1].page_len = k * 2;
4353	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4354	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4355
4356	return (CTL_RETVAL_COMPLETE);
4357}
4358
4359static int
4360hex2bin(const char *str, uint8_t *buf, int buf_size)
4361{
4362	int i;
4363	u_char c;
4364
4365	memset(buf, 0, buf_size);
4366	while (isspace(str[0]))
4367		str++;
4368	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4369		str += 2;
4370	buf_size *= 2;
4371	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4372		c = str[i];
4373		if (isdigit(c))
4374			c -= '0';
4375		else if (isalpha(c))
4376			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4377		else
4378			break;
4379		if (c >= 16)
4380			break;
4381		if ((i & 1) == 0)
4382			buf[i / 2] |= (c << 4);
4383		else
4384			buf[i / 2] |= c;
4385	}
4386	return ((i + 1) / 2);
4387}
4388
4389/*
4390 * LUN allocation.
4391 *
4392 * Requirements:
4393 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4394 *   wants us to allocate the LUN and he can block.
4395 * - ctl_softc is always set
4396 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4397 *
4398 * Returns 0 for success, non-zero (errno) for failure.
4399 */
4400static int
4401ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4402	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4403{
4404	struct ctl_lun *nlun, *lun;
4405	struct ctl_port *port;
4406	struct scsi_vpd_id_descriptor *desc;
4407	struct scsi_vpd_id_t10 *t10id;
4408	const char *eui, *naa, *scsiname, *vendor, *value;
4409	int lun_number, i, lun_malloced;
4410	int devidlen, idlen1, idlen2 = 0, len;
4411
4412	if (be_lun == NULL)
4413		return (EINVAL);
4414
4415	/*
4416	 * We currently only support Direct Access or Processor LUN types.
4417	 */
4418	switch (be_lun->lun_type) {
4419	case T_DIRECT:
4420		break;
4421	case T_PROCESSOR:
4422		break;
4423	case T_SEQUENTIAL:
4424	case T_CHANGER:
4425	default:
4426		be_lun->lun_config_status(be_lun->be_lun,
4427					  CTL_LUN_CONFIG_FAILURE);
4428		break;
4429	}
4430	if (ctl_lun == NULL) {
4431		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4432		lun_malloced = 1;
4433	} else {
4434		lun_malloced = 0;
4435		lun = ctl_lun;
4436	}
4437
4438	memset(lun, 0, sizeof(*lun));
4439	if (lun_malloced)
4440		lun->flags = CTL_LUN_MALLOCED;
4441
4442	/* Generate LUN ID. */
4443	devidlen = max(CTL_DEVID_MIN_LEN,
4444	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4445	idlen1 = sizeof(*t10id) + devidlen;
4446	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4447	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4448	if (scsiname != NULL) {
4449		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4450		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4451	}
4452	eui = ctl_get_opt(&be_lun->options, "eui");
4453	if (eui != NULL) {
4454		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4455	}
4456	naa = ctl_get_opt(&be_lun->options, "naa");
4457	if (naa != NULL) {
4458		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4459	}
4460	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4461	    M_CTL, M_WAITOK | M_ZERO);
4462	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4463	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4464	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4465	desc->length = idlen1;
4466	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4467	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4468	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4469		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4470	} else {
4471		strncpy(t10id->vendor, vendor,
4472		    min(sizeof(t10id->vendor), strlen(vendor)));
4473	}
4474	strncpy((char *)t10id->vendor_spec_id,
4475	    (char *)be_lun->device_id, devidlen);
4476	if (scsiname != NULL) {
4477		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4478		    desc->length);
4479		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4480		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4481		    SVPD_ID_TYPE_SCSI_NAME;
4482		desc->length = idlen2;
4483		strlcpy(desc->identifier, scsiname, idlen2);
4484	}
4485	if (eui != NULL) {
4486		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4487		    desc->length);
4488		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4489		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4490		    SVPD_ID_TYPE_EUI64;
4491		desc->length = hex2bin(eui, desc->identifier, 16);
4492		desc->length = desc->length > 12 ? 16 :
4493		    (desc->length > 8 ? 12 : 8);
4494		len -= 16 - desc->length;
4495	}
4496	if (naa != NULL) {
4497		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4498		    desc->length);
4499		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4500		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4501		    SVPD_ID_TYPE_NAA;
4502		desc->length = hex2bin(naa, desc->identifier, 16);
4503		desc->length = desc->length > 8 ? 16 : 8;
4504		len -= 16 - desc->length;
4505	}
4506	lun->lun_devid->len = len;
4507
4508	mtx_lock(&ctl_softc->ctl_lock);
4509	/*
4510	 * See if the caller requested a particular LUN number.  If so, see
4511	 * if it is available.  Otherwise, allocate the first available LUN.
4512	 */
4513	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4514		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4515		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4516			mtx_unlock(&ctl_softc->ctl_lock);
4517			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4518				printf("ctl: requested LUN ID %d is higher "
4519				       "than CTL_MAX_LUNS - 1 (%d)\n",
4520				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4521			} else {
4522				/*
4523				 * XXX KDM return an error, or just assign
4524				 * another LUN ID in this case??
4525				 */
4526				printf("ctl: requested LUN ID %d is already "
4527				       "in use\n", be_lun->req_lun_id);
4528			}
4529			if (lun->flags & CTL_LUN_MALLOCED)
4530				free(lun, M_CTL);
4531			be_lun->lun_config_status(be_lun->be_lun,
4532						  CTL_LUN_CONFIG_FAILURE);
4533			return (ENOSPC);
4534		}
4535		lun_number = be_lun->req_lun_id;
4536	} else {
4537		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4538		if (lun_number == -1) {
4539			mtx_unlock(&ctl_softc->ctl_lock);
4540			printf("ctl: can't allocate LUN on target %ju, out of "
4541			       "LUNs\n", (uintmax_t)target_id.id);
4542			if (lun->flags & CTL_LUN_MALLOCED)
4543				free(lun, M_CTL);
4544			be_lun->lun_config_status(be_lun->be_lun,
4545						  CTL_LUN_CONFIG_FAILURE);
4546			return (ENOSPC);
4547		}
4548	}
4549	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4550
4551	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4552	lun->target = target_id;
4553	lun->lun = lun_number;
4554	lun->be_lun = be_lun;
4555	/*
4556	 * The processor LUN is always enabled.  Disk LUNs come on line
4557	 * disabled, and must be enabled by the backend.
4558	 */
4559	lun->flags |= CTL_LUN_DISABLED;
4560	lun->backend = be_lun->be;
4561	be_lun->ctl_lun = lun;
4562	be_lun->lun_id = lun_number;
4563	atomic_add_int(&be_lun->be->num_luns, 1);
4564	if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4565		lun->flags |= CTL_LUN_OFFLINE;
4566
4567	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4568		lun->flags |= CTL_LUN_STOPPED;
4569
4570	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4571		lun->flags |= CTL_LUN_INOPERABLE;
4572
4573	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4574		lun->flags |= CTL_LUN_PRIMARY_SC;
4575
4576	value = ctl_get_opt(&be_lun->options, "readonly");
4577	if (value != NULL && strcmp(value, "on") == 0)
4578		lun->flags |= CTL_LUN_READONLY;
4579
4580	lun->ctl_softc = ctl_softc;
4581	TAILQ_INIT(&lun->ooa_queue);
4582	TAILQ_INIT(&lun->blocked_queue);
4583	STAILQ_INIT(&lun->error_list);
4584	ctl_tpc_lun_init(lun);
4585
4586	/*
4587	 * Initialize the mode and log page index.
4588	 */
4589	ctl_init_page_index(lun);
4590	ctl_init_log_page_index(lun);
4591
4592	/*
4593	 * Set the poweron UA for all initiators on this LUN only.
4594	 */
4595	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4596		lun->pending_ua[i] = CTL_UA_POWERON;
4597
4598	/*
4599	 * Now, before we insert this lun on the lun list, set the lun
4600	 * inventory changed UA for all other luns.
4601	 */
4602	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4603		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4604			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4605		}
4606	}
4607
4608	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4609
4610	ctl_softc->ctl_luns[lun_number] = lun;
4611
4612	ctl_softc->num_luns++;
4613
4614	/* Setup statistics gathering */
4615	lun->stats.device_type = be_lun->lun_type;
4616	lun->stats.lun_number = lun_number;
4617	if (lun->stats.device_type == T_DIRECT)
4618		lun->stats.blocksize = be_lun->blocksize;
4619	else
4620		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4621	for (i = 0;i < CTL_MAX_PORTS;i++)
4622		lun->stats.ports[i].targ_port = i;
4623
4624	mtx_unlock(&ctl_softc->ctl_lock);
4625
4626	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4627
4628	/*
4629	 * Run through each registered FETD and bring it online if it isn't
4630	 * already.  Enable the target ID if it hasn't been enabled, and
4631	 * enable this particular LUN.
4632	 */
4633	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4634		int retval;
4635
4636		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4637		if (retval != 0) {
4638			printf("ctl_alloc_lun: FETD %s port %d returned error "
4639			       "%d for lun_enable on target %ju lun %d\n",
4640			       port->port_name, port->targ_port, retval,
4641			       (uintmax_t)target_id.id, lun_number);
4642		} else
4643			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4644	}
4645	return (0);
4646}
4647
4648/*
4649 * Delete a LUN.
4650 * Assumptions:
4651 * - LUN has already been marked invalid and any pending I/O has been taken
4652 *   care of.
4653 */
4654static int
4655ctl_free_lun(struct ctl_lun *lun)
4656{
4657	struct ctl_softc *softc;
4658#if 0
4659	struct ctl_port *port;
4660#endif
4661	struct ctl_lun *nlun;
4662	int i;
4663
4664	softc = lun->ctl_softc;
4665
4666	mtx_assert(&softc->ctl_lock, MA_OWNED);
4667
4668	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4669
4670	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4671
4672	softc->ctl_luns[lun->lun] = NULL;
4673
4674	if (!TAILQ_EMPTY(&lun->ooa_queue))
4675		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4676
4677	softc->num_luns--;
4678
4679	/*
4680	 * XXX KDM this scheme only works for a single target/multiple LUN
4681	 * setup.  It needs to be revamped for a multiple target scheme.
4682	 *
4683	 * XXX KDM this results in port->lun_disable() getting called twice,
4684	 * once when ctl_disable_lun() is called, and a second time here.
4685	 * We really need to re-think the LUN disable semantics.  There
4686	 * should probably be several steps/levels to LUN removal:
4687	 *  - disable
4688	 *  - invalidate
4689	 *  - free
4690 	 *
4691	 * Right now we only have a disable method when communicating to
4692	 * the front end ports, at least for individual LUNs.
4693	 */
4694#if 0
4695	STAILQ_FOREACH(port, &softc->port_list, links) {
4696		int retval;
4697
4698		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4699					 lun->lun);
4700		if (retval != 0) {
4701			printf("ctl_free_lun: FETD %s port %d returned error "
4702			       "%d for lun_disable on target %ju lun %jd\n",
4703			       port->port_name, port->targ_port, retval,
4704			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4705		}
4706
4707		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4708			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4709
4710			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4711			if (retval != 0) {
4712				printf("ctl_free_lun: FETD %s port %d "
4713				       "returned error %d for targ_disable on "
4714				       "target %ju\n", port->port_name,
4715				       port->targ_port, retval,
4716				       (uintmax_t)lun->target.id);
4717			} else
4718				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4719
4720			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4721				continue;
4722
4723#if 0
4724			port->port_offline(port->onoff_arg);
4725			port->status &= ~CTL_PORT_STATUS_ONLINE;
4726#endif
4727		}
4728	}
4729#endif
4730
4731	/*
4732	 * Tell the backend to free resources, if this LUN has a backend.
4733	 */
4734	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4735	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4736
4737	ctl_tpc_lun_shutdown(lun);
4738	mtx_destroy(&lun->lun_lock);
4739	free(lun->lun_devid, M_CTL);
4740	for (i = 0; i < 2 * CTL_MAX_PORTS; i++) {
4741		if (lun->pr_keys[i] != NULL)
4742			free(lun->pr_keys[i], M_CTL);
4743	}
4744	free(lun->write_buffer, M_CTL);
4745	if (lun->flags & CTL_LUN_MALLOCED)
4746		free(lun, M_CTL);
4747
4748	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4749		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4750			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4751		}
4752	}
4753
4754	return (0);
4755}
4756
4757static void
4758ctl_create_lun(struct ctl_be_lun *be_lun)
4759{
4760	struct ctl_softc *ctl_softc;
4761
4762	ctl_softc = control_softc;
4763
4764	/*
4765	 * ctl_alloc_lun() should handle all potential failure cases.
4766	 */
4767	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4768}
4769
4770int
4771ctl_add_lun(struct ctl_be_lun *be_lun)
4772{
4773	struct ctl_softc *ctl_softc = control_softc;
4774
4775	mtx_lock(&ctl_softc->ctl_lock);
4776	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4777	mtx_unlock(&ctl_softc->ctl_lock);
4778	wakeup(&ctl_softc->pending_lun_queue);
4779
4780	return (0);
4781}
4782
4783int
4784ctl_enable_lun(struct ctl_be_lun *be_lun)
4785{
4786	struct ctl_softc *ctl_softc;
4787	struct ctl_port *port, *nport;
4788	struct ctl_lun *lun;
4789	int retval;
4790
4791	ctl_softc = control_softc;
4792
4793	lun = (struct ctl_lun *)be_lun->ctl_lun;
4794
4795	mtx_lock(&ctl_softc->ctl_lock);
4796	mtx_lock(&lun->lun_lock);
4797	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4798		/*
4799		 * eh?  Why did we get called if the LUN is already
4800		 * enabled?
4801		 */
4802		mtx_unlock(&lun->lun_lock);
4803		mtx_unlock(&ctl_softc->ctl_lock);
4804		return (0);
4805	}
4806	lun->flags &= ~CTL_LUN_DISABLED;
4807	mtx_unlock(&lun->lun_lock);
4808
4809	for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4810		nport = STAILQ_NEXT(port, links);
4811
4812		/*
4813		 * Drop the lock while we call the FETD's enable routine.
4814		 * This can lead to a callback into CTL (at least in the
4815		 * case of the internal initiator frontend.
4816		 */
4817		mtx_unlock(&ctl_softc->ctl_lock);
4818		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4819		mtx_lock(&ctl_softc->ctl_lock);
4820		if (retval != 0) {
4821			printf("%s: FETD %s port %d returned error "
4822			       "%d for lun_enable on target %ju lun %jd\n",
4823			       __func__, port->port_name, port->targ_port, retval,
4824			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4825		}
4826#if 0
4827		 else {
4828            /* NOTE:  TODO:  why does lun enable affect port status? */
4829			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4830		}
4831#endif
4832	}
4833
4834	mtx_unlock(&ctl_softc->ctl_lock);
4835
4836	return (0);
4837}
4838
4839int
4840ctl_disable_lun(struct ctl_be_lun *be_lun)
4841{
4842	struct ctl_softc *ctl_softc;
4843	struct ctl_port *port;
4844	struct ctl_lun *lun;
4845	int retval;
4846
4847	ctl_softc = control_softc;
4848
4849	lun = (struct ctl_lun *)be_lun->ctl_lun;
4850
4851	mtx_lock(&ctl_softc->ctl_lock);
4852	mtx_lock(&lun->lun_lock);
4853	if (lun->flags & CTL_LUN_DISABLED) {
4854		mtx_unlock(&lun->lun_lock);
4855		mtx_unlock(&ctl_softc->ctl_lock);
4856		return (0);
4857	}
4858	lun->flags |= CTL_LUN_DISABLED;
4859	mtx_unlock(&lun->lun_lock);
4860
4861	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4862		mtx_unlock(&ctl_softc->ctl_lock);
4863		/*
4864		 * Drop the lock before we call the frontend's disable
4865		 * routine, to avoid lock order reversals.
4866		 *
4867		 * XXX KDM what happens if the frontend list changes while
4868		 * we're traversing it?  It's unlikely, but should be handled.
4869		 */
4870		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4871					 lun->lun);
4872		mtx_lock(&ctl_softc->ctl_lock);
4873		if (retval != 0) {
4874			printf("ctl_alloc_lun: FETD %s port %d returned error "
4875			       "%d for lun_disable on target %ju lun %jd\n",
4876			       port->port_name, port->targ_port, retval,
4877			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4878		}
4879	}
4880
4881	mtx_unlock(&ctl_softc->ctl_lock);
4882
4883	return (0);
4884}
4885
4886int
4887ctl_start_lun(struct ctl_be_lun *be_lun)
4888{
4889	struct ctl_softc *ctl_softc;
4890	struct ctl_lun *lun;
4891
4892	ctl_softc = control_softc;
4893
4894	lun = (struct ctl_lun *)be_lun->ctl_lun;
4895
4896	mtx_lock(&lun->lun_lock);
4897	lun->flags &= ~CTL_LUN_STOPPED;
4898	mtx_unlock(&lun->lun_lock);
4899
4900	return (0);
4901}
4902
4903int
4904ctl_stop_lun(struct ctl_be_lun *be_lun)
4905{
4906	struct ctl_softc *ctl_softc;
4907	struct ctl_lun *lun;
4908
4909	ctl_softc = control_softc;
4910
4911	lun = (struct ctl_lun *)be_lun->ctl_lun;
4912
4913	mtx_lock(&lun->lun_lock);
4914	lun->flags |= CTL_LUN_STOPPED;
4915	mtx_unlock(&lun->lun_lock);
4916
4917	return (0);
4918}
4919
4920int
4921ctl_lun_offline(struct ctl_be_lun *be_lun)
4922{
4923	struct ctl_softc *ctl_softc;
4924	struct ctl_lun *lun;
4925
4926	ctl_softc = control_softc;
4927
4928	lun = (struct ctl_lun *)be_lun->ctl_lun;
4929
4930	mtx_lock(&lun->lun_lock);
4931	lun->flags |= CTL_LUN_OFFLINE;
4932	mtx_unlock(&lun->lun_lock);
4933
4934	return (0);
4935}
4936
4937int
4938ctl_lun_online(struct ctl_be_lun *be_lun)
4939{
4940	struct ctl_softc *ctl_softc;
4941	struct ctl_lun *lun;
4942
4943	ctl_softc = control_softc;
4944
4945	lun = (struct ctl_lun *)be_lun->ctl_lun;
4946
4947	mtx_lock(&lun->lun_lock);
4948	lun->flags &= ~CTL_LUN_OFFLINE;
4949	mtx_unlock(&lun->lun_lock);
4950
4951	return (0);
4952}
4953
4954int
4955ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4956{
4957	struct ctl_softc *ctl_softc;
4958	struct ctl_lun *lun;
4959
4960	ctl_softc = control_softc;
4961
4962	lun = (struct ctl_lun *)be_lun->ctl_lun;
4963
4964	mtx_lock(&lun->lun_lock);
4965
4966	/*
4967	 * The LUN needs to be disabled before it can be marked invalid.
4968	 */
4969	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4970		mtx_unlock(&lun->lun_lock);
4971		return (-1);
4972	}
4973	/*
4974	 * Mark the LUN invalid.
4975	 */
4976	lun->flags |= CTL_LUN_INVALID;
4977
4978	/*
4979	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4980	 * If we have something in the OOA queue, we'll free it when the
4981	 * last I/O completes.
4982	 */
4983	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4984		mtx_unlock(&lun->lun_lock);
4985		mtx_lock(&ctl_softc->ctl_lock);
4986		ctl_free_lun(lun);
4987		mtx_unlock(&ctl_softc->ctl_lock);
4988	} else
4989		mtx_unlock(&lun->lun_lock);
4990
4991	return (0);
4992}
4993
4994int
4995ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4996{
4997	struct ctl_softc *ctl_softc;
4998	struct ctl_lun *lun;
4999
5000	ctl_softc = control_softc;
5001	lun = (struct ctl_lun *)be_lun->ctl_lun;
5002
5003	mtx_lock(&lun->lun_lock);
5004	lun->flags |= CTL_LUN_INOPERABLE;
5005	mtx_unlock(&lun->lun_lock);
5006
5007	return (0);
5008}
5009
5010int
5011ctl_lun_operable(struct ctl_be_lun *be_lun)
5012{
5013	struct ctl_softc *ctl_softc;
5014	struct ctl_lun *lun;
5015
5016	ctl_softc = control_softc;
5017	lun = (struct ctl_lun *)be_lun->ctl_lun;
5018
5019	mtx_lock(&lun->lun_lock);
5020	lun->flags &= ~CTL_LUN_INOPERABLE;
5021	mtx_unlock(&lun->lun_lock);
5022
5023	return (0);
5024}
5025
5026void
5027ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5028{
5029	struct ctl_lun *lun;
5030	struct ctl_softc *softc;
5031	int i;
5032
5033	softc = control_softc;
5034
5035	lun = (struct ctl_lun *)be_lun->ctl_lun;
5036
5037	mtx_lock(&lun->lun_lock);
5038
5039	for (i = 0; i < CTL_MAX_INITIATORS; i++)
5040		lun->pending_ua[i] |= CTL_UA_CAPACITY_CHANGED;
5041
5042	mtx_unlock(&lun->lun_lock);
5043}
5044
5045/*
5046 * Backend "memory move is complete" callback for requests that never
5047 * make it down to say RAIDCore's configuration code.
5048 */
5049int
5050ctl_config_move_done(union ctl_io *io)
5051{
5052	int retval;
5053
5054	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5055	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5056	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5057
5058	if ((io->io_hdr.port_status != 0) &&
5059	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5060	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5061		/*
5062		 * For hardware error sense keys, the sense key
5063		 * specific value is defined to be a retry count,
5064		 * but we use it to pass back an internal FETD
5065		 * error code.  XXX KDM  Hopefully the FETD is only
5066		 * using 16 bits for an error code, since that's
5067		 * all the space we have in the sks field.
5068		 */
5069		ctl_set_internal_failure(&io->scsiio,
5070					 /*sks_valid*/ 1,
5071					 /*retry_count*/
5072					 io->io_hdr.port_status);
5073	}
5074
5075	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5076	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5077	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5078	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5079		/*
5080		 * XXX KDM just assuming a single pointer here, and not a
5081		 * S/G list.  If we start using S/G lists for config data,
5082		 * we'll need to know how to clean them up here as well.
5083		 */
5084		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5085			free(io->scsiio.kern_data_ptr, M_CTL);
5086		ctl_done(io);
5087		retval = CTL_RETVAL_COMPLETE;
5088	} else {
5089		/*
5090		 * XXX KDM now we need to continue data movement.  Some
5091		 * options:
5092		 * - call ctl_scsiio() again?  We don't do this for data
5093		 *   writes, because for those at least we know ahead of
5094		 *   time where the write will go and how long it is.  For
5095		 *   config writes, though, that information is largely
5096		 *   contained within the write itself, thus we need to
5097		 *   parse out the data again.
5098		 *
5099		 * - Call some other function once the data is in?
5100		 */
5101		if (ctl_debug & CTL_DEBUG_CDB_DATA)
5102			ctl_data_print(io);
5103
5104		/*
5105		 * XXX KDM call ctl_scsiio() again for now, and check flag
5106		 * bits to see whether we're allocated or not.
5107		 */
5108		retval = ctl_scsiio(&io->scsiio);
5109	}
5110	return (retval);
5111}
5112
5113/*
5114 * This gets called by a backend driver when it is done with a
5115 * data_submit method.
5116 */
5117void
5118ctl_data_submit_done(union ctl_io *io)
5119{
5120	/*
5121	 * If the IO_CONT flag is set, we need to call the supplied
5122	 * function to continue processing the I/O, instead of completing
5123	 * the I/O just yet.
5124	 *
5125	 * If there is an error, though, we don't want to keep processing.
5126	 * Instead, just send status back to the initiator.
5127	 */
5128	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5129	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5130	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5131	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5132		io->scsiio.io_cont(io);
5133		return;
5134	}
5135	ctl_done(io);
5136}
5137
5138/*
5139 * This gets called by a backend driver when it is done with a
5140 * configuration write.
5141 */
5142void
5143ctl_config_write_done(union ctl_io *io)
5144{
5145	uint8_t *buf;
5146
5147	/*
5148	 * If the IO_CONT flag is set, we need to call the supplied
5149	 * function to continue processing the I/O, instead of completing
5150	 * the I/O just yet.
5151	 *
5152	 * If there is an error, though, we don't want to keep processing.
5153	 * Instead, just send status back to the initiator.
5154	 */
5155	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5156	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5157	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5158	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5159		io->scsiio.io_cont(io);
5160		return;
5161	}
5162	/*
5163	 * Since a configuration write can be done for commands that actually
5164	 * have data allocated, like write buffer, and commands that have
5165	 * no data, like start/stop unit, we need to check here.
5166	 */
5167	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5168		buf = io->scsiio.kern_data_ptr;
5169	else
5170		buf = NULL;
5171	ctl_done(io);
5172	if (buf)
5173		free(buf, M_CTL);
5174}
5175
5176/*
5177 * SCSI release command.
5178 */
5179int
5180ctl_scsi_release(struct ctl_scsiio *ctsio)
5181{
5182	int length, longid, thirdparty_id, resv_id;
5183	struct ctl_softc *ctl_softc;
5184	struct ctl_lun *lun;
5185	uint32_t residx;
5186
5187	length = 0;
5188	resv_id = 0;
5189
5190	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5191
5192	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5193	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5194	ctl_softc = control_softc;
5195
5196	switch (ctsio->cdb[0]) {
5197	case RELEASE_10: {
5198		struct scsi_release_10 *cdb;
5199
5200		cdb = (struct scsi_release_10 *)ctsio->cdb;
5201
5202		if (cdb->byte2 & SR10_LONGID)
5203			longid = 1;
5204		else
5205			thirdparty_id = cdb->thirdparty_id;
5206
5207		resv_id = cdb->resv_id;
5208		length = scsi_2btoul(cdb->length);
5209		break;
5210	}
5211	}
5212
5213
5214	/*
5215	 * XXX KDM right now, we only support LUN reservation.  We don't
5216	 * support 3rd party reservations, or extent reservations, which
5217	 * might actually need the parameter list.  If we've gotten this
5218	 * far, we've got a LUN reservation.  Anything else got kicked out
5219	 * above.  So, according to SPC, ignore the length.
5220	 */
5221	length = 0;
5222
5223	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5224	 && (length > 0)) {
5225		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5226		ctsio->kern_data_len = length;
5227		ctsio->kern_total_len = length;
5228		ctsio->kern_data_resid = 0;
5229		ctsio->kern_rel_offset = 0;
5230		ctsio->kern_sg_entries = 0;
5231		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5232		ctsio->be_move_done = ctl_config_move_done;
5233		ctl_datamove((union ctl_io *)ctsio);
5234
5235		return (CTL_RETVAL_COMPLETE);
5236	}
5237
5238	if (length > 0)
5239		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5240
5241	mtx_lock(&lun->lun_lock);
5242
5243	/*
5244	 * According to SPC, it is not an error for an intiator to attempt
5245	 * to release a reservation on a LUN that isn't reserved, or that
5246	 * is reserved by another initiator.  The reservation can only be
5247	 * released, though, by the initiator who made it or by one of
5248	 * several reset type events.
5249	 */
5250	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5251			lun->flags &= ~CTL_LUN_RESERVED;
5252
5253	mtx_unlock(&lun->lun_lock);
5254
5255	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5256		free(ctsio->kern_data_ptr, M_CTL);
5257		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5258	}
5259
5260	ctl_set_success(ctsio);
5261	ctl_done((union ctl_io *)ctsio);
5262	return (CTL_RETVAL_COMPLETE);
5263}
5264
5265int
5266ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5267{
5268	int extent, thirdparty, longid;
5269	int resv_id, length;
5270	uint64_t thirdparty_id;
5271	struct ctl_softc *ctl_softc;
5272	struct ctl_lun *lun;
5273	uint32_t residx;
5274
5275	extent = 0;
5276	thirdparty = 0;
5277	longid = 0;
5278	resv_id = 0;
5279	length = 0;
5280	thirdparty_id = 0;
5281
5282	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5283
5284	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5285	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5286	ctl_softc = control_softc;
5287
5288	switch (ctsio->cdb[0]) {
5289	case RESERVE_10: {
5290		struct scsi_reserve_10 *cdb;
5291
5292		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5293
5294		if (cdb->byte2 & SR10_LONGID)
5295			longid = 1;
5296		else
5297			thirdparty_id = cdb->thirdparty_id;
5298
5299		resv_id = cdb->resv_id;
5300		length = scsi_2btoul(cdb->length);
5301		break;
5302	}
5303	}
5304
5305	/*
5306	 * XXX KDM right now, we only support LUN reservation.  We don't
5307	 * support 3rd party reservations, or extent reservations, which
5308	 * might actually need the parameter list.  If we've gotten this
5309	 * far, we've got a LUN reservation.  Anything else got kicked out
5310	 * above.  So, according to SPC, ignore the length.
5311	 */
5312	length = 0;
5313
5314	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5315	 && (length > 0)) {
5316		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5317		ctsio->kern_data_len = length;
5318		ctsio->kern_total_len = length;
5319		ctsio->kern_data_resid = 0;
5320		ctsio->kern_rel_offset = 0;
5321		ctsio->kern_sg_entries = 0;
5322		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5323		ctsio->be_move_done = ctl_config_move_done;
5324		ctl_datamove((union ctl_io *)ctsio);
5325
5326		return (CTL_RETVAL_COMPLETE);
5327	}
5328
5329	if (length > 0)
5330		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5331
5332	mtx_lock(&lun->lun_lock);
5333	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5334		ctl_set_reservation_conflict(ctsio);
5335		goto bailout;
5336	}
5337
5338	lun->flags |= CTL_LUN_RESERVED;
5339	lun->res_idx = residx;
5340
5341	ctl_set_success(ctsio);
5342
5343bailout:
5344	mtx_unlock(&lun->lun_lock);
5345
5346	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5347		free(ctsio->kern_data_ptr, M_CTL);
5348		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5349	}
5350
5351	ctl_done((union ctl_io *)ctsio);
5352	return (CTL_RETVAL_COMPLETE);
5353}
5354
5355int
5356ctl_start_stop(struct ctl_scsiio *ctsio)
5357{
5358	struct scsi_start_stop_unit *cdb;
5359	struct ctl_lun *lun;
5360	struct ctl_softc *ctl_softc;
5361	int retval;
5362
5363	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5364
5365	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5366	ctl_softc = control_softc;
5367	retval = 0;
5368
5369	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5370
5371	/*
5372	 * XXX KDM
5373	 * We don't support the immediate bit on a stop unit.  In order to
5374	 * do that, we would need to code up a way to know that a stop is
5375	 * pending, and hold off any new commands until it completes, one
5376	 * way or another.  Then we could accept or reject those commands
5377	 * depending on its status.  We would almost need to do the reverse
5378	 * of what we do below for an immediate start -- return the copy of
5379	 * the ctl_io to the FETD with status to send to the host (and to
5380	 * free the copy!) and then free the original I/O once the stop
5381	 * actually completes.  That way, the OOA queue mechanism can work
5382	 * to block commands that shouldn't proceed.  Another alternative
5383	 * would be to put the copy in the queue in place of the original,
5384	 * and return the original back to the caller.  That could be
5385	 * slightly safer..
5386	 */
5387	if ((cdb->byte2 & SSS_IMMED)
5388	 && ((cdb->how & SSS_START) == 0)) {
5389		ctl_set_invalid_field(ctsio,
5390				      /*sks_valid*/ 1,
5391				      /*command*/ 1,
5392				      /*field*/ 1,
5393				      /*bit_valid*/ 1,
5394				      /*bit*/ 0);
5395		ctl_done((union ctl_io *)ctsio);
5396		return (CTL_RETVAL_COMPLETE);
5397	}
5398
5399	if ((lun->flags & CTL_LUN_PR_RESERVED)
5400	 && ((cdb->how & SSS_START)==0)) {
5401		uint32_t residx;
5402
5403		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5404		if (ctl_get_prkey(lun, residx) == 0
5405		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5406
5407			ctl_set_reservation_conflict(ctsio);
5408			ctl_done((union ctl_io *)ctsio);
5409			return (CTL_RETVAL_COMPLETE);
5410		}
5411	}
5412
5413	/*
5414	 * If there is no backend on this device, we can't start or stop
5415	 * it.  In theory we shouldn't get any start/stop commands in the
5416	 * first place at this level if the LUN doesn't have a backend.
5417	 * That should get stopped by the command decode code.
5418	 */
5419	if (lun->backend == NULL) {
5420		ctl_set_invalid_opcode(ctsio);
5421		ctl_done((union ctl_io *)ctsio);
5422		return (CTL_RETVAL_COMPLETE);
5423	}
5424
5425	/*
5426	 * XXX KDM Copan-specific offline behavior.
5427	 * Figure out a reasonable way to port this?
5428	 */
5429#ifdef NEEDTOPORT
5430	mtx_lock(&lun->lun_lock);
5431
5432	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5433	 && (lun->flags & CTL_LUN_OFFLINE)) {
5434		/*
5435		 * If the LUN is offline, and the on/offline bit isn't set,
5436		 * reject the start or stop.  Otherwise, let it through.
5437		 */
5438		mtx_unlock(&lun->lun_lock);
5439		ctl_set_lun_not_ready(ctsio);
5440		ctl_done((union ctl_io *)ctsio);
5441	} else {
5442		mtx_unlock(&lun->lun_lock);
5443#endif /* NEEDTOPORT */
5444		/*
5445		 * This could be a start or a stop when we're online,
5446		 * or a stop/offline or start/online.  A start or stop when
5447		 * we're offline is covered in the case above.
5448		 */
5449		/*
5450		 * In the non-immediate case, we send the request to
5451		 * the backend and return status to the user when
5452		 * it is done.
5453		 *
5454		 * In the immediate case, we allocate a new ctl_io
5455		 * to hold a copy of the request, and send that to
5456		 * the backend.  We then set good status on the
5457		 * user's request and return it immediately.
5458		 */
5459		if (cdb->byte2 & SSS_IMMED) {
5460			union ctl_io *new_io;
5461
5462			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5463			ctl_copy_io((union ctl_io *)ctsio, new_io);
5464			retval = lun->backend->config_write(new_io);
5465			ctl_set_success(ctsio);
5466			ctl_done((union ctl_io *)ctsio);
5467		} else {
5468			retval = lun->backend->config_write(
5469				(union ctl_io *)ctsio);
5470		}
5471#ifdef NEEDTOPORT
5472	}
5473#endif
5474	return (retval);
5475}
5476
5477/*
5478 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5479 * we don't really do anything with the LBA and length fields if the user
5480 * passes them in.  Instead we'll just flush out the cache for the entire
5481 * LUN.
5482 */
5483int
5484ctl_sync_cache(struct ctl_scsiio *ctsio)
5485{
5486	struct ctl_lun *lun;
5487	struct ctl_softc *ctl_softc;
5488	uint64_t starting_lba;
5489	uint32_t block_count;
5490	int retval;
5491
5492	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5493
5494	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5495	ctl_softc = control_softc;
5496	retval = 0;
5497
5498	switch (ctsio->cdb[0]) {
5499	case SYNCHRONIZE_CACHE: {
5500		struct scsi_sync_cache *cdb;
5501		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5502
5503		starting_lba = scsi_4btoul(cdb->begin_lba);
5504		block_count = scsi_2btoul(cdb->lb_count);
5505		break;
5506	}
5507	case SYNCHRONIZE_CACHE_16: {
5508		struct scsi_sync_cache_16 *cdb;
5509		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5510
5511		starting_lba = scsi_8btou64(cdb->begin_lba);
5512		block_count = scsi_4btoul(cdb->lb_count);
5513		break;
5514	}
5515	default:
5516		ctl_set_invalid_opcode(ctsio);
5517		ctl_done((union ctl_io *)ctsio);
5518		goto bailout;
5519		break; /* NOTREACHED */
5520	}
5521
5522	/*
5523	 * We check the LBA and length, but don't do anything with them.
5524	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5525	 * get flushed.  This check will just help satisfy anyone who wants
5526	 * to see an error for an out of range LBA.
5527	 */
5528	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5529		ctl_set_lba_out_of_range(ctsio);
5530		ctl_done((union ctl_io *)ctsio);
5531		goto bailout;
5532	}
5533
5534	/*
5535	 * If this LUN has no backend, we can't flush the cache anyway.
5536	 */
5537	if (lun->backend == NULL) {
5538		ctl_set_invalid_opcode(ctsio);
5539		ctl_done((union ctl_io *)ctsio);
5540		goto bailout;
5541	}
5542
5543	/*
5544	 * Check to see whether we're configured to send the SYNCHRONIZE
5545	 * CACHE command directly to the back end.
5546	 */
5547	mtx_lock(&lun->lun_lock);
5548	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5549	 && (++(lun->sync_count) >= lun->sync_interval)) {
5550		lun->sync_count = 0;
5551		mtx_unlock(&lun->lun_lock);
5552		retval = lun->backend->config_write((union ctl_io *)ctsio);
5553	} else {
5554		mtx_unlock(&lun->lun_lock);
5555		ctl_set_success(ctsio);
5556		ctl_done((union ctl_io *)ctsio);
5557	}
5558
5559bailout:
5560
5561	return (retval);
5562}
5563
5564int
5565ctl_format(struct ctl_scsiio *ctsio)
5566{
5567	struct scsi_format *cdb;
5568	struct ctl_lun *lun;
5569	struct ctl_softc *ctl_softc;
5570	int length, defect_list_len;
5571
5572	CTL_DEBUG_PRINT(("ctl_format\n"));
5573
5574	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5575	ctl_softc = control_softc;
5576
5577	cdb = (struct scsi_format *)ctsio->cdb;
5578
5579	length = 0;
5580	if (cdb->byte2 & SF_FMTDATA) {
5581		if (cdb->byte2 & SF_LONGLIST)
5582			length = sizeof(struct scsi_format_header_long);
5583		else
5584			length = sizeof(struct scsi_format_header_short);
5585	}
5586
5587	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5588	 && (length > 0)) {
5589		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5590		ctsio->kern_data_len = length;
5591		ctsio->kern_total_len = length;
5592		ctsio->kern_data_resid = 0;
5593		ctsio->kern_rel_offset = 0;
5594		ctsio->kern_sg_entries = 0;
5595		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5596		ctsio->be_move_done = ctl_config_move_done;
5597		ctl_datamove((union ctl_io *)ctsio);
5598
5599		return (CTL_RETVAL_COMPLETE);
5600	}
5601
5602	defect_list_len = 0;
5603
5604	if (cdb->byte2 & SF_FMTDATA) {
5605		if (cdb->byte2 & SF_LONGLIST) {
5606			struct scsi_format_header_long *header;
5607
5608			header = (struct scsi_format_header_long *)
5609				ctsio->kern_data_ptr;
5610
5611			defect_list_len = scsi_4btoul(header->defect_list_len);
5612			if (defect_list_len != 0) {
5613				ctl_set_invalid_field(ctsio,
5614						      /*sks_valid*/ 1,
5615						      /*command*/ 0,
5616						      /*field*/ 2,
5617						      /*bit_valid*/ 0,
5618						      /*bit*/ 0);
5619				goto bailout;
5620			}
5621		} else {
5622			struct scsi_format_header_short *header;
5623
5624			header = (struct scsi_format_header_short *)
5625				ctsio->kern_data_ptr;
5626
5627			defect_list_len = scsi_2btoul(header->defect_list_len);
5628			if (defect_list_len != 0) {
5629				ctl_set_invalid_field(ctsio,
5630						      /*sks_valid*/ 1,
5631						      /*command*/ 0,
5632						      /*field*/ 2,
5633						      /*bit_valid*/ 0,
5634						      /*bit*/ 0);
5635				goto bailout;
5636			}
5637		}
5638	}
5639
5640	/*
5641	 * The format command will clear out the "Medium format corrupted"
5642	 * status if set by the configuration code.  That status is really
5643	 * just a way to notify the host that we have lost the media, and
5644	 * get them to issue a command that will basically make them think
5645	 * they're blowing away the media.
5646	 */
5647	mtx_lock(&lun->lun_lock);
5648	lun->flags &= ~CTL_LUN_INOPERABLE;
5649	mtx_unlock(&lun->lun_lock);
5650
5651	ctl_set_success(ctsio);
5652bailout:
5653
5654	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5655		free(ctsio->kern_data_ptr, M_CTL);
5656		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5657	}
5658
5659	ctl_done((union ctl_io *)ctsio);
5660	return (CTL_RETVAL_COMPLETE);
5661}
5662
5663int
5664ctl_read_buffer(struct ctl_scsiio *ctsio)
5665{
5666	struct scsi_read_buffer *cdb;
5667	struct ctl_lun *lun;
5668	int buffer_offset, len;
5669	static uint8_t descr[4];
5670	static uint8_t echo_descr[4] = { 0 };
5671
5672	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5673
5674	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5675	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5676
5677	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5678	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5679	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5680		ctl_set_invalid_field(ctsio,
5681				      /*sks_valid*/ 1,
5682				      /*command*/ 1,
5683				      /*field*/ 1,
5684				      /*bit_valid*/ 1,
5685				      /*bit*/ 4);
5686		ctl_done((union ctl_io *)ctsio);
5687		return (CTL_RETVAL_COMPLETE);
5688	}
5689
5690	len = scsi_3btoul(cdb->length);
5691	buffer_offset = scsi_3btoul(cdb->offset);
5692
5693	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5694		ctl_set_invalid_field(ctsio,
5695				      /*sks_valid*/ 1,
5696				      /*command*/ 1,
5697				      /*field*/ 6,
5698				      /*bit_valid*/ 0,
5699				      /*bit*/ 0);
5700		ctl_done((union ctl_io *)ctsio);
5701		return (CTL_RETVAL_COMPLETE);
5702	}
5703
5704	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5705		descr[0] = 0;
5706		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5707		ctsio->kern_data_ptr = descr;
5708		len = min(len, sizeof(descr));
5709	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5710		ctsio->kern_data_ptr = echo_descr;
5711		len = min(len, sizeof(echo_descr));
5712	} else {
5713		if (lun->write_buffer == NULL) {
5714			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5715			    M_CTL, M_WAITOK);
5716		}
5717		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5718	}
5719	ctsio->kern_data_len = len;
5720	ctsio->kern_total_len = len;
5721	ctsio->kern_data_resid = 0;
5722	ctsio->kern_rel_offset = 0;
5723	ctsio->kern_sg_entries = 0;
5724	ctl_set_success(ctsio);
5725	ctsio->be_move_done = ctl_config_move_done;
5726	ctl_datamove((union ctl_io *)ctsio);
5727	return (CTL_RETVAL_COMPLETE);
5728}
5729
5730int
5731ctl_write_buffer(struct ctl_scsiio *ctsio)
5732{
5733	struct scsi_write_buffer *cdb;
5734	struct ctl_lun *lun;
5735	int buffer_offset, len;
5736
5737	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5738
5739	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5740	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5741
5742	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5743		ctl_set_invalid_field(ctsio,
5744				      /*sks_valid*/ 1,
5745				      /*command*/ 1,
5746				      /*field*/ 1,
5747				      /*bit_valid*/ 1,
5748				      /*bit*/ 4);
5749		ctl_done((union ctl_io *)ctsio);
5750		return (CTL_RETVAL_COMPLETE);
5751	}
5752
5753	len = scsi_3btoul(cdb->length);
5754	buffer_offset = scsi_3btoul(cdb->offset);
5755
5756	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5757		ctl_set_invalid_field(ctsio,
5758				      /*sks_valid*/ 1,
5759				      /*command*/ 1,
5760				      /*field*/ 6,
5761				      /*bit_valid*/ 0,
5762				      /*bit*/ 0);
5763		ctl_done((union ctl_io *)ctsio);
5764		return (CTL_RETVAL_COMPLETE);
5765	}
5766
5767	/*
5768	 * If we've got a kernel request that hasn't been malloced yet,
5769	 * malloc it and tell the caller the data buffer is here.
5770	 */
5771	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5772		if (lun->write_buffer == NULL) {
5773			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5774			    M_CTL, M_WAITOK);
5775		}
5776		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5777		ctsio->kern_data_len = len;
5778		ctsio->kern_total_len = len;
5779		ctsio->kern_data_resid = 0;
5780		ctsio->kern_rel_offset = 0;
5781		ctsio->kern_sg_entries = 0;
5782		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5783		ctsio->be_move_done = ctl_config_move_done;
5784		ctl_datamove((union ctl_io *)ctsio);
5785
5786		return (CTL_RETVAL_COMPLETE);
5787	}
5788
5789	ctl_set_success(ctsio);
5790	ctl_done((union ctl_io *)ctsio);
5791	return (CTL_RETVAL_COMPLETE);
5792}
5793
5794int
5795ctl_write_same(struct ctl_scsiio *ctsio)
5796{
5797	struct ctl_lun *lun;
5798	struct ctl_lba_len_flags *lbalen;
5799	uint64_t lba;
5800	uint32_t num_blocks;
5801	int len, retval;
5802	uint8_t byte2;
5803
5804	retval = CTL_RETVAL_COMPLETE;
5805
5806	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5807
5808	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5809
5810	switch (ctsio->cdb[0]) {
5811	case WRITE_SAME_10: {
5812		struct scsi_write_same_10 *cdb;
5813
5814		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5815
5816		lba = scsi_4btoul(cdb->addr);
5817		num_blocks = scsi_2btoul(cdb->length);
5818		byte2 = cdb->byte2;
5819		break;
5820	}
5821	case WRITE_SAME_16: {
5822		struct scsi_write_same_16 *cdb;
5823
5824		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5825
5826		lba = scsi_8btou64(cdb->addr);
5827		num_blocks = scsi_4btoul(cdb->length);
5828		byte2 = cdb->byte2;
5829		break;
5830	}
5831	default:
5832		/*
5833		 * We got a command we don't support.  This shouldn't
5834		 * happen, commands should be filtered out above us.
5835		 */
5836		ctl_set_invalid_opcode(ctsio);
5837		ctl_done((union ctl_io *)ctsio);
5838
5839		return (CTL_RETVAL_COMPLETE);
5840		break; /* NOTREACHED */
5841	}
5842
5843	/* NDOB and ANCHOR flags can be used only together with UNMAP */
5844	if ((byte2 & SWS_UNMAP) == 0 &&
5845	    (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5846		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5847		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5848		ctl_done((union ctl_io *)ctsio);
5849		return (CTL_RETVAL_COMPLETE);
5850	}
5851
5852	/*
5853	 * The first check is to make sure we're in bounds, the second
5854	 * check is to catch wrap-around problems.  If the lba + num blocks
5855	 * is less than the lba, then we've wrapped around and the block
5856	 * range is invalid anyway.
5857	 */
5858	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5859	 || ((lba + num_blocks) < lba)) {
5860		ctl_set_lba_out_of_range(ctsio);
5861		ctl_done((union ctl_io *)ctsio);
5862		return (CTL_RETVAL_COMPLETE);
5863	}
5864
5865	/* Zero number of blocks means "to the last logical block" */
5866	if (num_blocks == 0) {
5867		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5868			ctl_set_invalid_field(ctsio,
5869					      /*sks_valid*/ 0,
5870					      /*command*/ 1,
5871					      /*field*/ 0,
5872					      /*bit_valid*/ 0,
5873					      /*bit*/ 0);
5874			ctl_done((union ctl_io *)ctsio);
5875			return (CTL_RETVAL_COMPLETE);
5876		}
5877		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5878	}
5879
5880	len = lun->be_lun->blocksize;
5881
5882	/*
5883	 * If we've got a kernel request that hasn't been malloced yet,
5884	 * malloc it and tell the caller the data buffer is here.
5885	 */
5886	if ((byte2 & SWS_NDOB) == 0 &&
5887	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5888		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5889		ctsio->kern_data_len = len;
5890		ctsio->kern_total_len = len;
5891		ctsio->kern_data_resid = 0;
5892		ctsio->kern_rel_offset = 0;
5893		ctsio->kern_sg_entries = 0;
5894		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5895		ctsio->be_move_done = ctl_config_move_done;
5896		ctl_datamove((union ctl_io *)ctsio);
5897
5898		return (CTL_RETVAL_COMPLETE);
5899	}
5900
5901	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5902	lbalen->lba = lba;
5903	lbalen->len = num_blocks;
5904	lbalen->flags = byte2;
5905	retval = lun->backend->config_write((union ctl_io *)ctsio);
5906
5907	return (retval);
5908}
5909
5910int
5911ctl_unmap(struct ctl_scsiio *ctsio)
5912{
5913	struct ctl_lun *lun;
5914	struct scsi_unmap *cdb;
5915	struct ctl_ptr_len_flags *ptrlen;
5916	struct scsi_unmap_header *hdr;
5917	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5918	uint64_t lba;
5919	uint32_t num_blocks;
5920	int len, retval;
5921	uint8_t byte2;
5922
5923	retval = CTL_RETVAL_COMPLETE;
5924
5925	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5926
5927	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5928	cdb = (struct scsi_unmap *)ctsio->cdb;
5929
5930	len = scsi_2btoul(cdb->length);
5931	byte2 = cdb->byte2;
5932
5933	/*
5934	 * If we've got a kernel request that hasn't been malloced yet,
5935	 * malloc it and tell the caller the data buffer is here.
5936	 */
5937	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5938		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5939		ctsio->kern_data_len = len;
5940		ctsio->kern_total_len = len;
5941		ctsio->kern_data_resid = 0;
5942		ctsio->kern_rel_offset = 0;
5943		ctsio->kern_sg_entries = 0;
5944		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5945		ctsio->be_move_done = ctl_config_move_done;
5946		ctl_datamove((union ctl_io *)ctsio);
5947
5948		return (CTL_RETVAL_COMPLETE);
5949	}
5950
5951	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5952	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5953	if (len < sizeof (*hdr) ||
5954	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5955	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5956	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5957		ctl_set_invalid_field(ctsio,
5958				      /*sks_valid*/ 0,
5959				      /*command*/ 0,
5960				      /*field*/ 0,
5961				      /*bit_valid*/ 0,
5962				      /*bit*/ 0);
5963		goto done;
5964	}
5965	len = scsi_2btoul(hdr->desc_length);
5966	buf = (struct scsi_unmap_desc *)(hdr + 1);
5967	end = buf + len / sizeof(*buf);
5968
5969	endnz = buf;
5970	for (range = buf; range < end; range++) {
5971		lba = scsi_8btou64(range->lba);
5972		num_blocks = scsi_4btoul(range->length);
5973		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5974		 || ((lba + num_blocks) < lba)) {
5975			ctl_set_lba_out_of_range(ctsio);
5976			ctl_done((union ctl_io *)ctsio);
5977			return (CTL_RETVAL_COMPLETE);
5978		}
5979		if (num_blocks != 0)
5980			endnz = range + 1;
5981	}
5982
5983	/*
5984	 * Block backend can not handle zero last range.
5985	 * Filter it out and return if there is nothing left.
5986	 */
5987	len = (uint8_t *)endnz - (uint8_t *)buf;
5988	if (len == 0) {
5989		ctl_set_success(ctsio);
5990		goto done;
5991	}
5992
5993	mtx_lock(&lun->lun_lock);
5994	ptrlen = (struct ctl_ptr_len_flags *)
5995	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5996	ptrlen->ptr = (void *)buf;
5997	ptrlen->len = len;
5998	ptrlen->flags = byte2;
5999	ctl_check_blocked(lun);
6000	mtx_unlock(&lun->lun_lock);
6001
6002	retval = lun->backend->config_write((union ctl_io *)ctsio);
6003	return (retval);
6004
6005done:
6006	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
6007		free(ctsio->kern_data_ptr, M_CTL);
6008		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
6009	}
6010	ctl_done((union ctl_io *)ctsio);
6011	return (CTL_RETVAL_COMPLETE);
6012}
6013
6014/*
6015 * Note that this function currently doesn't actually do anything inside
6016 * CTL to enforce things if the DQue bit is turned on.
6017 *
6018 * Also note that this function can't be used in the default case, because
6019 * the DQue bit isn't set in the changeable mask for the control mode page
6020 * anyway.  This is just here as an example for how to implement a page
6021 * handler, and a placeholder in case we want to allow the user to turn
6022 * tagged queueing on and off.
6023 *
6024 * The D_SENSE bit handling is functional, however, and will turn
6025 * descriptor sense on and off for a given LUN.
6026 */
6027int
6028ctl_control_page_handler(struct ctl_scsiio *ctsio,
6029			 struct ctl_page_index *page_index, uint8_t *page_ptr)
6030{
6031	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6032	struct ctl_lun *lun;
6033	struct ctl_softc *softc;
6034	int set_ua;
6035	uint32_t initidx;
6036
6037	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6038	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6039	set_ua = 0;
6040
6041	user_cp = (struct scsi_control_page *)page_ptr;
6042	current_cp = (struct scsi_control_page *)
6043		(page_index->page_data + (page_index->page_len *
6044		CTL_PAGE_CURRENT));
6045	saved_cp = (struct scsi_control_page *)
6046		(page_index->page_data + (page_index->page_len *
6047		CTL_PAGE_SAVED));
6048
6049	softc = control_softc;
6050
6051	mtx_lock(&lun->lun_lock);
6052	if (((current_cp->rlec & SCP_DSENSE) == 0)
6053	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6054		/*
6055		 * Descriptor sense is currently turned off and the user
6056		 * wants to turn it on.
6057		 */
6058		current_cp->rlec |= SCP_DSENSE;
6059		saved_cp->rlec |= SCP_DSENSE;
6060		lun->flags |= CTL_LUN_SENSE_DESC;
6061		set_ua = 1;
6062	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6063		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6064		/*
6065		 * Descriptor sense is currently turned on, and the user
6066		 * wants to turn it off.
6067		 */
6068		current_cp->rlec &= ~SCP_DSENSE;
6069		saved_cp->rlec &= ~SCP_DSENSE;
6070		lun->flags &= ~CTL_LUN_SENSE_DESC;
6071		set_ua = 1;
6072	}
6073	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6074	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6075		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6076		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6077		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6078		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6079		set_ua = 1;
6080	}
6081	if ((current_cp->eca_and_aen & SCP_SWP) !=
6082	    (user_cp->eca_and_aen & SCP_SWP)) {
6083		current_cp->eca_and_aen &= ~SCP_SWP;
6084		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6085		saved_cp->eca_and_aen &= ~SCP_SWP;
6086		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6087		set_ua = 1;
6088	}
6089	if (set_ua != 0) {
6090		int i;
6091		/*
6092		 * Let other initiators know that the mode
6093		 * parameters for this LUN have changed.
6094		 */
6095		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6096			if (i == initidx)
6097				continue;
6098
6099			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6100		}
6101	}
6102	mtx_unlock(&lun->lun_lock);
6103
6104	return (0);
6105}
6106
6107int
6108ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6109		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6110{
6111	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6112	struct ctl_lun *lun;
6113	int set_ua;
6114	uint32_t initidx;
6115
6116	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6117	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6118	set_ua = 0;
6119
6120	user_cp = (struct scsi_caching_page *)page_ptr;
6121	current_cp = (struct scsi_caching_page *)
6122		(page_index->page_data + (page_index->page_len *
6123		CTL_PAGE_CURRENT));
6124	saved_cp = (struct scsi_caching_page *)
6125		(page_index->page_data + (page_index->page_len *
6126		CTL_PAGE_SAVED));
6127
6128	mtx_lock(&lun->lun_lock);
6129	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6130	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6131		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6132		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6133		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6134		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6135		set_ua = 1;
6136	}
6137	if (set_ua != 0) {
6138		int i;
6139		/*
6140		 * Let other initiators know that the mode
6141		 * parameters for this LUN have changed.
6142		 */
6143		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6144			if (i == initidx)
6145				continue;
6146
6147			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6148		}
6149	}
6150	mtx_unlock(&lun->lun_lock);
6151
6152	return (0);
6153}
6154
6155int
6156ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6157				struct ctl_page_index *page_index,
6158				uint8_t *page_ptr)
6159{
6160	uint8_t *c;
6161	int i;
6162
6163	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6164	ctl_time_io_secs =
6165		(c[0] << 8) |
6166		(c[1] << 0) |
6167		0;
6168	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6169	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6170	printf("page data:");
6171	for (i=0; i<8; i++)
6172		printf(" %.2x",page_ptr[i]);
6173	printf("\n");
6174	return (0);
6175}
6176
6177int
6178ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6179			       struct ctl_page_index *page_index,
6180			       int pc)
6181{
6182	struct copan_debugconf_subpage *page;
6183
6184	page = (struct copan_debugconf_subpage *)page_index->page_data +
6185		(page_index->page_len * pc);
6186
6187	switch (pc) {
6188	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6189	case SMS_PAGE_CTRL_DEFAULT >> 6:
6190	case SMS_PAGE_CTRL_SAVED >> 6:
6191		/*
6192		 * We don't update the changable or default bits for this page.
6193		 */
6194		break;
6195	case SMS_PAGE_CTRL_CURRENT >> 6:
6196		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6197		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6198		break;
6199	default:
6200#ifdef NEEDTOPORT
6201		EPRINT(0, "Invalid PC %d!!", pc);
6202#endif /* NEEDTOPORT */
6203		break;
6204	}
6205	return (0);
6206}
6207
6208
6209static int
6210ctl_do_mode_select(union ctl_io *io)
6211{
6212	struct scsi_mode_page_header *page_header;
6213	struct ctl_page_index *page_index;
6214	struct ctl_scsiio *ctsio;
6215	int control_dev, page_len;
6216	int page_len_offset, page_len_size;
6217	union ctl_modepage_info *modepage_info;
6218	struct ctl_lun *lun;
6219	int *len_left, *len_used;
6220	int retval, i;
6221
6222	ctsio = &io->scsiio;
6223	page_index = NULL;
6224	page_len = 0;
6225	retval = CTL_RETVAL_COMPLETE;
6226
6227	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6228
6229	if (lun->be_lun->lun_type != T_DIRECT)
6230		control_dev = 1;
6231	else
6232		control_dev = 0;
6233
6234	modepage_info = (union ctl_modepage_info *)
6235		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6236	len_left = &modepage_info->header.len_left;
6237	len_used = &modepage_info->header.len_used;
6238
6239do_next_page:
6240
6241	page_header = (struct scsi_mode_page_header *)
6242		(ctsio->kern_data_ptr + *len_used);
6243
6244	if (*len_left == 0) {
6245		free(ctsio->kern_data_ptr, M_CTL);
6246		ctl_set_success(ctsio);
6247		ctl_done((union ctl_io *)ctsio);
6248		return (CTL_RETVAL_COMPLETE);
6249	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6250
6251		free(ctsio->kern_data_ptr, M_CTL);
6252		ctl_set_param_len_error(ctsio);
6253		ctl_done((union ctl_io *)ctsio);
6254		return (CTL_RETVAL_COMPLETE);
6255
6256	} else if ((page_header->page_code & SMPH_SPF)
6257		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6258
6259		free(ctsio->kern_data_ptr, M_CTL);
6260		ctl_set_param_len_error(ctsio);
6261		ctl_done((union ctl_io *)ctsio);
6262		return (CTL_RETVAL_COMPLETE);
6263	}
6264
6265
6266	/*
6267	 * XXX KDM should we do something with the block descriptor?
6268	 */
6269	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6270
6271		if ((control_dev != 0)
6272		 && (lun->mode_pages.index[i].page_flags &
6273		     CTL_PAGE_FLAG_DISK_ONLY))
6274			continue;
6275
6276		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6277		    (page_header->page_code & SMPH_PC_MASK))
6278			continue;
6279
6280		/*
6281		 * If neither page has a subpage code, then we've got a
6282		 * match.
6283		 */
6284		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6285		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6286			page_index = &lun->mode_pages.index[i];
6287			page_len = page_header->page_length;
6288			break;
6289		}
6290
6291		/*
6292		 * If both pages have subpages, then the subpage numbers
6293		 * have to match.
6294		 */
6295		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6296		  && (page_header->page_code & SMPH_SPF)) {
6297			struct scsi_mode_page_header_sp *sph;
6298
6299			sph = (struct scsi_mode_page_header_sp *)page_header;
6300
6301			if (lun->mode_pages.index[i].subpage ==
6302			    sph->subpage) {
6303				page_index = &lun->mode_pages.index[i];
6304				page_len = scsi_2btoul(sph->page_length);
6305				break;
6306			}
6307		}
6308	}
6309
6310	/*
6311	 * If we couldn't find the page, or if we don't have a mode select
6312	 * handler for it, send back an error to the user.
6313	 */
6314	if ((page_index == NULL)
6315	 || (page_index->select_handler == NULL)) {
6316		ctl_set_invalid_field(ctsio,
6317				      /*sks_valid*/ 1,
6318				      /*command*/ 0,
6319				      /*field*/ *len_used,
6320				      /*bit_valid*/ 0,
6321				      /*bit*/ 0);
6322		free(ctsio->kern_data_ptr, M_CTL);
6323		ctl_done((union ctl_io *)ctsio);
6324		return (CTL_RETVAL_COMPLETE);
6325	}
6326
6327	if (page_index->page_code & SMPH_SPF) {
6328		page_len_offset = 2;
6329		page_len_size = 2;
6330	} else {
6331		page_len_size = 1;
6332		page_len_offset = 1;
6333	}
6334
6335	/*
6336	 * If the length the initiator gives us isn't the one we specify in
6337	 * the mode page header, or if they didn't specify enough data in
6338	 * the CDB to avoid truncating this page, kick out the request.
6339	 */
6340	if ((page_len != (page_index->page_len - page_len_offset -
6341			  page_len_size))
6342	 || (*len_left < page_index->page_len)) {
6343
6344
6345		ctl_set_invalid_field(ctsio,
6346				      /*sks_valid*/ 1,
6347				      /*command*/ 0,
6348				      /*field*/ *len_used + page_len_offset,
6349				      /*bit_valid*/ 0,
6350				      /*bit*/ 0);
6351		free(ctsio->kern_data_ptr, M_CTL);
6352		ctl_done((union ctl_io *)ctsio);
6353		return (CTL_RETVAL_COMPLETE);
6354	}
6355
6356	/*
6357	 * Run through the mode page, checking to make sure that the bits
6358	 * the user changed are actually legal for him to change.
6359	 */
6360	for (i = 0; i < page_index->page_len; i++) {
6361		uint8_t *user_byte, *change_mask, *current_byte;
6362		int bad_bit;
6363		int j;
6364
6365		user_byte = (uint8_t *)page_header + i;
6366		change_mask = page_index->page_data +
6367			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6368		current_byte = page_index->page_data +
6369			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6370
6371		/*
6372		 * Check to see whether the user set any bits in this byte
6373		 * that he is not allowed to set.
6374		 */
6375		if ((*user_byte & ~(*change_mask)) ==
6376		    (*current_byte & ~(*change_mask)))
6377			continue;
6378
6379		/*
6380		 * Go through bit by bit to determine which one is illegal.
6381		 */
6382		bad_bit = 0;
6383		for (j = 7; j >= 0; j--) {
6384			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6385			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6386				bad_bit = i;
6387				break;
6388			}
6389		}
6390		ctl_set_invalid_field(ctsio,
6391				      /*sks_valid*/ 1,
6392				      /*command*/ 0,
6393				      /*field*/ *len_used + i,
6394				      /*bit_valid*/ 1,
6395				      /*bit*/ bad_bit);
6396		free(ctsio->kern_data_ptr, M_CTL);
6397		ctl_done((union ctl_io *)ctsio);
6398		return (CTL_RETVAL_COMPLETE);
6399	}
6400
6401	/*
6402	 * Decrement these before we call the page handler, since we may
6403	 * end up getting called back one way or another before the handler
6404	 * returns to this context.
6405	 */
6406	*len_left -= page_index->page_len;
6407	*len_used += page_index->page_len;
6408
6409	retval = page_index->select_handler(ctsio, page_index,
6410					    (uint8_t *)page_header);
6411
6412	/*
6413	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6414	 * wait until this queued command completes to finish processing
6415	 * the mode page.  If it returns anything other than
6416	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6417	 * already set the sense information, freed the data pointer, and
6418	 * completed the io for us.
6419	 */
6420	if (retval != CTL_RETVAL_COMPLETE)
6421		goto bailout_no_done;
6422
6423	/*
6424	 * If the initiator sent us more than one page, parse the next one.
6425	 */
6426	if (*len_left > 0)
6427		goto do_next_page;
6428
6429	ctl_set_success(ctsio);
6430	free(ctsio->kern_data_ptr, M_CTL);
6431	ctl_done((union ctl_io *)ctsio);
6432
6433bailout_no_done:
6434
6435	return (CTL_RETVAL_COMPLETE);
6436
6437}
6438
6439int
6440ctl_mode_select(struct ctl_scsiio *ctsio)
6441{
6442	int param_len, pf, sp;
6443	int header_size, bd_len;
6444	int len_left, len_used;
6445	struct ctl_page_index *page_index;
6446	struct ctl_lun *lun;
6447	int control_dev, page_len;
6448	union ctl_modepage_info *modepage_info;
6449	int retval;
6450
6451	pf = 0;
6452	sp = 0;
6453	page_len = 0;
6454	len_used = 0;
6455	len_left = 0;
6456	retval = 0;
6457	bd_len = 0;
6458	page_index = NULL;
6459
6460	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6461
6462	if (lun->be_lun->lun_type != T_DIRECT)
6463		control_dev = 1;
6464	else
6465		control_dev = 0;
6466
6467	switch (ctsio->cdb[0]) {
6468	case MODE_SELECT_6: {
6469		struct scsi_mode_select_6 *cdb;
6470
6471		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6472
6473		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6474		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6475
6476		param_len = cdb->length;
6477		header_size = sizeof(struct scsi_mode_header_6);
6478		break;
6479	}
6480	case MODE_SELECT_10: {
6481		struct scsi_mode_select_10 *cdb;
6482
6483		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6484
6485		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6486		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6487
6488		param_len = scsi_2btoul(cdb->length);
6489		header_size = sizeof(struct scsi_mode_header_10);
6490		break;
6491	}
6492	default:
6493		ctl_set_invalid_opcode(ctsio);
6494		ctl_done((union ctl_io *)ctsio);
6495		return (CTL_RETVAL_COMPLETE);
6496		break; /* NOTREACHED */
6497	}
6498
6499	/*
6500	 * From SPC-3:
6501	 * "A parameter list length of zero indicates that the Data-Out Buffer
6502	 * shall be empty. This condition shall not be considered as an error."
6503	 */
6504	if (param_len == 0) {
6505		ctl_set_success(ctsio);
6506		ctl_done((union ctl_io *)ctsio);
6507		return (CTL_RETVAL_COMPLETE);
6508	}
6509
6510	/*
6511	 * Since we'll hit this the first time through, prior to
6512	 * allocation, we don't need to free a data buffer here.
6513	 */
6514	if (param_len < header_size) {
6515		ctl_set_param_len_error(ctsio);
6516		ctl_done((union ctl_io *)ctsio);
6517		return (CTL_RETVAL_COMPLETE);
6518	}
6519
6520	/*
6521	 * Allocate the data buffer and grab the user's data.  In theory,
6522	 * we shouldn't have to sanity check the parameter list length here
6523	 * because the maximum size is 64K.  We should be able to malloc
6524	 * that much without too many problems.
6525	 */
6526	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6527		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6528		ctsio->kern_data_len = param_len;
6529		ctsio->kern_total_len = param_len;
6530		ctsio->kern_data_resid = 0;
6531		ctsio->kern_rel_offset = 0;
6532		ctsio->kern_sg_entries = 0;
6533		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6534		ctsio->be_move_done = ctl_config_move_done;
6535		ctl_datamove((union ctl_io *)ctsio);
6536
6537		return (CTL_RETVAL_COMPLETE);
6538	}
6539
6540	switch (ctsio->cdb[0]) {
6541	case MODE_SELECT_6: {
6542		struct scsi_mode_header_6 *mh6;
6543
6544		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6545		bd_len = mh6->blk_desc_len;
6546		break;
6547	}
6548	case MODE_SELECT_10: {
6549		struct scsi_mode_header_10 *mh10;
6550
6551		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6552		bd_len = scsi_2btoul(mh10->blk_desc_len);
6553		break;
6554	}
6555	default:
6556		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6557		break;
6558	}
6559
6560	if (param_len < (header_size + bd_len)) {
6561		free(ctsio->kern_data_ptr, M_CTL);
6562		ctl_set_param_len_error(ctsio);
6563		ctl_done((union ctl_io *)ctsio);
6564		return (CTL_RETVAL_COMPLETE);
6565	}
6566
6567	/*
6568	 * Set the IO_CONT flag, so that if this I/O gets passed to
6569	 * ctl_config_write_done(), it'll get passed back to
6570	 * ctl_do_mode_select() for further processing, or completion if
6571	 * we're all done.
6572	 */
6573	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6574	ctsio->io_cont = ctl_do_mode_select;
6575
6576	modepage_info = (union ctl_modepage_info *)
6577		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6578
6579	memset(modepage_info, 0, sizeof(*modepage_info));
6580
6581	len_left = param_len - header_size - bd_len;
6582	len_used = header_size + bd_len;
6583
6584	modepage_info->header.len_left = len_left;
6585	modepage_info->header.len_used = len_used;
6586
6587	return (ctl_do_mode_select((union ctl_io *)ctsio));
6588}
6589
6590int
6591ctl_mode_sense(struct ctl_scsiio *ctsio)
6592{
6593	struct ctl_lun *lun;
6594	int pc, page_code, dbd, llba, subpage;
6595	int alloc_len, page_len, header_len, total_len;
6596	struct scsi_mode_block_descr *block_desc;
6597	struct ctl_page_index *page_index;
6598	int control_dev;
6599
6600	dbd = 0;
6601	llba = 0;
6602	block_desc = NULL;
6603	page_index = NULL;
6604
6605	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6606
6607	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6608
6609	if (lun->be_lun->lun_type != T_DIRECT)
6610		control_dev = 1;
6611	else
6612		control_dev = 0;
6613
6614	switch (ctsio->cdb[0]) {
6615	case MODE_SENSE_6: {
6616		struct scsi_mode_sense_6 *cdb;
6617
6618		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6619
6620		header_len = sizeof(struct scsi_mode_hdr_6);
6621		if (cdb->byte2 & SMS_DBD)
6622			dbd = 1;
6623		else
6624			header_len += sizeof(struct scsi_mode_block_descr);
6625
6626		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6627		page_code = cdb->page & SMS_PAGE_CODE;
6628		subpage = cdb->subpage;
6629		alloc_len = cdb->length;
6630		break;
6631	}
6632	case MODE_SENSE_10: {
6633		struct scsi_mode_sense_10 *cdb;
6634
6635		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6636
6637		header_len = sizeof(struct scsi_mode_hdr_10);
6638
6639		if (cdb->byte2 & SMS_DBD)
6640			dbd = 1;
6641		else
6642			header_len += sizeof(struct scsi_mode_block_descr);
6643		if (cdb->byte2 & SMS10_LLBAA)
6644			llba = 1;
6645		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6646		page_code = cdb->page & SMS_PAGE_CODE;
6647		subpage = cdb->subpage;
6648		alloc_len = scsi_2btoul(cdb->length);
6649		break;
6650	}
6651	default:
6652		ctl_set_invalid_opcode(ctsio);
6653		ctl_done((union ctl_io *)ctsio);
6654		return (CTL_RETVAL_COMPLETE);
6655		break; /* NOTREACHED */
6656	}
6657
6658	/*
6659	 * We have to make a first pass through to calculate the size of
6660	 * the pages that match the user's query.  Then we allocate enough
6661	 * memory to hold it, and actually copy the data into the buffer.
6662	 */
6663	switch (page_code) {
6664	case SMS_ALL_PAGES_PAGE: {
6665		int i;
6666
6667		page_len = 0;
6668
6669		/*
6670		 * At the moment, values other than 0 and 0xff here are
6671		 * reserved according to SPC-3.
6672		 */
6673		if ((subpage != SMS_SUBPAGE_PAGE_0)
6674		 && (subpage != SMS_SUBPAGE_ALL)) {
6675			ctl_set_invalid_field(ctsio,
6676					      /*sks_valid*/ 1,
6677					      /*command*/ 1,
6678					      /*field*/ 3,
6679					      /*bit_valid*/ 0,
6680					      /*bit*/ 0);
6681			ctl_done((union ctl_io *)ctsio);
6682			return (CTL_RETVAL_COMPLETE);
6683		}
6684
6685		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6686			if ((control_dev != 0)
6687			 && (lun->mode_pages.index[i].page_flags &
6688			     CTL_PAGE_FLAG_DISK_ONLY))
6689				continue;
6690
6691			/*
6692			 * We don't use this subpage if the user didn't
6693			 * request all subpages.
6694			 */
6695			if ((lun->mode_pages.index[i].subpage != 0)
6696			 && (subpage == SMS_SUBPAGE_PAGE_0))
6697				continue;
6698
6699#if 0
6700			printf("found page %#x len %d\n",
6701			       lun->mode_pages.index[i].page_code &
6702			       SMPH_PC_MASK,
6703			       lun->mode_pages.index[i].page_len);
6704#endif
6705			page_len += lun->mode_pages.index[i].page_len;
6706		}
6707		break;
6708	}
6709	default: {
6710		int i;
6711
6712		page_len = 0;
6713
6714		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6715			/* Look for the right page code */
6716			if ((lun->mode_pages.index[i].page_code &
6717			     SMPH_PC_MASK) != page_code)
6718				continue;
6719
6720			/* Look for the right subpage or the subpage wildcard*/
6721			if ((lun->mode_pages.index[i].subpage != subpage)
6722			 && (subpage != SMS_SUBPAGE_ALL))
6723				continue;
6724
6725			/* Make sure the page is supported for this dev type */
6726			if ((control_dev != 0)
6727			 && (lun->mode_pages.index[i].page_flags &
6728			     CTL_PAGE_FLAG_DISK_ONLY))
6729				continue;
6730
6731#if 0
6732			printf("found page %#x len %d\n",
6733			       lun->mode_pages.index[i].page_code &
6734			       SMPH_PC_MASK,
6735			       lun->mode_pages.index[i].page_len);
6736#endif
6737
6738			page_len += lun->mode_pages.index[i].page_len;
6739		}
6740
6741		if (page_len == 0) {
6742			ctl_set_invalid_field(ctsio,
6743					      /*sks_valid*/ 1,
6744					      /*command*/ 1,
6745					      /*field*/ 2,
6746					      /*bit_valid*/ 1,
6747					      /*bit*/ 5);
6748			ctl_done((union ctl_io *)ctsio);
6749			return (CTL_RETVAL_COMPLETE);
6750		}
6751		break;
6752	}
6753	}
6754
6755	total_len = header_len + page_len;
6756#if 0
6757	printf("header_len = %d, page_len = %d, total_len = %d\n",
6758	       header_len, page_len, total_len);
6759#endif
6760
6761	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6762	ctsio->kern_sg_entries = 0;
6763	ctsio->kern_data_resid = 0;
6764	ctsio->kern_rel_offset = 0;
6765	if (total_len < alloc_len) {
6766		ctsio->residual = alloc_len - total_len;
6767		ctsio->kern_data_len = total_len;
6768		ctsio->kern_total_len = total_len;
6769	} else {
6770		ctsio->residual = 0;
6771		ctsio->kern_data_len = alloc_len;
6772		ctsio->kern_total_len = alloc_len;
6773	}
6774
6775	switch (ctsio->cdb[0]) {
6776	case MODE_SENSE_6: {
6777		struct scsi_mode_hdr_6 *header;
6778
6779		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6780
6781		header->datalen = ctl_min(total_len - 1, 254);
6782		if (control_dev == 0) {
6783			header->dev_specific = 0x10; /* DPOFUA */
6784			if ((lun->flags & CTL_LUN_READONLY) ||
6785			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6786			    .eca_and_aen & SCP_SWP) != 0)
6787				    header->dev_specific |= 0x80; /* WP */
6788		}
6789		if (dbd)
6790			header->block_descr_len = 0;
6791		else
6792			header->block_descr_len =
6793				sizeof(struct scsi_mode_block_descr);
6794		block_desc = (struct scsi_mode_block_descr *)&header[1];
6795		break;
6796	}
6797	case MODE_SENSE_10: {
6798		struct scsi_mode_hdr_10 *header;
6799		int datalen;
6800
6801		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6802
6803		datalen = ctl_min(total_len - 2, 65533);
6804		scsi_ulto2b(datalen, header->datalen);
6805		if (control_dev == 0) {
6806			header->dev_specific = 0x10; /* DPOFUA */
6807			if ((lun->flags & CTL_LUN_READONLY) ||
6808			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6809			    .eca_and_aen & SCP_SWP) != 0)
6810				    header->dev_specific |= 0x80; /* WP */
6811		}
6812		if (dbd)
6813			scsi_ulto2b(0, header->block_descr_len);
6814		else
6815			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6816				    header->block_descr_len);
6817		block_desc = (struct scsi_mode_block_descr *)&header[1];
6818		break;
6819	}
6820	default:
6821		panic("invalid CDB type %#x", ctsio->cdb[0]);
6822		break; /* NOTREACHED */
6823	}
6824
6825	/*
6826	 * If we've got a disk, use its blocksize in the block
6827	 * descriptor.  Otherwise, just set it to 0.
6828	 */
6829	if (dbd == 0) {
6830		if (control_dev == 0)
6831			scsi_ulto3b(lun->be_lun->blocksize,
6832				    block_desc->block_len);
6833		else
6834			scsi_ulto3b(0, block_desc->block_len);
6835	}
6836
6837	switch (page_code) {
6838	case SMS_ALL_PAGES_PAGE: {
6839		int i, data_used;
6840
6841		data_used = header_len;
6842		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6843			struct ctl_page_index *page_index;
6844
6845			page_index = &lun->mode_pages.index[i];
6846
6847			if ((control_dev != 0)
6848			 && (page_index->page_flags &
6849			    CTL_PAGE_FLAG_DISK_ONLY))
6850				continue;
6851
6852			/*
6853			 * We don't use this subpage if the user didn't
6854			 * request all subpages.  We already checked (above)
6855			 * to make sure the user only specified a subpage
6856			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6857			 */
6858			if ((page_index->subpage != 0)
6859			 && (subpage == SMS_SUBPAGE_PAGE_0))
6860				continue;
6861
6862			/*
6863			 * Call the handler, if it exists, to update the
6864			 * page to the latest values.
6865			 */
6866			if (page_index->sense_handler != NULL)
6867				page_index->sense_handler(ctsio, page_index,pc);
6868
6869			memcpy(ctsio->kern_data_ptr + data_used,
6870			       page_index->page_data +
6871			       (page_index->page_len * pc),
6872			       page_index->page_len);
6873			data_used += page_index->page_len;
6874		}
6875		break;
6876	}
6877	default: {
6878		int i, data_used;
6879
6880		data_used = header_len;
6881
6882		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6883			struct ctl_page_index *page_index;
6884
6885			page_index = &lun->mode_pages.index[i];
6886
6887			/* Look for the right page code */
6888			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6889				continue;
6890
6891			/* Look for the right subpage or the subpage wildcard*/
6892			if ((page_index->subpage != subpage)
6893			 && (subpage != SMS_SUBPAGE_ALL))
6894				continue;
6895
6896			/* Make sure the page is supported for this dev type */
6897			if ((control_dev != 0)
6898			 && (page_index->page_flags &
6899			     CTL_PAGE_FLAG_DISK_ONLY))
6900				continue;
6901
6902			/*
6903			 * Call the handler, if it exists, to update the
6904			 * page to the latest values.
6905			 */
6906			if (page_index->sense_handler != NULL)
6907				page_index->sense_handler(ctsio, page_index,pc);
6908
6909			memcpy(ctsio->kern_data_ptr + data_used,
6910			       page_index->page_data +
6911			       (page_index->page_len * pc),
6912			       page_index->page_len);
6913			data_used += page_index->page_len;
6914		}
6915		break;
6916	}
6917	}
6918
6919	ctl_set_success(ctsio);
6920	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6921	ctsio->be_move_done = ctl_config_move_done;
6922	ctl_datamove((union ctl_io *)ctsio);
6923	return (CTL_RETVAL_COMPLETE);
6924}
6925
6926int
6927ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6928			       struct ctl_page_index *page_index,
6929			       int pc)
6930{
6931	struct ctl_lun *lun;
6932	struct scsi_log_param_header *phdr;
6933	uint8_t *data;
6934	uint64_t val;
6935
6936	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6937	data = page_index->page_data;
6938
6939	if (lun->backend->lun_attr != NULL &&
6940	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6941	     != UINT64_MAX) {
6942		phdr = (struct scsi_log_param_header *)data;
6943		scsi_ulto2b(0x0001, phdr->param_code);
6944		phdr->param_control = SLP_LBIN | SLP_LP;
6945		phdr->param_len = 8;
6946		data = (uint8_t *)(phdr + 1);
6947		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6948		data[4] = 0x01; /* per-LUN */
6949		data += phdr->param_len;
6950	}
6951
6952	if (lun->backend->lun_attr != NULL &&
6953	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6954	     != UINT64_MAX) {
6955		phdr = (struct scsi_log_param_header *)data;
6956		scsi_ulto2b(0x0002, phdr->param_code);
6957		phdr->param_control = SLP_LBIN | SLP_LP;
6958		phdr->param_len = 8;
6959		data = (uint8_t *)(phdr + 1);
6960		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6961		data[4] = 0x02; /* per-pool */
6962		data += phdr->param_len;
6963	}
6964
6965	if (lun->backend->lun_attr != NULL &&
6966	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6967	     != UINT64_MAX) {
6968		phdr = (struct scsi_log_param_header *)data;
6969		scsi_ulto2b(0x00f1, phdr->param_code);
6970		phdr->param_control = SLP_LBIN | SLP_LP;
6971		phdr->param_len = 8;
6972		data = (uint8_t *)(phdr + 1);
6973		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6974		data[4] = 0x02; /* per-pool */
6975		data += phdr->param_len;
6976	}
6977
6978	if (lun->backend->lun_attr != NULL &&
6979	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6980	     != UINT64_MAX) {
6981		phdr = (struct scsi_log_param_header *)data;
6982		scsi_ulto2b(0x00f2, phdr->param_code);
6983		phdr->param_control = SLP_LBIN | SLP_LP;
6984		phdr->param_len = 8;
6985		data = (uint8_t *)(phdr + 1);
6986		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6987		data[4] = 0x02; /* per-pool */
6988		data += phdr->param_len;
6989	}
6990
6991	page_index->page_len = data - page_index->page_data;
6992	return (0);
6993}
6994
6995int
6996ctl_log_sense(struct ctl_scsiio *ctsio)
6997{
6998	struct ctl_lun *lun;
6999	int i, pc, page_code, subpage;
7000	int alloc_len, total_len;
7001	struct ctl_page_index *page_index;
7002	struct scsi_log_sense *cdb;
7003	struct scsi_log_header *header;
7004
7005	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
7006
7007	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7008	cdb = (struct scsi_log_sense *)ctsio->cdb;
7009	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
7010	page_code = cdb->page & SLS_PAGE_CODE;
7011	subpage = cdb->subpage;
7012	alloc_len = scsi_2btoul(cdb->length);
7013
7014	page_index = NULL;
7015	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
7016		page_index = &lun->log_pages.index[i];
7017
7018		/* Look for the right page code */
7019		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
7020			continue;
7021
7022		/* Look for the right subpage or the subpage wildcard*/
7023		if (page_index->subpage != subpage)
7024			continue;
7025
7026		break;
7027	}
7028	if (i >= CTL_NUM_LOG_PAGES) {
7029		ctl_set_invalid_field(ctsio,
7030				      /*sks_valid*/ 1,
7031				      /*command*/ 1,
7032				      /*field*/ 2,
7033				      /*bit_valid*/ 0,
7034				      /*bit*/ 0);
7035		ctl_done((union ctl_io *)ctsio);
7036		return (CTL_RETVAL_COMPLETE);
7037	}
7038
7039	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
7040
7041	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7042	ctsio->kern_sg_entries = 0;
7043	ctsio->kern_data_resid = 0;
7044	ctsio->kern_rel_offset = 0;
7045	if (total_len < alloc_len) {
7046		ctsio->residual = alloc_len - total_len;
7047		ctsio->kern_data_len = total_len;
7048		ctsio->kern_total_len = total_len;
7049	} else {
7050		ctsio->residual = 0;
7051		ctsio->kern_data_len = alloc_len;
7052		ctsio->kern_total_len = alloc_len;
7053	}
7054
7055	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7056	header->page = page_index->page_code;
7057	if (page_index->subpage) {
7058		header->page |= SL_SPF;
7059		header->subpage = page_index->subpage;
7060	}
7061	scsi_ulto2b(page_index->page_len, header->datalen);
7062
7063	/*
7064	 * Call the handler, if it exists, to update the
7065	 * page to the latest values.
7066	 */
7067	if (page_index->sense_handler != NULL)
7068		page_index->sense_handler(ctsio, page_index, pc);
7069
7070	memcpy(header + 1, page_index->page_data, page_index->page_len);
7071
7072	ctl_set_success(ctsio);
7073	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7074	ctsio->be_move_done = ctl_config_move_done;
7075	ctl_datamove((union ctl_io *)ctsio);
7076	return (CTL_RETVAL_COMPLETE);
7077}
7078
7079int
7080ctl_read_capacity(struct ctl_scsiio *ctsio)
7081{
7082	struct scsi_read_capacity *cdb;
7083	struct scsi_read_capacity_data *data;
7084	struct ctl_lun *lun;
7085	uint32_t lba;
7086
7087	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7088
7089	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7090
7091	lba = scsi_4btoul(cdb->addr);
7092	if (((cdb->pmi & SRC_PMI) == 0)
7093	 && (lba != 0)) {
7094		ctl_set_invalid_field(/*ctsio*/ ctsio,
7095				      /*sks_valid*/ 1,
7096				      /*command*/ 1,
7097				      /*field*/ 2,
7098				      /*bit_valid*/ 0,
7099				      /*bit*/ 0);
7100		ctl_done((union ctl_io *)ctsio);
7101		return (CTL_RETVAL_COMPLETE);
7102	}
7103
7104	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7105
7106	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7107	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7108	ctsio->residual = 0;
7109	ctsio->kern_data_len = sizeof(*data);
7110	ctsio->kern_total_len = sizeof(*data);
7111	ctsio->kern_data_resid = 0;
7112	ctsio->kern_rel_offset = 0;
7113	ctsio->kern_sg_entries = 0;
7114
7115	/*
7116	 * If the maximum LBA is greater than 0xfffffffe, the user must
7117	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7118	 * serivce action set.
7119	 */
7120	if (lun->be_lun->maxlba > 0xfffffffe)
7121		scsi_ulto4b(0xffffffff, data->addr);
7122	else
7123		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7124
7125	/*
7126	 * XXX KDM this may not be 512 bytes...
7127	 */
7128	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7129
7130	ctl_set_success(ctsio);
7131	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7132	ctsio->be_move_done = ctl_config_move_done;
7133	ctl_datamove((union ctl_io *)ctsio);
7134	return (CTL_RETVAL_COMPLETE);
7135}
7136
7137int
7138ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7139{
7140	struct scsi_read_capacity_16 *cdb;
7141	struct scsi_read_capacity_data_long *data;
7142	struct ctl_lun *lun;
7143	uint64_t lba;
7144	uint32_t alloc_len;
7145
7146	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7147
7148	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7149
7150	alloc_len = scsi_4btoul(cdb->alloc_len);
7151	lba = scsi_8btou64(cdb->addr);
7152
7153	if ((cdb->reladr & SRC16_PMI)
7154	 && (lba != 0)) {
7155		ctl_set_invalid_field(/*ctsio*/ ctsio,
7156				      /*sks_valid*/ 1,
7157				      /*command*/ 1,
7158				      /*field*/ 2,
7159				      /*bit_valid*/ 0,
7160				      /*bit*/ 0);
7161		ctl_done((union ctl_io *)ctsio);
7162		return (CTL_RETVAL_COMPLETE);
7163	}
7164
7165	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7166
7167	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7168	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7169
7170	if (sizeof(*data) < alloc_len) {
7171		ctsio->residual = alloc_len - sizeof(*data);
7172		ctsio->kern_data_len = sizeof(*data);
7173		ctsio->kern_total_len = sizeof(*data);
7174	} else {
7175		ctsio->residual = 0;
7176		ctsio->kern_data_len = alloc_len;
7177		ctsio->kern_total_len = alloc_len;
7178	}
7179	ctsio->kern_data_resid = 0;
7180	ctsio->kern_rel_offset = 0;
7181	ctsio->kern_sg_entries = 0;
7182
7183	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7184	/* XXX KDM this may not be 512 bytes... */
7185	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7186	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7187	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7188	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7189		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7190
7191	ctl_set_success(ctsio);
7192	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7193	ctsio->be_move_done = ctl_config_move_done;
7194	ctl_datamove((union ctl_io *)ctsio);
7195	return (CTL_RETVAL_COMPLETE);
7196}
7197
7198int
7199ctl_read_defect(struct ctl_scsiio *ctsio)
7200{
7201	struct scsi_read_defect_data_10 *ccb10;
7202	struct scsi_read_defect_data_12 *ccb12;
7203	struct scsi_read_defect_data_hdr_10 *data10;
7204	struct scsi_read_defect_data_hdr_12 *data12;
7205	uint32_t alloc_len, data_len;
7206	uint8_t format;
7207
7208	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7209
7210	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7211		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7212		format = ccb10->format;
7213		alloc_len = scsi_2btoul(ccb10->alloc_length);
7214		data_len = sizeof(*data10);
7215	} else {
7216		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7217		format = ccb12->format;
7218		alloc_len = scsi_4btoul(ccb12->alloc_length);
7219		data_len = sizeof(*data12);
7220	}
7221	if (alloc_len == 0) {
7222		ctl_set_success(ctsio);
7223		ctl_done((union ctl_io *)ctsio);
7224		return (CTL_RETVAL_COMPLETE);
7225	}
7226
7227	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7228	if (data_len < alloc_len) {
7229		ctsio->residual = alloc_len - data_len;
7230		ctsio->kern_data_len = data_len;
7231		ctsio->kern_total_len = data_len;
7232	} else {
7233		ctsio->residual = 0;
7234		ctsio->kern_data_len = alloc_len;
7235		ctsio->kern_total_len = alloc_len;
7236	}
7237	ctsio->kern_data_resid = 0;
7238	ctsio->kern_rel_offset = 0;
7239	ctsio->kern_sg_entries = 0;
7240
7241	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7242		data10 = (struct scsi_read_defect_data_hdr_10 *)
7243		    ctsio->kern_data_ptr;
7244		data10->format = format;
7245		scsi_ulto2b(0, data10->length);
7246	} else {
7247		data12 = (struct scsi_read_defect_data_hdr_12 *)
7248		    ctsio->kern_data_ptr;
7249		data12->format = format;
7250		scsi_ulto2b(0, data12->generation);
7251		scsi_ulto4b(0, data12->length);
7252	}
7253
7254	ctl_set_success(ctsio);
7255	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7256	ctsio->be_move_done = ctl_config_move_done;
7257	ctl_datamove((union ctl_io *)ctsio);
7258	return (CTL_RETVAL_COMPLETE);
7259}
7260
7261int
7262ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7263{
7264	struct scsi_maintenance_in *cdb;
7265	int retval;
7266	int alloc_len, ext, total_len = 0, g, p, pc, pg, gs, os;
7267	int num_target_port_groups, num_target_ports;
7268	struct ctl_lun *lun;
7269	struct ctl_softc *softc;
7270	struct ctl_port *port;
7271	struct scsi_target_group_data *rtg_ptr;
7272	struct scsi_target_group_data_extended *rtg_ext_ptr;
7273	struct scsi_target_port_group_descriptor *tpg_desc;
7274
7275	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7276
7277	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7278	softc = control_softc;
7279	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7280
7281	retval = CTL_RETVAL_COMPLETE;
7282
7283	switch (cdb->byte2 & STG_PDF_MASK) {
7284	case STG_PDF_LENGTH:
7285		ext = 0;
7286		break;
7287	case STG_PDF_EXTENDED:
7288		ext = 1;
7289		break;
7290	default:
7291		ctl_set_invalid_field(/*ctsio*/ ctsio,
7292				      /*sks_valid*/ 1,
7293				      /*command*/ 1,
7294				      /*field*/ 2,
7295				      /*bit_valid*/ 1,
7296				      /*bit*/ 5);
7297		ctl_done((union ctl_io *)ctsio);
7298		return(retval);
7299	}
7300
7301	if (softc->is_single)
7302		num_target_port_groups = 1;
7303	else
7304		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7305	num_target_ports = 0;
7306	mtx_lock(&softc->ctl_lock);
7307	STAILQ_FOREACH(port, &softc->port_list, links) {
7308		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7309			continue;
7310		if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7311			continue;
7312		num_target_ports++;
7313	}
7314	mtx_unlock(&softc->ctl_lock);
7315
7316	if (ext)
7317		total_len = sizeof(struct scsi_target_group_data_extended);
7318	else
7319		total_len = sizeof(struct scsi_target_group_data);
7320	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7321		num_target_port_groups +
7322	    sizeof(struct scsi_target_port_descriptor) *
7323		num_target_ports * num_target_port_groups;
7324
7325	alloc_len = scsi_4btoul(cdb->length);
7326
7327	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7328
7329	ctsio->kern_sg_entries = 0;
7330
7331	if (total_len < alloc_len) {
7332		ctsio->residual = alloc_len - total_len;
7333		ctsio->kern_data_len = total_len;
7334		ctsio->kern_total_len = total_len;
7335	} else {
7336		ctsio->residual = 0;
7337		ctsio->kern_data_len = alloc_len;
7338		ctsio->kern_total_len = alloc_len;
7339	}
7340	ctsio->kern_data_resid = 0;
7341	ctsio->kern_rel_offset = 0;
7342
7343	if (ext) {
7344		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7345		    ctsio->kern_data_ptr;
7346		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7347		rtg_ext_ptr->format_type = 0x10;
7348		rtg_ext_ptr->implicit_transition_time = 0;
7349		tpg_desc = &rtg_ext_ptr->groups[0];
7350	} else {
7351		rtg_ptr = (struct scsi_target_group_data *)
7352		    ctsio->kern_data_ptr;
7353		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7354		tpg_desc = &rtg_ptr->groups[0];
7355	}
7356
7357	mtx_lock(&softc->ctl_lock);
7358	pg = softc->port_offset / CTL_MAX_PORTS;
7359	if (softc->flags & CTL_FLAG_ACTIVE_SHELF) {
7360		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY) {
7361			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7362			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7363		} else if (lun->flags & CTL_LUN_PRIMARY_SC) {
7364			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7365			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7366		} else {
7367			gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7368			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7369		}
7370	} else {
7371		gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7372		os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7373	}
7374	for (g = 0; g < num_target_port_groups; g++) {
7375		tpg_desc->pref_state = (g == pg) ? gs : os;
7376		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP;
7377		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7378		tpg_desc->status = TPG_IMPLICIT;
7379		pc = 0;
7380		STAILQ_FOREACH(port, &softc->port_list, links) {
7381			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7382				continue;
7383			if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7384			    CTL_MAX_LUNS)
7385				continue;
7386			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7387			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7388			    relative_target_port_identifier);
7389			pc++;
7390		}
7391		tpg_desc->target_port_count = pc;
7392		tpg_desc = (struct scsi_target_port_group_descriptor *)
7393		    &tpg_desc->descriptors[pc];
7394	}
7395	mtx_unlock(&softc->ctl_lock);
7396
7397	ctl_set_success(ctsio);
7398	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7399	ctsio->be_move_done = ctl_config_move_done;
7400	ctl_datamove((union ctl_io *)ctsio);
7401	return(retval);
7402}
7403
7404int
7405ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7406{
7407	struct ctl_lun *lun;
7408	struct scsi_report_supported_opcodes *cdb;
7409	const struct ctl_cmd_entry *entry, *sentry;
7410	struct scsi_report_supported_opcodes_all *all;
7411	struct scsi_report_supported_opcodes_descr *descr;
7412	struct scsi_report_supported_opcodes_one *one;
7413	int retval;
7414	int alloc_len, total_len;
7415	int opcode, service_action, i, j, num;
7416
7417	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7418
7419	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7420	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7421
7422	retval = CTL_RETVAL_COMPLETE;
7423
7424	opcode = cdb->requested_opcode;
7425	service_action = scsi_2btoul(cdb->requested_service_action);
7426	switch (cdb->options & RSO_OPTIONS_MASK) {
7427	case RSO_OPTIONS_ALL:
7428		num = 0;
7429		for (i = 0; i < 256; i++) {
7430			entry = &ctl_cmd_table[i];
7431			if (entry->flags & CTL_CMD_FLAG_SA5) {
7432				for (j = 0; j < 32; j++) {
7433					sentry = &((const struct ctl_cmd_entry *)
7434					    entry->execute)[j];
7435					if (ctl_cmd_applicable(
7436					    lun->be_lun->lun_type, sentry))
7437						num++;
7438				}
7439			} else {
7440				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7441				    entry))
7442					num++;
7443			}
7444		}
7445		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7446		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7447		break;
7448	case RSO_OPTIONS_OC:
7449		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7450			ctl_set_invalid_field(/*ctsio*/ ctsio,
7451					      /*sks_valid*/ 1,
7452					      /*command*/ 1,
7453					      /*field*/ 2,
7454					      /*bit_valid*/ 1,
7455					      /*bit*/ 2);
7456			ctl_done((union ctl_io *)ctsio);
7457			return (CTL_RETVAL_COMPLETE);
7458		}
7459		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7460		break;
7461	case RSO_OPTIONS_OC_SA:
7462		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7463		    service_action >= 32) {
7464			ctl_set_invalid_field(/*ctsio*/ ctsio,
7465					      /*sks_valid*/ 1,
7466					      /*command*/ 1,
7467					      /*field*/ 2,
7468					      /*bit_valid*/ 1,
7469					      /*bit*/ 2);
7470			ctl_done((union ctl_io *)ctsio);
7471			return (CTL_RETVAL_COMPLETE);
7472		}
7473		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7474		break;
7475	default:
7476		ctl_set_invalid_field(/*ctsio*/ ctsio,
7477				      /*sks_valid*/ 1,
7478				      /*command*/ 1,
7479				      /*field*/ 2,
7480				      /*bit_valid*/ 1,
7481				      /*bit*/ 2);
7482		ctl_done((union ctl_io *)ctsio);
7483		return (CTL_RETVAL_COMPLETE);
7484	}
7485
7486	alloc_len = scsi_4btoul(cdb->length);
7487
7488	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7489
7490	ctsio->kern_sg_entries = 0;
7491
7492	if (total_len < alloc_len) {
7493		ctsio->residual = alloc_len - total_len;
7494		ctsio->kern_data_len = total_len;
7495		ctsio->kern_total_len = total_len;
7496	} else {
7497		ctsio->residual = 0;
7498		ctsio->kern_data_len = alloc_len;
7499		ctsio->kern_total_len = alloc_len;
7500	}
7501	ctsio->kern_data_resid = 0;
7502	ctsio->kern_rel_offset = 0;
7503
7504	switch (cdb->options & RSO_OPTIONS_MASK) {
7505	case RSO_OPTIONS_ALL:
7506		all = (struct scsi_report_supported_opcodes_all *)
7507		    ctsio->kern_data_ptr;
7508		num = 0;
7509		for (i = 0; i < 256; i++) {
7510			entry = &ctl_cmd_table[i];
7511			if (entry->flags & CTL_CMD_FLAG_SA5) {
7512				for (j = 0; j < 32; j++) {
7513					sentry = &((const struct ctl_cmd_entry *)
7514					    entry->execute)[j];
7515					if (!ctl_cmd_applicable(
7516					    lun->be_lun->lun_type, sentry))
7517						continue;
7518					descr = &all->descr[num++];
7519					descr->opcode = i;
7520					scsi_ulto2b(j, descr->service_action);
7521					descr->flags = RSO_SERVACTV;
7522					scsi_ulto2b(sentry->length,
7523					    descr->cdb_length);
7524				}
7525			} else {
7526				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7527				    entry))
7528					continue;
7529				descr = &all->descr[num++];
7530				descr->opcode = i;
7531				scsi_ulto2b(0, descr->service_action);
7532				descr->flags = 0;
7533				scsi_ulto2b(entry->length, descr->cdb_length);
7534			}
7535		}
7536		scsi_ulto4b(
7537		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7538		    all->length);
7539		break;
7540	case RSO_OPTIONS_OC:
7541		one = (struct scsi_report_supported_opcodes_one *)
7542		    ctsio->kern_data_ptr;
7543		entry = &ctl_cmd_table[opcode];
7544		goto fill_one;
7545	case RSO_OPTIONS_OC_SA:
7546		one = (struct scsi_report_supported_opcodes_one *)
7547		    ctsio->kern_data_ptr;
7548		entry = &ctl_cmd_table[opcode];
7549		entry = &((const struct ctl_cmd_entry *)
7550		    entry->execute)[service_action];
7551fill_one:
7552		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7553			one->support = 3;
7554			scsi_ulto2b(entry->length, one->cdb_length);
7555			one->cdb_usage[0] = opcode;
7556			memcpy(&one->cdb_usage[1], entry->usage,
7557			    entry->length - 1);
7558		} else
7559			one->support = 1;
7560		break;
7561	}
7562
7563	ctl_set_success(ctsio);
7564	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7565	ctsio->be_move_done = ctl_config_move_done;
7566	ctl_datamove((union ctl_io *)ctsio);
7567	return(retval);
7568}
7569
7570int
7571ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7572{
7573	struct scsi_report_supported_tmf *cdb;
7574	struct scsi_report_supported_tmf_data *data;
7575	int retval;
7576	int alloc_len, total_len;
7577
7578	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7579
7580	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7581
7582	retval = CTL_RETVAL_COMPLETE;
7583
7584	total_len = sizeof(struct scsi_report_supported_tmf_data);
7585	alloc_len = scsi_4btoul(cdb->length);
7586
7587	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7588
7589	ctsio->kern_sg_entries = 0;
7590
7591	if (total_len < alloc_len) {
7592		ctsio->residual = alloc_len - total_len;
7593		ctsio->kern_data_len = total_len;
7594		ctsio->kern_total_len = total_len;
7595	} else {
7596		ctsio->residual = 0;
7597		ctsio->kern_data_len = alloc_len;
7598		ctsio->kern_total_len = alloc_len;
7599	}
7600	ctsio->kern_data_resid = 0;
7601	ctsio->kern_rel_offset = 0;
7602
7603	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7604	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7605	data->byte2 |= RST_ITNRS;
7606
7607	ctl_set_success(ctsio);
7608	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7609	ctsio->be_move_done = ctl_config_move_done;
7610	ctl_datamove((union ctl_io *)ctsio);
7611	return (retval);
7612}
7613
7614int
7615ctl_report_timestamp(struct ctl_scsiio *ctsio)
7616{
7617	struct scsi_report_timestamp *cdb;
7618	struct scsi_report_timestamp_data *data;
7619	struct timeval tv;
7620	int64_t timestamp;
7621	int retval;
7622	int alloc_len, total_len;
7623
7624	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7625
7626	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7627
7628	retval = CTL_RETVAL_COMPLETE;
7629
7630	total_len = sizeof(struct scsi_report_timestamp_data);
7631	alloc_len = scsi_4btoul(cdb->length);
7632
7633	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7634
7635	ctsio->kern_sg_entries = 0;
7636
7637	if (total_len < alloc_len) {
7638		ctsio->residual = alloc_len - total_len;
7639		ctsio->kern_data_len = total_len;
7640		ctsio->kern_total_len = total_len;
7641	} else {
7642		ctsio->residual = 0;
7643		ctsio->kern_data_len = alloc_len;
7644		ctsio->kern_total_len = alloc_len;
7645	}
7646	ctsio->kern_data_resid = 0;
7647	ctsio->kern_rel_offset = 0;
7648
7649	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7650	scsi_ulto2b(sizeof(*data) - 2, data->length);
7651	data->origin = RTS_ORIG_OUTSIDE;
7652	getmicrotime(&tv);
7653	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7654	scsi_ulto4b(timestamp >> 16, data->timestamp);
7655	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7656
7657	ctl_set_success(ctsio);
7658	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7659	ctsio->be_move_done = ctl_config_move_done;
7660	ctl_datamove((union ctl_io *)ctsio);
7661	return (retval);
7662}
7663
7664int
7665ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7666{
7667	struct scsi_per_res_in *cdb;
7668	int alloc_len, total_len = 0;
7669	/* struct scsi_per_res_in_rsrv in_data; */
7670	struct ctl_lun *lun;
7671	struct ctl_softc *softc;
7672	uint64_t key;
7673
7674	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7675
7676	softc = control_softc;
7677
7678	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7679
7680	alloc_len = scsi_2btoul(cdb->length);
7681
7682	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7683
7684retry:
7685	mtx_lock(&lun->lun_lock);
7686	switch (cdb->action) {
7687	case SPRI_RK: /* read keys */
7688		total_len = sizeof(struct scsi_per_res_in_keys) +
7689			lun->pr_key_count *
7690			sizeof(struct scsi_per_res_key);
7691		break;
7692	case SPRI_RR: /* read reservation */
7693		if (lun->flags & CTL_LUN_PR_RESERVED)
7694			total_len = sizeof(struct scsi_per_res_in_rsrv);
7695		else
7696			total_len = sizeof(struct scsi_per_res_in_header);
7697		break;
7698	case SPRI_RC: /* report capabilities */
7699		total_len = sizeof(struct scsi_per_res_cap);
7700		break;
7701	case SPRI_RS: /* read full status */
7702		total_len = sizeof(struct scsi_per_res_in_header) +
7703		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7704		    lun->pr_key_count;
7705		break;
7706	default:
7707		panic("Invalid PR type %x", cdb->action);
7708	}
7709	mtx_unlock(&lun->lun_lock);
7710
7711	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7712
7713	if (total_len < alloc_len) {
7714		ctsio->residual = alloc_len - total_len;
7715		ctsio->kern_data_len = total_len;
7716		ctsio->kern_total_len = total_len;
7717	} else {
7718		ctsio->residual = 0;
7719		ctsio->kern_data_len = alloc_len;
7720		ctsio->kern_total_len = alloc_len;
7721	}
7722
7723	ctsio->kern_data_resid = 0;
7724	ctsio->kern_rel_offset = 0;
7725	ctsio->kern_sg_entries = 0;
7726
7727	mtx_lock(&lun->lun_lock);
7728	switch (cdb->action) {
7729	case SPRI_RK: { // read keys
7730        struct scsi_per_res_in_keys *res_keys;
7731		int i, key_count;
7732
7733		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7734
7735		/*
7736		 * We had to drop the lock to allocate our buffer, which
7737		 * leaves time for someone to come in with another
7738		 * persistent reservation.  (That is unlikely, though,
7739		 * since this should be the only persistent reservation
7740		 * command active right now.)
7741		 */
7742		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7743		    (lun->pr_key_count *
7744		     sizeof(struct scsi_per_res_key)))){
7745			mtx_unlock(&lun->lun_lock);
7746			free(ctsio->kern_data_ptr, M_CTL);
7747			printf("%s: reservation length changed, retrying\n",
7748			       __func__);
7749			goto retry;
7750		}
7751
7752		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7753
7754		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7755			     lun->pr_key_count, res_keys->header.length);
7756
7757		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7758			if ((key = ctl_get_prkey(lun, i)) == 0)
7759				continue;
7760
7761			/*
7762			 * We used lun->pr_key_count to calculate the
7763			 * size to allocate.  If it turns out the number of
7764			 * initiators with the registered flag set is
7765			 * larger than that (i.e. they haven't been kept in
7766			 * sync), we've got a problem.
7767			 */
7768			if (key_count >= lun->pr_key_count) {
7769#ifdef NEEDTOPORT
7770				csevent_log(CSC_CTL | CSC_SHELF_SW |
7771					    CTL_PR_ERROR,
7772					    csevent_LogType_Fault,
7773					    csevent_AlertLevel_Yellow,
7774					    csevent_FRU_ShelfController,
7775					    csevent_FRU_Firmware,
7776				        csevent_FRU_Unknown,
7777					    "registered keys %d >= key "
7778					    "count %d", key_count,
7779					    lun->pr_key_count);
7780#endif
7781				key_count++;
7782				continue;
7783			}
7784			scsi_u64to8b(key, res_keys->keys[key_count].key);
7785			key_count++;
7786		}
7787		break;
7788	}
7789	case SPRI_RR: { // read reservation
7790		struct scsi_per_res_in_rsrv *res;
7791		int tmp_len, header_only;
7792
7793		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7794
7795		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7796
7797		if (lun->flags & CTL_LUN_PR_RESERVED)
7798		{
7799			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7800			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7801				    res->header.length);
7802			header_only = 0;
7803		} else {
7804			tmp_len = sizeof(struct scsi_per_res_in_header);
7805			scsi_ulto4b(0, res->header.length);
7806			header_only = 1;
7807		}
7808
7809		/*
7810		 * We had to drop the lock to allocate our buffer, which
7811		 * leaves time for someone to come in with another
7812		 * persistent reservation.  (That is unlikely, though,
7813		 * since this should be the only persistent reservation
7814		 * command active right now.)
7815		 */
7816		if (tmp_len != total_len) {
7817			mtx_unlock(&lun->lun_lock);
7818			free(ctsio->kern_data_ptr, M_CTL);
7819			printf("%s: reservation status changed, retrying\n",
7820			       __func__);
7821			goto retry;
7822		}
7823
7824		/*
7825		 * No reservation held, so we're done.
7826		 */
7827		if (header_only != 0)
7828			break;
7829
7830		/*
7831		 * If the registration is an All Registrants type, the key
7832		 * is 0, since it doesn't really matter.
7833		 */
7834		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7835			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7836			    res->data.reservation);
7837		}
7838		res->data.scopetype = lun->res_type;
7839		break;
7840	}
7841	case SPRI_RC:     //report capabilities
7842	{
7843		struct scsi_per_res_cap *res_cap;
7844		uint16_t type_mask;
7845
7846		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7847		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7848		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7849		type_mask = SPRI_TM_WR_EX_AR |
7850			    SPRI_TM_EX_AC_RO |
7851			    SPRI_TM_WR_EX_RO |
7852			    SPRI_TM_EX_AC |
7853			    SPRI_TM_WR_EX |
7854			    SPRI_TM_EX_AC_AR;
7855		scsi_ulto2b(type_mask, res_cap->type_mask);
7856		break;
7857	}
7858	case SPRI_RS: { // read full status
7859		struct scsi_per_res_in_full *res_status;
7860		struct scsi_per_res_in_full_desc *res_desc;
7861		struct ctl_port *port;
7862		int i, len;
7863
7864		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7865
7866		/*
7867		 * We had to drop the lock to allocate our buffer, which
7868		 * leaves time for someone to come in with another
7869		 * persistent reservation.  (That is unlikely, though,
7870		 * since this should be the only persistent reservation
7871		 * command active right now.)
7872		 */
7873		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7874		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7875		     lun->pr_key_count)){
7876			mtx_unlock(&lun->lun_lock);
7877			free(ctsio->kern_data_ptr, M_CTL);
7878			printf("%s: reservation length changed, retrying\n",
7879			       __func__);
7880			goto retry;
7881		}
7882
7883		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7884
7885		res_desc = &res_status->desc[0];
7886		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7887			if ((key = ctl_get_prkey(lun, i)) == 0)
7888				continue;
7889
7890			scsi_u64to8b(key, res_desc->res_key.key);
7891			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7892			    (lun->pr_res_idx == i ||
7893			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7894				res_desc->flags = SPRI_FULL_R_HOLDER;
7895				res_desc->scopetype = lun->res_type;
7896			}
7897			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7898			    res_desc->rel_trgt_port_id);
7899			len = 0;
7900			port = softc->ctl_ports[
7901			    ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
7902			if (port != NULL)
7903				len = ctl_create_iid(port,
7904				    i % CTL_MAX_INIT_PER_PORT,
7905				    res_desc->transport_id);
7906			scsi_ulto4b(len, res_desc->additional_length);
7907			res_desc = (struct scsi_per_res_in_full_desc *)
7908			    &res_desc->transport_id[len];
7909		}
7910		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7911		    res_status->header.length);
7912		break;
7913	}
7914	default:
7915		/*
7916		 * This is a bug, because we just checked for this above,
7917		 * and should have returned an error.
7918		 */
7919		panic("Invalid PR type %x", cdb->action);
7920		break; /* NOTREACHED */
7921	}
7922	mtx_unlock(&lun->lun_lock);
7923
7924	ctl_set_success(ctsio);
7925	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7926	ctsio->be_move_done = ctl_config_move_done;
7927	ctl_datamove((union ctl_io *)ctsio);
7928	return (CTL_RETVAL_COMPLETE);
7929}
7930
7931static void
7932ctl_set_res_ua(struct ctl_lun *lun, uint32_t residx, ctl_ua_type ua)
7933{
7934	int off = lun->ctl_softc->persis_offset;
7935
7936	if (residx >= off && residx < off + CTL_MAX_INITIATORS)
7937		lun->pending_ua[residx - off] |= ua;
7938}
7939
7940/*
7941 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7942 * it should return.
7943 */
7944static int
7945ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7946		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7947		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7948		struct scsi_per_res_out_parms* param)
7949{
7950	union ctl_ha_msg persis_io;
7951	int retval, i;
7952	int isc_retval;
7953
7954	retval = 0;
7955
7956	mtx_lock(&lun->lun_lock);
7957	if (sa_res_key == 0) {
7958		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7959			/* validate scope and type */
7960			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7961			     SPR_LU_SCOPE) {
7962				mtx_unlock(&lun->lun_lock);
7963				ctl_set_invalid_field(/*ctsio*/ ctsio,
7964						      /*sks_valid*/ 1,
7965						      /*command*/ 1,
7966						      /*field*/ 2,
7967						      /*bit_valid*/ 1,
7968						      /*bit*/ 4);
7969				ctl_done((union ctl_io *)ctsio);
7970				return (1);
7971			}
7972
7973		        if (type>8 || type==2 || type==4 || type==0) {
7974				mtx_unlock(&lun->lun_lock);
7975				ctl_set_invalid_field(/*ctsio*/ ctsio,
7976       	           				      /*sks_valid*/ 1,
7977						      /*command*/ 1,
7978						      /*field*/ 2,
7979						      /*bit_valid*/ 1,
7980						      /*bit*/ 0);
7981				ctl_done((union ctl_io *)ctsio);
7982				return (1);
7983		        }
7984
7985			/*
7986			 * Unregister everybody else and build UA for
7987			 * them
7988			 */
7989			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7990				if (i == residx || ctl_get_prkey(lun, i) == 0)
7991					continue;
7992
7993				ctl_clr_prkey(lun, i);
7994				ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
7995			}
7996			lun->pr_key_count = 1;
7997			lun->res_type = type;
7998			if (lun->res_type != SPR_TYPE_WR_EX_AR
7999			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8000				lun->pr_res_idx = residx;
8001
8002			/* send msg to other side */
8003			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8004			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8005			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8006			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8007			persis_io.pr.pr_info.res_type = type;
8008			memcpy(persis_io.pr.pr_info.sa_res_key,
8009			       param->serv_act_res_key,
8010			       sizeof(param->serv_act_res_key));
8011			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8012			     &persis_io, sizeof(persis_io), 0)) >
8013			     CTL_HA_STATUS_SUCCESS) {
8014				printf("CTL:Persis Out error returned "
8015				       "from ctl_ha_msg_send %d\n",
8016				       isc_retval);
8017			}
8018		} else {
8019			/* not all registrants */
8020			mtx_unlock(&lun->lun_lock);
8021			free(ctsio->kern_data_ptr, M_CTL);
8022			ctl_set_invalid_field(ctsio,
8023					      /*sks_valid*/ 1,
8024					      /*command*/ 0,
8025					      /*field*/ 8,
8026					      /*bit_valid*/ 0,
8027					      /*bit*/ 0);
8028			ctl_done((union ctl_io *)ctsio);
8029			return (1);
8030		}
8031	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8032		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8033		int found = 0;
8034
8035		if (res_key == sa_res_key) {
8036			/* special case */
8037			/*
8038			 * The spec implies this is not good but doesn't
8039			 * say what to do. There are two choices either
8040			 * generate a res conflict or check condition
8041			 * with illegal field in parameter data. Since
8042			 * that is what is done when the sa_res_key is
8043			 * zero I'll take that approach since this has
8044			 * to do with the sa_res_key.
8045			 */
8046			mtx_unlock(&lun->lun_lock);
8047			free(ctsio->kern_data_ptr, M_CTL);
8048			ctl_set_invalid_field(ctsio,
8049					      /*sks_valid*/ 1,
8050					      /*command*/ 0,
8051					      /*field*/ 8,
8052					      /*bit_valid*/ 0,
8053					      /*bit*/ 0);
8054			ctl_done((union ctl_io *)ctsio);
8055			return (1);
8056		}
8057
8058		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8059			if (ctl_get_prkey(lun, i) != sa_res_key)
8060				continue;
8061
8062			found = 1;
8063			ctl_clr_prkey(lun, i);
8064			lun->pr_key_count--;
8065			ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8066		}
8067		if (!found) {
8068			mtx_unlock(&lun->lun_lock);
8069			free(ctsio->kern_data_ptr, M_CTL);
8070			ctl_set_reservation_conflict(ctsio);
8071			ctl_done((union ctl_io *)ctsio);
8072			return (CTL_RETVAL_COMPLETE);
8073		}
8074		/* send msg to other side */
8075		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8076		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8077		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8078		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8079		persis_io.pr.pr_info.res_type = type;
8080		memcpy(persis_io.pr.pr_info.sa_res_key,
8081		       param->serv_act_res_key,
8082		       sizeof(param->serv_act_res_key));
8083		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8084		     &persis_io, sizeof(persis_io), 0)) >
8085		     CTL_HA_STATUS_SUCCESS) {
8086			printf("CTL:Persis Out error returned from "
8087			       "ctl_ha_msg_send %d\n", isc_retval);
8088		}
8089	} else {
8090		/* Reserved but not all registrants */
8091		/* sa_res_key is res holder */
8092		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
8093			/* validate scope and type */
8094			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8095			     SPR_LU_SCOPE) {
8096				mtx_unlock(&lun->lun_lock);
8097				ctl_set_invalid_field(/*ctsio*/ ctsio,
8098						      /*sks_valid*/ 1,
8099						      /*command*/ 1,
8100						      /*field*/ 2,
8101						      /*bit_valid*/ 1,
8102						      /*bit*/ 4);
8103				ctl_done((union ctl_io *)ctsio);
8104				return (1);
8105			}
8106
8107			if (type>8 || type==2 || type==4 || type==0) {
8108				mtx_unlock(&lun->lun_lock);
8109				ctl_set_invalid_field(/*ctsio*/ ctsio,
8110						      /*sks_valid*/ 1,
8111						      /*command*/ 1,
8112						      /*field*/ 2,
8113						      /*bit_valid*/ 1,
8114						      /*bit*/ 0);
8115				ctl_done((union ctl_io *)ctsio);
8116				return (1);
8117			}
8118
8119			/*
8120			 * Do the following:
8121			 * if sa_res_key != res_key remove all
8122			 * registrants w/sa_res_key and generate UA
8123			 * for these registrants(Registrations
8124			 * Preempted) if it wasn't an exclusive
8125			 * reservation generate UA(Reservations
8126			 * Preempted) for all other registered nexuses
8127			 * if the type has changed. Establish the new
8128			 * reservation and holder. If res_key and
8129			 * sa_res_key are the same do the above
8130			 * except don't unregister the res holder.
8131			 */
8132
8133			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8134				if (i == residx || ctl_get_prkey(lun, i) == 0)
8135					continue;
8136
8137				if (sa_res_key == ctl_get_prkey(lun, i)) {
8138					ctl_clr_prkey(lun, i);
8139					lun->pr_key_count--;
8140					ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8141				} else if (type != lun->res_type
8142					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8143					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8144					ctl_set_res_ua(lun, i, CTL_UA_RES_RELEASE);
8145				}
8146			}
8147			lun->res_type = type;
8148			if (lun->res_type != SPR_TYPE_WR_EX_AR
8149			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8150				lun->pr_res_idx = residx;
8151			else
8152				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8153
8154			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8155			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8156			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8157			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8158			persis_io.pr.pr_info.res_type = type;
8159			memcpy(persis_io.pr.pr_info.sa_res_key,
8160			       param->serv_act_res_key,
8161			       sizeof(param->serv_act_res_key));
8162			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8163			     &persis_io, sizeof(persis_io), 0)) >
8164			     CTL_HA_STATUS_SUCCESS) {
8165				printf("CTL:Persis Out error returned "
8166				       "from ctl_ha_msg_send %d\n",
8167				       isc_retval);
8168			}
8169		} else {
8170			/*
8171			 * sa_res_key is not the res holder just
8172			 * remove registrants
8173			 */
8174			int found=0;
8175
8176			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8177				if (sa_res_key != ctl_get_prkey(lun, i))
8178					continue;
8179
8180				found = 1;
8181				ctl_clr_prkey(lun, i);
8182				lun->pr_key_count--;
8183				ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8184			}
8185
8186			if (!found) {
8187				mtx_unlock(&lun->lun_lock);
8188				free(ctsio->kern_data_ptr, M_CTL);
8189				ctl_set_reservation_conflict(ctsio);
8190				ctl_done((union ctl_io *)ctsio);
8191		        	return (1);
8192			}
8193			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8194			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8195			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8196			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8197			persis_io.pr.pr_info.res_type = type;
8198			memcpy(persis_io.pr.pr_info.sa_res_key,
8199			       param->serv_act_res_key,
8200			       sizeof(param->serv_act_res_key));
8201			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8202			     &persis_io, sizeof(persis_io), 0)) >
8203			     CTL_HA_STATUS_SUCCESS) {
8204				printf("CTL:Persis Out error returned "
8205				       "from ctl_ha_msg_send %d\n",
8206				isc_retval);
8207			}
8208		}
8209	}
8210
8211	lun->PRGeneration++;
8212	mtx_unlock(&lun->lun_lock);
8213
8214	return (retval);
8215}
8216
8217static void
8218ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8219{
8220	uint64_t sa_res_key;
8221	int i;
8222
8223	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8224
8225	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8226	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8227	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8228		if (sa_res_key == 0) {
8229			/*
8230			 * Unregister everybody else and build UA for
8231			 * them
8232			 */
8233			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8234				if (i == msg->pr.pr_info.residx ||
8235				    ctl_get_prkey(lun, i) == 0)
8236					continue;
8237
8238				ctl_clr_prkey(lun, i);
8239				ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8240			}
8241
8242			lun->pr_key_count = 1;
8243			lun->res_type = msg->pr.pr_info.res_type;
8244			if (lun->res_type != SPR_TYPE_WR_EX_AR
8245			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8246				lun->pr_res_idx = msg->pr.pr_info.residx;
8247		} else {
8248		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8249				if (sa_res_key == ctl_get_prkey(lun, i))
8250					continue;
8251
8252				ctl_clr_prkey(lun, i);
8253				lun->pr_key_count--;
8254				ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8255			}
8256		}
8257	} else {
8258		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8259			if (i == msg->pr.pr_info.residx ||
8260			    ctl_get_prkey(lun, i) == 0)
8261				continue;
8262
8263			if (sa_res_key == ctl_get_prkey(lun, i)) {
8264				ctl_clr_prkey(lun, i);
8265				lun->pr_key_count--;
8266				ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8267			} else if (msg->pr.pr_info.res_type != lun->res_type
8268				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8269				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8270				ctl_set_res_ua(lun, i, CTL_UA_RES_RELEASE);
8271			}
8272		}
8273		lun->res_type = msg->pr.pr_info.res_type;
8274		if (lun->res_type != SPR_TYPE_WR_EX_AR
8275		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8276			lun->pr_res_idx = msg->pr.pr_info.residx;
8277		else
8278			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8279	}
8280	lun->PRGeneration++;
8281
8282}
8283
8284
8285int
8286ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8287{
8288	int retval;
8289	int isc_retval;
8290	u_int32_t param_len;
8291	struct scsi_per_res_out *cdb;
8292	struct ctl_lun *lun;
8293	struct scsi_per_res_out_parms* param;
8294	struct ctl_softc *softc;
8295	uint32_t residx;
8296	uint64_t res_key, sa_res_key, key;
8297	uint8_t type;
8298	union ctl_ha_msg persis_io;
8299	int    i;
8300
8301	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8302
8303	retval = CTL_RETVAL_COMPLETE;
8304
8305	softc = control_softc;
8306
8307	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8308	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8309
8310	/*
8311	 * We only support whole-LUN scope.  The scope & type are ignored for
8312	 * register, register and ignore existing key and clear.
8313	 * We sometimes ignore scope and type on preempts too!!
8314	 * Verify reservation type here as well.
8315	 */
8316	type = cdb->scope_type & SPR_TYPE_MASK;
8317	if ((cdb->action == SPRO_RESERVE)
8318	 || (cdb->action == SPRO_RELEASE)) {
8319		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8320			ctl_set_invalid_field(/*ctsio*/ ctsio,
8321					      /*sks_valid*/ 1,
8322					      /*command*/ 1,
8323					      /*field*/ 2,
8324					      /*bit_valid*/ 1,
8325					      /*bit*/ 4);
8326			ctl_done((union ctl_io *)ctsio);
8327			return (CTL_RETVAL_COMPLETE);
8328		}
8329
8330		if (type>8 || type==2 || type==4 || type==0) {
8331			ctl_set_invalid_field(/*ctsio*/ ctsio,
8332					      /*sks_valid*/ 1,
8333					      /*command*/ 1,
8334					      /*field*/ 2,
8335					      /*bit_valid*/ 1,
8336					      /*bit*/ 0);
8337			ctl_done((union ctl_io *)ctsio);
8338			return (CTL_RETVAL_COMPLETE);
8339		}
8340	}
8341
8342	param_len = scsi_4btoul(cdb->length);
8343
8344	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8345		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8346		ctsio->kern_data_len = param_len;
8347		ctsio->kern_total_len = param_len;
8348		ctsio->kern_data_resid = 0;
8349		ctsio->kern_rel_offset = 0;
8350		ctsio->kern_sg_entries = 0;
8351		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8352		ctsio->be_move_done = ctl_config_move_done;
8353		ctl_datamove((union ctl_io *)ctsio);
8354
8355		return (CTL_RETVAL_COMPLETE);
8356	}
8357
8358	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8359
8360	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8361	res_key = scsi_8btou64(param->res_key.key);
8362	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8363
8364	/*
8365	 * Validate the reservation key here except for SPRO_REG_IGNO
8366	 * This must be done for all other service actions
8367	 */
8368	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8369		mtx_lock(&lun->lun_lock);
8370		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8371			if (res_key != key) {
8372				/*
8373				 * The current key passed in doesn't match
8374				 * the one the initiator previously
8375				 * registered.
8376				 */
8377				mtx_unlock(&lun->lun_lock);
8378				free(ctsio->kern_data_ptr, M_CTL);
8379				ctl_set_reservation_conflict(ctsio);
8380				ctl_done((union ctl_io *)ctsio);
8381				return (CTL_RETVAL_COMPLETE);
8382			}
8383		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8384			/*
8385			 * We are not registered
8386			 */
8387			mtx_unlock(&lun->lun_lock);
8388			free(ctsio->kern_data_ptr, M_CTL);
8389			ctl_set_reservation_conflict(ctsio);
8390			ctl_done((union ctl_io *)ctsio);
8391			return (CTL_RETVAL_COMPLETE);
8392		} else if (res_key != 0) {
8393			/*
8394			 * We are not registered and trying to register but
8395			 * the register key isn't zero.
8396			 */
8397			mtx_unlock(&lun->lun_lock);
8398			free(ctsio->kern_data_ptr, M_CTL);
8399			ctl_set_reservation_conflict(ctsio);
8400			ctl_done((union ctl_io *)ctsio);
8401			return (CTL_RETVAL_COMPLETE);
8402		}
8403		mtx_unlock(&lun->lun_lock);
8404	}
8405
8406	switch (cdb->action & SPRO_ACTION_MASK) {
8407	case SPRO_REGISTER:
8408	case SPRO_REG_IGNO: {
8409
8410#if 0
8411		printf("Registration received\n");
8412#endif
8413
8414		/*
8415		 * We don't support any of these options, as we report in
8416		 * the read capabilities request (see
8417		 * ctl_persistent_reserve_in(), above).
8418		 */
8419		if ((param->flags & SPR_SPEC_I_PT)
8420		 || (param->flags & SPR_ALL_TG_PT)
8421		 || (param->flags & SPR_APTPL)) {
8422			int bit_ptr;
8423
8424			if (param->flags & SPR_APTPL)
8425				bit_ptr = 0;
8426			else if (param->flags & SPR_ALL_TG_PT)
8427				bit_ptr = 2;
8428			else /* SPR_SPEC_I_PT */
8429				bit_ptr = 3;
8430
8431			free(ctsio->kern_data_ptr, M_CTL);
8432			ctl_set_invalid_field(ctsio,
8433					      /*sks_valid*/ 1,
8434					      /*command*/ 0,
8435					      /*field*/ 20,
8436					      /*bit_valid*/ 1,
8437					      /*bit*/ bit_ptr);
8438			ctl_done((union ctl_io *)ctsio);
8439			return (CTL_RETVAL_COMPLETE);
8440		}
8441
8442		mtx_lock(&lun->lun_lock);
8443
8444		/*
8445		 * The initiator wants to clear the
8446		 * key/unregister.
8447		 */
8448		if (sa_res_key == 0) {
8449			if ((res_key == 0
8450			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8451			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8452			  && ctl_get_prkey(lun, residx) == 0)) {
8453				mtx_unlock(&lun->lun_lock);
8454				goto done;
8455			}
8456
8457			ctl_clr_prkey(lun, residx);
8458			lun->pr_key_count--;
8459
8460			if (residx == lun->pr_res_idx) {
8461				lun->flags &= ~CTL_LUN_PR_RESERVED;
8462				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8463
8464				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8465				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8466				 && lun->pr_key_count) {
8467					/*
8468					 * If the reservation is a registrants
8469					 * only type we need to generate a UA
8470					 * for other registered inits.  The
8471					 * sense code should be RESERVATIONS
8472					 * RELEASED
8473					 */
8474
8475					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8476						if (ctl_get_prkey(lun, i +
8477						    softc->persis_offset) == 0)
8478							continue;
8479						lun->pending_ua[i] |=
8480							CTL_UA_RES_RELEASE;
8481					}
8482				}
8483				lun->res_type = 0;
8484			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8485				if (lun->pr_key_count==0) {
8486					lun->flags &= ~CTL_LUN_PR_RESERVED;
8487					lun->res_type = 0;
8488					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8489				}
8490			}
8491			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8492			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8493			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8494			persis_io.pr.pr_info.residx = residx;
8495			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8496			     &persis_io, sizeof(persis_io), 0 )) >
8497			     CTL_HA_STATUS_SUCCESS) {
8498				printf("CTL:Persis Out error returned from "
8499				       "ctl_ha_msg_send %d\n", isc_retval);
8500			}
8501		} else /* sa_res_key != 0 */ {
8502
8503			/*
8504			 * If we aren't registered currently then increment
8505			 * the key count and set the registered flag.
8506			 */
8507			ctl_alloc_prkey(lun, residx);
8508			if (ctl_get_prkey(lun, residx) == 0)
8509				lun->pr_key_count++;
8510			ctl_set_prkey(lun, residx, sa_res_key);
8511
8512			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8513			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8514			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8515			persis_io.pr.pr_info.residx = residx;
8516			memcpy(persis_io.pr.pr_info.sa_res_key,
8517			       param->serv_act_res_key,
8518			       sizeof(param->serv_act_res_key));
8519			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8520			     &persis_io, sizeof(persis_io), 0)) >
8521			     CTL_HA_STATUS_SUCCESS) {
8522				printf("CTL:Persis Out error returned from "
8523				       "ctl_ha_msg_send %d\n", isc_retval);
8524			}
8525		}
8526		lun->PRGeneration++;
8527		mtx_unlock(&lun->lun_lock);
8528
8529		break;
8530	}
8531	case SPRO_RESERVE:
8532#if 0
8533                printf("Reserve executed type %d\n", type);
8534#endif
8535		mtx_lock(&lun->lun_lock);
8536		if (lun->flags & CTL_LUN_PR_RESERVED) {
8537			/*
8538			 * if this isn't the reservation holder and it's
8539			 * not a "all registrants" type or if the type is
8540			 * different then we have a conflict
8541			 */
8542			if ((lun->pr_res_idx != residx
8543			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8544			 || lun->res_type != type) {
8545				mtx_unlock(&lun->lun_lock);
8546				free(ctsio->kern_data_ptr, M_CTL);
8547				ctl_set_reservation_conflict(ctsio);
8548				ctl_done((union ctl_io *)ctsio);
8549				return (CTL_RETVAL_COMPLETE);
8550			}
8551			mtx_unlock(&lun->lun_lock);
8552		} else /* create a reservation */ {
8553			/*
8554			 * If it's not an "all registrants" type record
8555			 * reservation holder
8556			 */
8557			if (type != SPR_TYPE_WR_EX_AR
8558			 && type != SPR_TYPE_EX_AC_AR)
8559				lun->pr_res_idx = residx; /* Res holder */
8560			else
8561				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8562
8563			lun->flags |= CTL_LUN_PR_RESERVED;
8564			lun->res_type = type;
8565
8566			mtx_unlock(&lun->lun_lock);
8567
8568			/* send msg to other side */
8569			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8570			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8571			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8572			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8573			persis_io.pr.pr_info.res_type = type;
8574			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8575			     &persis_io, sizeof(persis_io), 0)) >
8576			     CTL_HA_STATUS_SUCCESS) {
8577				printf("CTL:Persis Out error returned from "
8578				       "ctl_ha_msg_send %d\n", isc_retval);
8579			}
8580		}
8581		break;
8582
8583	case SPRO_RELEASE:
8584		mtx_lock(&lun->lun_lock);
8585		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8586			/* No reservation exists return good status */
8587			mtx_unlock(&lun->lun_lock);
8588			goto done;
8589		}
8590		/*
8591		 * Is this nexus a reservation holder?
8592		 */
8593		if (lun->pr_res_idx != residx
8594		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8595			/*
8596			 * not a res holder return good status but
8597			 * do nothing
8598			 */
8599			mtx_unlock(&lun->lun_lock);
8600			goto done;
8601		}
8602
8603		if (lun->res_type != type) {
8604			mtx_unlock(&lun->lun_lock);
8605			free(ctsio->kern_data_ptr, M_CTL);
8606			ctl_set_illegal_pr_release(ctsio);
8607			ctl_done((union ctl_io *)ctsio);
8608			return (CTL_RETVAL_COMPLETE);
8609		}
8610
8611		/* okay to release */
8612		lun->flags &= ~CTL_LUN_PR_RESERVED;
8613		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8614		lun->res_type = 0;
8615
8616		/*
8617		 * if this isn't an exclusive access
8618		 * res generate UA for all other
8619		 * registrants.
8620		 */
8621		if (type != SPR_TYPE_EX_AC
8622		 && type != SPR_TYPE_WR_EX) {
8623			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8624				if (i == residx ||
8625				    ctl_get_prkey(lun,
8626				     i + softc->persis_offset) == 0)
8627					continue;
8628				lun->pending_ua[i] |= CTL_UA_RES_RELEASE;
8629			}
8630		}
8631		mtx_unlock(&lun->lun_lock);
8632		/* Send msg to other side */
8633		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8634		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8635		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8636		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8637		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8638			printf("CTL:Persis Out error returned from "
8639			       "ctl_ha_msg_send %d\n", isc_retval);
8640		}
8641		break;
8642
8643	case SPRO_CLEAR:
8644		/* send msg to other side */
8645
8646		mtx_lock(&lun->lun_lock);
8647		lun->flags &= ~CTL_LUN_PR_RESERVED;
8648		lun->res_type = 0;
8649		lun->pr_key_count = 0;
8650		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8651
8652		ctl_clr_prkey(lun, residx);
8653		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8654			if (ctl_get_prkey(lun, i) != 0) {
8655				ctl_clr_prkey(lun, i);
8656				ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8657			}
8658		lun->PRGeneration++;
8659		mtx_unlock(&lun->lun_lock);
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_CLEAR;
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_PREEMPT:
8671	case SPRO_PRE_ABO: {
8672		int nretval;
8673
8674		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8675					  residx, ctsio, cdb, param);
8676		if (nretval != 0)
8677			return (CTL_RETVAL_COMPLETE);
8678		break;
8679	}
8680	default:
8681		panic("Invalid PR type %x", cdb->action);
8682	}
8683
8684done:
8685	free(ctsio->kern_data_ptr, M_CTL);
8686	ctl_set_success(ctsio);
8687	ctl_done((union ctl_io *)ctsio);
8688
8689	return (retval);
8690}
8691
8692/*
8693 * This routine is for handling a message from the other SC pertaining to
8694 * persistent reserve out. All the error checking will have been done
8695 * so only perorming the action need be done here to keep the two
8696 * in sync.
8697 */
8698static void
8699ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8700{
8701	struct ctl_lun *lun;
8702	struct ctl_softc *softc;
8703	int i;
8704	uint32_t targ_lun;
8705
8706	softc = control_softc;
8707
8708	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8709	lun = softc->ctl_luns[targ_lun];
8710	mtx_lock(&lun->lun_lock);
8711	switch(msg->pr.pr_info.action) {
8712	case CTL_PR_REG_KEY:
8713		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8714		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8715			lun->pr_key_count++;
8716		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8717		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8718		lun->PRGeneration++;
8719		break;
8720
8721	case CTL_PR_UNREG_KEY:
8722		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8723		lun->pr_key_count--;
8724
8725		/* XXX Need to see if the reservation has been released */
8726		/* if so do we need to generate UA? */
8727		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8728			lun->flags &= ~CTL_LUN_PR_RESERVED;
8729			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8730
8731			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8732			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8733			 && lun->pr_key_count) {
8734				/*
8735				 * If the reservation is a registrants
8736				 * only type we need to generate a UA
8737				 * for other registered inits.  The
8738				 * sense code should be RESERVATIONS
8739				 * RELEASED
8740				 */
8741
8742				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8743					if (ctl_get_prkey(lun, i +
8744					    softc->persis_offset) == 0)
8745						continue;
8746
8747					lun->pending_ua[i] |=
8748						CTL_UA_RES_RELEASE;
8749				}
8750			}
8751			lun->res_type = 0;
8752		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8753			if (lun->pr_key_count==0) {
8754				lun->flags &= ~CTL_LUN_PR_RESERVED;
8755				lun->res_type = 0;
8756				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8757			}
8758		}
8759		lun->PRGeneration++;
8760		break;
8761
8762	case CTL_PR_RESERVE:
8763		lun->flags |= CTL_LUN_PR_RESERVED;
8764		lun->res_type = msg->pr.pr_info.res_type;
8765		lun->pr_res_idx = msg->pr.pr_info.residx;
8766
8767		break;
8768
8769	case CTL_PR_RELEASE:
8770		/*
8771		 * if this isn't an exclusive access res generate UA for all
8772		 * other registrants.
8773		 */
8774		if (lun->res_type != SPR_TYPE_EX_AC
8775		 && lun->res_type != SPR_TYPE_WR_EX) {
8776			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8777				if (ctl_get_prkey(lun, i + softc->persis_offset) != 0)
8778					lun->pending_ua[i] |=
8779						CTL_UA_RES_RELEASE;
8780		}
8781
8782		lun->flags &= ~CTL_LUN_PR_RESERVED;
8783		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8784		lun->res_type = 0;
8785		break;
8786
8787	case CTL_PR_PREEMPT:
8788		ctl_pro_preempt_other(lun, msg);
8789		break;
8790	case CTL_PR_CLEAR:
8791		lun->flags &= ~CTL_LUN_PR_RESERVED;
8792		lun->res_type = 0;
8793		lun->pr_key_count = 0;
8794		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8795
8796		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8797			if (ctl_get_prkey(lun, i) == 0)
8798				continue;
8799			ctl_clr_prkey(lun, i);
8800			ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8801		}
8802		lun->PRGeneration++;
8803		break;
8804	}
8805
8806	mtx_unlock(&lun->lun_lock);
8807}
8808
8809int
8810ctl_read_write(struct ctl_scsiio *ctsio)
8811{
8812	struct ctl_lun *lun;
8813	struct ctl_lba_len_flags *lbalen;
8814	uint64_t lba;
8815	uint32_t num_blocks;
8816	int flags, retval;
8817	int isread;
8818
8819	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8820
8821	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8822
8823	flags = 0;
8824	retval = CTL_RETVAL_COMPLETE;
8825
8826	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8827	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8828	switch (ctsio->cdb[0]) {
8829	case READ_6:
8830	case WRITE_6: {
8831		struct scsi_rw_6 *cdb;
8832
8833		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8834
8835		lba = scsi_3btoul(cdb->addr);
8836		/* only 5 bits are valid in the most significant address byte */
8837		lba &= 0x1fffff;
8838		num_blocks = cdb->length;
8839		/*
8840		 * This is correct according to SBC-2.
8841		 */
8842		if (num_blocks == 0)
8843			num_blocks = 256;
8844		break;
8845	}
8846	case READ_10:
8847	case WRITE_10: {
8848		struct scsi_rw_10 *cdb;
8849
8850		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8851		if (cdb->byte2 & SRW10_FUA)
8852			flags |= CTL_LLF_FUA;
8853		if (cdb->byte2 & SRW10_DPO)
8854			flags |= CTL_LLF_DPO;
8855		lba = scsi_4btoul(cdb->addr);
8856		num_blocks = scsi_2btoul(cdb->length);
8857		break;
8858	}
8859	case WRITE_VERIFY_10: {
8860		struct scsi_write_verify_10 *cdb;
8861
8862		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8863		flags |= CTL_LLF_FUA;
8864		if (cdb->byte2 & SWV_DPO)
8865			flags |= CTL_LLF_DPO;
8866		lba = scsi_4btoul(cdb->addr);
8867		num_blocks = scsi_2btoul(cdb->length);
8868		break;
8869	}
8870	case READ_12:
8871	case WRITE_12: {
8872		struct scsi_rw_12 *cdb;
8873
8874		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8875		if (cdb->byte2 & SRW12_FUA)
8876			flags |= CTL_LLF_FUA;
8877		if (cdb->byte2 & SRW12_DPO)
8878			flags |= CTL_LLF_DPO;
8879		lba = scsi_4btoul(cdb->addr);
8880		num_blocks = scsi_4btoul(cdb->length);
8881		break;
8882	}
8883	case WRITE_VERIFY_12: {
8884		struct scsi_write_verify_12 *cdb;
8885
8886		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8887		flags |= CTL_LLF_FUA;
8888		if (cdb->byte2 & SWV_DPO)
8889			flags |= CTL_LLF_DPO;
8890		lba = scsi_4btoul(cdb->addr);
8891		num_blocks = scsi_4btoul(cdb->length);
8892		break;
8893	}
8894	case READ_16:
8895	case WRITE_16: {
8896		struct scsi_rw_16 *cdb;
8897
8898		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8899		if (cdb->byte2 & SRW12_FUA)
8900			flags |= CTL_LLF_FUA;
8901		if (cdb->byte2 & SRW12_DPO)
8902			flags |= CTL_LLF_DPO;
8903		lba = scsi_8btou64(cdb->addr);
8904		num_blocks = scsi_4btoul(cdb->length);
8905		break;
8906	}
8907	case WRITE_ATOMIC_16: {
8908		struct scsi_rw_16 *cdb;
8909
8910		if (lun->be_lun->atomicblock == 0) {
8911			ctl_set_invalid_opcode(ctsio);
8912			ctl_done((union ctl_io *)ctsio);
8913			return (CTL_RETVAL_COMPLETE);
8914		}
8915
8916		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8917		if (cdb->byte2 & SRW12_FUA)
8918			flags |= CTL_LLF_FUA;
8919		if (cdb->byte2 & SRW12_DPO)
8920			flags |= CTL_LLF_DPO;
8921		lba = scsi_8btou64(cdb->addr);
8922		num_blocks = scsi_4btoul(cdb->length);
8923		if (num_blocks > lun->be_lun->atomicblock) {
8924			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8925			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8926			    /*bit*/ 0);
8927			ctl_done((union ctl_io *)ctsio);
8928			return (CTL_RETVAL_COMPLETE);
8929		}
8930		break;
8931	}
8932	case WRITE_VERIFY_16: {
8933		struct scsi_write_verify_16 *cdb;
8934
8935		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8936		flags |= CTL_LLF_FUA;
8937		if (cdb->byte2 & SWV_DPO)
8938			flags |= CTL_LLF_DPO;
8939		lba = scsi_8btou64(cdb->addr);
8940		num_blocks = scsi_4btoul(cdb->length);
8941		break;
8942	}
8943	default:
8944		/*
8945		 * We got a command we don't support.  This shouldn't
8946		 * happen, commands should be filtered out above us.
8947		 */
8948		ctl_set_invalid_opcode(ctsio);
8949		ctl_done((union ctl_io *)ctsio);
8950
8951		return (CTL_RETVAL_COMPLETE);
8952		break; /* NOTREACHED */
8953	}
8954
8955	/*
8956	 * The first check is to make sure we're in bounds, the second
8957	 * check is to catch wrap-around problems.  If the lba + num blocks
8958	 * is less than the lba, then we've wrapped around and the block
8959	 * range is invalid anyway.
8960	 */
8961	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8962	 || ((lba + num_blocks) < lba)) {
8963		ctl_set_lba_out_of_range(ctsio);
8964		ctl_done((union ctl_io *)ctsio);
8965		return (CTL_RETVAL_COMPLETE);
8966	}
8967
8968	/*
8969	 * According to SBC-3, a transfer length of 0 is not an error.
8970	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8971	 * translates to 256 blocks for those commands.
8972	 */
8973	if (num_blocks == 0) {
8974		ctl_set_success(ctsio);
8975		ctl_done((union ctl_io *)ctsio);
8976		return (CTL_RETVAL_COMPLETE);
8977	}
8978
8979	/* Set FUA and/or DPO if caches are disabled. */
8980	if (isread) {
8981		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8982		    SCP_RCD) != 0)
8983			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8984	} else {
8985		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8986		    SCP_WCE) == 0)
8987			flags |= CTL_LLF_FUA;
8988	}
8989
8990	lbalen = (struct ctl_lba_len_flags *)
8991	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8992	lbalen->lba = lba;
8993	lbalen->len = num_blocks;
8994	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8995
8996	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8997	ctsio->kern_rel_offset = 0;
8998
8999	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9000
9001	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9002
9003	return (retval);
9004}
9005
9006static int
9007ctl_cnw_cont(union ctl_io *io)
9008{
9009	struct ctl_scsiio *ctsio;
9010	struct ctl_lun *lun;
9011	struct ctl_lba_len_flags *lbalen;
9012	int retval;
9013
9014	ctsio = &io->scsiio;
9015	ctsio->io_hdr.status = CTL_STATUS_NONE;
9016	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9017	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9018	lbalen = (struct ctl_lba_len_flags *)
9019	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9020	lbalen->flags &= ~CTL_LLF_COMPARE;
9021	lbalen->flags |= CTL_LLF_WRITE;
9022
9023	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9024	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9025	return (retval);
9026}
9027
9028int
9029ctl_cnw(struct ctl_scsiio *ctsio)
9030{
9031	struct ctl_lun *lun;
9032	struct ctl_lba_len_flags *lbalen;
9033	uint64_t lba;
9034	uint32_t num_blocks;
9035	int flags, retval;
9036
9037	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9038
9039	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9040
9041	flags = 0;
9042	retval = CTL_RETVAL_COMPLETE;
9043
9044	switch (ctsio->cdb[0]) {
9045	case COMPARE_AND_WRITE: {
9046		struct scsi_compare_and_write *cdb;
9047
9048		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9049		if (cdb->byte2 & SRW10_FUA)
9050			flags |= CTL_LLF_FUA;
9051		if (cdb->byte2 & SRW10_DPO)
9052			flags |= CTL_LLF_DPO;
9053		lba = scsi_8btou64(cdb->addr);
9054		num_blocks = cdb->length;
9055		break;
9056	}
9057	default:
9058		/*
9059		 * We got a command we don't support.  This shouldn't
9060		 * happen, commands should be filtered out above us.
9061		 */
9062		ctl_set_invalid_opcode(ctsio);
9063		ctl_done((union ctl_io *)ctsio);
9064
9065		return (CTL_RETVAL_COMPLETE);
9066		break; /* NOTREACHED */
9067	}
9068
9069	/*
9070	 * The first check is to make sure we're in bounds, the second
9071	 * check is to catch wrap-around problems.  If the lba + num blocks
9072	 * is less than the lba, then we've wrapped around and the block
9073	 * range is invalid anyway.
9074	 */
9075	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9076	 || ((lba + num_blocks) < lba)) {
9077		ctl_set_lba_out_of_range(ctsio);
9078		ctl_done((union ctl_io *)ctsio);
9079		return (CTL_RETVAL_COMPLETE);
9080	}
9081
9082	/*
9083	 * According to SBC-3, a transfer length of 0 is not an error.
9084	 */
9085	if (num_blocks == 0) {
9086		ctl_set_success(ctsio);
9087		ctl_done((union ctl_io *)ctsio);
9088		return (CTL_RETVAL_COMPLETE);
9089	}
9090
9091	/* Set FUA if write cache is disabled. */
9092	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9093	    SCP_WCE) == 0)
9094		flags |= CTL_LLF_FUA;
9095
9096	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9097	ctsio->kern_rel_offset = 0;
9098
9099	/*
9100	 * Set the IO_CONT flag, so that if this I/O gets passed to
9101	 * ctl_data_submit_done(), it'll get passed back to
9102	 * ctl_ctl_cnw_cont() for further processing.
9103	 */
9104	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9105	ctsio->io_cont = ctl_cnw_cont;
9106
9107	lbalen = (struct ctl_lba_len_flags *)
9108	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9109	lbalen->lba = lba;
9110	lbalen->len = num_blocks;
9111	lbalen->flags = CTL_LLF_COMPARE | flags;
9112
9113	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9114	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9115	return (retval);
9116}
9117
9118int
9119ctl_verify(struct ctl_scsiio *ctsio)
9120{
9121	struct ctl_lun *lun;
9122	struct ctl_lba_len_flags *lbalen;
9123	uint64_t lba;
9124	uint32_t num_blocks;
9125	int bytchk, flags;
9126	int retval;
9127
9128	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9129
9130	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9131
9132	bytchk = 0;
9133	flags = CTL_LLF_FUA;
9134	retval = CTL_RETVAL_COMPLETE;
9135
9136	switch (ctsio->cdb[0]) {
9137	case VERIFY_10: {
9138		struct scsi_verify_10 *cdb;
9139
9140		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9141		if (cdb->byte2 & SVFY_BYTCHK)
9142			bytchk = 1;
9143		if (cdb->byte2 & SVFY_DPO)
9144			flags |= CTL_LLF_DPO;
9145		lba = scsi_4btoul(cdb->addr);
9146		num_blocks = scsi_2btoul(cdb->length);
9147		break;
9148	}
9149	case VERIFY_12: {
9150		struct scsi_verify_12 *cdb;
9151
9152		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9153		if (cdb->byte2 & SVFY_BYTCHK)
9154			bytchk = 1;
9155		if (cdb->byte2 & SVFY_DPO)
9156			flags |= CTL_LLF_DPO;
9157		lba = scsi_4btoul(cdb->addr);
9158		num_blocks = scsi_4btoul(cdb->length);
9159		break;
9160	}
9161	case VERIFY_16: {
9162		struct scsi_rw_16 *cdb;
9163
9164		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9165		if (cdb->byte2 & SVFY_BYTCHK)
9166			bytchk = 1;
9167		if (cdb->byte2 & SVFY_DPO)
9168			flags |= CTL_LLF_DPO;
9169		lba = scsi_8btou64(cdb->addr);
9170		num_blocks = scsi_4btoul(cdb->length);
9171		break;
9172	}
9173	default:
9174		/*
9175		 * We got a command we don't support.  This shouldn't
9176		 * happen, commands should be filtered out above us.
9177		 */
9178		ctl_set_invalid_opcode(ctsio);
9179		ctl_done((union ctl_io *)ctsio);
9180		return (CTL_RETVAL_COMPLETE);
9181	}
9182
9183	/*
9184	 * The first check is to make sure we're in bounds, the second
9185	 * check is to catch wrap-around problems.  If the lba + num blocks
9186	 * is less than the lba, then we've wrapped around and the block
9187	 * range is invalid anyway.
9188	 */
9189	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9190	 || ((lba + num_blocks) < lba)) {
9191		ctl_set_lba_out_of_range(ctsio);
9192		ctl_done((union ctl_io *)ctsio);
9193		return (CTL_RETVAL_COMPLETE);
9194	}
9195
9196	/*
9197	 * According to SBC-3, a transfer length of 0 is not an error.
9198	 */
9199	if (num_blocks == 0) {
9200		ctl_set_success(ctsio);
9201		ctl_done((union ctl_io *)ctsio);
9202		return (CTL_RETVAL_COMPLETE);
9203	}
9204
9205	lbalen = (struct ctl_lba_len_flags *)
9206	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9207	lbalen->lba = lba;
9208	lbalen->len = num_blocks;
9209	if (bytchk) {
9210		lbalen->flags = CTL_LLF_COMPARE | flags;
9211		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9212	} else {
9213		lbalen->flags = CTL_LLF_VERIFY | flags;
9214		ctsio->kern_total_len = 0;
9215	}
9216	ctsio->kern_rel_offset = 0;
9217
9218	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9219	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9220	return (retval);
9221}
9222
9223int
9224ctl_report_luns(struct ctl_scsiio *ctsio)
9225{
9226	struct scsi_report_luns *cdb;
9227	struct scsi_report_luns_data *lun_data;
9228	struct ctl_lun *lun, *request_lun;
9229	int num_luns, retval;
9230	uint32_t alloc_len, lun_datalen;
9231	int num_filled, well_known;
9232	uint32_t initidx, targ_lun_id, lun_id;
9233
9234	retval = CTL_RETVAL_COMPLETE;
9235	well_known = 0;
9236
9237	cdb = (struct scsi_report_luns *)ctsio->cdb;
9238
9239	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9240
9241	mtx_lock(&control_softc->ctl_lock);
9242	num_luns = control_softc->num_luns;
9243	mtx_unlock(&control_softc->ctl_lock);
9244
9245	switch (cdb->select_report) {
9246	case RPL_REPORT_DEFAULT:
9247	case RPL_REPORT_ALL:
9248		break;
9249	case RPL_REPORT_WELLKNOWN:
9250		well_known = 1;
9251		num_luns = 0;
9252		break;
9253	default:
9254		ctl_set_invalid_field(ctsio,
9255				      /*sks_valid*/ 1,
9256				      /*command*/ 1,
9257				      /*field*/ 2,
9258				      /*bit_valid*/ 0,
9259				      /*bit*/ 0);
9260		ctl_done((union ctl_io *)ctsio);
9261		return (retval);
9262		break; /* NOTREACHED */
9263	}
9264
9265	alloc_len = scsi_4btoul(cdb->length);
9266	/*
9267	 * The initiator has to allocate at least 16 bytes for this request,
9268	 * so he can at least get the header and the first LUN.  Otherwise
9269	 * we reject the request (per SPC-3 rev 14, section 6.21).
9270	 */
9271	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9272	    sizeof(struct scsi_report_luns_lundata))) {
9273		ctl_set_invalid_field(ctsio,
9274				      /*sks_valid*/ 1,
9275				      /*command*/ 1,
9276				      /*field*/ 6,
9277				      /*bit_valid*/ 0,
9278				      /*bit*/ 0);
9279		ctl_done((union ctl_io *)ctsio);
9280		return (retval);
9281	}
9282
9283	request_lun = (struct ctl_lun *)
9284		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9285
9286	lun_datalen = sizeof(*lun_data) +
9287		(num_luns * sizeof(struct scsi_report_luns_lundata));
9288
9289	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9290	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9291	ctsio->kern_sg_entries = 0;
9292
9293	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9294
9295	mtx_lock(&control_softc->ctl_lock);
9296	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9297		lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9298		if (lun_id >= CTL_MAX_LUNS)
9299			continue;
9300		lun = control_softc->ctl_luns[lun_id];
9301		if (lun == NULL)
9302			continue;
9303
9304		if (targ_lun_id <= 0xff) {
9305			/*
9306			 * Peripheral addressing method, bus number 0.
9307			 */
9308			lun_data->luns[num_filled].lundata[0] =
9309				RPL_LUNDATA_ATYP_PERIPH;
9310			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9311			num_filled++;
9312		} else if (targ_lun_id <= 0x3fff) {
9313			/*
9314			 * Flat addressing method.
9315			 */
9316			lun_data->luns[num_filled].lundata[0] =
9317				RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9318			lun_data->luns[num_filled].lundata[1] =
9319				(targ_lun_id & 0xff);
9320			num_filled++;
9321		} else if (targ_lun_id <= 0xffffff) {
9322			/*
9323			 * Extended flat addressing method.
9324			 */
9325			lun_data->luns[num_filled].lundata[0] =
9326			    RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9327			scsi_ulto3b(targ_lun_id,
9328			    &lun_data->luns[num_filled].lundata[1]);
9329			num_filled++;
9330		} else {
9331			printf("ctl_report_luns: bogus LUN number %jd, "
9332			       "skipping\n", (intmax_t)targ_lun_id);
9333		}
9334		/*
9335		 * According to SPC-3, rev 14 section 6.21:
9336		 *
9337		 * "The execution of a REPORT LUNS command to any valid and
9338		 * installed logical unit shall clear the REPORTED LUNS DATA
9339		 * HAS CHANGED unit attention condition for all logical
9340		 * units of that target with respect to the requesting
9341		 * initiator. A valid and installed logical unit is one
9342		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9343		 * INQUIRY data (see 6.4.2)."
9344		 *
9345		 * If request_lun is NULL, the LUN this report luns command
9346		 * was issued to is either disabled or doesn't exist. In that
9347		 * case, we shouldn't clear any pending lun change unit
9348		 * attention.
9349		 */
9350		if (request_lun != NULL) {
9351			mtx_lock(&lun->lun_lock);
9352			lun->pending_ua[initidx] &= ~CTL_UA_LUN_CHANGE;
9353			mtx_unlock(&lun->lun_lock);
9354		}
9355	}
9356	mtx_unlock(&control_softc->ctl_lock);
9357
9358	/*
9359	 * It's quite possible that we've returned fewer LUNs than we allocated
9360	 * space for.  Trim it.
9361	 */
9362	lun_datalen = sizeof(*lun_data) +
9363		(num_filled * sizeof(struct scsi_report_luns_lundata));
9364
9365	if (lun_datalen < alloc_len) {
9366		ctsio->residual = alloc_len - lun_datalen;
9367		ctsio->kern_data_len = lun_datalen;
9368		ctsio->kern_total_len = lun_datalen;
9369	} else {
9370		ctsio->residual = 0;
9371		ctsio->kern_data_len = alloc_len;
9372		ctsio->kern_total_len = alloc_len;
9373	}
9374	ctsio->kern_data_resid = 0;
9375	ctsio->kern_rel_offset = 0;
9376	ctsio->kern_sg_entries = 0;
9377
9378	/*
9379	 * We set this to the actual data length, regardless of how much
9380	 * space we actually have to return results.  If the user looks at
9381	 * this value, he'll know whether or not he allocated enough space
9382	 * and reissue the command if necessary.  We don't support well
9383	 * known logical units, so if the user asks for that, return none.
9384	 */
9385	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9386
9387	/*
9388	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9389	 * this request.
9390	 */
9391	ctl_set_success(ctsio);
9392	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9393	ctsio->be_move_done = ctl_config_move_done;
9394	ctl_datamove((union ctl_io *)ctsio);
9395	return (retval);
9396}
9397
9398int
9399ctl_request_sense(struct ctl_scsiio *ctsio)
9400{
9401	struct scsi_request_sense *cdb;
9402	struct scsi_sense_data *sense_ptr;
9403	struct ctl_lun *lun;
9404	uint32_t initidx;
9405	int have_error;
9406	scsi_sense_data_type sense_format;
9407
9408	cdb = (struct scsi_request_sense *)ctsio->cdb;
9409
9410	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9411
9412	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9413
9414	/*
9415	 * Determine which sense format the user wants.
9416	 */
9417	if (cdb->byte2 & SRS_DESC)
9418		sense_format = SSD_TYPE_DESC;
9419	else
9420		sense_format = SSD_TYPE_FIXED;
9421
9422	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9423	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9424	ctsio->kern_sg_entries = 0;
9425
9426	/*
9427	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9428	 * larger than the largest allowed value for the length field in the
9429	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9430	 */
9431	ctsio->residual = 0;
9432	ctsio->kern_data_len = cdb->length;
9433	ctsio->kern_total_len = cdb->length;
9434
9435	ctsio->kern_data_resid = 0;
9436	ctsio->kern_rel_offset = 0;
9437	ctsio->kern_sg_entries = 0;
9438
9439	/*
9440	 * If we don't have a LUN, we don't have any pending sense.
9441	 */
9442	if (lun == NULL)
9443		goto no_sense;
9444
9445	have_error = 0;
9446	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9447	/*
9448	 * Check for pending sense, and then for pending unit attentions.
9449	 * Pending sense gets returned first, then pending unit attentions.
9450	 */
9451	mtx_lock(&lun->lun_lock);
9452#ifdef CTL_WITH_CA
9453	if (ctl_is_set(lun->have_ca, initidx)) {
9454		scsi_sense_data_type stored_format;
9455
9456		/*
9457		 * Check to see which sense format was used for the stored
9458		 * sense data.
9459		 */
9460		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9461
9462		/*
9463		 * If the user requested a different sense format than the
9464		 * one we stored, then we need to convert it to the other
9465		 * format.  If we're going from descriptor to fixed format
9466		 * sense data, we may lose things in translation, depending
9467		 * on what options were used.
9468		 *
9469		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9470		 * for some reason we'll just copy it out as-is.
9471		 */
9472		if ((stored_format == SSD_TYPE_FIXED)
9473		 && (sense_format == SSD_TYPE_DESC))
9474			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9475			    &lun->pending_sense[initidx],
9476			    (struct scsi_sense_data_desc *)sense_ptr);
9477		else if ((stored_format == SSD_TYPE_DESC)
9478		      && (sense_format == SSD_TYPE_FIXED))
9479			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9480			    &lun->pending_sense[initidx],
9481			    (struct scsi_sense_data_fixed *)sense_ptr);
9482		else
9483			memcpy(sense_ptr, &lun->pending_sense[initidx],
9484			       ctl_min(sizeof(*sense_ptr),
9485			       sizeof(lun->pending_sense[initidx])));
9486
9487		ctl_clear_mask(lun->have_ca, initidx);
9488		have_error = 1;
9489	} else
9490#endif
9491	if (lun->pending_ua[initidx] != CTL_UA_NONE) {
9492		ctl_ua_type ua_type;
9493
9494		ua_type = ctl_build_ua(&lun->pending_ua[initidx],
9495				       sense_ptr, sense_format);
9496		if (ua_type != CTL_UA_NONE)
9497			have_error = 1;
9498	}
9499	mtx_unlock(&lun->lun_lock);
9500
9501	/*
9502	 * We already have a pending error, return it.
9503	 */
9504	if (have_error != 0) {
9505		/*
9506		 * We report the SCSI status as OK, since the status of the
9507		 * request sense command itself is OK.
9508		 * We report 0 for the sense length, because we aren't doing
9509		 * autosense in this case.  We're reporting sense as
9510		 * parameter data.
9511		 */
9512		ctl_set_success(ctsio);
9513		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9514		ctsio->be_move_done = ctl_config_move_done;
9515		ctl_datamove((union ctl_io *)ctsio);
9516		return (CTL_RETVAL_COMPLETE);
9517	}
9518
9519no_sense:
9520
9521	/*
9522	 * No sense information to report, so we report that everything is
9523	 * okay.
9524	 */
9525	ctl_set_sense_data(sense_ptr,
9526			   lun,
9527			   sense_format,
9528			   /*current_error*/ 1,
9529			   /*sense_key*/ SSD_KEY_NO_SENSE,
9530			   /*asc*/ 0x00,
9531			   /*ascq*/ 0x00,
9532			   SSD_ELEM_NONE);
9533
9534	/*
9535	 * We report 0 for the sense length, because we aren't doing
9536	 * autosense in this case.  We're reporting sense as parameter data.
9537	 */
9538	ctl_set_success(ctsio);
9539	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9540	ctsio->be_move_done = ctl_config_move_done;
9541	ctl_datamove((union ctl_io *)ctsio);
9542	return (CTL_RETVAL_COMPLETE);
9543}
9544
9545int
9546ctl_tur(struct ctl_scsiio *ctsio)
9547{
9548
9549	CTL_DEBUG_PRINT(("ctl_tur\n"));
9550
9551	ctl_set_success(ctsio);
9552	ctl_done((union ctl_io *)ctsio);
9553
9554	return (CTL_RETVAL_COMPLETE);
9555}
9556
9557#ifdef notyet
9558static int
9559ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9560{
9561
9562}
9563#endif
9564
9565static int
9566ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9567{
9568	struct scsi_vpd_supported_pages *pages;
9569	int sup_page_size;
9570	struct ctl_lun *lun;
9571
9572	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9573
9574	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9575	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9576	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9577	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9578	ctsio->kern_sg_entries = 0;
9579
9580	if (sup_page_size < alloc_len) {
9581		ctsio->residual = alloc_len - sup_page_size;
9582		ctsio->kern_data_len = sup_page_size;
9583		ctsio->kern_total_len = sup_page_size;
9584	} else {
9585		ctsio->residual = 0;
9586		ctsio->kern_data_len = alloc_len;
9587		ctsio->kern_total_len = alloc_len;
9588	}
9589	ctsio->kern_data_resid = 0;
9590	ctsio->kern_rel_offset = 0;
9591	ctsio->kern_sg_entries = 0;
9592
9593	/*
9594	 * The control device is always connected.  The disk device, on the
9595	 * other hand, may not be online all the time.  Need to change this
9596	 * to figure out whether the disk device is actually online or not.
9597	 */
9598	if (lun != NULL)
9599		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9600				lun->be_lun->lun_type;
9601	else
9602		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9603
9604	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9605	/* Supported VPD pages */
9606	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9607	/* Serial Number */
9608	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9609	/* Device Identification */
9610	pages->page_list[2] = SVPD_DEVICE_ID;
9611	/* Extended INQUIRY Data */
9612	pages->page_list[3] = SVPD_EXTENDED_INQUIRY_DATA;
9613	/* Mode Page Policy */
9614	pages->page_list[4] = SVPD_MODE_PAGE_POLICY;
9615	/* SCSI Ports */
9616	pages->page_list[5] = SVPD_SCSI_PORTS;
9617	/* Third-party Copy */
9618	pages->page_list[6] = SVPD_SCSI_TPC;
9619	/* Block limits */
9620	pages->page_list[7] = SVPD_BLOCK_LIMITS;
9621	/* Block Device Characteristics */
9622	pages->page_list[8] = SVPD_BDC;
9623	/* Logical Block Provisioning */
9624	pages->page_list[9] = SVPD_LBP;
9625
9626	ctl_set_success(ctsio);
9627	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9628	ctsio->be_move_done = ctl_config_move_done;
9629	ctl_datamove((union ctl_io *)ctsio);
9630	return (CTL_RETVAL_COMPLETE);
9631}
9632
9633static int
9634ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9635{
9636	struct scsi_vpd_unit_serial_number *sn_ptr;
9637	struct ctl_lun *lun;
9638	int data_len;
9639
9640	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9641
9642	data_len = 4 + CTL_SN_LEN;
9643	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9644	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9645	if (data_len < alloc_len) {
9646		ctsio->residual = alloc_len - data_len;
9647		ctsio->kern_data_len = data_len;
9648		ctsio->kern_total_len = data_len;
9649	} else {
9650		ctsio->residual = 0;
9651		ctsio->kern_data_len = alloc_len;
9652		ctsio->kern_total_len = alloc_len;
9653	}
9654	ctsio->kern_data_resid = 0;
9655	ctsio->kern_rel_offset = 0;
9656	ctsio->kern_sg_entries = 0;
9657
9658	/*
9659	 * The control device is always connected.  The disk device, on the
9660	 * other hand, may not be online all the time.  Need to change this
9661	 * to figure out whether the disk device is actually online or not.
9662	 */
9663	if (lun != NULL)
9664		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9665				  lun->be_lun->lun_type;
9666	else
9667		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9668
9669	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9670	sn_ptr->length = CTL_SN_LEN;
9671	/*
9672	 * If we don't have a LUN, we just leave the serial number as
9673	 * all spaces.
9674	 */
9675	if (lun != NULL) {
9676		strncpy((char *)sn_ptr->serial_num,
9677			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9678	} else
9679		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9680
9681	ctl_set_success(ctsio);
9682	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9683	ctsio->be_move_done = ctl_config_move_done;
9684	ctl_datamove((union ctl_io *)ctsio);
9685	return (CTL_RETVAL_COMPLETE);
9686}
9687
9688
9689static int
9690ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9691{
9692	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9693	struct ctl_lun *lun;
9694	int data_len;
9695
9696	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9697
9698	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9699	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9700	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9701	ctsio->kern_sg_entries = 0;
9702
9703	if (data_len < alloc_len) {
9704		ctsio->residual = alloc_len - data_len;
9705		ctsio->kern_data_len = data_len;
9706		ctsio->kern_total_len = data_len;
9707	} else {
9708		ctsio->residual = 0;
9709		ctsio->kern_data_len = alloc_len;
9710		ctsio->kern_total_len = alloc_len;
9711	}
9712	ctsio->kern_data_resid = 0;
9713	ctsio->kern_rel_offset = 0;
9714	ctsio->kern_sg_entries = 0;
9715
9716	/*
9717	 * The control device is always connected.  The disk device, on the
9718	 * other hand, may not be online all the time.
9719	 */
9720	if (lun != NULL)
9721		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9722				     lun->be_lun->lun_type;
9723	else
9724		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9725	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9726	eid_ptr->page_length = data_len - 4;
9727	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9728	eid_ptr->flags3 = SVPD_EID_V_SUP;
9729
9730	ctl_set_success(ctsio);
9731	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9732	ctsio->be_move_done = ctl_config_move_done;
9733	ctl_datamove((union ctl_io *)ctsio);
9734	return (CTL_RETVAL_COMPLETE);
9735}
9736
9737static int
9738ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9739{
9740	struct scsi_vpd_mode_page_policy *mpp_ptr;
9741	struct ctl_lun *lun;
9742	int data_len;
9743
9744	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9745
9746	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9747	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9748
9749	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9750	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9751	ctsio->kern_sg_entries = 0;
9752
9753	if (data_len < alloc_len) {
9754		ctsio->residual = alloc_len - data_len;
9755		ctsio->kern_data_len = data_len;
9756		ctsio->kern_total_len = data_len;
9757	} else {
9758		ctsio->residual = 0;
9759		ctsio->kern_data_len = alloc_len;
9760		ctsio->kern_total_len = alloc_len;
9761	}
9762	ctsio->kern_data_resid = 0;
9763	ctsio->kern_rel_offset = 0;
9764	ctsio->kern_sg_entries = 0;
9765
9766	/*
9767	 * The control device is always connected.  The disk device, on the
9768	 * other hand, may not be online all the time.
9769	 */
9770	if (lun != NULL)
9771		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9772				     lun->be_lun->lun_type;
9773	else
9774		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9775	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9776	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9777	mpp_ptr->descr[0].page_code = 0x3f;
9778	mpp_ptr->descr[0].subpage_code = 0xff;
9779	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9780
9781	ctl_set_success(ctsio);
9782	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9783	ctsio->be_move_done = ctl_config_move_done;
9784	ctl_datamove((union ctl_io *)ctsio);
9785	return (CTL_RETVAL_COMPLETE);
9786}
9787
9788static int
9789ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9790{
9791	struct scsi_vpd_device_id *devid_ptr;
9792	struct scsi_vpd_id_descriptor *desc;
9793	struct ctl_softc *ctl_softc;
9794	struct ctl_lun *lun;
9795	struct ctl_port *port;
9796	int data_len;
9797	uint8_t proto;
9798
9799	ctl_softc = control_softc;
9800
9801	port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9802	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9803
9804	data_len = sizeof(struct scsi_vpd_device_id) +
9805	    sizeof(struct scsi_vpd_id_descriptor) +
9806		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9807	    sizeof(struct scsi_vpd_id_descriptor) +
9808		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9809	if (lun && lun->lun_devid)
9810		data_len += lun->lun_devid->len;
9811	if (port->port_devid)
9812		data_len += port->port_devid->len;
9813	if (port->target_devid)
9814		data_len += port->target_devid->len;
9815
9816	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9817	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9818	ctsio->kern_sg_entries = 0;
9819
9820	if (data_len < alloc_len) {
9821		ctsio->residual = alloc_len - data_len;
9822		ctsio->kern_data_len = data_len;
9823		ctsio->kern_total_len = data_len;
9824	} else {
9825		ctsio->residual = 0;
9826		ctsio->kern_data_len = alloc_len;
9827		ctsio->kern_total_len = alloc_len;
9828	}
9829	ctsio->kern_data_resid = 0;
9830	ctsio->kern_rel_offset = 0;
9831	ctsio->kern_sg_entries = 0;
9832
9833	/*
9834	 * The control device is always connected.  The disk device, on the
9835	 * other hand, may not be online all the time.
9836	 */
9837	if (lun != NULL)
9838		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9839				     lun->be_lun->lun_type;
9840	else
9841		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9842	devid_ptr->page_code = SVPD_DEVICE_ID;
9843	scsi_ulto2b(data_len - 4, devid_ptr->length);
9844
9845	if (port->port_type == CTL_PORT_FC)
9846		proto = SCSI_PROTO_FC << 4;
9847	else if (port->port_type == CTL_PORT_ISCSI)
9848		proto = SCSI_PROTO_ISCSI << 4;
9849	else
9850		proto = SCSI_PROTO_SPI << 4;
9851	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9852
9853	/*
9854	 * We're using a LUN association here.  i.e., this device ID is a
9855	 * per-LUN identifier.
9856	 */
9857	if (lun && lun->lun_devid) {
9858		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9859		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9860		    lun->lun_devid->len);
9861	}
9862
9863	/*
9864	 * This is for the WWPN which is a port association.
9865	 */
9866	if (port->port_devid) {
9867		memcpy(desc, port->port_devid->data, port->port_devid->len);
9868		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9869		    port->port_devid->len);
9870	}
9871
9872	/*
9873	 * This is for the Relative Target Port(type 4h) identifier
9874	 */
9875	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9876	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9877	    SVPD_ID_TYPE_RELTARG;
9878	desc->length = 4;
9879	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9880	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9881	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9882
9883	/*
9884	 * This is for the Target Port Group(type 5h) identifier
9885	 */
9886	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9887	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9888	    SVPD_ID_TYPE_TPORTGRP;
9889	desc->length = 4;
9890	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
9891	    &desc->identifier[2]);
9892	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9893	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9894
9895	/*
9896	 * This is for the Target identifier
9897	 */
9898	if (port->target_devid) {
9899		memcpy(desc, port->target_devid->data, port->target_devid->len);
9900	}
9901
9902	ctl_set_success(ctsio);
9903	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9904	ctsio->be_move_done = ctl_config_move_done;
9905	ctl_datamove((union ctl_io *)ctsio);
9906	return (CTL_RETVAL_COMPLETE);
9907}
9908
9909static int
9910ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9911{
9912	struct ctl_softc *softc = control_softc;
9913	struct scsi_vpd_scsi_ports *sp;
9914	struct scsi_vpd_port_designation *pd;
9915	struct scsi_vpd_port_designation_cont *pdc;
9916	struct ctl_lun *lun;
9917	struct ctl_port *port;
9918	int data_len, num_target_ports, iid_len, id_len, g, pg, p;
9919	int num_target_port_groups;
9920
9921	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9922
9923	if (softc->is_single)
9924		num_target_port_groups = 1;
9925	else
9926		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
9927	num_target_ports = 0;
9928	iid_len = 0;
9929	id_len = 0;
9930	mtx_lock(&softc->ctl_lock);
9931	STAILQ_FOREACH(port, &softc->port_list, links) {
9932		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9933			continue;
9934		if (lun != NULL &&
9935		    ctl_map_lun_back(port->targ_port, lun->lun) >=
9936		    CTL_MAX_LUNS)
9937			continue;
9938		num_target_ports++;
9939		if (port->init_devid)
9940			iid_len += port->init_devid->len;
9941		if (port->port_devid)
9942			id_len += port->port_devid->len;
9943	}
9944	mtx_unlock(&softc->ctl_lock);
9945
9946	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
9947	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9948	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9949	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9950	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9951	ctsio->kern_sg_entries = 0;
9952
9953	if (data_len < alloc_len) {
9954		ctsio->residual = alloc_len - data_len;
9955		ctsio->kern_data_len = data_len;
9956		ctsio->kern_total_len = data_len;
9957	} else {
9958		ctsio->residual = 0;
9959		ctsio->kern_data_len = alloc_len;
9960		ctsio->kern_total_len = alloc_len;
9961	}
9962	ctsio->kern_data_resid = 0;
9963	ctsio->kern_rel_offset = 0;
9964	ctsio->kern_sg_entries = 0;
9965
9966	/*
9967	 * The control device is always connected.  The disk device, on the
9968	 * other hand, may not be online all the time.  Need to change this
9969	 * to figure out whether the disk device is actually online or not.
9970	 */
9971	if (lun != NULL)
9972		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9973				  lun->be_lun->lun_type;
9974	else
9975		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9976
9977	sp->page_code = SVPD_SCSI_PORTS;
9978	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9979	    sp->page_length);
9980	pd = &sp->design[0];
9981
9982	mtx_lock(&softc->ctl_lock);
9983	pg = softc->port_offset / CTL_MAX_PORTS;
9984	for (g = 0; g < num_target_port_groups; g++) {
9985		STAILQ_FOREACH(port, &softc->port_list, links) {
9986			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9987				continue;
9988			if (lun != NULL &&
9989			    ctl_map_lun_back(port->targ_port, lun->lun) >=
9990			    CTL_MAX_LUNS)
9991				continue;
9992			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
9993			scsi_ulto2b(p, pd->relative_port_id);
9994			if (port->init_devid && g == pg) {
9995				iid_len = port->init_devid->len;
9996				memcpy(pd->initiator_transportid,
9997				    port->init_devid->data, port->init_devid->len);
9998			} else
9999				iid_len = 0;
10000			scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10001			pdc = (struct scsi_vpd_port_designation_cont *)
10002			    (&pd->initiator_transportid[iid_len]);
10003			if (port->port_devid && g == pg) {
10004				id_len = port->port_devid->len;
10005				memcpy(pdc->target_port_descriptors,
10006				    port->port_devid->data, port->port_devid->len);
10007			} else
10008				id_len = 0;
10009			scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10010			pd = (struct scsi_vpd_port_designation *)
10011			    ((uint8_t *)pdc->target_port_descriptors + id_len);
10012		}
10013	}
10014	mtx_unlock(&softc->ctl_lock);
10015
10016	ctl_set_success(ctsio);
10017	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10018	ctsio->be_move_done = ctl_config_move_done;
10019	ctl_datamove((union ctl_io *)ctsio);
10020	return (CTL_RETVAL_COMPLETE);
10021}
10022
10023static int
10024ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10025{
10026	struct scsi_vpd_block_limits *bl_ptr;
10027	struct ctl_lun *lun;
10028	int bs;
10029
10030	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10031
10032	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10033	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10034	ctsio->kern_sg_entries = 0;
10035
10036	if (sizeof(*bl_ptr) < alloc_len) {
10037		ctsio->residual = alloc_len - sizeof(*bl_ptr);
10038		ctsio->kern_data_len = sizeof(*bl_ptr);
10039		ctsio->kern_total_len = sizeof(*bl_ptr);
10040	} else {
10041		ctsio->residual = 0;
10042		ctsio->kern_data_len = alloc_len;
10043		ctsio->kern_total_len = alloc_len;
10044	}
10045	ctsio->kern_data_resid = 0;
10046	ctsio->kern_rel_offset = 0;
10047	ctsio->kern_sg_entries = 0;
10048
10049	/*
10050	 * The control device is always connected.  The disk device, on the
10051	 * other hand, may not be online all the time.  Need to change this
10052	 * to figure out whether the disk device is actually online or not.
10053	 */
10054	if (lun != NULL)
10055		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10056				  lun->be_lun->lun_type;
10057	else
10058		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10059
10060	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10061	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10062	bl_ptr->max_cmp_write_len = 0xff;
10063	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10064	if (lun != NULL) {
10065		bs = lun->be_lun->blocksize;
10066		scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10067		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10068			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10069			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10070			if (lun->be_lun->pblockexp != 0) {
10071				scsi_ulto4b((1 << lun->be_lun->pblockexp),
10072				    bl_ptr->opt_unmap_grain);
10073				scsi_ulto4b(0x80000000 | lun->be_lun->pblockoff,
10074				    bl_ptr->unmap_grain_align);
10075			}
10076		}
10077		scsi_ulto4b(lun->be_lun->atomicblock,
10078		    bl_ptr->max_atomic_transfer_length);
10079		scsi_ulto4b(0, bl_ptr->atomic_alignment);
10080		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10081	}
10082	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10083
10084	ctl_set_success(ctsio);
10085	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10086	ctsio->be_move_done = ctl_config_move_done;
10087	ctl_datamove((union ctl_io *)ctsio);
10088	return (CTL_RETVAL_COMPLETE);
10089}
10090
10091static int
10092ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10093{
10094	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10095	struct ctl_lun *lun;
10096	const char *value;
10097	u_int i;
10098
10099	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10100
10101	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10102	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10103	ctsio->kern_sg_entries = 0;
10104
10105	if (sizeof(*bdc_ptr) < alloc_len) {
10106		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10107		ctsio->kern_data_len = sizeof(*bdc_ptr);
10108		ctsio->kern_total_len = sizeof(*bdc_ptr);
10109	} else {
10110		ctsio->residual = 0;
10111		ctsio->kern_data_len = alloc_len;
10112		ctsio->kern_total_len = alloc_len;
10113	}
10114	ctsio->kern_data_resid = 0;
10115	ctsio->kern_rel_offset = 0;
10116	ctsio->kern_sg_entries = 0;
10117
10118	/*
10119	 * The control device is always connected.  The disk device, on the
10120	 * other hand, may not be online all the time.  Need to change this
10121	 * to figure out whether the disk device is actually online or not.
10122	 */
10123	if (lun != NULL)
10124		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10125				  lun->be_lun->lun_type;
10126	else
10127		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10128	bdc_ptr->page_code = SVPD_BDC;
10129	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10130	if (lun != NULL &&
10131	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10132		i = strtol(value, NULL, 0);
10133	else
10134		i = CTL_DEFAULT_ROTATION_RATE;
10135	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10136	if (lun != NULL &&
10137	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10138		i = strtol(value, NULL, 0);
10139	else
10140		i = 0;
10141	bdc_ptr->wab_wac_ff = (i & 0x0f);
10142	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10143
10144	ctl_set_success(ctsio);
10145	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10146	ctsio->be_move_done = ctl_config_move_done;
10147	ctl_datamove((union ctl_io *)ctsio);
10148	return (CTL_RETVAL_COMPLETE);
10149}
10150
10151static int
10152ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10153{
10154	struct scsi_vpd_logical_block_prov *lbp_ptr;
10155	struct ctl_lun *lun;
10156
10157	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10158
10159	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10160	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10161	ctsio->kern_sg_entries = 0;
10162
10163	if (sizeof(*lbp_ptr) < alloc_len) {
10164		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10165		ctsio->kern_data_len = sizeof(*lbp_ptr);
10166		ctsio->kern_total_len = sizeof(*lbp_ptr);
10167	} else {
10168		ctsio->residual = 0;
10169		ctsio->kern_data_len = alloc_len;
10170		ctsio->kern_total_len = alloc_len;
10171	}
10172	ctsio->kern_data_resid = 0;
10173	ctsio->kern_rel_offset = 0;
10174	ctsio->kern_sg_entries = 0;
10175
10176	/*
10177	 * The control device is always connected.  The disk device, on the
10178	 * other hand, may not be online all the time.  Need to change this
10179	 * to figure out whether the disk device is actually online or not.
10180	 */
10181	if (lun != NULL)
10182		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10183				  lun->be_lun->lun_type;
10184	else
10185		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10186
10187	lbp_ptr->page_code = SVPD_LBP;
10188	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10189	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10190		lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10191		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10192		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10193		lbp_ptr->prov_type = SVPD_LBP_THIN;
10194	}
10195
10196	ctl_set_success(ctsio);
10197	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10198	ctsio->be_move_done = ctl_config_move_done;
10199	ctl_datamove((union ctl_io *)ctsio);
10200	return (CTL_RETVAL_COMPLETE);
10201}
10202
10203static int
10204ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10205{
10206	struct scsi_inquiry *cdb;
10207	int alloc_len, retval;
10208
10209	cdb = (struct scsi_inquiry *)ctsio->cdb;
10210
10211	retval = CTL_RETVAL_COMPLETE;
10212
10213	alloc_len = scsi_2btoul(cdb->length);
10214
10215	switch (cdb->page_code) {
10216	case SVPD_SUPPORTED_PAGES:
10217		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10218		break;
10219	case SVPD_UNIT_SERIAL_NUMBER:
10220		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10221		break;
10222	case SVPD_DEVICE_ID:
10223		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10224		break;
10225	case SVPD_EXTENDED_INQUIRY_DATA:
10226		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10227		break;
10228	case SVPD_MODE_PAGE_POLICY:
10229		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10230		break;
10231	case SVPD_SCSI_PORTS:
10232		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10233		break;
10234	case SVPD_SCSI_TPC:
10235		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10236		break;
10237	case SVPD_BLOCK_LIMITS:
10238		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10239		break;
10240	case SVPD_BDC:
10241		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10242		break;
10243	case SVPD_LBP:
10244		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10245		break;
10246	default:
10247		ctl_set_invalid_field(ctsio,
10248				      /*sks_valid*/ 1,
10249				      /*command*/ 1,
10250				      /*field*/ 2,
10251				      /*bit_valid*/ 0,
10252				      /*bit*/ 0);
10253		ctl_done((union ctl_io *)ctsio);
10254		retval = CTL_RETVAL_COMPLETE;
10255		break;
10256	}
10257
10258	return (retval);
10259}
10260
10261static int
10262ctl_inquiry_std(struct ctl_scsiio *ctsio)
10263{
10264	struct scsi_inquiry_data *inq_ptr;
10265	struct scsi_inquiry *cdb;
10266	struct ctl_softc *ctl_softc;
10267	struct ctl_lun *lun;
10268	char *val;
10269	uint32_t alloc_len, data_len;
10270	ctl_port_type port_type;
10271
10272	ctl_softc = control_softc;
10273
10274	/*
10275	 * Figure out whether we're talking to a Fibre Channel port or not.
10276	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10277	 * SCSI front ends.
10278	 */
10279	port_type = ctl_softc->ctl_ports[
10280	    ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10281	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10282		port_type = CTL_PORT_SCSI;
10283
10284	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10285	cdb = (struct scsi_inquiry *)ctsio->cdb;
10286	alloc_len = scsi_2btoul(cdb->length);
10287
10288	/*
10289	 * We malloc the full inquiry data size here and fill it
10290	 * in.  If the user only asks for less, we'll give him
10291	 * that much.
10292	 */
10293	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10294	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10295	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10296	ctsio->kern_sg_entries = 0;
10297	ctsio->kern_data_resid = 0;
10298	ctsio->kern_rel_offset = 0;
10299
10300	if (data_len < alloc_len) {
10301		ctsio->residual = alloc_len - data_len;
10302		ctsio->kern_data_len = data_len;
10303		ctsio->kern_total_len = data_len;
10304	} else {
10305		ctsio->residual = 0;
10306		ctsio->kern_data_len = alloc_len;
10307		ctsio->kern_total_len = alloc_len;
10308	}
10309
10310	/*
10311	 * If we have a LUN configured, report it as connected.  Otherwise,
10312	 * report that it is offline or no device is supported, depending
10313	 * on the value of inquiry_pq_no_lun.
10314	 *
10315	 * According to the spec (SPC-4 r34), the peripheral qualifier
10316	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10317	 *
10318	 * "A peripheral device having the specified peripheral device type
10319	 * is not connected to this logical unit. However, the device
10320	 * server is capable of supporting the specified peripheral device
10321	 * type on this logical unit."
10322	 *
10323	 * According to the same spec, the peripheral qualifier
10324	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10325	 *
10326	 * "The device server is not capable of supporting a peripheral
10327	 * device on this logical unit. For this peripheral qualifier the
10328	 * peripheral device type shall be set to 1Fh. All other peripheral
10329	 * device type values are reserved for this peripheral qualifier."
10330	 *
10331	 * Given the text, it would seem that we probably want to report that
10332	 * the LUN is offline here.  There is no LUN connected, but we can
10333	 * support a LUN at the given LUN number.
10334	 *
10335	 * In the real world, though, it sounds like things are a little
10336	 * different:
10337	 *
10338	 * - Linux, when presented with a LUN with the offline peripheral
10339	 *   qualifier, will create an sg driver instance for it.  So when
10340	 *   you attach it to CTL, you wind up with a ton of sg driver
10341	 *   instances.  (One for every LUN that Linux bothered to probe.)
10342	 *   Linux does this despite the fact that it issues a REPORT LUNs
10343	 *   to LUN 0 to get the inventory of supported LUNs.
10344	 *
10345	 * - There is other anecdotal evidence (from Emulex folks) about
10346	 *   arrays that use the offline peripheral qualifier for LUNs that
10347	 *   are on the "passive" path in an active/passive array.
10348	 *
10349	 * So the solution is provide a hopefully reasonable default
10350	 * (return bad/no LUN) and allow the user to change the behavior
10351	 * with a tunable/sysctl variable.
10352	 */
10353	if (lun != NULL)
10354		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10355				  lun->be_lun->lun_type;
10356	else if (ctl_softc->inquiry_pq_no_lun == 0)
10357		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10358	else
10359		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10360
10361	/* RMB in byte 2 is 0 */
10362	inq_ptr->version = SCSI_REV_SPC4;
10363
10364	/*
10365	 * According to SAM-3, even if a device only supports a single
10366	 * level of LUN addressing, it should still set the HISUP bit:
10367	 *
10368	 * 4.9.1 Logical unit numbers overview
10369	 *
10370	 * All logical unit number formats described in this standard are
10371	 * hierarchical in structure even when only a single level in that
10372	 * hierarchy is used. The HISUP bit shall be set to one in the
10373	 * standard INQUIRY data (see SPC-2) when any logical unit number
10374	 * format described in this standard is used.  Non-hierarchical
10375	 * formats are outside the scope of this standard.
10376	 *
10377	 * Therefore we set the HiSup bit here.
10378	 *
10379	 * The reponse format is 2, per SPC-3.
10380	 */
10381	inq_ptr->response_format = SID_HiSup | 2;
10382
10383	inq_ptr->additional_length = data_len -
10384	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10385	CTL_DEBUG_PRINT(("additional_length = %d\n",
10386			 inq_ptr->additional_length));
10387
10388	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10389	/* 16 bit addressing */
10390	if (port_type == CTL_PORT_SCSI)
10391		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10392	/* XXX set the SID_MultiP bit here if we're actually going to
10393	   respond on multiple ports */
10394	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10395
10396	/* 16 bit data bus, synchronous transfers */
10397	if (port_type == CTL_PORT_SCSI)
10398		inq_ptr->flags = SID_WBus16 | SID_Sync;
10399	/*
10400	 * XXX KDM do we want to support tagged queueing on the control
10401	 * device at all?
10402	 */
10403	if ((lun == NULL)
10404	 || (lun->be_lun->lun_type != T_PROCESSOR))
10405		inq_ptr->flags |= SID_CmdQue;
10406	/*
10407	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10408	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10409	 * name and 4 bytes for the revision.
10410	 */
10411	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10412	    "vendor")) == NULL) {
10413		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10414	} else {
10415		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10416		strncpy(inq_ptr->vendor, val,
10417		    min(sizeof(inq_ptr->vendor), strlen(val)));
10418	}
10419	if (lun == NULL) {
10420		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10421		    sizeof(inq_ptr->product));
10422	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10423		switch (lun->be_lun->lun_type) {
10424		case T_DIRECT:
10425			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10426			    sizeof(inq_ptr->product));
10427			break;
10428		case T_PROCESSOR:
10429			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10430			    sizeof(inq_ptr->product));
10431			break;
10432		default:
10433			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10434			    sizeof(inq_ptr->product));
10435			break;
10436		}
10437	} else {
10438		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10439		strncpy(inq_ptr->product, val,
10440		    min(sizeof(inq_ptr->product), strlen(val)));
10441	}
10442
10443	/*
10444	 * XXX make this a macro somewhere so it automatically gets
10445	 * incremented when we make changes.
10446	 */
10447	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10448	    "revision")) == NULL) {
10449		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10450	} else {
10451		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10452		strncpy(inq_ptr->revision, val,
10453		    min(sizeof(inq_ptr->revision), strlen(val)));
10454	}
10455
10456	/*
10457	 * For parallel SCSI, we support double transition and single
10458	 * transition clocking.  We also support QAS (Quick Arbitration
10459	 * and Selection) and Information Unit transfers on both the
10460	 * control and array devices.
10461	 */
10462	if (port_type == CTL_PORT_SCSI)
10463		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10464				    SID_SPI_IUS;
10465
10466	/* SAM-5 (no version claimed) */
10467	scsi_ulto2b(0x00A0, inq_ptr->version1);
10468	/* SPC-4 (no version claimed) */
10469	scsi_ulto2b(0x0460, inq_ptr->version2);
10470	if (port_type == CTL_PORT_FC) {
10471		/* FCP-2 ANSI INCITS.350:2003 */
10472		scsi_ulto2b(0x0917, inq_ptr->version3);
10473	} else if (port_type == CTL_PORT_SCSI) {
10474		/* SPI-4 ANSI INCITS.362:200x */
10475		scsi_ulto2b(0x0B56, inq_ptr->version3);
10476	} else if (port_type == CTL_PORT_ISCSI) {
10477		/* iSCSI (no version claimed) */
10478		scsi_ulto2b(0x0960, inq_ptr->version3);
10479	} else if (port_type == CTL_PORT_SAS) {
10480		/* SAS (no version claimed) */
10481		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10482	}
10483
10484	if (lun == NULL) {
10485		/* SBC-4 (no version claimed) */
10486		scsi_ulto2b(0x0600, inq_ptr->version4);
10487	} else {
10488		switch (lun->be_lun->lun_type) {
10489		case T_DIRECT:
10490			/* SBC-4 (no version claimed) */
10491			scsi_ulto2b(0x0600, inq_ptr->version4);
10492			break;
10493		case T_PROCESSOR:
10494		default:
10495			break;
10496		}
10497	}
10498
10499	ctl_set_success(ctsio);
10500	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10501	ctsio->be_move_done = ctl_config_move_done;
10502	ctl_datamove((union ctl_io *)ctsio);
10503	return (CTL_RETVAL_COMPLETE);
10504}
10505
10506int
10507ctl_inquiry(struct ctl_scsiio *ctsio)
10508{
10509	struct scsi_inquiry *cdb;
10510	int retval;
10511
10512	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10513
10514	cdb = (struct scsi_inquiry *)ctsio->cdb;
10515	if (cdb->byte2 & SI_EVPD)
10516		retval = ctl_inquiry_evpd(ctsio);
10517	else if (cdb->page_code == 0)
10518		retval = ctl_inquiry_std(ctsio);
10519	else {
10520		ctl_set_invalid_field(ctsio,
10521				      /*sks_valid*/ 1,
10522				      /*command*/ 1,
10523				      /*field*/ 2,
10524				      /*bit_valid*/ 0,
10525				      /*bit*/ 0);
10526		ctl_done((union ctl_io *)ctsio);
10527		return (CTL_RETVAL_COMPLETE);
10528	}
10529
10530	return (retval);
10531}
10532
10533/*
10534 * For known CDB types, parse the LBA and length.
10535 */
10536static int
10537ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10538{
10539	if (io->io_hdr.io_type != CTL_IO_SCSI)
10540		return (1);
10541
10542	switch (io->scsiio.cdb[0]) {
10543	case COMPARE_AND_WRITE: {
10544		struct scsi_compare_and_write *cdb;
10545
10546		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10547
10548		*lba = scsi_8btou64(cdb->addr);
10549		*len = cdb->length;
10550		break;
10551	}
10552	case READ_6:
10553	case WRITE_6: {
10554		struct scsi_rw_6 *cdb;
10555
10556		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10557
10558		*lba = scsi_3btoul(cdb->addr);
10559		/* only 5 bits are valid in the most significant address byte */
10560		*lba &= 0x1fffff;
10561		*len = cdb->length;
10562		break;
10563	}
10564	case READ_10:
10565	case WRITE_10: {
10566		struct scsi_rw_10 *cdb;
10567
10568		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10569
10570		*lba = scsi_4btoul(cdb->addr);
10571		*len = scsi_2btoul(cdb->length);
10572		break;
10573	}
10574	case WRITE_VERIFY_10: {
10575		struct scsi_write_verify_10 *cdb;
10576
10577		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10578
10579		*lba = scsi_4btoul(cdb->addr);
10580		*len = scsi_2btoul(cdb->length);
10581		break;
10582	}
10583	case READ_12:
10584	case WRITE_12: {
10585		struct scsi_rw_12 *cdb;
10586
10587		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10588
10589		*lba = scsi_4btoul(cdb->addr);
10590		*len = scsi_4btoul(cdb->length);
10591		break;
10592	}
10593	case WRITE_VERIFY_12: {
10594		struct scsi_write_verify_12 *cdb;
10595
10596		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10597
10598		*lba = scsi_4btoul(cdb->addr);
10599		*len = scsi_4btoul(cdb->length);
10600		break;
10601	}
10602	case READ_16:
10603	case WRITE_16:
10604	case WRITE_ATOMIC_16: {
10605		struct scsi_rw_16 *cdb;
10606
10607		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10608
10609		*lba = scsi_8btou64(cdb->addr);
10610		*len = scsi_4btoul(cdb->length);
10611		break;
10612	}
10613	case WRITE_VERIFY_16: {
10614		struct scsi_write_verify_16 *cdb;
10615
10616		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10617
10618		*lba = scsi_8btou64(cdb->addr);
10619		*len = scsi_4btoul(cdb->length);
10620		break;
10621	}
10622	case WRITE_SAME_10: {
10623		struct scsi_write_same_10 *cdb;
10624
10625		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10626
10627		*lba = scsi_4btoul(cdb->addr);
10628		*len = scsi_2btoul(cdb->length);
10629		break;
10630	}
10631	case WRITE_SAME_16: {
10632		struct scsi_write_same_16 *cdb;
10633
10634		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10635
10636		*lba = scsi_8btou64(cdb->addr);
10637		*len = scsi_4btoul(cdb->length);
10638		break;
10639	}
10640	case VERIFY_10: {
10641		struct scsi_verify_10 *cdb;
10642
10643		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10644
10645		*lba = scsi_4btoul(cdb->addr);
10646		*len = scsi_2btoul(cdb->length);
10647		break;
10648	}
10649	case VERIFY_12: {
10650		struct scsi_verify_12 *cdb;
10651
10652		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10653
10654		*lba = scsi_4btoul(cdb->addr);
10655		*len = scsi_4btoul(cdb->length);
10656		break;
10657	}
10658	case VERIFY_16: {
10659		struct scsi_verify_16 *cdb;
10660
10661		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10662
10663		*lba = scsi_8btou64(cdb->addr);
10664		*len = scsi_4btoul(cdb->length);
10665		break;
10666	}
10667	case UNMAP: {
10668		*lba = 0;
10669		*len = UINT64_MAX;
10670		break;
10671	}
10672	default:
10673		return (1);
10674		break; /* NOTREACHED */
10675	}
10676
10677	return (0);
10678}
10679
10680static ctl_action
10681ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2)
10682{
10683	uint64_t endlba1, endlba2;
10684
10685	endlba1 = lba1 + len1 - 1;
10686	endlba2 = lba2 + len2 - 1;
10687
10688	if ((endlba1 < lba2)
10689	 || (endlba2 < lba1))
10690		return (CTL_ACTION_PASS);
10691	else
10692		return (CTL_ACTION_BLOCK);
10693}
10694
10695static int
10696ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10697{
10698	struct ctl_ptr_len_flags *ptrlen;
10699	struct scsi_unmap_desc *buf, *end, *range;
10700	uint64_t lba;
10701	uint32_t len;
10702
10703	/* If not UNMAP -- go other way. */
10704	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10705	    io->scsiio.cdb[0] != UNMAP)
10706		return (CTL_ACTION_ERROR);
10707
10708	/* If UNMAP without data -- block and wait for data. */
10709	ptrlen = (struct ctl_ptr_len_flags *)
10710	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10711	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10712	    ptrlen->ptr == NULL)
10713		return (CTL_ACTION_BLOCK);
10714
10715	/* UNMAP with data -- check for collision. */
10716	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10717	end = buf + ptrlen->len / sizeof(*buf);
10718	for (range = buf; range < end; range++) {
10719		lba = scsi_8btou64(range->lba);
10720		len = scsi_4btoul(range->length);
10721		if ((lba < lba2 + len2) && (lba + len > lba2))
10722			return (CTL_ACTION_BLOCK);
10723	}
10724	return (CTL_ACTION_PASS);
10725}
10726
10727static ctl_action
10728ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10729{
10730	uint64_t lba1, lba2;
10731	uint64_t len1, len2;
10732	int retval;
10733
10734	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10735		return (CTL_ACTION_ERROR);
10736
10737	retval = ctl_extent_check_unmap(io2, lba1, len1);
10738	if (retval != CTL_ACTION_ERROR)
10739		return (retval);
10740
10741	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10742		return (CTL_ACTION_ERROR);
10743
10744	return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10745}
10746
10747static ctl_action
10748ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10749    union ctl_io *ooa_io)
10750{
10751	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10752	ctl_serialize_action *serialize_row;
10753
10754	/*
10755	 * The initiator attempted multiple untagged commands at the same
10756	 * time.  Can't do that.
10757	 */
10758	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10759	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10760	 && ((pending_io->io_hdr.nexus.targ_port ==
10761	      ooa_io->io_hdr.nexus.targ_port)
10762	  && (pending_io->io_hdr.nexus.initid.id ==
10763	      ooa_io->io_hdr.nexus.initid.id))
10764	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10765		return (CTL_ACTION_OVERLAP);
10766
10767	/*
10768	 * The initiator attempted to send multiple tagged commands with
10769	 * the same ID.  (It's fine if different initiators have the same
10770	 * tag ID.)
10771	 *
10772	 * Even if all of those conditions are true, we don't kill the I/O
10773	 * if the command ahead of us has been aborted.  We won't end up
10774	 * sending it to the FETD, and it's perfectly legal to resend a
10775	 * command with the same tag number as long as the previous
10776	 * instance of this tag number has been aborted somehow.
10777	 */
10778	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10779	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10780	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10781	 && ((pending_io->io_hdr.nexus.targ_port ==
10782	      ooa_io->io_hdr.nexus.targ_port)
10783	  && (pending_io->io_hdr.nexus.initid.id ==
10784	      ooa_io->io_hdr.nexus.initid.id))
10785	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10786		return (CTL_ACTION_OVERLAP_TAG);
10787
10788	/*
10789	 * If we get a head of queue tag, SAM-3 says that we should
10790	 * immediately execute it.
10791	 *
10792	 * What happens if this command would normally block for some other
10793	 * reason?  e.g. a request sense with a head of queue tag
10794	 * immediately after a write.  Normally that would block, but this
10795	 * will result in its getting executed immediately...
10796	 *
10797	 * We currently return "pass" instead of "skip", so we'll end up
10798	 * going through the rest of the queue to check for overlapped tags.
10799	 *
10800	 * XXX KDM check for other types of blockage first??
10801	 */
10802	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10803		return (CTL_ACTION_PASS);
10804
10805	/*
10806	 * Ordered tags have to block until all items ahead of them
10807	 * have completed.  If we get called with an ordered tag, we always
10808	 * block, if something else is ahead of us in the queue.
10809	 */
10810	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10811		return (CTL_ACTION_BLOCK);
10812
10813	/*
10814	 * Simple tags get blocked until all head of queue and ordered tags
10815	 * ahead of them have completed.  I'm lumping untagged commands in
10816	 * with simple tags here.  XXX KDM is that the right thing to do?
10817	 */
10818	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10819	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10820	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10821	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10822		return (CTL_ACTION_BLOCK);
10823
10824	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10825	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10826
10827	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10828
10829	switch (serialize_row[pending_entry->seridx]) {
10830	case CTL_SER_BLOCK:
10831		return (CTL_ACTION_BLOCK);
10832	case CTL_SER_EXTENT:
10833		return (ctl_extent_check(pending_io, ooa_io));
10834	case CTL_SER_EXTENTOPT:
10835		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10836		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10837			return (ctl_extent_check(pending_io, ooa_io));
10838		/* FALLTHROUGH */
10839	case CTL_SER_PASS:
10840		return (CTL_ACTION_PASS);
10841	case CTL_SER_BLOCKOPT:
10842		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10843		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10844			return (CTL_ACTION_BLOCK);
10845		return (CTL_ACTION_PASS);
10846	case CTL_SER_SKIP:
10847		return (CTL_ACTION_SKIP);
10848	default:
10849		panic("invalid serialization value %d",
10850		      serialize_row[pending_entry->seridx]);
10851	}
10852
10853	return (CTL_ACTION_ERROR);
10854}
10855
10856/*
10857 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10858 * Assumptions:
10859 * - pending_io is generally either incoming, or on the blocked queue
10860 * - starting I/O is the I/O we want to start the check with.
10861 */
10862static ctl_action
10863ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10864	      union ctl_io *starting_io)
10865{
10866	union ctl_io *ooa_io;
10867	ctl_action action;
10868
10869	mtx_assert(&lun->lun_lock, MA_OWNED);
10870
10871	/*
10872	 * Run back along the OOA queue, starting with the current
10873	 * blocked I/O and going through every I/O before it on the
10874	 * queue.  If starting_io is NULL, we'll just end up returning
10875	 * CTL_ACTION_PASS.
10876	 */
10877	for (ooa_io = starting_io; ooa_io != NULL;
10878	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10879	     ooa_links)){
10880
10881		/*
10882		 * This routine just checks to see whether
10883		 * cur_blocked is blocked by ooa_io, which is ahead
10884		 * of it in the queue.  It doesn't queue/dequeue
10885		 * cur_blocked.
10886		 */
10887		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10888		switch (action) {
10889		case CTL_ACTION_BLOCK:
10890		case CTL_ACTION_OVERLAP:
10891		case CTL_ACTION_OVERLAP_TAG:
10892		case CTL_ACTION_SKIP:
10893		case CTL_ACTION_ERROR:
10894			return (action);
10895			break; /* NOTREACHED */
10896		case CTL_ACTION_PASS:
10897			break;
10898		default:
10899			panic("invalid action %d", action);
10900			break;  /* NOTREACHED */
10901		}
10902	}
10903
10904	return (CTL_ACTION_PASS);
10905}
10906
10907/*
10908 * Assumptions:
10909 * - An I/O has just completed, and has been removed from the per-LUN OOA
10910 *   queue, so some items on the blocked queue may now be unblocked.
10911 */
10912static int
10913ctl_check_blocked(struct ctl_lun *lun)
10914{
10915	union ctl_io *cur_blocked, *next_blocked;
10916
10917	mtx_assert(&lun->lun_lock, MA_OWNED);
10918
10919	/*
10920	 * Run forward from the head of the blocked queue, checking each
10921	 * entry against the I/Os prior to it on the OOA queue to see if
10922	 * there is still any blockage.
10923	 *
10924	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10925	 * with our removing a variable on it while it is traversing the
10926	 * list.
10927	 */
10928	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10929	     cur_blocked != NULL; cur_blocked = next_blocked) {
10930		union ctl_io *prev_ooa;
10931		ctl_action action;
10932
10933		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10934							  blocked_links);
10935
10936		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10937						      ctl_ooaq, ooa_links);
10938
10939		/*
10940		 * If cur_blocked happens to be the first item in the OOA
10941		 * queue now, prev_ooa will be NULL, and the action
10942		 * returned will just be CTL_ACTION_PASS.
10943		 */
10944		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
10945
10946		switch (action) {
10947		case CTL_ACTION_BLOCK:
10948			/* Nothing to do here, still blocked */
10949			break;
10950		case CTL_ACTION_OVERLAP:
10951		case CTL_ACTION_OVERLAP_TAG:
10952			/*
10953			 * This shouldn't happen!  In theory we've already
10954			 * checked this command for overlap...
10955			 */
10956			break;
10957		case CTL_ACTION_PASS:
10958		case CTL_ACTION_SKIP: {
10959			struct ctl_softc *softc;
10960			const struct ctl_cmd_entry *entry;
10961			int isc_retval;
10962
10963			/*
10964			 * The skip case shouldn't happen, this transaction
10965			 * should have never made it onto the blocked queue.
10966			 */
10967			/*
10968			 * This I/O is no longer blocked, we can remove it
10969			 * from the blocked queue.  Since this is a TAILQ
10970			 * (doubly linked list), we can do O(1) removals
10971			 * from any place on the list.
10972			 */
10973			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
10974				     blocked_links);
10975			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10976
10977			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
10978				/*
10979				 * Need to send IO back to original side to
10980				 * run
10981				 */
10982				union ctl_ha_msg msg_info;
10983
10984				msg_info.hdr.original_sc =
10985					cur_blocked->io_hdr.original_sc;
10986				msg_info.hdr.serializing_sc = cur_blocked;
10987				msg_info.hdr.msg_type = CTL_MSG_R2R;
10988				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
10989				     &msg_info, sizeof(msg_info), 0)) >
10990				     CTL_HA_STATUS_SUCCESS) {
10991					printf("CTL:Check Blocked error from "
10992					       "ctl_ha_msg_send %d\n",
10993					       isc_retval);
10994				}
10995				break;
10996			}
10997			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
10998			softc = control_softc;
10999
11000			/*
11001			 * Check this I/O for LUN state changes that may
11002			 * have happened while this command was blocked.
11003			 * The LUN state may have been changed by a command
11004			 * ahead of us in the queue, so we need to re-check
11005			 * for any states that can be caused by SCSI
11006			 * commands.
11007			 */
11008			if (ctl_scsiio_lun_check(softc, lun, entry,
11009						 &cur_blocked->scsiio) == 0) {
11010				cur_blocked->io_hdr.flags |=
11011				                      CTL_FLAG_IS_WAS_ON_RTR;
11012				ctl_enqueue_rtr(cur_blocked);
11013			} else
11014				ctl_done(cur_blocked);
11015			break;
11016		}
11017		default:
11018			/*
11019			 * This probably shouldn't happen -- we shouldn't
11020			 * get CTL_ACTION_ERROR, or anything else.
11021			 */
11022			break;
11023		}
11024	}
11025
11026	return (CTL_RETVAL_COMPLETE);
11027}
11028
11029/*
11030 * This routine (with one exception) checks LUN flags that can be set by
11031 * commands ahead of us in the OOA queue.  These flags have to be checked
11032 * when a command initially comes in, and when we pull a command off the
11033 * blocked queue and are preparing to execute it.  The reason we have to
11034 * check these flags for commands on the blocked queue is that the LUN
11035 * state may have been changed by a command ahead of us while we're on the
11036 * blocked queue.
11037 *
11038 * Ordering is somewhat important with these checks, so please pay
11039 * careful attention to the placement of any new checks.
11040 */
11041static int
11042ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11043    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11044{
11045	int retval;
11046	uint32_t residx;
11047
11048	retval = 0;
11049
11050	mtx_assert(&lun->lun_lock, MA_OWNED);
11051
11052	/*
11053	 * If this shelf is a secondary shelf controller, we have to reject
11054	 * any media access commands.
11055	 */
11056	if ((ctl_softc->flags & CTL_FLAG_ACTIVE_SHELF) == 0 &&
11057	    (entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0) {
11058		ctl_set_lun_standby(ctsio);
11059		retval = 1;
11060		goto bailout;
11061	}
11062
11063	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11064		if (lun->flags & CTL_LUN_READONLY) {
11065			ctl_set_sense(ctsio, /*current_error*/ 1,
11066			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11067			    /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11068			retval = 1;
11069			goto bailout;
11070		}
11071		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11072		    .eca_and_aen & SCP_SWP) != 0) {
11073			ctl_set_sense(ctsio, /*current_error*/ 1,
11074			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11075			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11076			retval = 1;
11077			goto bailout;
11078		}
11079	}
11080
11081	/*
11082	 * Check for a reservation conflict.  If this command isn't allowed
11083	 * even on reserved LUNs, and if this initiator isn't the one who
11084	 * reserved us, reject the command with a reservation conflict.
11085	 */
11086	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11087	if ((lun->flags & CTL_LUN_RESERVED)
11088	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11089		if (lun->res_idx != residx) {
11090			ctl_set_reservation_conflict(ctsio);
11091			retval = 1;
11092			goto bailout;
11093		}
11094	}
11095
11096	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11097	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11098		/* No reservation or command is allowed. */;
11099	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11100	    (lun->res_type == SPR_TYPE_WR_EX ||
11101	     lun->res_type == SPR_TYPE_WR_EX_RO ||
11102	     lun->res_type == SPR_TYPE_WR_EX_AR)) {
11103		/* The command is allowed for Write Exclusive resv. */;
11104	} else {
11105		/*
11106		 * if we aren't registered or it's a res holder type
11107		 * reservation and this isn't the res holder then set a
11108		 * conflict.
11109		 */
11110		if (ctl_get_prkey(lun, residx) == 0
11111		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11112			ctl_set_reservation_conflict(ctsio);
11113			retval = 1;
11114			goto bailout;
11115		}
11116
11117	}
11118
11119	if ((lun->flags & CTL_LUN_OFFLINE)
11120	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11121		ctl_set_lun_not_ready(ctsio);
11122		retval = 1;
11123		goto bailout;
11124	}
11125
11126	/*
11127	 * If the LUN is stopped, see if this particular command is allowed
11128	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11129	 */
11130	if ((lun->flags & CTL_LUN_STOPPED)
11131	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11132		/* "Logical unit not ready, initializing cmd. required" */
11133		ctl_set_lun_stopped(ctsio);
11134		retval = 1;
11135		goto bailout;
11136	}
11137
11138	if ((lun->flags & CTL_LUN_INOPERABLE)
11139	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11140		/* "Medium format corrupted" */
11141		ctl_set_medium_format_corrupted(ctsio);
11142		retval = 1;
11143		goto bailout;
11144	}
11145
11146bailout:
11147	return (retval);
11148
11149}
11150
11151static void
11152ctl_failover_io(union ctl_io *io, int have_lock)
11153{
11154	ctl_set_busy(&io->scsiio);
11155	ctl_done(io);
11156}
11157
11158static void
11159ctl_failover(void)
11160{
11161	struct ctl_lun *lun;
11162	struct ctl_softc *ctl_softc;
11163	union ctl_io *next_io, *pending_io;
11164	union ctl_io *io;
11165	int lun_idx;
11166	int i;
11167
11168	ctl_softc = control_softc;
11169
11170	mtx_lock(&ctl_softc->ctl_lock);
11171	/*
11172	 * Remove any cmds from the other SC from the rtr queue.  These
11173	 * will obviously only be for LUNs for which we're the primary.
11174	 * We can't send status or get/send data for these commands.
11175	 * Since they haven't been executed yet, we can just remove them.
11176	 * We'll either abort them or delete them below, depending on
11177	 * which HA mode we're in.
11178	 */
11179#ifdef notyet
11180	mtx_lock(&ctl_softc->queue_lock);
11181	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11182	     io != NULL; io = next_io) {
11183		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11184		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11185			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11186				      ctl_io_hdr, links);
11187	}
11188	mtx_unlock(&ctl_softc->queue_lock);
11189#endif
11190
11191	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11192		lun = ctl_softc->ctl_luns[lun_idx];
11193		if (lun==NULL)
11194			continue;
11195
11196		/*
11197		 * Processor LUNs are primary on both sides.
11198		 * XXX will this always be true?
11199		 */
11200		if (lun->be_lun->lun_type == T_PROCESSOR)
11201			continue;
11202
11203		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11204		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11205			printf("FAILOVER: primary lun %d\n", lun_idx);
11206		        /*
11207			 * Remove all commands from the other SC. First from the
11208			 * blocked queue then from the ooa queue. Once we have
11209			 * removed them. Call ctl_check_blocked to see if there
11210			 * is anything that can run.
11211			 */
11212			for (io = (union ctl_io *)TAILQ_FIRST(
11213			     &lun->blocked_queue); io != NULL; io = next_io) {
11214
11215		        	next_io = (union ctl_io *)TAILQ_NEXT(
11216				    &io->io_hdr, blocked_links);
11217
11218				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11219					TAILQ_REMOVE(&lun->blocked_queue,
11220						     &io->io_hdr,blocked_links);
11221					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11222					TAILQ_REMOVE(&lun->ooa_queue,
11223						     &io->io_hdr, ooa_links);
11224
11225					ctl_free_io(io);
11226				}
11227			}
11228
11229			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11230	     		     io != NULL; io = next_io) {
11231
11232		        	next_io = (union ctl_io *)TAILQ_NEXT(
11233				    &io->io_hdr, ooa_links);
11234
11235				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11236
11237					TAILQ_REMOVE(&lun->ooa_queue,
11238						&io->io_hdr,
11239					     	ooa_links);
11240
11241					ctl_free_io(io);
11242				}
11243			}
11244			ctl_check_blocked(lun);
11245		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11246			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11247
11248			printf("FAILOVER: primary lun %d\n", lun_idx);
11249			/*
11250			 * Abort all commands from the other SC.  We can't
11251			 * send status back for them now.  These should get
11252			 * cleaned up when they are completed or come out
11253			 * for a datamove operation.
11254			 */
11255			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11256	     		     io != NULL; io = next_io) {
11257		        	next_io = (union ctl_io *)TAILQ_NEXT(
11258					&io->io_hdr, ooa_links);
11259
11260				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11261					io->io_hdr.flags |= CTL_FLAG_ABORT;
11262			}
11263		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11264			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11265
11266			printf("FAILOVER: secondary lun %d\n", lun_idx);
11267
11268			lun->flags |= CTL_LUN_PRIMARY_SC;
11269
11270			/*
11271			 * We send all I/O that was sent to this controller
11272			 * and redirected to the other side back with
11273			 * busy status, and have the initiator retry it.
11274			 * Figuring out how much data has been transferred,
11275			 * etc. and picking up where we left off would be
11276			 * very tricky.
11277			 *
11278			 * XXX KDM need to remove I/O from the blocked
11279			 * queue as well!
11280			 */
11281			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11282			     &lun->ooa_queue); pending_io != NULL;
11283			     pending_io = next_io) {
11284
11285				next_io =  (union ctl_io *)TAILQ_NEXT(
11286					&pending_io->io_hdr, ooa_links);
11287
11288				pending_io->io_hdr.flags &=
11289					~CTL_FLAG_SENT_2OTHER_SC;
11290
11291				if (pending_io->io_hdr.flags &
11292				    CTL_FLAG_IO_ACTIVE) {
11293					pending_io->io_hdr.flags |=
11294						CTL_FLAG_FAILOVER;
11295				} else {
11296					ctl_set_busy(&pending_io->scsiio);
11297					ctl_done(pending_io);
11298				}
11299			}
11300
11301			/*
11302			 * Build Unit Attention
11303			 */
11304			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11305				lun->pending_ua[i] |=
11306				                     CTL_UA_ASYM_ACC_CHANGE;
11307			}
11308		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11309			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11310			printf("FAILOVER: secondary lun %d\n", lun_idx);
11311			/*
11312			 * if the first io on the OOA is not on the RtR queue
11313			 * add it.
11314			 */
11315			lun->flags |= CTL_LUN_PRIMARY_SC;
11316
11317			pending_io = (union ctl_io *)TAILQ_FIRST(
11318			    &lun->ooa_queue);
11319			if (pending_io==NULL) {
11320				printf("Nothing on OOA queue\n");
11321				continue;
11322			}
11323
11324			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11325			if ((pending_io->io_hdr.flags &
11326			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11327				pending_io->io_hdr.flags |=
11328				    CTL_FLAG_IS_WAS_ON_RTR;
11329				ctl_enqueue_rtr(pending_io);
11330			}
11331#if 0
11332			else
11333			{
11334				printf("Tag 0x%04x is running\n",
11335				      pending_io->scsiio.tag_num);
11336			}
11337#endif
11338
11339			next_io = (union ctl_io *)TAILQ_NEXT(
11340			    &pending_io->io_hdr, ooa_links);
11341			for (pending_io=next_io; pending_io != NULL;
11342			     pending_io = next_io) {
11343				pending_io->io_hdr.flags &=
11344				    ~CTL_FLAG_SENT_2OTHER_SC;
11345				next_io = (union ctl_io *)TAILQ_NEXT(
11346					&pending_io->io_hdr, ooa_links);
11347				if (pending_io->io_hdr.flags &
11348				    CTL_FLAG_IS_WAS_ON_RTR) {
11349#if 0
11350				        printf("Tag 0x%04x is running\n",
11351				      		pending_io->scsiio.tag_num);
11352#endif
11353					continue;
11354				}
11355
11356				switch (ctl_check_ooa(lun, pending_io,
11357			            (union ctl_io *)TAILQ_PREV(
11358				    &pending_io->io_hdr, ctl_ooaq,
11359				    ooa_links))) {
11360
11361				case CTL_ACTION_BLOCK:
11362					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11363							  &pending_io->io_hdr,
11364							  blocked_links);
11365					pending_io->io_hdr.flags |=
11366					    CTL_FLAG_BLOCKED;
11367					break;
11368				case CTL_ACTION_PASS:
11369				case CTL_ACTION_SKIP:
11370					pending_io->io_hdr.flags |=
11371					    CTL_FLAG_IS_WAS_ON_RTR;
11372					ctl_enqueue_rtr(pending_io);
11373					break;
11374				case CTL_ACTION_OVERLAP:
11375					ctl_set_overlapped_cmd(
11376					    (struct ctl_scsiio *)pending_io);
11377					ctl_done(pending_io);
11378					break;
11379				case CTL_ACTION_OVERLAP_TAG:
11380					ctl_set_overlapped_tag(
11381					    (struct ctl_scsiio *)pending_io,
11382					    pending_io->scsiio.tag_num & 0xff);
11383					ctl_done(pending_io);
11384					break;
11385				case CTL_ACTION_ERROR:
11386				default:
11387					ctl_set_internal_failure(
11388						(struct ctl_scsiio *)pending_io,
11389						0,  // sks_valid
11390						0); //retry count
11391					ctl_done(pending_io);
11392					break;
11393				}
11394			}
11395
11396			/*
11397			 * Build Unit Attention
11398			 */
11399			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11400				lun->pending_ua[i] |=
11401				                     CTL_UA_ASYM_ACC_CHANGE;
11402			}
11403		} else {
11404			panic("Unhandled HA mode failover, LUN flags = %#x, "
11405			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11406		}
11407	}
11408	ctl_pause_rtr = 0;
11409	mtx_unlock(&ctl_softc->ctl_lock);
11410}
11411
11412static int
11413ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11414{
11415	struct ctl_lun *lun;
11416	const struct ctl_cmd_entry *entry;
11417	uint32_t initidx, targ_lun;
11418	int retval;
11419
11420	retval = 0;
11421
11422	lun = NULL;
11423
11424	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11425	if ((targ_lun < CTL_MAX_LUNS)
11426	 && ((lun = ctl_softc->ctl_luns[targ_lun]) != NULL)) {
11427		/*
11428		 * If the LUN is invalid, pretend that it doesn't exist.
11429		 * It will go away as soon as all pending I/O has been
11430		 * completed.
11431		 */
11432		mtx_lock(&lun->lun_lock);
11433		if (lun->flags & CTL_LUN_DISABLED) {
11434			mtx_unlock(&lun->lun_lock);
11435			lun = NULL;
11436			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11437			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11438		} else {
11439			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11440			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11441				lun->be_lun;
11442			if (lun->be_lun->lun_type == T_PROCESSOR) {
11443				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11444			}
11445
11446			/*
11447			 * Every I/O goes into the OOA queue for a
11448			 * particular LUN, and stays there until completion.
11449			 */
11450			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11451			    ooa_links);
11452		}
11453	} else {
11454		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11455		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11456	}
11457
11458	/* Get command entry and return error if it is unsuppotyed. */
11459	entry = ctl_validate_command(ctsio);
11460	if (entry == NULL) {
11461		if (lun)
11462			mtx_unlock(&lun->lun_lock);
11463		return (retval);
11464	}
11465
11466	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11467	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11468
11469	/*
11470	 * Check to see whether we can send this command to LUNs that don't
11471	 * exist.  This should pretty much only be the case for inquiry
11472	 * and request sense.  Further checks, below, really require having
11473	 * a LUN, so we can't really check the command anymore.  Just put
11474	 * it on the rtr queue.
11475	 */
11476	if (lun == NULL) {
11477		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11478			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11479			ctl_enqueue_rtr((union ctl_io *)ctsio);
11480			return (retval);
11481		}
11482
11483		ctl_set_unsupported_lun(ctsio);
11484		ctl_done((union ctl_io *)ctsio);
11485		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11486		return (retval);
11487	} else {
11488		/*
11489		 * Make sure we support this particular command on this LUN.
11490		 * e.g., we don't support writes to the control LUN.
11491		 */
11492		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11493			mtx_unlock(&lun->lun_lock);
11494			ctl_set_invalid_opcode(ctsio);
11495			ctl_done((union ctl_io *)ctsio);
11496			return (retval);
11497		}
11498	}
11499
11500	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11501
11502#ifdef CTL_WITH_CA
11503	/*
11504	 * If we've got a request sense, it'll clear the contingent
11505	 * allegiance condition.  Otherwise, if we have a CA condition for
11506	 * this initiator, clear it, because it sent down a command other
11507	 * than request sense.
11508	 */
11509	if ((ctsio->cdb[0] != REQUEST_SENSE)
11510	 && (ctl_is_set(lun->have_ca, initidx)))
11511		ctl_clear_mask(lun->have_ca, initidx);
11512#endif
11513
11514	/*
11515	 * If the command has this flag set, it handles its own unit
11516	 * attention reporting, we shouldn't do anything.  Otherwise we
11517	 * check for any pending unit attentions, and send them back to the
11518	 * initiator.  We only do this when a command initially comes in,
11519	 * not when we pull it off the blocked queue.
11520	 *
11521	 * According to SAM-3, section 5.3.2, the order that things get
11522	 * presented back to the host is basically unit attentions caused
11523	 * by some sort of reset event, busy status, reservation conflicts
11524	 * or task set full, and finally any other status.
11525	 *
11526	 * One issue here is that some of the unit attentions we report
11527	 * don't fall into the "reset" category (e.g. "reported luns data
11528	 * has changed").  So reporting it here, before the reservation
11529	 * check, may be technically wrong.  I guess the only thing to do
11530	 * would be to check for and report the reset events here, and then
11531	 * check for the other unit attention types after we check for a
11532	 * reservation conflict.
11533	 *
11534	 * XXX KDM need to fix this
11535	 */
11536	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11537		ctl_ua_type ua_type;
11538
11539		if (lun->pending_ua[initidx] != CTL_UA_NONE) {
11540			scsi_sense_data_type sense_format;
11541
11542			if (lun != NULL)
11543				sense_format = (lun->flags &
11544				    CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11545				    SSD_TYPE_FIXED;
11546			else
11547				sense_format = SSD_TYPE_FIXED;
11548
11549			ua_type = ctl_build_ua(&lun->pending_ua[initidx],
11550			    &ctsio->sense_data, sense_format);
11551			if (ua_type != CTL_UA_NONE) {
11552				ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11553				ctsio->io_hdr.status = CTL_SCSI_ERROR |
11554						       CTL_AUTOSENSE;
11555				ctsio->sense_len = SSD_FULL_SIZE;
11556				mtx_unlock(&lun->lun_lock);
11557				ctl_done((union ctl_io *)ctsio);
11558				return (retval);
11559			}
11560		}
11561	}
11562
11563
11564	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11565		mtx_unlock(&lun->lun_lock);
11566		ctl_done((union ctl_io *)ctsio);
11567		return (retval);
11568	}
11569
11570	/*
11571	 * XXX CHD this is where we want to send IO to other side if
11572	 * this LUN is secondary on this SC. We will need to make a copy
11573	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11574	 * the copy we send as FROM_OTHER.
11575	 * We also need to stuff the address of the original IO so we can
11576	 * find it easily. Something similar will need be done on the other
11577	 * side so when we are done we can find the copy.
11578	 */
11579	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11580		union ctl_ha_msg msg_info;
11581		int isc_retval;
11582
11583		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11584
11585		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11586		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11587#if 0
11588		printf("1. ctsio %p\n", ctsio);
11589#endif
11590		msg_info.hdr.serializing_sc = NULL;
11591		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11592		msg_info.scsi.tag_num = ctsio->tag_num;
11593		msg_info.scsi.tag_type = ctsio->tag_type;
11594		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11595
11596		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11597
11598		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11599		    (void *)&msg_info, sizeof(msg_info), 0)) >
11600		    CTL_HA_STATUS_SUCCESS) {
11601			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11602			       isc_retval);
11603			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11604		} else {
11605#if 0
11606			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11607#endif
11608		}
11609
11610		/*
11611		 * XXX KDM this I/O is off the incoming queue, but hasn't
11612		 * been inserted on any other queue.  We may need to come
11613		 * up with a holding queue while we wait for serialization
11614		 * so that we have an idea of what we're waiting for from
11615		 * the other side.
11616		 */
11617		mtx_unlock(&lun->lun_lock);
11618		return (retval);
11619	}
11620
11621	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11622			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11623			      ctl_ooaq, ooa_links))) {
11624	case CTL_ACTION_BLOCK:
11625		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11626		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11627				  blocked_links);
11628		mtx_unlock(&lun->lun_lock);
11629		return (retval);
11630	case CTL_ACTION_PASS:
11631	case CTL_ACTION_SKIP:
11632		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11633		mtx_unlock(&lun->lun_lock);
11634		ctl_enqueue_rtr((union ctl_io *)ctsio);
11635		break;
11636	case CTL_ACTION_OVERLAP:
11637		mtx_unlock(&lun->lun_lock);
11638		ctl_set_overlapped_cmd(ctsio);
11639		ctl_done((union ctl_io *)ctsio);
11640		break;
11641	case CTL_ACTION_OVERLAP_TAG:
11642		mtx_unlock(&lun->lun_lock);
11643		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11644		ctl_done((union ctl_io *)ctsio);
11645		break;
11646	case CTL_ACTION_ERROR:
11647	default:
11648		mtx_unlock(&lun->lun_lock);
11649		ctl_set_internal_failure(ctsio,
11650					 /*sks_valid*/ 0,
11651					 /*retry_count*/ 0);
11652		ctl_done((union ctl_io *)ctsio);
11653		break;
11654	}
11655	return (retval);
11656}
11657
11658const struct ctl_cmd_entry *
11659ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11660{
11661	const struct ctl_cmd_entry *entry;
11662	int service_action;
11663
11664	entry = &ctl_cmd_table[ctsio->cdb[0]];
11665	if (sa)
11666		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11667	if (entry->flags & CTL_CMD_FLAG_SA5) {
11668		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11669		entry = &((const struct ctl_cmd_entry *)
11670		    entry->execute)[service_action];
11671	}
11672	return (entry);
11673}
11674
11675const struct ctl_cmd_entry *
11676ctl_validate_command(struct ctl_scsiio *ctsio)
11677{
11678	const struct ctl_cmd_entry *entry;
11679	int i, sa;
11680	uint8_t diff;
11681
11682	entry = ctl_get_cmd_entry(ctsio, &sa);
11683	if (entry->execute == NULL) {
11684		if (sa)
11685			ctl_set_invalid_field(ctsio,
11686					      /*sks_valid*/ 1,
11687					      /*command*/ 1,
11688					      /*field*/ 1,
11689					      /*bit_valid*/ 1,
11690					      /*bit*/ 4);
11691		else
11692			ctl_set_invalid_opcode(ctsio);
11693		ctl_done((union ctl_io *)ctsio);
11694		return (NULL);
11695	}
11696	KASSERT(entry->length > 0,
11697	    ("Not defined length for command 0x%02x/0x%02x",
11698	     ctsio->cdb[0], ctsio->cdb[1]));
11699	for (i = 1; i < entry->length; i++) {
11700		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11701		if (diff == 0)
11702			continue;
11703		ctl_set_invalid_field(ctsio,
11704				      /*sks_valid*/ 1,
11705				      /*command*/ 1,
11706				      /*field*/ i,
11707				      /*bit_valid*/ 1,
11708				      /*bit*/ fls(diff) - 1);
11709		ctl_done((union ctl_io *)ctsio);
11710		return (NULL);
11711	}
11712	return (entry);
11713}
11714
11715static int
11716ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11717{
11718
11719	switch (lun_type) {
11720	case T_PROCESSOR:
11721		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11722		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11723			return (0);
11724		break;
11725	case T_DIRECT:
11726		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11727		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11728			return (0);
11729		break;
11730	default:
11731		return (0);
11732	}
11733	return (1);
11734}
11735
11736static int
11737ctl_scsiio(struct ctl_scsiio *ctsio)
11738{
11739	int retval;
11740	const struct ctl_cmd_entry *entry;
11741
11742	retval = CTL_RETVAL_COMPLETE;
11743
11744	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11745
11746	entry = ctl_get_cmd_entry(ctsio, NULL);
11747
11748	/*
11749	 * If this I/O has been aborted, just send it straight to
11750	 * ctl_done() without executing it.
11751	 */
11752	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11753		ctl_done((union ctl_io *)ctsio);
11754		goto bailout;
11755	}
11756
11757	/*
11758	 * All the checks should have been handled by ctl_scsiio_precheck().
11759	 * We should be clear now to just execute the I/O.
11760	 */
11761	retval = entry->execute(ctsio);
11762
11763bailout:
11764	return (retval);
11765}
11766
11767/*
11768 * Since we only implement one target right now, a bus reset simply resets
11769 * our single target.
11770 */
11771static int
11772ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11773{
11774	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11775}
11776
11777static int
11778ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11779		 ctl_ua_type ua_type)
11780{
11781	struct ctl_lun *lun;
11782	int retval;
11783
11784	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11785		union ctl_ha_msg msg_info;
11786
11787		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11788		msg_info.hdr.nexus = io->io_hdr.nexus;
11789		if (ua_type==CTL_UA_TARG_RESET)
11790			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11791		else
11792			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11793		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11794		msg_info.hdr.original_sc = NULL;
11795		msg_info.hdr.serializing_sc = NULL;
11796		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11797		    (void *)&msg_info, sizeof(msg_info), 0)) {
11798		}
11799	}
11800	retval = 0;
11801
11802	mtx_lock(&ctl_softc->ctl_lock);
11803	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11804		retval += ctl_lun_reset(lun, io, ua_type);
11805	mtx_unlock(&ctl_softc->ctl_lock);
11806
11807	return (retval);
11808}
11809
11810/*
11811 * The LUN should always be set.  The I/O is optional, and is used to
11812 * distinguish between I/Os sent by this initiator, and by other
11813 * initiators.  We set unit attention for initiators other than this one.
11814 * SAM-3 is vague on this point.  It does say that a unit attention should
11815 * be established for other initiators when a LUN is reset (see section
11816 * 5.7.3), but it doesn't specifically say that the unit attention should
11817 * be established for this particular initiator when a LUN is reset.  Here
11818 * is the relevant text, from SAM-3 rev 8:
11819 *
11820 * 5.7.2 When a SCSI initiator port aborts its own tasks
11821 *
11822 * When a SCSI initiator port causes its own task(s) to be aborted, no
11823 * notification that the task(s) have been aborted shall be returned to
11824 * the SCSI initiator port other than the completion response for the
11825 * command or task management function action that caused the task(s) to
11826 * be aborted and notification(s) associated with related effects of the
11827 * action (e.g., a reset unit attention condition).
11828 *
11829 * XXX KDM for now, we're setting unit attention for all initiators.
11830 */
11831static int
11832ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11833{
11834	union ctl_io *xio;
11835#if 0
11836	uint32_t initidx;
11837#endif
11838	int i;
11839
11840	mtx_lock(&lun->lun_lock);
11841	/*
11842	 * Run through the OOA queue and abort each I/O.
11843	 */
11844#if 0
11845	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11846#endif
11847	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11848	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11849		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11850	}
11851
11852	/*
11853	 * This version sets unit attention for every
11854	 */
11855#if 0
11856	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11857	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11858		if (initidx == i)
11859			continue;
11860		lun->pending_ua[i] |= ua_type;
11861	}
11862#endif
11863
11864	/*
11865	 * A reset (any kind, really) clears reservations established with
11866	 * RESERVE/RELEASE.  It does not clear reservations established
11867	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11868	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11869	 * reservations made with the RESERVE/RELEASE commands, because
11870	 * those commands are obsolete in SPC-3.
11871	 */
11872	lun->flags &= ~CTL_LUN_RESERVED;
11873
11874	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11875#ifdef CTL_WITH_CA
11876		ctl_clear_mask(lun->have_ca, i);
11877#endif
11878		lun->pending_ua[i] |= ua_type;
11879	}
11880	mtx_unlock(&lun->lun_lock);
11881
11882	return (0);
11883}
11884
11885static void
11886ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11887    int other_sc)
11888{
11889	union ctl_io *xio;
11890
11891	mtx_assert(&lun->lun_lock, MA_OWNED);
11892
11893	/*
11894	 * Run through the OOA queue and attempt to find the given I/O.
11895	 * The target port, initiator ID, tag type and tag number have to
11896	 * match the values that we got from the initiator.  If we have an
11897	 * untagged command to abort, simply abort the first untagged command
11898	 * we come to.  We only allow one untagged command at a time of course.
11899	 */
11900	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11901	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11902
11903		if ((targ_port == UINT32_MAX ||
11904		     targ_port == xio->io_hdr.nexus.targ_port) &&
11905		    (init_id == UINT32_MAX ||
11906		     init_id == xio->io_hdr.nexus.initid.id)) {
11907			if (targ_port != xio->io_hdr.nexus.targ_port ||
11908			    init_id != xio->io_hdr.nexus.initid.id)
11909				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11910			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11911			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11912				union ctl_ha_msg msg_info;
11913
11914				msg_info.hdr.nexus = xio->io_hdr.nexus;
11915				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11916				msg_info.task.tag_num = xio->scsiio.tag_num;
11917				msg_info.task.tag_type = xio->scsiio.tag_type;
11918				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11919				msg_info.hdr.original_sc = NULL;
11920				msg_info.hdr.serializing_sc = NULL;
11921				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11922				    (void *)&msg_info, sizeof(msg_info), 0);
11923			}
11924		}
11925	}
11926}
11927
11928static int
11929ctl_abort_task_set(union ctl_io *io)
11930{
11931	struct ctl_softc *softc = control_softc;
11932	struct ctl_lun *lun;
11933	uint32_t targ_lun;
11934
11935	/*
11936	 * Look up the LUN.
11937	 */
11938	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11939	mtx_lock(&softc->ctl_lock);
11940	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
11941		lun = softc->ctl_luns[targ_lun];
11942	else {
11943		mtx_unlock(&softc->ctl_lock);
11944		return (1);
11945	}
11946
11947	mtx_lock(&lun->lun_lock);
11948	mtx_unlock(&softc->ctl_lock);
11949	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11950		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11951		    io->io_hdr.nexus.initid.id,
11952		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11953	} else { /* CTL_TASK_CLEAR_TASK_SET */
11954		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11955		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11956	}
11957	mtx_unlock(&lun->lun_lock);
11958	return (0);
11959}
11960
11961static int
11962ctl_i_t_nexus_reset(union ctl_io *io)
11963{
11964	struct ctl_softc *softc = control_softc;
11965	struct ctl_lun *lun;
11966	uint32_t initidx, residx;
11967
11968	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11969	residx = ctl_get_resindex(&io->io_hdr.nexus);
11970	mtx_lock(&softc->ctl_lock);
11971	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11972		mtx_lock(&lun->lun_lock);
11973		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11974		    io->io_hdr.nexus.initid.id,
11975		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11976#ifdef CTL_WITH_CA
11977		ctl_clear_mask(lun->have_ca, initidx);
11978#endif
11979		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
11980			lun->flags &= ~CTL_LUN_RESERVED;
11981		lun->pending_ua[initidx] |= CTL_UA_I_T_NEXUS_LOSS;
11982		mtx_unlock(&lun->lun_lock);
11983	}
11984	mtx_unlock(&softc->ctl_lock);
11985	return (0);
11986}
11987
11988static int
11989ctl_abort_task(union ctl_io *io)
11990{
11991	union ctl_io *xio;
11992	struct ctl_lun *lun;
11993	struct ctl_softc *ctl_softc;
11994#if 0
11995	struct sbuf sb;
11996	char printbuf[128];
11997#endif
11998	int found;
11999	uint32_t targ_lun;
12000
12001	ctl_softc = control_softc;
12002	found = 0;
12003
12004	/*
12005	 * Look up the LUN.
12006	 */
12007	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12008	mtx_lock(&ctl_softc->ctl_lock);
12009	if ((targ_lun < CTL_MAX_LUNS)
12010	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12011		lun = ctl_softc->ctl_luns[targ_lun];
12012	else {
12013		mtx_unlock(&ctl_softc->ctl_lock);
12014		return (1);
12015	}
12016
12017#if 0
12018	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12019	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12020#endif
12021
12022	mtx_lock(&lun->lun_lock);
12023	mtx_unlock(&ctl_softc->ctl_lock);
12024	/*
12025	 * Run through the OOA queue and attempt to find the given I/O.
12026	 * The target port, initiator ID, tag type and tag number have to
12027	 * match the values that we got from the initiator.  If we have an
12028	 * untagged command to abort, simply abort the first untagged command
12029	 * we come to.  We only allow one untagged command at a time of course.
12030	 */
12031#if 0
12032	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12033#endif
12034	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12035	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12036#if 0
12037		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12038
12039		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12040			    lun->lun, xio->scsiio.tag_num,
12041			    xio->scsiio.tag_type,
12042			    (xio->io_hdr.blocked_links.tqe_prev
12043			    == NULL) ? "" : " BLOCKED",
12044			    (xio->io_hdr.flags &
12045			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12046			    (xio->io_hdr.flags &
12047			    CTL_FLAG_ABORT) ? " ABORT" : "",
12048			    (xio->io_hdr.flags &
12049			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12050		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12051		sbuf_finish(&sb);
12052		printf("%s\n", sbuf_data(&sb));
12053#endif
12054
12055		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12056		 && (xio->io_hdr.nexus.initid.id ==
12057		     io->io_hdr.nexus.initid.id)) {
12058			/*
12059			 * If the abort says that the task is untagged, the
12060			 * task in the queue must be untagged.  Otherwise,
12061			 * we just check to see whether the tag numbers
12062			 * match.  This is because the QLogic firmware
12063			 * doesn't pass back the tag type in an abort
12064			 * request.
12065			 */
12066#if 0
12067			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12068			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12069			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12070#endif
12071			/*
12072			 * XXX KDM we've got problems with FC, because it
12073			 * doesn't send down a tag type with aborts.  So we
12074			 * can only really go by the tag number...
12075			 * This may cause problems with parallel SCSI.
12076			 * Need to figure that out!!
12077			 */
12078			if (xio->scsiio.tag_num == io->taskio.tag_num) {
12079				xio->io_hdr.flags |= CTL_FLAG_ABORT;
12080				found = 1;
12081				if ((io->io_hdr.flags &
12082				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
12083				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12084					union ctl_ha_msg msg_info;
12085
12086					io->io_hdr.flags |=
12087					                CTL_FLAG_SENT_2OTHER_SC;
12088					msg_info.hdr.nexus = io->io_hdr.nexus;
12089					msg_info.task.task_action =
12090						CTL_TASK_ABORT_TASK;
12091					msg_info.task.tag_num =
12092						io->taskio.tag_num;
12093					msg_info.task.tag_type =
12094						io->taskio.tag_type;
12095					msg_info.hdr.msg_type =
12096						CTL_MSG_MANAGE_TASKS;
12097					msg_info.hdr.original_sc = NULL;
12098					msg_info.hdr.serializing_sc = NULL;
12099#if 0
12100					printf("Sent Abort to other side\n");
12101#endif
12102					if (CTL_HA_STATUS_SUCCESS !=
12103					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12104		    				(void *)&msg_info,
12105						sizeof(msg_info), 0)) {
12106					}
12107				}
12108#if 0
12109				printf("ctl_abort_task: found I/O to abort\n");
12110#endif
12111				break;
12112			}
12113		}
12114	}
12115	mtx_unlock(&lun->lun_lock);
12116
12117	if (found == 0) {
12118		/*
12119		 * This isn't really an error.  It's entirely possible for
12120		 * the abort and command completion to cross on the wire.
12121		 * This is more of an informative/diagnostic error.
12122		 */
12123#if 0
12124		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12125		       "%d:%d:%d:%d tag %d type %d\n",
12126		       io->io_hdr.nexus.initid.id,
12127		       io->io_hdr.nexus.targ_port,
12128		       io->io_hdr.nexus.targ_target.id,
12129		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12130		       io->taskio.tag_type);
12131#endif
12132	}
12133	return (0);
12134}
12135
12136static void
12137ctl_run_task(union ctl_io *io)
12138{
12139	struct ctl_softc *ctl_softc = control_softc;
12140	int retval = 1;
12141	const char *task_desc;
12142
12143	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12144
12145	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12146	    ("ctl_run_task: Unextected io_type %d\n",
12147	     io->io_hdr.io_type));
12148
12149	task_desc = ctl_scsi_task_string(&io->taskio);
12150	if (task_desc != NULL) {
12151#ifdef NEEDTOPORT
12152		csevent_log(CSC_CTL | CSC_SHELF_SW |
12153			    CTL_TASK_REPORT,
12154			    csevent_LogType_Trace,
12155			    csevent_Severity_Information,
12156			    csevent_AlertLevel_Green,
12157			    csevent_FRU_Firmware,
12158			    csevent_FRU_Unknown,
12159			    "CTL: received task: %s",task_desc);
12160#endif
12161	} else {
12162#ifdef NEEDTOPORT
12163		csevent_log(CSC_CTL | CSC_SHELF_SW |
12164			    CTL_TASK_REPORT,
12165			    csevent_LogType_Trace,
12166			    csevent_Severity_Information,
12167			    csevent_AlertLevel_Green,
12168			    csevent_FRU_Firmware,
12169			    csevent_FRU_Unknown,
12170			    "CTL: received unknown task "
12171			    "type: %d (%#x)",
12172			    io->taskio.task_action,
12173			    io->taskio.task_action);
12174#endif
12175	}
12176	switch (io->taskio.task_action) {
12177	case CTL_TASK_ABORT_TASK:
12178		retval = ctl_abort_task(io);
12179		break;
12180	case CTL_TASK_ABORT_TASK_SET:
12181	case CTL_TASK_CLEAR_TASK_SET:
12182		retval = ctl_abort_task_set(io);
12183		break;
12184	case CTL_TASK_CLEAR_ACA:
12185		break;
12186	case CTL_TASK_I_T_NEXUS_RESET:
12187		retval = ctl_i_t_nexus_reset(io);
12188		break;
12189	case CTL_TASK_LUN_RESET: {
12190		struct ctl_lun *lun;
12191		uint32_t targ_lun;
12192
12193		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12194		mtx_lock(&ctl_softc->ctl_lock);
12195		if ((targ_lun < CTL_MAX_LUNS)
12196		 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12197			lun = ctl_softc->ctl_luns[targ_lun];
12198		else {
12199			mtx_unlock(&ctl_softc->ctl_lock);
12200			retval = 1;
12201			break;
12202		}
12203
12204		if (!(io->io_hdr.flags &
12205		    CTL_FLAG_FROM_OTHER_SC)) {
12206			union ctl_ha_msg msg_info;
12207
12208			io->io_hdr.flags |=
12209				CTL_FLAG_SENT_2OTHER_SC;
12210			msg_info.hdr.msg_type =
12211				CTL_MSG_MANAGE_TASKS;
12212			msg_info.hdr.nexus = io->io_hdr.nexus;
12213			msg_info.task.task_action =
12214				CTL_TASK_LUN_RESET;
12215			msg_info.hdr.original_sc = NULL;
12216			msg_info.hdr.serializing_sc = NULL;
12217			if (CTL_HA_STATUS_SUCCESS !=
12218			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12219			    (void *)&msg_info,
12220			    sizeof(msg_info), 0)) {
12221			}
12222		}
12223
12224		retval = ctl_lun_reset(lun, io,
12225				       CTL_UA_LUN_RESET);
12226		mtx_unlock(&ctl_softc->ctl_lock);
12227		break;
12228	}
12229	case CTL_TASK_TARGET_RESET:
12230		retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12231		break;
12232	case CTL_TASK_BUS_RESET:
12233		retval = ctl_bus_reset(ctl_softc, io);
12234		break;
12235	case CTL_TASK_PORT_LOGIN:
12236		break;
12237	case CTL_TASK_PORT_LOGOUT:
12238		break;
12239	default:
12240		printf("ctl_run_task: got unknown task management event %d\n",
12241		       io->taskio.task_action);
12242		break;
12243	}
12244	if (retval == 0)
12245		io->io_hdr.status = CTL_SUCCESS;
12246	else
12247		io->io_hdr.status = CTL_ERROR;
12248	ctl_done(io);
12249}
12250
12251/*
12252 * For HA operation.  Handle commands that come in from the other
12253 * controller.
12254 */
12255static void
12256ctl_handle_isc(union ctl_io *io)
12257{
12258	int free_io;
12259	struct ctl_lun *lun;
12260	struct ctl_softc *ctl_softc;
12261	uint32_t targ_lun;
12262
12263	ctl_softc = control_softc;
12264
12265	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12266	lun = ctl_softc->ctl_luns[targ_lun];
12267
12268	switch (io->io_hdr.msg_type) {
12269	case CTL_MSG_SERIALIZE:
12270		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12271		break;
12272	case CTL_MSG_R2R: {
12273		const struct ctl_cmd_entry *entry;
12274
12275		/*
12276		 * This is only used in SER_ONLY mode.
12277		 */
12278		free_io = 0;
12279		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12280		mtx_lock(&lun->lun_lock);
12281		if (ctl_scsiio_lun_check(ctl_softc, lun,
12282		    entry, (struct ctl_scsiio *)io) != 0) {
12283			mtx_unlock(&lun->lun_lock);
12284			ctl_done(io);
12285			break;
12286		}
12287		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12288		mtx_unlock(&lun->lun_lock);
12289		ctl_enqueue_rtr(io);
12290		break;
12291	}
12292	case CTL_MSG_FINISH_IO:
12293		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12294			free_io = 0;
12295			ctl_done(io);
12296		} else {
12297			free_io = 1;
12298			mtx_lock(&lun->lun_lock);
12299			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12300				     ooa_links);
12301			ctl_check_blocked(lun);
12302			mtx_unlock(&lun->lun_lock);
12303		}
12304		break;
12305	case CTL_MSG_PERS_ACTION:
12306		ctl_hndl_per_res_out_on_other_sc(
12307			(union ctl_ha_msg *)&io->presio.pr_msg);
12308		free_io = 1;
12309		break;
12310	case CTL_MSG_BAD_JUJU:
12311		free_io = 0;
12312		ctl_done(io);
12313		break;
12314	case CTL_MSG_DATAMOVE:
12315		/* Only used in XFER mode */
12316		free_io = 0;
12317		ctl_datamove_remote(io);
12318		break;
12319	case CTL_MSG_DATAMOVE_DONE:
12320		/* Only used in XFER mode */
12321		free_io = 0;
12322		io->scsiio.be_move_done(io);
12323		break;
12324	default:
12325		free_io = 1;
12326		printf("%s: Invalid message type %d\n",
12327		       __func__, io->io_hdr.msg_type);
12328		break;
12329	}
12330	if (free_io)
12331		ctl_free_io(io);
12332
12333}
12334
12335
12336/*
12337 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12338 * there is no match.
12339 */
12340static ctl_lun_error_pattern
12341ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12342{
12343	const struct ctl_cmd_entry *entry;
12344	ctl_lun_error_pattern filtered_pattern, pattern;
12345
12346	pattern = desc->error_pattern;
12347
12348	/*
12349	 * XXX KDM we need more data passed into this function to match a
12350	 * custom pattern, and we actually need to implement custom pattern
12351	 * matching.
12352	 */
12353	if (pattern & CTL_LUN_PAT_CMD)
12354		return (CTL_LUN_PAT_CMD);
12355
12356	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12357		return (CTL_LUN_PAT_ANY);
12358
12359	entry = ctl_get_cmd_entry(ctsio, NULL);
12360
12361	filtered_pattern = entry->pattern & pattern;
12362
12363	/*
12364	 * If the user requested specific flags in the pattern (e.g.
12365	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12366	 * flags.
12367	 *
12368	 * If the user did not specify any flags, it doesn't matter whether
12369	 * or not the command supports the flags.
12370	 */
12371	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12372	     (pattern & ~CTL_LUN_PAT_MASK))
12373		return (CTL_LUN_PAT_NONE);
12374
12375	/*
12376	 * If the user asked for a range check, see if the requested LBA
12377	 * range overlaps with this command's LBA range.
12378	 */
12379	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12380		uint64_t lba1;
12381		uint64_t len1;
12382		ctl_action action;
12383		int retval;
12384
12385		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12386		if (retval != 0)
12387			return (CTL_LUN_PAT_NONE);
12388
12389		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12390					      desc->lba_range.len);
12391		/*
12392		 * A "pass" means that the LBA ranges don't overlap, so
12393		 * this doesn't match the user's range criteria.
12394		 */
12395		if (action == CTL_ACTION_PASS)
12396			return (CTL_LUN_PAT_NONE);
12397	}
12398
12399	return (filtered_pattern);
12400}
12401
12402static void
12403ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12404{
12405	struct ctl_error_desc *desc, *desc2;
12406
12407	mtx_assert(&lun->lun_lock, MA_OWNED);
12408
12409	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12410		ctl_lun_error_pattern pattern;
12411		/*
12412		 * Check to see whether this particular command matches
12413		 * the pattern in the descriptor.
12414		 */
12415		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12416		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12417			continue;
12418
12419		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12420		case CTL_LUN_INJ_ABORTED:
12421			ctl_set_aborted(&io->scsiio);
12422			break;
12423		case CTL_LUN_INJ_MEDIUM_ERR:
12424			ctl_set_medium_error(&io->scsiio);
12425			break;
12426		case CTL_LUN_INJ_UA:
12427			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12428			 * OCCURRED */
12429			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12430			break;
12431		case CTL_LUN_INJ_CUSTOM:
12432			/*
12433			 * We're assuming the user knows what he is doing.
12434			 * Just copy the sense information without doing
12435			 * checks.
12436			 */
12437			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12438			      ctl_min(sizeof(desc->custom_sense),
12439				      sizeof(io->scsiio.sense_data)));
12440			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12441			io->scsiio.sense_len = SSD_FULL_SIZE;
12442			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12443			break;
12444		case CTL_LUN_INJ_NONE:
12445		default:
12446			/*
12447			 * If this is an error injection type we don't know
12448			 * about, clear the continuous flag (if it is set)
12449			 * so it will get deleted below.
12450			 */
12451			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12452			break;
12453		}
12454		/*
12455		 * By default, each error injection action is a one-shot
12456		 */
12457		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12458			continue;
12459
12460		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12461
12462		free(desc, M_CTL);
12463	}
12464}
12465
12466#ifdef CTL_IO_DELAY
12467static void
12468ctl_datamove_timer_wakeup(void *arg)
12469{
12470	union ctl_io *io;
12471
12472	io = (union ctl_io *)arg;
12473
12474	ctl_datamove(io);
12475}
12476#endif /* CTL_IO_DELAY */
12477
12478void
12479ctl_datamove(union ctl_io *io)
12480{
12481	void (*fe_datamove)(union ctl_io *io);
12482
12483	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12484
12485	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12486
12487#ifdef CTL_TIME_IO
12488	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12489		char str[256];
12490		char path_str[64];
12491		struct sbuf sb;
12492
12493		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12494		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12495
12496		sbuf_cat(&sb, path_str);
12497		switch (io->io_hdr.io_type) {
12498		case CTL_IO_SCSI:
12499			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12500			sbuf_printf(&sb, "\n");
12501			sbuf_cat(&sb, path_str);
12502			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12503				    io->scsiio.tag_num, io->scsiio.tag_type);
12504			break;
12505		case CTL_IO_TASK:
12506			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12507				    "Tag Type: %d\n", io->taskio.task_action,
12508				    io->taskio.tag_num, io->taskio.tag_type);
12509			break;
12510		default:
12511			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12512			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12513			break;
12514		}
12515		sbuf_cat(&sb, path_str);
12516		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12517			    (intmax_t)time_uptime - io->io_hdr.start_time);
12518		sbuf_finish(&sb);
12519		printf("%s", sbuf_data(&sb));
12520	}
12521#endif /* CTL_TIME_IO */
12522
12523#ifdef CTL_IO_DELAY
12524	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12525		struct ctl_lun *lun;
12526
12527		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12528
12529		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12530	} else {
12531		struct ctl_lun *lun;
12532
12533		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12534		if ((lun != NULL)
12535		 && (lun->delay_info.datamove_delay > 0)) {
12536			struct callout *callout;
12537
12538			callout = (struct callout *)&io->io_hdr.timer_bytes;
12539			callout_init(callout, /*mpsafe*/ 1);
12540			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12541			callout_reset(callout,
12542				      lun->delay_info.datamove_delay * hz,
12543				      ctl_datamove_timer_wakeup, io);
12544			if (lun->delay_info.datamove_type ==
12545			    CTL_DELAY_TYPE_ONESHOT)
12546				lun->delay_info.datamove_delay = 0;
12547			return;
12548		}
12549	}
12550#endif
12551
12552	/*
12553	 * This command has been aborted.  Set the port status, so we fail
12554	 * the data move.
12555	 */
12556	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12557		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12558		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12559		       io->io_hdr.nexus.targ_port,
12560		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12561		       io->io_hdr.nexus.targ_lun);
12562		io->io_hdr.port_status = 31337;
12563		/*
12564		 * Note that the backend, in this case, will get the
12565		 * callback in its context.  In other cases it may get
12566		 * called in the frontend's interrupt thread context.
12567		 */
12568		io->scsiio.be_move_done(io);
12569		return;
12570	}
12571
12572	/* Don't confuse frontend with zero length data move. */
12573	if (io->scsiio.kern_data_len == 0) {
12574		io->scsiio.be_move_done(io);
12575		return;
12576	}
12577
12578	/*
12579	 * If we're in XFER mode and this I/O is from the other shelf
12580	 * controller, we need to send the DMA to the other side to
12581	 * actually transfer the data to/from the host.  In serialize only
12582	 * mode the transfer happens below CTL and ctl_datamove() is only
12583	 * called on the machine that originally received the I/O.
12584	 */
12585	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12586	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12587		union ctl_ha_msg msg;
12588		uint32_t sg_entries_sent;
12589		int do_sg_copy;
12590		int i;
12591
12592		memset(&msg, 0, sizeof(msg));
12593		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12594		msg.hdr.original_sc = io->io_hdr.original_sc;
12595		msg.hdr.serializing_sc = io;
12596		msg.hdr.nexus = io->io_hdr.nexus;
12597		msg.dt.flags = io->io_hdr.flags;
12598		/*
12599		 * We convert everything into a S/G list here.  We can't
12600		 * pass by reference, only by value between controllers.
12601		 * So we can't pass a pointer to the S/G list, only as many
12602		 * S/G entries as we can fit in here.  If it's possible for
12603		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12604		 * then we need to break this up into multiple transfers.
12605		 */
12606		if (io->scsiio.kern_sg_entries == 0) {
12607			msg.dt.kern_sg_entries = 1;
12608			/*
12609			 * If this is in cached memory, flush the cache
12610			 * before we send the DMA request to the other
12611			 * controller.  We want to do this in either the
12612			 * read or the write case.  The read case is
12613			 * straightforward.  In the write case, we want to
12614			 * make sure nothing is in the local cache that
12615			 * could overwrite the DMAed data.
12616			 */
12617			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12618				/*
12619				 * XXX KDM use bus_dmamap_sync() here.
12620				 */
12621			}
12622
12623			/*
12624			 * Convert to a physical address if this is a
12625			 * virtual address.
12626			 */
12627			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12628				msg.dt.sg_list[0].addr =
12629					io->scsiio.kern_data_ptr;
12630			} else {
12631				/*
12632				 * XXX KDM use busdma here!
12633				 */
12634#if 0
12635				msg.dt.sg_list[0].addr = (void *)
12636					vtophys(io->scsiio.kern_data_ptr);
12637#endif
12638			}
12639
12640			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12641			do_sg_copy = 0;
12642		} else {
12643			struct ctl_sg_entry *sgl;
12644
12645			do_sg_copy = 1;
12646			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12647			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12648			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12649				/*
12650				 * XXX KDM use bus_dmamap_sync() here.
12651				 */
12652			}
12653		}
12654
12655		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12656		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12657		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12658		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12659		msg.dt.sg_sequence = 0;
12660
12661		/*
12662		 * Loop until we've sent all of the S/G entries.  On the
12663		 * other end, we'll recompose these S/G entries into one
12664		 * contiguous list before passing it to the
12665		 */
12666		for (sg_entries_sent = 0; sg_entries_sent <
12667		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12668			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12669				sizeof(msg.dt.sg_list[0])),
12670				msg.dt.kern_sg_entries - sg_entries_sent);
12671
12672			if (do_sg_copy != 0) {
12673				struct ctl_sg_entry *sgl;
12674				int j;
12675
12676				sgl = (struct ctl_sg_entry *)
12677					io->scsiio.kern_data_ptr;
12678				/*
12679				 * If this is in cached memory, flush the cache
12680				 * before we send the DMA request to the other
12681				 * controller.  We want to do this in either
12682				 * the * read or the write case.  The read
12683				 * case is straightforward.  In the write
12684				 * case, we want to make sure nothing is
12685				 * in the local cache that could overwrite
12686				 * the DMAed data.
12687				 */
12688
12689				for (i = sg_entries_sent, j = 0;
12690				     i < msg.dt.cur_sg_entries; i++, j++) {
12691					if ((io->io_hdr.flags &
12692					     CTL_FLAG_NO_DATASYNC) == 0) {
12693						/*
12694						 * XXX KDM use bus_dmamap_sync()
12695						 */
12696					}
12697					if ((io->io_hdr.flags &
12698					     CTL_FLAG_BUS_ADDR) == 0) {
12699						/*
12700						 * XXX KDM use busdma.
12701						 */
12702#if 0
12703						msg.dt.sg_list[j].addr =(void *)
12704						       vtophys(sgl[i].addr);
12705#endif
12706					} else {
12707						msg.dt.sg_list[j].addr =
12708							sgl[i].addr;
12709					}
12710					msg.dt.sg_list[j].len = sgl[i].len;
12711				}
12712			}
12713
12714			sg_entries_sent += msg.dt.cur_sg_entries;
12715			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12716				msg.dt.sg_last = 1;
12717			else
12718				msg.dt.sg_last = 0;
12719
12720			/*
12721			 * XXX KDM drop and reacquire the lock here?
12722			 */
12723			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12724			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12725				/*
12726				 * XXX do something here.
12727				 */
12728			}
12729
12730			msg.dt.sent_sg_entries = sg_entries_sent;
12731		}
12732		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12733		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12734			ctl_failover_io(io, /*have_lock*/ 0);
12735
12736	} else {
12737
12738		/*
12739		 * Lookup the fe_datamove() function for this particular
12740		 * front end.
12741		 */
12742		fe_datamove =
12743		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12744
12745		fe_datamove(io);
12746	}
12747}
12748
12749static void
12750ctl_send_datamove_done(union ctl_io *io, int have_lock)
12751{
12752	union ctl_ha_msg msg;
12753	int isc_status;
12754
12755	memset(&msg, 0, sizeof(msg));
12756
12757	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12758	msg.hdr.original_sc = io;
12759	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12760	msg.hdr.nexus = io->io_hdr.nexus;
12761	msg.hdr.status = io->io_hdr.status;
12762	msg.scsi.tag_num = io->scsiio.tag_num;
12763	msg.scsi.tag_type = io->scsiio.tag_type;
12764	msg.scsi.scsi_status = io->scsiio.scsi_status;
12765	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12766	       sizeof(io->scsiio.sense_data));
12767	msg.scsi.sense_len = io->scsiio.sense_len;
12768	msg.scsi.sense_residual = io->scsiio.sense_residual;
12769	msg.scsi.fetd_status = io->io_hdr.port_status;
12770	msg.scsi.residual = io->scsiio.residual;
12771	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12772
12773	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12774		ctl_failover_io(io, /*have_lock*/ have_lock);
12775		return;
12776	}
12777
12778	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12779	if (isc_status > CTL_HA_STATUS_SUCCESS) {
12780		/* XXX do something if this fails */
12781	}
12782
12783}
12784
12785/*
12786 * The DMA to the remote side is done, now we need to tell the other side
12787 * we're done so it can continue with its data movement.
12788 */
12789static void
12790ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12791{
12792	union ctl_io *io;
12793
12794	io = rq->context;
12795
12796	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12797		printf("%s: ISC DMA write failed with error %d", __func__,
12798		       rq->ret);
12799		ctl_set_internal_failure(&io->scsiio,
12800					 /*sks_valid*/ 1,
12801					 /*retry_count*/ rq->ret);
12802	}
12803
12804	ctl_dt_req_free(rq);
12805
12806	/*
12807	 * In this case, we had to malloc the memory locally.  Free it.
12808	 */
12809	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12810		int i;
12811		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12812			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12813	}
12814	/*
12815	 * The data is in local and remote memory, so now we need to send
12816	 * status (good or back) back to the other side.
12817	 */
12818	ctl_send_datamove_done(io, /*have_lock*/ 0);
12819}
12820
12821/*
12822 * We've moved the data from the host/controller into local memory.  Now we
12823 * need to push it over to the remote controller's memory.
12824 */
12825static int
12826ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12827{
12828	int retval;
12829
12830	retval = 0;
12831
12832	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12833					  ctl_datamove_remote_write_cb);
12834
12835	return (retval);
12836}
12837
12838static void
12839ctl_datamove_remote_write(union ctl_io *io)
12840{
12841	int retval;
12842	void (*fe_datamove)(union ctl_io *io);
12843
12844	/*
12845	 * - Get the data from the host/HBA into local memory.
12846	 * - DMA memory from the local controller to the remote controller.
12847	 * - Send status back to the remote controller.
12848	 */
12849
12850	retval = ctl_datamove_remote_sgl_setup(io);
12851	if (retval != 0)
12852		return;
12853
12854	/* Switch the pointer over so the FETD knows what to do */
12855	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12856
12857	/*
12858	 * Use a custom move done callback, since we need to send completion
12859	 * back to the other controller, not to the backend on this side.
12860	 */
12861	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12862
12863	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12864
12865	fe_datamove(io);
12866
12867	return;
12868
12869}
12870
12871static int
12872ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12873{
12874#if 0
12875	char str[256];
12876	char path_str[64];
12877	struct sbuf sb;
12878#endif
12879
12880	/*
12881	 * In this case, we had to malloc the memory locally.  Free it.
12882	 */
12883	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12884		int i;
12885		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12886			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12887	}
12888
12889#if 0
12890	scsi_path_string(io, path_str, sizeof(path_str));
12891	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12892	sbuf_cat(&sb, path_str);
12893	scsi_command_string(&io->scsiio, NULL, &sb);
12894	sbuf_printf(&sb, "\n");
12895	sbuf_cat(&sb, path_str);
12896	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12897		    io->scsiio.tag_num, io->scsiio.tag_type);
12898	sbuf_cat(&sb, path_str);
12899	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12900		    io->io_hdr.flags, io->io_hdr.status);
12901	sbuf_finish(&sb);
12902	printk("%s", sbuf_data(&sb));
12903#endif
12904
12905
12906	/*
12907	 * The read is done, now we need to send status (good or bad) back
12908	 * to the other side.
12909	 */
12910	ctl_send_datamove_done(io, /*have_lock*/ 0);
12911
12912	return (0);
12913}
12914
12915static void
12916ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12917{
12918	union ctl_io *io;
12919	void (*fe_datamove)(union ctl_io *io);
12920
12921	io = rq->context;
12922
12923	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12924		printf("%s: ISC DMA read failed with error %d", __func__,
12925		       rq->ret);
12926		ctl_set_internal_failure(&io->scsiio,
12927					 /*sks_valid*/ 1,
12928					 /*retry_count*/ rq->ret);
12929	}
12930
12931	ctl_dt_req_free(rq);
12932
12933	/* Switch the pointer over so the FETD knows what to do */
12934	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12935
12936	/*
12937	 * Use a custom move done callback, since we need to send completion
12938	 * back to the other controller, not to the backend on this side.
12939	 */
12940	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12941
12942	/* XXX KDM add checks like the ones in ctl_datamove? */
12943
12944	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12945
12946	fe_datamove(io);
12947}
12948
12949static int
12950ctl_datamove_remote_sgl_setup(union ctl_io *io)
12951{
12952	struct ctl_sg_entry *local_sglist, *remote_sglist;
12953	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
12954	struct ctl_softc *softc;
12955	int retval;
12956	int i;
12957
12958	retval = 0;
12959	softc = control_softc;
12960
12961	local_sglist = io->io_hdr.local_sglist;
12962	local_dma_sglist = io->io_hdr.local_dma_sglist;
12963	remote_sglist = io->io_hdr.remote_sglist;
12964	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
12965
12966	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
12967		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
12968			local_sglist[i].len = remote_sglist[i].len;
12969
12970			/*
12971			 * XXX Detect the situation where the RS-level I/O
12972			 * redirector on the other side has already read the
12973			 * data off of the AOR RS on this side, and
12974			 * transferred it to remote (mirror) memory on the
12975			 * other side.  Since we already have the data in
12976			 * memory here, we just need to use it.
12977			 *
12978			 * XXX KDM this can probably be removed once we
12979			 * get the cache device code in and take the
12980			 * current AOR implementation out.
12981			 */
12982#ifdef NEEDTOPORT
12983			if ((remote_sglist[i].addr >=
12984			     (void *)vtophys(softc->mirr->addr))
12985			 && (remote_sglist[i].addr <
12986			     ((void *)vtophys(softc->mirr->addr) +
12987			     CacheMirrorOffset))) {
12988				local_sglist[i].addr = remote_sglist[i].addr -
12989					CacheMirrorOffset;
12990				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12991				     CTL_FLAG_DATA_IN)
12992					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
12993			} else {
12994				local_sglist[i].addr = remote_sglist[i].addr +
12995					CacheMirrorOffset;
12996			}
12997#endif
12998#if 0
12999			printf("%s: local %p, remote %p, len %d\n",
13000			       __func__, local_sglist[i].addr,
13001			       remote_sglist[i].addr, local_sglist[i].len);
13002#endif
13003		}
13004	} else {
13005		uint32_t len_to_go;
13006
13007		/*
13008		 * In this case, we don't have automatically allocated
13009		 * memory for this I/O on this controller.  This typically
13010		 * happens with internal CTL I/O -- e.g. inquiry, mode
13011		 * sense, etc.  Anything coming from RAIDCore will have
13012		 * a mirror area available.
13013		 */
13014		len_to_go = io->scsiio.kern_data_len;
13015
13016		/*
13017		 * Clear the no datasync flag, we have to use malloced
13018		 * buffers.
13019		 */
13020		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13021
13022		/*
13023		 * The difficult thing here is that the size of the various
13024		 * S/G segments may be different than the size from the
13025		 * remote controller.  That'll make it harder when DMAing
13026		 * the data back to the other side.
13027		 */
13028		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13029		     sizeof(io->io_hdr.remote_sglist[0])) &&
13030		     (len_to_go > 0); i++) {
13031			local_sglist[i].len = ctl_min(len_to_go, 131072);
13032			CTL_SIZE_8B(local_dma_sglist[i].len,
13033				    local_sglist[i].len);
13034			local_sglist[i].addr =
13035				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13036
13037			local_dma_sglist[i].addr = local_sglist[i].addr;
13038
13039			if (local_sglist[i].addr == NULL) {
13040				int j;
13041
13042				printf("malloc failed for %zd bytes!",
13043				       local_dma_sglist[i].len);
13044				for (j = 0; j < i; j++) {
13045					free(local_sglist[j].addr, M_CTL);
13046				}
13047				ctl_set_internal_failure(&io->scsiio,
13048							 /*sks_valid*/ 1,
13049							 /*retry_count*/ 4857);
13050				retval = 1;
13051				goto bailout_error;
13052
13053			}
13054			/* XXX KDM do we need a sync here? */
13055
13056			len_to_go -= local_sglist[i].len;
13057		}
13058		/*
13059		 * Reset the number of S/G entries accordingly.  The
13060		 * original number of S/G entries is available in
13061		 * rem_sg_entries.
13062		 */
13063		io->scsiio.kern_sg_entries = i;
13064
13065#if 0
13066		printf("%s: kern_sg_entries = %d\n", __func__,
13067		       io->scsiio.kern_sg_entries);
13068		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13069			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13070			       local_sglist[i].addr, local_sglist[i].len,
13071			       local_dma_sglist[i].len);
13072#endif
13073	}
13074
13075
13076	return (retval);
13077
13078bailout_error:
13079
13080	ctl_send_datamove_done(io, /*have_lock*/ 0);
13081
13082	return (retval);
13083}
13084
13085static int
13086ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13087			 ctl_ha_dt_cb callback)
13088{
13089	struct ctl_ha_dt_req *rq;
13090	struct ctl_sg_entry *remote_sglist, *local_sglist;
13091	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13092	uint32_t local_used, remote_used, total_used;
13093	int retval;
13094	int i, j;
13095
13096	retval = 0;
13097
13098	rq = ctl_dt_req_alloc();
13099
13100	/*
13101	 * If we failed to allocate the request, and if the DMA didn't fail
13102	 * anyway, set busy status.  This is just a resource allocation
13103	 * failure.
13104	 */
13105	if ((rq == NULL)
13106	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13107		ctl_set_busy(&io->scsiio);
13108
13109	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13110
13111		if (rq != NULL)
13112			ctl_dt_req_free(rq);
13113
13114		/*
13115		 * The data move failed.  We need to return status back
13116		 * to the other controller.  No point in trying to DMA
13117		 * data to the remote controller.
13118		 */
13119
13120		ctl_send_datamove_done(io, /*have_lock*/ 0);
13121
13122		retval = 1;
13123
13124		goto bailout;
13125	}
13126
13127	local_sglist = io->io_hdr.local_sglist;
13128	local_dma_sglist = io->io_hdr.local_dma_sglist;
13129	remote_sglist = io->io_hdr.remote_sglist;
13130	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13131	local_used = 0;
13132	remote_used = 0;
13133	total_used = 0;
13134
13135	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13136		rq->ret = CTL_HA_STATUS_SUCCESS;
13137		rq->context = io;
13138		callback(rq);
13139		goto bailout;
13140	}
13141
13142	/*
13143	 * Pull/push the data over the wire from/to the other controller.
13144	 * This takes into account the possibility that the local and
13145	 * remote sglists may not be identical in terms of the size of
13146	 * the elements and the number of elements.
13147	 *
13148	 * One fundamental assumption here is that the length allocated for
13149	 * both the local and remote sglists is identical.  Otherwise, we've
13150	 * essentially got a coding error of some sort.
13151	 */
13152	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13153		int isc_ret;
13154		uint32_t cur_len, dma_length;
13155		uint8_t *tmp_ptr;
13156
13157		rq->id = CTL_HA_DATA_CTL;
13158		rq->command = command;
13159		rq->context = io;
13160
13161		/*
13162		 * Both pointers should be aligned.  But it is possible
13163		 * that the allocation length is not.  They should both
13164		 * also have enough slack left over at the end, though,
13165		 * to round up to the next 8 byte boundary.
13166		 */
13167		cur_len = ctl_min(local_sglist[i].len - local_used,
13168				  remote_sglist[j].len - remote_used);
13169
13170		/*
13171		 * In this case, we have a size issue and need to decrease
13172		 * the size, except in the case where we actually have less
13173		 * than 8 bytes left.  In that case, we need to increase
13174		 * the DMA length to get the last bit.
13175		 */
13176		if ((cur_len & 0x7) != 0) {
13177			if (cur_len > 0x7) {
13178				cur_len = cur_len - (cur_len & 0x7);
13179				dma_length = cur_len;
13180			} else {
13181				CTL_SIZE_8B(dma_length, cur_len);
13182			}
13183
13184		} else
13185			dma_length = cur_len;
13186
13187		/*
13188		 * If we had to allocate memory for this I/O, instead of using
13189		 * the non-cached mirror memory, we'll need to flush the cache
13190		 * before trying to DMA to the other controller.
13191		 *
13192		 * We could end up doing this multiple times for the same
13193		 * segment if we have a larger local segment than remote
13194		 * segment.  That shouldn't be an issue.
13195		 */
13196		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13197			/*
13198			 * XXX KDM use bus_dmamap_sync() here.
13199			 */
13200		}
13201
13202		rq->size = dma_length;
13203
13204		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13205		tmp_ptr += local_used;
13206
13207		/* Use physical addresses when talking to ISC hardware */
13208		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13209			/* XXX KDM use busdma */
13210#if 0
13211			rq->local = vtophys(tmp_ptr);
13212#endif
13213		} else
13214			rq->local = tmp_ptr;
13215
13216		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13217		tmp_ptr += remote_used;
13218		rq->remote = tmp_ptr;
13219
13220		rq->callback = NULL;
13221
13222		local_used += cur_len;
13223		if (local_used >= local_sglist[i].len) {
13224			i++;
13225			local_used = 0;
13226		}
13227
13228		remote_used += cur_len;
13229		if (remote_used >= remote_sglist[j].len) {
13230			j++;
13231			remote_used = 0;
13232		}
13233		total_used += cur_len;
13234
13235		if (total_used >= io->scsiio.kern_data_len)
13236			rq->callback = callback;
13237
13238		if ((rq->size & 0x7) != 0) {
13239			printf("%s: warning: size %d is not on 8b boundary\n",
13240			       __func__, rq->size);
13241		}
13242		if (((uintptr_t)rq->local & 0x7) != 0) {
13243			printf("%s: warning: local %p not on 8b boundary\n",
13244			       __func__, rq->local);
13245		}
13246		if (((uintptr_t)rq->remote & 0x7) != 0) {
13247			printf("%s: warning: remote %p not on 8b boundary\n",
13248			       __func__, rq->local);
13249		}
13250#if 0
13251		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13252		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13253		       rq->local, rq->remote, rq->size);
13254#endif
13255
13256		isc_ret = ctl_dt_single(rq);
13257		if (isc_ret == CTL_HA_STATUS_WAIT)
13258			continue;
13259
13260		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13261			rq->ret = CTL_HA_STATUS_SUCCESS;
13262		} else {
13263			rq->ret = isc_ret;
13264		}
13265		callback(rq);
13266		goto bailout;
13267	}
13268
13269bailout:
13270	return (retval);
13271
13272}
13273
13274static void
13275ctl_datamove_remote_read(union ctl_io *io)
13276{
13277	int retval;
13278	int i;
13279
13280	/*
13281	 * This will send an error to the other controller in the case of a
13282	 * failure.
13283	 */
13284	retval = ctl_datamove_remote_sgl_setup(io);
13285	if (retval != 0)
13286		return;
13287
13288	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13289					  ctl_datamove_remote_read_cb);
13290	if ((retval != 0)
13291	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13292		/*
13293		 * Make sure we free memory if there was an error..  The
13294		 * ctl_datamove_remote_xfer() function will send the
13295		 * datamove done message, or call the callback with an
13296		 * error if there is a problem.
13297		 */
13298		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13299			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13300	}
13301
13302	return;
13303}
13304
13305/*
13306 * Process a datamove request from the other controller.  This is used for
13307 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13308 * first.  Once that is complete, the data gets DMAed into the remote
13309 * controller's memory.  For reads, we DMA from the remote controller's
13310 * memory into our memory first, and then move it out to the FETD.
13311 */
13312static void
13313ctl_datamove_remote(union ctl_io *io)
13314{
13315	struct ctl_softc *softc;
13316
13317	softc = control_softc;
13318
13319	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13320
13321	/*
13322	 * Note that we look for an aborted I/O here, but don't do some of
13323	 * the other checks that ctl_datamove() normally does.
13324	 * We don't need to run the datamove delay code, since that should
13325	 * have been done if need be on the other controller.
13326	 */
13327	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13328		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13329		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13330		       io->io_hdr.nexus.targ_port,
13331		       io->io_hdr.nexus.targ_target.id,
13332		       io->io_hdr.nexus.targ_lun);
13333		io->io_hdr.port_status = 31338;
13334		ctl_send_datamove_done(io, /*have_lock*/ 0);
13335		return;
13336	}
13337
13338	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13339		ctl_datamove_remote_write(io);
13340	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13341		ctl_datamove_remote_read(io);
13342	} else {
13343		union ctl_ha_msg msg;
13344		struct scsi_sense_data *sense;
13345		uint8_t sks[3];
13346		int retry_count;
13347
13348		memset(&msg, 0, sizeof(msg));
13349
13350		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13351		msg.hdr.status = CTL_SCSI_ERROR;
13352		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13353
13354		retry_count = 4243;
13355
13356		sense = &msg.scsi.sense_data;
13357		sks[0] = SSD_SCS_VALID;
13358		sks[1] = (retry_count >> 8) & 0xff;
13359		sks[2] = retry_count & 0xff;
13360
13361		/* "Internal target failure" */
13362		scsi_set_sense_data(sense,
13363				    /*sense_format*/ SSD_TYPE_NONE,
13364				    /*current_error*/ 1,
13365				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13366				    /*asc*/ 0x44,
13367				    /*ascq*/ 0x00,
13368				    /*type*/ SSD_ELEM_SKS,
13369				    /*size*/ sizeof(sks),
13370				    /*data*/ sks,
13371				    SSD_ELEM_NONE);
13372
13373		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13374		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13375			ctl_failover_io(io, /*have_lock*/ 1);
13376			return;
13377		}
13378
13379		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13380		    CTL_HA_STATUS_SUCCESS) {
13381			/* XXX KDM what to do if this fails? */
13382		}
13383		return;
13384	}
13385
13386}
13387
13388static int
13389ctl_process_done(union ctl_io *io)
13390{
13391	struct ctl_lun *lun;
13392	struct ctl_softc *ctl_softc = control_softc;
13393	void (*fe_done)(union ctl_io *io);
13394	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13395
13396	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13397
13398	fe_done =
13399	    control_softc->ctl_ports[targ_port]->fe_done;
13400
13401#ifdef CTL_TIME_IO
13402	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13403		char str[256];
13404		char path_str[64];
13405		struct sbuf sb;
13406
13407		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13408		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13409
13410		sbuf_cat(&sb, path_str);
13411		switch (io->io_hdr.io_type) {
13412		case CTL_IO_SCSI:
13413			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13414			sbuf_printf(&sb, "\n");
13415			sbuf_cat(&sb, path_str);
13416			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13417				    io->scsiio.tag_num, io->scsiio.tag_type);
13418			break;
13419		case CTL_IO_TASK:
13420			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13421				    "Tag Type: %d\n", io->taskio.task_action,
13422				    io->taskio.tag_num, io->taskio.tag_type);
13423			break;
13424		default:
13425			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13426			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13427			break;
13428		}
13429		sbuf_cat(&sb, path_str);
13430		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13431			    (intmax_t)time_uptime - io->io_hdr.start_time);
13432		sbuf_finish(&sb);
13433		printf("%s", sbuf_data(&sb));
13434	}
13435#endif /* CTL_TIME_IO */
13436
13437	switch (io->io_hdr.io_type) {
13438	case CTL_IO_SCSI:
13439		break;
13440	case CTL_IO_TASK:
13441		if (bootverbose || (ctl_debug & CTL_DEBUG_INFO))
13442			ctl_io_error_print(io, NULL);
13443		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13444			ctl_free_io(io);
13445		else
13446			fe_done(io);
13447		return (CTL_RETVAL_COMPLETE);
13448	default:
13449		panic("ctl_process_done: invalid io type %d\n",
13450		      io->io_hdr.io_type);
13451		break; /* NOTREACHED */
13452	}
13453
13454	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13455	if (lun == NULL) {
13456		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13457				 io->io_hdr.nexus.targ_mapped_lun));
13458		goto bailout;
13459	}
13460
13461	mtx_lock(&lun->lun_lock);
13462
13463	/*
13464	 * Check to see if we have any errors to inject here.  We only
13465	 * inject errors for commands that don't already have errors set.
13466	 */
13467	if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
13468	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13469	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13470		ctl_inject_error(lun, io);
13471
13472	/*
13473	 * XXX KDM how do we treat commands that aren't completed
13474	 * successfully?
13475	 *
13476	 * XXX KDM should we also track I/O latency?
13477	 */
13478	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13479	    io->io_hdr.io_type == CTL_IO_SCSI) {
13480#ifdef CTL_TIME_IO
13481		struct bintime cur_bt;
13482#endif
13483		int type;
13484
13485		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13486		    CTL_FLAG_DATA_IN)
13487			type = CTL_STATS_READ;
13488		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13489		    CTL_FLAG_DATA_OUT)
13490			type = CTL_STATS_WRITE;
13491		else
13492			type = CTL_STATS_NO_IO;
13493
13494		lun->stats.ports[targ_port].bytes[type] +=
13495		    io->scsiio.kern_total_len;
13496		lun->stats.ports[targ_port].operations[type]++;
13497#ifdef CTL_TIME_IO
13498		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13499		   &io->io_hdr.dma_bt);
13500		lun->stats.ports[targ_port].num_dmas[type] +=
13501		    io->io_hdr.num_dmas;
13502		getbintime(&cur_bt);
13503		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13504		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13505#endif
13506	}
13507
13508	/*
13509	 * Remove this from the OOA queue.
13510	 */
13511	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13512
13513	/*
13514	 * Run through the blocked queue on this LUN and see if anything
13515	 * has become unblocked, now that this transaction is done.
13516	 */
13517	ctl_check_blocked(lun);
13518
13519	/*
13520	 * If the LUN has been invalidated, free it if there is nothing
13521	 * left on its OOA queue.
13522	 */
13523	if ((lun->flags & CTL_LUN_INVALID)
13524	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13525		mtx_unlock(&lun->lun_lock);
13526		mtx_lock(&ctl_softc->ctl_lock);
13527		ctl_free_lun(lun);
13528		mtx_unlock(&ctl_softc->ctl_lock);
13529	} else
13530		mtx_unlock(&lun->lun_lock);
13531
13532bailout:
13533
13534	/*
13535	 * If this command has been aborted, make sure we set the status
13536	 * properly.  The FETD is responsible for freeing the I/O and doing
13537	 * whatever it needs to do to clean up its state.
13538	 */
13539	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13540		ctl_set_task_aborted(&io->scsiio);
13541
13542	/*
13543	 * If enabled, print command error status.
13544	 * We don't print UAs unless debugging was enabled explicitly.
13545	 */
13546	do {
13547		if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)
13548			break;
13549		if (!bootverbose && (ctl_debug & CTL_DEBUG_INFO) == 0)
13550			break;
13551		if ((ctl_debug & CTL_DEBUG_INFO) == 0 &&
13552		    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR) &&
13553		     (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13554			int error_code, sense_key, asc, ascq;
13555
13556			scsi_extract_sense_len(&io->scsiio.sense_data,
13557			    io->scsiio.sense_len, &error_code, &sense_key,
13558			    &asc, &ascq, /*show_errors*/ 0);
13559			if (sense_key == SSD_KEY_UNIT_ATTENTION)
13560				break;
13561		}
13562
13563		ctl_io_error_print(io, NULL);
13564	} while (0);
13565
13566	/*
13567	 * Tell the FETD or the other shelf controller we're done with this
13568	 * command.  Note that only SCSI commands get to this point.  Task
13569	 * management commands are completed above.
13570	 *
13571	 * We only send status to the other controller if we're in XFER
13572	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13573	 * received the I/O (from CTL's perspective), and so the status is
13574	 * generated there.
13575	 *
13576	 * XXX KDM if we hold the lock here, we could cause a deadlock
13577	 * if the frontend comes back in in this context to queue
13578	 * something.
13579	 */
13580	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13581	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13582		union ctl_ha_msg msg;
13583
13584		memset(&msg, 0, sizeof(msg));
13585		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13586		msg.hdr.original_sc = io->io_hdr.original_sc;
13587		msg.hdr.nexus = io->io_hdr.nexus;
13588		msg.hdr.status = io->io_hdr.status;
13589		msg.scsi.scsi_status = io->scsiio.scsi_status;
13590		msg.scsi.tag_num = io->scsiio.tag_num;
13591		msg.scsi.tag_type = io->scsiio.tag_type;
13592		msg.scsi.sense_len = io->scsiio.sense_len;
13593		msg.scsi.sense_residual = io->scsiio.sense_residual;
13594		msg.scsi.residual = io->scsiio.residual;
13595		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13596		       sizeof(io->scsiio.sense_data));
13597		/*
13598		 * We copy this whether or not this is an I/O-related
13599		 * command.  Otherwise, we'd have to go and check to see
13600		 * whether it's a read/write command, and it really isn't
13601		 * worth it.
13602		 */
13603		memcpy(&msg.scsi.lbalen,
13604		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13605		       sizeof(msg.scsi.lbalen));
13606
13607		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13608				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13609			/* XXX do something here */
13610		}
13611
13612		ctl_free_io(io);
13613	} else
13614		fe_done(io);
13615
13616	return (CTL_RETVAL_COMPLETE);
13617}
13618
13619#ifdef CTL_WITH_CA
13620/*
13621 * Front end should call this if it doesn't do autosense.  When the request
13622 * sense comes back in from the initiator, we'll dequeue this and send it.
13623 */
13624int
13625ctl_queue_sense(union ctl_io *io)
13626{
13627	struct ctl_lun *lun;
13628	struct ctl_softc *ctl_softc;
13629	uint32_t initidx, targ_lun;
13630
13631	ctl_softc = control_softc;
13632
13633	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13634
13635	/*
13636	 * LUN lookup will likely move to the ctl_work_thread() once we
13637	 * have our new queueing infrastructure (that doesn't put things on
13638	 * a per-LUN queue initially).  That is so that we can handle
13639	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13640	 * can't deal with that right now.
13641	 */
13642	mtx_lock(&ctl_softc->ctl_lock);
13643
13644	/*
13645	 * If we don't have a LUN for this, just toss the sense
13646	 * information.
13647	 */
13648	targ_lun = io->io_hdr.nexus.targ_lun;
13649	targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13650	if ((targ_lun < CTL_MAX_LUNS)
13651	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
13652		lun = ctl_softc->ctl_luns[targ_lun];
13653	else
13654		goto bailout;
13655
13656	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13657
13658	mtx_lock(&lun->lun_lock);
13659	/*
13660	 * Already have CA set for this LUN...toss the sense information.
13661	 */
13662	if (ctl_is_set(lun->have_ca, initidx)) {
13663		mtx_unlock(&lun->lun_lock);
13664		goto bailout;
13665	}
13666
13667	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13668	       ctl_min(sizeof(lun->pending_sense[initidx]),
13669	       sizeof(io->scsiio.sense_data)));
13670	ctl_set_mask(lun->have_ca, initidx);
13671	mtx_unlock(&lun->lun_lock);
13672
13673bailout:
13674	mtx_unlock(&ctl_softc->ctl_lock);
13675
13676	ctl_free_io(io);
13677
13678	return (CTL_RETVAL_COMPLETE);
13679}
13680#endif
13681
13682/*
13683 * Primary command inlet from frontend ports.  All SCSI and task I/O
13684 * requests must go through this function.
13685 */
13686int
13687ctl_queue(union ctl_io *io)
13688{
13689	struct ctl_softc *ctl_softc;
13690
13691	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13692
13693	ctl_softc = control_softc;
13694
13695#ifdef CTL_TIME_IO
13696	io->io_hdr.start_time = time_uptime;
13697	getbintime(&io->io_hdr.start_bt);
13698#endif /* CTL_TIME_IO */
13699
13700	/* Map FE-specific LUN ID into global one. */
13701	io->io_hdr.nexus.targ_mapped_lun =
13702	    ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13703
13704	switch (io->io_hdr.io_type) {
13705	case CTL_IO_SCSI:
13706	case CTL_IO_TASK:
13707		if (ctl_debug & CTL_DEBUG_CDB)
13708			ctl_io_print(io);
13709		ctl_enqueue_incoming(io);
13710		break;
13711	default:
13712		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13713		return (EINVAL);
13714	}
13715
13716	return (CTL_RETVAL_COMPLETE);
13717}
13718
13719#ifdef CTL_IO_DELAY
13720static void
13721ctl_done_timer_wakeup(void *arg)
13722{
13723	union ctl_io *io;
13724
13725	io = (union ctl_io *)arg;
13726	ctl_done(io);
13727}
13728#endif /* CTL_IO_DELAY */
13729
13730void
13731ctl_done(union ctl_io *io)
13732{
13733	struct ctl_softc *ctl_softc;
13734
13735	ctl_softc = control_softc;
13736
13737	/*
13738	 * Enable this to catch duplicate completion issues.
13739	 */
13740#if 0
13741	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13742		printf("%s: type %d msg %d cdb %x iptl: "
13743		       "%d:%d:%d:%d tag 0x%04x "
13744		       "flag %#x status %x\n",
13745			__func__,
13746			io->io_hdr.io_type,
13747			io->io_hdr.msg_type,
13748			io->scsiio.cdb[0],
13749			io->io_hdr.nexus.initid.id,
13750			io->io_hdr.nexus.targ_port,
13751			io->io_hdr.nexus.targ_target.id,
13752			io->io_hdr.nexus.targ_lun,
13753			(io->io_hdr.io_type ==
13754			CTL_IO_TASK) ?
13755			io->taskio.tag_num :
13756			io->scsiio.tag_num,
13757		        io->io_hdr.flags,
13758			io->io_hdr.status);
13759	} else
13760		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13761#endif
13762
13763	/*
13764	 * This is an internal copy of an I/O, and should not go through
13765	 * the normal done processing logic.
13766	 */
13767	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13768		return;
13769
13770	/*
13771	 * We need to send a msg to the serializing shelf to finish the IO
13772	 * as well.  We don't send a finish message to the other shelf if
13773	 * this is a task management command.  Task management commands
13774	 * aren't serialized in the OOA queue, but rather just executed on
13775	 * both shelf controllers for commands that originated on that
13776	 * controller.
13777	 */
13778	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13779	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
13780		union ctl_ha_msg msg_io;
13781
13782		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13783		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13784		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13785		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13786		}
13787		/* continue on to finish IO */
13788	}
13789#ifdef CTL_IO_DELAY
13790	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13791		struct ctl_lun *lun;
13792
13793		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13794
13795		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13796	} else {
13797		struct ctl_lun *lun;
13798
13799		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13800
13801		if ((lun != NULL)
13802		 && (lun->delay_info.done_delay > 0)) {
13803			struct callout *callout;
13804
13805			callout = (struct callout *)&io->io_hdr.timer_bytes;
13806			callout_init(callout, /*mpsafe*/ 1);
13807			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13808			callout_reset(callout,
13809				      lun->delay_info.done_delay * hz,
13810				      ctl_done_timer_wakeup, io);
13811			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13812				lun->delay_info.done_delay = 0;
13813			return;
13814		}
13815	}
13816#endif /* CTL_IO_DELAY */
13817
13818	ctl_enqueue_done(io);
13819}
13820
13821int
13822ctl_isc(struct ctl_scsiio *ctsio)
13823{
13824	struct ctl_lun *lun;
13825	int retval;
13826
13827	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13828
13829	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13830
13831	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13832
13833	retval = lun->backend->data_submit((union ctl_io *)ctsio);
13834
13835	return (retval);
13836}
13837
13838
13839static void
13840ctl_work_thread(void *arg)
13841{
13842	struct ctl_thread *thr = (struct ctl_thread *)arg;
13843	struct ctl_softc *softc = thr->ctl_softc;
13844	union ctl_io *io;
13845	int retval;
13846
13847	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13848
13849	for (;;) {
13850		retval = 0;
13851
13852		/*
13853		 * We handle the queues in this order:
13854		 * - ISC
13855		 * - done queue (to free up resources, unblock other commands)
13856		 * - RtR queue
13857		 * - incoming queue
13858		 *
13859		 * If those queues are empty, we break out of the loop and
13860		 * go to sleep.
13861		 */
13862		mtx_lock(&thr->queue_lock);
13863		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13864		if (io != NULL) {
13865			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13866			mtx_unlock(&thr->queue_lock);
13867			ctl_handle_isc(io);
13868			continue;
13869		}
13870		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13871		if (io != NULL) {
13872			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13873			/* clear any blocked commands, call fe_done */
13874			mtx_unlock(&thr->queue_lock);
13875			retval = ctl_process_done(io);
13876			continue;
13877		}
13878		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13879		if (io != NULL) {
13880			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13881			mtx_unlock(&thr->queue_lock);
13882			if (io->io_hdr.io_type == CTL_IO_TASK)
13883				ctl_run_task(io);
13884			else
13885				ctl_scsiio_precheck(softc, &io->scsiio);
13886			continue;
13887		}
13888		if (!ctl_pause_rtr) {
13889			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13890			if (io != NULL) {
13891				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13892				mtx_unlock(&thr->queue_lock);
13893				retval = ctl_scsiio(&io->scsiio);
13894				if (retval != CTL_RETVAL_COMPLETE)
13895					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13896				continue;
13897			}
13898		}
13899
13900		/* Sleep until we have something to do. */
13901		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13902	}
13903}
13904
13905static void
13906ctl_lun_thread(void *arg)
13907{
13908	struct ctl_softc *softc = (struct ctl_softc *)arg;
13909	struct ctl_be_lun *be_lun;
13910	int retval;
13911
13912	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13913
13914	for (;;) {
13915		retval = 0;
13916		mtx_lock(&softc->ctl_lock);
13917		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13918		if (be_lun != NULL) {
13919			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13920			mtx_unlock(&softc->ctl_lock);
13921			ctl_create_lun(be_lun);
13922			continue;
13923		}
13924
13925		/* Sleep until we have something to do. */
13926		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13927		    PDROP | PRIBIO, "-", 0);
13928	}
13929}
13930
13931static void
13932ctl_thresh_thread(void *arg)
13933{
13934	struct ctl_softc *softc = (struct ctl_softc *)arg;
13935	struct ctl_lun *lun;
13936	struct ctl_be_lun *be_lun;
13937	struct scsi_da_rw_recovery_page *rwpage;
13938	struct ctl_logical_block_provisioning_page *page;
13939	const char *attr;
13940	uint64_t thres, val;
13941	int i, e;
13942
13943	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13944
13945	for (;;) {
13946		mtx_lock(&softc->ctl_lock);
13947		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13948			be_lun = lun->be_lun;
13949			if ((lun->flags & CTL_LUN_DISABLED) ||
13950			    (lun->flags & CTL_LUN_OFFLINE) ||
13951			    (be_lun->flags & CTL_LUN_FLAG_UNMAP) == 0 ||
13952			    lun->backend->lun_attr == NULL)
13953				continue;
13954			rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13955			if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13956				continue;
13957			e = 0;
13958			page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13959			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13960				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13961					continue;
13962				thres = scsi_4btoul(page->descr[i].count);
13963				thres <<= CTL_LBP_EXPONENT;
13964				switch (page->descr[i].resource) {
13965				case 0x01:
13966					attr = "blocksavail";
13967					break;
13968				case 0x02:
13969					attr = "blocksused";
13970					break;
13971				case 0xf1:
13972					attr = "poolblocksavail";
13973					break;
13974				case 0xf2:
13975					attr = "poolblocksused";
13976					break;
13977				default:
13978					continue;
13979				}
13980				mtx_unlock(&softc->ctl_lock); // XXX
13981				val = lun->backend->lun_attr(
13982				    lun->be_lun->be_lun, attr);
13983				mtx_lock(&softc->ctl_lock);
13984				if (val == UINT64_MAX)
13985					continue;
13986				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13987				    == SLBPPD_ARMING_INC)
13988					e |= (val >= thres);
13989				else
13990					e |= (val <= thres);
13991			}
13992			mtx_lock(&lun->lun_lock);
13993			if (e) {
13994				if (lun->lasttpt == 0 ||
13995				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13996					lun->lasttpt = time_uptime;
13997					for (i = 0; i < CTL_MAX_INITIATORS; i++)
13998						lun->pending_ua[i] |=
13999						    CTL_UA_THIN_PROV_THRES;
14000				}
14001			} else {
14002				lun->lasttpt = 0;
14003				for (i = 0; i < CTL_MAX_INITIATORS; i++)
14004					lun->pending_ua[i] &= ~CTL_UA_THIN_PROV_THRES;
14005			}
14006			mtx_unlock(&lun->lun_lock);
14007		}
14008		mtx_unlock(&softc->ctl_lock);
14009		pause("-", CTL_LBP_PERIOD * hz);
14010	}
14011}
14012
14013static void
14014ctl_enqueue_incoming(union ctl_io *io)
14015{
14016	struct ctl_softc *softc = control_softc;
14017	struct ctl_thread *thr;
14018	u_int idx;
14019
14020	idx = (io->io_hdr.nexus.targ_port * 127 +
14021	       io->io_hdr.nexus.initid.id) % worker_threads;
14022	thr = &softc->threads[idx];
14023	mtx_lock(&thr->queue_lock);
14024	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14025	mtx_unlock(&thr->queue_lock);
14026	wakeup(thr);
14027}
14028
14029static void
14030ctl_enqueue_rtr(union ctl_io *io)
14031{
14032	struct ctl_softc *softc = control_softc;
14033	struct ctl_thread *thr;
14034
14035	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14036	mtx_lock(&thr->queue_lock);
14037	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14038	mtx_unlock(&thr->queue_lock);
14039	wakeup(thr);
14040}
14041
14042static void
14043ctl_enqueue_done(union ctl_io *io)
14044{
14045	struct ctl_softc *softc = control_softc;
14046	struct ctl_thread *thr;
14047
14048	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14049	mtx_lock(&thr->queue_lock);
14050	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14051	mtx_unlock(&thr->queue_lock);
14052	wakeup(thr);
14053}
14054
14055static void
14056ctl_enqueue_isc(union ctl_io *io)
14057{
14058	struct ctl_softc *softc = control_softc;
14059	struct ctl_thread *thr;
14060
14061	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14062	mtx_lock(&thr->queue_lock);
14063	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14064	mtx_unlock(&thr->queue_lock);
14065	wakeup(thr);
14066}
14067
14068/* Initialization and failover */
14069
14070void
14071ctl_init_isc_msg(void)
14072{
14073	printf("CTL: Still calling this thing\n");
14074}
14075
14076/*
14077 * Init component
14078 * 	Initializes component into configuration defined by bootMode
14079 *	(see hasc-sv.c)
14080 *  	returns hasc_Status:
14081 * 		OK
14082 *		ERROR - fatal error
14083 */
14084static ctl_ha_comp_status
14085ctl_isc_init(struct ctl_ha_component *c)
14086{
14087	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14088
14089	c->status = ret;
14090	return ret;
14091}
14092
14093/* Start component
14094 * 	Starts component in state requested. If component starts successfully,
14095 *	it must set its own state to the requestrd state
14096 *	When requested state is HASC_STATE_HA, the component may refine it
14097 * 	by adding _SLAVE or _MASTER flags.
14098 *	Currently allowed state transitions are:
14099 *	UNKNOWN->HA		- initial startup
14100 *	UNKNOWN->SINGLE - initial startup when no parter detected
14101 *	HA->SINGLE		- failover
14102 * returns ctl_ha_comp_status:
14103 * 		OK	- component successfully started in requested state
14104 *		FAILED  - could not start the requested state, failover may
14105 * 			  be possible
14106 *		ERROR	- fatal error detected, no future startup possible
14107 */
14108static ctl_ha_comp_status
14109ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14110{
14111	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14112
14113	printf("%s: go\n", __func__);
14114
14115	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14116	if (c->state == CTL_HA_STATE_UNKNOWN ) {
14117		control_softc->is_single = 0;
14118		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14119		    != CTL_HA_STATUS_SUCCESS) {
14120			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14121			ret = CTL_HA_COMP_STATUS_ERROR;
14122		}
14123	} else if (CTL_HA_STATE_IS_HA(c->state)
14124		&& CTL_HA_STATE_IS_SINGLE(state)){
14125		// HA->SINGLE transition
14126	        ctl_failover();
14127		control_softc->is_single = 1;
14128	} else {
14129		printf("ctl_isc_start:Invalid state transition %X->%X\n",
14130		       c->state, state);
14131		ret = CTL_HA_COMP_STATUS_ERROR;
14132	}
14133	if (CTL_HA_STATE_IS_SINGLE(state))
14134		control_softc->is_single = 1;
14135
14136	c->state = state;
14137	c->status = ret;
14138	return ret;
14139}
14140
14141/*
14142 * Quiesce component
14143 * The component must clear any error conditions (set status to OK) and
14144 * prepare itself to another Start call
14145 * returns ctl_ha_comp_status:
14146 * 	OK
14147 *	ERROR
14148 */
14149static ctl_ha_comp_status
14150ctl_isc_quiesce(struct ctl_ha_component *c)
14151{
14152	int ret = CTL_HA_COMP_STATUS_OK;
14153
14154	ctl_pause_rtr = 1;
14155	c->status = ret;
14156	return ret;
14157}
14158
14159struct ctl_ha_component ctl_ha_component_ctlisc =
14160{
14161	.name = "CTL ISC",
14162	.state = CTL_HA_STATE_UNKNOWN,
14163	.init = ctl_isc_init,
14164	.start = ctl_isc_start,
14165	.quiesce = ctl_isc_quiesce
14166};
14167
14168/*
14169 *  vim: ts=8
14170 */
14171