ctl.c revision 278598
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$
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 278598 2015-02-11 22:03:23Z 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 */
114const static 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
124const static 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
133const static 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
147const static 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
161const static 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
178const static 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
194const static 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
211const static 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
227const static 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
243const static 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
259const static 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
271const static 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
283const static 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
292const static 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
303const static 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
329const static 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 int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
402			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
403static int ctl_free_lun(struct ctl_lun *lun);
404static void ctl_create_lun(struct ctl_be_lun *be_lun);
405static struct ctl_port * ctl_io_port(struct ctl_io_hdr *io_hdr);
406/**
407static void ctl_failover_change_pages(struct ctl_softc *softc,
408				      struct ctl_scsiio *ctsio, int master);
409**/
410
411static int ctl_do_mode_select(union ctl_io *io);
412static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
413			   uint64_t res_key, uint64_t sa_res_key,
414			   uint8_t type, uint32_t residx,
415			   struct ctl_scsiio *ctsio,
416			   struct scsi_per_res_out *cdb,
417			   struct scsi_per_res_out_parms* param);
418static void ctl_pro_preempt_other(struct ctl_lun *lun,
419				  union ctl_ha_msg *msg);
420static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
421static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
422static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
423static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
424static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
425static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
426static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
427					 int alloc_len);
428static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
429					 int alloc_len);
430static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
431static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
432static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
433static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
434static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
435static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
436    bool seq);
437static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
438static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
439    union ctl_io *pending_io, union ctl_io *ooa_io);
440static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
441				union ctl_io *starting_io);
442static int ctl_check_blocked(struct ctl_lun *lun);
443static int ctl_scsiio_lun_check(struct ctl_lun *lun,
444				const struct ctl_cmd_entry *entry,
445				struct ctl_scsiio *ctsio);
446//static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
447static void ctl_failover(void);
448static void ctl_clear_ua(struct ctl_softc *ctl_softc, uint32_t initidx,
449			 ctl_ua_type ua_type);
450static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
451			       struct ctl_scsiio *ctsio);
452static int ctl_scsiio(struct ctl_scsiio *ctsio);
453
454static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
455static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
456			    ctl_ua_type ua_type);
457static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
458			 ctl_ua_type ua_type);
459static int ctl_abort_task(union ctl_io *io);
460static int ctl_abort_task_set(union ctl_io *io);
461static int ctl_i_t_nexus_reset(union ctl_io *io);
462static void ctl_run_task(union ctl_io *io);
463#ifdef CTL_IO_DELAY
464static void ctl_datamove_timer_wakeup(void *arg);
465static void ctl_done_timer_wakeup(void *arg);
466#endif /* CTL_IO_DELAY */
467
468static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
469static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
470static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
471static void ctl_datamove_remote_write(union ctl_io *io);
472static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
473static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
474static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
475static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
476				    ctl_ha_dt_cb callback);
477static void ctl_datamove_remote_read(union ctl_io *io);
478static void ctl_datamove_remote(union ctl_io *io);
479static int ctl_process_done(union ctl_io *io);
480static void ctl_lun_thread(void *arg);
481static void ctl_thresh_thread(void *arg);
482static void ctl_work_thread(void *arg);
483static void ctl_enqueue_incoming(union ctl_io *io);
484static void ctl_enqueue_rtr(union ctl_io *io);
485static void ctl_enqueue_done(union ctl_io *io);
486static void ctl_enqueue_isc(union ctl_io *io);
487static const struct ctl_cmd_entry *
488    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
489static const struct ctl_cmd_entry *
490    ctl_validate_command(struct ctl_scsiio *ctsio);
491static int ctl_cmd_applicable(uint8_t lun_type,
492    const struct ctl_cmd_entry *entry);
493
494/*
495 * Load the serialization table.  This isn't very pretty, but is probably
496 * the easiest way to do it.
497 */
498#include "ctl_ser_table.c"
499
500/*
501 * We only need to define open, close and ioctl routines for this driver.
502 */
503static struct cdevsw ctl_cdevsw = {
504	.d_version =	D_VERSION,
505	.d_flags =	0,
506	.d_open =	ctl_open,
507	.d_close =	ctl_close,
508	.d_ioctl =	ctl_ioctl,
509	.d_name =	"ctl",
510};
511
512
513MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
514MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
515
516static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
517
518static moduledata_t ctl_moduledata = {
519	"ctl",
520	ctl_module_event_handler,
521	NULL
522};
523
524DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
525MODULE_VERSION(ctl, 1);
526
527static struct ctl_frontend ioctl_frontend =
528{
529	.name = "ioctl",
530};
531
532static void
533ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
534			    union ctl_ha_msg *msg_info)
535{
536	struct ctl_scsiio *ctsio;
537
538	if (msg_info->hdr.original_sc == NULL) {
539		printf("%s: original_sc == NULL!\n", __func__);
540		/* XXX KDM now what? */
541		return;
542	}
543
544	ctsio = &msg_info->hdr.original_sc->scsiio;
545	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
546	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
547	ctsio->io_hdr.status = msg_info->hdr.status;
548	ctsio->scsi_status = msg_info->scsi.scsi_status;
549	ctsio->sense_len = msg_info->scsi.sense_len;
550	ctsio->sense_residual = msg_info->scsi.sense_residual;
551	ctsio->residual = msg_info->scsi.residual;
552	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
553	       sizeof(ctsio->sense_data));
554	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
555	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
556	ctl_enqueue_isc((union ctl_io *)ctsio);
557}
558
559static void
560ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
561				union ctl_ha_msg *msg_info)
562{
563	struct ctl_scsiio *ctsio;
564
565	if (msg_info->hdr.serializing_sc == NULL) {
566		printf("%s: serializing_sc == NULL!\n", __func__);
567		/* XXX KDM now what? */
568		return;
569	}
570
571	ctsio = &msg_info->hdr.serializing_sc->scsiio;
572#if 0
573	/*
574	 * Attempt to catch the situation where an I/O has
575	 * been freed, and we're using it again.
576	 */
577	if (ctsio->io_hdr.io_type == 0xff) {
578		union ctl_io *tmp_io;
579		tmp_io = (union ctl_io *)ctsio;
580		printf("%s: %p use after free!\n", __func__,
581		       ctsio);
582		printf("%s: type %d msg %d cdb %x iptl: "
583		       "%d:%d:%d:%d tag 0x%04x "
584		       "flag %#x status %x\n",
585			__func__,
586			tmp_io->io_hdr.io_type,
587			tmp_io->io_hdr.msg_type,
588			tmp_io->scsiio.cdb[0],
589			tmp_io->io_hdr.nexus.initid.id,
590			tmp_io->io_hdr.nexus.targ_port,
591			tmp_io->io_hdr.nexus.targ_target.id,
592			tmp_io->io_hdr.nexus.targ_lun,
593			(tmp_io->io_hdr.io_type ==
594			CTL_IO_TASK) ?
595			tmp_io->taskio.tag_num :
596			tmp_io->scsiio.tag_num,
597		        tmp_io->io_hdr.flags,
598			tmp_io->io_hdr.status);
599	}
600#endif
601	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
602	ctl_enqueue_isc((union ctl_io *)ctsio);
603}
604
605/*
606 * ISC (Inter Shelf Communication) event handler.  Events from the HA
607 * subsystem come in here.
608 */
609static void
610ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
611{
612	struct ctl_softc *softc;
613	union ctl_io *io;
614	struct ctl_prio *presio;
615	ctl_ha_status isc_status;
616
617	softc = control_softc;
618	io = NULL;
619
620
621#if 0
622	printf("CTL: Isc Msg event %d\n", event);
623#endif
624	if (event == CTL_HA_EVT_MSG_RECV) {
625		union ctl_ha_msg msg_info;
626
627		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
628					     sizeof(msg_info), /*wait*/ 0);
629#if 0
630		printf("CTL: msg_type %d\n", msg_info.msg_type);
631#endif
632		if (isc_status != 0) {
633			printf("Error receiving message, status = %d\n",
634			       isc_status);
635			return;
636		}
637
638		switch (msg_info.hdr.msg_type) {
639		case CTL_MSG_SERIALIZE:
640#if 0
641			printf("Serialize\n");
642#endif
643			io = ctl_alloc_io_nowait(softc->othersc_pool);
644			if (io == NULL) {
645				printf("ctl_isc_event_handler: can't allocate "
646				       "ctl_io!\n");
647				/* Bad Juju */
648				/* Need to set busy and send msg back */
649				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
650				msg_info.hdr.status = CTL_SCSI_ERROR;
651				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
652				msg_info.scsi.sense_len = 0;
653			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
654				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
655				}
656				goto bailout;
657			}
658			ctl_zero_io(io);
659			// populate ctsio from msg_info
660			io->io_hdr.io_type = CTL_IO_SCSI;
661			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
662			io->io_hdr.original_sc = msg_info.hdr.original_sc;
663#if 0
664			printf("pOrig %x\n", (int)msg_info.original_sc);
665#endif
666			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
667					    CTL_FLAG_IO_ACTIVE;
668			/*
669			 * If we're in serialization-only mode, we don't
670			 * want to go through full done processing.  Thus
671			 * the COPY flag.
672			 *
673			 * XXX KDM add another flag that is more specific.
674			 */
675			if (softc->ha_mode == CTL_HA_MODE_SER_ONLY)
676				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
677			io->io_hdr.nexus = msg_info.hdr.nexus;
678#if 0
679			printf("targ %d, port %d, iid %d, lun %d\n",
680			       io->io_hdr.nexus.targ_target.id,
681			       io->io_hdr.nexus.targ_port,
682			       io->io_hdr.nexus.initid.id,
683			       io->io_hdr.nexus.targ_lun);
684#endif
685			io->scsiio.tag_num = msg_info.scsi.tag_num;
686			io->scsiio.tag_type = msg_info.scsi.tag_type;
687			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
688			       CTL_MAX_CDBLEN);
689			if (softc->ha_mode == CTL_HA_MODE_XFER) {
690				const struct ctl_cmd_entry *entry;
691
692				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
693				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
694				io->io_hdr.flags |=
695					entry->flags & CTL_FLAG_DATA_MASK;
696			}
697			ctl_enqueue_isc(io);
698			break;
699
700		/* Performed on the Originating SC, XFER mode only */
701		case CTL_MSG_DATAMOVE: {
702			struct ctl_sg_entry *sgl;
703			int i, j;
704
705			io = msg_info.hdr.original_sc;
706			if (io == NULL) {
707				printf("%s: original_sc == NULL!\n", __func__);
708				/* XXX KDM do something here */
709				break;
710			}
711			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
712			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
713			/*
714			 * Keep track of this, we need to send it back over
715			 * when the datamove is complete.
716			 */
717			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
718
719			if (msg_info.dt.sg_sequence == 0) {
720				/*
721				 * XXX KDM we use the preallocated S/G list
722				 * here, but we'll need to change this to
723				 * dynamic allocation if we need larger S/G
724				 * lists.
725				 */
726				if (msg_info.dt.kern_sg_entries >
727				    sizeof(io->io_hdr.remote_sglist) /
728				    sizeof(io->io_hdr.remote_sglist[0])) {
729					printf("%s: number of S/G entries "
730					    "needed %u > allocated num %zd\n",
731					    __func__,
732					    msg_info.dt.kern_sg_entries,
733					    sizeof(io->io_hdr.remote_sglist)/
734					    sizeof(io->io_hdr.remote_sglist[0]));
735
736					/*
737					 * XXX KDM send a message back to
738					 * the other side to shut down the
739					 * DMA.  The error will come back
740					 * through via the normal channel.
741					 */
742					break;
743				}
744				sgl = io->io_hdr.remote_sglist;
745				memset(sgl, 0,
746				       sizeof(io->io_hdr.remote_sglist));
747
748				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
749
750				io->scsiio.kern_sg_entries =
751					msg_info.dt.kern_sg_entries;
752				io->scsiio.rem_sg_entries =
753					msg_info.dt.kern_sg_entries;
754				io->scsiio.kern_data_len =
755					msg_info.dt.kern_data_len;
756				io->scsiio.kern_total_len =
757					msg_info.dt.kern_total_len;
758				io->scsiio.kern_data_resid =
759					msg_info.dt.kern_data_resid;
760				io->scsiio.kern_rel_offset =
761					msg_info.dt.kern_rel_offset;
762				/*
763				 * Clear out per-DMA flags.
764				 */
765				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
766				/*
767				 * Add per-DMA flags that are set for this
768				 * particular DMA request.
769				 */
770				io->io_hdr.flags |= msg_info.dt.flags &
771						    CTL_FLAG_RDMA_MASK;
772			} else
773				sgl = (struct ctl_sg_entry *)
774					io->scsiio.kern_data_ptr;
775
776			for (i = msg_info.dt.sent_sg_entries, j = 0;
777			     i < (msg_info.dt.sent_sg_entries +
778			     msg_info.dt.cur_sg_entries); i++, j++) {
779				sgl[i].addr = msg_info.dt.sg_list[j].addr;
780				sgl[i].len = msg_info.dt.sg_list[j].len;
781
782#if 0
783				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
784				       __func__,
785				       msg_info.dt.sg_list[j].addr,
786				       msg_info.dt.sg_list[j].len,
787				       sgl[i].addr, sgl[i].len, j, i);
788#endif
789			}
790#if 0
791			memcpy(&sgl[msg_info.dt.sent_sg_entries],
792			       msg_info.dt.sg_list,
793			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
794#endif
795
796			/*
797			 * If this is the last piece of the I/O, we've got
798			 * the full S/G list.  Queue processing in the thread.
799			 * Otherwise wait for the next piece.
800			 */
801			if (msg_info.dt.sg_last != 0)
802				ctl_enqueue_isc(io);
803			break;
804		}
805		/* Performed on the Serializing (primary) SC, XFER mode only */
806		case CTL_MSG_DATAMOVE_DONE: {
807			if (msg_info.hdr.serializing_sc == NULL) {
808				printf("%s: serializing_sc == NULL!\n",
809				       __func__);
810				/* XXX KDM now what? */
811				break;
812			}
813			/*
814			 * We grab the sense information here in case
815			 * there was a failure, so we can return status
816			 * back to the initiator.
817			 */
818			io = msg_info.hdr.serializing_sc;
819			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
820			io->io_hdr.status = msg_info.hdr.status;
821			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
822			io->scsiio.sense_len = msg_info.scsi.sense_len;
823			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
824			io->io_hdr.port_status = msg_info.scsi.fetd_status;
825			io->scsiio.residual = msg_info.scsi.residual;
826			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
827			       sizeof(io->scsiio.sense_data));
828			ctl_enqueue_isc(io);
829			break;
830		}
831
832		/* Preformed on Originating SC, SER_ONLY mode */
833		case CTL_MSG_R2R:
834			io = msg_info.hdr.original_sc;
835			if (io == NULL) {
836				printf("%s: Major Bummer\n", __func__);
837				return;
838			} else {
839#if 0
840				printf("pOrig %x\n",(int) ctsio);
841#endif
842			}
843			io->io_hdr.msg_type = CTL_MSG_R2R;
844			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
845			ctl_enqueue_isc(io);
846			break;
847
848		/*
849		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
850		 * mode.
851		 * Performed on the Originating (i.e. secondary) SC in XFER
852		 * mode
853		 */
854		case CTL_MSG_FINISH_IO:
855			if (softc->ha_mode == CTL_HA_MODE_XFER)
856				ctl_isc_handler_finish_xfer(softc,
857							    &msg_info);
858			else
859				ctl_isc_handler_finish_ser_only(softc,
860								&msg_info);
861			break;
862
863		/* Preformed on Originating SC */
864		case CTL_MSG_BAD_JUJU:
865			io = msg_info.hdr.original_sc;
866			if (io == NULL) {
867				printf("%s: Bad JUJU!, original_sc is NULL!\n",
868				       __func__);
869				break;
870			}
871			ctl_copy_sense_data(&msg_info, io);
872			/*
873			 * IO should have already been cleaned up on other
874			 * SC so clear this flag so we won't send a message
875			 * back to finish the IO there.
876			 */
877			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
878			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
879
880			/* io = msg_info.hdr.serializing_sc; */
881			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
882			ctl_enqueue_isc(io);
883			break;
884
885		/* Handle resets sent from the other side */
886		case CTL_MSG_MANAGE_TASKS: {
887			struct ctl_taskio *taskio;
888			taskio = (struct ctl_taskio *)ctl_alloc_io_nowait(
889			    softc->othersc_pool);
890			if (taskio == NULL) {
891				printf("ctl_isc_event_handler: can't allocate "
892				       "ctl_io!\n");
893				/* Bad Juju */
894				/* should I just call the proper reset func
895				   here??? */
896				goto bailout;
897			}
898			ctl_zero_io((union ctl_io *)taskio);
899			taskio->io_hdr.io_type = CTL_IO_TASK;
900			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
901			taskio->io_hdr.nexus = msg_info.hdr.nexus;
902			taskio->task_action = msg_info.task.task_action;
903			taskio->tag_num = msg_info.task.tag_num;
904			taskio->tag_type = msg_info.task.tag_type;
905#ifdef CTL_TIME_IO
906			taskio->io_hdr.start_time = time_uptime;
907			getbintime(&taskio->io_hdr.start_bt);
908#if 0
909			cs_prof_gettime(&taskio->io_hdr.start_ticks);
910#endif
911#endif /* CTL_TIME_IO */
912			ctl_run_task((union ctl_io *)taskio);
913			break;
914		}
915		/* Persistent Reserve action which needs attention */
916		case CTL_MSG_PERS_ACTION:
917			presio = (struct ctl_prio *)ctl_alloc_io_nowait(
918			    softc->othersc_pool);
919			if (presio == NULL) {
920				printf("ctl_isc_event_handler: can't allocate "
921				       "ctl_io!\n");
922				/* Bad Juju */
923				/* Need to set busy and send msg back */
924				goto bailout;
925			}
926			ctl_zero_io((union ctl_io *)presio);
927			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
928			presio->pr_msg = msg_info.pr;
929			ctl_enqueue_isc((union ctl_io *)presio);
930			break;
931		case CTL_MSG_SYNC_FE:
932			rcv_sync_msg = 1;
933			break;
934		default:
935		        printf("How did I get here?\n");
936		}
937	} else if (event == CTL_HA_EVT_MSG_SENT) {
938		if (param != CTL_HA_STATUS_SUCCESS) {
939			printf("Bad status from ctl_ha_msg_send status %d\n",
940			       param);
941		}
942		return;
943	} else if (event == CTL_HA_EVT_DISCONNECT) {
944		printf("CTL: Got a disconnect from Isc\n");
945		return;
946	} else {
947		printf("ctl_isc_event_handler: Unknown event %d\n", event);
948		return;
949	}
950
951bailout:
952	return;
953}
954
955static void
956ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
957{
958	struct scsi_sense_data *sense;
959
960	sense = &dest->scsiio.sense_data;
961	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
962	dest->scsiio.scsi_status = src->scsi.scsi_status;
963	dest->scsiio.sense_len = src->scsi.sense_len;
964	dest->io_hdr.status = src->hdr.status;
965}
966
967static void
968ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
969{
970	ctl_ua_type *pu;
971
972	mtx_assert(&lun->lun_lock, MA_OWNED);
973	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
974	if (pu == NULL)
975		return;
976	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
977}
978
979static void
980ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
981{
982	int i, j;
983
984	mtx_assert(&lun->lun_lock, MA_OWNED);
985	for (i = 0; i < CTL_MAX_PORTS; i++) {
986		if (lun->pending_ua[i] == NULL)
987			continue;
988		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
989			if (i * CTL_MAX_INIT_PER_PORT + j == except)
990				continue;
991			lun->pending_ua[i][j] |= ua;
992		}
993	}
994}
995
996static void
997ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
998{
999	ctl_ua_type *pu;
1000
1001	mtx_assert(&lun->lun_lock, MA_OWNED);
1002	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1003	if (pu == NULL)
1004		return;
1005	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1006}
1007
1008static void
1009ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1010{
1011	int i, j;
1012
1013	mtx_assert(&lun->lun_lock, MA_OWNED);
1014	for (i = 0; i < CTL_MAX_PORTS; i++) {
1015		if (lun->pending_ua[i] == NULL)
1016			continue;
1017		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1018			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1019				continue;
1020			lun->pending_ua[i][j] &= ~ua;
1021		}
1022	}
1023}
1024
1025static int
1026ctl_ha_state_sysctl(SYSCTL_HANDLER_ARGS)
1027{
1028	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1029	struct ctl_lun *lun;
1030	int error, value;
1031
1032	if (softc->flags & CTL_FLAG_ACTIVE_SHELF)
1033		value = 0;
1034	else
1035		value = 1;
1036
1037	error = sysctl_handle_int(oidp, &value, 0, req);
1038	if ((error != 0) || (req->newptr == NULL))
1039		return (error);
1040
1041	mtx_lock(&softc->ctl_lock);
1042	if (value == 0)
1043		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1044	else
1045		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1046	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1047		mtx_lock(&lun->lun_lock);
1048		ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1049		mtx_unlock(&lun->lun_lock);
1050	}
1051	mtx_unlock(&softc->ctl_lock);
1052	return (0);
1053}
1054
1055static int
1056ctl_init(void)
1057{
1058	struct ctl_softc *softc;
1059	void *other_pool;
1060	struct ctl_port *port;
1061	int i, error, retval;
1062	//int isc_retval;
1063
1064	retval = 0;
1065	ctl_pause_rtr = 0;
1066        rcv_sync_msg = 0;
1067
1068	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1069			       M_WAITOK | M_ZERO);
1070	softc = control_softc;
1071
1072	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1073			      "cam/ctl");
1074
1075	softc->dev->si_drv1 = softc;
1076
1077	/*
1078	 * By default, return a "bad LUN" peripheral qualifier for unknown
1079	 * LUNs.  The user can override this default using the tunable or
1080	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
1081	 */
1082	softc->inquiry_pq_no_lun = 1;
1083	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
1084			  &softc->inquiry_pq_no_lun);
1085	sysctl_ctx_init(&softc->sysctl_ctx);
1086	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1087		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1088		CTLFLAG_RD, 0, "CAM Target Layer");
1089
1090	if (softc->sysctl_tree == NULL) {
1091		printf("%s: unable to allocate sysctl tree\n", __func__);
1092		destroy_dev(softc->dev);
1093		free(control_softc, M_DEVBUF);
1094		control_softc = NULL;
1095		return (ENOMEM);
1096	}
1097
1098	SYSCTL_ADD_INT(&softc->sysctl_ctx,
1099		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1100		       "inquiry_pq_no_lun", CTLFLAG_RW,
1101		       &softc->inquiry_pq_no_lun, 0,
1102		       "Report no lun possible for invalid LUNs");
1103
1104	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1105	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1106	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1107	softc->open_count = 0;
1108
1109	/*
1110	 * Default to actually sending a SYNCHRONIZE CACHE command down to
1111	 * the drive.
1112	 */
1113	softc->flags = CTL_FLAG_REAL_SYNC;
1114
1115	/*
1116	 * In Copan's HA scheme, the "master" and "slave" roles are
1117	 * figured out through the slot the controller is in.  Although it
1118	 * is an active/active system, someone has to be in charge.
1119	 */
1120	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1121	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1122	    "HA head ID (0 - no HA)");
1123	if (softc->ha_id == 0) {
1124		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1125		softc->is_single = 1;
1126		softc->port_offset = 0;
1127	} else
1128		softc->port_offset = (softc->ha_id - 1) * CTL_MAX_PORTS;
1129	softc->persis_offset = softc->port_offset * CTL_MAX_INIT_PER_PORT;
1130
1131	/*
1132	 * XXX KDM need to figure out where we want to get our target ID
1133	 * and WWID.  Is it different on each port?
1134	 */
1135	softc->target.id = 0;
1136	softc->target.wwid[0] = 0x12345678;
1137	softc->target.wwid[1] = 0x87654321;
1138	STAILQ_INIT(&softc->lun_list);
1139	STAILQ_INIT(&softc->pending_lun_queue);
1140	STAILQ_INIT(&softc->fe_list);
1141	STAILQ_INIT(&softc->port_list);
1142	STAILQ_INIT(&softc->be_list);
1143	ctl_tpc_init(softc);
1144
1145	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1146	                    &other_pool) != 0)
1147	{
1148		printf("ctl: can't allocate %d entry other SC pool, "
1149		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1150		return (ENOMEM);
1151	}
1152	softc->othersc_pool = other_pool;
1153
1154	if (worker_threads <= 0)
1155		worker_threads = max(1, mp_ncpus / 4);
1156	if (worker_threads > CTL_MAX_THREADS)
1157		worker_threads = CTL_MAX_THREADS;
1158
1159	for (i = 0; i < worker_threads; i++) {
1160		struct ctl_thread *thr = &softc->threads[i];
1161
1162		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1163		thr->ctl_softc = softc;
1164		STAILQ_INIT(&thr->incoming_queue);
1165		STAILQ_INIT(&thr->rtr_queue);
1166		STAILQ_INIT(&thr->done_queue);
1167		STAILQ_INIT(&thr->isc_queue);
1168
1169		error = kproc_kthread_add(ctl_work_thread, thr,
1170		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1171		if (error != 0) {
1172			printf("error creating CTL work thread!\n");
1173			ctl_pool_free(other_pool);
1174			return (error);
1175		}
1176	}
1177	error = kproc_kthread_add(ctl_lun_thread, softc,
1178	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1179	if (error != 0) {
1180		printf("error creating CTL lun thread!\n");
1181		ctl_pool_free(other_pool);
1182		return (error);
1183	}
1184	error = kproc_kthread_add(ctl_thresh_thread, softc,
1185	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1186	if (error != 0) {
1187		printf("error creating CTL threshold thread!\n");
1188		ctl_pool_free(other_pool);
1189		return (error);
1190	}
1191	if (bootverbose)
1192		printf("ctl: CAM Target Layer loaded\n");
1193
1194	/*
1195	 * Initialize the ioctl front end.
1196	 */
1197	ctl_frontend_register(&ioctl_frontend);
1198	port = &softc->ioctl_info.port;
1199	port->frontend = &ioctl_frontend;
1200	sprintf(softc->ioctl_info.port_name, "ioctl");
1201	port->port_type = CTL_PORT_IOCTL;
1202	port->num_requested_ctl_io = 100;
1203	port->port_name = softc->ioctl_info.port_name;
1204	port->port_online = ctl_ioctl_online;
1205	port->port_offline = ctl_ioctl_offline;
1206	port->onoff_arg = &softc->ioctl_info;
1207	port->lun_enable = ctl_ioctl_lun_enable;
1208	port->lun_disable = ctl_ioctl_lun_disable;
1209	port->targ_lun_arg = &softc->ioctl_info;
1210	port->fe_datamove = ctl_ioctl_datamove;
1211	port->fe_done = ctl_ioctl_done;
1212	port->max_targets = 15;
1213	port->max_target_id = 15;
1214
1215	if (ctl_port_register(&softc->ioctl_info.port) != 0) {
1216		printf("ctl: ioctl front end registration failed, will "
1217		       "continue anyway\n");
1218	}
1219
1220	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1221	    OID_AUTO, "ha_state", CTLTYPE_INT | CTLFLAG_RWTUN,
1222	    softc, 0, ctl_ha_state_sysctl, "I", "HA state for this head");
1223
1224#ifdef CTL_IO_DELAY
1225	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1226		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1227		       sizeof(struct callout), CTL_TIMER_BYTES);
1228		return (EINVAL);
1229	}
1230#endif /* CTL_IO_DELAY */
1231
1232	return (0);
1233}
1234
1235void
1236ctl_shutdown(void)
1237{
1238	struct ctl_softc *softc;
1239	struct ctl_lun *lun, *next_lun;
1240
1241	softc = (struct ctl_softc *)control_softc;
1242
1243	if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1244		printf("ctl: ioctl front end deregistration failed\n");
1245
1246	mtx_lock(&softc->ctl_lock);
1247
1248	/*
1249	 * Free up each LUN.
1250	 */
1251	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1252		next_lun = STAILQ_NEXT(lun, links);
1253		ctl_free_lun(lun);
1254	}
1255
1256	mtx_unlock(&softc->ctl_lock);
1257
1258	ctl_frontend_deregister(&ioctl_frontend);
1259
1260#if 0
1261	ctl_shutdown_thread(softc->work_thread);
1262	mtx_destroy(&softc->queue_lock);
1263#endif
1264
1265	ctl_tpc_shutdown(softc);
1266	uma_zdestroy(softc->io_zone);
1267	mtx_destroy(&softc->ctl_lock);
1268
1269	destroy_dev(softc->dev);
1270
1271	sysctl_ctx_free(&softc->sysctl_ctx);
1272
1273	free(control_softc, M_DEVBUF);
1274	control_softc = NULL;
1275
1276	if (bootverbose)
1277		printf("ctl: CAM Target Layer unloaded\n");
1278}
1279
1280static int
1281ctl_module_event_handler(module_t mod, int what, void *arg)
1282{
1283
1284	switch (what) {
1285	case MOD_LOAD:
1286		return (ctl_init());
1287	case MOD_UNLOAD:
1288		return (EBUSY);
1289	default:
1290		return (EOPNOTSUPP);
1291	}
1292}
1293
1294/*
1295 * XXX KDM should we do some access checks here?  Bump a reference count to
1296 * prevent a CTL module from being unloaded while someone has it open?
1297 */
1298static int
1299ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1300{
1301	return (0);
1302}
1303
1304static int
1305ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1306{
1307	return (0);
1308}
1309
1310int
1311ctl_port_enable(ctl_port_type port_type)
1312{
1313	struct ctl_softc *softc = control_softc;
1314	struct ctl_port *port;
1315
1316	if (softc->is_single == 0) {
1317		union ctl_ha_msg msg_info;
1318		int isc_retval;
1319
1320#if 0
1321		printf("%s: HA mode, synchronizing frontend enable\n",
1322		        __func__);
1323#endif
1324		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1325	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1326		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1327			printf("Sync msg send error retval %d\n", isc_retval);
1328		}
1329		if (!rcv_sync_msg) {
1330			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1331			        sizeof(msg_info), 1);
1332		}
1333#if 0
1334        	printf("CTL:Frontend Enable\n");
1335	} else {
1336		printf("%s: single mode, skipping frontend synchronization\n",
1337		        __func__);
1338#endif
1339	}
1340
1341	STAILQ_FOREACH(port, &softc->port_list, links) {
1342		if (port_type & port->port_type)
1343		{
1344#if 0
1345			printf("port %d\n", port->targ_port);
1346#endif
1347			ctl_port_online(port);
1348		}
1349	}
1350
1351	return (0);
1352}
1353
1354int
1355ctl_port_disable(ctl_port_type port_type)
1356{
1357	struct ctl_softc *softc;
1358	struct ctl_port *port;
1359
1360	softc = control_softc;
1361
1362	STAILQ_FOREACH(port, &softc->port_list, links) {
1363		if (port_type & port->port_type)
1364			ctl_port_offline(port);
1365	}
1366
1367	return (0);
1368}
1369
1370/*
1371 * Returns 0 for success, 1 for failure.
1372 * Currently the only failure mode is if there aren't enough entries
1373 * allocated.  So, in case of a failure, look at num_entries_dropped,
1374 * reallocate and try again.
1375 */
1376int
1377ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1378	      int *num_entries_filled, int *num_entries_dropped,
1379	      ctl_port_type port_type, int no_virtual)
1380{
1381	struct ctl_softc *softc;
1382	struct ctl_port *port;
1383	int entries_dropped, entries_filled;
1384	int retval;
1385	int i;
1386
1387	softc = control_softc;
1388
1389	retval = 0;
1390	entries_filled = 0;
1391	entries_dropped = 0;
1392
1393	i = 0;
1394	mtx_lock(&softc->ctl_lock);
1395	STAILQ_FOREACH(port, &softc->port_list, links) {
1396		struct ctl_port_entry *entry;
1397
1398		if ((port->port_type & port_type) == 0)
1399			continue;
1400
1401		if ((no_virtual != 0)
1402		 && (port->virtual_port != 0))
1403			continue;
1404
1405		if (entries_filled >= num_entries_alloced) {
1406			entries_dropped++;
1407			continue;
1408		}
1409		entry = &entries[i];
1410
1411		entry->port_type = port->port_type;
1412		strlcpy(entry->port_name, port->port_name,
1413			sizeof(entry->port_name));
1414		entry->physical_port = port->physical_port;
1415		entry->virtual_port = port->virtual_port;
1416		entry->wwnn = port->wwnn;
1417		entry->wwpn = port->wwpn;
1418
1419		i++;
1420		entries_filled++;
1421	}
1422
1423	mtx_unlock(&softc->ctl_lock);
1424
1425	if (entries_dropped > 0)
1426		retval = 1;
1427
1428	*num_entries_dropped = entries_dropped;
1429	*num_entries_filled = entries_filled;
1430
1431	return (retval);
1432}
1433
1434static void
1435ctl_ioctl_online(void *arg)
1436{
1437	struct ctl_ioctl_info *ioctl_info;
1438
1439	ioctl_info = (struct ctl_ioctl_info *)arg;
1440
1441	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1442}
1443
1444static void
1445ctl_ioctl_offline(void *arg)
1446{
1447	struct ctl_ioctl_info *ioctl_info;
1448
1449	ioctl_info = (struct ctl_ioctl_info *)arg;
1450
1451	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1452}
1453
1454/*
1455 * Remove an initiator by port number and initiator ID.
1456 * Returns 0 for success, -1 for failure.
1457 */
1458int
1459ctl_remove_initiator(struct ctl_port *port, int iid)
1460{
1461	struct ctl_softc *softc = control_softc;
1462
1463	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1464
1465	if (iid > CTL_MAX_INIT_PER_PORT) {
1466		printf("%s: initiator ID %u > maximun %u!\n",
1467		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1468		return (-1);
1469	}
1470
1471	mtx_lock(&softc->ctl_lock);
1472	port->wwpn_iid[iid].in_use--;
1473	port->wwpn_iid[iid].last_use = time_uptime;
1474	mtx_unlock(&softc->ctl_lock);
1475
1476	return (0);
1477}
1478
1479/*
1480 * Add an initiator to the initiator map.
1481 * Returns iid for success, < 0 for failure.
1482 */
1483int
1484ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1485{
1486	struct ctl_softc *softc = control_softc;
1487	time_t best_time;
1488	int i, best;
1489
1490	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1491
1492	if (iid >= CTL_MAX_INIT_PER_PORT) {
1493		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1494		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1495		free(name, M_CTL);
1496		return (-1);
1497	}
1498
1499	mtx_lock(&softc->ctl_lock);
1500
1501	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1502		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1503			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1504				iid = i;
1505				break;
1506			}
1507			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1508			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1509				iid = i;
1510				break;
1511			}
1512		}
1513	}
1514
1515	if (iid < 0) {
1516		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1517			if (port->wwpn_iid[i].in_use == 0 &&
1518			    port->wwpn_iid[i].wwpn == 0 &&
1519			    port->wwpn_iid[i].name == NULL) {
1520				iid = i;
1521				break;
1522			}
1523		}
1524	}
1525
1526	if (iid < 0) {
1527		best = -1;
1528		best_time = INT32_MAX;
1529		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1530			if (port->wwpn_iid[i].in_use == 0) {
1531				if (port->wwpn_iid[i].last_use < best_time) {
1532					best = i;
1533					best_time = port->wwpn_iid[i].last_use;
1534				}
1535			}
1536		}
1537		iid = best;
1538	}
1539
1540	if (iid < 0) {
1541		mtx_unlock(&softc->ctl_lock);
1542		free(name, M_CTL);
1543		return (-2);
1544	}
1545
1546	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1547		/*
1548		 * This is not an error yet.
1549		 */
1550		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1551#if 0
1552			printf("%s: port %d iid %u WWPN %#jx arrived"
1553			    " again\n", __func__, port->targ_port,
1554			    iid, (uintmax_t)wwpn);
1555#endif
1556			goto take;
1557		}
1558		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1559		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1560#if 0
1561			printf("%s: port %d iid %u name '%s' arrived"
1562			    " again\n", __func__, port->targ_port,
1563			    iid, name);
1564#endif
1565			goto take;
1566		}
1567
1568		/*
1569		 * This is an error, but what do we do about it?  The
1570		 * driver is telling us we have a new WWPN for this
1571		 * initiator ID, so we pretty much need to use it.
1572		 */
1573		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1574		    " but WWPN %#jx '%s' is still at that address\n",
1575		    __func__, port->targ_port, iid, wwpn, name,
1576		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1577		    port->wwpn_iid[iid].name);
1578
1579		/*
1580		 * XXX KDM clear have_ca and ua_pending on each LUN for
1581		 * this initiator.
1582		 */
1583	}
1584take:
1585	free(port->wwpn_iid[iid].name, M_CTL);
1586	port->wwpn_iid[iid].name = name;
1587	port->wwpn_iid[iid].wwpn = wwpn;
1588	port->wwpn_iid[iid].in_use++;
1589	mtx_unlock(&softc->ctl_lock);
1590
1591	return (iid);
1592}
1593
1594static int
1595ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1596{
1597	int len;
1598
1599	switch (port->port_type) {
1600	case CTL_PORT_FC:
1601	{
1602		struct scsi_transportid_fcp *id =
1603		    (struct scsi_transportid_fcp *)buf;
1604		if (port->wwpn_iid[iid].wwpn == 0)
1605			return (0);
1606		memset(id, 0, sizeof(*id));
1607		id->format_protocol = SCSI_PROTO_FC;
1608		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1609		return (sizeof(*id));
1610	}
1611	case CTL_PORT_ISCSI:
1612	{
1613		struct scsi_transportid_iscsi_port *id =
1614		    (struct scsi_transportid_iscsi_port *)buf;
1615		if (port->wwpn_iid[iid].name == NULL)
1616			return (0);
1617		memset(id, 0, 256);
1618		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1619		    SCSI_PROTO_ISCSI;
1620		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1621		len = roundup2(min(len, 252), 4);
1622		scsi_ulto2b(len, id->additional_length);
1623		return (sizeof(*id) + len);
1624	}
1625	case CTL_PORT_SAS:
1626	{
1627		struct scsi_transportid_sas *id =
1628		    (struct scsi_transportid_sas *)buf;
1629		if (port->wwpn_iid[iid].wwpn == 0)
1630			return (0);
1631		memset(id, 0, sizeof(*id));
1632		id->format_protocol = SCSI_PROTO_SAS;
1633		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1634		return (sizeof(*id));
1635	}
1636	default:
1637	{
1638		struct scsi_transportid_spi *id =
1639		    (struct scsi_transportid_spi *)buf;
1640		memset(id, 0, sizeof(*id));
1641		id->format_protocol = SCSI_PROTO_SPI;
1642		scsi_ulto2b(iid, id->scsi_addr);
1643		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1644		return (sizeof(*id));
1645	}
1646	}
1647}
1648
1649static int
1650ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1651{
1652	return (0);
1653}
1654
1655static int
1656ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1657{
1658	return (0);
1659}
1660
1661/*
1662 * Data movement routine for the CTL ioctl frontend port.
1663 */
1664static int
1665ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1666{
1667	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1668	struct ctl_sg_entry ext_entry, kern_entry;
1669	int ext_sglen, ext_sg_entries, kern_sg_entries;
1670	int ext_sg_start, ext_offset;
1671	int len_to_copy, len_copied;
1672	int kern_watermark, ext_watermark;
1673	int ext_sglist_malloced;
1674	int i, j;
1675
1676	ext_sglist_malloced = 0;
1677	ext_sg_start = 0;
1678	ext_offset = 0;
1679
1680	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1681
1682	/*
1683	 * If this flag is set, fake the data transfer.
1684	 */
1685	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1686		ctsio->ext_data_filled = ctsio->ext_data_len;
1687		goto bailout;
1688	}
1689
1690	/*
1691	 * To simplify things here, if we have a single buffer, stick it in
1692	 * a S/G entry and just make it a single entry S/G list.
1693	 */
1694	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1695		int len_seen;
1696
1697		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1698
1699		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1700							   M_WAITOK);
1701		ext_sglist_malloced = 1;
1702		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1703				   ext_sglen) != 0) {
1704			ctl_set_internal_failure(ctsio,
1705						 /*sks_valid*/ 0,
1706						 /*retry_count*/ 0);
1707			goto bailout;
1708		}
1709		ext_sg_entries = ctsio->ext_sg_entries;
1710		len_seen = 0;
1711		for (i = 0; i < ext_sg_entries; i++) {
1712			if ((len_seen + ext_sglist[i].len) >=
1713			     ctsio->ext_data_filled) {
1714				ext_sg_start = i;
1715				ext_offset = ctsio->ext_data_filled - len_seen;
1716				break;
1717			}
1718			len_seen += ext_sglist[i].len;
1719		}
1720	} else {
1721		ext_sglist = &ext_entry;
1722		ext_sglist->addr = ctsio->ext_data_ptr;
1723		ext_sglist->len = ctsio->ext_data_len;
1724		ext_sg_entries = 1;
1725		ext_sg_start = 0;
1726		ext_offset = ctsio->ext_data_filled;
1727	}
1728
1729	if (ctsio->kern_sg_entries > 0) {
1730		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1731		kern_sg_entries = ctsio->kern_sg_entries;
1732	} else {
1733		kern_sglist = &kern_entry;
1734		kern_sglist->addr = ctsio->kern_data_ptr;
1735		kern_sglist->len = ctsio->kern_data_len;
1736		kern_sg_entries = 1;
1737	}
1738
1739
1740	kern_watermark = 0;
1741	ext_watermark = ext_offset;
1742	len_copied = 0;
1743	for (i = ext_sg_start, j = 0;
1744	     i < ext_sg_entries && j < kern_sg_entries;) {
1745		uint8_t *ext_ptr, *kern_ptr;
1746
1747		len_to_copy = MIN(ext_sglist[i].len - ext_watermark,
1748				  kern_sglist[j].len - kern_watermark);
1749
1750		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1751		ext_ptr = ext_ptr + ext_watermark;
1752		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1753			/*
1754			 * XXX KDM fix this!
1755			 */
1756			panic("need to implement bus address support");
1757#if 0
1758			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1759#endif
1760		} else
1761			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1762		kern_ptr = kern_ptr + kern_watermark;
1763
1764		kern_watermark += len_to_copy;
1765		ext_watermark += len_to_copy;
1766
1767		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1768		     CTL_FLAG_DATA_IN) {
1769			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1770					 "bytes to user\n", len_to_copy));
1771			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1772					 "to %p\n", kern_ptr, ext_ptr));
1773			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1774				ctl_set_internal_failure(ctsio,
1775							 /*sks_valid*/ 0,
1776							 /*retry_count*/ 0);
1777				goto bailout;
1778			}
1779		} else {
1780			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1781					 "bytes from user\n", len_to_copy));
1782			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1783					 "to %p\n", ext_ptr, kern_ptr));
1784			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1785				ctl_set_internal_failure(ctsio,
1786							 /*sks_valid*/ 0,
1787							 /*retry_count*/0);
1788				goto bailout;
1789			}
1790		}
1791
1792		len_copied += len_to_copy;
1793
1794		if (ext_sglist[i].len == ext_watermark) {
1795			i++;
1796			ext_watermark = 0;
1797		}
1798
1799		if (kern_sglist[j].len == kern_watermark) {
1800			j++;
1801			kern_watermark = 0;
1802		}
1803	}
1804
1805	ctsio->ext_data_filled += len_copied;
1806
1807	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1808			 "kern_sg_entries: %d\n", ext_sg_entries,
1809			 kern_sg_entries));
1810	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1811			 "kern_data_len = %d\n", ctsio->ext_data_len,
1812			 ctsio->kern_data_len));
1813
1814
1815	/* XXX KDM set residual?? */
1816bailout:
1817
1818	if (ext_sglist_malloced != 0)
1819		free(ext_sglist, M_CTL);
1820
1821	return (CTL_RETVAL_COMPLETE);
1822}
1823
1824/*
1825 * Serialize a command that went down the "wrong" side, and so was sent to
1826 * this controller for execution.  The logic is a little different than the
1827 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1828 * sent back to the other side, but in the success case, we execute the
1829 * command on this side (XFER mode) or tell the other side to execute it
1830 * (SER_ONLY mode).
1831 */
1832static int
1833ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1834{
1835	struct ctl_softc *softc;
1836	union ctl_ha_msg msg_info;
1837	struct ctl_lun *lun;
1838	int retval = 0;
1839	uint32_t targ_lun;
1840
1841	softc = control_softc;
1842
1843	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1844	lun = softc->ctl_luns[targ_lun];
1845	if (lun==NULL)
1846	{
1847		/*
1848		 * Why isn't LUN defined? The other side wouldn't
1849		 * send a cmd if the LUN is undefined.
1850		 */
1851		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1852
1853		/* "Logical unit not supported" */
1854		ctl_set_sense_data(&msg_info.scsi.sense_data,
1855				   lun,
1856				   /*sense_format*/SSD_TYPE_NONE,
1857				   /*current_error*/ 1,
1858				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1859				   /*asc*/ 0x25,
1860				   /*ascq*/ 0x00,
1861				   SSD_ELEM_NONE);
1862
1863		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1864		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1865		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1866		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1867		msg_info.hdr.serializing_sc = NULL;
1868		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1869	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1870				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1871		}
1872		return(1);
1873
1874	}
1875
1876	mtx_lock(&lun->lun_lock);
1877    	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1878
1879	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1880		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1881		 ooa_links))) {
1882	case CTL_ACTION_BLOCK:
1883		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1884		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1885				  blocked_links);
1886		break;
1887	case CTL_ACTION_PASS:
1888	case CTL_ACTION_SKIP:
1889		if (softc->ha_mode == CTL_HA_MODE_XFER) {
1890			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1891			ctl_enqueue_rtr((union ctl_io *)ctsio);
1892		} else {
1893
1894			/* send msg back to other side */
1895			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1896			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1897			msg_info.hdr.msg_type = CTL_MSG_R2R;
1898#if 0
1899			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1900#endif
1901		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1902			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1903			}
1904		}
1905		break;
1906	case CTL_ACTION_OVERLAP:
1907		/* OVERLAPPED COMMANDS ATTEMPTED */
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_ILLEGAL_REQUEST,
1913				   /*asc*/ 0x4E,
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 Overlap\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	case CTL_ACTION_OVERLAP_TAG:
1933		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1934		ctl_set_sense_data(&msg_info.scsi.sense_data,
1935				   lun,
1936				   /*sense_format*/SSD_TYPE_NONE,
1937				   /*current_error*/ 1,
1938				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1939				   /*asc*/ 0x4D,
1940				   /*ascq*/ ctsio->tag_num & 0xff,
1941				   SSD_ELEM_NONE);
1942
1943		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1944		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1945		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1946		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1947		msg_info.hdr.serializing_sc = NULL;
1948		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1949#if 0
1950		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1951#endif
1952		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1953		retval = 1;
1954		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1955		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1956		}
1957		break;
1958	case CTL_ACTION_ERROR:
1959	default:
1960		/* "Internal target failure" */
1961		ctl_set_sense_data(&msg_info.scsi.sense_data,
1962				   lun,
1963				   /*sense_format*/SSD_TYPE_NONE,
1964				   /*current_error*/ 1,
1965				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1966				   /*asc*/ 0x44,
1967				   /*ascq*/ 0x00,
1968				   SSD_ELEM_NONE);
1969
1970		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1971		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1972		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1973		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1974		msg_info.hdr.serializing_sc = NULL;
1975		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1976#if 0
1977		printf("BAD JUJU:Major Bummer HW Error\n");
1978#endif
1979		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1980		retval = 1;
1981		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1982		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1983		}
1984		break;
1985	}
1986	mtx_unlock(&lun->lun_lock);
1987	return (retval);
1988}
1989
1990static int
1991ctl_ioctl_submit_wait(union ctl_io *io)
1992{
1993	struct ctl_fe_ioctl_params params;
1994	ctl_fe_ioctl_state last_state;
1995	int done, retval;
1996
1997	retval = 0;
1998
1999	bzero(&params, sizeof(params));
2000
2001	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
2002	cv_init(&params.sem, "ctlioccv");
2003	params.state = CTL_IOCTL_INPROG;
2004	last_state = params.state;
2005
2006	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
2007
2008	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
2009
2010	/* This shouldn't happen */
2011	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
2012		return (retval);
2013
2014	done = 0;
2015
2016	do {
2017		mtx_lock(&params.ioctl_mtx);
2018		/*
2019		 * Check the state here, and don't sleep if the state has
2020		 * already changed (i.e. wakeup has already occured, but we
2021		 * weren't waiting yet).
2022		 */
2023		if (params.state == last_state) {
2024			/* XXX KDM cv_wait_sig instead? */
2025			cv_wait(&params.sem, &params.ioctl_mtx);
2026		}
2027		last_state = params.state;
2028
2029		switch (params.state) {
2030		case CTL_IOCTL_INPROG:
2031			/* Why did we wake up? */
2032			/* XXX KDM error here? */
2033			mtx_unlock(&params.ioctl_mtx);
2034			break;
2035		case CTL_IOCTL_DATAMOVE:
2036			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
2037
2038			/*
2039			 * change last_state back to INPROG to avoid
2040			 * deadlock on subsequent data moves.
2041			 */
2042			params.state = last_state = CTL_IOCTL_INPROG;
2043
2044			mtx_unlock(&params.ioctl_mtx);
2045			ctl_ioctl_do_datamove(&io->scsiio);
2046			/*
2047			 * Note that in some cases, most notably writes,
2048			 * this will queue the I/O and call us back later.
2049			 * In other cases, generally reads, this routine
2050			 * will immediately call back and wake us up,
2051			 * probably using our own context.
2052			 */
2053			io->scsiio.be_move_done(io);
2054			break;
2055		case CTL_IOCTL_DONE:
2056			mtx_unlock(&params.ioctl_mtx);
2057			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
2058			done = 1;
2059			break;
2060		default:
2061			mtx_unlock(&params.ioctl_mtx);
2062			/* XXX KDM error here? */
2063			break;
2064		}
2065	} while (done == 0);
2066
2067	mtx_destroy(&params.ioctl_mtx);
2068	cv_destroy(&params.sem);
2069
2070	return (CTL_RETVAL_COMPLETE);
2071}
2072
2073static void
2074ctl_ioctl_datamove(union ctl_io *io)
2075{
2076	struct ctl_fe_ioctl_params *params;
2077
2078	params = (struct ctl_fe_ioctl_params *)
2079		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2080
2081	mtx_lock(&params->ioctl_mtx);
2082	params->state = CTL_IOCTL_DATAMOVE;
2083	cv_broadcast(&params->sem);
2084	mtx_unlock(&params->ioctl_mtx);
2085}
2086
2087static void
2088ctl_ioctl_done(union ctl_io *io)
2089{
2090	struct ctl_fe_ioctl_params *params;
2091
2092	params = (struct ctl_fe_ioctl_params *)
2093		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2094
2095	mtx_lock(&params->ioctl_mtx);
2096	params->state = CTL_IOCTL_DONE;
2097	cv_broadcast(&params->sem);
2098	mtx_unlock(&params->ioctl_mtx);
2099}
2100
2101static void
2102ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2103{
2104	struct ctl_fe_ioctl_startstop_info *sd_info;
2105
2106	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2107
2108	sd_info->hs_info.status = metatask->status;
2109	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2110	sd_info->hs_info.luns_complete =
2111		metatask->taskinfo.startstop.luns_complete;
2112	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2113
2114	cv_broadcast(&sd_info->sem);
2115}
2116
2117static void
2118ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2119{
2120	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2121
2122	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2123
2124	mtx_lock(fe_bbr_info->lock);
2125	fe_bbr_info->bbr_info->status = metatask->status;
2126	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2127	fe_bbr_info->wakeup_done = 1;
2128	mtx_unlock(fe_bbr_info->lock);
2129
2130	cv_broadcast(&fe_bbr_info->sem);
2131}
2132
2133/*
2134 * Returns 0 for success, errno for failure.
2135 */
2136static int
2137ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2138		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2139{
2140	union ctl_io *io;
2141	int retval;
2142
2143	retval = 0;
2144
2145	mtx_lock(&lun->lun_lock);
2146	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2147	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2148	     ooa_links)) {
2149		struct ctl_ooa_entry *entry;
2150
2151		/*
2152		 * If we've got more than we can fit, just count the
2153		 * remaining entries.
2154		 */
2155		if (*cur_fill_num >= ooa_hdr->alloc_num)
2156			continue;
2157
2158		entry = &kern_entries[*cur_fill_num];
2159
2160		entry->tag_num = io->scsiio.tag_num;
2161		entry->lun_num = lun->lun;
2162#ifdef CTL_TIME_IO
2163		entry->start_bt = io->io_hdr.start_bt;
2164#endif
2165		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2166		entry->cdb_len = io->scsiio.cdb_len;
2167		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2168			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2169
2170		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2171			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2172
2173		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2174			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2175
2176		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2177			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2178
2179		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2180			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2181	}
2182	mtx_unlock(&lun->lun_lock);
2183
2184	return (retval);
2185}
2186
2187static void *
2188ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2189		 size_t error_str_len)
2190{
2191	void *kptr;
2192
2193	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2194
2195	if (copyin(user_addr, kptr, len) != 0) {
2196		snprintf(error_str, error_str_len, "Error copying %d bytes "
2197			 "from user address %p to kernel address %p", len,
2198			 user_addr, kptr);
2199		free(kptr, M_CTL);
2200		return (NULL);
2201	}
2202
2203	return (kptr);
2204}
2205
2206static void
2207ctl_free_args(int num_args, struct ctl_be_arg *args)
2208{
2209	int i;
2210
2211	if (args == NULL)
2212		return;
2213
2214	for (i = 0; i < num_args; i++) {
2215		free(args[i].kname, M_CTL);
2216		free(args[i].kvalue, M_CTL);
2217	}
2218
2219	free(args, M_CTL);
2220}
2221
2222static struct ctl_be_arg *
2223ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2224		char *error_str, size_t error_str_len)
2225{
2226	struct ctl_be_arg *args;
2227	int i;
2228
2229	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2230				error_str, error_str_len);
2231
2232	if (args == NULL)
2233		goto bailout;
2234
2235	for (i = 0; i < num_args; i++) {
2236		args[i].kname = NULL;
2237		args[i].kvalue = NULL;
2238	}
2239
2240	for (i = 0; i < num_args; i++) {
2241		uint8_t *tmpptr;
2242
2243		args[i].kname = ctl_copyin_alloc(args[i].name,
2244			args[i].namelen, error_str, error_str_len);
2245		if (args[i].kname == NULL)
2246			goto bailout;
2247
2248		if (args[i].kname[args[i].namelen - 1] != '\0') {
2249			snprintf(error_str, error_str_len, "Argument %d "
2250				 "name is not NUL-terminated", i);
2251			goto bailout;
2252		}
2253
2254		if (args[i].flags & CTL_BEARG_RD) {
2255			tmpptr = ctl_copyin_alloc(args[i].value,
2256				args[i].vallen, error_str, error_str_len);
2257			if (tmpptr == NULL)
2258				goto bailout;
2259			if ((args[i].flags & CTL_BEARG_ASCII)
2260			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2261				snprintf(error_str, error_str_len, "Argument "
2262				    "%d value is not NUL-terminated", i);
2263				goto bailout;
2264			}
2265			args[i].kvalue = tmpptr;
2266		} else {
2267			args[i].kvalue = malloc(args[i].vallen,
2268			    M_CTL, M_WAITOK | M_ZERO);
2269		}
2270	}
2271
2272	return (args);
2273bailout:
2274
2275	ctl_free_args(num_args, args);
2276
2277	return (NULL);
2278}
2279
2280static void
2281ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2282{
2283	int i;
2284
2285	for (i = 0; i < num_args; i++) {
2286		if (args[i].flags & CTL_BEARG_WR)
2287			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2288	}
2289}
2290
2291/*
2292 * Escape characters that are illegal or not recommended in XML.
2293 */
2294int
2295ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2296{
2297	char *end = str + size;
2298	int retval;
2299
2300	retval = 0;
2301
2302	for (; *str && str < end; str++) {
2303		switch (*str) {
2304		case '&':
2305			retval = sbuf_printf(sb, "&amp;");
2306			break;
2307		case '>':
2308			retval = sbuf_printf(sb, "&gt;");
2309			break;
2310		case '<':
2311			retval = sbuf_printf(sb, "&lt;");
2312			break;
2313		default:
2314			retval = sbuf_putc(sb, *str);
2315			break;
2316		}
2317
2318		if (retval != 0)
2319			break;
2320
2321	}
2322
2323	return (retval);
2324}
2325
2326static void
2327ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2328{
2329	struct scsi_vpd_id_descriptor *desc;
2330	int i;
2331
2332	if (id == NULL || id->len < 4)
2333		return;
2334	desc = (struct scsi_vpd_id_descriptor *)id->data;
2335	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2336	case SVPD_ID_TYPE_T10:
2337		sbuf_printf(sb, "t10.");
2338		break;
2339	case SVPD_ID_TYPE_EUI64:
2340		sbuf_printf(sb, "eui.");
2341		break;
2342	case SVPD_ID_TYPE_NAA:
2343		sbuf_printf(sb, "naa.");
2344		break;
2345	case SVPD_ID_TYPE_SCSI_NAME:
2346		break;
2347	}
2348	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2349	case SVPD_ID_CODESET_BINARY:
2350		for (i = 0; i < desc->length; i++)
2351			sbuf_printf(sb, "%02x", desc->identifier[i]);
2352		break;
2353	case SVPD_ID_CODESET_ASCII:
2354		sbuf_printf(sb, "%.*s", (int)desc->length,
2355		    (char *)desc->identifier);
2356		break;
2357	case SVPD_ID_CODESET_UTF8:
2358		sbuf_printf(sb, "%s", (char *)desc->identifier);
2359		break;
2360	}
2361}
2362
2363static int
2364ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2365	  struct thread *td)
2366{
2367	struct ctl_softc *softc;
2368	int retval;
2369
2370	softc = control_softc;
2371
2372	retval = 0;
2373
2374	switch (cmd) {
2375	case CTL_IO: {
2376		union ctl_io *io;
2377		void *pool_tmp;
2378
2379		/*
2380		 * If we haven't been "enabled", don't allow any SCSI I/O
2381		 * to this FETD.
2382		 */
2383		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2384			retval = EPERM;
2385			break;
2386		}
2387
2388		io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2389
2390		/*
2391		 * Need to save the pool reference so it doesn't get
2392		 * spammed by the user's ctl_io.
2393		 */
2394		pool_tmp = io->io_hdr.pool;
2395		memcpy(io, (void *)addr, sizeof(*io));
2396		io->io_hdr.pool = pool_tmp;
2397
2398		/*
2399		 * No status yet, so make sure the status is set properly.
2400		 */
2401		io->io_hdr.status = CTL_STATUS_NONE;
2402
2403		/*
2404		 * The user sets the initiator ID, target and LUN IDs.
2405		 */
2406		io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2407		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2408		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2409		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2410			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2411
2412		retval = ctl_ioctl_submit_wait(io);
2413
2414		if (retval != 0) {
2415			ctl_free_io(io);
2416			break;
2417		}
2418
2419		memcpy((void *)addr, io, sizeof(*io));
2420
2421		/* return this to our pool */
2422		ctl_free_io(io);
2423
2424		break;
2425	}
2426	case CTL_ENABLE_PORT:
2427	case CTL_DISABLE_PORT:
2428	case CTL_SET_PORT_WWNS: {
2429		struct ctl_port *port;
2430		struct ctl_port_entry *entry;
2431
2432		entry = (struct ctl_port_entry *)addr;
2433
2434		mtx_lock(&softc->ctl_lock);
2435		STAILQ_FOREACH(port, &softc->port_list, links) {
2436			int action, done;
2437
2438			action = 0;
2439			done = 0;
2440
2441			if ((entry->port_type == CTL_PORT_NONE)
2442			 && (entry->targ_port == port->targ_port)) {
2443				/*
2444				 * If the user only wants to enable or
2445				 * disable or set WWNs on a specific port,
2446				 * do the operation and we're done.
2447				 */
2448				action = 1;
2449				done = 1;
2450			} else if (entry->port_type & port->port_type) {
2451				/*
2452				 * Compare the user's type mask with the
2453				 * particular frontend type to see if we
2454				 * have a match.
2455				 */
2456				action = 1;
2457				done = 0;
2458
2459				/*
2460				 * Make sure the user isn't trying to set
2461				 * WWNs on multiple ports at the same time.
2462				 */
2463				if (cmd == CTL_SET_PORT_WWNS) {
2464					printf("%s: Can't set WWNs on "
2465					       "multiple ports\n", __func__);
2466					retval = EINVAL;
2467					break;
2468				}
2469			}
2470			if (action != 0) {
2471				/*
2472				 * XXX KDM we have to drop the lock here,
2473				 * because the online/offline operations
2474				 * can potentially block.  We need to
2475				 * reference count the frontends so they
2476				 * can't go away,
2477				 */
2478				mtx_unlock(&softc->ctl_lock);
2479
2480				if (cmd == CTL_ENABLE_PORT) {
2481					struct ctl_lun *lun;
2482
2483					STAILQ_FOREACH(lun, &softc->lun_list,
2484						       links) {
2485						port->lun_enable(port->targ_lun_arg,
2486						    lun->target,
2487						    lun->lun);
2488					}
2489
2490					ctl_port_online(port);
2491				} else if (cmd == CTL_DISABLE_PORT) {
2492					struct ctl_lun *lun;
2493
2494					ctl_port_offline(port);
2495
2496					STAILQ_FOREACH(lun, &softc->lun_list,
2497						       links) {
2498						port->lun_disable(
2499						    port->targ_lun_arg,
2500						    lun->target,
2501						    lun->lun);
2502					}
2503				}
2504
2505				mtx_lock(&softc->ctl_lock);
2506
2507				if (cmd == CTL_SET_PORT_WWNS)
2508					ctl_port_set_wwns(port,
2509					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2510					    1 : 0, entry->wwnn,
2511					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2512					    1 : 0, entry->wwpn);
2513			}
2514			if (done != 0)
2515				break;
2516		}
2517		mtx_unlock(&softc->ctl_lock);
2518		break;
2519	}
2520	case CTL_GET_PORT_LIST: {
2521		struct ctl_port *port;
2522		struct ctl_port_list *list;
2523		int i;
2524
2525		list = (struct ctl_port_list *)addr;
2526
2527		if (list->alloc_len != (list->alloc_num *
2528		    sizeof(struct ctl_port_entry))) {
2529			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2530			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2531			       "%zu\n", __func__, list->alloc_len,
2532			       list->alloc_num, sizeof(struct ctl_port_entry));
2533			retval = EINVAL;
2534			break;
2535		}
2536		list->fill_len = 0;
2537		list->fill_num = 0;
2538		list->dropped_num = 0;
2539		i = 0;
2540		mtx_lock(&softc->ctl_lock);
2541		STAILQ_FOREACH(port, &softc->port_list, links) {
2542			struct ctl_port_entry entry, *list_entry;
2543
2544			if (list->fill_num >= list->alloc_num) {
2545				list->dropped_num++;
2546				continue;
2547			}
2548
2549			entry.port_type = port->port_type;
2550			strlcpy(entry.port_name, port->port_name,
2551				sizeof(entry.port_name));
2552			entry.targ_port = port->targ_port;
2553			entry.physical_port = port->physical_port;
2554			entry.virtual_port = port->virtual_port;
2555			entry.wwnn = port->wwnn;
2556			entry.wwpn = port->wwpn;
2557			if (port->status & CTL_PORT_STATUS_ONLINE)
2558				entry.online = 1;
2559			else
2560				entry.online = 0;
2561
2562			list_entry = &list->entries[i];
2563
2564			retval = copyout(&entry, list_entry, sizeof(entry));
2565			if (retval != 0) {
2566				printf("%s: CTL_GET_PORT_LIST: copyout "
2567				       "returned %d\n", __func__, retval);
2568				break;
2569			}
2570			i++;
2571			list->fill_num++;
2572			list->fill_len += sizeof(entry);
2573		}
2574		mtx_unlock(&softc->ctl_lock);
2575
2576		/*
2577		 * If this is non-zero, we had a copyout fault, so there's
2578		 * probably no point in attempting to set the status inside
2579		 * the structure.
2580		 */
2581		if (retval != 0)
2582			break;
2583
2584		if (list->dropped_num > 0)
2585			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2586		else
2587			list->status = CTL_PORT_LIST_OK;
2588		break;
2589	}
2590	case CTL_DUMP_OOA: {
2591		struct ctl_lun *lun;
2592		union ctl_io *io;
2593		char printbuf[128];
2594		struct sbuf sb;
2595
2596		mtx_lock(&softc->ctl_lock);
2597		printf("Dumping OOA queues:\n");
2598		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2599			mtx_lock(&lun->lun_lock);
2600			for (io = (union ctl_io *)TAILQ_FIRST(
2601			     &lun->ooa_queue); io != NULL;
2602			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2603			     ooa_links)) {
2604				sbuf_new(&sb, printbuf, sizeof(printbuf),
2605					 SBUF_FIXEDLEN);
2606				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2607					    (intmax_t)lun->lun,
2608					    io->scsiio.tag_num,
2609					    (io->io_hdr.flags &
2610					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2611					    (io->io_hdr.flags &
2612					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2613					    (io->io_hdr.flags &
2614					    CTL_FLAG_ABORT) ? " ABORT" : "",
2615			                    (io->io_hdr.flags &
2616		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2617				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2618				sbuf_finish(&sb);
2619				printf("%s\n", sbuf_data(&sb));
2620			}
2621			mtx_unlock(&lun->lun_lock);
2622		}
2623		printf("OOA queues dump done\n");
2624		mtx_unlock(&softc->ctl_lock);
2625		break;
2626	}
2627	case CTL_GET_OOA: {
2628		struct ctl_lun *lun;
2629		struct ctl_ooa *ooa_hdr;
2630		struct ctl_ooa_entry *entries;
2631		uint32_t cur_fill_num;
2632
2633		ooa_hdr = (struct ctl_ooa *)addr;
2634
2635		if ((ooa_hdr->alloc_len == 0)
2636		 || (ooa_hdr->alloc_num == 0)) {
2637			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2638			       "must be non-zero\n", __func__,
2639			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2640			retval = EINVAL;
2641			break;
2642		}
2643
2644		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2645		    sizeof(struct ctl_ooa_entry))) {
2646			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2647			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2648			       __func__, ooa_hdr->alloc_len,
2649			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2650			retval = EINVAL;
2651			break;
2652		}
2653
2654		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2655		if (entries == NULL) {
2656			printf("%s: could not allocate %d bytes for OOA "
2657			       "dump\n", __func__, ooa_hdr->alloc_len);
2658			retval = ENOMEM;
2659			break;
2660		}
2661
2662		mtx_lock(&softc->ctl_lock);
2663		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2664		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2665		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2666			mtx_unlock(&softc->ctl_lock);
2667			free(entries, M_CTL);
2668			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2669			       __func__, (uintmax_t)ooa_hdr->lun_num);
2670			retval = EINVAL;
2671			break;
2672		}
2673
2674		cur_fill_num = 0;
2675
2676		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2677			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2678				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2679					ooa_hdr, entries);
2680				if (retval != 0)
2681					break;
2682			}
2683			if (retval != 0) {
2684				mtx_unlock(&softc->ctl_lock);
2685				free(entries, M_CTL);
2686				break;
2687			}
2688		} else {
2689			lun = softc->ctl_luns[ooa_hdr->lun_num];
2690
2691			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2692						    entries);
2693		}
2694		mtx_unlock(&softc->ctl_lock);
2695
2696		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2697		ooa_hdr->fill_len = ooa_hdr->fill_num *
2698			sizeof(struct ctl_ooa_entry);
2699		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2700		if (retval != 0) {
2701			printf("%s: error copying out %d bytes for OOA dump\n",
2702			       __func__, ooa_hdr->fill_len);
2703		}
2704
2705		getbintime(&ooa_hdr->cur_bt);
2706
2707		if (cur_fill_num > ooa_hdr->alloc_num) {
2708			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2709			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2710		} else {
2711			ooa_hdr->dropped_num = 0;
2712			ooa_hdr->status = CTL_OOA_OK;
2713		}
2714
2715		free(entries, M_CTL);
2716		break;
2717	}
2718	case CTL_CHECK_OOA: {
2719		union ctl_io *io;
2720		struct ctl_lun *lun;
2721		struct ctl_ooa_info *ooa_info;
2722
2723
2724		ooa_info = (struct ctl_ooa_info *)addr;
2725
2726		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2727			ooa_info->status = CTL_OOA_INVALID_LUN;
2728			break;
2729		}
2730		mtx_lock(&softc->ctl_lock);
2731		lun = softc->ctl_luns[ooa_info->lun_id];
2732		if (lun == NULL) {
2733			mtx_unlock(&softc->ctl_lock);
2734			ooa_info->status = CTL_OOA_INVALID_LUN;
2735			break;
2736		}
2737		mtx_lock(&lun->lun_lock);
2738		mtx_unlock(&softc->ctl_lock);
2739		ooa_info->num_entries = 0;
2740		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2741		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2742		     &io->io_hdr, ooa_links)) {
2743			ooa_info->num_entries++;
2744		}
2745		mtx_unlock(&lun->lun_lock);
2746
2747		ooa_info->status = CTL_OOA_SUCCESS;
2748
2749		break;
2750	}
2751	case CTL_HARD_START:
2752	case CTL_HARD_STOP: {
2753		struct ctl_fe_ioctl_startstop_info ss_info;
2754		struct cfi_metatask *metatask;
2755		struct mtx hs_mtx;
2756
2757		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2758
2759		cv_init(&ss_info.sem, "hard start/stop cv" );
2760
2761		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2762		if (metatask == NULL) {
2763			retval = ENOMEM;
2764			mtx_destroy(&hs_mtx);
2765			break;
2766		}
2767
2768		if (cmd == CTL_HARD_START)
2769			metatask->tasktype = CFI_TASK_STARTUP;
2770		else
2771			metatask->tasktype = CFI_TASK_SHUTDOWN;
2772
2773		metatask->callback = ctl_ioctl_hard_startstop_callback;
2774		metatask->callback_arg = &ss_info;
2775
2776		cfi_action(metatask);
2777
2778		/* Wait for the callback */
2779		mtx_lock(&hs_mtx);
2780		cv_wait_sig(&ss_info.sem, &hs_mtx);
2781		mtx_unlock(&hs_mtx);
2782
2783		/*
2784		 * All information has been copied from the metatask by the
2785		 * time cv_broadcast() is called, so we free the metatask here.
2786		 */
2787		cfi_free_metatask(metatask);
2788
2789		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2790
2791		mtx_destroy(&hs_mtx);
2792		break;
2793	}
2794	case CTL_BBRREAD: {
2795		struct ctl_bbrread_info *bbr_info;
2796		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2797		struct mtx bbr_mtx;
2798		struct cfi_metatask *metatask;
2799
2800		bbr_info = (struct ctl_bbrread_info *)addr;
2801
2802		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2803
2804		bzero(&bbr_mtx, sizeof(bbr_mtx));
2805		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2806
2807		fe_bbr_info.bbr_info = bbr_info;
2808		fe_bbr_info.lock = &bbr_mtx;
2809
2810		cv_init(&fe_bbr_info.sem, "BBR read cv");
2811		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2812
2813		if (metatask == NULL) {
2814			mtx_destroy(&bbr_mtx);
2815			cv_destroy(&fe_bbr_info.sem);
2816			retval = ENOMEM;
2817			break;
2818		}
2819		metatask->tasktype = CFI_TASK_BBRREAD;
2820		metatask->callback = ctl_ioctl_bbrread_callback;
2821		metatask->callback_arg = &fe_bbr_info;
2822		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2823		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2824		metatask->taskinfo.bbrread.len = bbr_info->len;
2825
2826		cfi_action(metatask);
2827
2828		mtx_lock(&bbr_mtx);
2829		while (fe_bbr_info.wakeup_done == 0)
2830			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2831		mtx_unlock(&bbr_mtx);
2832
2833		bbr_info->status = metatask->status;
2834		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2835		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2836		memcpy(&bbr_info->sense_data,
2837		       &metatask->taskinfo.bbrread.sense_data,
2838		       MIN(sizeof(bbr_info->sense_data),
2839			   sizeof(metatask->taskinfo.bbrread.sense_data)));
2840
2841		cfi_free_metatask(metatask);
2842
2843		mtx_destroy(&bbr_mtx);
2844		cv_destroy(&fe_bbr_info.sem);
2845
2846		break;
2847	}
2848	case CTL_DELAY_IO: {
2849		struct ctl_io_delay_info *delay_info;
2850#ifdef CTL_IO_DELAY
2851		struct ctl_lun *lun;
2852#endif /* CTL_IO_DELAY */
2853
2854		delay_info = (struct ctl_io_delay_info *)addr;
2855
2856#ifdef CTL_IO_DELAY
2857		mtx_lock(&softc->ctl_lock);
2858
2859		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2860		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2861			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2862		} else {
2863			lun = softc->ctl_luns[delay_info->lun_id];
2864			mtx_lock(&lun->lun_lock);
2865
2866			delay_info->status = CTL_DELAY_STATUS_OK;
2867
2868			switch (delay_info->delay_type) {
2869			case CTL_DELAY_TYPE_CONT:
2870				break;
2871			case CTL_DELAY_TYPE_ONESHOT:
2872				break;
2873			default:
2874				delay_info->status =
2875					CTL_DELAY_STATUS_INVALID_TYPE;
2876				break;
2877			}
2878
2879			switch (delay_info->delay_loc) {
2880			case CTL_DELAY_LOC_DATAMOVE:
2881				lun->delay_info.datamove_type =
2882					delay_info->delay_type;
2883				lun->delay_info.datamove_delay =
2884					delay_info->delay_secs;
2885				break;
2886			case CTL_DELAY_LOC_DONE:
2887				lun->delay_info.done_type =
2888					delay_info->delay_type;
2889				lun->delay_info.done_delay =
2890					delay_info->delay_secs;
2891				break;
2892			default:
2893				delay_info->status =
2894					CTL_DELAY_STATUS_INVALID_LOC;
2895				break;
2896			}
2897			mtx_unlock(&lun->lun_lock);
2898		}
2899
2900		mtx_unlock(&softc->ctl_lock);
2901#else
2902		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2903#endif /* CTL_IO_DELAY */
2904		break;
2905	}
2906	case CTL_REALSYNC_SET: {
2907		int *syncstate;
2908
2909		syncstate = (int *)addr;
2910
2911		mtx_lock(&softc->ctl_lock);
2912		switch (*syncstate) {
2913		case 0:
2914			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2915			break;
2916		case 1:
2917			softc->flags |= CTL_FLAG_REAL_SYNC;
2918			break;
2919		default:
2920			retval = EINVAL;
2921			break;
2922		}
2923		mtx_unlock(&softc->ctl_lock);
2924		break;
2925	}
2926	case CTL_REALSYNC_GET: {
2927		int *syncstate;
2928
2929		syncstate = (int*)addr;
2930
2931		mtx_lock(&softc->ctl_lock);
2932		if (softc->flags & CTL_FLAG_REAL_SYNC)
2933			*syncstate = 1;
2934		else
2935			*syncstate = 0;
2936		mtx_unlock(&softc->ctl_lock);
2937
2938		break;
2939	}
2940	case CTL_SETSYNC:
2941	case CTL_GETSYNC: {
2942		struct ctl_sync_info *sync_info;
2943		struct ctl_lun *lun;
2944
2945		sync_info = (struct ctl_sync_info *)addr;
2946
2947		mtx_lock(&softc->ctl_lock);
2948		lun = softc->ctl_luns[sync_info->lun_id];
2949		if (lun == NULL) {
2950			mtx_unlock(&softc->ctl_lock);
2951			sync_info->status = CTL_GS_SYNC_NO_LUN;
2952		}
2953		/*
2954		 * Get or set the sync interval.  We're not bounds checking
2955		 * in the set case, hopefully the user won't do something
2956		 * silly.
2957		 */
2958		mtx_lock(&lun->lun_lock);
2959		mtx_unlock(&softc->ctl_lock);
2960		if (cmd == CTL_GETSYNC)
2961			sync_info->sync_interval = lun->sync_interval;
2962		else
2963			lun->sync_interval = sync_info->sync_interval;
2964		mtx_unlock(&lun->lun_lock);
2965
2966		sync_info->status = CTL_GS_SYNC_OK;
2967
2968		break;
2969	}
2970	case CTL_GETSTATS: {
2971		struct ctl_stats *stats;
2972		struct ctl_lun *lun;
2973		int i;
2974
2975		stats = (struct ctl_stats *)addr;
2976
2977		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2978		     stats->alloc_len) {
2979			stats->status = CTL_SS_NEED_MORE_SPACE;
2980			stats->num_luns = softc->num_luns;
2981			break;
2982		}
2983		/*
2984		 * XXX KDM no locking here.  If the LUN list changes,
2985		 * things can blow up.
2986		 */
2987		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2988		     i++, lun = STAILQ_NEXT(lun, links)) {
2989			retval = copyout(&lun->stats, &stats->lun_stats[i],
2990					 sizeof(lun->stats));
2991			if (retval != 0)
2992				break;
2993		}
2994		stats->num_luns = softc->num_luns;
2995		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2996				 softc->num_luns;
2997		stats->status = CTL_SS_OK;
2998#ifdef CTL_TIME_IO
2999		stats->flags = CTL_STATS_FLAG_TIME_VALID;
3000#else
3001		stats->flags = CTL_STATS_FLAG_NONE;
3002#endif
3003		getnanouptime(&stats->timestamp);
3004		break;
3005	}
3006	case CTL_ERROR_INJECT: {
3007		struct ctl_error_desc *err_desc, *new_err_desc;
3008		struct ctl_lun *lun;
3009
3010		err_desc = (struct ctl_error_desc *)addr;
3011
3012		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
3013				      M_WAITOK | M_ZERO);
3014		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
3015
3016		mtx_lock(&softc->ctl_lock);
3017		lun = softc->ctl_luns[err_desc->lun_id];
3018		if (lun == NULL) {
3019			mtx_unlock(&softc->ctl_lock);
3020			free(new_err_desc, M_CTL);
3021			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
3022			       __func__, (uintmax_t)err_desc->lun_id);
3023			retval = EINVAL;
3024			break;
3025		}
3026		mtx_lock(&lun->lun_lock);
3027		mtx_unlock(&softc->ctl_lock);
3028
3029		/*
3030		 * We could do some checking here to verify the validity
3031		 * of the request, but given the complexity of error
3032		 * injection requests, the checking logic would be fairly
3033		 * complex.
3034		 *
3035		 * For now, if the request is invalid, it just won't get
3036		 * executed and might get deleted.
3037		 */
3038		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
3039
3040		/*
3041		 * XXX KDM check to make sure the serial number is unique,
3042		 * in case we somehow manage to wrap.  That shouldn't
3043		 * happen for a very long time, but it's the right thing to
3044		 * do.
3045		 */
3046		new_err_desc->serial = lun->error_serial;
3047		err_desc->serial = lun->error_serial;
3048		lun->error_serial++;
3049
3050		mtx_unlock(&lun->lun_lock);
3051		break;
3052	}
3053	case CTL_ERROR_INJECT_DELETE: {
3054		struct ctl_error_desc *delete_desc, *desc, *desc2;
3055		struct ctl_lun *lun;
3056		int delete_done;
3057
3058		delete_desc = (struct ctl_error_desc *)addr;
3059		delete_done = 0;
3060
3061		mtx_lock(&softc->ctl_lock);
3062		lun = softc->ctl_luns[delete_desc->lun_id];
3063		if (lun == NULL) {
3064			mtx_unlock(&softc->ctl_lock);
3065			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
3066			       __func__, (uintmax_t)delete_desc->lun_id);
3067			retval = EINVAL;
3068			break;
3069		}
3070		mtx_lock(&lun->lun_lock);
3071		mtx_unlock(&softc->ctl_lock);
3072		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
3073			if (desc->serial != delete_desc->serial)
3074				continue;
3075
3076			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
3077				      links);
3078			free(desc, M_CTL);
3079			delete_done = 1;
3080		}
3081		mtx_unlock(&lun->lun_lock);
3082		if (delete_done == 0) {
3083			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
3084			       "error serial %ju on LUN %u\n", __func__,
3085			       delete_desc->serial, delete_desc->lun_id);
3086			retval = EINVAL;
3087			break;
3088		}
3089		break;
3090	}
3091	case CTL_DUMP_STRUCTS: {
3092		int i, j, k;
3093		struct ctl_port *port;
3094		struct ctl_frontend *fe;
3095
3096		mtx_lock(&softc->ctl_lock);
3097		printf("CTL Persistent Reservation information start:\n");
3098		for (i = 0; i < CTL_MAX_LUNS; i++) {
3099			struct ctl_lun *lun;
3100
3101			lun = softc->ctl_luns[i];
3102
3103			if ((lun == NULL)
3104			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
3105				continue;
3106
3107			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
3108				if (lun->pr_keys[j] == NULL)
3109					continue;
3110				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
3111					if (lun->pr_keys[j][k] == 0)
3112						continue;
3113					printf("  LUN %d port %d iid %d key "
3114					       "%#jx\n", i, j, k,
3115					       (uintmax_t)lun->pr_keys[j][k]);
3116				}
3117			}
3118		}
3119		printf("CTL Persistent Reservation information end\n");
3120		printf("CTL Ports:\n");
3121		STAILQ_FOREACH(port, &softc->port_list, links) {
3122			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3123			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3124			       port->frontend->name, port->port_type,
3125			       port->physical_port, port->virtual_port,
3126			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3127			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3128				if (port->wwpn_iid[j].in_use == 0 &&
3129				    port->wwpn_iid[j].wwpn == 0 &&
3130				    port->wwpn_iid[j].name == NULL)
3131					continue;
3132
3133				printf("    iid %u use %d WWPN %#jx '%s'\n",
3134				    j, port->wwpn_iid[j].in_use,
3135				    (uintmax_t)port->wwpn_iid[j].wwpn,
3136				    port->wwpn_iid[j].name);
3137			}
3138		}
3139		printf("CTL Port information end\n");
3140		mtx_unlock(&softc->ctl_lock);
3141		/*
3142		 * XXX KDM calling this without a lock.  We'd likely want
3143		 * to drop the lock before calling the frontend's dump
3144		 * routine anyway.
3145		 */
3146		printf("CTL Frontends:\n");
3147		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3148			printf("  Frontend '%s'\n", fe->name);
3149			if (fe->fe_dump != NULL)
3150				fe->fe_dump();
3151		}
3152		printf("CTL Frontend information end\n");
3153		break;
3154	}
3155	case CTL_LUN_REQ: {
3156		struct ctl_lun_req *lun_req;
3157		struct ctl_backend_driver *backend;
3158
3159		lun_req = (struct ctl_lun_req *)addr;
3160
3161		backend = ctl_backend_find(lun_req->backend);
3162		if (backend == NULL) {
3163			lun_req->status = CTL_LUN_ERROR;
3164			snprintf(lun_req->error_str,
3165				 sizeof(lun_req->error_str),
3166				 "Backend \"%s\" not found.",
3167				 lun_req->backend);
3168			break;
3169		}
3170		if (lun_req->num_be_args > 0) {
3171			lun_req->kern_be_args = ctl_copyin_args(
3172				lun_req->num_be_args,
3173				lun_req->be_args,
3174				lun_req->error_str,
3175				sizeof(lun_req->error_str));
3176			if (lun_req->kern_be_args == NULL) {
3177				lun_req->status = CTL_LUN_ERROR;
3178				break;
3179			}
3180		}
3181
3182		retval = backend->ioctl(dev, cmd, addr, flag, td);
3183
3184		if (lun_req->num_be_args > 0) {
3185			ctl_copyout_args(lun_req->num_be_args,
3186				      lun_req->kern_be_args);
3187			ctl_free_args(lun_req->num_be_args,
3188				      lun_req->kern_be_args);
3189		}
3190		break;
3191	}
3192	case CTL_LUN_LIST: {
3193		struct sbuf *sb;
3194		struct ctl_lun *lun;
3195		struct ctl_lun_list *list;
3196		struct ctl_option *opt;
3197
3198		list = (struct ctl_lun_list *)addr;
3199
3200		/*
3201		 * Allocate a fixed length sbuf here, based on the length
3202		 * of the user's buffer.  We could allocate an auto-extending
3203		 * buffer, and then tell the user how much larger our
3204		 * amount of data is than his buffer, but that presents
3205		 * some problems:
3206		 *
3207		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3208		 *     we can't hold a lock while calling them with an
3209		 *     auto-extending buffer.
3210 		 *
3211		 * 2.  There is not currently a LUN reference counting
3212		 *     mechanism, outside of outstanding transactions on
3213		 *     the LUN's OOA queue.  So a LUN could go away on us
3214		 *     while we're getting the LUN number, backend-specific
3215		 *     information, etc.  Thus, given the way things
3216		 *     currently work, we need to hold the CTL lock while
3217		 *     grabbing LUN information.
3218		 *
3219		 * So, from the user's standpoint, the best thing to do is
3220		 * allocate what he thinks is a reasonable buffer length,
3221		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3222		 * double the buffer length and try again.  (And repeat
3223		 * that until he succeeds.)
3224		 */
3225		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3226		if (sb == NULL) {
3227			list->status = CTL_LUN_LIST_ERROR;
3228			snprintf(list->error_str, sizeof(list->error_str),
3229				 "Unable to allocate %d bytes for LUN list",
3230				 list->alloc_len);
3231			break;
3232		}
3233
3234		sbuf_printf(sb, "<ctllunlist>\n");
3235
3236		mtx_lock(&softc->ctl_lock);
3237		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3238			mtx_lock(&lun->lun_lock);
3239			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3240					     (uintmax_t)lun->lun);
3241
3242			/*
3243			 * Bail out as soon as we see that we've overfilled
3244			 * the buffer.
3245			 */
3246			if (retval != 0)
3247				break;
3248
3249			retval = sbuf_printf(sb, "\t<backend_type>%s"
3250					     "</backend_type>\n",
3251					     (lun->backend == NULL) ?  "none" :
3252					     lun->backend->name);
3253
3254			if (retval != 0)
3255				break;
3256
3257			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3258					     lun->be_lun->lun_type);
3259
3260			if (retval != 0)
3261				break;
3262
3263			if (lun->backend == NULL) {
3264				retval = sbuf_printf(sb, "</lun>\n");
3265				if (retval != 0)
3266					break;
3267				continue;
3268			}
3269
3270			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3271					     (lun->be_lun->maxlba > 0) ?
3272					     lun->be_lun->maxlba + 1 : 0);
3273
3274			if (retval != 0)
3275				break;
3276
3277			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3278					     lun->be_lun->blocksize);
3279
3280			if (retval != 0)
3281				break;
3282
3283			retval = sbuf_printf(sb, "\t<serial_number>");
3284
3285			if (retval != 0)
3286				break;
3287
3288			retval = ctl_sbuf_printf_esc(sb,
3289			    lun->be_lun->serial_num,
3290			    sizeof(lun->be_lun->serial_num));
3291
3292			if (retval != 0)
3293				break;
3294
3295			retval = sbuf_printf(sb, "</serial_number>\n");
3296
3297			if (retval != 0)
3298				break;
3299
3300			retval = sbuf_printf(sb, "\t<device_id>");
3301
3302			if (retval != 0)
3303				break;
3304
3305			retval = ctl_sbuf_printf_esc(sb,
3306			    lun->be_lun->device_id,
3307			    sizeof(lun->be_lun->device_id));
3308
3309			if (retval != 0)
3310				break;
3311
3312			retval = sbuf_printf(sb, "</device_id>\n");
3313
3314			if (retval != 0)
3315				break;
3316
3317			if (lun->backend->lun_info != NULL) {
3318				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3319				if (retval != 0)
3320					break;
3321			}
3322			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3323				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3324				    opt->name, opt->value, opt->name);
3325				if (retval != 0)
3326					break;
3327			}
3328
3329			retval = sbuf_printf(sb, "</lun>\n");
3330
3331			if (retval != 0)
3332				break;
3333			mtx_unlock(&lun->lun_lock);
3334		}
3335		if (lun != NULL)
3336			mtx_unlock(&lun->lun_lock);
3337		mtx_unlock(&softc->ctl_lock);
3338
3339		if ((retval != 0)
3340		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3341			retval = 0;
3342			sbuf_delete(sb);
3343			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3344			snprintf(list->error_str, sizeof(list->error_str),
3345				 "Out of space, %d bytes is too small",
3346				 list->alloc_len);
3347			break;
3348		}
3349
3350		sbuf_finish(sb);
3351
3352		retval = copyout(sbuf_data(sb), list->lun_xml,
3353				 sbuf_len(sb) + 1);
3354
3355		list->fill_len = sbuf_len(sb) + 1;
3356		list->status = CTL_LUN_LIST_OK;
3357		sbuf_delete(sb);
3358		break;
3359	}
3360	case CTL_ISCSI: {
3361		struct ctl_iscsi *ci;
3362		struct ctl_frontend *fe;
3363
3364		ci = (struct ctl_iscsi *)addr;
3365
3366		fe = ctl_frontend_find("iscsi");
3367		if (fe == NULL) {
3368			ci->status = CTL_ISCSI_ERROR;
3369			snprintf(ci->error_str, sizeof(ci->error_str),
3370			    "Frontend \"iscsi\" not found.");
3371			break;
3372		}
3373
3374		retval = fe->ioctl(dev, cmd, addr, flag, td);
3375		break;
3376	}
3377	case CTL_PORT_REQ: {
3378		struct ctl_req *req;
3379		struct ctl_frontend *fe;
3380
3381		req = (struct ctl_req *)addr;
3382
3383		fe = ctl_frontend_find(req->driver);
3384		if (fe == NULL) {
3385			req->status = CTL_LUN_ERROR;
3386			snprintf(req->error_str, sizeof(req->error_str),
3387			    "Frontend \"%s\" not found.", req->driver);
3388			break;
3389		}
3390		if (req->num_args > 0) {
3391			req->kern_args = ctl_copyin_args(req->num_args,
3392			    req->args, req->error_str, sizeof(req->error_str));
3393			if (req->kern_args == NULL) {
3394				req->status = CTL_LUN_ERROR;
3395				break;
3396			}
3397		}
3398
3399		retval = fe->ioctl(dev, cmd, addr, flag, td);
3400
3401		if (req->num_args > 0) {
3402			ctl_copyout_args(req->num_args, req->kern_args);
3403			ctl_free_args(req->num_args, req->kern_args);
3404		}
3405		break;
3406	}
3407	case CTL_PORT_LIST: {
3408		struct sbuf *sb;
3409		struct ctl_port *port;
3410		struct ctl_lun_list *list;
3411		struct ctl_option *opt;
3412		int j;
3413		uint32_t plun;
3414
3415		list = (struct ctl_lun_list *)addr;
3416
3417		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3418		if (sb == NULL) {
3419			list->status = CTL_LUN_LIST_ERROR;
3420			snprintf(list->error_str, sizeof(list->error_str),
3421				 "Unable to allocate %d bytes for LUN list",
3422				 list->alloc_len);
3423			break;
3424		}
3425
3426		sbuf_printf(sb, "<ctlportlist>\n");
3427
3428		mtx_lock(&softc->ctl_lock);
3429		STAILQ_FOREACH(port, &softc->port_list, links) {
3430			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3431					     (uintmax_t)port->targ_port);
3432
3433			/*
3434			 * Bail out as soon as we see that we've overfilled
3435			 * the buffer.
3436			 */
3437			if (retval != 0)
3438				break;
3439
3440			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3441			    "</frontend_type>\n", port->frontend->name);
3442			if (retval != 0)
3443				break;
3444
3445			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3446					     port->port_type);
3447			if (retval != 0)
3448				break;
3449
3450			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3451			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3452			if (retval != 0)
3453				break;
3454
3455			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3456			    port->port_name);
3457			if (retval != 0)
3458				break;
3459
3460			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3461			    port->physical_port);
3462			if (retval != 0)
3463				break;
3464
3465			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3466			    port->virtual_port);
3467			if (retval != 0)
3468				break;
3469
3470			if (port->target_devid != NULL) {
3471				sbuf_printf(sb, "\t<target>");
3472				ctl_id_sbuf(port->target_devid, sb);
3473				sbuf_printf(sb, "</target>\n");
3474			}
3475
3476			if (port->port_devid != NULL) {
3477				sbuf_printf(sb, "\t<port>");
3478				ctl_id_sbuf(port->port_devid, sb);
3479				sbuf_printf(sb, "</port>\n");
3480			}
3481
3482			if (port->port_info != NULL) {
3483				retval = port->port_info(port->onoff_arg, sb);
3484				if (retval != 0)
3485					break;
3486			}
3487			STAILQ_FOREACH(opt, &port->options, links) {
3488				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3489				    opt->name, opt->value, opt->name);
3490				if (retval != 0)
3491					break;
3492			}
3493
3494			if (port->lun_map != NULL) {
3495				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3496				for (j = 0; j < CTL_MAX_LUNS; j++) {
3497					plun = ctl_lun_map_from_port(port, j);
3498					if (plun >= CTL_MAX_LUNS)
3499						continue;
3500					sbuf_printf(sb,
3501					    "\t<lun id=\"%u\">%u</lun>\n",
3502					    j, plun);
3503				}
3504			}
3505
3506			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3507				if (port->wwpn_iid[j].in_use == 0 ||
3508				    (port->wwpn_iid[j].wwpn == 0 &&
3509				     port->wwpn_iid[j].name == NULL))
3510					continue;
3511
3512				if (port->wwpn_iid[j].name != NULL)
3513					retval = sbuf_printf(sb,
3514					    "\t<initiator id=\"%u\">%s</initiator>\n",
3515					    j, port->wwpn_iid[j].name);
3516				else
3517					retval = sbuf_printf(sb,
3518					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3519					    j, port->wwpn_iid[j].wwpn);
3520				if (retval != 0)
3521					break;
3522			}
3523			if (retval != 0)
3524				break;
3525
3526			retval = sbuf_printf(sb, "</targ_port>\n");
3527			if (retval != 0)
3528				break;
3529		}
3530		mtx_unlock(&softc->ctl_lock);
3531
3532		if ((retval != 0)
3533		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3534			retval = 0;
3535			sbuf_delete(sb);
3536			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3537			snprintf(list->error_str, sizeof(list->error_str),
3538				 "Out of space, %d bytes is too small",
3539				 list->alloc_len);
3540			break;
3541		}
3542
3543		sbuf_finish(sb);
3544
3545		retval = copyout(sbuf_data(sb), list->lun_xml,
3546				 sbuf_len(sb) + 1);
3547
3548		list->fill_len = sbuf_len(sb) + 1;
3549		list->status = CTL_LUN_LIST_OK;
3550		sbuf_delete(sb);
3551		break;
3552	}
3553	case CTL_LUN_MAP: {
3554		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3555		struct ctl_port *port;
3556
3557		mtx_lock(&softc->ctl_lock);
3558		if (lm->port >= CTL_MAX_PORTS ||
3559		    (port = softc->ctl_ports[lm->port]) == NULL) {
3560			mtx_unlock(&softc->ctl_lock);
3561			return (ENXIO);
3562		}
3563		if (lm->plun < CTL_MAX_LUNS) {
3564			if (lm->lun == UINT32_MAX)
3565				retval = ctl_lun_map_unset(port, lm->plun);
3566			else if (lm->lun < CTL_MAX_LUNS &&
3567			    softc->ctl_luns[lm->lun] != NULL)
3568				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3569			else {
3570				mtx_unlock(&softc->ctl_lock);
3571				return (ENXIO);
3572			}
3573		} else if (lm->plun == UINT32_MAX) {
3574			if (lm->lun == UINT32_MAX)
3575				retval = ctl_lun_map_deinit(port);
3576			else
3577				retval = ctl_lun_map_init(port);
3578		} else {
3579			mtx_unlock(&softc->ctl_lock);
3580			return (ENXIO);
3581		}
3582		mtx_unlock(&softc->ctl_lock);
3583		break;
3584	}
3585	default: {
3586		/* XXX KDM should we fix this? */
3587#if 0
3588		struct ctl_backend_driver *backend;
3589		unsigned int type;
3590		int found;
3591
3592		found = 0;
3593
3594		/*
3595		 * We encode the backend type as the ioctl type for backend
3596		 * ioctls.  So parse it out here, and then search for a
3597		 * backend of this type.
3598		 */
3599		type = _IOC_TYPE(cmd);
3600
3601		STAILQ_FOREACH(backend, &softc->be_list, links) {
3602			if (backend->type == type) {
3603				found = 1;
3604				break;
3605			}
3606		}
3607		if (found == 0) {
3608			printf("ctl: unknown ioctl command %#lx or backend "
3609			       "%d\n", cmd, type);
3610			retval = EINVAL;
3611			break;
3612		}
3613		retval = backend->ioctl(dev, cmd, addr, flag, td);
3614#endif
3615		retval = ENOTTY;
3616		break;
3617	}
3618	}
3619	return (retval);
3620}
3621
3622uint32_t
3623ctl_get_initindex(struct ctl_nexus *nexus)
3624{
3625	if (nexus->targ_port < CTL_MAX_PORTS)
3626		return (nexus->initid.id +
3627			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3628	else
3629		return (nexus->initid.id +
3630		       ((nexus->targ_port - CTL_MAX_PORTS) *
3631			CTL_MAX_INIT_PER_PORT));
3632}
3633
3634uint32_t
3635ctl_get_resindex(struct ctl_nexus *nexus)
3636{
3637	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3638}
3639
3640uint32_t
3641ctl_port_idx(int port_num)
3642{
3643	if (port_num < CTL_MAX_PORTS)
3644		return(port_num);
3645	else
3646		return(port_num - CTL_MAX_PORTS);
3647}
3648
3649int
3650ctl_lun_map_init(struct ctl_port *port)
3651{
3652	uint32_t i;
3653
3654	if (port->lun_map == NULL)
3655		port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3656		    M_CTL, M_NOWAIT);
3657	if (port->lun_map == NULL)
3658		return (ENOMEM);
3659	for (i = 0; i < CTL_MAX_LUNS; i++)
3660		port->lun_map[i] = UINT32_MAX;
3661	return (0);
3662}
3663
3664int
3665ctl_lun_map_deinit(struct ctl_port *port)
3666{
3667
3668	if (port->lun_map == NULL)
3669		return (0);
3670	free(port->lun_map, M_CTL);
3671	port->lun_map = NULL;
3672	return (0);
3673}
3674
3675int
3676ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3677{
3678	int status;
3679
3680	if (port->lun_map == NULL) {
3681		status = ctl_lun_map_init(port);
3682		if (status != 0)
3683			return (status);
3684	}
3685	port->lun_map[plun] = glun;
3686	return (0);
3687}
3688
3689int
3690ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3691{
3692
3693	if (port->lun_map == NULL)
3694		return (0);
3695	port->lun_map[plun] = UINT32_MAX;
3696	return (0);
3697}
3698
3699int
3700ctl_lun_map_unsetg(struct ctl_port *port, uint32_t glun)
3701{
3702	int i;
3703
3704	if (port->lun_map == NULL)
3705		return (0);
3706	for (i = 0; i < CTL_MAX_LUNS; i++) {
3707		if (port->lun_map[i] == glun)
3708			port->lun_map[i] = UINT32_MAX;
3709	}
3710	return (0);
3711}
3712
3713uint32_t
3714ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3715{
3716
3717	if (port == NULL)
3718		return (UINT32_MAX);
3719	if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3720		return (lun_id);
3721	return (port->lun_map[lun_id]);
3722}
3723
3724uint32_t
3725ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3726{
3727	uint32_t i;
3728
3729	if (port == NULL)
3730		return (UINT32_MAX);
3731	if (port->lun_map == NULL)
3732		return (lun_id);
3733	for (i = 0; i < CTL_MAX_LUNS; i++) {
3734		if (port->lun_map[i] == lun_id)
3735			return (i);
3736	}
3737	return (UINT32_MAX);
3738}
3739
3740static struct ctl_port *
3741ctl_io_port(struct ctl_io_hdr *io_hdr)
3742{
3743	int port_num;
3744
3745	port_num = io_hdr->nexus.targ_port;
3746	return (control_softc->ctl_ports[ctl_port_idx(port_num)]);
3747}
3748
3749/*
3750 * Note:  This only works for bitmask sizes that are at least 32 bits, and
3751 * that are a power of 2.
3752 */
3753int
3754ctl_ffz(uint32_t *mask, uint32_t size)
3755{
3756	uint32_t num_chunks, num_pieces;
3757	int i, j;
3758
3759	num_chunks = (size >> 5);
3760	if (num_chunks == 0)
3761		num_chunks++;
3762	num_pieces = MIN((sizeof(uint32_t) * 8), size);
3763
3764	for (i = 0; i < num_chunks; i++) {
3765		for (j = 0; j < num_pieces; j++) {
3766			if ((mask[i] & (1 << j)) == 0)
3767				return ((i << 5) + j);
3768		}
3769	}
3770
3771	return (-1);
3772}
3773
3774int
3775ctl_set_mask(uint32_t *mask, uint32_t bit)
3776{
3777	uint32_t chunk, piece;
3778
3779	chunk = bit >> 5;
3780	piece = bit % (sizeof(uint32_t) * 8);
3781
3782	if ((mask[chunk] & (1 << piece)) != 0)
3783		return (-1);
3784	else
3785		mask[chunk] |= (1 << piece);
3786
3787	return (0);
3788}
3789
3790int
3791ctl_clear_mask(uint32_t *mask, uint32_t bit)
3792{
3793	uint32_t chunk, piece;
3794
3795	chunk = bit >> 5;
3796	piece = bit % (sizeof(uint32_t) * 8);
3797
3798	if ((mask[chunk] & (1 << piece)) == 0)
3799		return (-1);
3800	else
3801		mask[chunk] &= ~(1 << piece);
3802
3803	return (0);
3804}
3805
3806int
3807ctl_is_set(uint32_t *mask, uint32_t bit)
3808{
3809	uint32_t chunk, piece;
3810
3811	chunk = bit >> 5;
3812	piece = bit % (sizeof(uint32_t) * 8);
3813
3814	if ((mask[chunk] & (1 << piece)) == 0)
3815		return (0);
3816	else
3817		return (1);
3818}
3819
3820static uint64_t
3821ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3822{
3823	uint64_t *t;
3824
3825	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3826	if (t == NULL)
3827		return (0);
3828	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3829}
3830
3831static void
3832ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3833{
3834	uint64_t *t;
3835
3836	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3837	if (t == NULL)
3838		return;
3839	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3840}
3841
3842static void
3843ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3844{
3845	uint64_t *p;
3846	u_int i;
3847
3848	i = residx/CTL_MAX_INIT_PER_PORT;
3849	if (lun->pr_keys[i] != NULL)
3850		return;
3851	mtx_unlock(&lun->lun_lock);
3852	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3853	    M_WAITOK | M_ZERO);
3854	mtx_lock(&lun->lun_lock);
3855	if (lun->pr_keys[i] == NULL)
3856		lun->pr_keys[i] = p;
3857	else
3858		free(p, M_CTL);
3859}
3860
3861static void
3862ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3863{
3864	uint64_t *t;
3865
3866	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3867	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3868	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3869}
3870
3871/*
3872 * ctl_softc, pool_name, total_ctl_io are passed in.
3873 * npool is passed out.
3874 */
3875int
3876ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3877		uint32_t total_ctl_io, void **npool)
3878{
3879#ifdef IO_POOLS
3880	struct ctl_io_pool *pool;
3881
3882	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3883					    M_NOWAIT | M_ZERO);
3884	if (pool == NULL)
3885		return (ENOMEM);
3886
3887	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3888	pool->ctl_softc = ctl_softc;
3889	pool->zone = uma_zsecond_create(pool->name, NULL,
3890	    NULL, NULL, NULL, ctl_softc->io_zone);
3891	/* uma_prealloc(pool->zone, total_ctl_io); */
3892
3893	*npool = pool;
3894#else
3895	*npool = ctl_softc->io_zone;
3896#endif
3897	return (0);
3898}
3899
3900void
3901ctl_pool_free(struct ctl_io_pool *pool)
3902{
3903
3904	if (pool == NULL)
3905		return;
3906
3907#ifdef IO_POOLS
3908	uma_zdestroy(pool->zone);
3909	free(pool, M_CTL);
3910#endif
3911}
3912
3913union ctl_io *
3914ctl_alloc_io(void *pool_ref)
3915{
3916	union ctl_io *io;
3917#ifdef IO_POOLS
3918	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3919
3920	io = uma_zalloc(pool->zone, M_WAITOK);
3921#else
3922	io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3923#endif
3924	if (io != NULL)
3925		io->io_hdr.pool = pool_ref;
3926	return (io);
3927}
3928
3929union ctl_io *
3930ctl_alloc_io_nowait(void *pool_ref)
3931{
3932	union ctl_io *io;
3933#ifdef IO_POOLS
3934	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3935
3936	io = uma_zalloc(pool->zone, M_NOWAIT);
3937#else
3938	io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3939#endif
3940	if (io != NULL)
3941		io->io_hdr.pool = pool_ref;
3942	return (io);
3943}
3944
3945void
3946ctl_free_io(union ctl_io *io)
3947{
3948#ifdef IO_POOLS
3949	struct ctl_io_pool *pool;
3950#endif
3951
3952	if (io == NULL)
3953		return;
3954
3955#ifdef IO_POOLS
3956	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3957	uma_zfree(pool->zone, io);
3958#else
3959	uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3960#endif
3961}
3962
3963void
3964ctl_zero_io(union ctl_io *io)
3965{
3966	void *pool_ref;
3967
3968	if (io == NULL)
3969		return;
3970
3971	/*
3972	 * May need to preserve linked list pointers at some point too.
3973	 */
3974	pool_ref = io->io_hdr.pool;
3975	memset(io, 0, sizeof(*io));
3976	io->io_hdr.pool = pool_ref;
3977}
3978
3979/*
3980 * This routine is currently used for internal copies of ctl_ios that need
3981 * to persist for some reason after we've already returned status to the
3982 * FETD.  (Thus the flag set.)
3983 *
3984 * XXX XXX
3985 * Note that this makes a blind copy of all fields in the ctl_io, except
3986 * for the pool reference.  This includes any memory that has been
3987 * allocated!  That memory will no longer be valid after done has been
3988 * called, so this would be VERY DANGEROUS for command that actually does
3989 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3990 * start and stop commands, which don't transfer any data, so this is not a
3991 * problem.  If it is used for anything else, the caller would also need to
3992 * allocate data buffer space and this routine would need to be modified to
3993 * copy the data buffer(s) as well.
3994 */
3995void
3996ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3997{
3998	void *pool_ref;
3999
4000	if ((src == NULL)
4001	 || (dest == NULL))
4002		return;
4003
4004	/*
4005	 * May need to preserve linked list pointers at some point too.
4006	 */
4007	pool_ref = dest->io_hdr.pool;
4008
4009	memcpy(dest, src, MIN(sizeof(*src), sizeof(*dest)));
4010
4011	dest->io_hdr.pool = pool_ref;
4012	/*
4013	 * We need to know that this is an internal copy, and doesn't need
4014	 * to get passed back to the FETD that allocated it.
4015	 */
4016	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
4017}
4018
4019int
4020ctl_expand_number(const char *buf, uint64_t *num)
4021{
4022	char *endptr;
4023	uint64_t number;
4024	unsigned shift;
4025
4026	number = strtoq(buf, &endptr, 0);
4027
4028	switch (tolower((unsigned char)*endptr)) {
4029	case 'e':
4030		shift = 60;
4031		break;
4032	case 'p':
4033		shift = 50;
4034		break;
4035	case 't':
4036		shift = 40;
4037		break;
4038	case 'g':
4039		shift = 30;
4040		break;
4041	case 'm':
4042		shift = 20;
4043		break;
4044	case 'k':
4045		shift = 10;
4046		break;
4047	case 'b':
4048	case '\0': /* No unit. */
4049		*num = number;
4050		return (0);
4051	default:
4052		/* Unrecognized unit. */
4053		return (-1);
4054	}
4055
4056	if ((number << shift) >> shift != number) {
4057		/* Overflow */
4058		return (-1);
4059	}
4060	*num = number << shift;
4061	return (0);
4062}
4063
4064
4065/*
4066 * This routine could be used in the future to load default and/or saved
4067 * mode page parameters for a particuar lun.
4068 */
4069static int
4070ctl_init_page_index(struct ctl_lun *lun)
4071{
4072	int i;
4073	struct ctl_page_index *page_index;
4074	const char *value;
4075	uint64_t ival;
4076
4077	memcpy(&lun->mode_pages.index, page_index_template,
4078	       sizeof(page_index_template));
4079
4080	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4081
4082		page_index = &lun->mode_pages.index[i];
4083		/*
4084		 * If this is a disk-only mode page, there's no point in
4085		 * setting it up.  For some pages, we have to have some
4086		 * basic information about the disk in order to calculate the
4087		 * mode page data.
4088		 */
4089		if ((lun->be_lun->lun_type != T_DIRECT)
4090		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4091			continue;
4092
4093		switch (page_index->page_code & SMPH_PC_MASK) {
4094		case SMS_RW_ERROR_RECOVERY_PAGE: {
4095			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4096				panic("subpage is incorrect!");
4097			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
4098			       &rw_er_page_default,
4099			       sizeof(rw_er_page_default));
4100			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
4101			       &rw_er_page_changeable,
4102			       sizeof(rw_er_page_changeable));
4103			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
4104			       &rw_er_page_default,
4105			       sizeof(rw_er_page_default));
4106			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
4107			       &rw_er_page_default,
4108			       sizeof(rw_er_page_default));
4109			page_index->page_data =
4110				(uint8_t *)lun->mode_pages.rw_er_page;
4111			break;
4112		}
4113		case SMS_FORMAT_DEVICE_PAGE: {
4114			struct scsi_format_page *format_page;
4115
4116			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4117				panic("subpage is incorrect!");
4118
4119			/*
4120			 * Sectors per track are set above.  Bytes per
4121			 * sector need to be set here on a per-LUN basis.
4122			 */
4123			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4124			       &format_page_default,
4125			       sizeof(format_page_default));
4126			memcpy(&lun->mode_pages.format_page[
4127			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4128			       sizeof(format_page_changeable));
4129			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4130			       &format_page_default,
4131			       sizeof(format_page_default));
4132			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4133			       &format_page_default,
4134			       sizeof(format_page_default));
4135
4136			format_page = &lun->mode_pages.format_page[
4137				CTL_PAGE_CURRENT];
4138			scsi_ulto2b(lun->be_lun->blocksize,
4139				    format_page->bytes_per_sector);
4140
4141			format_page = &lun->mode_pages.format_page[
4142				CTL_PAGE_DEFAULT];
4143			scsi_ulto2b(lun->be_lun->blocksize,
4144				    format_page->bytes_per_sector);
4145
4146			format_page = &lun->mode_pages.format_page[
4147				CTL_PAGE_SAVED];
4148			scsi_ulto2b(lun->be_lun->blocksize,
4149				    format_page->bytes_per_sector);
4150
4151			page_index->page_data =
4152				(uint8_t *)lun->mode_pages.format_page;
4153			break;
4154		}
4155		case SMS_RIGID_DISK_PAGE: {
4156			struct scsi_rigid_disk_page *rigid_disk_page;
4157			uint32_t sectors_per_cylinder;
4158			uint64_t cylinders;
4159#ifndef	__XSCALE__
4160			int shift;
4161#endif /* !__XSCALE__ */
4162
4163			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4164				panic("invalid subpage value %d",
4165				      page_index->subpage);
4166
4167			/*
4168			 * Rotation rate and sectors per track are set
4169			 * above.  We calculate the cylinders here based on
4170			 * capacity.  Due to the number of heads and
4171			 * sectors per track we're using, smaller arrays
4172			 * may turn out to have 0 cylinders.  Linux and
4173			 * FreeBSD don't pay attention to these mode pages
4174			 * to figure out capacity, but Solaris does.  It
4175			 * seems to deal with 0 cylinders just fine, and
4176			 * works out a fake geometry based on the capacity.
4177			 */
4178			memcpy(&lun->mode_pages.rigid_disk_page[
4179			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4180			       sizeof(rigid_disk_page_default));
4181			memcpy(&lun->mode_pages.rigid_disk_page[
4182			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4183			       sizeof(rigid_disk_page_changeable));
4184
4185			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4186				CTL_DEFAULT_HEADS;
4187
4188			/*
4189			 * The divide method here will be more accurate,
4190			 * probably, but results in floating point being
4191			 * used in the kernel on i386 (__udivdi3()).  On the
4192			 * XScale, though, __udivdi3() is implemented in
4193			 * software.
4194			 *
4195			 * The shift method for cylinder calculation is
4196			 * accurate if sectors_per_cylinder is a power of
4197			 * 2.  Otherwise it might be slightly off -- you
4198			 * might have a bit of a truncation problem.
4199			 */
4200#ifdef	__XSCALE__
4201			cylinders = (lun->be_lun->maxlba + 1) /
4202				sectors_per_cylinder;
4203#else
4204			for (shift = 31; shift > 0; shift--) {
4205				if (sectors_per_cylinder & (1 << shift))
4206					break;
4207			}
4208			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4209#endif
4210
4211			/*
4212			 * We've basically got 3 bytes, or 24 bits for the
4213			 * cylinder size in the mode page.  If we're over,
4214			 * just round down to 2^24.
4215			 */
4216			if (cylinders > 0xffffff)
4217				cylinders = 0xffffff;
4218
4219			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4220				CTL_PAGE_DEFAULT];
4221			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4222
4223			if ((value = ctl_get_opt(&lun->be_lun->options,
4224			    "rpm")) != NULL) {
4225				scsi_ulto2b(strtol(value, NULL, 0),
4226				     rigid_disk_page->rotation_rate);
4227			}
4228
4229			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4230			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4231			       sizeof(rigid_disk_page_default));
4232			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4233			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4234			       sizeof(rigid_disk_page_default));
4235
4236			page_index->page_data =
4237				(uint8_t *)lun->mode_pages.rigid_disk_page;
4238			break;
4239		}
4240		case SMS_CACHING_PAGE: {
4241			struct scsi_caching_page *caching_page;
4242
4243			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4244				panic("invalid subpage value %d",
4245				      page_index->subpage);
4246			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4247			       &caching_page_default,
4248			       sizeof(caching_page_default));
4249			memcpy(&lun->mode_pages.caching_page[
4250			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4251			       sizeof(caching_page_changeable));
4252			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4253			       &caching_page_default,
4254			       sizeof(caching_page_default));
4255			caching_page = &lun->mode_pages.caching_page[
4256			    CTL_PAGE_SAVED];
4257			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4258			if (value != NULL && strcmp(value, "off") == 0)
4259				caching_page->flags1 &= ~SCP_WCE;
4260			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4261			if (value != NULL && strcmp(value, "off") == 0)
4262				caching_page->flags1 |= SCP_RCD;
4263			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4264			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4265			       sizeof(caching_page_default));
4266			page_index->page_data =
4267				(uint8_t *)lun->mode_pages.caching_page;
4268			break;
4269		}
4270		case SMS_CONTROL_MODE_PAGE: {
4271			struct scsi_control_page *control_page;
4272
4273			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4274				panic("invalid subpage value %d",
4275				      page_index->subpage);
4276
4277			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4278			       &control_page_default,
4279			       sizeof(control_page_default));
4280			memcpy(&lun->mode_pages.control_page[
4281			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4282			       sizeof(control_page_changeable));
4283			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4284			       &control_page_default,
4285			       sizeof(control_page_default));
4286			control_page = &lun->mode_pages.control_page[
4287			    CTL_PAGE_SAVED];
4288			value = ctl_get_opt(&lun->be_lun->options, "reordering");
4289			if (value != NULL && strcmp(value, "unrestricted") == 0) {
4290				control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4291				control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4292			}
4293			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4294			       &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4295			       sizeof(control_page_default));
4296			page_index->page_data =
4297				(uint8_t *)lun->mode_pages.control_page;
4298			break;
4299
4300		}
4301		case SMS_INFO_EXCEPTIONS_PAGE: {
4302			switch (page_index->subpage) {
4303			case SMS_SUBPAGE_PAGE_0:
4304				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4305				       &ie_page_default,
4306				       sizeof(ie_page_default));
4307				memcpy(&lun->mode_pages.ie_page[
4308				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4309				       sizeof(ie_page_changeable));
4310				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4311				       &ie_page_default,
4312				       sizeof(ie_page_default));
4313				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4314				       &ie_page_default,
4315				       sizeof(ie_page_default));
4316				page_index->page_data =
4317					(uint8_t *)lun->mode_pages.ie_page;
4318				break;
4319			case 0x02: {
4320				struct ctl_logical_block_provisioning_page *page;
4321
4322				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4323				       &lbp_page_default,
4324				       sizeof(lbp_page_default));
4325				memcpy(&lun->mode_pages.lbp_page[
4326				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4327				       sizeof(lbp_page_changeable));
4328				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4329				       &lbp_page_default,
4330				       sizeof(lbp_page_default));
4331				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4332				value = ctl_get_opt(&lun->be_lun->options,
4333				    "avail-threshold");
4334				if (value != NULL &&
4335				    ctl_expand_number(value, &ival) == 0) {
4336					page->descr[0].flags |= SLBPPD_ENABLED |
4337					    SLBPPD_ARMING_DEC;
4338					if (lun->be_lun->blocksize)
4339						ival /= lun->be_lun->blocksize;
4340					else
4341						ival /= 512;
4342					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4343					    page->descr[0].count);
4344				}
4345				value = ctl_get_opt(&lun->be_lun->options,
4346				    "used-threshold");
4347				if (value != NULL &&
4348				    ctl_expand_number(value, &ival) == 0) {
4349					page->descr[1].flags |= SLBPPD_ENABLED |
4350					    SLBPPD_ARMING_INC;
4351					if (lun->be_lun->blocksize)
4352						ival /= lun->be_lun->blocksize;
4353					else
4354						ival /= 512;
4355					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4356					    page->descr[1].count);
4357				}
4358				value = ctl_get_opt(&lun->be_lun->options,
4359				    "pool-avail-threshold");
4360				if (value != NULL &&
4361				    ctl_expand_number(value, &ival) == 0) {
4362					page->descr[2].flags |= SLBPPD_ENABLED |
4363					    SLBPPD_ARMING_DEC;
4364					if (lun->be_lun->blocksize)
4365						ival /= lun->be_lun->blocksize;
4366					else
4367						ival /= 512;
4368					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4369					    page->descr[2].count);
4370				}
4371				value = ctl_get_opt(&lun->be_lun->options,
4372				    "pool-used-threshold");
4373				if (value != NULL &&
4374				    ctl_expand_number(value, &ival) == 0) {
4375					page->descr[3].flags |= SLBPPD_ENABLED |
4376					    SLBPPD_ARMING_INC;
4377					if (lun->be_lun->blocksize)
4378						ival /= lun->be_lun->blocksize;
4379					else
4380						ival /= 512;
4381					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4382					    page->descr[3].count);
4383				}
4384				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4385				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4386				       sizeof(lbp_page_default));
4387				page_index->page_data =
4388					(uint8_t *)lun->mode_pages.lbp_page;
4389			}}
4390			break;
4391		}
4392		case SMS_VENDOR_SPECIFIC_PAGE:{
4393			switch (page_index->subpage) {
4394			case DBGCNF_SUBPAGE_CODE: {
4395				struct copan_debugconf_subpage *current_page,
4396							       *saved_page;
4397
4398				memcpy(&lun->mode_pages.debugconf_subpage[
4399				       CTL_PAGE_CURRENT],
4400				       &debugconf_page_default,
4401				       sizeof(debugconf_page_default));
4402				memcpy(&lun->mode_pages.debugconf_subpage[
4403				       CTL_PAGE_CHANGEABLE],
4404				       &debugconf_page_changeable,
4405				       sizeof(debugconf_page_changeable));
4406				memcpy(&lun->mode_pages.debugconf_subpage[
4407				       CTL_PAGE_DEFAULT],
4408				       &debugconf_page_default,
4409				       sizeof(debugconf_page_default));
4410				memcpy(&lun->mode_pages.debugconf_subpage[
4411				       CTL_PAGE_SAVED],
4412				       &debugconf_page_default,
4413				       sizeof(debugconf_page_default));
4414				page_index->page_data =
4415					(uint8_t *)lun->mode_pages.debugconf_subpage;
4416
4417				current_page = (struct copan_debugconf_subpage *)
4418					(page_index->page_data +
4419					 (page_index->page_len *
4420					  CTL_PAGE_CURRENT));
4421				saved_page = (struct copan_debugconf_subpage *)
4422					(page_index->page_data +
4423					 (page_index->page_len *
4424					  CTL_PAGE_SAVED));
4425				break;
4426			}
4427			default:
4428				panic("invalid subpage value %d",
4429				      page_index->subpage);
4430				break;
4431			}
4432   			break;
4433		}
4434		default:
4435			panic("invalid page value %d",
4436			      page_index->page_code & SMPH_PC_MASK);
4437			break;
4438    	}
4439	}
4440
4441	return (CTL_RETVAL_COMPLETE);
4442}
4443
4444static int
4445ctl_init_log_page_index(struct ctl_lun *lun)
4446{
4447	struct ctl_page_index *page_index;
4448	int i, j, k, prev;
4449
4450	memcpy(&lun->log_pages.index, log_page_index_template,
4451	       sizeof(log_page_index_template));
4452
4453	prev = -1;
4454	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4455
4456		page_index = &lun->log_pages.index[i];
4457		/*
4458		 * If this is a disk-only mode page, there's no point in
4459		 * setting it up.  For some pages, we have to have some
4460		 * basic information about the disk in order to calculate the
4461		 * mode page data.
4462		 */
4463		if ((lun->be_lun->lun_type != T_DIRECT)
4464		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4465			continue;
4466
4467		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4468		     lun->backend->lun_attr == NULL)
4469			continue;
4470
4471		if (page_index->page_code != prev) {
4472			lun->log_pages.pages_page[j] = page_index->page_code;
4473			prev = page_index->page_code;
4474			j++;
4475		}
4476		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4477		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4478		k++;
4479	}
4480	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4481	lun->log_pages.index[0].page_len = j;
4482	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4483	lun->log_pages.index[1].page_len = k * 2;
4484	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4485	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4486	lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4487	lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4488
4489	return (CTL_RETVAL_COMPLETE);
4490}
4491
4492static int
4493hex2bin(const char *str, uint8_t *buf, int buf_size)
4494{
4495	int i;
4496	u_char c;
4497
4498	memset(buf, 0, buf_size);
4499	while (isspace(str[0]))
4500		str++;
4501	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4502		str += 2;
4503	buf_size *= 2;
4504	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4505		c = str[i];
4506		if (isdigit(c))
4507			c -= '0';
4508		else if (isalpha(c))
4509			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4510		else
4511			break;
4512		if (c >= 16)
4513			break;
4514		if ((i & 1) == 0)
4515			buf[i / 2] |= (c << 4);
4516		else
4517			buf[i / 2] |= c;
4518	}
4519	return ((i + 1) / 2);
4520}
4521
4522/*
4523 * LUN allocation.
4524 *
4525 * Requirements:
4526 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4527 *   wants us to allocate the LUN and he can block.
4528 * - ctl_softc is always set
4529 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4530 *
4531 * Returns 0 for success, non-zero (errno) for failure.
4532 */
4533static int
4534ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4535	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4536{
4537	struct ctl_lun *nlun, *lun;
4538	struct ctl_port *port;
4539	struct scsi_vpd_id_descriptor *desc;
4540	struct scsi_vpd_id_t10 *t10id;
4541	const char *eui, *naa, *scsiname, *vendor, *value;
4542	int lun_number, i, lun_malloced;
4543	int devidlen, idlen1, idlen2 = 0, len;
4544
4545	if (be_lun == NULL)
4546		return (EINVAL);
4547
4548	/*
4549	 * We currently only support Direct Access or Processor LUN types.
4550	 */
4551	switch (be_lun->lun_type) {
4552	case T_DIRECT:
4553		break;
4554	case T_PROCESSOR:
4555		break;
4556	case T_SEQUENTIAL:
4557	case T_CHANGER:
4558	default:
4559		be_lun->lun_config_status(be_lun->be_lun,
4560					  CTL_LUN_CONFIG_FAILURE);
4561		break;
4562	}
4563	if (ctl_lun == NULL) {
4564		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4565		lun_malloced = 1;
4566	} else {
4567		lun_malloced = 0;
4568		lun = ctl_lun;
4569	}
4570
4571	memset(lun, 0, sizeof(*lun));
4572	if (lun_malloced)
4573		lun->flags = CTL_LUN_MALLOCED;
4574
4575	/* Generate LUN ID. */
4576	devidlen = max(CTL_DEVID_MIN_LEN,
4577	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4578	idlen1 = sizeof(*t10id) + devidlen;
4579	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4580	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4581	if (scsiname != NULL) {
4582		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4583		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4584	}
4585	eui = ctl_get_opt(&be_lun->options, "eui");
4586	if (eui != NULL) {
4587		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4588	}
4589	naa = ctl_get_opt(&be_lun->options, "naa");
4590	if (naa != NULL) {
4591		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4592	}
4593	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4594	    M_CTL, M_WAITOK | M_ZERO);
4595	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4596	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4597	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4598	desc->length = idlen1;
4599	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4600	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4601	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4602		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4603	} else {
4604		strncpy(t10id->vendor, vendor,
4605		    min(sizeof(t10id->vendor), strlen(vendor)));
4606	}
4607	strncpy((char *)t10id->vendor_spec_id,
4608	    (char *)be_lun->device_id, devidlen);
4609	if (scsiname != NULL) {
4610		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4611		    desc->length);
4612		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4613		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4614		    SVPD_ID_TYPE_SCSI_NAME;
4615		desc->length = idlen2;
4616		strlcpy(desc->identifier, scsiname, idlen2);
4617	}
4618	if (eui != NULL) {
4619		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4620		    desc->length);
4621		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4622		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4623		    SVPD_ID_TYPE_EUI64;
4624		desc->length = hex2bin(eui, desc->identifier, 16);
4625		desc->length = desc->length > 12 ? 16 :
4626		    (desc->length > 8 ? 12 : 8);
4627		len -= 16 - desc->length;
4628	}
4629	if (naa != NULL) {
4630		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4631		    desc->length);
4632		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4633		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4634		    SVPD_ID_TYPE_NAA;
4635		desc->length = hex2bin(naa, desc->identifier, 16);
4636		desc->length = desc->length > 8 ? 16 : 8;
4637		len -= 16 - desc->length;
4638	}
4639	lun->lun_devid->len = len;
4640
4641	mtx_lock(&ctl_softc->ctl_lock);
4642	/*
4643	 * See if the caller requested a particular LUN number.  If so, see
4644	 * if it is available.  Otherwise, allocate the first available LUN.
4645	 */
4646	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4647		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4648		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4649			mtx_unlock(&ctl_softc->ctl_lock);
4650			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4651				printf("ctl: requested LUN ID %d is higher "
4652				       "than CTL_MAX_LUNS - 1 (%d)\n",
4653				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4654			} else {
4655				/*
4656				 * XXX KDM return an error, or just assign
4657				 * another LUN ID in this case??
4658				 */
4659				printf("ctl: requested LUN ID %d is already "
4660				       "in use\n", be_lun->req_lun_id);
4661			}
4662			if (lun->flags & CTL_LUN_MALLOCED)
4663				free(lun, M_CTL);
4664			be_lun->lun_config_status(be_lun->be_lun,
4665						  CTL_LUN_CONFIG_FAILURE);
4666			return (ENOSPC);
4667		}
4668		lun_number = be_lun->req_lun_id;
4669	} else {
4670		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4671		if (lun_number == -1) {
4672			mtx_unlock(&ctl_softc->ctl_lock);
4673			printf("ctl: can't allocate LUN on target %ju, out of "
4674			       "LUNs\n", (uintmax_t)target_id.id);
4675			if (lun->flags & CTL_LUN_MALLOCED)
4676				free(lun, M_CTL);
4677			be_lun->lun_config_status(be_lun->be_lun,
4678						  CTL_LUN_CONFIG_FAILURE);
4679			return (ENOSPC);
4680		}
4681	}
4682	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4683
4684	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4685	lun->target = target_id;
4686	lun->lun = lun_number;
4687	lun->be_lun = be_lun;
4688	/*
4689	 * The processor LUN is always enabled.  Disk LUNs come on line
4690	 * disabled, and must be enabled by the backend.
4691	 */
4692	lun->flags |= CTL_LUN_DISABLED;
4693	lun->backend = be_lun->be;
4694	be_lun->ctl_lun = lun;
4695	be_lun->lun_id = lun_number;
4696	atomic_add_int(&be_lun->be->num_luns, 1);
4697	if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4698		lun->flags |= CTL_LUN_OFFLINE;
4699
4700	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4701		lun->flags |= CTL_LUN_STOPPED;
4702
4703	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4704		lun->flags |= CTL_LUN_INOPERABLE;
4705
4706	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4707		lun->flags |= CTL_LUN_PRIMARY_SC;
4708
4709	value = ctl_get_opt(&be_lun->options, "readonly");
4710	if (value != NULL && strcmp(value, "on") == 0)
4711		lun->flags |= CTL_LUN_READONLY;
4712
4713	lun->serseq = CTL_LUN_SERSEQ_OFF;
4714	if (be_lun->flags & CTL_LUN_FLAG_SERSEQ_READ)
4715		lun->serseq = CTL_LUN_SERSEQ_READ;
4716	value = ctl_get_opt(&be_lun->options, "serseq");
4717	if (value != NULL && strcmp(value, "on") == 0)
4718		lun->serseq = CTL_LUN_SERSEQ_ON;
4719	else if (value != NULL && strcmp(value, "read") == 0)
4720		lun->serseq = CTL_LUN_SERSEQ_READ;
4721	else if (value != NULL && strcmp(value, "off") == 0)
4722		lun->serseq = CTL_LUN_SERSEQ_OFF;
4723
4724	lun->ctl_softc = ctl_softc;
4725#ifdef CTL_TIME_IO
4726	lun->last_busy = getsbinuptime();
4727#endif
4728	TAILQ_INIT(&lun->ooa_queue);
4729	TAILQ_INIT(&lun->blocked_queue);
4730	STAILQ_INIT(&lun->error_list);
4731	ctl_tpc_lun_init(lun);
4732
4733	/*
4734	 * Initialize the mode and log page index.
4735	 */
4736	ctl_init_page_index(lun);
4737	ctl_init_log_page_index(lun);
4738
4739	/*
4740	 * Now, before we insert this lun on the lun list, set the lun
4741	 * inventory changed UA for all other luns.
4742	 */
4743	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4744		mtx_lock(&nlun->lun_lock);
4745		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4746		mtx_unlock(&nlun->lun_lock);
4747	}
4748
4749	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4750
4751	ctl_softc->ctl_luns[lun_number] = lun;
4752
4753	ctl_softc->num_luns++;
4754
4755	/* Setup statistics gathering */
4756	lun->stats.device_type = be_lun->lun_type;
4757	lun->stats.lun_number = lun_number;
4758	if (lun->stats.device_type == T_DIRECT)
4759		lun->stats.blocksize = be_lun->blocksize;
4760	else
4761		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4762	for (i = 0;i < CTL_MAX_PORTS;i++)
4763		lun->stats.ports[i].targ_port = i;
4764
4765	mtx_unlock(&ctl_softc->ctl_lock);
4766
4767	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4768
4769	/*
4770	 * Run through each registered FETD and bring it online if it isn't
4771	 * already.  Enable the target ID if it hasn't been enabled, and
4772	 * enable this particular LUN.
4773	 */
4774	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4775		int retval;
4776
4777		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4778		if (retval != 0) {
4779			printf("ctl_alloc_lun: FETD %s port %d returned error "
4780			       "%d for lun_enable on target %ju lun %d\n",
4781			       port->port_name, port->targ_port, retval,
4782			       (uintmax_t)target_id.id, lun_number);
4783		} else
4784			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4785	}
4786	return (0);
4787}
4788
4789/*
4790 * Delete a LUN.
4791 * Assumptions:
4792 * - LUN has already been marked invalid and any pending I/O has been taken
4793 *   care of.
4794 */
4795static int
4796ctl_free_lun(struct ctl_lun *lun)
4797{
4798	struct ctl_softc *softc;
4799	struct ctl_port *port;
4800	struct ctl_lun *nlun;
4801	int i;
4802
4803	softc = lun->ctl_softc;
4804
4805	mtx_assert(&softc->ctl_lock, MA_OWNED);
4806
4807	STAILQ_FOREACH(port, &softc->port_list, links)
4808		ctl_lun_map_unsetg(port, lun->lun);
4809
4810	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4811
4812	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4813
4814	softc->ctl_luns[lun->lun] = NULL;
4815
4816	if (!TAILQ_EMPTY(&lun->ooa_queue))
4817		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4818
4819	softc->num_luns--;
4820
4821	/*
4822	 * XXX KDM this scheme only works for a single target/multiple LUN
4823	 * setup.  It needs to be revamped for a multiple target scheme.
4824	 *
4825	 * XXX KDM this results in port->lun_disable() getting called twice,
4826	 * once when ctl_disable_lun() is called, and a second time here.
4827	 * We really need to re-think the LUN disable semantics.  There
4828	 * should probably be several steps/levels to LUN removal:
4829	 *  - disable
4830	 *  - invalidate
4831	 *  - free
4832 	 *
4833	 * Right now we only have a disable method when communicating to
4834	 * the front end ports, at least for individual LUNs.
4835	 */
4836#if 0
4837	STAILQ_FOREACH(port, &softc->port_list, links) {
4838		int retval;
4839
4840		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4841					 lun->lun);
4842		if (retval != 0) {
4843			printf("ctl_free_lun: FETD %s port %d returned error "
4844			       "%d for lun_disable on target %ju lun %jd\n",
4845			       port->port_name, port->targ_port, retval,
4846			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4847		}
4848
4849		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4850			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4851
4852			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4853			if (retval != 0) {
4854				printf("ctl_free_lun: FETD %s port %d "
4855				       "returned error %d for targ_disable on "
4856				       "target %ju\n", port->port_name,
4857				       port->targ_port, retval,
4858				       (uintmax_t)lun->target.id);
4859			} else
4860				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4861
4862			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4863				continue;
4864
4865#if 0
4866			port->port_offline(port->onoff_arg);
4867			port->status &= ~CTL_PORT_STATUS_ONLINE;
4868#endif
4869		}
4870	}
4871#endif
4872
4873	/*
4874	 * Tell the backend to free resources, if this LUN has a backend.
4875	 */
4876	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4877	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4878
4879	ctl_tpc_lun_shutdown(lun);
4880	mtx_destroy(&lun->lun_lock);
4881	free(lun->lun_devid, M_CTL);
4882	for (i = 0; i < CTL_MAX_PORTS; i++)
4883		free(lun->pending_ua[i], M_CTL);
4884	for (i = 0; i < 2 * CTL_MAX_PORTS; i++)
4885		free(lun->pr_keys[i], M_CTL);
4886	free(lun->write_buffer, M_CTL);
4887	if (lun->flags & CTL_LUN_MALLOCED)
4888		free(lun, M_CTL);
4889
4890	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4891		mtx_lock(&nlun->lun_lock);
4892		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4893		mtx_unlock(&nlun->lun_lock);
4894	}
4895
4896	return (0);
4897}
4898
4899static void
4900ctl_create_lun(struct ctl_be_lun *be_lun)
4901{
4902	struct ctl_softc *softc;
4903
4904	softc = control_softc;
4905
4906	/*
4907	 * ctl_alloc_lun() should handle all potential failure cases.
4908	 */
4909	ctl_alloc_lun(softc, NULL, be_lun, softc->target);
4910}
4911
4912int
4913ctl_add_lun(struct ctl_be_lun *be_lun)
4914{
4915	struct ctl_softc *softc = control_softc;
4916
4917	mtx_lock(&softc->ctl_lock);
4918	STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4919	mtx_unlock(&softc->ctl_lock);
4920	wakeup(&softc->pending_lun_queue);
4921
4922	return (0);
4923}
4924
4925int
4926ctl_enable_lun(struct ctl_be_lun *be_lun)
4927{
4928	struct ctl_softc *softc;
4929	struct ctl_port *port, *nport;
4930	struct ctl_lun *lun;
4931	int retval;
4932
4933	lun = (struct ctl_lun *)be_lun->ctl_lun;
4934	softc = lun->ctl_softc;
4935
4936	mtx_lock(&softc->ctl_lock);
4937	mtx_lock(&lun->lun_lock);
4938	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4939		/*
4940		 * eh?  Why did we get called if the LUN is already
4941		 * enabled?
4942		 */
4943		mtx_unlock(&lun->lun_lock);
4944		mtx_unlock(&softc->ctl_lock);
4945		return (0);
4946	}
4947	lun->flags &= ~CTL_LUN_DISABLED;
4948	mtx_unlock(&lun->lun_lock);
4949
4950	for (port = STAILQ_FIRST(&softc->port_list); port != NULL; port = nport) {
4951		nport = STAILQ_NEXT(port, links);
4952
4953		/*
4954		 * Drop the lock while we call the FETD's enable routine.
4955		 * This can lead to a callback into CTL (at least in the
4956		 * case of the internal initiator frontend.
4957		 */
4958		mtx_unlock(&softc->ctl_lock);
4959		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4960		mtx_lock(&softc->ctl_lock);
4961		if (retval != 0) {
4962			printf("%s: FETD %s port %d returned error "
4963			       "%d for lun_enable on target %ju lun %jd\n",
4964			       __func__, port->port_name, port->targ_port, retval,
4965			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4966		}
4967#if 0
4968		 else {
4969            /* NOTE:  TODO:  why does lun enable affect port status? */
4970			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4971		}
4972#endif
4973	}
4974
4975	mtx_unlock(&softc->ctl_lock);
4976
4977	return (0);
4978}
4979
4980int
4981ctl_disable_lun(struct ctl_be_lun *be_lun)
4982{
4983	struct ctl_softc *softc;
4984	struct ctl_port *port;
4985	struct ctl_lun *lun;
4986	int retval;
4987
4988	lun = (struct ctl_lun *)be_lun->ctl_lun;
4989	softc = lun->ctl_softc;
4990
4991	mtx_lock(&softc->ctl_lock);
4992	mtx_lock(&lun->lun_lock);
4993	if (lun->flags & CTL_LUN_DISABLED) {
4994		mtx_unlock(&lun->lun_lock);
4995		mtx_unlock(&softc->ctl_lock);
4996		return (0);
4997	}
4998	lun->flags |= CTL_LUN_DISABLED;
4999	mtx_unlock(&lun->lun_lock);
5000
5001	STAILQ_FOREACH(port, &softc->port_list, links) {
5002		mtx_unlock(&softc->ctl_lock);
5003		/*
5004		 * Drop the lock before we call the frontend's disable
5005		 * routine, to avoid lock order reversals.
5006		 *
5007		 * XXX KDM what happens if the frontend list changes while
5008		 * we're traversing it?  It's unlikely, but should be handled.
5009		 */
5010		retval = port->lun_disable(port->targ_lun_arg, lun->target,
5011					 lun->lun);
5012		mtx_lock(&softc->ctl_lock);
5013		if (retval != 0) {
5014			printf("ctl_alloc_lun: FETD %s port %d returned error "
5015			       "%d for lun_disable on target %ju lun %jd\n",
5016			       port->port_name, port->targ_port, retval,
5017			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
5018		}
5019	}
5020
5021	mtx_unlock(&softc->ctl_lock);
5022
5023	return (0);
5024}
5025
5026int
5027ctl_start_lun(struct ctl_be_lun *be_lun)
5028{
5029	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5030
5031	mtx_lock(&lun->lun_lock);
5032	lun->flags &= ~CTL_LUN_STOPPED;
5033	mtx_unlock(&lun->lun_lock);
5034	return (0);
5035}
5036
5037int
5038ctl_stop_lun(struct ctl_be_lun *be_lun)
5039{
5040	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5041
5042	mtx_lock(&lun->lun_lock);
5043	lun->flags |= CTL_LUN_STOPPED;
5044	mtx_unlock(&lun->lun_lock);
5045	return (0);
5046}
5047
5048int
5049ctl_lun_offline(struct ctl_be_lun *be_lun)
5050{
5051	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5052
5053	mtx_lock(&lun->lun_lock);
5054	lun->flags |= CTL_LUN_OFFLINE;
5055	mtx_unlock(&lun->lun_lock);
5056	return (0);
5057}
5058
5059int
5060ctl_lun_online(struct ctl_be_lun *be_lun)
5061{
5062	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5063
5064	mtx_lock(&lun->lun_lock);
5065	lun->flags &= ~CTL_LUN_OFFLINE;
5066	mtx_unlock(&lun->lun_lock);
5067	return (0);
5068}
5069
5070int
5071ctl_invalidate_lun(struct ctl_be_lun *be_lun)
5072{
5073	struct ctl_softc *softc;
5074	struct ctl_lun *lun;
5075
5076	lun = (struct ctl_lun *)be_lun->ctl_lun;
5077	softc = lun->ctl_softc;
5078
5079	mtx_lock(&lun->lun_lock);
5080
5081	/*
5082	 * The LUN needs to be disabled before it can be marked invalid.
5083	 */
5084	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
5085		mtx_unlock(&lun->lun_lock);
5086		return (-1);
5087	}
5088	/*
5089	 * Mark the LUN invalid.
5090	 */
5091	lun->flags |= CTL_LUN_INVALID;
5092
5093	/*
5094	 * If there is nothing in the OOA queue, go ahead and free the LUN.
5095	 * If we have something in the OOA queue, we'll free it when the
5096	 * last I/O completes.
5097	 */
5098	if (TAILQ_EMPTY(&lun->ooa_queue)) {
5099		mtx_unlock(&lun->lun_lock);
5100		mtx_lock(&softc->ctl_lock);
5101		ctl_free_lun(lun);
5102		mtx_unlock(&softc->ctl_lock);
5103	} else
5104		mtx_unlock(&lun->lun_lock);
5105
5106	return (0);
5107}
5108
5109int
5110ctl_lun_inoperable(struct ctl_be_lun *be_lun)
5111{
5112	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5113
5114	mtx_lock(&lun->lun_lock);
5115	lun->flags |= CTL_LUN_INOPERABLE;
5116	mtx_unlock(&lun->lun_lock);
5117	return (0);
5118}
5119
5120int
5121ctl_lun_operable(struct ctl_be_lun *be_lun)
5122{
5123	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5124
5125	mtx_lock(&lun->lun_lock);
5126	lun->flags &= ~CTL_LUN_INOPERABLE;
5127	mtx_unlock(&lun->lun_lock);
5128	return (0);
5129}
5130
5131void
5132ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5133{
5134	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5135
5136	mtx_lock(&lun->lun_lock);
5137	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGED);
5138	mtx_unlock(&lun->lun_lock);
5139}
5140
5141/*
5142 * Backend "memory move is complete" callback for requests that never
5143 * make it down to say RAIDCore's configuration code.
5144 */
5145int
5146ctl_config_move_done(union ctl_io *io)
5147{
5148	int retval;
5149
5150	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5151	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5152	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5153
5154	if ((io->io_hdr.port_status != 0) &&
5155	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5156	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5157		/*
5158		 * For hardware error sense keys, the sense key
5159		 * specific value is defined to be a retry count,
5160		 * but we use it to pass back an internal FETD
5161		 * error code.  XXX KDM  Hopefully the FETD is only
5162		 * using 16 bits for an error code, since that's
5163		 * all the space we have in the sks field.
5164		 */
5165		ctl_set_internal_failure(&io->scsiio,
5166					 /*sks_valid*/ 1,
5167					 /*retry_count*/
5168					 io->io_hdr.port_status);
5169	}
5170
5171	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5172	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5173	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5174	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5175		/*
5176		 * XXX KDM just assuming a single pointer here, and not a
5177		 * S/G list.  If we start using S/G lists for config data,
5178		 * we'll need to know how to clean them up here as well.
5179		 */
5180		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5181			free(io->scsiio.kern_data_ptr, M_CTL);
5182		ctl_done(io);
5183		retval = CTL_RETVAL_COMPLETE;
5184	} else {
5185		/*
5186		 * XXX KDM now we need to continue data movement.  Some
5187		 * options:
5188		 * - call ctl_scsiio() again?  We don't do this for data
5189		 *   writes, because for those at least we know ahead of
5190		 *   time where the write will go and how long it is.  For
5191		 *   config writes, though, that information is largely
5192		 *   contained within the write itself, thus we need to
5193		 *   parse out the data again.
5194		 *
5195		 * - Call some other function once the data is in?
5196		 */
5197		if (ctl_debug & CTL_DEBUG_CDB_DATA)
5198			ctl_data_print(io);
5199
5200		/*
5201		 * XXX KDM call ctl_scsiio() again for now, and check flag
5202		 * bits to see whether we're allocated or not.
5203		 */
5204		retval = ctl_scsiio(&io->scsiio);
5205	}
5206	return (retval);
5207}
5208
5209/*
5210 * This gets called by a backend driver when it is done with a
5211 * data_submit method.
5212 */
5213void
5214ctl_data_submit_done(union ctl_io *io)
5215{
5216	/*
5217	 * If the IO_CONT flag is set, we need to call the supplied
5218	 * function to continue processing the I/O, instead of completing
5219	 * the I/O just yet.
5220	 *
5221	 * If there is an error, though, we don't want to keep processing.
5222	 * Instead, just send status back to the initiator.
5223	 */
5224	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5225	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5226	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5227	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5228		io->scsiio.io_cont(io);
5229		return;
5230	}
5231	ctl_done(io);
5232}
5233
5234/*
5235 * This gets called by a backend driver when it is done with a
5236 * configuration write.
5237 */
5238void
5239ctl_config_write_done(union ctl_io *io)
5240{
5241	uint8_t *buf;
5242
5243	/*
5244	 * If the IO_CONT flag is set, we need to call the supplied
5245	 * function to continue processing the I/O, instead of completing
5246	 * the I/O just yet.
5247	 *
5248	 * If there is an error, though, we don't want to keep processing.
5249	 * Instead, just send status back to the initiator.
5250	 */
5251	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5252	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5253	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5254	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5255		io->scsiio.io_cont(io);
5256		return;
5257	}
5258	/*
5259	 * Since a configuration write can be done for commands that actually
5260	 * have data allocated, like write buffer, and commands that have
5261	 * no data, like start/stop unit, we need to check here.
5262	 */
5263	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5264		buf = io->scsiio.kern_data_ptr;
5265	else
5266		buf = NULL;
5267	ctl_done(io);
5268	if (buf)
5269		free(buf, M_CTL);
5270}
5271
5272void
5273ctl_config_read_done(union ctl_io *io)
5274{
5275	uint8_t *buf;
5276
5277	/*
5278	 * If there is some error -- we are done, skip data transfer.
5279	 */
5280	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5281	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5282	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5283		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5284			buf = io->scsiio.kern_data_ptr;
5285		else
5286			buf = NULL;
5287		ctl_done(io);
5288		if (buf)
5289			free(buf, M_CTL);
5290		return;
5291	}
5292
5293	/*
5294	 * If the IO_CONT flag is set, we need to call the supplied
5295	 * function to continue processing the I/O, instead of completing
5296	 * the I/O just yet.
5297	 */
5298	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5299		io->scsiio.io_cont(io);
5300		return;
5301	}
5302
5303	ctl_datamove(io);
5304}
5305
5306/*
5307 * SCSI release command.
5308 */
5309int
5310ctl_scsi_release(struct ctl_scsiio *ctsio)
5311{
5312	int length, longid, thirdparty_id, resv_id;
5313	struct ctl_lun *lun;
5314	uint32_t residx;
5315
5316	length = 0;
5317	resv_id = 0;
5318
5319	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5320
5321	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5322	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5323
5324	switch (ctsio->cdb[0]) {
5325	case RELEASE_10: {
5326		struct scsi_release_10 *cdb;
5327
5328		cdb = (struct scsi_release_10 *)ctsio->cdb;
5329
5330		if (cdb->byte2 & SR10_LONGID)
5331			longid = 1;
5332		else
5333			thirdparty_id = cdb->thirdparty_id;
5334
5335		resv_id = cdb->resv_id;
5336		length = scsi_2btoul(cdb->length);
5337		break;
5338	}
5339	}
5340
5341
5342	/*
5343	 * XXX KDM right now, we only support LUN reservation.  We don't
5344	 * support 3rd party reservations, or extent reservations, which
5345	 * might actually need the parameter list.  If we've gotten this
5346	 * far, we've got a LUN reservation.  Anything else got kicked out
5347	 * above.  So, according to SPC, ignore the length.
5348	 */
5349	length = 0;
5350
5351	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5352	 && (length > 0)) {
5353		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5354		ctsio->kern_data_len = length;
5355		ctsio->kern_total_len = length;
5356		ctsio->kern_data_resid = 0;
5357		ctsio->kern_rel_offset = 0;
5358		ctsio->kern_sg_entries = 0;
5359		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5360		ctsio->be_move_done = ctl_config_move_done;
5361		ctl_datamove((union ctl_io *)ctsio);
5362
5363		return (CTL_RETVAL_COMPLETE);
5364	}
5365
5366	if (length > 0)
5367		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5368
5369	mtx_lock(&lun->lun_lock);
5370
5371	/*
5372	 * According to SPC, it is not an error for an intiator to attempt
5373	 * to release a reservation on a LUN that isn't reserved, or that
5374	 * is reserved by another initiator.  The reservation can only be
5375	 * released, though, by the initiator who made it or by one of
5376	 * several reset type events.
5377	 */
5378	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5379			lun->flags &= ~CTL_LUN_RESERVED;
5380
5381	mtx_unlock(&lun->lun_lock);
5382
5383	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5384		free(ctsio->kern_data_ptr, M_CTL);
5385		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5386	}
5387
5388	ctl_set_success(ctsio);
5389	ctl_done((union ctl_io *)ctsio);
5390	return (CTL_RETVAL_COMPLETE);
5391}
5392
5393int
5394ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5395{
5396	int extent, thirdparty, longid;
5397	int resv_id, length;
5398	uint64_t thirdparty_id;
5399	struct ctl_lun *lun;
5400	uint32_t residx;
5401
5402	extent = 0;
5403	thirdparty = 0;
5404	longid = 0;
5405	resv_id = 0;
5406	length = 0;
5407	thirdparty_id = 0;
5408
5409	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5410
5411	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5412	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5413
5414	switch (ctsio->cdb[0]) {
5415	case RESERVE_10: {
5416		struct scsi_reserve_10 *cdb;
5417
5418		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5419
5420		if (cdb->byte2 & SR10_LONGID)
5421			longid = 1;
5422		else
5423			thirdparty_id = cdb->thirdparty_id;
5424
5425		resv_id = cdb->resv_id;
5426		length = scsi_2btoul(cdb->length);
5427		break;
5428	}
5429	}
5430
5431	/*
5432	 * XXX KDM right now, we only support LUN reservation.  We don't
5433	 * support 3rd party reservations, or extent reservations, which
5434	 * might actually need the parameter list.  If we've gotten this
5435	 * far, we've got a LUN reservation.  Anything else got kicked out
5436	 * above.  So, according to SPC, ignore the length.
5437	 */
5438	length = 0;
5439
5440	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5441	 && (length > 0)) {
5442		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5443		ctsio->kern_data_len = length;
5444		ctsio->kern_total_len = length;
5445		ctsio->kern_data_resid = 0;
5446		ctsio->kern_rel_offset = 0;
5447		ctsio->kern_sg_entries = 0;
5448		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5449		ctsio->be_move_done = ctl_config_move_done;
5450		ctl_datamove((union ctl_io *)ctsio);
5451
5452		return (CTL_RETVAL_COMPLETE);
5453	}
5454
5455	if (length > 0)
5456		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5457
5458	mtx_lock(&lun->lun_lock);
5459	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5460		ctl_set_reservation_conflict(ctsio);
5461		goto bailout;
5462	}
5463
5464	lun->flags |= CTL_LUN_RESERVED;
5465	lun->res_idx = residx;
5466
5467	ctl_set_success(ctsio);
5468
5469bailout:
5470	mtx_unlock(&lun->lun_lock);
5471
5472	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5473		free(ctsio->kern_data_ptr, M_CTL);
5474		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5475	}
5476
5477	ctl_done((union ctl_io *)ctsio);
5478	return (CTL_RETVAL_COMPLETE);
5479}
5480
5481int
5482ctl_start_stop(struct ctl_scsiio *ctsio)
5483{
5484	struct scsi_start_stop_unit *cdb;
5485	struct ctl_lun *lun;
5486	int retval;
5487
5488	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5489
5490	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5491	retval = 0;
5492
5493	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5494
5495	/*
5496	 * XXX KDM
5497	 * We don't support the immediate bit on a stop unit.  In order to
5498	 * do that, we would need to code up a way to know that a stop is
5499	 * pending, and hold off any new commands until it completes, one
5500	 * way or another.  Then we could accept or reject those commands
5501	 * depending on its status.  We would almost need to do the reverse
5502	 * of what we do below for an immediate start -- return the copy of
5503	 * the ctl_io to the FETD with status to send to the host (and to
5504	 * free the copy!) and then free the original I/O once the stop
5505	 * actually completes.  That way, the OOA queue mechanism can work
5506	 * to block commands that shouldn't proceed.  Another alternative
5507	 * would be to put the copy in the queue in place of the original,
5508	 * and return the original back to the caller.  That could be
5509	 * slightly safer..
5510	 */
5511	if ((cdb->byte2 & SSS_IMMED)
5512	 && ((cdb->how & SSS_START) == 0)) {
5513		ctl_set_invalid_field(ctsio,
5514				      /*sks_valid*/ 1,
5515				      /*command*/ 1,
5516				      /*field*/ 1,
5517				      /*bit_valid*/ 1,
5518				      /*bit*/ 0);
5519		ctl_done((union ctl_io *)ctsio);
5520		return (CTL_RETVAL_COMPLETE);
5521	}
5522
5523	if ((lun->flags & CTL_LUN_PR_RESERVED)
5524	 && ((cdb->how & SSS_START)==0)) {
5525		uint32_t residx;
5526
5527		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5528		if (ctl_get_prkey(lun, residx) == 0
5529		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5530
5531			ctl_set_reservation_conflict(ctsio);
5532			ctl_done((union ctl_io *)ctsio);
5533			return (CTL_RETVAL_COMPLETE);
5534		}
5535	}
5536
5537	/*
5538	 * If there is no backend on this device, we can't start or stop
5539	 * it.  In theory we shouldn't get any start/stop commands in the
5540	 * first place at this level if the LUN doesn't have a backend.
5541	 * That should get stopped by the command decode code.
5542	 */
5543	if (lun->backend == NULL) {
5544		ctl_set_invalid_opcode(ctsio);
5545		ctl_done((union ctl_io *)ctsio);
5546		return (CTL_RETVAL_COMPLETE);
5547	}
5548
5549	/*
5550	 * XXX KDM Copan-specific offline behavior.
5551	 * Figure out a reasonable way to port this?
5552	 */
5553#ifdef NEEDTOPORT
5554	mtx_lock(&lun->lun_lock);
5555
5556	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5557	 && (lun->flags & CTL_LUN_OFFLINE)) {
5558		/*
5559		 * If the LUN is offline, and the on/offline bit isn't set,
5560		 * reject the start or stop.  Otherwise, let it through.
5561		 */
5562		mtx_unlock(&lun->lun_lock);
5563		ctl_set_lun_not_ready(ctsio);
5564		ctl_done((union ctl_io *)ctsio);
5565	} else {
5566		mtx_unlock(&lun->lun_lock);
5567#endif /* NEEDTOPORT */
5568		/*
5569		 * This could be a start or a stop when we're online,
5570		 * or a stop/offline or start/online.  A start or stop when
5571		 * we're offline is covered in the case above.
5572		 */
5573		/*
5574		 * In the non-immediate case, we send the request to
5575		 * the backend and return status to the user when
5576		 * it is done.
5577		 *
5578		 * In the immediate case, we allocate a new ctl_io
5579		 * to hold a copy of the request, and send that to
5580		 * the backend.  We then set good status on the
5581		 * user's request and return it immediately.
5582		 */
5583		if (cdb->byte2 & SSS_IMMED) {
5584			union ctl_io *new_io;
5585
5586			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5587			ctl_copy_io((union ctl_io *)ctsio, new_io);
5588			retval = lun->backend->config_write(new_io);
5589			ctl_set_success(ctsio);
5590			ctl_done((union ctl_io *)ctsio);
5591		} else {
5592			retval = lun->backend->config_write(
5593				(union ctl_io *)ctsio);
5594		}
5595#ifdef NEEDTOPORT
5596	}
5597#endif
5598	return (retval);
5599}
5600
5601/*
5602 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5603 * we don't really do anything with the LBA and length fields if the user
5604 * passes them in.  Instead we'll just flush out the cache for the entire
5605 * LUN.
5606 */
5607int
5608ctl_sync_cache(struct ctl_scsiio *ctsio)
5609{
5610	struct ctl_lun *lun;
5611	struct ctl_softc *softc;
5612	uint64_t starting_lba;
5613	uint32_t block_count;
5614	int retval;
5615
5616	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5617
5618	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5619	softc = lun->ctl_softc;
5620	retval = 0;
5621
5622	switch (ctsio->cdb[0]) {
5623	case SYNCHRONIZE_CACHE: {
5624		struct scsi_sync_cache *cdb;
5625		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5626
5627		starting_lba = scsi_4btoul(cdb->begin_lba);
5628		block_count = scsi_2btoul(cdb->lb_count);
5629		break;
5630	}
5631	case SYNCHRONIZE_CACHE_16: {
5632		struct scsi_sync_cache_16 *cdb;
5633		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5634
5635		starting_lba = scsi_8btou64(cdb->begin_lba);
5636		block_count = scsi_4btoul(cdb->lb_count);
5637		break;
5638	}
5639	default:
5640		ctl_set_invalid_opcode(ctsio);
5641		ctl_done((union ctl_io *)ctsio);
5642		goto bailout;
5643		break; /* NOTREACHED */
5644	}
5645
5646	/*
5647	 * We check the LBA and length, but don't do anything with them.
5648	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5649	 * get flushed.  This check will just help satisfy anyone who wants
5650	 * to see an error for an out of range LBA.
5651	 */
5652	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5653		ctl_set_lba_out_of_range(ctsio);
5654		ctl_done((union ctl_io *)ctsio);
5655		goto bailout;
5656	}
5657
5658	/*
5659	 * If this LUN has no backend, we can't flush the cache anyway.
5660	 */
5661	if (lun->backend == NULL) {
5662		ctl_set_invalid_opcode(ctsio);
5663		ctl_done((union ctl_io *)ctsio);
5664		goto bailout;
5665	}
5666
5667	/*
5668	 * Check to see whether we're configured to send the SYNCHRONIZE
5669	 * CACHE command directly to the back end.
5670	 */
5671	mtx_lock(&lun->lun_lock);
5672	if ((softc->flags & CTL_FLAG_REAL_SYNC)
5673	 && (++(lun->sync_count) >= lun->sync_interval)) {
5674		lun->sync_count = 0;
5675		mtx_unlock(&lun->lun_lock);
5676		retval = lun->backend->config_write((union ctl_io *)ctsio);
5677	} else {
5678		mtx_unlock(&lun->lun_lock);
5679		ctl_set_success(ctsio);
5680		ctl_done((union ctl_io *)ctsio);
5681	}
5682
5683bailout:
5684
5685	return (retval);
5686}
5687
5688int
5689ctl_format(struct ctl_scsiio *ctsio)
5690{
5691	struct scsi_format *cdb;
5692	struct ctl_lun *lun;
5693	int length, defect_list_len;
5694
5695	CTL_DEBUG_PRINT(("ctl_format\n"));
5696
5697	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5698
5699	cdb = (struct scsi_format *)ctsio->cdb;
5700
5701	length = 0;
5702	if (cdb->byte2 & SF_FMTDATA) {
5703		if (cdb->byte2 & SF_LONGLIST)
5704			length = sizeof(struct scsi_format_header_long);
5705		else
5706			length = sizeof(struct scsi_format_header_short);
5707	}
5708
5709	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5710	 && (length > 0)) {
5711		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5712		ctsio->kern_data_len = length;
5713		ctsio->kern_total_len = length;
5714		ctsio->kern_data_resid = 0;
5715		ctsio->kern_rel_offset = 0;
5716		ctsio->kern_sg_entries = 0;
5717		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5718		ctsio->be_move_done = ctl_config_move_done;
5719		ctl_datamove((union ctl_io *)ctsio);
5720
5721		return (CTL_RETVAL_COMPLETE);
5722	}
5723
5724	defect_list_len = 0;
5725
5726	if (cdb->byte2 & SF_FMTDATA) {
5727		if (cdb->byte2 & SF_LONGLIST) {
5728			struct scsi_format_header_long *header;
5729
5730			header = (struct scsi_format_header_long *)
5731				ctsio->kern_data_ptr;
5732
5733			defect_list_len = scsi_4btoul(header->defect_list_len);
5734			if (defect_list_len != 0) {
5735				ctl_set_invalid_field(ctsio,
5736						      /*sks_valid*/ 1,
5737						      /*command*/ 0,
5738						      /*field*/ 2,
5739						      /*bit_valid*/ 0,
5740						      /*bit*/ 0);
5741				goto bailout;
5742			}
5743		} else {
5744			struct scsi_format_header_short *header;
5745
5746			header = (struct scsi_format_header_short *)
5747				ctsio->kern_data_ptr;
5748
5749			defect_list_len = scsi_2btoul(header->defect_list_len);
5750			if (defect_list_len != 0) {
5751				ctl_set_invalid_field(ctsio,
5752						      /*sks_valid*/ 1,
5753						      /*command*/ 0,
5754						      /*field*/ 2,
5755						      /*bit_valid*/ 0,
5756						      /*bit*/ 0);
5757				goto bailout;
5758			}
5759		}
5760	}
5761
5762	/*
5763	 * The format command will clear out the "Medium format corrupted"
5764	 * status if set by the configuration code.  That status is really
5765	 * just a way to notify the host that we have lost the media, and
5766	 * get them to issue a command that will basically make them think
5767	 * they're blowing away the media.
5768	 */
5769	mtx_lock(&lun->lun_lock);
5770	lun->flags &= ~CTL_LUN_INOPERABLE;
5771	mtx_unlock(&lun->lun_lock);
5772
5773	ctl_set_success(ctsio);
5774bailout:
5775
5776	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5777		free(ctsio->kern_data_ptr, M_CTL);
5778		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5779	}
5780
5781	ctl_done((union ctl_io *)ctsio);
5782	return (CTL_RETVAL_COMPLETE);
5783}
5784
5785int
5786ctl_read_buffer(struct ctl_scsiio *ctsio)
5787{
5788	struct scsi_read_buffer *cdb;
5789	struct ctl_lun *lun;
5790	int buffer_offset, len;
5791	static uint8_t descr[4];
5792	static uint8_t echo_descr[4] = { 0 };
5793
5794	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5795
5796	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5797	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5798
5799	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5800	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5801	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5802		ctl_set_invalid_field(ctsio,
5803				      /*sks_valid*/ 1,
5804				      /*command*/ 1,
5805				      /*field*/ 1,
5806				      /*bit_valid*/ 1,
5807				      /*bit*/ 4);
5808		ctl_done((union ctl_io *)ctsio);
5809		return (CTL_RETVAL_COMPLETE);
5810	}
5811
5812	len = scsi_3btoul(cdb->length);
5813	buffer_offset = scsi_3btoul(cdb->offset);
5814
5815	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5816		ctl_set_invalid_field(ctsio,
5817				      /*sks_valid*/ 1,
5818				      /*command*/ 1,
5819				      /*field*/ 6,
5820				      /*bit_valid*/ 0,
5821				      /*bit*/ 0);
5822		ctl_done((union ctl_io *)ctsio);
5823		return (CTL_RETVAL_COMPLETE);
5824	}
5825
5826	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5827		descr[0] = 0;
5828		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5829		ctsio->kern_data_ptr = descr;
5830		len = min(len, sizeof(descr));
5831	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5832		ctsio->kern_data_ptr = echo_descr;
5833		len = min(len, sizeof(echo_descr));
5834	} else {
5835		if (lun->write_buffer == NULL) {
5836			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5837			    M_CTL, M_WAITOK);
5838		}
5839		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5840	}
5841	ctsio->kern_data_len = len;
5842	ctsio->kern_total_len = len;
5843	ctsio->kern_data_resid = 0;
5844	ctsio->kern_rel_offset = 0;
5845	ctsio->kern_sg_entries = 0;
5846	ctl_set_success(ctsio);
5847	ctsio->be_move_done = ctl_config_move_done;
5848	ctl_datamove((union ctl_io *)ctsio);
5849	return (CTL_RETVAL_COMPLETE);
5850}
5851
5852int
5853ctl_write_buffer(struct ctl_scsiio *ctsio)
5854{
5855	struct scsi_write_buffer *cdb;
5856	struct ctl_lun *lun;
5857	int buffer_offset, len;
5858
5859	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5860
5861	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5862	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5863
5864	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5865		ctl_set_invalid_field(ctsio,
5866				      /*sks_valid*/ 1,
5867				      /*command*/ 1,
5868				      /*field*/ 1,
5869				      /*bit_valid*/ 1,
5870				      /*bit*/ 4);
5871		ctl_done((union ctl_io *)ctsio);
5872		return (CTL_RETVAL_COMPLETE);
5873	}
5874
5875	len = scsi_3btoul(cdb->length);
5876	buffer_offset = scsi_3btoul(cdb->offset);
5877
5878	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5879		ctl_set_invalid_field(ctsio,
5880				      /*sks_valid*/ 1,
5881				      /*command*/ 1,
5882				      /*field*/ 6,
5883				      /*bit_valid*/ 0,
5884				      /*bit*/ 0);
5885		ctl_done((union ctl_io *)ctsio);
5886		return (CTL_RETVAL_COMPLETE);
5887	}
5888
5889	/*
5890	 * If we've got a kernel request that hasn't been malloced yet,
5891	 * malloc it and tell the caller the data buffer is here.
5892	 */
5893	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5894		if (lun->write_buffer == NULL) {
5895			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5896			    M_CTL, M_WAITOK);
5897		}
5898		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5899		ctsio->kern_data_len = len;
5900		ctsio->kern_total_len = len;
5901		ctsio->kern_data_resid = 0;
5902		ctsio->kern_rel_offset = 0;
5903		ctsio->kern_sg_entries = 0;
5904		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5905		ctsio->be_move_done = ctl_config_move_done;
5906		ctl_datamove((union ctl_io *)ctsio);
5907
5908		return (CTL_RETVAL_COMPLETE);
5909	}
5910
5911	ctl_set_success(ctsio);
5912	ctl_done((union ctl_io *)ctsio);
5913	return (CTL_RETVAL_COMPLETE);
5914}
5915
5916int
5917ctl_write_same(struct ctl_scsiio *ctsio)
5918{
5919	struct ctl_lun *lun;
5920	struct ctl_lba_len_flags *lbalen;
5921	uint64_t lba;
5922	uint32_t num_blocks;
5923	int len, retval;
5924	uint8_t byte2;
5925
5926	retval = CTL_RETVAL_COMPLETE;
5927
5928	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5929
5930	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5931
5932	switch (ctsio->cdb[0]) {
5933	case WRITE_SAME_10: {
5934		struct scsi_write_same_10 *cdb;
5935
5936		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5937
5938		lba = scsi_4btoul(cdb->addr);
5939		num_blocks = scsi_2btoul(cdb->length);
5940		byte2 = cdb->byte2;
5941		break;
5942	}
5943	case WRITE_SAME_16: {
5944		struct scsi_write_same_16 *cdb;
5945
5946		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5947
5948		lba = scsi_8btou64(cdb->addr);
5949		num_blocks = scsi_4btoul(cdb->length);
5950		byte2 = cdb->byte2;
5951		break;
5952	}
5953	default:
5954		/*
5955		 * We got a command we don't support.  This shouldn't
5956		 * happen, commands should be filtered out above us.
5957		 */
5958		ctl_set_invalid_opcode(ctsio);
5959		ctl_done((union ctl_io *)ctsio);
5960
5961		return (CTL_RETVAL_COMPLETE);
5962		break; /* NOTREACHED */
5963	}
5964
5965	/* NDOB and ANCHOR flags can be used only together with UNMAP */
5966	if ((byte2 & SWS_UNMAP) == 0 &&
5967	    (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5968		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5969		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5970		ctl_done((union ctl_io *)ctsio);
5971		return (CTL_RETVAL_COMPLETE);
5972	}
5973
5974	/*
5975	 * The first check is to make sure we're in bounds, the second
5976	 * check is to catch wrap-around problems.  If the lba + num blocks
5977	 * is less than the lba, then we've wrapped around and the block
5978	 * range is invalid anyway.
5979	 */
5980	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5981	 || ((lba + num_blocks) < lba)) {
5982		ctl_set_lba_out_of_range(ctsio);
5983		ctl_done((union ctl_io *)ctsio);
5984		return (CTL_RETVAL_COMPLETE);
5985	}
5986
5987	/* Zero number of blocks means "to the last logical block" */
5988	if (num_blocks == 0) {
5989		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5990			ctl_set_invalid_field(ctsio,
5991					      /*sks_valid*/ 0,
5992					      /*command*/ 1,
5993					      /*field*/ 0,
5994					      /*bit_valid*/ 0,
5995					      /*bit*/ 0);
5996			ctl_done((union ctl_io *)ctsio);
5997			return (CTL_RETVAL_COMPLETE);
5998		}
5999		num_blocks = (lun->be_lun->maxlba + 1) - lba;
6000	}
6001
6002	len = lun->be_lun->blocksize;
6003
6004	/*
6005	 * If we've got a kernel request that hasn't been malloced yet,
6006	 * malloc it and tell the caller the data buffer is here.
6007	 */
6008	if ((byte2 & SWS_NDOB) == 0 &&
6009	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6010		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6011		ctsio->kern_data_len = len;
6012		ctsio->kern_total_len = len;
6013		ctsio->kern_data_resid = 0;
6014		ctsio->kern_rel_offset = 0;
6015		ctsio->kern_sg_entries = 0;
6016		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6017		ctsio->be_move_done = ctl_config_move_done;
6018		ctl_datamove((union ctl_io *)ctsio);
6019
6020		return (CTL_RETVAL_COMPLETE);
6021	}
6022
6023	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6024	lbalen->lba = lba;
6025	lbalen->len = num_blocks;
6026	lbalen->flags = byte2;
6027	retval = lun->backend->config_write((union ctl_io *)ctsio);
6028
6029	return (retval);
6030}
6031
6032int
6033ctl_unmap(struct ctl_scsiio *ctsio)
6034{
6035	struct ctl_lun *lun;
6036	struct scsi_unmap *cdb;
6037	struct ctl_ptr_len_flags *ptrlen;
6038	struct scsi_unmap_header *hdr;
6039	struct scsi_unmap_desc *buf, *end, *endnz, *range;
6040	uint64_t lba;
6041	uint32_t num_blocks;
6042	int len, retval;
6043	uint8_t byte2;
6044
6045	retval = CTL_RETVAL_COMPLETE;
6046
6047	CTL_DEBUG_PRINT(("ctl_unmap\n"));
6048
6049	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6050	cdb = (struct scsi_unmap *)ctsio->cdb;
6051
6052	len = scsi_2btoul(cdb->length);
6053	byte2 = cdb->byte2;
6054
6055	/*
6056	 * If we've got a kernel request that hasn't been malloced yet,
6057	 * malloc it and tell the caller the data buffer is here.
6058	 */
6059	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6060		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6061		ctsio->kern_data_len = len;
6062		ctsio->kern_total_len = len;
6063		ctsio->kern_data_resid = 0;
6064		ctsio->kern_rel_offset = 0;
6065		ctsio->kern_sg_entries = 0;
6066		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6067		ctsio->be_move_done = ctl_config_move_done;
6068		ctl_datamove((union ctl_io *)ctsio);
6069
6070		return (CTL_RETVAL_COMPLETE);
6071	}
6072
6073	len = ctsio->kern_total_len - ctsio->kern_data_resid;
6074	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
6075	if (len < sizeof (*hdr) ||
6076	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
6077	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
6078	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
6079		ctl_set_invalid_field(ctsio,
6080				      /*sks_valid*/ 0,
6081				      /*command*/ 0,
6082				      /*field*/ 0,
6083				      /*bit_valid*/ 0,
6084				      /*bit*/ 0);
6085		goto done;
6086	}
6087	len = scsi_2btoul(hdr->desc_length);
6088	buf = (struct scsi_unmap_desc *)(hdr + 1);
6089	end = buf + len / sizeof(*buf);
6090
6091	endnz = buf;
6092	for (range = buf; range < end; range++) {
6093		lba = scsi_8btou64(range->lba);
6094		num_blocks = scsi_4btoul(range->length);
6095		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6096		 || ((lba + num_blocks) < lba)) {
6097			ctl_set_lba_out_of_range(ctsio);
6098			ctl_done((union ctl_io *)ctsio);
6099			return (CTL_RETVAL_COMPLETE);
6100		}
6101		if (num_blocks != 0)
6102			endnz = range + 1;
6103	}
6104
6105	/*
6106	 * Block backend can not handle zero last range.
6107	 * Filter it out and return if there is nothing left.
6108	 */
6109	len = (uint8_t *)endnz - (uint8_t *)buf;
6110	if (len == 0) {
6111		ctl_set_success(ctsio);
6112		goto done;
6113	}
6114
6115	mtx_lock(&lun->lun_lock);
6116	ptrlen = (struct ctl_ptr_len_flags *)
6117	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6118	ptrlen->ptr = (void *)buf;
6119	ptrlen->len = len;
6120	ptrlen->flags = byte2;
6121	ctl_check_blocked(lun);
6122	mtx_unlock(&lun->lun_lock);
6123
6124	retval = lun->backend->config_write((union ctl_io *)ctsio);
6125	return (retval);
6126
6127done:
6128	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
6129		free(ctsio->kern_data_ptr, M_CTL);
6130		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
6131	}
6132	ctl_done((union ctl_io *)ctsio);
6133	return (CTL_RETVAL_COMPLETE);
6134}
6135
6136/*
6137 * Note that this function currently doesn't actually do anything inside
6138 * CTL to enforce things if the DQue bit is turned on.
6139 *
6140 * Also note that this function can't be used in the default case, because
6141 * the DQue bit isn't set in the changeable mask for the control mode page
6142 * anyway.  This is just here as an example for how to implement a page
6143 * handler, and a placeholder in case we want to allow the user to turn
6144 * tagged queueing on and off.
6145 *
6146 * The D_SENSE bit handling is functional, however, and will turn
6147 * descriptor sense on and off for a given LUN.
6148 */
6149int
6150ctl_control_page_handler(struct ctl_scsiio *ctsio,
6151			 struct ctl_page_index *page_index, uint8_t *page_ptr)
6152{
6153	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6154	struct ctl_lun *lun;
6155	int set_ua;
6156	uint32_t initidx;
6157
6158	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6159	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6160	set_ua = 0;
6161
6162	user_cp = (struct scsi_control_page *)page_ptr;
6163	current_cp = (struct scsi_control_page *)
6164		(page_index->page_data + (page_index->page_len *
6165		CTL_PAGE_CURRENT));
6166	saved_cp = (struct scsi_control_page *)
6167		(page_index->page_data + (page_index->page_len *
6168		CTL_PAGE_SAVED));
6169
6170	mtx_lock(&lun->lun_lock);
6171	if (((current_cp->rlec & SCP_DSENSE) == 0)
6172	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6173		/*
6174		 * Descriptor sense is currently turned off and the user
6175		 * wants to turn it on.
6176		 */
6177		current_cp->rlec |= SCP_DSENSE;
6178		saved_cp->rlec |= SCP_DSENSE;
6179		lun->flags |= CTL_LUN_SENSE_DESC;
6180		set_ua = 1;
6181	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6182		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6183		/*
6184		 * Descriptor sense is currently turned on, and the user
6185		 * wants to turn it off.
6186		 */
6187		current_cp->rlec &= ~SCP_DSENSE;
6188		saved_cp->rlec &= ~SCP_DSENSE;
6189		lun->flags &= ~CTL_LUN_SENSE_DESC;
6190		set_ua = 1;
6191	}
6192	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6193	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6194		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6195		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6196		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6197		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6198		set_ua = 1;
6199	}
6200	if ((current_cp->eca_and_aen & SCP_SWP) !=
6201	    (user_cp->eca_and_aen & SCP_SWP)) {
6202		current_cp->eca_and_aen &= ~SCP_SWP;
6203		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6204		saved_cp->eca_and_aen &= ~SCP_SWP;
6205		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6206		set_ua = 1;
6207	}
6208	if (set_ua != 0)
6209		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6210	mtx_unlock(&lun->lun_lock);
6211
6212	return (0);
6213}
6214
6215int
6216ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6217		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6218{
6219	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6220	struct ctl_lun *lun;
6221	int set_ua;
6222	uint32_t initidx;
6223
6224	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6225	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6226	set_ua = 0;
6227
6228	user_cp = (struct scsi_caching_page *)page_ptr;
6229	current_cp = (struct scsi_caching_page *)
6230		(page_index->page_data + (page_index->page_len *
6231		CTL_PAGE_CURRENT));
6232	saved_cp = (struct scsi_caching_page *)
6233		(page_index->page_data + (page_index->page_len *
6234		CTL_PAGE_SAVED));
6235
6236	mtx_lock(&lun->lun_lock);
6237	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6238	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6239		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6240		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6241		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6242		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6243		set_ua = 1;
6244	}
6245	if (set_ua != 0)
6246		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6247	mtx_unlock(&lun->lun_lock);
6248
6249	return (0);
6250}
6251
6252int
6253ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6254				struct ctl_page_index *page_index,
6255				uint8_t *page_ptr)
6256{
6257	uint8_t *c;
6258	int i;
6259
6260	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6261	ctl_time_io_secs =
6262		(c[0] << 8) |
6263		(c[1] << 0) |
6264		0;
6265	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6266	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6267	printf("page data:");
6268	for (i=0; i<8; i++)
6269		printf(" %.2x",page_ptr[i]);
6270	printf("\n");
6271	return (0);
6272}
6273
6274int
6275ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6276			       struct ctl_page_index *page_index,
6277			       int pc)
6278{
6279	struct copan_debugconf_subpage *page;
6280
6281	page = (struct copan_debugconf_subpage *)page_index->page_data +
6282		(page_index->page_len * pc);
6283
6284	switch (pc) {
6285	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6286	case SMS_PAGE_CTRL_DEFAULT >> 6:
6287	case SMS_PAGE_CTRL_SAVED >> 6:
6288		/*
6289		 * We don't update the changable or default bits for this page.
6290		 */
6291		break;
6292	case SMS_PAGE_CTRL_CURRENT >> 6:
6293		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6294		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6295		break;
6296	default:
6297#ifdef NEEDTOPORT
6298		EPRINT(0, "Invalid PC %d!!", pc);
6299#endif /* NEEDTOPORT */
6300		break;
6301	}
6302	return (0);
6303}
6304
6305
6306static int
6307ctl_do_mode_select(union ctl_io *io)
6308{
6309	struct scsi_mode_page_header *page_header;
6310	struct ctl_page_index *page_index;
6311	struct ctl_scsiio *ctsio;
6312	int control_dev, page_len;
6313	int page_len_offset, page_len_size;
6314	union ctl_modepage_info *modepage_info;
6315	struct ctl_lun *lun;
6316	int *len_left, *len_used;
6317	int retval, i;
6318
6319	ctsio = &io->scsiio;
6320	page_index = NULL;
6321	page_len = 0;
6322	retval = CTL_RETVAL_COMPLETE;
6323
6324	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6325
6326	if (lun->be_lun->lun_type != T_DIRECT)
6327		control_dev = 1;
6328	else
6329		control_dev = 0;
6330
6331	modepage_info = (union ctl_modepage_info *)
6332		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6333	len_left = &modepage_info->header.len_left;
6334	len_used = &modepage_info->header.len_used;
6335
6336do_next_page:
6337
6338	page_header = (struct scsi_mode_page_header *)
6339		(ctsio->kern_data_ptr + *len_used);
6340
6341	if (*len_left == 0) {
6342		free(ctsio->kern_data_ptr, M_CTL);
6343		ctl_set_success(ctsio);
6344		ctl_done((union ctl_io *)ctsio);
6345		return (CTL_RETVAL_COMPLETE);
6346	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6347
6348		free(ctsio->kern_data_ptr, M_CTL);
6349		ctl_set_param_len_error(ctsio);
6350		ctl_done((union ctl_io *)ctsio);
6351		return (CTL_RETVAL_COMPLETE);
6352
6353	} else if ((page_header->page_code & SMPH_SPF)
6354		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6355
6356		free(ctsio->kern_data_ptr, M_CTL);
6357		ctl_set_param_len_error(ctsio);
6358		ctl_done((union ctl_io *)ctsio);
6359		return (CTL_RETVAL_COMPLETE);
6360	}
6361
6362
6363	/*
6364	 * XXX KDM should we do something with the block descriptor?
6365	 */
6366	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6367
6368		if ((control_dev != 0)
6369		 && (lun->mode_pages.index[i].page_flags &
6370		     CTL_PAGE_FLAG_DISK_ONLY))
6371			continue;
6372
6373		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6374		    (page_header->page_code & SMPH_PC_MASK))
6375			continue;
6376
6377		/*
6378		 * If neither page has a subpage code, then we've got a
6379		 * match.
6380		 */
6381		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6382		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6383			page_index = &lun->mode_pages.index[i];
6384			page_len = page_header->page_length;
6385			break;
6386		}
6387
6388		/*
6389		 * If both pages have subpages, then the subpage numbers
6390		 * have to match.
6391		 */
6392		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6393		  && (page_header->page_code & SMPH_SPF)) {
6394			struct scsi_mode_page_header_sp *sph;
6395
6396			sph = (struct scsi_mode_page_header_sp *)page_header;
6397
6398			if (lun->mode_pages.index[i].subpage ==
6399			    sph->subpage) {
6400				page_index = &lun->mode_pages.index[i];
6401				page_len = scsi_2btoul(sph->page_length);
6402				break;
6403			}
6404		}
6405	}
6406
6407	/*
6408	 * If we couldn't find the page, or if we don't have a mode select
6409	 * handler for it, send back an error to the user.
6410	 */
6411	if ((page_index == NULL)
6412	 || (page_index->select_handler == NULL)) {
6413		ctl_set_invalid_field(ctsio,
6414				      /*sks_valid*/ 1,
6415				      /*command*/ 0,
6416				      /*field*/ *len_used,
6417				      /*bit_valid*/ 0,
6418				      /*bit*/ 0);
6419		free(ctsio->kern_data_ptr, M_CTL);
6420		ctl_done((union ctl_io *)ctsio);
6421		return (CTL_RETVAL_COMPLETE);
6422	}
6423
6424	if (page_index->page_code & SMPH_SPF) {
6425		page_len_offset = 2;
6426		page_len_size = 2;
6427	} else {
6428		page_len_size = 1;
6429		page_len_offset = 1;
6430	}
6431
6432	/*
6433	 * If the length the initiator gives us isn't the one we specify in
6434	 * the mode page header, or if they didn't specify enough data in
6435	 * the CDB to avoid truncating this page, kick out the request.
6436	 */
6437	if ((page_len != (page_index->page_len - page_len_offset -
6438			  page_len_size))
6439	 || (*len_left < page_index->page_len)) {
6440
6441
6442		ctl_set_invalid_field(ctsio,
6443				      /*sks_valid*/ 1,
6444				      /*command*/ 0,
6445				      /*field*/ *len_used + page_len_offset,
6446				      /*bit_valid*/ 0,
6447				      /*bit*/ 0);
6448		free(ctsio->kern_data_ptr, M_CTL);
6449		ctl_done((union ctl_io *)ctsio);
6450		return (CTL_RETVAL_COMPLETE);
6451	}
6452
6453	/*
6454	 * Run through the mode page, checking to make sure that the bits
6455	 * the user changed are actually legal for him to change.
6456	 */
6457	for (i = 0; i < page_index->page_len; i++) {
6458		uint8_t *user_byte, *change_mask, *current_byte;
6459		int bad_bit;
6460		int j;
6461
6462		user_byte = (uint8_t *)page_header + i;
6463		change_mask = page_index->page_data +
6464			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6465		current_byte = page_index->page_data +
6466			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6467
6468		/*
6469		 * Check to see whether the user set any bits in this byte
6470		 * that he is not allowed to set.
6471		 */
6472		if ((*user_byte & ~(*change_mask)) ==
6473		    (*current_byte & ~(*change_mask)))
6474			continue;
6475
6476		/*
6477		 * Go through bit by bit to determine which one is illegal.
6478		 */
6479		bad_bit = 0;
6480		for (j = 7; j >= 0; j--) {
6481			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6482			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6483				bad_bit = i;
6484				break;
6485			}
6486		}
6487		ctl_set_invalid_field(ctsio,
6488				      /*sks_valid*/ 1,
6489				      /*command*/ 0,
6490				      /*field*/ *len_used + i,
6491				      /*bit_valid*/ 1,
6492				      /*bit*/ bad_bit);
6493		free(ctsio->kern_data_ptr, M_CTL);
6494		ctl_done((union ctl_io *)ctsio);
6495		return (CTL_RETVAL_COMPLETE);
6496	}
6497
6498	/*
6499	 * Decrement these before we call the page handler, since we may
6500	 * end up getting called back one way or another before the handler
6501	 * returns to this context.
6502	 */
6503	*len_left -= page_index->page_len;
6504	*len_used += page_index->page_len;
6505
6506	retval = page_index->select_handler(ctsio, page_index,
6507					    (uint8_t *)page_header);
6508
6509	/*
6510	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6511	 * wait until this queued command completes to finish processing
6512	 * the mode page.  If it returns anything other than
6513	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6514	 * already set the sense information, freed the data pointer, and
6515	 * completed the io for us.
6516	 */
6517	if (retval != CTL_RETVAL_COMPLETE)
6518		goto bailout_no_done;
6519
6520	/*
6521	 * If the initiator sent us more than one page, parse the next one.
6522	 */
6523	if (*len_left > 0)
6524		goto do_next_page;
6525
6526	ctl_set_success(ctsio);
6527	free(ctsio->kern_data_ptr, M_CTL);
6528	ctl_done((union ctl_io *)ctsio);
6529
6530bailout_no_done:
6531
6532	return (CTL_RETVAL_COMPLETE);
6533
6534}
6535
6536int
6537ctl_mode_select(struct ctl_scsiio *ctsio)
6538{
6539	int param_len, pf, sp;
6540	int header_size, bd_len;
6541	int len_left, len_used;
6542	struct ctl_page_index *page_index;
6543	struct ctl_lun *lun;
6544	int control_dev, page_len;
6545	union ctl_modepage_info *modepage_info;
6546	int retval;
6547
6548	pf = 0;
6549	sp = 0;
6550	page_len = 0;
6551	len_used = 0;
6552	len_left = 0;
6553	retval = 0;
6554	bd_len = 0;
6555	page_index = NULL;
6556
6557	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6558
6559	if (lun->be_lun->lun_type != T_DIRECT)
6560		control_dev = 1;
6561	else
6562		control_dev = 0;
6563
6564	switch (ctsio->cdb[0]) {
6565	case MODE_SELECT_6: {
6566		struct scsi_mode_select_6 *cdb;
6567
6568		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6569
6570		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6571		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6572
6573		param_len = cdb->length;
6574		header_size = sizeof(struct scsi_mode_header_6);
6575		break;
6576	}
6577	case MODE_SELECT_10: {
6578		struct scsi_mode_select_10 *cdb;
6579
6580		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6581
6582		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6583		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6584
6585		param_len = scsi_2btoul(cdb->length);
6586		header_size = sizeof(struct scsi_mode_header_10);
6587		break;
6588	}
6589	default:
6590		ctl_set_invalid_opcode(ctsio);
6591		ctl_done((union ctl_io *)ctsio);
6592		return (CTL_RETVAL_COMPLETE);
6593		break; /* NOTREACHED */
6594	}
6595
6596	/*
6597	 * From SPC-3:
6598	 * "A parameter list length of zero indicates that the Data-Out Buffer
6599	 * shall be empty. This condition shall not be considered as an error."
6600	 */
6601	if (param_len == 0) {
6602		ctl_set_success(ctsio);
6603		ctl_done((union ctl_io *)ctsio);
6604		return (CTL_RETVAL_COMPLETE);
6605	}
6606
6607	/*
6608	 * Since we'll hit this the first time through, prior to
6609	 * allocation, we don't need to free a data buffer here.
6610	 */
6611	if (param_len < header_size) {
6612		ctl_set_param_len_error(ctsio);
6613		ctl_done((union ctl_io *)ctsio);
6614		return (CTL_RETVAL_COMPLETE);
6615	}
6616
6617	/*
6618	 * Allocate the data buffer and grab the user's data.  In theory,
6619	 * we shouldn't have to sanity check the parameter list length here
6620	 * because the maximum size is 64K.  We should be able to malloc
6621	 * that much without too many problems.
6622	 */
6623	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6624		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6625		ctsio->kern_data_len = param_len;
6626		ctsio->kern_total_len = param_len;
6627		ctsio->kern_data_resid = 0;
6628		ctsio->kern_rel_offset = 0;
6629		ctsio->kern_sg_entries = 0;
6630		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6631		ctsio->be_move_done = ctl_config_move_done;
6632		ctl_datamove((union ctl_io *)ctsio);
6633
6634		return (CTL_RETVAL_COMPLETE);
6635	}
6636
6637	switch (ctsio->cdb[0]) {
6638	case MODE_SELECT_6: {
6639		struct scsi_mode_header_6 *mh6;
6640
6641		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6642		bd_len = mh6->blk_desc_len;
6643		break;
6644	}
6645	case MODE_SELECT_10: {
6646		struct scsi_mode_header_10 *mh10;
6647
6648		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6649		bd_len = scsi_2btoul(mh10->blk_desc_len);
6650		break;
6651	}
6652	default:
6653		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6654		break;
6655	}
6656
6657	if (param_len < (header_size + bd_len)) {
6658		free(ctsio->kern_data_ptr, M_CTL);
6659		ctl_set_param_len_error(ctsio);
6660		ctl_done((union ctl_io *)ctsio);
6661		return (CTL_RETVAL_COMPLETE);
6662	}
6663
6664	/*
6665	 * Set the IO_CONT flag, so that if this I/O gets passed to
6666	 * ctl_config_write_done(), it'll get passed back to
6667	 * ctl_do_mode_select() for further processing, or completion if
6668	 * we're all done.
6669	 */
6670	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6671	ctsio->io_cont = ctl_do_mode_select;
6672
6673	modepage_info = (union ctl_modepage_info *)
6674		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6675
6676	memset(modepage_info, 0, sizeof(*modepage_info));
6677
6678	len_left = param_len - header_size - bd_len;
6679	len_used = header_size + bd_len;
6680
6681	modepage_info->header.len_left = len_left;
6682	modepage_info->header.len_used = len_used;
6683
6684	return (ctl_do_mode_select((union ctl_io *)ctsio));
6685}
6686
6687int
6688ctl_mode_sense(struct ctl_scsiio *ctsio)
6689{
6690	struct ctl_lun *lun;
6691	int pc, page_code, dbd, llba, subpage;
6692	int alloc_len, page_len, header_len, total_len;
6693	struct scsi_mode_block_descr *block_desc;
6694	struct ctl_page_index *page_index;
6695	int control_dev;
6696
6697	dbd = 0;
6698	llba = 0;
6699	block_desc = NULL;
6700	page_index = NULL;
6701
6702	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6703
6704	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6705
6706	if (lun->be_lun->lun_type != T_DIRECT)
6707		control_dev = 1;
6708	else
6709		control_dev = 0;
6710
6711	switch (ctsio->cdb[0]) {
6712	case MODE_SENSE_6: {
6713		struct scsi_mode_sense_6 *cdb;
6714
6715		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6716
6717		header_len = sizeof(struct scsi_mode_hdr_6);
6718		if (cdb->byte2 & SMS_DBD)
6719			dbd = 1;
6720		else
6721			header_len += sizeof(struct scsi_mode_block_descr);
6722
6723		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6724		page_code = cdb->page & SMS_PAGE_CODE;
6725		subpage = cdb->subpage;
6726		alloc_len = cdb->length;
6727		break;
6728	}
6729	case MODE_SENSE_10: {
6730		struct scsi_mode_sense_10 *cdb;
6731
6732		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6733
6734		header_len = sizeof(struct scsi_mode_hdr_10);
6735
6736		if (cdb->byte2 & SMS_DBD)
6737			dbd = 1;
6738		else
6739			header_len += sizeof(struct scsi_mode_block_descr);
6740		if (cdb->byte2 & SMS10_LLBAA)
6741			llba = 1;
6742		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6743		page_code = cdb->page & SMS_PAGE_CODE;
6744		subpage = cdb->subpage;
6745		alloc_len = scsi_2btoul(cdb->length);
6746		break;
6747	}
6748	default:
6749		ctl_set_invalid_opcode(ctsio);
6750		ctl_done((union ctl_io *)ctsio);
6751		return (CTL_RETVAL_COMPLETE);
6752		break; /* NOTREACHED */
6753	}
6754
6755	/*
6756	 * We have to make a first pass through to calculate the size of
6757	 * the pages that match the user's query.  Then we allocate enough
6758	 * memory to hold it, and actually copy the data into the buffer.
6759	 */
6760	switch (page_code) {
6761	case SMS_ALL_PAGES_PAGE: {
6762		int i;
6763
6764		page_len = 0;
6765
6766		/*
6767		 * At the moment, values other than 0 and 0xff here are
6768		 * reserved according to SPC-3.
6769		 */
6770		if ((subpage != SMS_SUBPAGE_PAGE_0)
6771		 && (subpage != SMS_SUBPAGE_ALL)) {
6772			ctl_set_invalid_field(ctsio,
6773					      /*sks_valid*/ 1,
6774					      /*command*/ 1,
6775					      /*field*/ 3,
6776					      /*bit_valid*/ 0,
6777					      /*bit*/ 0);
6778			ctl_done((union ctl_io *)ctsio);
6779			return (CTL_RETVAL_COMPLETE);
6780		}
6781
6782		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6783			if ((control_dev != 0)
6784			 && (lun->mode_pages.index[i].page_flags &
6785			     CTL_PAGE_FLAG_DISK_ONLY))
6786				continue;
6787
6788			/*
6789			 * We don't use this subpage if the user didn't
6790			 * request all subpages.
6791			 */
6792			if ((lun->mode_pages.index[i].subpage != 0)
6793			 && (subpage == SMS_SUBPAGE_PAGE_0))
6794				continue;
6795
6796#if 0
6797			printf("found page %#x len %d\n",
6798			       lun->mode_pages.index[i].page_code &
6799			       SMPH_PC_MASK,
6800			       lun->mode_pages.index[i].page_len);
6801#endif
6802			page_len += lun->mode_pages.index[i].page_len;
6803		}
6804		break;
6805	}
6806	default: {
6807		int i;
6808
6809		page_len = 0;
6810
6811		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6812			/* Look for the right page code */
6813			if ((lun->mode_pages.index[i].page_code &
6814			     SMPH_PC_MASK) != page_code)
6815				continue;
6816
6817			/* Look for the right subpage or the subpage wildcard*/
6818			if ((lun->mode_pages.index[i].subpage != subpage)
6819			 && (subpage != SMS_SUBPAGE_ALL))
6820				continue;
6821
6822			/* Make sure the page is supported for this dev type */
6823			if ((control_dev != 0)
6824			 && (lun->mode_pages.index[i].page_flags &
6825			     CTL_PAGE_FLAG_DISK_ONLY))
6826				continue;
6827
6828#if 0
6829			printf("found page %#x len %d\n",
6830			       lun->mode_pages.index[i].page_code &
6831			       SMPH_PC_MASK,
6832			       lun->mode_pages.index[i].page_len);
6833#endif
6834
6835			page_len += lun->mode_pages.index[i].page_len;
6836		}
6837
6838		if (page_len == 0) {
6839			ctl_set_invalid_field(ctsio,
6840					      /*sks_valid*/ 1,
6841					      /*command*/ 1,
6842					      /*field*/ 2,
6843					      /*bit_valid*/ 1,
6844					      /*bit*/ 5);
6845			ctl_done((union ctl_io *)ctsio);
6846			return (CTL_RETVAL_COMPLETE);
6847		}
6848		break;
6849	}
6850	}
6851
6852	total_len = header_len + page_len;
6853#if 0
6854	printf("header_len = %d, page_len = %d, total_len = %d\n",
6855	       header_len, page_len, total_len);
6856#endif
6857
6858	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6859	ctsio->kern_sg_entries = 0;
6860	ctsio->kern_data_resid = 0;
6861	ctsio->kern_rel_offset = 0;
6862	if (total_len < alloc_len) {
6863		ctsio->residual = alloc_len - total_len;
6864		ctsio->kern_data_len = total_len;
6865		ctsio->kern_total_len = total_len;
6866	} else {
6867		ctsio->residual = 0;
6868		ctsio->kern_data_len = alloc_len;
6869		ctsio->kern_total_len = alloc_len;
6870	}
6871
6872	switch (ctsio->cdb[0]) {
6873	case MODE_SENSE_6: {
6874		struct scsi_mode_hdr_6 *header;
6875
6876		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6877
6878		header->datalen = MIN(total_len - 1, 254);
6879		if (control_dev == 0) {
6880			header->dev_specific = 0x10; /* DPOFUA */
6881			if ((lun->flags & CTL_LUN_READONLY) ||
6882			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6883			    .eca_and_aen & SCP_SWP) != 0)
6884				    header->dev_specific |= 0x80; /* WP */
6885		}
6886		if (dbd)
6887			header->block_descr_len = 0;
6888		else
6889			header->block_descr_len =
6890				sizeof(struct scsi_mode_block_descr);
6891		block_desc = (struct scsi_mode_block_descr *)&header[1];
6892		break;
6893	}
6894	case MODE_SENSE_10: {
6895		struct scsi_mode_hdr_10 *header;
6896		int datalen;
6897
6898		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6899
6900		datalen = MIN(total_len - 2, 65533);
6901		scsi_ulto2b(datalen, header->datalen);
6902		if (control_dev == 0) {
6903			header->dev_specific = 0x10; /* DPOFUA */
6904			if ((lun->flags & CTL_LUN_READONLY) ||
6905			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6906			    .eca_and_aen & SCP_SWP) != 0)
6907				    header->dev_specific |= 0x80; /* WP */
6908		}
6909		if (dbd)
6910			scsi_ulto2b(0, header->block_descr_len);
6911		else
6912			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6913				    header->block_descr_len);
6914		block_desc = (struct scsi_mode_block_descr *)&header[1];
6915		break;
6916	}
6917	default:
6918		panic("invalid CDB type %#x", ctsio->cdb[0]);
6919		break; /* NOTREACHED */
6920	}
6921
6922	/*
6923	 * If we've got a disk, use its blocksize in the block
6924	 * descriptor.  Otherwise, just set it to 0.
6925	 */
6926	if (dbd == 0) {
6927		if (control_dev == 0)
6928			scsi_ulto3b(lun->be_lun->blocksize,
6929				    block_desc->block_len);
6930		else
6931			scsi_ulto3b(0, block_desc->block_len);
6932	}
6933
6934	switch (page_code) {
6935	case SMS_ALL_PAGES_PAGE: {
6936		int i, data_used;
6937
6938		data_used = header_len;
6939		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6940			struct ctl_page_index *page_index;
6941
6942			page_index = &lun->mode_pages.index[i];
6943
6944			if ((control_dev != 0)
6945			 && (page_index->page_flags &
6946			    CTL_PAGE_FLAG_DISK_ONLY))
6947				continue;
6948
6949			/*
6950			 * We don't use this subpage if the user didn't
6951			 * request all subpages.  We already checked (above)
6952			 * to make sure the user only specified a subpage
6953			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6954			 */
6955			if ((page_index->subpage != 0)
6956			 && (subpage == SMS_SUBPAGE_PAGE_0))
6957				continue;
6958
6959			/*
6960			 * Call the handler, if it exists, to update the
6961			 * page to the latest values.
6962			 */
6963			if (page_index->sense_handler != NULL)
6964				page_index->sense_handler(ctsio, page_index,pc);
6965
6966			memcpy(ctsio->kern_data_ptr + data_used,
6967			       page_index->page_data +
6968			       (page_index->page_len * pc),
6969			       page_index->page_len);
6970			data_used += page_index->page_len;
6971		}
6972		break;
6973	}
6974	default: {
6975		int i, data_used;
6976
6977		data_used = header_len;
6978
6979		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6980			struct ctl_page_index *page_index;
6981
6982			page_index = &lun->mode_pages.index[i];
6983
6984			/* Look for the right page code */
6985			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6986				continue;
6987
6988			/* Look for the right subpage or the subpage wildcard*/
6989			if ((page_index->subpage != subpage)
6990			 && (subpage != SMS_SUBPAGE_ALL))
6991				continue;
6992
6993			/* Make sure the page is supported for this dev type */
6994			if ((control_dev != 0)
6995			 && (page_index->page_flags &
6996			     CTL_PAGE_FLAG_DISK_ONLY))
6997				continue;
6998
6999			/*
7000			 * Call the handler, if it exists, to update the
7001			 * page to the latest values.
7002			 */
7003			if (page_index->sense_handler != NULL)
7004				page_index->sense_handler(ctsio, page_index,pc);
7005
7006			memcpy(ctsio->kern_data_ptr + data_used,
7007			       page_index->page_data +
7008			       (page_index->page_len * pc),
7009			       page_index->page_len);
7010			data_used += page_index->page_len;
7011		}
7012		break;
7013	}
7014	}
7015
7016	ctl_set_success(ctsio);
7017	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7018	ctsio->be_move_done = ctl_config_move_done;
7019	ctl_datamove((union ctl_io *)ctsio);
7020	return (CTL_RETVAL_COMPLETE);
7021}
7022
7023int
7024ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
7025			       struct ctl_page_index *page_index,
7026			       int pc)
7027{
7028	struct ctl_lun *lun;
7029	struct scsi_log_param_header *phdr;
7030	uint8_t *data;
7031	uint64_t val;
7032
7033	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7034	data = page_index->page_data;
7035
7036	if (lun->backend->lun_attr != NULL &&
7037	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
7038	     != UINT64_MAX) {
7039		phdr = (struct scsi_log_param_header *)data;
7040		scsi_ulto2b(0x0001, phdr->param_code);
7041		phdr->param_control = SLP_LBIN | SLP_LP;
7042		phdr->param_len = 8;
7043		data = (uint8_t *)(phdr + 1);
7044		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
7045		data[4] = 0x02; /* per-pool */
7046		data += phdr->param_len;
7047	}
7048
7049	if (lun->backend->lun_attr != NULL &&
7050	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
7051	     != UINT64_MAX) {
7052		phdr = (struct scsi_log_param_header *)data;
7053		scsi_ulto2b(0x0002, phdr->param_code);
7054		phdr->param_control = SLP_LBIN | SLP_LP;
7055		phdr->param_len = 8;
7056		data = (uint8_t *)(phdr + 1);
7057		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
7058		data[4] = 0x01; /* per-LUN */
7059		data += phdr->param_len;
7060	}
7061
7062	if (lun->backend->lun_attr != NULL &&
7063	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
7064	     != UINT64_MAX) {
7065		phdr = (struct scsi_log_param_header *)data;
7066		scsi_ulto2b(0x00f1, phdr->param_code);
7067		phdr->param_control = SLP_LBIN | SLP_LP;
7068		phdr->param_len = 8;
7069		data = (uint8_t *)(phdr + 1);
7070		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
7071		data[4] = 0x02; /* per-pool */
7072		data += phdr->param_len;
7073	}
7074
7075	if (lun->backend->lun_attr != NULL &&
7076	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
7077	     != UINT64_MAX) {
7078		phdr = (struct scsi_log_param_header *)data;
7079		scsi_ulto2b(0x00f2, phdr->param_code);
7080		phdr->param_control = SLP_LBIN | SLP_LP;
7081		phdr->param_len = 8;
7082		data = (uint8_t *)(phdr + 1);
7083		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
7084		data[4] = 0x02; /* per-pool */
7085		data += phdr->param_len;
7086	}
7087
7088	page_index->page_len = data - page_index->page_data;
7089	return (0);
7090}
7091
7092int
7093ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
7094			       struct ctl_page_index *page_index,
7095			       int pc)
7096{
7097	struct ctl_lun *lun;
7098	struct stat_page *data;
7099	uint64_t rn, wn, rb, wb;
7100	struct bintime rt, wt;
7101	int i;
7102
7103	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7104	data = (struct stat_page *)page_index->page_data;
7105
7106	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
7107	data->sap.hdr.param_control = SLP_LBIN;
7108	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
7109	    sizeof(struct scsi_log_param_header);
7110	rn = wn = rb = wb = 0;
7111	bintime_clear(&rt);
7112	bintime_clear(&wt);
7113	for (i = 0; i < CTL_MAX_PORTS; i++) {
7114		rn += lun->stats.ports[i].operations[CTL_STATS_READ];
7115		wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
7116		rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
7117		wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
7118		bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
7119		bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
7120	}
7121	scsi_u64to8b(rn, data->sap.read_num);
7122	scsi_u64to8b(wn, data->sap.write_num);
7123	if (lun->stats.blocksize > 0) {
7124		scsi_u64to8b(wb / lun->stats.blocksize,
7125		    data->sap.recvieved_lba);
7126		scsi_u64to8b(rb / lun->stats.blocksize,
7127		    data->sap.transmitted_lba);
7128	}
7129	scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
7130	    data->sap.read_int);
7131	scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
7132	    data->sap.write_int);
7133	scsi_u64to8b(0, data->sap.weighted_num);
7134	scsi_u64to8b(0, data->sap.weighted_int);
7135	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
7136	data->it.hdr.param_control = SLP_LBIN;
7137	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
7138	    sizeof(struct scsi_log_param_header);
7139#ifdef CTL_TIME_IO
7140	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
7141#endif
7142	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
7143	data->it.hdr.param_control = SLP_LBIN;
7144	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
7145	    sizeof(struct scsi_log_param_header);
7146	scsi_ulto4b(3, data->ti.exponent);
7147	scsi_ulto4b(1, data->ti.integer);
7148
7149	page_index->page_len = sizeof(*data);
7150	return (0);
7151}
7152
7153int
7154ctl_log_sense(struct ctl_scsiio *ctsio)
7155{
7156	struct ctl_lun *lun;
7157	int i, pc, page_code, subpage;
7158	int alloc_len, total_len;
7159	struct ctl_page_index *page_index;
7160	struct scsi_log_sense *cdb;
7161	struct scsi_log_header *header;
7162
7163	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
7164
7165	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7166	cdb = (struct scsi_log_sense *)ctsio->cdb;
7167	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
7168	page_code = cdb->page & SLS_PAGE_CODE;
7169	subpage = cdb->subpage;
7170	alloc_len = scsi_2btoul(cdb->length);
7171
7172	page_index = NULL;
7173	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
7174		page_index = &lun->log_pages.index[i];
7175
7176		/* Look for the right page code */
7177		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
7178			continue;
7179
7180		/* Look for the right subpage or the subpage wildcard*/
7181		if (page_index->subpage != subpage)
7182			continue;
7183
7184		break;
7185	}
7186	if (i >= CTL_NUM_LOG_PAGES) {
7187		ctl_set_invalid_field(ctsio,
7188				      /*sks_valid*/ 1,
7189				      /*command*/ 1,
7190				      /*field*/ 2,
7191				      /*bit_valid*/ 0,
7192				      /*bit*/ 0);
7193		ctl_done((union ctl_io *)ctsio);
7194		return (CTL_RETVAL_COMPLETE);
7195	}
7196
7197	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
7198
7199	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7200	ctsio->kern_sg_entries = 0;
7201	ctsio->kern_data_resid = 0;
7202	ctsio->kern_rel_offset = 0;
7203	if (total_len < alloc_len) {
7204		ctsio->residual = alloc_len - total_len;
7205		ctsio->kern_data_len = total_len;
7206		ctsio->kern_total_len = total_len;
7207	} else {
7208		ctsio->residual = 0;
7209		ctsio->kern_data_len = alloc_len;
7210		ctsio->kern_total_len = alloc_len;
7211	}
7212
7213	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7214	header->page = page_index->page_code;
7215	if (page_index->subpage) {
7216		header->page |= SL_SPF;
7217		header->subpage = page_index->subpage;
7218	}
7219	scsi_ulto2b(page_index->page_len, header->datalen);
7220
7221	/*
7222	 * Call the handler, if it exists, to update the
7223	 * page to the latest values.
7224	 */
7225	if (page_index->sense_handler != NULL)
7226		page_index->sense_handler(ctsio, page_index, pc);
7227
7228	memcpy(header + 1, page_index->page_data, page_index->page_len);
7229
7230	ctl_set_success(ctsio);
7231	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7232	ctsio->be_move_done = ctl_config_move_done;
7233	ctl_datamove((union ctl_io *)ctsio);
7234	return (CTL_RETVAL_COMPLETE);
7235}
7236
7237int
7238ctl_read_capacity(struct ctl_scsiio *ctsio)
7239{
7240	struct scsi_read_capacity *cdb;
7241	struct scsi_read_capacity_data *data;
7242	struct ctl_lun *lun;
7243	uint32_t lba;
7244
7245	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7246
7247	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7248
7249	lba = scsi_4btoul(cdb->addr);
7250	if (((cdb->pmi & SRC_PMI) == 0)
7251	 && (lba != 0)) {
7252		ctl_set_invalid_field(/*ctsio*/ ctsio,
7253				      /*sks_valid*/ 1,
7254				      /*command*/ 1,
7255				      /*field*/ 2,
7256				      /*bit_valid*/ 0,
7257				      /*bit*/ 0);
7258		ctl_done((union ctl_io *)ctsio);
7259		return (CTL_RETVAL_COMPLETE);
7260	}
7261
7262	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7263
7264	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7265	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7266	ctsio->residual = 0;
7267	ctsio->kern_data_len = sizeof(*data);
7268	ctsio->kern_total_len = sizeof(*data);
7269	ctsio->kern_data_resid = 0;
7270	ctsio->kern_rel_offset = 0;
7271	ctsio->kern_sg_entries = 0;
7272
7273	/*
7274	 * If the maximum LBA is greater than 0xfffffffe, the user must
7275	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7276	 * serivce action set.
7277	 */
7278	if (lun->be_lun->maxlba > 0xfffffffe)
7279		scsi_ulto4b(0xffffffff, data->addr);
7280	else
7281		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7282
7283	/*
7284	 * XXX KDM this may not be 512 bytes...
7285	 */
7286	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7287
7288	ctl_set_success(ctsio);
7289	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7290	ctsio->be_move_done = ctl_config_move_done;
7291	ctl_datamove((union ctl_io *)ctsio);
7292	return (CTL_RETVAL_COMPLETE);
7293}
7294
7295int
7296ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7297{
7298	struct scsi_read_capacity_16 *cdb;
7299	struct scsi_read_capacity_data_long *data;
7300	struct ctl_lun *lun;
7301	uint64_t lba;
7302	uint32_t alloc_len;
7303
7304	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7305
7306	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7307
7308	alloc_len = scsi_4btoul(cdb->alloc_len);
7309	lba = scsi_8btou64(cdb->addr);
7310
7311	if ((cdb->reladr & SRC16_PMI)
7312	 && (lba != 0)) {
7313		ctl_set_invalid_field(/*ctsio*/ ctsio,
7314				      /*sks_valid*/ 1,
7315				      /*command*/ 1,
7316				      /*field*/ 2,
7317				      /*bit_valid*/ 0,
7318				      /*bit*/ 0);
7319		ctl_done((union ctl_io *)ctsio);
7320		return (CTL_RETVAL_COMPLETE);
7321	}
7322
7323	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7324
7325	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7326	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7327
7328	if (sizeof(*data) < alloc_len) {
7329		ctsio->residual = alloc_len - sizeof(*data);
7330		ctsio->kern_data_len = sizeof(*data);
7331		ctsio->kern_total_len = sizeof(*data);
7332	} else {
7333		ctsio->residual = 0;
7334		ctsio->kern_data_len = alloc_len;
7335		ctsio->kern_total_len = alloc_len;
7336	}
7337	ctsio->kern_data_resid = 0;
7338	ctsio->kern_rel_offset = 0;
7339	ctsio->kern_sg_entries = 0;
7340
7341	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7342	/* XXX KDM this may not be 512 bytes... */
7343	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7344	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7345	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7346	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7347		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7348
7349	ctl_set_success(ctsio);
7350	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7351	ctsio->be_move_done = ctl_config_move_done;
7352	ctl_datamove((union ctl_io *)ctsio);
7353	return (CTL_RETVAL_COMPLETE);
7354}
7355
7356int
7357ctl_get_lba_status(struct ctl_scsiio *ctsio)
7358{
7359	struct scsi_get_lba_status *cdb;
7360	struct scsi_get_lba_status_data *data;
7361	struct ctl_lun *lun;
7362	struct ctl_lba_len_flags *lbalen;
7363	uint64_t lba;
7364	uint32_t alloc_len, total_len;
7365	int retval;
7366
7367	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7368
7369	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7370	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7371	lba = scsi_8btou64(cdb->addr);
7372	alloc_len = scsi_4btoul(cdb->alloc_len);
7373
7374	if (lba > lun->be_lun->maxlba) {
7375		ctl_set_lba_out_of_range(ctsio);
7376		ctl_done((union ctl_io *)ctsio);
7377		return (CTL_RETVAL_COMPLETE);
7378	}
7379
7380	total_len = sizeof(*data) + sizeof(data->descr[0]);
7381	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7382	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7383
7384	if (total_len < alloc_len) {
7385		ctsio->residual = alloc_len - total_len;
7386		ctsio->kern_data_len = total_len;
7387		ctsio->kern_total_len = total_len;
7388	} else {
7389		ctsio->residual = 0;
7390		ctsio->kern_data_len = alloc_len;
7391		ctsio->kern_total_len = alloc_len;
7392	}
7393	ctsio->kern_data_resid = 0;
7394	ctsio->kern_rel_offset = 0;
7395	ctsio->kern_sg_entries = 0;
7396
7397	/* Fill dummy data in case backend can't tell anything. */
7398	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7399	scsi_u64to8b(lba, data->descr[0].addr);
7400	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7401	    data->descr[0].length);
7402	data->descr[0].status = 0; /* Mapped or unknown. */
7403
7404	ctl_set_success(ctsio);
7405	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7406	ctsio->be_move_done = ctl_config_move_done;
7407
7408	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7409	lbalen->lba = lba;
7410	lbalen->len = total_len;
7411	lbalen->flags = 0;
7412	retval = lun->backend->config_read((union ctl_io *)ctsio);
7413	return (CTL_RETVAL_COMPLETE);
7414}
7415
7416int
7417ctl_read_defect(struct ctl_scsiio *ctsio)
7418{
7419	struct scsi_read_defect_data_10 *ccb10;
7420	struct scsi_read_defect_data_12 *ccb12;
7421	struct scsi_read_defect_data_hdr_10 *data10;
7422	struct scsi_read_defect_data_hdr_12 *data12;
7423	uint32_t alloc_len, data_len;
7424	uint8_t format;
7425
7426	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7427
7428	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7429		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7430		format = ccb10->format;
7431		alloc_len = scsi_2btoul(ccb10->alloc_length);
7432		data_len = sizeof(*data10);
7433	} else {
7434		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7435		format = ccb12->format;
7436		alloc_len = scsi_4btoul(ccb12->alloc_length);
7437		data_len = sizeof(*data12);
7438	}
7439	if (alloc_len == 0) {
7440		ctl_set_success(ctsio);
7441		ctl_done((union ctl_io *)ctsio);
7442		return (CTL_RETVAL_COMPLETE);
7443	}
7444
7445	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7446	if (data_len < alloc_len) {
7447		ctsio->residual = alloc_len - data_len;
7448		ctsio->kern_data_len = data_len;
7449		ctsio->kern_total_len = data_len;
7450	} else {
7451		ctsio->residual = 0;
7452		ctsio->kern_data_len = alloc_len;
7453		ctsio->kern_total_len = alloc_len;
7454	}
7455	ctsio->kern_data_resid = 0;
7456	ctsio->kern_rel_offset = 0;
7457	ctsio->kern_sg_entries = 0;
7458
7459	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7460		data10 = (struct scsi_read_defect_data_hdr_10 *)
7461		    ctsio->kern_data_ptr;
7462		data10->format = format;
7463		scsi_ulto2b(0, data10->length);
7464	} else {
7465		data12 = (struct scsi_read_defect_data_hdr_12 *)
7466		    ctsio->kern_data_ptr;
7467		data12->format = format;
7468		scsi_ulto2b(0, data12->generation);
7469		scsi_ulto4b(0, data12->length);
7470	}
7471
7472	ctl_set_success(ctsio);
7473	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7474	ctsio->be_move_done = ctl_config_move_done;
7475	ctl_datamove((union ctl_io *)ctsio);
7476	return (CTL_RETVAL_COMPLETE);
7477}
7478
7479int
7480ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7481{
7482	struct scsi_maintenance_in *cdb;
7483	int retval;
7484	int alloc_len, ext, total_len = 0, g, p, pc, pg, gs, os;
7485	int num_target_port_groups, num_target_ports;
7486	struct ctl_lun *lun;
7487	struct ctl_softc *softc;
7488	struct ctl_port *port;
7489	struct scsi_target_group_data *rtg_ptr;
7490	struct scsi_target_group_data_extended *rtg_ext_ptr;
7491	struct scsi_target_port_group_descriptor *tpg_desc;
7492
7493	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7494
7495	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7496	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7497	softc = lun->ctl_softc;
7498
7499	retval = CTL_RETVAL_COMPLETE;
7500
7501	switch (cdb->byte2 & STG_PDF_MASK) {
7502	case STG_PDF_LENGTH:
7503		ext = 0;
7504		break;
7505	case STG_PDF_EXTENDED:
7506		ext = 1;
7507		break;
7508	default:
7509		ctl_set_invalid_field(/*ctsio*/ ctsio,
7510				      /*sks_valid*/ 1,
7511				      /*command*/ 1,
7512				      /*field*/ 2,
7513				      /*bit_valid*/ 1,
7514				      /*bit*/ 5);
7515		ctl_done((union ctl_io *)ctsio);
7516		return(retval);
7517	}
7518
7519	if (softc->is_single)
7520		num_target_port_groups = 1;
7521	else
7522		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7523	num_target_ports = 0;
7524	mtx_lock(&softc->ctl_lock);
7525	STAILQ_FOREACH(port, &softc->port_list, links) {
7526		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7527			continue;
7528		if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7529			continue;
7530		num_target_ports++;
7531	}
7532	mtx_unlock(&softc->ctl_lock);
7533
7534	if (ext)
7535		total_len = sizeof(struct scsi_target_group_data_extended);
7536	else
7537		total_len = sizeof(struct scsi_target_group_data);
7538	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7539		num_target_port_groups +
7540	    sizeof(struct scsi_target_port_descriptor) *
7541		num_target_ports * num_target_port_groups;
7542
7543	alloc_len = scsi_4btoul(cdb->length);
7544
7545	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7546
7547	ctsio->kern_sg_entries = 0;
7548
7549	if (total_len < alloc_len) {
7550		ctsio->residual = alloc_len - total_len;
7551		ctsio->kern_data_len = total_len;
7552		ctsio->kern_total_len = total_len;
7553	} else {
7554		ctsio->residual = 0;
7555		ctsio->kern_data_len = alloc_len;
7556		ctsio->kern_total_len = alloc_len;
7557	}
7558	ctsio->kern_data_resid = 0;
7559	ctsio->kern_rel_offset = 0;
7560
7561	if (ext) {
7562		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7563		    ctsio->kern_data_ptr;
7564		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7565		rtg_ext_ptr->format_type = 0x10;
7566		rtg_ext_ptr->implicit_transition_time = 0;
7567		tpg_desc = &rtg_ext_ptr->groups[0];
7568	} else {
7569		rtg_ptr = (struct scsi_target_group_data *)
7570		    ctsio->kern_data_ptr;
7571		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7572		tpg_desc = &rtg_ptr->groups[0];
7573	}
7574
7575	mtx_lock(&softc->ctl_lock);
7576	pg = softc->port_offset / CTL_MAX_PORTS;
7577	if (softc->flags & CTL_FLAG_ACTIVE_SHELF) {
7578		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY) {
7579			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7580			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7581		} else if (lun->flags & CTL_LUN_PRIMARY_SC) {
7582			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7583			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7584		} else {
7585			gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7586			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7587		}
7588	} else {
7589		gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7590		os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7591	}
7592	for (g = 0; g < num_target_port_groups; g++) {
7593		tpg_desc->pref_state = (g == pg) ? gs : os;
7594		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP;
7595		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7596		tpg_desc->status = TPG_IMPLICIT;
7597		pc = 0;
7598		STAILQ_FOREACH(port, &softc->port_list, links) {
7599			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7600				continue;
7601			if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7602				continue;
7603			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7604			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7605			    relative_target_port_identifier);
7606			pc++;
7607		}
7608		tpg_desc->target_port_count = pc;
7609		tpg_desc = (struct scsi_target_port_group_descriptor *)
7610		    &tpg_desc->descriptors[pc];
7611	}
7612	mtx_unlock(&softc->ctl_lock);
7613
7614	ctl_set_success(ctsio);
7615	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7616	ctsio->be_move_done = ctl_config_move_done;
7617	ctl_datamove((union ctl_io *)ctsio);
7618	return(retval);
7619}
7620
7621int
7622ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7623{
7624	struct ctl_lun *lun;
7625	struct scsi_report_supported_opcodes *cdb;
7626	const struct ctl_cmd_entry *entry, *sentry;
7627	struct scsi_report_supported_opcodes_all *all;
7628	struct scsi_report_supported_opcodes_descr *descr;
7629	struct scsi_report_supported_opcodes_one *one;
7630	int retval;
7631	int alloc_len, total_len;
7632	int opcode, service_action, i, j, num;
7633
7634	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7635
7636	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7637	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7638
7639	retval = CTL_RETVAL_COMPLETE;
7640
7641	opcode = cdb->requested_opcode;
7642	service_action = scsi_2btoul(cdb->requested_service_action);
7643	switch (cdb->options & RSO_OPTIONS_MASK) {
7644	case RSO_OPTIONS_ALL:
7645		num = 0;
7646		for (i = 0; i < 256; i++) {
7647			entry = &ctl_cmd_table[i];
7648			if (entry->flags & CTL_CMD_FLAG_SA5) {
7649				for (j = 0; j < 32; j++) {
7650					sentry = &((const struct ctl_cmd_entry *)
7651					    entry->execute)[j];
7652					if (ctl_cmd_applicable(
7653					    lun->be_lun->lun_type, sentry))
7654						num++;
7655				}
7656			} else {
7657				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7658				    entry))
7659					num++;
7660			}
7661		}
7662		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7663		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7664		break;
7665	case RSO_OPTIONS_OC:
7666		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7667			ctl_set_invalid_field(/*ctsio*/ ctsio,
7668					      /*sks_valid*/ 1,
7669					      /*command*/ 1,
7670					      /*field*/ 2,
7671					      /*bit_valid*/ 1,
7672					      /*bit*/ 2);
7673			ctl_done((union ctl_io *)ctsio);
7674			return (CTL_RETVAL_COMPLETE);
7675		}
7676		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7677		break;
7678	case RSO_OPTIONS_OC_SA:
7679		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7680		    service_action >= 32) {
7681			ctl_set_invalid_field(/*ctsio*/ ctsio,
7682					      /*sks_valid*/ 1,
7683					      /*command*/ 1,
7684					      /*field*/ 2,
7685					      /*bit_valid*/ 1,
7686					      /*bit*/ 2);
7687			ctl_done((union ctl_io *)ctsio);
7688			return (CTL_RETVAL_COMPLETE);
7689		}
7690		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7691		break;
7692	default:
7693		ctl_set_invalid_field(/*ctsio*/ ctsio,
7694				      /*sks_valid*/ 1,
7695				      /*command*/ 1,
7696				      /*field*/ 2,
7697				      /*bit_valid*/ 1,
7698				      /*bit*/ 2);
7699		ctl_done((union ctl_io *)ctsio);
7700		return (CTL_RETVAL_COMPLETE);
7701	}
7702
7703	alloc_len = scsi_4btoul(cdb->length);
7704
7705	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7706
7707	ctsio->kern_sg_entries = 0;
7708
7709	if (total_len < alloc_len) {
7710		ctsio->residual = alloc_len - total_len;
7711		ctsio->kern_data_len = total_len;
7712		ctsio->kern_total_len = total_len;
7713	} else {
7714		ctsio->residual = 0;
7715		ctsio->kern_data_len = alloc_len;
7716		ctsio->kern_total_len = alloc_len;
7717	}
7718	ctsio->kern_data_resid = 0;
7719	ctsio->kern_rel_offset = 0;
7720
7721	switch (cdb->options & RSO_OPTIONS_MASK) {
7722	case RSO_OPTIONS_ALL:
7723		all = (struct scsi_report_supported_opcodes_all *)
7724		    ctsio->kern_data_ptr;
7725		num = 0;
7726		for (i = 0; i < 256; i++) {
7727			entry = &ctl_cmd_table[i];
7728			if (entry->flags & CTL_CMD_FLAG_SA5) {
7729				for (j = 0; j < 32; j++) {
7730					sentry = &((const struct ctl_cmd_entry *)
7731					    entry->execute)[j];
7732					if (!ctl_cmd_applicable(
7733					    lun->be_lun->lun_type, sentry))
7734						continue;
7735					descr = &all->descr[num++];
7736					descr->opcode = i;
7737					scsi_ulto2b(j, descr->service_action);
7738					descr->flags = RSO_SERVACTV;
7739					scsi_ulto2b(sentry->length,
7740					    descr->cdb_length);
7741				}
7742			} else {
7743				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7744				    entry))
7745					continue;
7746				descr = &all->descr[num++];
7747				descr->opcode = i;
7748				scsi_ulto2b(0, descr->service_action);
7749				descr->flags = 0;
7750				scsi_ulto2b(entry->length, descr->cdb_length);
7751			}
7752		}
7753		scsi_ulto4b(
7754		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7755		    all->length);
7756		break;
7757	case RSO_OPTIONS_OC:
7758		one = (struct scsi_report_supported_opcodes_one *)
7759		    ctsio->kern_data_ptr;
7760		entry = &ctl_cmd_table[opcode];
7761		goto fill_one;
7762	case RSO_OPTIONS_OC_SA:
7763		one = (struct scsi_report_supported_opcodes_one *)
7764		    ctsio->kern_data_ptr;
7765		entry = &ctl_cmd_table[opcode];
7766		entry = &((const struct ctl_cmd_entry *)
7767		    entry->execute)[service_action];
7768fill_one:
7769		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7770			one->support = 3;
7771			scsi_ulto2b(entry->length, one->cdb_length);
7772			one->cdb_usage[0] = opcode;
7773			memcpy(&one->cdb_usage[1], entry->usage,
7774			    entry->length - 1);
7775		} else
7776			one->support = 1;
7777		break;
7778	}
7779
7780	ctl_set_success(ctsio);
7781	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7782	ctsio->be_move_done = ctl_config_move_done;
7783	ctl_datamove((union ctl_io *)ctsio);
7784	return(retval);
7785}
7786
7787int
7788ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7789{
7790	struct scsi_report_supported_tmf *cdb;
7791	struct scsi_report_supported_tmf_data *data;
7792	int retval;
7793	int alloc_len, total_len;
7794
7795	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7796
7797	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7798
7799	retval = CTL_RETVAL_COMPLETE;
7800
7801	total_len = sizeof(struct scsi_report_supported_tmf_data);
7802	alloc_len = scsi_4btoul(cdb->length);
7803
7804	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7805
7806	ctsio->kern_sg_entries = 0;
7807
7808	if (total_len < alloc_len) {
7809		ctsio->residual = alloc_len - total_len;
7810		ctsio->kern_data_len = total_len;
7811		ctsio->kern_total_len = total_len;
7812	} else {
7813		ctsio->residual = 0;
7814		ctsio->kern_data_len = alloc_len;
7815		ctsio->kern_total_len = alloc_len;
7816	}
7817	ctsio->kern_data_resid = 0;
7818	ctsio->kern_rel_offset = 0;
7819
7820	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7821	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7822	data->byte2 |= RST_ITNRS;
7823
7824	ctl_set_success(ctsio);
7825	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7826	ctsio->be_move_done = ctl_config_move_done;
7827	ctl_datamove((union ctl_io *)ctsio);
7828	return (retval);
7829}
7830
7831int
7832ctl_report_timestamp(struct ctl_scsiio *ctsio)
7833{
7834	struct scsi_report_timestamp *cdb;
7835	struct scsi_report_timestamp_data *data;
7836	struct timeval tv;
7837	int64_t timestamp;
7838	int retval;
7839	int alloc_len, total_len;
7840
7841	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7842
7843	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7844
7845	retval = CTL_RETVAL_COMPLETE;
7846
7847	total_len = sizeof(struct scsi_report_timestamp_data);
7848	alloc_len = scsi_4btoul(cdb->length);
7849
7850	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7851
7852	ctsio->kern_sg_entries = 0;
7853
7854	if (total_len < alloc_len) {
7855		ctsio->residual = alloc_len - total_len;
7856		ctsio->kern_data_len = total_len;
7857		ctsio->kern_total_len = total_len;
7858	} else {
7859		ctsio->residual = 0;
7860		ctsio->kern_data_len = alloc_len;
7861		ctsio->kern_total_len = alloc_len;
7862	}
7863	ctsio->kern_data_resid = 0;
7864	ctsio->kern_rel_offset = 0;
7865
7866	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7867	scsi_ulto2b(sizeof(*data) - 2, data->length);
7868	data->origin = RTS_ORIG_OUTSIDE;
7869	getmicrotime(&tv);
7870	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7871	scsi_ulto4b(timestamp >> 16, data->timestamp);
7872	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7873
7874	ctl_set_success(ctsio);
7875	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7876	ctsio->be_move_done = ctl_config_move_done;
7877	ctl_datamove((union ctl_io *)ctsio);
7878	return (retval);
7879}
7880
7881int
7882ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7883{
7884	struct scsi_per_res_in *cdb;
7885	int alloc_len, total_len = 0;
7886	/* struct scsi_per_res_in_rsrv in_data; */
7887	struct ctl_lun *lun;
7888	struct ctl_softc *softc;
7889	uint64_t key;
7890
7891	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7892
7893	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7894
7895	alloc_len = scsi_2btoul(cdb->length);
7896
7897	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7898	softc = lun->ctl_softc;
7899
7900retry:
7901	mtx_lock(&lun->lun_lock);
7902	switch (cdb->action) {
7903	case SPRI_RK: /* read keys */
7904		total_len = sizeof(struct scsi_per_res_in_keys) +
7905			lun->pr_key_count *
7906			sizeof(struct scsi_per_res_key);
7907		break;
7908	case SPRI_RR: /* read reservation */
7909		if (lun->flags & CTL_LUN_PR_RESERVED)
7910			total_len = sizeof(struct scsi_per_res_in_rsrv);
7911		else
7912			total_len = sizeof(struct scsi_per_res_in_header);
7913		break;
7914	case SPRI_RC: /* report capabilities */
7915		total_len = sizeof(struct scsi_per_res_cap);
7916		break;
7917	case SPRI_RS: /* read full status */
7918		total_len = sizeof(struct scsi_per_res_in_header) +
7919		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7920		    lun->pr_key_count;
7921		break;
7922	default:
7923		panic("Invalid PR type %x", cdb->action);
7924	}
7925	mtx_unlock(&lun->lun_lock);
7926
7927	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7928
7929	if (total_len < alloc_len) {
7930		ctsio->residual = alloc_len - total_len;
7931		ctsio->kern_data_len = total_len;
7932		ctsio->kern_total_len = total_len;
7933	} else {
7934		ctsio->residual = 0;
7935		ctsio->kern_data_len = alloc_len;
7936		ctsio->kern_total_len = alloc_len;
7937	}
7938
7939	ctsio->kern_data_resid = 0;
7940	ctsio->kern_rel_offset = 0;
7941	ctsio->kern_sg_entries = 0;
7942
7943	mtx_lock(&lun->lun_lock);
7944	switch (cdb->action) {
7945	case SPRI_RK: { // read keys
7946        struct scsi_per_res_in_keys *res_keys;
7947		int i, key_count;
7948
7949		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7950
7951		/*
7952		 * We had to drop the lock to allocate our buffer, which
7953		 * leaves time for someone to come in with another
7954		 * persistent reservation.  (That is unlikely, though,
7955		 * since this should be the only persistent reservation
7956		 * command active right now.)
7957		 */
7958		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7959		    (lun->pr_key_count *
7960		     sizeof(struct scsi_per_res_key)))){
7961			mtx_unlock(&lun->lun_lock);
7962			free(ctsio->kern_data_ptr, M_CTL);
7963			printf("%s: reservation length changed, retrying\n",
7964			       __func__);
7965			goto retry;
7966		}
7967
7968		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7969
7970		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7971			     lun->pr_key_count, res_keys->header.length);
7972
7973		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7974			if ((key = ctl_get_prkey(lun, i)) == 0)
7975				continue;
7976
7977			/*
7978			 * We used lun->pr_key_count to calculate the
7979			 * size to allocate.  If it turns out the number of
7980			 * initiators with the registered flag set is
7981			 * larger than that (i.e. they haven't been kept in
7982			 * sync), we've got a problem.
7983			 */
7984			if (key_count >= lun->pr_key_count) {
7985#ifdef NEEDTOPORT
7986				csevent_log(CSC_CTL | CSC_SHELF_SW |
7987					    CTL_PR_ERROR,
7988					    csevent_LogType_Fault,
7989					    csevent_AlertLevel_Yellow,
7990					    csevent_FRU_ShelfController,
7991					    csevent_FRU_Firmware,
7992				        csevent_FRU_Unknown,
7993					    "registered keys %d >= key "
7994					    "count %d", key_count,
7995					    lun->pr_key_count);
7996#endif
7997				key_count++;
7998				continue;
7999			}
8000			scsi_u64to8b(key, res_keys->keys[key_count].key);
8001			key_count++;
8002		}
8003		break;
8004	}
8005	case SPRI_RR: { // read reservation
8006		struct scsi_per_res_in_rsrv *res;
8007		int tmp_len, header_only;
8008
8009		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
8010
8011		scsi_ulto4b(lun->PRGeneration, res->header.generation);
8012
8013		if (lun->flags & CTL_LUN_PR_RESERVED)
8014		{
8015			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
8016			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
8017				    res->header.length);
8018			header_only = 0;
8019		} else {
8020			tmp_len = sizeof(struct scsi_per_res_in_header);
8021			scsi_ulto4b(0, res->header.length);
8022			header_only = 1;
8023		}
8024
8025		/*
8026		 * We had to drop the lock to allocate our buffer, which
8027		 * leaves time for someone to come in with another
8028		 * persistent reservation.  (That is unlikely, though,
8029		 * since this should be the only persistent reservation
8030		 * command active right now.)
8031		 */
8032		if (tmp_len != total_len) {
8033			mtx_unlock(&lun->lun_lock);
8034			free(ctsio->kern_data_ptr, M_CTL);
8035			printf("%s: reservation status changed, retrying\n",
8036			       __func__);
8037			goto retry;
8038		}
8039
8040		/*
8041		 * No reservation held, so we're done.
8042		 */
8043		if (header_only != 0)
8044			break;
8045
8046		/*
8047		 * If the registration is an All Registrants type, the key
8048		 * is 0, since it doesn't really matter.
8049		 */
8050		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8051			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
8052			    res->data.reservation);
8053		}
8054		res->data.scopetype = lun->res_type;
8055		break;
8056	}
8057	case SPRI_RC:     //report capabilities
8058	{
8059		struct scsi_per_res_cap *res_cap;
8060		uint16_t type_mask;
8061
8062		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
8063		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
8064		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
8065		type_mask = SPRI_TM_WR_EX_AR |
8066			    SPRI_TM_EX_AC_RO |
8067			    SPRI_TM_WR_EX_RO |
8068			    SPRI_TM_EX_AC |
8069			    SPRI_TM_WR_EX |
8070			    SPRI_TM_EX_AC_AR;
8071		scsi_ulto2b(type_mask, res_cap->type_mask);
8072		break;
8073	}
8074	case SPRI_RS: { // read full status
8075		struct scsi_per_res_in_full *res_status;
8076		struct scsi_per_res_in_full_desc *res_desc;
8077		struct ctl_port *port;
8078		int i, len;
8079
8080		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
8081
8082		/*
8083		 * We had to drop the lock to allocate our buffer, which
8084		 * leaves time for someone to come in with another
8085		 * persistent reservation.  (That is unlikely, though,
8086		 * since this should be the only persistent reservation
8087		 * command active right now.)
8088		 */
8089		if (total_len < (sizeof(struct scsi_per_res_in_header) +
8090		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
8091		     lun->pr_key_count)){
8092			mtx_unlock(&lun->lun_lock);
8093			free(ctsio->kern_data_ptr, M_CTL);
8094			printf("%s: reservation length changed, retrying\n",
8095			       __func__);
8096			goto retry;
8097		}
8098
8099		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
8100
8101		res_desc = &res_status->desc[0];
8102		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
8103			if ((key = ctl_get_prkey(lun, i)) == 0)
8104				continue;
8105
8106			scsi_u64to8b(key, res_desc->res_key.key);
8107			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
8108			    (lun->pr_res_idx == i ||
8109			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
8110				res_desc->flags = SPRI_FULL_R_HOLDER;
8111				res_desc->scopetype = lun->res_type;
8112			}
8113			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
8114			    res_desc->rel_trgt_port_id);
8115			len = 0;
8116			port = softc->ctl_ports[
8117			    ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
8118			if (port != NULL)
8119				len = ctl_create_iid(port,
8120				    i % CTL_MAX_INIT_PER_PORT,
8121				    res_desc->transport_id);
8122			scsi_ulto4b(len, res_desc->additional_length);
8123			res_desc = (struct scsi_per_res_in_full_desc *)
8124			    &res_desc->transport_id[len];
8125		}
8126		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
8127		    res_status->header.length);
8128		break;
8129	}
8130	default:
8131		/*
8132		 * This is a bug, because we just checked for this above,
8133		 * and should have returned an error.
8134		 */
8135		panic("Invalid PR type %x", cdb->action);
8136		break; /* NOTREACHED */
8137	}
8138	mtx_unlock(&lun->lun_lock);
8139
8140	ctl_set_success(ctsio);
8141	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8142	ctsio->be_move_done = ctl_config_move_done;
8143	ctl_datamove((union ctl_io *)ctsio);
8144	return (CTL_RETVAL_COMPLETE);
8145}
8146
8147static void
8148ctl_est_res_ua(struct ctl_lun *lun, uint32_t residx, ctl_ua_type ua)
8149{
8150	int off = lun->ctl_softc->persis_offset;
8151
8152	if (residx >= off && residx < off + CTL_MAX_INITIATORS)
8153		ctl_est_ua(lun, residx - off, ua);
8154}
8155
8156/*
8157 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
8158 * it should return.
8159 */
8160static int
8161ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
8162		uint64_t sa_res_key, uint8_t type, uint32_t residx,
8163		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
8164		struct scsi_per_res_out_parms* param)
8165{
8166	union ctl_ha_msg persis_io;
8167	int retval, i;
8168	int isc_retval;
8169
8170	retval = 0;
8171
8172	mtx_lock(&lun->lun_lock);
8173	if (sa_res_key == 0) {
8174		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8175			/* validate scope and type */
8176			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8177			     SPR_LU_SCOPE) {
8178				mtx_unlock(&lun->lun_lock);
8179				ctl_set_invalid_field(/*ctsio*/ ctsio,
8180						      /*sks_valid*/ 1,
8181						      /*command*/ 1,
8182						      /*field*/ 2,
8183						      /*bit_valid*/ 1,
8184						      /*bit*/ 4);
8185				ctl_done((union ctl_io *)ctsio);
8186				return (1);
8187			}
8188
8189		        if (type>8 || type==2 || type==4 || type==0) {
8190				mtx_unlock(&lun->lun_lock);
8191				ctl_set_invalid_field(/*ctsio*/ ctsio,
8192       	           				      /*sks_valid*/ 1,
8193						      /*command*/ 1,
8194						      /*field*/ 2,
8195						      /*bit_valid*/ 1,
8196						      /*bit*/ 0);
8197				ctl_done((union ctl_io *)ctsio);
8198				return (1);
8199		        }
8200
8201			/*
8202			 * Unregister everybody else and build UA for
8203			 * them
8204			 */
8205			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8206				if (i == residx || ctl_get_prkey(lun, i) == 0)
8207					continue;
8208
8209				ctl_clr_prkey(lun, i);
8210				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8211			}
8212			lun->pr_key_count = 1;
8213			lun->res_type = type;
8214			if (lun->res_type != SPR_TYPE_WR_EX_AR
8215			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8216				lun->pr_res_idx = residx;
8217
8218			/* send msg to other side */
8219			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8220			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8221			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8222			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8223			persis_io.pr.pr_info.res_type = type;
8224			memcpy(persis_io.pr.pr_info.sa_res_key,
8225			       param->serv_act_res_key,
8226			       sizeof(param->serv_act_res_key));
8227			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8228			     &persis_io, sizeof(persis_io), 0)) >
8229			     CTL_HA_STATUS_SUCCESS) {
8230				printf("CTL:Persis Out error returned "
8231				       "from ctl_ha_msg_send %d\n",
8232				       isc_retval);
8233			}
8234		} else {
8235			/* not all registrants */
8236			mtx_unlock(&lun->lun_lock);
8237			free(ctsio->kern_data_ptr, M_CTL);
8238			ctl_set_invalid_field(ctsio,
8239					      /*sks_valid*/ 1,
8240					      /*command*/ 0,
8241					      /*field*/ 8,
8242					      /*bit_valid*/ 0,
8243					      /*bit*/ 0);
8244			ctl_done((union ctl_io *)ctsio);
8245			return (1);
8246		}
8247	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8248		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8249		int found = 0;
8250
8251		if (res_key == sa_res_key) {
8252			/* special case */
8253			/*
8254			 * The spec implies this is not good but doesn't
8255			 * say what to do. There are two choices either
8256			 * generate a res conflict or check condition
8257			 * with illegal field in parameter data. Since
8258			 * that is what is done when the sa_res_key is
8259			 * zero I'll take that approach since this has
8260			 * to do with the sa_res_key.
8261			 */
8262			mtx_unlock(&lun->lun_lock);
8263			free(ctsio->kern_data_ptr, M_CTL);
8264			ctl_set_invalid_field(ctsio,
8265					      /*sks_valid*/ 1,
8266					      /*command*/ 0,
8267					      /*field*/ 8,
8268					      /*bit_valid*/ 0,
8269					      /*bit*/ 0);
8270			ctl_done((union ctl_io *)ctsio);
8271			return (1);
8272		}
8273
8274		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8275			if (ctl_get_prkey(lun, i) != sa_res_key)
8276				continue;
8277
8278			found = 1;
8279			ctl_clr_prkey(lun, i);
8280			lun->pr_key_count--;
8281			ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8282		}
8283		if (!found) {
8284			mtx_unlock(&lun->lun_lock);
8285			free(ctsio->kern_data_ptr, M_CTL);
8286			ctl_set_reservation_conflict(ctsio);
8287			ctl_done((union ctl_io *)ctsio);
8288			return (CTL_RETVAL_COMPLETE);
8289		}
8290		/* send msg to other side */
8291		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8292		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8293		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8294		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8295		persis_io.pr.pr_info.res_type = type;
8296		memcpy(persis_io.pr.pr_info.sa_res_key,
8297		       param->serv_act_res_key,
8298		       sizeof(param->serv_act_res_key));
8299		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8300		     &persis_io, sizeof(persis_io), 0)) >
8301		     CTL_HA_STATUS_SUCCESS) {
8302			printf("CTL:Persis Out error returned from "
8303			       "ctl_ha_msg_send %d\n", isc_retval);
8304		}
8305	} else {
8306		/* Reserved but not all registrants */
8307		/* sa_res_key is res holder */
8308		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
8309			/* validate scope and type */
8310			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8311			     SPR_LU_SCOPE) {
8312				mtx_unlock(&lun->lun_lock);
8313				ctl_set_invalid_field(/*ctsio*/ ctsio,
8314						      /*sks_valid*/ 1,
8315						      /*command*/ 1,
8316						      /*field*/ 2,
8317						      /*bit_valid*/ 1,
8318						      /*bit*/ 4);
8319				ctl_done((union ctl_io *)ctsio);
8320				return (1);
8321			}
8322
8323			if (type>8 || type==2 || type==4 || type==0) {
8324				mtx_unlock(&lun->lun_lock);
8325				ctl_set_invalid_field(/*ctsio*/ ctsio,
8326						      /*sks_valid*/ 1,
8327						      /*command*/ 1,
8328						      /*field*/ 2,
8329						      /*bit_valid*/ 1,
8330						      /*bit*/ 0);
8331				ctl_done((union ctl_io *)ctsio);
8332				return (1);
8333			}
8334
8335			/*
8336			 * Do the following:
8337			 * if sa_res_key != res_key remove all
8338			 * registrants w/sa_res_key and generate UA
8339			 * for these registrants(Registrations
8340			 * Preempted) if it wasn't an exclusive
8341			 * reservation generate UA(Reservations
8342			 * Preempted) for all other registered nexuses
8343			 * if the type has changed. Establish the new
8344			 * reservation and holder. If res_key and
8345			 * sa_res_key are the same do the above
8346			 * except don't unregister the res holder.
8347			 */
8348
8349			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8350				if (i == residx || ctl_get_prkey(lun, i) == 0)
8351					continue;
8352
8353				if (sa_res_key == ctl_get_prkey(lun, i)) {
8354					ctl_clr_prkey(lun, i);
8355					lun->pr_key_count--;
8356					ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8357				} else if (type != lun->res_type
8358					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8359					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8360					ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
8361				}
8362			}
8363			lun->res_type = type;
8364			if (lun->res_type != SPR_TYPE_WR_EX_AR
8365			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8366				lun->pr_res_idx = residx;
8367			else
8368				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8369
8370			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8371			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8372			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8373			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8374			persis_io.pr.pr_info.res_type = type;
8375			memcpy(persis_io.pr.pr_info.sa_res_key,
8376			       param->serv_act_res_key,
8377			       sizeof(param->serv_act_res_key));
8378			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8379			     &persis_io, sizeof(persis_io), 0)) >
8380			     CTL_HA_STATUS_SUCCESS) {
8381				printf("CTL:Persis Out error returned "
8382				       "from ctl_ha_msg_send %d\n",
8383				       isc_retval);
8384			}
8385		} else {
8386			/*
8387			 * sa_res_key is not the res holder just
8388			 * remove registrants
8389			 */
8390			int found=0;
8391
8392			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8393				if (sa_res_key != ctl_get_prkey(lun, i))
8394					continue;
8395
8396				found = 1;
8397				ctl_clr_prkey(lun, i);
8398				lun->pr_key_count--;
8399				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8400			}
8401
8402			if (!found) {
8403				mtx_unlock(&lun->lun_lock);
8404				free(ctsio->kern_data_ptr, M_CTL);
8405				ctl_set_reservation_conflict(ctsio);
8406				ctl_done((union ctl_io *)ctsio);
8407		        	return (1);
8408			}
8409			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8410			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8411			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8412			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8413			persis_io.pr.pr_info.res_type = type;
8414			memcpy(persis_io.pr.pr_info.sa_res_key,
8415			       param->serv_act_res_key,
8416			       sizeof(param->serv_act_res_key));
8417			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8418			     &persis_io, sizeof(persis_io), 0)) >
8419			     CTL_HA_STATUS_SUCCESS) {
8420				printf("CTL:Persis Out error returned "
8421				       "from ctl_ha_msg_send %d\n",
8422				isc_retval);
8423			}
8424		}
8425	}
8426
8427	lun->PRGeneration++;
8428	mtx_unlock(&lun->lun_lock);
8429
8430	return (retval);
8431}
8432
8433static void
8434ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8435{
8436	uint64_t sa_res_key;
8437	int i;
8438
8439	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8440
8441	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8442	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8443	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8444		if (sa_res_key == 0) {
8445			/*
8446			 * Unregister everybody else and build UA for
8447			 * them
8448			 */
8449			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8450				if (i == msg->pr.pr_info.residx ||
8451				    ctl_get_prkey(lun, i) == 0)
8452					continue;
8453
8454				ctl_clr_prkey(lun, i);
8455				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8456			}
8457
8458			lun->pr_key_count = 1;
8459			lun->res_type = msg->pr.pr_info.res_type;
8460			if (lun->res_type != SPR_TYPE_WR_EX_AR
8461			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8462				lun->pr_res_idx = msg->pr.pr_info.residx;
8463		} else {
8464		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8465				if (sa_res_key == ctl_get_prkey(lun, i))
8466					continue;
8467
8468				ctl_clr_prkey(lun, i);
8469				lun->pr_key_count--;
8470				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8471			}
8472		}
8473	} else {
8474		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8475			if (i == msg->pr.pr_info.residx ||
8476			    ctl_get_prkey(lun, i) == 0)
8477				continue;
8478
8479			if (sa_res_key == ctl_get_prkey(lun, i)) {
8480				ctl_clr_prkey(lun, i);
8481				lun->pr_key_count--;
8482				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8483			} else if (msg->pr.pr_info.res_type != lun->res_type
8484				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8485				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8486				ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
8487			}
8488		}
8489		lun->res_type = msg->pr.pr_info.res_type;
8490		if (lun->res_type != SPR_TYPE_WR_EX_AR
8491		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8492			lun->pr_res_idx = msg->pr.pr_info.residx;
8493		else
8494			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8495	}
8496	lun->PRGeneration++;
8497
8498}
8499
8500
8501int
8502ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8503{
8504	int retval;
8505	int isc_retval;
8506	u_int32_t param_len;
8507	struct scsi_per_res_out *cdb;
8508	struct ctl_lun *lun;
8509	struct scsi_per_res_out_parms* param;
8510	struct ctl_softc *softc;
8511	uint32_t residx;
8512	uint64_t res_key, sa_res_key, key;
8513	uint8_t type;
8514	union ctl_ha_msg persis_io;
8515	int    i;
8516
8517	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8518
8519	retval = CTL_RETVAL_COMPLETE;
8520
8521	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8522	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8523	softc = lun->ctl_softc;
8524
8525	/*
8526	 * We only support whole-LUN scope.  The scope & type are ignored for
8527	 * register, register and ignore existing key and clear.
8528	 * We sometimes ignore scope and type on preempts too!!
8529	 * Verify reservation type here as well.
8530	 */
8531	type = cdb->scope_type & SPR_TYPE_MASK;
8532	if ((cdb->action == SPRO_RESERVE)
8533	 || (cdb->action == SPRO_RELEASE)) {
8534		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8535			ctl_set_invalid_field(/*ctsio*/ ctsio,
8536					      /*sks_valid*/ 1,
8537					      /*command*/ 1,
8538					      /*field*/ 2,
8539					      /*bit_valid*/ 1,
8540					      /*bit*/ 4);
8541			ctl_done((union ctl_io *)ctsio);
8542			return (CTL_RETVAL_COMPLETE);
8543		}
8544
8545		if (type>8 || type==2 || type==4 || type==0) {
8546			ctl_set_invalid_field(/*ctsio*/ ctsio,
8547					      /*sks_valid*/ 1,
8548					      /*command*/ 1,
8549					      /*field*/ 2,
8550					      /*bit_valid*/ 1,
8551					      /*bit*/ 0);
8552			ctl_done((union ctl_io *)ctsio);
8553			return (CTL_RETVAL_COMPLETE);
8554		}
8555	}
8556
8557	param_len = scsi_4btoul(cdb->length);
8558
8559	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8560		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8561		ctsio->kern_data_len = param_len;
8562		ctsio->kern_total_len = param_len;
8563		ctsio->kern_data_resid = 0;
8564		ctsio->kern_rel_offset = 0;
8565		ctsio->kern_sg_entries = 0;
8566		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8567		ctsio->be_move_done = ctl_config_move_done;
8568		ctl_datamove((union ctl_io *)ctsio);
8569
8570		return (CTL_RETVAL_COMPLETE);
8571	}
8572
8573	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8574
8575	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8576	res_key = scsi_8btou64(param->res_key.key);
8577	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8578
8579	/*
8580	 * Validate the reservation key here except for SPRO_REG_IGNO
8581	 * This must be done for all other service actions
8582	 */
8583	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8584		mtx_lock(&lun->lun_lock);
8585		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8586			if (res_key != key) {
8587				/*
8588				 * The current key passed in doesn't match
8589				 * the one the initiator previously
8590				 * registered.
8591				 */
8592				mtx_unlock(&lun->lun_lock);
8593				free(ctsio->kern_data_ptr, M_CTL);
8594				ctl_set_reservation_conflict(ctsio);
8595				ctl_done((union ctl_io *)ctsio);
8596				return (CTL_RETVAL_COMPLETE);
8597			}
8598		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8599			/*
8600			 * We are not registered
8601			 */
8602			mtx_unlock(&lun->lun_lock);
8603			free(ctsio->kern_data_ptr, M_CTL);
8604			ctl_set_reservation_conflict(ctsio);
8605			ctl_done((union ctl_io *)ctsio);
8606			return (CTL_RETVAL_COMPLETE);
8607		} else if (res_key != 0) {
8608			/*
8609			 * We are not registered and trying to register but
8610			 * the register key isn't zero.
8611			 */
8612			mtx_unlock(&lun->lun_lock);
8613			free(ctsio->kern_data_ptr, M_CTL);
8614			ctl_set_reservation_conflict(ctsio);
8615			ctl_done((union ctl_io *)ctsio);
8616			return (CTL_RETVAL_COMPLETE);
8617		}
8618		mtx_unlock(&lun->lun_lock);
8619	}
8620
8621	switch (cdb->action & SPRO_ACTION_MASK) {
8622	case SPRO_REGISTER:
8623	case SPRO_REG_IGNO: {
8624
8625#if 0
8626		printf("Registration received\n");
8627#endif
8628
8629		/*
8630		 * We don't support any of these options, as we report in
8631		 * the read capabilities request (see
8632		 * ctl_persistent_reserve_in(), above).
8633		 */
8634		if ((param->flags & SPR_SPEC_I_PT)
8635		 || (param->flags & SPR_ALL_TG_PT)
8636		 || (param->flags & SPR_APTPL)) {
8637			int bit_ptr;
8638
8639			if (param->flags & SPR_APTPL)
8640				bit_ptr = 0;
8641			else if (param->flags & SPR_ALL_TG_PT)
8642				bit_ptr = 2;
8643			else /* SPR_SPEC_I_PT */
8644				bit_ptr = 3;
8645
8646			free(ctsio->kern_data_ptr, M_CTL);
8647			ctl_set_invalid_field(ctsio,
8648					      /*sks_valid*/ 1,
8649					      /*command*/ 0,
8650					      /*field*/ 20,
8651					      /*bit_valid*/ 1,
8652					      /*bit*/ bit_ptr);
8653			ctl_done((union ctl_io *)ctsio);
8654			return (CTL_RETVAL_COMPLETE);
8655		}
8656
8657		mtx_lock(&lun->lun_lock);
8658
8659		/*
8660		 * The initiator wants to clear the
8661		 * key/unregister.
8662		 */
8663		if (sa_res_key == 0) {
8664			if ((res_key == 0
8665			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8666			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8667			  && ctl_get_prkey(lun, residx) == 0)) {
8668				mtx_unlock(&lun->lun_lock);
8669				goto done;
8670			}
8671
8672			ctl_clr_prkey(lun, residx);
8673			lun->pr_key_count--;
8674
8675			if (residx == lun->pr_res_idx) {
8676				lun->flags &= ~CTL_LUN_PR_RESERVED;
8677				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8678
8679				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8680				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8681				 && lun->pr_key_count) {
8682					/*
8683					 * If the reservation is a registrants
8684					 * only type we need to generate a UA
8685					 * for other registered inits.  The
8686					 * sense code should be RESERVATIONS
8687					 * RELEASED
8688					 */
8689
8690					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8691						if (ctl_get_prkey(lun, i +
8692						    softc->persis_offset) == 0)
8693							continue;
8694						ctl_est_ua(lun, i,
8695						    CTL_UA_RES_RELEASE);
8696					}
8697				}
8698				lun->res_type = 0;
8699			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8700				if (lun->pr_key_count==0) {
8701					lun->flags &= ~CTL_LUN_PR_RESERVED;
8702					lun->res_type = 0;
8703					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8704				}
8705			}
8706			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8707			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8708			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8709			persis_io.pr.pr_info.residx = residx;
8710			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8711			     &persis_io, sizeof(persis_io), 0 )) >
8712			     CTL_HA_STATUS_SUCCESS) {
8713				printf("CTL:Persis Out error returned from "
8714				       "ctl_ha_msg_send %d\n", isc_retval);
8715			}
8716		} else /* sa_res_key != 0 */ {
8717
8718			/*
8719			 * If we aren't registered currently then increment
8720			 * the key count and set the registered flag.
8721			 */
8722			ctl_alloc_prkey(lun, residx);
8723			if (ctl_get_prkey(lun, residx) == 0)
8724				lun->pr_key_count++;
8725			ctl_set_prkey(lun, residx, sa_res_key);
8726
8727			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8728			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8729			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8730			persis_io.pr.pr_info.residx = residx;
8731			memcpy(persis_io.pr.pr_info.sa_res_key,
8732			       param->serv_act_res_key,
8733			       sizeof(param->serv_act_res_key));
8734			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8735			     &persis_io, sizeof(persis_io), 0)) >
8736			     CTL_HA_STATUS_SUCCESS) {
8737				printf("CTL:Persis Out error returned from "
8738				       "ctl_ha_msg_send %d\n", isc_retval);
8739			}
8740		}
8741		lun->PRGeneration++;
8742		mtx_unlock(&lun->lun_lock);
8743
8744		break;
8745	}
8746	case SPRO_RESERVE:
8747#if 0
8748                printf("Reserve executed type %d\n", type);
8749#endif
8750		mtx_lock(&lun->lun_lock);
8751		if (lun->flags & CTL_LUN_PR_RESERVED) {
8752			/*
8753			 * if this isn't the reservation holder and it's
8754			 * not a "all registrants" type or if the type is
8755			 * different then we have a conflict
8756			 */
8757			if ((lun->pr_res_idx != residx
8758			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8759			 || lun->res_type != type) {
8760				mtx_unlock(&lun->lun_lock);
8761				free(ctsio->kern_data_ptr, M_CTL);
8762				ctl_set_reservation_conflict(ctsio);
8763				ctl_done((union ctl_io *)ctsio);
8764				return (CTL_RETVAL_COMPLETE);
8765			}
8766			mtx_unlock(&lun->lun_lock);
8767		} else /* create a reservation */ {
8768			/*
8769			 * If it's not an "all registrants" type record
8770			 * reservation holder
8771			 */
8772			if (type != SPR_TYPE_WR_EX_AR
8773			 && type != SPR_TYPE_EX_AC_AR)
8774				lun->pr_res_idx = residx; /* Res holder */
8775			else
8776				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8777
8778			lun->flags |= CTL_LUN_PR_RESERVED;
8779			lun->res_type = type;
8780
8781			mtx_unlock(&lun->lun_lock);
8782
8783			/* send msg to other side */
8784			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8785			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8786			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8787			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8788			persis_io.pr.pr_info.res_type = type;
8789			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8790			     &persis_io, sizeof(persis_io), 0)) >
8791			     CTL_HA_STATUS_SUCCESS) {
8792				printf("CTL:Persis Out error returned from "
8793				       "ctl_ha_msg_send %d\n", isc_retval);
8794			}
8795		}
8796		break;
8797
8798	case SPRO_RELEASE:
8799		mtx_lock(&lun->lun_lock);
8800		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8801			/* No reservation exists return good status */
8802			mtx_unlock(&lun->lun_lock);
8803			goto done;
8804		}
8805		/*
8806		 * Is this nexus a reservation holder?
8807		 */
8808		if (lun->pr_res_idx != residx
8809		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8810			/*
8811			 * not a res holder return good status but
8812			 * do nothing
8813			 */
8814			mtx_unlock(&lun->lun_lock);
8815			goto done;
8816		}
8817
8818		if (lun->res_type != type) {
8819			mtx_unlock(&lun->lun_lock);
8820			free(ctsio->kern_data_ptr, M_CTL);
8821			ctl_set_illegal_pr_release(ctsio);
8822			ctl_done((union ctl_io *)ctsio);
8823			return (CTL_RETVAL_COMPLETE);
8824		}
8825
8826		/* okay to release */
8827		lun->flags &= ~CTL_LUN_PR_RESERVED;
8828		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8829		lun->res_type = 0;
8830
8831		/*
8832		 * if this isn't an exclusive access
8833		 * res generate UA for all other
8834		 * registrants.
8835		 */
8836		if (type != SPR_TYPE_EX_AC
8837		 && type != SPR_TYPE_WR_EX) {
8838			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8839				if (i == residx ||
8840				    ctl_get_prkey(lun,
8841				     i + softc->persis_offset) == 0)
8842					continue;
8843				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8844			}
8845		}
8846		mtx_unlock(&lun->lun_lock);
8847		/* Send msg to other side */
8848		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8849		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8850		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8851		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8852		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8853			printf("CTL:Persis Out error returned from "
8854			       "ctl_ha_msg_send %d\n", isc_retval);
8855		}
8856		break;
8857
8858	case SPRO_CLEAR:
8859		/* send msg to other side */
8860
8861		mtx_lock(&lun->lun_lock);
8862		lun->flags &= ~CTL_LUN_PR_RESERVED;
8863		lun->res_type = 0;
8864		lun->pr_key_count = 0;
8865		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8866
8867		ctl_clr_prkey(lun, residx);
8868		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8869			if (ctl_get_prkey(lun, i) != 0) {
8870				ctl_clr_prkey(lun, i);
8871				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8872			}
8873		lun->PRGeneration++;
8874		mtx_unlock(&lun->lun_lock);
8875		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8876		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8877		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8878		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8879		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8880			printf("CTL:Persis Out error returned from "
8881			       "ctl_ha_msg_send %d\n", isc_retval);
8882		}
8883		break;
8884
8885	case SPRO_PREEMPT:
8886	case SPRO_PRE_ABO: {
8887		int nretval;
8888
8889		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8890					  residx, ctsio, cdb, param);
8891		if (nretval != 0)
8892			return (CTL_RETVAL_COMPLETE);
8893		break;
8894	}
8895	default:
8896		panic("Invalid PR type %x", cdb->action);
8897	}
8898
8899done:
8900	free(ctsio->kern_data_ptr, M_CTL);
8901	ctl_set_success(ctsio);
8902	ctl_done((union ctl_io *)ctsio);
8903
8904	return (retval);
8905}
8906
8907/*
8908 * This routine is for handling a message from the other SC pertaining to
8909 * persistent reserve out. All the error checking will have been done
8910 * so only perorming the action need be done here to keep the two
8911 * in sync.
8912 */
8913static void
8914ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8915{
8916	struct ctl_lun *lun;
8917	struct ctl_softc *softc;
8918	int i;
8919	uint32_t targ_lun;
8920
8921	softc = control_softc;
8922
8923	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8924	lun = softc->ctl_luns[targ_lun];
8925	mtx_lock(&lun->lun_lock);
8926	switch(msg->pr.pr_info.action) {
8927	case CTL_PR_REG_KEY:
8928		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8929		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8930			lun->pr_key_count++;
8931		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8932		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8933		lun->PRGeneration++;
8934		break;
8935
8936	case CTL_PR_UNREG_KEY:
8937		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8938		lun->pr_key_count--;
8939
8940		/* XXX Need to see if the reservation has been released */
8941		/* if so do we need to generate UA? */
8942		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8943			lun->flags &= ~CTL_LUN_PR_RESERVED;
8944			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8945
8946			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8947			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8948			 && lun->pr_key_count) {
8949				/*
8950				 * If the reservation is a registrants
8951				 * only type we need to generate a UA
8952				 * for other registered inits.  The
8953				 * sense code should be RESERVATIONS
8954				 * RELEASED
8955				 */
8956
8957				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8958					if (ctl_get_prkey(lun, i +
8959					    softc->persis_offset) == 0)
8960						continue;
8961
8962					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8963				}
8964			}
8965			lun->res_type = 0;
8966		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8967			if (lun->pr_key_count==0) {
8968				lun->flags &= ~CTL_LUN_PR_RESERVED;
8969				lun->res_type = 0;
8970				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8971			}
8972		}
8973		lun->PRGeneration++;
8974		break;
8975
8976	case CTL_PR_RESERVE:
8977		lun->flags |= CTL_LUN_PR_RESERVED;
8978		lun->res_type = msg->pr.pr_info.res_type;
8979		lun->pr_res_idx = msg->pr.pr_info.residx;
8980
8981		break;
8982
8983	case CTL_PR_RELEASE:
8984		/*
8985		 * if this isn't an exclusive access res generate UA for all
8986		 * other registrants.
8987		 */
8988		if (lun->res_type != SPR_TYPE_EX_AC
8989		 && lun->res_type != SPR_TYPE_WR_EX) {
8990			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8991				if (ctl_get_prkey(lun, i + softc->persis_offset) != 0)
8992					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8993		}
8994
8995		lun->flags &= ~CTL_LUN_PR_RESERVED;
8996		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8997		lun->res_type = 0;
8998		break;
8999
9000	case CTL_PR_PREEMPT:
9001		ctl_pro_preempt_other(lun, msg);
9002		break;
9003	case CTL_PR_CLEAR:
9004		lun->flags &= ~CTL_LUN_PR_RESERVED;
9005		lun->res_type = 0;
9006		lun->pr_key_count = 0;
9007		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
9008
9009		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
9010			if (ctl_get_prkey(lun, i) == 0)
9011				continue;
9012			ctl_clr_prkey(lun, i);
9013			ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
9014		}
9015		lun->PRGeneration++;
9016		break;
9017	}
9018
9019	mtx_unlock(&lun->lun_lock);
9020}
9021
9022int
9023ctl_read_write(struct ctl_scsiio *ctsio)
9024{
9025	struct ctl_lun *lun;
9026	struct ctl_lba_len_flags *lbalen;
9027	uint64_t lba;
9028	uint32_t num_blocks;
9029	int flags, retval;
9030	int isread;
9031
9032	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9033
9034	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
9035
9036	flags = 0;
9037	retval = CTL_RETVAL_COMPLETE;
9038
9039	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
9040	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
9041	switch (ctsio->cdb[0]) {
9042	case READ_6:
9043	case WRITE_6: {
9044		struct scsi_rw_6 *cdb;
9045
9046		cdb = (struct scsi_rw_6 *)ctsio->cdb;
9047
9048		lba = scsi_3btoul(cdb->addr);
9049		/* only 5 bits are valid in the most significant address byte */
9050		lba &= 0x1fffff;
9051		num_blocks = cdb->length;
9052		/*
9053		 * This is correct according to SBC-2.
9054		 */
9055		if (num_blocks == 0)
9056			num_blocks = 256;
9057		break;
9058	}
9059	case READ_10:
9060	case WRITE_10: {
9061		struct scsi_rw_10 *cdb;
9062
9063		cdb = (struct scsi_rw_10 *)ctsio->cdb;
9064		if (cdb->byte2 & SRW10_FUA)
9065			flags |= CTL_LLF_FUA;
9066		if (cdb->byte2 & SRW10_DPO)
9067			flags |= CTL_LLF_DPO;
9068		lba = scsi_4btoul(cdb->addr);
9069		num_blocks = scsi_2btoul(cdb->length);
9070		break;
9071	}
9072	case WRITE_VERIFY_10: {
9073		struct scsi_write_verify_10 *cdb;
9074
9075		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
9076		flags |= CTL_LLF_FUA;
9077		if (cdb->byte2 & SWV_DPO)
9078			flags |= CTL_LLF_DPO;
9079		lba = scsi_4btoul(cdb->addr);
9080		num_blocks = scsi_2btoul(cdb->length);
9081		break;
9082	}
9083	case READ_12:
9084	case WRITE_12: {
9085		struct scsi_rw_12 *cdb;
9086
9087		cdb = (struct scsi_rw_12 *)ctsio->cdb;
9088		if (cdb->byte2 & SRW12_FUA)
9089			flags |= CTL_LLF_FUA;
9090		if (cdb->byte2 & SRW12_DPO)
9091			flags |= CTL_LLF_DPO;
9092		lba = scsi_4btoul(cdb->addr);
9093		num_blocks = scsi_4btoul(cdb->length);
9094		break;
9095	}
9096	case WRITE_VERIFY_12: {
9097		struct scsi_write_verify_12 *cdb;
9098
9099		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
9100		flags |= CTL_LLF_FUA;
9101		if (cdb->byte2 & SWV_DPO)
9102			flags |= CTL_LLF_DPO;
9103		lba = scsi_4btoul(cdb->addr);
9104		num_blocks = scsi_4btoul(cdb->length);
9105		break;
9106	}
9107	case READ_16:
9108	case WRITE_16: {
9109		struct scsi_rw_16 *cdb;
9110
9111		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9112		if (cdb->byte2 & SRW12_FUA)
9113			flags |= CTL_LLF_FUA;
9114		if (cdb->byte2 & SRW12_DPO)
9115			flags |= CTL_LLF_DPO;
9116		lba = scsi_8btou64(cdb->addr);
9117		num_blocks = scsi_4btoul(cdb->length);
9118		break;
9119	}
9120	case WRITE_ATOMIC_16: {
9121		struct scsi_rw_16 *cdb;
9122
9123		if (lun->be_lun->atomicblock == 0) {
9124			ctl_set_invalid_opcode(ctsio);
9125			ctl_done((union ctl_io *)ctsio);
9126			return (CTL_RETVAL_COMPLETE);
9127		}
9128
9129		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9130		if (cdb->byte2 & SRW12_FUA)
9131			flags |= CTL_LLF_FUA;
9132		if (cdb->byte2 & SRW12_DPO)
9133			flags |= CTL_LLF_DPO;
9134		lba = scsi_8btou64(cdb->addr);
9135		num_blocks = scsi_4btoul(cdb->length);
9136		if (num_blocks > lun->be_lun->atomicblock) {
9137			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
9138			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
9139			    /*bit*/ 0);
9140			ctl_done((union ctl_io *)ctsio);
9141			return (CTL_RETVAL_COMPLETE);
9142		}
9143		break;
9144	}
9145	case WRITE_VERIFY_16: {
9146		struct scsi_write_verify_16 *cdb;
9147
9148		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9149		flags |= CTL_LLF_FUA;
9150		if (cdb->byte2 & SWV_DPO)
9151			flags |= CTL_LLF_DPO;
9152		lba = scsi_8btou64(cdb->addr);
9153		num_blocks = scsi_4btoul(cdb->length);
9154		break;
9155	}
9156	default:
9157		/*
9158		 * We got a command we don't support.  This shouldn't
9159		 * happen, commands should be filtered out above us.
9160		 */
9161		ctl_set_invalid_opcode(ctsio);
9162		ctl_done((union ctl_io *)ctsio);
9163
9164		return (CTL_RETVAL_COMPLETE);
9165		break; /* NOTREACHED */
9166	}
9167
9168	/*
9169	 * The first check is to make sure we're in bounds, the second
9170	 * check is to catch wrap-around problems.  If the lba + num blocks
9171	 * is less than the lba, then we've wrapped around and the block
9172	 * range is invalid anyway.
9173	 */
9174	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9175	 || ((lba + num_blocks) < lba)) {
9176		ctl_set_lba_out_of_range(ctsio);
9177		ctl_done((union ctl_io *)ctsio);
9178		return (CTL_RETVAL_COMPLETE);
9179	}
9180
9181	/*
9182	 * According to SBC-3, a transfer length of 0 is not an error.
9183	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
9184	 * translates to 256 blocks for those commands.
9185	 */
9186	if (num_blocks == 0) {
9187		ctl_set_success(ctsio);
9188		ctl_done((union ctl_io *)ctsio);
9189		return (CTL_RETVAL_COMPLETE);
9190	}
9191
9192	/* Set FUA and/or DPO if caches are disabled. */
9193	if (isread) {
9194		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9195		    SCP_RCD) != 0)
9196			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9197	} else {
9198		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9199		    SCP_WCE) == 0)
9200			flags |= CTL_LLF_FUA;
9201	}
9202
9203	lbalen = (struct ctl_lba_len_flags *)
9204	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9205	lbalen->lba = lba;
9206	lbalen->len = num_blocks;
9207	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9208
9209	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9210	ctsio->kern_rel_offset = 0;
9211
9212	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9213
9214	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9215
9216	return (retval);
9217}
9218
9219static int
9220ctl_cnw_cont(union ctl_io *io)
9221{
9222	struct ctl_scsiio *ctsio;
9223	struct ctl_lun *lun;
9224	struct ctl_lba_len_flags *lbalen;
9225	int retval;
9226
9227	ctsio = &io->scsiio;
9228	ctsio->io_hdr.status = CTL_STATUS_NONE;
9229	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9230	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9231	lbalen = (struct ctl_lba_len_flags *)
9232	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9233	lbalen->flags &= ~CTL_LLF_COMPARE;
9234	lbalen->flags |= CTL_LLF_WRITE;
9235
9236	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9237	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9238	return (retval);
9239}
9240
9241int
9242ctl_cnw(struct ctl_scsiio *ctsio)
9243{
9244	struct ctl_lun *lun;
9245	struct ctl_lba_len_flags *lbalen;
9246	uint64_t lba;
9247	uint32_t num_blocks;
9248	int flags, retval;
9249
9250	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9251
9252	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9253
9254	flags = 0;
9255	retval = CTL_RETVAL_COMPLETE;
9256
9257	switch (ctsio->cdb[0]) {
9258	case COMPARE_AND_WRITE: {
9259		struct scsi_compare_and_write *cdb;
9260
9261		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9262		if (cdb->byte2 & SRW10_FUA)
9263			flags |= CTL_LLF_FUA;
9264		if (cdb->byte2 & SRW10_DPO)
9265			flags |= CTL_LLF_DPO;
9266		lba = scsi_8btou64(cdb->addr);
9267		num_blocks = cdb->length;
9268		break;
9269	}
9270	default:
9271		/*
9272		 * We got a command we don't support.  This shouldn't
9273		 * happen, commands should be filtered out above us.
9274		 */
9275		ctl_set_invalid_opcode(ctsio);
9276		ctl_done((union ctl_io *)ctsio);
9277
9278		return (CTL_RETVAL_COMPLETE);
9279		break; /* NOTREACHED */
9280	}
9281
9282	/*
9283	 * The first check is to make sure we're in bounds, the second
9284	 * check is to catch wrap-around problems.  If the lba + num blocks
9285	 * is less than the lba, then we've wrapped around and the block
9286	 * range is invalid anyway.
9287	 */
9288	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9289	 || ((lba + num_blocks) < lba)) {
9290		ctl_set_lba_out_of_range(ctsio);
9291		ctl_done((union ctl_io *)ctsio);
9292		return (CTL_RETVAL_COMPLETE);
9293	}
9294
9295	/*
9296	 * According to SBC-3, a transfer length of 0 is not an error.
9297	 */
9298	if (num_blocks == 0) {
9299		ctl_set_success(ctsio);
9300		ctl_done((union ctl_io *)ctsio);
9301		return (CTL_RETVAL_COMPLETE);
9302	}
9303
9304	/* Set FUA if write cache is disabled. */
9305	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9306	    SCP_WCE) == 0)
9307		flags |= CTL_LLF_FUA;
9308
9309	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9310	ctsio->kern_rel_offset = 0;
9311
9312	/*
9313	 * Set the IO_CONT flag, so that if this I/O gets passed to
9314	 * ctl_data_submit_done(), it'll get passed back to
9315	 * ctl_ctl_cnw_cont() for further processing.
9316	 */
9317	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9318	ctsio->io_cont = ctl_cnw_cont;
9319
9320	lbalen = (struct ctl_lba_len_flags *)
9321	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9322	lbalen->lba = lba;
9323	lbalen->len = num_blocks;
9324	lbalen->flags = CTL_LLF_COMPARE | flags;
9325
9326	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9327	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9328	return (retval);
9329}
9330
9331int
9332ctl_verify(struct ctl_scsiio *ctsio)
9333{
9334	struct ctl_lun *lun;
9335	struct ctl_lba_len_flags *lbalen;
9336	uint64_t lba;
9337	uint32_t num_blocks;
9338	int bytchk, flags;
9339	int retval;
9340
9341	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9342
9343	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9344
9345	bytchk = 0;
9346	flags = CTL_LLF_FUA;
9347	retval = CTL_RETVAL_COMPLETE;
9348
9349	switch (ctsio->cdb[0]) {
9350	case VERIFY_10: {
9351		struct scsi_verify_10 *cdb;
9352
9353		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9354		if (cdb->byte2 & SVFY_BYTCHK)
9355			bytchk = 1;
9356		if (cdb->byte2 & SVFY_DPO)
9357			flags |= CTL_LLF_DPO;
9358		lba = scsi_4btoul(cdb->addr);
9359		num_blocks = scsi_2btoul(cdb->length);
9360		break;
9361	}
9362	case VERIFY_12: {
9363		struct scsi_verify_12 *cdb;
9364
9365		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9366		if (cdb->byte2 & SVFY_BYTCHK)
9367			bytchk = 1;
9368		if (cdb->byte2 & SVFY_DPO)
9369			flags |= CTL_LLF_DPO;
9370		lba = scsi_4btoul(cdb->addr);
9371		num_blocks = scsi_4btoul(cdb->length);
9372		break;
9373	}
9374	case VERIFY_16: {
9375		struct scsi_rw_16 *cdb;
9376
9377		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9378		if (cdb->byte2 & SVFY_BYTCHK)
9379			bytchk = 1;
9380		if (cdb->byte2 & SVFY_DPO)
9381			flags |= CTL_LLF_DPO;
9382		lba = scsi_8btou64(cdb->addr);
9383		num_blocks = scsi_4btoul(cdb->length);
9384		break;
9385	}
9386	default:
9387		/*
9388		 * We got a command we don't support.  This shouldn't
9389		 * happen, commands should be filtered out above us.
9390		 */
9391		ctl_set_invalid_opcode(ctsio);
9392		ctl_done((union ctl_io *)ctsio);
9393		return (CTL_RETVAL_COMPLETE);
9394	}
9395
9396	/*
9397	 * The first check is to make sure we're in bounds, the second
9398	 * check is to catch wrap-around problems.  If the lba + num blocks
9399	 * is less than the lba, then we've wrapped around and the block
9400	 * range is invalid anyway.
9401	 */
9402	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9403	 || ((lba + num_blocks) < lba)) {
9404		ctl_set_lba_out_of_range(ctsio);
9405		ctl_done((union ctl_io *)ctsio);
9406		return (CTL_RETVAL_COMPLETE);
9407	}
9408
9409	/*
9410	 * According to SBC-3, a transfer length of 0 is not an error.
9411	 */
9412	if (num_blocks == 0) {
9413		ctl_set_success(ctsio);
9414		ctl_done((union ctl_io *)ctsio);
9415		return (CTL_RETVAL_COMPLETE);
9416	}
9417
9418	lbalen = (struct ctl_lba_len_flags *)
9419	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9420	lbalen->lba = lba;
9421	lbalen->len = num_blocks;
9422	if (bytchk) {
9423		lbalen->flags = CTL_LLF_COMPARE | flags;
9424		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9425	} else {
9426		lbalen->flags = CTL_LLF_VERIFY | flags;
9427		ctsio->kern_total_len = 0;
9428	}
9429	ctsio->kern_rel_offset = 0;
9430
9431	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9432	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9433	return (retval);
9434}
9435
9436int
9437ctl_report_luns(struct ctl_scsiio *ctsio)
9438{
9439	struct ctl_softc *softc = control_softc;
9440	struct scsi_report_luns *cdb;
9441	struct scsi_report_luns_data *lun_data;
9442	struct ctl_lun *lun, *request_lun;
9443	struct ctl_port *port;
9444	int num_luns, retval;
9445	uint32_t alloc_len, lun_datalen;
9446	int num_filled, well_known;
9447	uint32_t initidx, targ_lun_id, lun_id;
9448
9449	retval = CTL_RETVAL_COMPLETE;
9450	well_known = 0;
9451
9452	cdb = (struct scsi_report_luns *)ctsio->cdb;
9453
9454	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9455
9456	mtx_lock(&softc->ctl_lock);
9457	num_luns = softc->num_luns;
9458	mtx_unlock(&softc->ctl_lock);
9459
9460	switch (cdb->select_report) {
9461	case RPL_REPORT_DEFAULT:
9462	case RPL_REPORT_ALL:
9463		break;
9464	case RPL_REPORT_WELLKNOWN:
9465		well_known = 1;
9466		num_luns = 0;
9467		break;
9468	default:
9469		ctl_set_invalid_field(ctsio,
9470				      /*sks_valid*/ 1,
9471				      /*command*/ 1,
9472				      /*field*/ 2,
9473				      /*bit_valid*/ 0,
9474				      /*bit*/ 0);
9475		ctl_done((union ctl_io *)ctsio);
9476		return (retval);
9477		break; /* NOTREACHED */
9478	}
9479
9480	alloc_len = scsi_4btoul(cdb->length);
9481	/*
9482	 * The initiator has to allocate at least 16 bytes for this request,
9483	 * so he can at least get the header and the first LUN.  Otherwise
9484	 * we reject the request (per SPC-3 rev 14, section 6.21).
9485	 */
9486	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9487	    sizeof(struct scsi_report_luns_lundata))) {
9488		ctl_set_invalid_field(ctsio,
9489				      /*sks_valid*/ 1,
9490				      /*command*/ 1,
9491				      /*field*/ 6,
9492				      /*bit_valid*/ 0,
9493				      /*bit*/ 0);
9494		ctl_done((union ctl_io *)ctsio);
9495		return (retval);
9496	}
9497
9498	request_lun = (struct ctl_lun *)
9499		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9500	port = ctl_io_port(&ctsio->io_hdr);
9501
9502	lun_datalen = sizeof(*lun_data) +
9503		(num_luns * sizeof(struct scsi_report_luns_lundata));
9504
9505	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9506	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9507	ctsio->kern_sg_entries = 0;
9508
9509	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9510
9511	mtx_lock(&softc->ctl_lock);
9512	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9513		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9514		if (lun_id >= CTL_MAX_LUNS)
9515			continue;
9516		lun = softc->ctl_luns[lun_id];
9517		if (lun == NULL)
9518			continue;
9519
9520		if (targ_lun_id <= 0xff) {
9521			/*
9522			 * Peripheral addressing method, bus number 0.
9523			 */
9524			lun_data->luns[num_filled].lundata[0] =
9525				RPL_LUNDATA_ATYP_PERIPH;
9526			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9527			num_filled++;
9528		} else if (targ_lun_id <= 0x3fff) {
9529			/*
9530			 * Flat addressing method.
9531			 */
9532			lun_data->luns[num_filled].lundata[0] =
9533				RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9534			lun_data->luns[num_filled].lundata[1] =
9535				(targ_lun_id & 0xff);
9536			num_filled++;
9537		} else if (targ_lun_id <= 0xffffff) {
9538			/*
9539			 * Extended flat addressing method.
9540			 */
9541			lun_data->luns[num_filled].lundata[0] =
9542			    RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9543			scsi_ulto3b(targ_lun_id,
9544			    &lun_data->luns[num_filled].lundata[1]);
9545			num_filled++;
9546		} else {
9547			printf("ctl_report_luns: bogus LUN number %jd, "
9548			       "skipping\n", (intmax_t)targ_lun_id);
9549		}
9550		/*
9551		 * According to SPC-3, rev 14 section 6.21:
9552		 *
9553		 * "The execution of a REPORT LUNS command to any valid and
9554		 * installed logical unit shall clear the REPORTED LUNS DATA
9555		 * HAS CHANGED unit attention condition for all logical
9556		 * units of that target with respect to the requesting
9557		 * initiator. A valid and installed logical unit is one
9558		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9559		 * INQUIRY data (see 6.4.2)."
9560		 *
9561		 * If request_lun is NULL, the LUN this report luns command
9562		 * was issued to is either disabled or doesn't exist. In that
9563		 * case, we shouldn't clear any pending lun change unit
9564		 * attention.
9565		 */
9566		if (request_lun != NULL) {
9567			mtx_lock(&lun->lun_lock);
9568			ctl_clr_ua(lun, initidx, CTL_UA_RES_RELEASE);
9569			mtx_unlock(&lun->lun_lock);
9570		}
9571	}
9572	mtx_unlock(&softc->ctl_lock);
9573
9574	/*
9575	 * It's quite possible that we've returned fewer LUNs than we allocated
9576	 * space for.  Trim it.
9577	 */
9578	lun_datalen = sizeof(*lun_data) +
9579		(num_filled * sizeof(struct scsi_report_luns_lundata));
9580
9581	if (lun_datalen < alloc_len) {
9582		ctsio->residual = alloc_len - lun_datalen;
9583		ctsio->kern_data_len = lun_datalen;
9584		ctsio->kern_total_len = lun_datalen;
9585	} else {
9586		ctsio->residual = 0;
9587		ctsio->kern_data_len = alloc_len;
9588		ctsio->kern_total_len = alloc_len;
9589	}
9590	ctsio->kern_data_resid = 0;
9591	ctsio->kern_rel_offset = 0;
9592	ctsio->kern_sg_entries = 0;
9593
9594	/*
9595	 * We set this to the actual data length, regardless of how much
9596	 * space we actually have to return results.  If the user looks at
9597	 * this value, he'll know whether or not he allocated enough space
9598	 * and reissue the command if necessary.  We don't support well
9599	 * known logical units, so if the user asks for that, return none.
9600	 */
9601	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9602
9603	/*
9604	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9605	 * this request.
9606	 */
9607	ctl_set_success(ctsio);
9608	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9609	ctsio->be_move_done = ctl_config_move_done;
9610	ctl_datamove((union ctl_io *)ctsio);
9611	return (retval);
9612}
9613
9614int
9615ctl_request_sense(struct ctl_scsiio *ctsio)
9616{
9617	struct scsi_request_sense *cdb;
9618	struct scsi_sense_data *sense_ptr;
9619	struct ctl_softc *ctl_softc;
9620	struct ctl_lun *lun;
9621	uint32_t initidx;
9622	int have_error;
9623	scsi_sense_data_type sense_format;
9624	ctl_ua_type ua_type;
9625
9626	cdb = (struct scsi_request_sense *)ctsio->cdb;
9627
9628	ctl_softc = control_softc;
9629	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9630
9631	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9632
9633	/*
9634	 * Determine which sense format the user wants.
9635	 */
9636	if (cdb->byte2 & SRS_DESC)
9637		sense_format = SSD_TYPE_DESC;
9638	else
9639		sense_format = SSD_TYPE_FIXED;
9640
9641	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9642	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9643	ctsio->kern_sg_entries = 0;
9644
9645	/*
9646	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9647	 * larger than the largest allowed value for the length field in the
9648	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9649	 */
9650	ctsio->residual = 0;
9651	ctsio->kern_data_len = cdb->length;
9652	ctsio->kern_total_len = cdb->length;
9653
9654	ctsio->kern_data_resid = 0;
9655	ctsio->kern_rel_offset = 0;
9656	ctsio->kern_sg_entries = 0;
9657
9658	/*
9659	 * If we don't have a LUN, we don't have any pending sense.
9660	 */
9661	if (lun == NULL)
9662		goto no_sense;
9663
9664	have_error = 0;
9665	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9666	/*
9667	 * Check for pending sense, and then for pending unit attentions.
9668	 * Pending sense gets returned first, then pending unit attentions.
9669	 */
9670	mtx_lock(&lun->lun_lock);
9671#ifdef CTL_WITH_CA
9672	if (ctl_is_set(lun->have_ca, initidx)) {
9673		scsi_sense_data_type stored_format;
9674
9675		/*
9676		 * Check to see which sense format was used for the stored
9677		 * sense data.
9678		 */
9679		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9680
9681		/*
9682		 * If the user requested a different sense format than the
9683		 * one we stored, then we need to convert it to the other
9684		 * format.  If we're going from descriptor to fixed format
9685		 * sense data, we may lose things in translation, depending
9686		 * on what options were used.
9687		 *
9688		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9689		 * for some reason we'll just copy it out as-is.
9690		 */
9691		if ((stored_format == SSD_TYPE_FIXED)
9692		 && (sense_format == SSD_TYPE_DESC))
9693			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9694			    &lun->pending_sense[initidx],
9695			    (struct scsi_sense_data_desc *)sense_ptr);
9696		else if ((stored_format == SSD_TYPE_DESC)
9697		      && (sense_format == SSD_TYPE_FIXED))
9698			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9699			    &lun->pending_sense[initidx],
9700			    (struct scsi_sense_data_fixed *)sense_ptr);
9701		else
9702			memcpy(sense_ptr, &lun->pending_sense[initidx],
9703			       MIN(sizeof(*sense_ptr),
9704			       sizeof(lun->pending_sense[initidx])));
9705
9706		ctl_clear_mask(lun->have_ca, initidx);
9707		have_error = 1;
9708	} else
9709#endif
9710	{
9711		ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9712		if (ua_type != CTL_UA_NONE)
9713			have_error = 1;
9714		if (ua_type == CTL_UA_LUN_CHANGE) {
9715			mtx_unlock(&lun->lun_lock);
9716			mtx_lock(&ctl_softc->ctl_lock);
9717			ctl_clear_ua(ctl_softc, initidx, ua_type);
9718			mtx_unlock(&ctl_softc->ctl_lock);
9719			mtx_lock(&lun->lun_lock);
9720		}
9721
9722	}
9723	mtx_unlock(&lun->lun_lock);
9724
9725	/*
9726	 * We already have a pending error, return it.
9727	 */
9728	if (have_error != 0) {
9729		/*
9730		 * We report the SCSI status as OK, since the status of the
9731		 * request sense command itself is OK.
9732		 * We report 0 for the sense length, because we aren't doing
9733		 * autosense in this case.  We're reporting sense as
9734		 * parameter data.
9735		 */
9736		ctl_set_success(ctsio);
9737		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9738		ctsio->be_move_done = ctl_config_move_done;
9739		ctl_datamove((union ctl_io *)ctsio);
9740		return (CTL_RETVAL_COMPLETE);
9741	}
9742
9743no_sense:
9744
9745	/*
9746	 * No sense information to report, so we report that everything is
9747	 * okay.
9748	 */
9749	ctl_set_sense_data(sense_ptr,
9750			   lun,
9751			   sense_format,
9752			   /*current_error*/ 1,
9753			   /*sense_key*/ SSD_KEY_NO_SENSE,
9754			   /*asc*/ 0x00,
9755			   /*ascq*/ 0x00,
9756			   SSD_ELEM_NONE);
9757
9758	/*
9759	 * We report 0 for the sense length, because we aren't doing
9760	 * autosense in this case.  We're reporting sense as parameter data.
9761	 */
9762	ctl_set_success(ctsio);
9763	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9764	ctsio->be_move_done = ctl_config_move_done;
9765	ctl_datamove((union ctl_io *)ctsio);
9766	return (CTL_RETVAL_COMPLETE);
9767}
9768
9769int
9770ctl_tur(struct ctl_scsiio *ctsio)
9771{
9772
9773	CTL_DEBUG_PRINT(("ctl_tur\n"));
9774
9775	ctl_set_success(ctsio);
9776	ctl_done((union ctl_io *)ctsio);
9777
9778	return (CTL_RETVAL_COMPLETE);
9779}
9780
9781#ifdef notyet
9782static int
9783ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9784{
9785
9786}
9787#endif
9788
9789/*
9790 * SCSI VPD page 0x00, the Supported VPD Pages page.
9791 */
9792static int
9793ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9794{
9795	struct scsi_vpd_supported_pages *pages;
9796	int sup_page_size;
9797	struct ctl_lun *lun;
9798	int p;
9799
9800	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9801
9802	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9803	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9804	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9805	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9806	ctsio->kern_sg_entries = 0;
9807
9808	if (sup_page_size < alloc_len) {
9809		ctsio->residual = alloc_len - sup_page_size;
9810		ctsio->kern_data_len = sup_page_size;
9811		ctsio->kern_total_len = sup_page_size;
9812	} else {
9813		ctsio->residual = 0;
9814		ctsio->kern_data_len = alloc_len;
9815		ctsio->kern_total_len = alloc_len;
9816	}
9817	ctsio->kern_data_resid = 0;
9818	ctsio->kern_rel_offset = 0;
9819	ctsio->kern_sg_entries = 0;
9820
9821	/*
9822	 * The control device is always connected.  The disk device, on the
9823	 * other hand, may not be online all the time.  Need to change this
9824	 * to figure out whether the disk device is actually online or not.
9825	 */
9826	if (lun != NULL)
9827		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9828				lun->be_lun->lun_type;
9829	else
9830		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9831
9832	p = 0;
9833	/* Supported VPD pages */
9834	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9835	/* Serial Number */
9836	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9837	/* Device Identification */
9838	pages->page_list[p++] = SVPD_DEVICE_ID;
9839	/* Extended INQUIRY Data */
9840	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9841	/* Mode Page Policy */
9842	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9843	/* SCSI Ports */
9844	pages->page_list[p++] = SVPD_SCSI_PORTS;
9845	/* Third-party Copy */
9846	pages->page_list[p++] = SVPD_SCSI_TPC;
9847	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9848		/* Block limits */
9849		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9850		/* Block Device Characteristics */
9851		pages->page_list[p++] = SVPD_BDC;
9852		/* Logical Block Provisioning */
9853		pages->page_list[p++] = SVPD_LBP;
9854	}
9855	pages->length = p;
9856
9857	ctl_set_success(ctsio);
9858	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9859	ctsio->be_move_done = ctl_config_move_done;
9860	ctl_datamove((union ctl_io *)ctsio);
9861	return (CTL_RETVAL_COMPLETE);
9862}
9863
9864/*
9865 * SCSI VPD page 0x80, the Unit Serial Number page.
9866 */
9867static int
9868ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9869{
9870	struct scsi_vpd_unit_serial_number *sn_ptr;
9871	struct ctl_lun *lun;
9872	int data_len;
9873
9874	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9875
9876	data_len = 4 + CTL_SN_LEN;
9877	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9878	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9879	if (data_len < alloc_len) {
9880		ctsio->residual = alloc_len - data_len;
9881		ctsio->kern_data_len = data_len;
9882		ctsio->kern_total_len = data_len;
9883	} else {
9884		ctsio->residual = 0;
9885		ctsio->kern_data_len = alloc_len;
9886		ctsio->kern_total_len = alloc_len;
9887	}
9888	ctsio->kern_data_resid = 0;
9889	ctsio->kern_rel_offset = 0;
9890	ctsio->kern_sg_entries = 0;
9891
9892	/*
9893	 * The control device is always connected.  The disk device, on the
9894	 * other hand, may not be online all the time.  Need to change this
9895	 * to figure out whether the disk device is actually online or not.
9896	 */
9897	if (lun != NULL)
9898		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9899				  lun->be_lun->lun_type;
9900	else
9901		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9902
9903	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9904	sn_ptr->length = CTL_SN_LEN;
9905	/*
9906	 * If we don't have a LUN, we just leave the serial number as
9907	 * all spaces.
9908	 */
9909	if (lun != NULL) {
9910		strncpy((char *)sn_ptr->serial_num,
9911			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9912	} else
9913		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9914
9915	ctl_set_success(ctsio);
9916	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9917	ctsio->be_move_done = ctl_config_move_done;
9918	ctl_datamove((union ctl_io *)ctsio);
9919	return (CTL_RETVAL_COMPLETE);
9920}
9921
9922
9923/*
9924 * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9925 */
9926static int
9927ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9928{
9929	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9930	struct ctl_lun *lun;
9931	int data_len;
9932
9933	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9934
9935	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9936	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9937	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9938	ctsio->kern_sg_entries = 0;
9939
9940	if (data_len < alloc_len) {
9941		ctsio->residual = alloc_len - data_len;
9942		ctsio->kern_data_len = data_len;
9943		ctsio->kern_total_len = data_len;
9944	} else {
9945		ctsio->residual = 0;
9946		ctsio->kern_data_len = alloc_len;
9947		ctsio->kern_total_len = alloc_len;
9948	}
9949	ctsio->kern_data_resid = 0;
9950	ctsio->kern_rel_offset = 0;
9951	ctsio->kern_sg_entries = 0;
9952
9953	/*
9954	 * The control device is always connected.  The disk device, on the
9955	 * other hand, may not be online all the time.
9956	 */
9957	if (lun != NULL)
9958		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9959				     lun->be_lun->lun_type;
9960	else
9961		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9962	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9963	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9964	/*
9965	 * We support head of queue, ordered and simple tags.
9966	 */
9967	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9968	/*
9969	 * Volatile cache supported.
9970	 */
9971	eid_ptr->flags3 = SVPD_EID_V_SUP;
9972
9973	/*
9974	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9975	 * attention for a particular IT nexus on all LUNs once we report
9976	 * it to that nexus once.  This bit is required as of SPC-4.
9977	 */
9978	eid_ptr->flags4 = SVPD_EID_LUICLT;
9979
9980	/*
9981	 * XXX KDM in order to correctly answer this, we would need
9982	 * information from the SIM to determine how much sense data it
9983	 * can send.  So this would really be a path inquiry field, most
9984	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9985	 * but the hardware may or may not be able to support that much.
9986	 * 0 just means that the maximum sense data length is not reported.
9987	 */
9988	eid_ptr->max_sense_length = 0;
9989
9990	ctl_set_success(ctsio);
9991	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9992	ctsio->be_move_done = ctl_config_move_done;
9993	ctl_datamove((union ctl_io *)ctsio);
9994	return (CTL_RETVAL_COMPLETE);
9995}
9996
9997static int
9998ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9999{
10000	struct scsi_vpd_mode_page_policy *mpp_ptr;
10001	struct ctl_lun *lun;
10002	int data_len;
10003
10004	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10005
10006	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
10007	    sizeof(struct scsi_vpd_mode_page_policy_descr);
10008
10009	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10010	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
10011	ctsio->kern_sg_entries = 0;
10012
10013	if (data_len < alloc_len) {
10014		ctsio->residual = alloc_len - data_len;
10015		ctsio->kern_data_len = data_len;
10016		ctsio->kern_total_len = data_len;
10017	} else {
10018		ctsio->residual = 0;
10019		ctsio->kern_data_len = alloc_len;
10020		ctsio->kern_total_len = alloc_len;
10021	}
10022	ctsio->kern_data_resid = 0;
10023	ctsio->kern_rel_offset = 0;
10024	ctsio->kern_sg_entries = 0;
10025
10026	/*
10027	 * The control device is always connected.  The disk device, on the
10028	 * other hand, may not be online all the time.
10029	 */
10030	if (lun != NULL)
10031		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10032				     lun->be_lun->lun_type;
10033	else
10034		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10035	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
10036	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
10037	mpp_ptr->descr[0].page_code = 0x3f;
10038	mpp_ptr->descr[0].subpage_code = 0xff;
10039	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
10040
10041	ctl_set_success(ctsio);
10042	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10043	ctsio->be_move_done = ctl_config_move_done;
10044	ctl_datamove((union ctl_io *)ctsio);
10045	return (CTL_RETVAL_COMPLETE);
10046}
10047
10048/*
10049 * SCSI VPD page 0x83, the Device Identification page.
10050 */
10051static int
10052ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
10053{
10054	struct scsi_vpd_device_id *devid_ptr;
10055	struct scsi_vpd_id_descriptor *desc;
10056	struct ctl_softc *softc;
10057	struct ctl_lun *lun;
10058	struct ctl_port *port;
10059	int data_len;
10060	uint8_t proto;
10061
10062	softc = control_softc;
10063
10064	port = softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
10065	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10066
10067	data_len = sizeof(struct scsi_vpd_device_id) +
10068	    sizeof(struct scsi_vpd_id_descriptor) +
10069		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
10070	    sizeof(struct scsi_vpd_id_descriptor) +
10071		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
10072	if (lun && lun->lun_devid)
10073		data_len += lun->lun_devid->len;
10074	if (port->port_devid)
10075		data_len += port->port_devid->len;
10076	if (port->target_devid)
10077		data_len += port->target_devid->len;
10078
10079	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10080	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
10081	ctsio->kern_sg_entries = 0;
10082
10083	if (data_len < alloc_len) {
10084		ctsio->residual = alloc_len - data_len;
10085		ctsio->kern_data_len = data_len;
10086		ctsio->kern_total_len = data_len;
10087	} else {
10088		ctsio->residual = 0;
10089		ctsio->kern_data_len = alloc_len;
10090		ctsio->kern_total_len = alloc_len;
10091	}
10092	ctsio->kern_data_resid = 0;
10093	ctsio->kern_rel_offset = 0;
10094	ctsio->kern_sg_entries = 0;
10095
10096	/*
10097	 * The control device is always connected.  The disk device, on the
10098	 * other hand, may not be online all the time.
10099	 */
10100	if (lun != NULL)
10101		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10102				     lun->be_lun->lun_type;
10103	else
10104		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10105	devid_ptr->page_code = SVPD_DEVICE_ID;
10106	scsi_ulto2b(data_len - 4, devid_ptr->length);
10107
10108	if (port->port_type == CTL_PORT_FC)
10109		proto = SCSI_PROTO_FC << 4;
10110	else if (port->port_type == CTL_PORT_ISCSI)
10111		proto = SCSI_PROTO_ISCSI << 4;
10112	else
10113		proto = SCSI_PROTO_SPI << 4;
10114	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
10115
10116	/*
10117	 * We're using a LUN association here.  i.e., this device ID is a
10118	 * per-LUN identifier.
10119	 */
10120	if (lun && lun->lun_devid) {
10121		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
10122		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10123		    lun->lun_devid->len);
10124	}
10125
10126	/*
10127	 * This is for the WWPN which is a port association.
10128	 */
10129	if (port->port_devid) {
10130		memcpy(desc, port->port_devid->data, port->port_devid->len);
10131		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10132		    port->port_devid->len);
10133	}
10134
10135	/*
10136	 * This is for the Relative Target Port(type 4h) identifier
10137	 */
10138	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10139	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10140	    SVPD_ID_TYPE_RELTARG;
10141	desc->length = 4;
10142	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
10143	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10144	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
10145
10146	/*
10147	 * This is for the Target Port Group(type 5h) identifier
10148	 */
10149	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10150	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10151	    SVPD_ID_TYPE_TPORTGRP;
10152	desc->length = 4;
10153	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
10154	    &desc->identifier[2]);
10155	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10156	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
10157
10158	/*
10159	 * This is for the Target identifier
10160	 */
10161	if (port->target_devid) {
10162		memcpy(desc, port->target_devid->data, port->target_devid->len);
10163	}
10164
10165	ctl_set_success(ctsio);
10166	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10167	ctsio->be_move_done = ctl_config_move_done;
10168	ctl_datamove((union ctl_io *)ctsio);
10169	return (CTL_RETVAL_COMPLETE);
10170}
10171
10172static int
10173ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
10174{
10175	struct ctl_softc *softc = control_softc;
10176	struct scsi_vpd_scsi_ports *sp;
10177	struct scsi_vpd_port_designation *pd;
10178	struct scsi_vpd_port_designation_cont *pdc;
10179	struct ctl_lun *lun;
10180	struct ctl_port *port;
10181	int data_len, num_target_ports, iid_len, id_len, g, pg, p;
10182	int num_target_port_groups;
10183
10184	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10185
10186	if (softc->is_single)
10187		num_target_port_groups = 1;
10188	else
10189		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10190	num_target_ports = 0;
10191	iid_len = 0;
10192	id_len = 0;
10193	mtx_lock(&softc->ctl_lock);
10194	STAILQ_FOREACH(port, &softc->port_list, links) {
10195		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10196			continue;
10197		if (lun != NULL &&
10198		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
10199			continue;
10200		num_target_ports++;
10201		if (port->init_devid)
10202			iid_len += port->init_devid->len;
10203		if (port->port_devid)
10204			id_len += port->port_devid->len;
10205	}
10206	mtx_unlock(&softc->ctl_lock);
10207
10208	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10209	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10210	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10211	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10212	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10213	ctsio->kern_sg_entries = 0;
10214
10215	if (data_len < alloc_len) {
10216		ctsio->residual = alloc_len - data_len;
10217		ctsio->kern_data_len = data_len;
10218		ctsio->kern_total_len = data_len;
10219	} else {
10220		ctsio->residual = 0;
10221		ctsio->kern_data_len = alloc_len;
10222		ctsio->kern_total_len = alloc_len;
10223	}
10224	ctsio->kern_data_resid = 0;
10225	ctsio->kern_rel_offset = 0;
10226	ctsio->kern_sg_entries = 0;
10227
10228	/*
10229	 * The control device is always connected.  The disk device, on the
10230	 * other hand, may not be online all the time.  Need to change this
10231	 * to figure out whether the disk device is actually online or not.
10232	 */
10233	if (lun != NULL)
10234		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10235				  lun->be_lun->lun_type;
10236	else
10237		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10238
10239	sp->page_code = SVPD_SCSI_PORTS;
10240	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10241	    sp->page_length);
10242	pd = &sp->design[0];
10243
10244	mtx_lock(&softc->ctl_lock);
10245	pg = softc->port_offset / CTL_MAX_PORTS;
10246	for (g = 0; g < num_target_port_groups; g++) {
10247		STAILQ_FOREACH(port, &softc->port_list, links) {
10248			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10249				continue;
10250			if (lun != NULL &&
10251			    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
10252				continue;
10253			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10254			scsi_ulto2b(p, pd->relative_port_id);
10255			if (port->init_devid && g == pg) {
10256				iid_len = port->init_devid->len;
10257				memcpy(pd->initiator_transportid,
10258				    port->init_devid->data, port->init_devid->len);
10259			} else
10260				iid_len = 0;
10261			scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10262			pdc = (struct scsi_vpd_port_designation_cont *)
10263			    (&pd->initiator_transportid[iid_len]);
10264			if (port->port_devid && g == pg) {
10265				id_len = port->port_devid->len;
10266				memcpy(pdc->target_port_descriptors,
10267				    port->port_devid->data, port->port_devid->len);
10268			} else
10269				id_len = 0;
10270			scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10271			pd = (struct scsi_vpd_port_designation *)
10272			    ((uint8_t *)pdc->target_port_descriptors + id_len);
10273		}
10274	}
10275	mtx_unlock(&softc->ctl_lock);
10276
10277	ctl_set_success(ctsio);
10278	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10279	ctsio->be_move_done = ctl_config_move_done;
10280	ctl_datamove((union ctl_io *)ctsio);
10281	return (CTL_RETVAL_COMPLETE);
10282}
10283
10284static int
10285ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10286{
10287	struct scsi_vpd_block_limits *bl_ptr;
10288	struct ctl_lun *lun;
10289	int bs;
10290
10291	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10292
10293	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10294	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10295	ctsio->kern_sg_entries = 0;
10296
10297	if (sizeof(*bl_ptr) < alloc_len) {
10298		ctsio->residual = alloc_len - sizeof(*bl_ptr);
10299		ctsio->kern_data_len = sizeof(*bl_ptr);
10300		ctsio->kern_total_len = sizeof(*bl_ptr);
10301	} else {
10302		ctsio->residual = 0;
10303		ctsio->kern_data_len = alloc_len;
10304		ctsio->kern_total_len = alloc_len;
10305	}
10306	ctsio->kern_data_resid = 0;
10307	ctsio->kern_rel_offset = 0;
10308	ctsio->kern_sg_entries = 0;
10309
10310	/*
10311	 * The control device is always connected.  The disk device, on the
10312	 * other hand, may not be online all the time.  Need to change this
10313	 * to figure out whether the disk device is actually online or not.
10314	 */
10315	if (lun != NULL)
10316		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10317				  lun->be_lun->lun_type;
10318	else
10319		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10320
10321	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10322	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10323	bl_ptr->max_cmp_write_len = 0xff;
10324	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10325	if (lun != NULL) {
10326		bs = lun->be_lun->blocksize;
10327		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
10328		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10329			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10330			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10331			if (lun->be_lun->ublockexp != 0) {
10332				scsi_ulto4b((1 << lun->be_lun->ublockexp),
10333				    bl_ptr->opt_unmap_grain);
10334				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
10335				    bl_ptr->unmap_grain_align);
10336			}
10337		}
10338		scsi_ulto4b(lun->be_lun->atomicblock,
10339		    bl_ptr->max_atomic_transfer_length);
10340		scsi_ulto4b(0, bl_ptr->atomic_alignment);
10341		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10342	}
10343	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10344
10345	ctl_set_success(ctsio);
10346	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10347	ctsio->be_move_done = ctl_config_move_done;
10348	ctl_datamove((union ctl_io *)ctsio);
10349	return (CTL_RETVAL_COMPLETE);
10350}
10351
10352static int
10353ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10354{
10355	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10356	struct ctl_lun *lun;
10357	const char *value;
10358	u_int i;
10359
10360	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10361
10362	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10363	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10364	ctsio->kern_sg_entries = 0;
10365
10366	if (sizeof(*bdc_ptr) < alloc_len) {
10367		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10368		ctsio->kern_data_len = sizeof(*bdc_ptr);
10369		ctsio->kern_total_len = sizeof(*bdc_ptr);
10370	} else {
10371		ctsio->residual = 0;
10372		ctsio->kern_data_len = alloc_len;
10373		ctsio->kern_total_len = alloc_len;
10374	}
10375	ctsio->kern_data_resid = 0;
10376	ctsio->kern_rel_offset = 0;
10377	ctsio->kern_sg_entries = 0;
10378
10379	/*
10380	 * The control device is always connected.  The disk device, on the
10381	 * other hand, may not be online all the time.  Need to change this
10382	 * to figure out whether the disk device is actually online or not.
10383	 */
10384	if (lun != NULL)
10385		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10386				  lun->be_lun->lun_type;
10387	else
10388		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10389	bdc_ptr->page_code = SVPD_BDC;
10390	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10391	if (lun != NULL &&
10392	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10393		i = strtol(value, NULL, 0);
10394	else
10395		i = CTL_DEFAULT_ROTATION_RATE;
10396	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10397	if (lun != NULL &&
10398	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10399		i = strtol(value, NULL, 0);
10400	else
10401		i = 0;
10402	bdc_ptr->wab_wac_ff = (i & 0x0f);
10403	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10404
10405	ctl_set_success(ctsio);
10406	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10407	ctsio->be_move_done = ctl_config_move_done;
10408	ctl_datamove((union ctl_io *)ctsio);
10409	return (CTL_RETVAL_COMPLETE);
10410}
10411
10412static int
10413ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10414{
10415	struct scsi_vpd_logical_block_prov *lbp_ptr;
10416	struct ctl_lun *lun;
10417
10418	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10419
10420	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10421	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10422	ctsio->kern_sg_entries = 0;
10423
10424	if (sizeof(*lbp_ptr) < alloc_len) {
10425		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10426		ctsio->kern_data_len = sizeof(*lbp_ptr);
10427		ctsio->kern_total_len = sizeof(*lbp_ptr);
10428	} else {
10429		ctsio->residual = 0;
10430		ctsio->kern_data_len = alloc_len;
10431		ctsio->kern_total_len = alloc_len;
10432	}
10433	ctsio->kern_data_resid = 0;
10434	ctsio->kern_rel_offset = 0;
10435	ctsio->kern_sg_entries = 0;
10436
10437	/*
10438	 * The control device is always connected.  The disk device, on the
10439	 * other hand, may not be online all the time.  Need to change this
10440	 * to figure out whether the disk device is actually online or not.
10441	 */
10442	if (lun != NULL)
10443		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10444				  lun->be_lun->lun_type;
10445	else
10446		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10447
10448	lbp_ptr->page_code = SVPD_LBP;
10449	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10450	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10451	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10452		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10453		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10454		lbp_ptr->prov_type = SVPD_LBP_THIN;
10455	}
10456
10457	ctl_set_success(ctsio);
10458	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10459	ctsio->be_move_done = ctl_config_move_done;
10460	ctl_datamove((union ctl_io *)ctsio);
10461	return (CTL_RETVAL_COMPLETE);
10462}
10463
10464/*
10465 * INQUIRY with the EVPD bit set.
10466 */
10467static int
10468ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10469{
10470	struct ctl_lun *lun;
10471	struct scsi_inquiry *cdb;
10472	int alloc_len, retval;
10473
10474	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10475	cdb = (struct scsi_inquiry *)ctsio->cdb;
10476	alloc_len = scsi_2btoul(cdb->length);
10477
10478	switch (cdb->page_code) {
10479	case SVPD_SUPPORTED_PAGES:
10480		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10481		break;
10482	case SVPD_UNIT_SERIAL_NUMBER:
10483		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10484		break;
10485	case SVPD_DEVICE_ID:
10486		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10487		break;
10488	case SVPD_EXTENDED_INQUIRY_DATA:
10489		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10490		break;
10491	case SVPD_MODE_PAGE_POLICY:
10492		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10493		break;
10494	case SVPD_SCSI_PORTS:
10495		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10496		break;
10497	case SVPD_SCSI_TPC:
10498		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10499		break;
10500	case SVPD_BLOCK_LIMITS:
10501		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10502			goto err;
10503		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10504		break;
10505	case SVPD_BDC:
10506		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10507			goto err;
10508		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10509		break;
10510	case SVPD_LBP:
10511		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10512			goto err;
10513		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10514		break;
10515	default:
10516err:
10517		ctl_set_invalid_field(ctsio,
10518				      /*sks_valid*/ 1,
10519				      /*command*/ 1,
10520				      /*field*/ 2,
10521				      /*bit_valid*/ 0,
10522				      /*bit*/ 0);
10523		ctl_done((union ctl_io *)ctsio);
10524		retval = CTL_RETVAL_COMPLETE;
10525		break;
10526	}
10527
10528	return (retval);
10529}
10530
10531/*
10532 * Standard INQUIRY data.
10533 */
10534static int
10535ctl_inquiry_std(struct ctl_scsiio *ctsio)
10536{
10537	struct scsi_inquiry_data *inq_ptr;
10538	struct scsi_inquiry *cdb;
10539	struct ctl_softc *softc;
10540	struct ctl_lun *lun;
10541	char *val;
10542	uint32_t alloc_len, data_len;
10543	ctl_port_type port_type;
10544
10545	softc = control_softc;
10546
10547	/*
10548	 * Figure out whether we're talking to a Fibre Channel port or not.
10549	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10550	 * SCSI front ends.
10551	 */
10552	port_type = softc->ctl_ports[
10553	    ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10554	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10555		port_type = CTL_PORT_SCSI;
10556
10557	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10558	cdb = (struct scsi_inquiry *)ctsio->cdb;
10559	alloc_len = scsi_2btoul(cdb->length);
10560
10561	/*
10562	 * We malloc the full inquiry data size here and fill it
10563	 * in.  If the user only asks for less, we'll give him
10564	 * that much.
10565	 */
10566	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10567	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10568	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10569	ctsio->kern_sg_entries = 0;
10570	ctsio->kern_data_resid = 0;
10571	ctsio->kern_rel_offset = 0;
10572
10573	if (data_len < alloc_len) {
10574		ctsio->residual = alloc_len - data_len;
10575		ctsio->kern_data_len = data_len;
10576		ctsio->kern_total_len = data_len;
10577	} else {
10578		ctsio->residual = 0;
10579		ctsio->kern_data_len = alloc_len;
10580		ctsio->kern_total_len = alloc_len;
10581	}
10582
10583	/*
10584	 * If we have a LUN configured, report it as connected.  Otherwise,
10585	 * report that it is offline or no device is supported, depending
10586	 * on the value of inquiry_pq_no_lun.
10587	 *
10588	 * According to the spec (SPC-4 r34), the peripheral qualifier
10589	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10590	 *
10591	 * "A peripheral device having the specified peripheral device type
10592	 * is not connected to this logical unit. However, the device
10593	 * server is capable of supporting the specified peripheral device
10594	 * type on this logical unit."
10595	 *
10596	 * According to the same spec, the peripheral qualifier
10597	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10598	 *
10599	 * "The device server is not capable of supporting a peripheral
10600	 * device on this logical unit. For this peripheral qualifier the
10601	 * peripheral device type shall be set to 1Fh. All other peripheral
10602	 * device type values are reserved for this peripheral qualifier."
10603	 *
10604	 * Given the text, it would seem that we probably want to report that
10605	 * the LUN is offline here.  There is no LUN connected, but we can
10606	 * support a LUN at the given LUN number.
10607	 *
10608	 * In the real world, though, it sounds like things are a little
10609	 * different:
10610	 *
10611	 * - Linux, when presented with a LUN with the offline peripheral
10612	 *   qualifier, will create an sg driver instance for it.  So when
10613	 *   you attach it to CTL, you wind up with a ton of sg driver
10614	 *   instances.  (One for every LUN that Linux bothered to probe.)
10615	 *   Linux does this despite the fact that it issues a REPORT LUNs
10616	 *   to LUN 0 to get the inventory of supported LUNs.
10617	 *
10618	 * - There is other anecdotal evidence (from Emulex folks) about
10619	 *   arrays that use the offline peripheral qualifier for LUNs that
10620	 *   are on the "passive" path in an active/passive array.
10621	 *
10622	 * So the solution is provide a hopefully reasonable default
10623	 * (return bad/no LUN) and allow the user to change the behavior
10624	 * with a tunable/sysctl variable.
10625	 */
10626	if (lun != NULL)
10627		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10628				  lun->be_lun->lun_type;
10629	else if (softc->inquiry_pq_no_lun == 0)
10630		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10631	else
10632		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10633
10634	/* RMB in byte 2 is 0 */
10635	inq_ptr->version = SCSI_REV_SPC4;
10636
10637	/*
10638	 * According to SAM-3, even if a device only supports a single
10639	 * level of LUN addressing, it should still set the HISUP bit:
10640	 *
10641	 * 4.9.1 Logical unit numbers overview
10642	 *
10643	 * All logical unit number formats described in this standard are
10644	 * hierarchical in structure even when only a single level in that
10645	 * hierarchy is used. The HISUP bit shall be set to one in the
10646	 * standard INQUIRY data (see SPC-2) when any logical unit number
10647	 * format described in this standard is used.  Non-hierarchical
10648	 * formats are outside the scope of this standard.
10649	 *
10650	 * Therefore we set the HiSup bit here.
10651	 *
10652	 * The reponse format is 2, per SPC-3.
10653	 */
10654	inq_ptr->response_format = SID_HiSup | 2;
10655
10656	inq_ptr->additional_length = data_len -
10657	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10658	CTL_DEBUG_PRINT(("additional_length = %d\n",
10659			 inq_ptr->additional_length));
10660
10661	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10662	/* 16 bit addressing */
10663	if (port_type == CTL_PORT_SCSI)
10664		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10665	/* XXX set the SID_MultiP bit here if we're actually going to
10666	   respond on multiple ports */
10667	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10668
10669	/* 16 bit data bus, synchronous transfers */
10670	if (port_type == CTL_PORT_SCSI)
10671		inq_ptr->flags = SID_WBus16 | SID_Sync;
10672	/*
10673	 * XXX KDM do we want to support tagged queueing on the control
10674	 * device at all?
10675	 */
10676	if ((lun == NULL)
10677	 || (lun->be_lun->lun_type != T_PROCESSOR))
10678		inq_ptr->flags |= SID_CmdQue;
10679	/*
10680	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10681	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10682	 * name and 4 bytes for the revision.
10683	 */
10684	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10685	    "vendor")) == NULL) {
10686		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10687	} else {
10688		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10689		strncpy(inq_ptr->vendor, val,
10690		    min(sizeof(inq_ptr->vendor), strlen(val)));
10691	}
10692	if (lun == NULL) {
10693		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10694		    sizeof(inq_ptr->product));
10695	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10696		switch (lun->be_lun->lun_type) {
10697		case T_DIRECT:
10698			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10699			    sizeof(inq_ptr->product));
10700			break;
10701		case T_PROCESSOR:
10702			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10703			    sizeof(inq_ptr->product));
10704			break;
10705		default:
10706			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10707			    sizeof(inq_ptr->product));
10708			break;
10709		}
10710	} else {
10711		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10712		strncpy(inq_ptr->product, val,
10713		    min(sizeof(inq_ptr->product), strlen(val)));
10714	}
10715
10716	/*
10717	 * XXX make this a macro somewhere so it automatically gets
10718	 * incremented when we make changes.
10719	 */
10720	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10721	    "revision")) == NULL) {
10722		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10723	} else {
10724		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10725		strncpy(inq_ptr->revision, val,
10726		    min(sizeof(inq_ptr->revision), strlen(val)));
10727	}
10728
10729	/*
10730	 * For parallel SCSI, we support double transition and single
10731	 * transition clocking.  We also support QAS (Quick Arbitration
10732	 * and Selection) and Information Unit transfers on both the
10733	 * control and array devices.
10734	 */
10735	if (port_type == CTL_PORT_SCSI)
10736		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10737				    SID_SPI_IUS;
10738
10739	/* SAM-5 (no version claimed) */
10740	scsi_ulto2b(0x00A0, inq_ptr->version1);
10741	/* SPC-4 (no version claimed) */
10742	scsi_ulto2b(0x0460, inq_ptr->version2);
10743	if (port_type == CTL_PORT_FC) {
10744		/* FCP-2 ANSI INCITS.350:2003 */
10745		scsi_ulto2b(0x0917, inq_ptr->version3);
10746	} else if (port_type == CTL_PORT_SCSI) {
10747		/* SPI-4 ANSI INCITS.362:200x */
10748		scsi_ulto2b(0x0B56, inq_ptr->version3);
10749	} else if (port_type == CTL_PORT_ISCSI) {
10750		/* iSCSI (no version claimed) */
10751		scsi_ulto2b(0x0960, inq_ptr->version3);
10752	} else if (port_type == CTL_PORT_SAS) {
10753		/* SAS (no version claimed) */
10754		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10755	}
10756
10757	if (lun == NULL) {
10758		/* SBC-4 (no version claimed) */
10759		scsi_ulto2b(0x0600, inq_ptr->version4);
10760	} else {
10761		switch (lun->be_lun->lun_type) {
10762		case T_DIRECT:
10763			/* SBC-4 (no version claimed) */
10764			scsi_ulto2b(0x0600, inq_ptr->version4);
10765			break;
10766		case T_PROCESSOR:
10767		default:
10768			break;
10769		}
10770	}
10771
10772	ctl_set_success(ctsio);
10773	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10774	ctsio->be_move_done = ctl_config_move_done;
10775	ctl_datamove((union ctl_io *)ctsio);
10776	return (CTL_RETVAL_COMPLETE);
10777}
10778
10779int
10780ctl_inquiry(struct ctl_scsiio *ctsio)
10781{
10782	struct scsi_inquiry *cdb;
10783	int retval;
10784
10785	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10786
10787	cdb = (struct scsi_inquiry *)ctsio->cdb;
10788	if (cdb->byte2 & SI_EVPD)
10789		retval = ctl_inquiry_evpd(ctsio);
10790	else if (cdb->page_code == 0)
10791		retval = ctl_inquiry_std(ctsio);
10792	else {
10793		ctl_set_invalid_field(ctsio,
10794				      /*sks_valid*/ 1,
10795				      /*command*/ 1,
10796				      /*field*/ 2,
10797				      /*bit_valid*/ 0,
10798				      /*bit*/ 0);
10799		ctl_done((union ctl_io *)ctsio);
10800		return (CTL_RETVAL_COMPLETE);
10801	}
10802
10803	return (retval);
10804}
10805
10806/*
10807 * For known CDB types, parse the LBA and length.
10808 */
10809static int
10810ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10811{
10812	if (io->io_hdr.io_type != CTL_IO_SCSI)
10813		return (1);
10814
10815	switch (io->scsiio.cdb[0]) {
10816	case COMPARE_AND_WRITE: {
10817		struct scsi_compare_and_write *cdb;
10818
10819		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10820
10821		*lba = scsi_8btou64(cdb->addr);
10822		*len = cdb->length;
10823		break;
10824	}
10825	case READ_6:
10826	case WRITE_6: {
10827		struct scsi_rw_6 *cdb;
10828
10829		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10830
10831		*lba = scsi_3btoul(cdb->addr);
10832		/* only 5 bits are valid in the most significant address byte */
10833		*lba &= 0x1fffff;
10834		*len = cdb->length;
10835		break;
10836	}
10837	case READ_10:
10838	case WRITE_10: {
10839		struct scsi_rw_10 *cdb;
10840
10841		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10842
10843		*lba = scsi_4btoul(cdb->addr);
10844		*len = scsi_2btoul(cdb->length);
10845		break;
10846	}
10847	case WRITE_VERIFY_10: {
10848		struct scsi_write_verify_10 *cdb;
10849
10850		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10851
10852		*lba = scsi_4btoul(cdb->addr);
10853		*len = scsi_2btoul(cdb->length);
10854		break;
10855	}
10856	case READ_12:
10857	case WRITE_12: {
10858		struct scsi_rw_12 *cdb;
10859
10860		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10861
10862		*lba = scsi_4btoul(cdb->addr);
10863		*len = scsi_4btoul(cdb->length);
10864		break;
10865	}
10866	case WRITE_VERIFY_12: {
10867		struct scsi_write_verify_12 *cdb;
10868
10869		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10870
10871		*lba = scsi_4btoul(cdb->addr);
10872		*len = scsi_4btoul(cdb->length);
10873		break;
10874	}
10875	case READ_16:
10876	case WRITE_16:
10877	case WRITE_ATOMIC_16: {
10878		struct scsi_rw_16 *cdb;
10879
10880		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10881
10882		*lba = scsi_8btou64(cdb->addr);
10883		*len = scsi_4btoul(cdb->length);
10884		break;
10885	}
10886	case WRITE_VERIFY_16: {
10887		struct scsi_write_verify_16 *cdb;
10888
10889		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10890
10891		*lba = scsi_8btou64(cdb->addr);
10892		*len = scsi_4btoul(cdb->length);
10893		break;
10894	}
10895	case WRITE_SAME_10: {
10896		struct scsi_write_same_10 *cdb;
10897
10898		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10899
10900		*lba = scsi_4btoul(cdb->addr);
10901		*len = scsi_2btoul(cdb->length);
10902		break;
10903	}
10904	case WRITE_SAME_16: {
10905		struct scsi_write_same_16 *cdb;
10906
10907		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10908
10909		*lba = scsi_8btou64(cdb->addr);
10910		*len = scsi_4btoul(cdb->length);
10911		break;
10912	}
10913	case VERIFY_10: {
10914		struct scsi_verify_10 *cdb;
10915
10916		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10917
10918		*lba = scsi_4btoul(cdb->addr);
10919		*len = scsi_2btoul(cdb->length);
10920		break;
10921	}
10922	case VERIFY_12: {
10923		struct scsi_verify_12 *cdb;
10924
10925		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10926
10927		*lba = scsi_4btoul(cdb->addr);
10928		*len = scsi_4btoul(cdb->length);
10929		break;
10930	}
10931	case VERIFY_16: {
10932		struct scsi_verify_16 *cdb;
10933
10934		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10935
10936		*lba = scsi_8btou64(cdb->addr);
10937		*len = scsi_4btoul(cdb->length);
10938		break;
10939	}
10940	case UNMAP: {
10941		*lba = 0;
10942		*len = UINT64_MAX;
10943		break;
10944	}
10945	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10946		struct scsi_get_lba_status *cdb;
10947
10948		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10949		*lba = scsi_8btou64(cdb->addr);
10950		*len = UINT32_MAX;
10951		break;
10952	}
10953	default:
10954		return (1);
10955		break; /* NOTREACHED */
10956	}
10957
10958	return (0);
10959}
10960
10961static ctl_action
10962ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10963    bool seq)
10964{
10965	uint64_t endlba1, endlba2;
10966
10967	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10968	endlba2 = lba2 + len2 - 1;
10969
10970	if ((endlba1 < lba2) || (endlba2 < lba1))
10971		return (CTL_ACTION_PASS);
10972	else
10973		return (CTL_ACTION_BLOCK);
10974}
10975
10976static int
10977ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10978{
10979	struct ctl_ptr_len_flags *ptrlen;
10980	struct scsi_unmap_desc *buf, *end, *range;
10981	uint64_t lba;
10982	uint32_t len;
10983
10984	/* If not UNMAP -- go other way. */
10985	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10986	    io->scsiio.cdb[0] != UNMAP)
10987		return (CTL_ACTION_ERROR);
10988
10989	/* If UNMAP without data -- block and wait for data. */
10990	ptrlen = (struct ctl_ptr_len_flags *)
10991	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10992	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10993	    ptrlen->ptr == NULL)
10994		return (CTL_ACTION_BLOCK);
10995
10996	/* UNMAP with data -- check for collision. */
10997	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10998	end = buf + ptrlen->len / sizeof(*buf);
10999	for (range = buf; range < end; range++) {
11000		lba = scsi_8btou64(range->lba);
11001		len = scsi_4btoul(range->length);
11002		if ((lba < lba2 + len2) && (lba + len > lba2))
11003			return (CTL_ACTION_BLOCK);
11004	}
11005	return (CTL_ACTION_PASS);
11006}
11007
11008static ctl_action
11009ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
11010{
11011	uint64_t lba1, lba2;
11012	uint64_t len1, len2;
11013	int retval;
11014
11015	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
11016		return (CTL_ACTION_ERROR);
11017
11018	retval = ctl_extent_check_unmap(io1, lba2, len2);
11019	if (retval != CTL_ACTION_ERROR)
11020		return (retval);
11021
11022	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
11023		return (CTL_ACTION_ERROR);
11024
11025	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
11026}
11027
11028static ctl_action
11029ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
11030{
11031	uint64_t lba1, lba2;
11032	uint64_t len1, len2;
11033
11034	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
11035		return (CTL_ACTION_ERROR);
11036	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
11037		return (CTL_ACTION_ERROR);
11038
11039	if (lba1 + len1 == lba2)
11040		return (CTL_ACTION_BLOCK);
11041	return (CTL_ACTION_PASS);
11042}
11043
11044static ctl_action
11045ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
11046    union ctl_io *ooa_io)
11047{
11048	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
11049	ctl_serialize_action *serialize_row;
11050
11051	/*
11052	 * The initiator attempted multiple untagged commands at the same
11053	 * time.  Can't do that.
11054	 */
11055	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11056	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11057	 && ((pending_io->io_hdr.nexus.targ_port ==
11058	      ooa_io->io_hdr.nexus.targ_port)
11059	  && (pending_io->io_hdr.nexus.initid.id ==
11060	      ooa_io->io_hdr.nexus.initid.id))
11061	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11062	      CTL_FLAG_STATUS_SENT)) == 0))
11063		return (CTL_ACTION_OVERLAP);
11064
11065	/*
11066	 * The initiator attempted to send multiple tagged commands with
11067	 * the same ID.  (It's fine if different initiators have the same
11068	 * tag ID.)
11069	 *
11070	 * Even if all of those conditions are true, we don't kill the I/O
11071	 * if the command ahead of us has been aborted.  We won't end up
11072	 * sending it to the FETD, and it's perfectly legal to resend a
11073	 * command with the same tag number as long as the previous
11074	 * instance of this tag number has been aborted somehow.
11075	 */
11076	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11077	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11078	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11079	 && ((pending_io->io_hdr.nexus.targ_port ==
11080	      ooa_io->io_hdr.nexus.targ_port)
11081	  && (pending_io->io_hdr.nexus.initid.id ==
11082	      ooa_io->io_hdr.nexus.initid.id))
11083	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11084	      CTL_FLAG_STATUS_SENT)) == 0))
11085		return (CTL_ACTION_OVERLAP_TAG);
11086
11087	/*
11088	 * If we get a head of queue tag, SAM-3 says that we should
11089	 * immediately execute it.
11090	 *
11091	 * What happens if this command would normally block for some other
11092	 * reason?  e.g. a request sense with a head of queue tag
11093	 * immediately after a write.  Normally that would block, but this
11094	 * will result in its getting executed immediately...
11095	 *
11096	 * We currently return "pass" instead of "skip", so we'll end up
11097	 * going through the rest of the queue to check for overlapped tags.
11098	 *
11099	 * XXX KDM check for other types of blockage first??
11100	 */
11101	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11102		return (CTL_ACTION_PASS);
11103
11104	/*
11105	 * Ordered tags have to block until all items ahead of them
11106	 * have completed.  If we get called with an ordered tag, we always
11107	 * block, if something else is ahead of us in the queue.
11108	 */
11109	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11110		return (CTL_ACTION_BLOCK);
11111
11112	/*
11113	 * Simple tags get blocked until all head of queue and ordered tags
11114	 * ahead of them have completed.  I'm lumping untagged commands in
11115	 * with simple tags here.  XXX KDM is that the right thing to do?
11116	 */
11117	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11118	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11119	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11120	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11121		return (CTL_ACTION_BLOCK);
11122
11123	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11124	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11125
11126	serialize_row = ctl_serialize_table[ooa_entry->seridx];
11127
11128	switch (serialize_row[pending_entry->seridx]) {
11129	case CTL_SER_BLOCK:
11130		return (CTL_ACTION_BLOCK);
11131	case CTL_SER_EXTENT:
11132		return (ctl_extent_check(ooa_io, pending_io,
11133		    (lun->serseq == CTL_LUN_SERSEQ_ON)));
11134	case CTL_SER_EXTENTOPT:
11135		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11136		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11137			return (ctl_extent_check(ooa_io, pending_io,
11138			    (lun->serseq == CTL_LUN_SERSEQ_ON)));
11139		return (CTL_ACTION_PASS);
11140	case CTL_SER_EXTENTSEQ:
11141		if (lun->serseq != CTL_LUN_SERSEQ_OFF)
11142			return (ctl_extent_check_seq(ooa_io, pending_io));
11143		return (CTL_ACTION_PASS);
11144	case CTL_SER_PASS:
11145		return (CTL_ACTION_PASS);
11146	case CTL_SER_BLOCKOPT:
11147		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11148		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11149			return (CTL_ACTION_BLOCK);
11150		return (CTL_ACTION_PASS);
11151	case CTL_SER_SKIP:
11152		return (CTL_ACTION_SKIP);
11153	default:
11154		panic("invalid serialization value %d",
11155		      serialize_row[pending_entry->seridx]);
11156	}
11157
11158	return (CTL_ACTION_ERROR);
11159}
11160
11161/*
11162 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11163 * Assumptions:
11164 * - pending_io is generally either incoming, or on the blocked queue
11165 * - starting I/O is the I/O we want to start the check with.
11166 */
11167static ctl_action
11168ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11169	      union ctl_io *starting_io)
11170{
11171	union ctl_io *ooa_io;
11172	ctl_action action;
11173
11174	mtx_assert(&lun->lun_lock, MA_OWNED);
11175
11176	/*
11177	 * Run back along the OOA queue, starting with the current
11178	 * blocked I/O and going through every I/O before it on the
11179	 * queue.  If starting_io is NULL, we'll just end up returning
11180	 * CTL_ACTION_PASS.
11181	 */
11182	for (ooa_io = starting_io; ooa_io != NULL;
11183	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11184	     ooa_links)){
11185
11186		/*
11187		 * This routine just checks to see whether
11188		 * cur_blocked is blocked by ooa_io, which is ahead
11189		 * of it in the queue.  It doesn't queue/dequeue
11190		 * cur_blocked.
11191		 */
11192		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11193		switch (action) {
11194		case CTL_ACTION_BLOCK:
11195		case CTL_ACTION_OVERLAP:
11196		case CTL_ACTION_OVERLAP_TAG:
11197		case CTL_ACTION_SKIP:
11198		case CTL_ACTION_ERROR:
11199			return (action);
11200			break; /* NOTREACHED */
11201		case CTL_ACTION_PASS:
11202			break;
11203		default:
11204			panic("invalid action %d", action);
11205			break;  /* NOTREACHED */
11206		}
11207	}
11208
11209	return (CTL_ACTION_PASS);
11210}
11211
11212/*
11213 * Assumptions:
11214 * - An I/O has just completed, and has been removed from the per-LUN OOA
11215 *   queue, so some items on the blocked queue may now be unblocked.
11216 */
11217static int
11218ctl_check_blocked(struct ctl_lun *lun)
11219{
11220	union ctl_io *cur_blocked, *next_blocked;
11221
11222	mtx_assert(&lun->lun_lock, MA_OWNED);
11223
11224	/*
11225	 * Run forward from the head of the blocked queue, checking each
11226	 * entry against the I/Os prior to it on the OOA queue to see if
11227	 * there is still any blockage.
11228	 *
11229	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11230	 * with our removing a variable on it while it is traversing the
11231	 * list.
11232	 */
11233	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11234	     cur_blocked != NULL; cur_blocked = next_blocked) {
11235		union ctl_io *prev_ooa;
11236		ctl_action action;
11237
11238		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11239							  blocked_links);
11240
11241		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11242						      ctl_ooaq, ooa_links);
11243
11244		/*
11245		 * If cur_blocked happens to be the first item in the OOA
11246		 * queue now, prev_ooa will be NULL, and the action
11247		 * returned will just be CTL_ACTION_PASS.
11248		 */
11249		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11250
11251		switch (action) {
11252		case CTL_ACTION_BLOCK:
11253			/* Nothing to do here, still blocked */
11254			break;
11255		case CTL_ACTION_OVERLAP:
11256		case CTL_ACTION_OVERLAP_TAG:
11257			/*
11258			 * This shouldn't happen!  In theory we've already
11259			 * checked this command for overlap...
11260			 */
11261			break;
11262		case CTL_ACTION_PASS:
11263		case CTL_ACTION_SKIP: {
11264			const struct ctl_cmd_entry *entry;
11265			int isc_retval;
11266
11267			/*
11268			 * The skip case shouldn't happen, this transaction
11269			 * should have never made it onto the blocked queue.
11270			 */
11271			/*
11272			 * This I/O is no longer blocked, we can remove it
11273			 * from the blocked queue.  Since this is a TAILQ
11274			 * (doubly linked list), we can do O(1) removals
11275			 * from any place on the list.
11276			 */
11277			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11278				     blocked_links);
11279			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11280
11281			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11282				/*
11283				 * Need to send IO back to original side to
11284				 * run
11285				 */
11286				union ctl_ha_msg msg_info;
11287
11288				msg_info.hdr.original_sc =
11289					cur_blocked->io_hdr.original_sc;
11290				msg_info.hdr.serializing_sc = cur_blocked;
11291				msg_info.hdr.msg_type = CTL_MSG_R2R;
11292				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11293				     &msg_info, sizeof(msg_info), 0)) >
11294				     CTL_HA_STATUS_SUCCESS) {
11295					printf("CTL:Check Blocked error from "
11296					       "ctl_ha_msg_send %d\n",
11297					       isc_retval);
11298				}
11299				break;
11300			}
11301			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11302
11303			/*
11304			 * Check this I/O for LUN state changes that may
11305			 * have happened while this command was blocked.
11306			 * The LUN state may have been changed by a command
11307			 * ahead of us in the queue, so we need to re-check
11308			 * for any states that can be caused by SCSI
11309			 * commands.
11310			 */
11311			if (ctl_scsiio_lun_check(lun, entry,
11312						 &cur_blocked->scsiio) == 0) {
11313				cur_blocked->io_hdr.flags |=
11314				                      CTL_FLAG_IS_WAS_ON_RTR;
11315				ctl_enqueue_rtr(cur_blocked);
11316			} else
11317				ctl_done(cur_blocked);
11318			break;
11319		}
11320		default:
11321			/*
11322			 * This probably shouldn't happen -- we shouldn't
11323			 * get CTL_ACTION_ERROR, or anything else.
11324			 */
11325			break;
11326		}
11327	}
11328
11329	return (CTL_RETVAL_COMPLETE);
11330}
11331
11332/*
11333 * This routine (with one exception) checks LUN flags that can be set by
11334 * commands ahead of us in the OOA queue.  These flags have to be checked
11335 * when a command initially comes in, and when we pull a command off the
11336 * blocked queue and are preparing to execute it.  The reason we have to
11337 * check these flags for commands on the blocked queue is that the LUN
11338 * state may have been changed by a command ahead of us while we're on the
11339 * blocked queue.
11340 *
11341 * Ordering is somewhat important with these checks, so please pay
11342 * careful attention to the placement of any new checks.
11343 */
11344static int
11345ctl_scsiio_lun_check(struct ctl_lun *lun,
11346    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11347{
11348	struct ctl_softc *softc = lun->ctl_softc;
11349	int retval;
11350	uint32_t residx;
11351
11352	retval = 0;
11353
11354	mtx_assert(&lun->lun_lock, MA_OWNED);
11355
11356	/*
11357	 * If this shelf is a secondary shelf controller, we have to reject
11358	 * any media access commands.
11359	 */
11360	if ((softc->flags & CTL_FLAG_ACTIVE_SHELF) == 0 &&
11361	    (entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0) {
11362		ctl_set_lun_standby(ctsio);
11363		retval = 1;
11364		goto bailout;
11365	}
11366
11367	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11368		if (lun->flags & CTL_LUN_READONLY) {
11369			ctl_set_sense(ctsio, /*current_error*/ 1,
11370			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11371			    /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11372			retval = 1;
11373			goto bailout;
11374		}
11375		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11376		    .eca_and_aen & SCP_SWP) != 0) {
11377			ctl_set_sense(ctsio, /*current_error*/ 1,
11378			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11379			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11380			retval = 1;
11381			goto bailout;
11382		}
11383	}
11384
11385	/*
11386	 * Check for a reservation conflict.  If this command isn't allowed
11387	 * even on reserved LUNs, and if this initiator isn't the one who
11388	 * reserved us, reject the command with a reservation conflict.
11389	 */
11390	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11391	if ((lun->flags & CTL_LUN_RESERVED)
11392	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11393		if (lun->res_idx != residx) {
11394			ctl_set_reservation_conflict(ctsio);
11395			retval = 1;
11396			goto bailout;
11397		}
11398	}
11399
11400	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11401	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11402		/* No reservation or command is allowed. */;
11403	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11404	    (lun->res_type == SPR_TYPE_WR_EX ||
11405	     lun->res_type == SPR_TYPE_WR_EX_RO ||
11406	     lun->res_type == SPR_TYPE_WR_EX_AR)) {
11407		/* The command is allowed for Write Exclusive resv. */;
11408	} else {
11409		/*
11410		 * if we aren't registered or it's a res holder type
11411		 * reservation and this isn't the res holder then set a
11412		 * conflict.
11413		 */
11414		if (ctl_get_prkey(lun, residx) == 0
11415		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11416			ctl_set_reservation_conflict(ctsio);
11417			retval = 1;
11418			goto bailout;
11419		}
11420
11421	}
11422
11423	if ((lun->flags & CTL_LUN_OFFLINE)
11424	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11425		ctl_set_lun_not_ready(ctsio);
11426		retval = 1;
11427		goto bailout;
11428	}
11429
11430	/*
11431	 * If the LUN is stopped, see if this particular command is allowed
11432	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11433	 */
11434	if ((lun->flags & CTL_LUN_STOPPED)
11435	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11436		/* "Logical unit not ready, initializing cmd. required" */
11437		ctl_set_lun_stopped(ctsio);
11438		retval = 1;
11439		goto bailout;
11440	}
11441
11442	if ((lun->flags & CTL_LUN_INOPERABLE)
11443	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11444		/* "Medium format corrupted" */
11445		ctl_set_medium_format_corrupted(ctsio);
11446		retval = 1;
11447		goto bailout;
11448	}
11449
11450bailout:
11451	return (retval);
11452
11453}
11454
11455static void
11456ctl_failover_io(union ctl_io *io, int have_lock)
11457{
11458	ctl_set_busy(&io->scsiio);
11459	ctl_done(io);
11460}
11461
11462static void
11463ctl_failover(void)
11464{
11465	struct ctl_lun *lun;
11466	struct ctl_softc *softc;
11467	union ctl_io *next_io, *pending_io;
11468	union ctl_io *io;
11469	int lun_idx;
11470
11471	softc = control_softc;
11472
11473	mtx_lock(&softc->ctl_lock);
11474	/*
11475	 * Remove any cmds from the other SC from the rtr queue.  These
11476	 * will obviously only be for LUNs for which we're the primary.
11477	 * We can't send status or get/send data for these commands.
11478	 * Since they haven't been executed yet, we can just remove them.
11479	 * We'll either abort them or delete them below, depending on
11480	 * which HA mode we're in.
11481	 */
11482#ifdef notyet
11483	mtx_lock(&softc->queue_lock);
11484	for (io = (union ctl_io *)STAILQ_FIRST(&softc->rtr_queue);
11485	     io != NULL; io = next_io) {
11486		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11487		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11488			STAILQ_REMOVE(&softc->rtr_queue, &io->io_hdr,
11489				      ctl_io_hdr, links);
11490	}
11491	mtx_unlock(&softc->queue_lock);
11492#endif
11493
11494	for (lun_idx=0; lun_idx < softc->num_luns; lun_idx++) {
11495		lun = softc->ctl_luns[lun_idx];
11496		if (lun==NULL)
11497			continue;
11498
11499		/*
11500		 * Processor LUNs are primary on both sides.
11501		 * XXX will this always be true?
11502		 */
11503		if (lun->be_lun->lun_type == T_PROCESSOR)
11504			continue;
11505
11506		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11507		 && (softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11508			printf("FAILOVER: primary lun %d\n", lun_idx);
11509		        /*
11510			 * Remove all commands from the other SC. First from the
11511			 * blocked queue then from the ooa queue. Once we have
11512			 * removed them. Call ctl_check_blocked to see if there
11513			 * is anything that can run.
11514			 */
11515			for (io = (union ctl_io *)TAILQ_FIRST(
11516			     &lun->blocked_queue); io != NULL; io = next_io) {
11517
11518		        	next_io = (union ctl_io *)TAILQ_NEXT(
11519				    &io->io_hdr, blocked_links);
11520
11521				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11522					TAILQ_REMOVE(&lun->blocked_queue,
11523						     &io->io_hdr,blocked_links);
11524					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11525					TAILQ_REMOVE(&lun->ooa_queue,
11526						     &io->io_hdr, ooa_links);
11527
11528					ctl_free_io(io);
11529				}
11530			}
11531
11532			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11533	     		     io != NULL; io = next_io) {
11534
11535		        	next_io = (union ctl_io *)TAILQ_NEXT(
11536				    &io->io_hdr, ooa_links);
11537
11538				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11539
11540					TAILQ_REMOVE(&lun->ooa_queue,
11541						&io->io_hdr,
11542					     	ooa_links);
11543
11544					ctl_free_io(io);
11545				}
11546			}
11547			ctl_check_blocked(lun);
11548		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11549			&& (softc->ha_mode == CTL_HA_MODE_XFER)) {
11550
11551			printf("FAILOVER: primary lun %d\n", lun_idx);
11552			/*
11553			 * Abort all commands from the other SC.  We can't
11554			 * send status back for them now.  These should get
11555			 * cleaned up when they are completed or come out
11556			 * for a datamove operation.
11557			 */
11558			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11559	     		     io != NULL; io = next_io) {
11560		        	next_io = (union ctl_io *)TAILQ_NEXT(
11561					&io->io_hdr, ooa_links);
11562
11563				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11564					io->io_hdr.flags |= CTL_FLAG_ABORT;
11565			}
11566		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11567			&& (softc->ha_mode == CTL_HA_MODE_XFER)) {
11568
11569			printf("FAILOVER: secondary lun %d\n", lun_idx);
11570
11571			lun->flags |= CTL_LUN_PRIMARY_SC;
11572
11573			/*
11574			 * We send all I/O that was sent to this controller
11575			 * and redirected to the other side back with
11576			 * busy status, and have the initiator retry it.
11577			 * Figuring out how much data has been transferred,
11578			 * etc. and picking up where we left off would be
11579			 * very tricky.
11580			 *
11581			 * XXX KDM need to remove I/O from the blocked
11582			 * queue as well!
11583			 */
11584			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11585			     &lun->ooa_queue); pending_io != NULL;
11586			     pending_io = next_io) {
11587
11588				next_io =  (union ctl_io *)TAILQ_NEXT(
11589					&pending_io->io_hdr, ooa_links);
11590
11591				pending_io->io_hdr.flags &=
11592					~CTL_FLAG_SENT_2OTHER_SC;
11593
11594				if (pending_io->io_hdr.flags &
11595				    CTL_FLAG_IO_ACTIVE) {
11596					pending_io->io_hdr.flags |=
11597						CTL_FLAG_FAILOVER;
11598				} else {
11599					ctl_set_busy(&pending_io->scsiio);
11600					ctl_done(pending_io);
11601				}
11602			}
11603
11604			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11605		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11606			&& (softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11607			printf("FAILOVER: secondary lun %d\n", lun_idx);
11608			/*
11609			 * if the first io on the OOA is not on the RtR queue
11610			 * add it.
11611			 */
11612			lun->flags |= CTL_LUN_PRIMARY_SC;
11613
11614			pending_io = (union ctl_io *)TAILQ_FIRST(
11615			    &lun->ooa_queue);
11616			if (pending_io==NULL) {
11617				printf("Nothing on OOA queue\n");
11618				continue;
11619			}
11620
11621			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11622			if ((pending_io->io_hdr.flags &
11623			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11624				pending_io->io_hdr.flags |=
11625				    CTL_FLAG_IS_WAS_ON_RTR;
11626				ctl_enqueue_rtr(pending_io);
11627			}
11628#if 0
11629			else
11630			{
11631				printf("Tag 0x%04x is running\n",
11632				      pending_io->scsiio.tag_num);
11633			}
11634#endif
11635
11636			next_io = (union ctl_io *)TAILQ_NEXT(
11637			    &pending_io->io_hdr, ooa_links);
11638			for (pending_io=next_io; pending_io != NULL;
11639			     pending_io = next_io) {
11640				pending_io->io_hdr.flags &=
11641				    ~CTL_FLAG_SENT_2OTHER_SC;
11642				next_io = (union ctl_io *)TAILQ_NEXT(
11643					&pending_io->io_hdr, ooa_links);
11644				if (pending_io->io_hdr.flags &
11645				    CTL_FLAG_IS_WAS_ON_RTR) {
11646#if 0
11647				        printf("Tag 0x%04x is running\n",
11648				      		pending_io->scsiio.tag_num);
11649#endif
11650					continue;
11651				}
11652
11653				switch (ctl_check_ooa(lun, pending_io,
11654			            (union ctl_io *)TAILQ_PREV(
11655				    &pending_io->io_hdr, ctl_ooaq,
11656				    ooa_links))) {
11657
11658				case CTL_ACTION_BLOCK:
11659					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11660							  &pending_io->io_hdr,
11661							  blocked_links);
11662					pending_io->io_hdr.flags |=
11663					    CTL_FLAG_BLOCKED;
11664					break;
11665				case CTL_ACTION_PASS:
11666				case CTL_ACTION_SKIP:
11667					pending_io->io_hdr.flags |=
11668					    CTL_FLAG_IS_WAS_ON_RTR;
11669					ctl_enqueue_rtr(pending_io);
11670					break;
11671				case CTL_ACTION_OVERLAP:
11672					ctl_set_overlapped_cmd(
11673					    (struct ctl_scsiio *)pending_io);
11674					ctl_done(pending_io);
11675					break;
11676				case CTL_ACTION_OVERLAP_TAG:
11677					ctl_set_overlapped_tag(
11678					    (struct ctl_scsiio *)pending_io,
11679					    pending_io->scsiio.tag_num & 0xff);
11680					ctl_done(pending_io);
11681					break;
11682				case CTL_ACTION_ERROR:
11683				default:
11684					ctl_set_internal_failure(
11685						(struct ctl_scsiio *)pending_io,
11686						0,  // sks_valid
11687						0); //retry count
11688					ctl_done(pending_io);
11689					break;
11690				}
11691			}
11692
11693			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11694		} else {
11695			panic("Unhandled HA mode failover, LUN flags = %#x, "
11696			      "ha_mode = #%x", lun->flags, softc->ha_mode);
11697		}
11698	}
11699	ctl_pause_rtr = 0;
11700	mtx_unlock(&softc->ctl_lock);
11701}
11702
11703static void
11704ctl_clear_ua(struct ctl_softc *ctl_softc, uint32_t initidx,
11705	     ctl_ua_type ua_type)
11706{
11707	struct ctl_lun *lun;
11708	ctl_ua_type *pu;
11709
11710	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
11711
11712	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
11713		mtx_lock(&lun->lun_lock);
11714		pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
11715		if (pu != NULL)
11716			pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua_type;
11717		mtx_unlock(&lun->lun_lock);
11718	}
11719}
11720
11721static int
11722ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11723{
11724	struct ctl_lun *lun;
11725	const struct ctl_cmd_entry *entry;
11726	uint32_t initidx, targ_lun;
11727	int retval;
11728
11729	retval = 0;
11730
11731	lun = NULL;
11732
11733	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11734	if ((targ_lun < CTL_MAX_LUNS)
11735	 && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11736		/*
11737		 * If the LUN is invalid, pretend that it doesn't exist.
11738		 * It will go away as soon as all pending I/O has been
11739		 * completed.
11740		 */
11741		mtx_lock(&lun->lun_lock);
11742		if (lun->flags & CTL_LUN_DISABLED) {
11743			mtx_unlock(&lun->lun_lock);
11744			lun = NULL;
11745			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11746			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11747		} else {
11748			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11749			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11750				lun->be_lun;
11751			if (lun->be_lun->lun_type == T_PROCESSOR) {
11752				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11753			}
11754
11755			/*
11756			 * Every I/O goes into the OOA queue for a
11757			 * particular LUN, and stays there until completion.
11758			 */
11759#ifdef CTL_TIME_IO
11760			if (TAILQ_EMPTY(&lun->ooa_queue)) {
11761				lun->idle_time += getsbinuptime() -
11762				    lun->last_busy;
11763			}
11764#endif
11765			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11766			    ooa_links);
11767		}
11768	} else {
11769		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11770		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11771	}
11772
11773	/* Get command entry and return error if it is unsuppotyed. */
11774	entry = ctl_validate_command(ctsio);
11775	if (entry == NULL) {
11776		if (lun)
11777			mtx_unlock(&lun->lun_lock);
11778		return (retval);
11779	}
11780
11781	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11782	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11783
11784	/*
11785	 * Check to see whether we can send this command to LUNs that don't
11786	 * exist.  This should pretty much only be the case for inquiry
11787	 * and request sense.  Further checks, below, really require having
11788	 * a LUN, so we can't really check the command anymore.  Just put
11789	 * it on the rtr queue.
11790	 */
11791	if (lun == NULL) {
11792		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11793			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11794			ctl_enqueue_rtr((union ctl_io *)ctsio);
11795			return (retval);
11796		}
11797
11798		ctl_set_unsupported_lun(ctsio);
11799		ctl_done((union ctl_io *)ctsio);
11800		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11801		return (retval);
11802	} else {
11803		/*
11804		 * Make sure we support this particular command on this LUN.
11805		 * e.g., we don't support writes to the control LUN.
11806		 */
11807		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11808			mtx_unlock(&lun->lun_lock);
11809			ctl_set_invalid_opcode(ctsio);
11810			ctl_done((union ctl_io *)ctsio);
11811			return (retval);
11812		}
11813	}
11814
11815	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11816
11817#ifdef CTL_WITH_CA
11818	/*
11819	 * If we've got a request sense, it'll clear the contingent
11820	 * allegiance condition.  Otherwise, if we have a CA condition for
11821	 * this initiator, clear it, because it sent down a command other
11822	 * than request sense.
11823	 */
11824	if ((ctsio->cdb[0] != REQUEST_SENSE)
11825	 && (ctl_is_set(lun->have_ca, initidx)))
11826		ctl_clear_mask(lun->have_ca, initidx);
11827#endif
11828
11829	/*
11830	 * If the command has this flag set, it handles its own unit
11831	 * attention reporting, we shouldn't do anything.  Otherwise we
11832	 * check for any pending unit attentions, and send them back to the
11833	 * initiator.  We only do this when a command initially comes in,
11834	 * not when we pull it off the blocked queue.
11835	 *
11836	 * According to SAM-3, section 5.3.2, the order that things get
11837	 * presented back to the host is basically unit attentions caused
11838	 * by some sort of reset event, busy status, reservation conflicts
11839	 * or task set full, and finally any other status.
11840	 *
11841	 * One issue here is that some of the unit attentions we report
11842	 * don't fall into the "reset" category (e.g. "reported luns data
11843	 * has changed").  So reporting it here, before the reservation
11844	 * check, may be technically wrong.  I guess the only thing to do
11845	 * would be to check for and report the reset events here, and then
11846	 * check for the other unit attention types after we check for a
11847	 * reservation conflict.
11848	 *
11849	 * XXX KDM need to fix this
11850	 */
11851	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11852		ctl_ua_type ua_type;
11853		scsi_sense_data_type sense_format;
11854
11855		if (lun->flags & CTL_LUN_SENSE_DESC)
11856			sense_format = SSD_TYPE_DESC;
11857		else
11858			sense_format = SSD_TYPE_FIXED;
11859
11860		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11861		    sense_format);
11862		if (ua_type != CTL_UA_NONE) {
11863			mtx_unlock(&lun->lun_lock);
11864			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11865			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11866			ctsio->sense_len = SSD_FULL_SIZE;
11867			ctl_done((union ctl_io *)ctsio);
11868			return (retval);
11869		}
11870	}
11871
11872
11873	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11874		mtx_unlock(&lun->lun_lock);
11875		ctl_done((union ctl_io *)ctsio);
11876		return (retval);
11877	}
11878
11879	/*
11880	 * XXX CHD this is where we want to send IO to other side if
11881	 * this LUN is secondary on this SC. We will need to make a copy
11882	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11883	 * the copy we send as FROM_OTHER.
11884	 * We also need to stuff the address of the original IO so we can
11885	 * find it easily. Something similar will need be done on the other
11886	 * side so when we are done we can find the copy.
11887	 */
11888	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11889		union ctl_ha_msg msg_info;
11890		int isc_retval;
11891
11892		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11893
11894		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11895		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11896#if 0
11897		printf("1. ctsio %p\n", ctsio);
11898#endif
11899		msg_info.hdr.serializing_sc = NULL;
11900		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11901		msg_info.scsi.tag_num = ctsio->tag_num;
11902		msg_info.scsi.tag_type = ctsio->tag_type;
11903		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11904
11905		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11906
11907		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11908		    (void *)&msg_info, sizeof(msg_info), 0)) >
11909		    CTL_HA_STATUS_SUCCESS) {
11910			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11911			       isc_retval);
11912			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11913		} else {
11914#if 0
11915			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11916#endif
11917		}
11918
11919		/*
11920		 * XXX KDM this I/O is off the incoming queue, but hasn't
11921		 * been inserted on any other queue.  We may need to come
11922		 * up with a holding queue while we wait for serialization
11923		 * so that we have an idea of what we're waiting for from
11924		 * the other side.
11925		 */
11926		mtx_unlock(&lun->lun_lock);
11927		return (retval);
11928	}
11929
11930	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11931			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11932			      ctl_ooaq, ooa_links))) {
11933	case CTL_ACTION_BLOCK:
11934		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11935		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11936				  blocked_links);
11937		mtx_unlock(&lun->lun_lock);
11938		return (retval);
11939	case CTL_ACTION_PASS:
11940	case CTL_ACTION_SKIP:
11941		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11942		mtx_unlock(&lun->lun_lock);
11943		ctl_enqueue_rtr((union ctl_io *)ctsio);
11944		break;
11945	case CTL_ACTION_OVERLAP:
11946		mtx_unlock(&lun->lun_lock);
11947		ctl_set_overlapped_cmd(ctsio);
11948		ctl_done((union ctl_io *)ctsio);
11949		break;
11950	case CTL_ACTION_OVERLAP_TAG:
11951		mtx_unlock(&lun->lun_lock);
11952		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11953		ctl_done((union ctl_io *)ctsio);
11954		break;
11955	case CTL_ACTION_ERROR:
11956	default:
11957		mtx_unlock(&lun->lun_lock);
11958		ctl_set_internal_failure(ctsio,
11959					 /*sks_valid*/ 0,
11960					 /*retry_count*/ 0);
11961		ctl_done((union ctl_io *)ctsio);
11962		break;
11963	}
11964	return (retval);
11965}
11966
11967const struct ctl_cmd_entry *
11968ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11969{
11970	const struct ctl_cmd_entry *entry;
11971	int service_action;
11972
11973	entry = &ctl_cmd_table[ctsio->cdb[0]];
11974	if (sa)
11975		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11976	if (entry->flags & CTL_CMD_FLAG_SA5) {
11977		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11978		entry = &((const struct ctl_cmd_entry *)
11979		    entry->execute)[service_action];
11980	}
11981	return (entry);
11982}
11983
11984const struct ctl_cmd_entry *
11985ctl_validate_command(struct ctl_scsiio *ctsio)
11986{
11987	const struct ctl_cmd_entry *entry;
11988	int i, sa;
11989	uint8_t diff;
11990
11991	entry = ctl_get_cmd_entry(ctsio, &sa);
11992	if (entry->execute == NULL) {
11993		if (sa)
11994			ctl_set_invalid_field(ctsio,
11995					      /*sks_valid*/ 1,
11996					      /*command*/ 1,
11997					      /*field*/ 1,
11998					      /*bit_valid*/ 1,
11999					      /*bit*/ 4);
12000		else
12001			ctl_set_invalid_opcode(ctsio);
12002		ctl_done((union ctl_io *)ctsio);
12003		return (NULL);
12004	}
12005	KASSERT(entry->length > 0,
12006	    ("Not defined length for command 0x%02x/0x%02x",
12007	     ctsio->cdb[0], ctsio->cdb[1]));
12008	for (i = 1; i < entry->length; i++) {
12009		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
12010		if (diff == 0)
12011			continue;
12012		ctl_set_invalid_field(ctsio,
12013				      /*sks_valid*/ 1,
12014				      /*command*/ 1,
12015				      /*field*/ i,
12016				      /*bit_valid*/ 1,
12017				      /*bit*/ fls(diff) - 1);
12018		ctl_done((union ctl_io *)ctsio);
12019		return (NULL);
12020	}
12021	return (entry);
12022}
12023
12024static int
12025ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
12026{
12027
12028	switch (lun_type) {
12029	case T_PROCESSOR:
12030		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
12031		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
12032			return (0);
12033		break;
12034	case T_DIRECT:
12035		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
12036		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
12037			return (0);
12038		break;
12039	default:
12040		return (0);
12041	}
12042	return (1);
12043}
12044
12045static int
12046ctl_scsiio(struct ctl_scsiio *ctsio)
12047{
12048	int retval;
12049	const struct ctl_cmd_entry *entry;
12050
12051	retval = CTL_RETVAL_COMPLETE;
12052
12053	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
12054
12055	entry = ctl_get_cmd_entry(ctsio, NULL);
12056
12057	/*
12058	 * If this I/O has been aborted, just send it straight to
12059	 * ctl_done() without executing it.
12060	 */
12061	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
12062		ctl_done((union ctl_io *)ctsio);
12063		goto bailout;
12064	}
12065
12066	/*
12067	 * All the checks should have been handled by ctl_scsiio_precheck().
12068	 * We should be clear now to just execute the I/O.
12069	 */
12070	retval = entry->execute(ctsio);
12071
12072bailout:
12073	return (retval);
12074}
12075
12076/*
12077 * Since we only implement one target right now, a bus reset simply resets
12078 * our single target.
12079 */
12080static int
12081ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
12082{
12083	return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
12084}
12085
12086static int
12087ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
12088		 ctl_ua_type ua_type)
12089{
12090	struct ctl_lun *lun;
12091	int retval;
12092
12093	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12094		union ctl_ha_msg msg_info;
12095
12096		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
12097		msg_info.hdr.nexus = io->io_hdr.nexus;
12098		if (ua_type==CTL_UA_TARG_RESET)
12099			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
12100		else
12101			msg_info.task.task_action = CTL_TASK_BUS_RESET;
12102		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12103		msg_info.hdr.original_sc = NULL;
12104		msg_info.hdr.serializing_sc = NULL;
12105		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12106		    (void *)&msg_info, sizeof(msg_info), 0)) {
12107		}
12108	}
12109	retval = 0;
12110
12111	mtx_lock(&softc->ctl_lock);
12112	STAILQ_FOREACH(lun, &softc->lun_list, links)
12113		retval += ctl_lun_reset(lun, io, ua_type);
12114	mtx_unlock(&softc->ctl_lock);
12115
12116	return (retval);
12117}
12118
12119/*
12120 * The LUN should always be set.  The I/O is optional, and is used to
12121 * distinguish between I/Os sent by this initiator, and by other
12122 * initiators.  We set unit attention for initiators other than this one.
12123 * SAM-3 is vague on this point.  It does say that a unit attention should
12124 * be established for other initiators when a LUN is reset (see section
12125 * 5.7.3), but it doesn't specifically say that the unit attention should
12126 * be established for this particular initiator when a LUN is reset.  Here
12127 * is the relevant text, from SAM-3 rev 8:
12128 *
12129 * 5.7.2 When a SCSI initiator port aborts its own tasks
12130 *
12131 * When a SCSI initiator port causes its own task(s) to be aborted, no
12132 * notification that the task(s) have been aborted shall be returned to
12133 * the SCSI initiator port other than the completion response for the
12134 * command or task management function action that caused the task(s) to
12135 * be aborted and notification(s) associated with related effects of the
12136 * action (e.g., a reset unit attention condition).
12137 *
12138 * XXX KDM for now, we're setting unit attention for all initiators.
12139 */
12140static int
12141ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
12142{
12143	union ctl_io *xio;
12144#if 0
12145	uint32_t initidx;
12146#endif
12147#ifdef CTL_WITH_CA
12148	int i;
12149#endif
12150
12151	mtx_lock(&lun->lun_lock);
12152	/*
12153	 * Run through the OOA queue and abort each I/O.
12154	 */
12155#if 0
12156	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12157#endif
12158	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12159	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12160		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
12161	}
12162
12163	/*
12164	 * This version sets unit attention for every
12165	 */
12166#if 0
12167	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12168	ctl_est_ua_all(lun, initidx, ua_type);
12169#else
12170	ctl_est_ua_all(lun, -1, ua_type);
12171#endif
12172
12173	/*
12174	 * A reset (any kind, really) clears reservations established with
12175	 * RESERVE/RELEASE.  It does not clear reservations established
12176	 * with PERSISTENT RESERVE OUT, but we don't support that at the
12177	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
12178	 * reservations made with the RESERVE/RELEASE commands, because
12179	 * those commands are obsolete in SPC-3.
12180	 */
12181	lun->flags &= ~CTL_LUN_RESERVED;
12182
12183#ifdef CTL_WITH_CA
12184	for (i = 0; i < CTL_MAX_INITIATORS; i++)
12185		ctl_clear_mask(lun->have_ca, i);
12186#endif
12187	mtx_unlock(&lun->lun_lock);
12188
12189	return (0);
12190}
12191
12192static void
12193ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
12194    int other_sc)
12195{
12196	union ctl_io *xio;
12197
12198	mtx_assert(&lun->lun_lock, MA_OWNED);
12199
12200	/*
12201	 * Run through the OOA queue and attempt to find the given I/O.
12202	 * The target port, initiator ID, tag type and tag number have to
12203	 * match the values that we got from the initiator.  If we have an
12204	 * untagged command to abort, simply abort the first untagged command
12205	 * we come to.  We only allow one untagged command at a time of course.
12206	 */
12207	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12208	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12209
12210		if ((targ_port == UINT32_MAX ||
12211		     targ_port == xio->io_hdr.nexus.targ_port) &&
12212		    (init_id == UINT32_MAX ||
12213		     init_id == xio->io_hdr.nexus.initid.id)) {
12214			if (targ_port != xio->io_hdr.nexus.targ_port ||
12215			    init_id != xio->io_hdr.nexus.initid.id)
12216				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12217			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12218			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12219				union ctl_ha_msg msg_info;
12220
12221				msg_info.hdr.nexus = xio->io_hdr.nexus;
12222				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12223				msg_info.task.tag_num = xio->scsiio.tag_num;
12224				msg_info.task.tag_type = xio->scsiio.tag_type;
12225				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12226				msg_info.hdr.original_sc = NULL;
12227				msg_info.hdr.serializing_sc = NULL;
12228				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12229				    (void *)&msg_info, sizeof(msg_info), 0);
12230			}
12231		}
12232	}
12233}
12234
12235static int
12236ctl_abort_task_set(union ctl_io *io)
12237{
12238	struct ctl_softc *softc = control_softc;
12239	struct ctl_lun *lun;
12240	uint32_t targ_lun;
12241
12242	/*
12243	 * Look up the LUN.
12244	 */
12245	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12246	mtx_lock(&softc->ctl_lock);
12247	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
12248		lun = softc->ctl_luns[targ_lun];
12249	else {
12250		mtx_unlock(&softc->ctl_lock);
12251		return (1);
12252	}
12253
12254	mtx_lock(&lun->lun_lock);
12255	mtx_unlock(&softc->ctl_lock);
12256	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12257		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12258		    io->io_hdr.nexus.initid.id,
12259		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12260	} else { /* CTL_TASK_CLEAR_TASK_SET */
12261		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12262		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12263	}
12264	mtx_unlock(&lun->lun_lock);
12265	return (0);
12266}
12267
12268static int
12269ctl_i_t_nexus_reset(union ctl_io *io)
12270{
12271	struct ctl_softc *softc = control_softc;
12272	struct ctl_lun *lun;
12273	uint32_t initidx, residx;
12274
12275	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12276	residx = ctl_get_resindex(&io->io_hdr.nexus);
12277	mtx_lock(&softc->ctl_lock);
12278	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12279		mtx_lock(&lun->lun_lock);
12280		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12281		    io->io_hdr.nexus.initid.id,
12282		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12283#ifdef CTL_WITH_CA
12284		ctl_clear_mask(lun->have_ca, initidx);
12285#endif
12286		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
12287			lun->flags &= ~CTL_LUN_RESERVED;
12288		ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12289		mtx_unlock(&lun->lun_lock);
12290	}
12291	mtx_unlock(&softc->ctl_lock);
12292	return (0);
12293}
12294
12295static int
12296ctl_abort_task(union ctl_io *io)
12297{
12298	union ctl_io *xio;
12299	struct ctl_lun *lun;
12300	struct ctl_softc *softc;
12301#if 0
12302	struct sbuf sb;
12303	char printbuf[128];
12304#endif
12305	int found;
12306	uint32_t targ_lun;
12307
12308	softc = control_softc;
12309	found = 0;
12310
12311	/*
12312	 * Look up the LUN.
12313	 */
12314	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12315	mtx_lock(&softc->ctl_lock);
12316	if ((targ_lun < CTL_MAX_LUNS)
12317	 && (softc->ctl_luns[targ_lun] != NULL))
12318		lun = softc->ctl_luns[targ_lun];
12319	else {
12320		mtx_unlock(&softc->ctl_lock);
12321		return (1);
12322	}
12323
12324#if 0
12325	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12326	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12327#endif
12328
12329	mtx_lock(&lun->lun_lock);
12330	mtx_unlock(&softc->ctl_lock);
12331	/*
12332	 * Run through the OOA queue and attempt to find the given I/O.
12333	 * The target port, initiator ID, tag type and tag number have to
12334	 * match the values that we got from the initiator.  If we have an
12335	 * untagged command to abort, simply abort the first untagged command
12336	 * we come to.  We only allow one untagged command at a time of course.
12337	 */
12338#if 0
12339	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12340#endif
12341	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12342	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12343#if 0
12344		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12345
12346		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12347			    lun->lun, xio->scsiio.tag_num,
12348			    xio->scsiio.tag_type,
12349			    (xio->io_hdr.blocked_links.tqe_prev
12350			    == NULL) ? "" : " BLOCKED",
12351			    (xio->io_hdr.flags &
12352			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12353			    (xio->io_hdr.flags &
12354			    CTL_FLAG_ABORT) ? " ABORT" : "",
12355			    (xio->io_hdr.flags &
12356			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12357		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12358		sbuf_finish(&sb);
12359		printf("%s\n", sbuf_data(&sb));
12360#endif
12361
12362		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12363		 || (xio->io_hdr.nexus.initid.id != io->io_hdr.nexus.initid.id)
12364		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12365			continue;
12366
12367		/*
12368		 * If the abort says that the task is untagged, the
12369		 * task in the queue must be untagged.  Otherwise,
12370		 * we just check to see whether the tag numbers
12371		 * match.  This is because the QLogic firmware
12372		 * doesn't pass back the tag type in an abort
12373		 * request.
12374		 */
12375#if 0
12376		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12377		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12378		 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12379#endif
12380		/*
12381		 * XXX KDM we've got problems with FC, because it
12382		 * doesn't send down a tag type with aborts.  So we
12383		 * can only really go by the tag number...
12384		 * This may cause problems with parallel SCSI.
12385		 * Need to figure that out!!
12386		 */
12387		if (xio->scsiio.tag_num == io->taskio.tag_num) {
12388			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12389			found = 1;
12390			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12391			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12392				union ctl_ha_msg msg_info;
12393
12394				io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
12395				msg_info.hdr.nexus = io->io_hdr.nexus;
12396				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12397				msg_info.task.tag_num = io->taskio.tag_num;
12398				msg_info.task.tag_type = io->taskio.tag_type;
12399				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12400				msg_info.hdr.original_sc = NULL;
12401				msg_info.hdr.serializing_sc = NULL;
12402#if 0
12403				printf("Sent Abort to other side\n");
12404#endif
12405				if (ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12406				    (void *)&msg_info, sizeof(msg_info), 0) !=
12407				    CTL_HA_STATUS_SUCCESS) {
12408				}
12409			}
12410#if 0
12411			printf("ctl_abort_task: found I/O to abort\n");
12412#endif
12413		}
12414	}
12415	mtx_unlock(&lun->lun_lock);
12416
12417	if (found == 0) {
12418		/*
12419		 * This isn't really an error.  It's entirely possible for
12420		 * the abort and command completion to cross on the wire.
12421		 * This is more of an informative/diagnostic error.
12422		 */
12423#if 0
12424		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12425		       "%d:%d:%d:%d tag %d type %d\n",
12426		       io->io_hdr.nexus.initid.id,
12427		       io->io_hdr.nexus.targ_port,
12428		       io->io_hdr.nexus.targ_target.id,
12429		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12430		       io->taskio.tag_type);
12431#endif
12432	}
12433	return (0);
12434}
12435
12436static void
12437ctl_run_task(union ctl_io *io)
12438{
12439	struct ctl_softc *softc = control_softc;
12440	int retval = 1;
12441	const char *task_desc;
12442
12443	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12444
12445	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12446	    ("ctl_run_task: Unextected io_type %d\n",
12447	     io->io_hdr.io_type));
12448
12449	task_desc = ctl_scsi_task_string(&io->taskio);
12450	if (task_desc != NULL) {
12451#ifdef NEEDTOPORT
12452		csevent_log(CSC_CTL | CSC_SHELF_SW |
12453			    CTL_TASK_REPORT,
12454			    csevent_LogType_Trace,
12455			    csevent_Severity_Information,
12456			    csevent_AlertLevel_Green,
12457			    csevent_FRU_Firmware,
12458			    csevent_FRU_Unknown,
12459			    "CTL: received task: %s",task_desc);
12460#endif
12461	} else {
12462#ifdef NEEDTOPORT
12463		csevent_log(CSC_CTL | CSC_SHELF_SW |
12464			    CTL_TASK_REPORT,
12465			    csevent_LogType_Trace,
12466			    csevent_Severity_Information,
12467			    csevent_AlertLevel_Green,
12468			    csevent_FRU_Firmware,
12469			    csevent_FRU_Unknown,
12470			    "CTL: received unknown task "
12471			    "type: %d (%#x)",
12472			    io->taskio.task_action,
12473			    io->taskio.task_action);
12474#endif
12475	}
12476	switch (io->taskio.task_action) {
12477	case CTL_TASK_ABORT_TASK:
12478		retval = ctl_abort_task(io);
12479		break;
12480	case CTL_TASK_ABORT_TASK_SET:
12481	case CTL_TASK_CLEAR_TASK_SET:
12482		retval = ctl_abort_task_set(io);
12483		break;
12484	case CTL_TASK_CLEAR_ACA:
12485		break;
12486	case CTL_TASK_I_T_NEXUS_RESET:
12487		retval = ctl_i_t_nexus_reset(io);
12488		break;
12489	case CTL_TASK_LUN_RESET: {
12490		struct ctl_lun *lun;
12491		uint32_t targ_lun;
12492
12493		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12494		mtx_lock(&softc->ctl_lock);
12495		if ((targ_lun < CTL_MAX_LUNS)
12496		 && (softc->ctl_luns[targ_lun] != NULL))
12497			lun = softc->ctl_luns[targ_lun];
12498		else {
12499			mtx_unlock(&softc->ctl_lock);
12500			retval = 1;
12501			break;
12502		}
12503
12504		if (!(io->io_hdr.flags &
12505		    CTL_FLAG_FROM_OTHER_SC)) {
12506			union ctl_ha_msg msg_info;
12507
12508			io->io_hdr.flags |=
12509				CTL_FLAG_SENT_2OTHER_SC;
12510			msg_info.hdr.msg_type =
12511				CTL_MSG_MANAGE_TASKS;
12512			msg_info.hdr.nexus = io->io_hdr.nexus;
12513			msg_info.task.task_action =
12514				CTL_TASK_LUN_RESET;
12515			msg_info.hdr.original_sc = NULL;
12516			msg_info.hdr.serializing_sc = NULL;
12517			if (CTL_HA_STATUS_SUCCESS !=
12518			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12519			    (void *)&msg_info,
12520			    sizeof(msg_info), 0)) {
12521			}
12522		}
12523
12524		retval = ctl_lun_reset(lun, io,
12525				       CTL_UA_LUN_RESET);
12526		mtx_unlock(&softc->ctl_lock);
12527		break;
12528	}
12529	case CTL_TASK_TARGET_RESET:
12530		retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12531		break;
12532	case CTL_TASK_BUS_RESET:
12533		retval = ctl_bus_reset(softc, io);
12534		break;
12535	case CTL_TASK_PORT_LOGIN:
12536		break;
12537	case CTL_TASK_PORT_LOGOUT:
12538		break;
12539	default:
12540		printf("ctl_run_task: got unknown task management event %d\n",
12541		       io->taskio.task_action);
12542		break;
12543	}
12544	if (retval == 0)
12545		io->io_hdr.status = CTL_SUCCESS;
12546	else
12547		io->io_hdr.status = CTL_ERROR;
12548	ctl_done(io);
12549}
12550
12551/*
12552 * For HA operation.  Handle commands that come in from the other
12553 * controller.
12554 */
12555static void
12556ctl_handle_isc(union ctl_io *io)
12557{
12558	int free_io;
12559	struct ctl_lun *lun;
12560	struct ctl_softc *softc;
12561	uint32_t targ_lun;
12562
12563	softc = control_softc;
12564
12565	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12566	lun = softc->ctl_luns[targ_lun];
12567
12568	switch (io->io_hdr.msg_type) {
12569	case CTL_MSG_SERIALIZE:
12570		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12571		break;
12572	case CTL_MSG_R2R: {
12573		const struct ctl_cmd_entry *entry;
12574
12575		/*
12576		 * This is only used in SER_ONLY mode.
12577		 */
12578		free_io = 0;
12579		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12580		mtx_lock(&lun->lun_lock);
12581		if (ctl_scsiio_lun_check(lun,
12582		    entry, (struct ctl_scsiio *)io) != 0) {
12583			mtx_unlock(&lun->lun_lock);
12584			ctl_done(io);
12585			break;
12586		}
12587		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12588		mtx_unlock(&lun->lun_lock);
12589		ctl_enqueue_rtr(io);
12590		break;
12591	}
12592	case CTL_MSG_FINISH_IO:
12593		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12594			free_io = 0;
12595			ctl_done(io);
12596		} else {
12597			free_io = 1;
12598			mtx_lock(&lun->lun_lock);
12599			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12600				     ooa_links);
12601			ctl_check_blocked(lun);
12602			mtx_unlock(&lun->lun_lock);
12603		}
12604		break;
12605	case CTL_MSG_PERS_ACTION:
12606		ctl_hndl_per_res_out_on_other_sc(
12607			(union ctl_ha_msg *)&io->presio.pr_msg);
12608		free_io = 1;
12609		break;
12610	case CTL_MSG_BAD_JUJU:
12611		free_io = 0;
12612		ctl_done(io);
12613		break;
12614	case CTL_MSG_DATAMOVE:
12615		/* Only used in XFER mode */
12616		free_io = 0;
12617		ctl_datamove_remote(io);
12618		break;
12619	case CTL_MSG_DATAMOVE_DONE:
12620		/* Only used in XFER mode */
12621		free_io = 0;
12622		io->scsiio.be_move_done(io);
12623		break;
12624	default:
12625		free_io = 1;
12626		printf("%s: Invalid message type %d\n",
12627		       __func__, io->io_hdr.msg_type);
12628		break;
12629	}
12630	if (free_io)
12631		ctl_free_io(io);
12632
12633}
12634
12635
12636/*
12637 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12638 * there is no match.
12639 */
12640static ctl_lun_error_pattern
12641ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12642{
12643	const struct ctl_cmd_entry *entry;
12644	ctl_lun_error_pattern filtered_pattern, pattern;
12645
12646	pattern = desc->error_pattern;
12647
12648	/*
12649	 * XXX KDM we need more data passed into this function to match a
12650	 * custom pattern, and we actually need to implement custom pattern
12651	 * matching.
12652	 */
12653	if (pattern & CTL_LUN_PAT_CMD)
12654		return (CTL_LUN_PAT_CMD);
12655
12656	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12657		return (CTL_LUN_PAT_ANY);
12658
12659	entry = ctl_get_cmd_entry(ctsio, NULL);
12660
12661	filtered_pattern = entry->pattern & pattern;
12662
12663	/*
12664	 * If the user requested specific flags in the pattern (e.g.
12665	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12666	 * flags.
12667	 *
12668	 * If the user did not specify any flags, it doesn't matter whether
12669	 * or not the command supports the flags.
12670	 */
12671	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12672	     (pattern & ~CTL_LUN_PAT_MASK))
12673		return (CTL_LUN_PAT_NONE);
12674
12675	/*
12676	 * If the user asked for a range check, see if the requested LBA
12677	 * range overlaps with this command's LBA range.
12678	 */
12679	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12680		uint64_t lba1;
12681		uint64_t len1;
12682		ctl_action action;
12683		int retval;
12684
12685		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12686		if (retval != 0)
12687			return (CTL_LUN_PAT_NONE);
12688
12689		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12690					      desc->lba_range.len, FALSE);
12691		/*
12692		 * A "pass" means that the LBA ranges don't overlap, so
12693		 * this doesn't match the user's range criteria.
12694		 */
12695		if (action == CTL_ACTION_PASS)
12696			return (CTL_LUN_PAT_NONE);
12697	}
12698
12699	return (filtered_pattern);
12700}
12701
12702static void
12703ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12704{
12705	struct ctl_error_desc *desc, *desc2;
12706
12707	mtx_assert(&lun->lun_lock, MA_OWNED);
12708
12709	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12710		ctl_lun_error_pattern pattern;
12711		/*
12712		 * Check to see whether this particular command matches
12713		 * the pattern in the descriptor.
12714		 */
12715		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12716		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12717			continue;
12718
12719		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12720		case CTL_LUN_INJ_ABORTED:
12721			ctl_set_aborted(&io->scsiio);
12722			break;
12723		case CTL_LUN_INJ_MEDIUM_ERR:
12724			ctl_set_medium_error(&io->scsiio);
12725			break;
12726		case CTL_LUN_INJ_UA:
12727			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12728			 * OCCURRED */
12729			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12730			break;
12731		case CTL_LUN_INJ_CUSTOM:
12732			/*
12733			 * We're assuming the user knows what he is doing.
12734			 * Just copy the sense information without doing
12735			 * checks.
12736			 */
12737			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12738			      MIN(sizeof(desc->custom_sense),
12739				  sizeof(io->scsiio.sense_data)));
12740			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12741			io->scsiio.sense_len = SSD_FULL_SIZE;
12742			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12743			break;
12744		case CTL_LUN_INJ_NONE:
12745		default:
12746			/*
12747			 * If this is an error injection type we don't know
12748			 * about, clear the continuous flag (if it is set)
12749			 * so it will get deleted below.
12750			 */
12751			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12752			break;
12753		}
12754		/*
12755		 * By default, each error injection action is a one-shot
12756		 */
12757		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12758			continue;
12759
12760		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12761
12762		free(desc, M_CTL);
12763	}
12764}
12765
12766#ifdef CTL_IO_DELAY
12767static void
12768ctl_datamove_timer_wakeup(void *arg)
12769{
12770	union ctl_io *io;
12771
12772	io = (union ctl_io *)arg;
12773
12774	ctl_datamove(io);
12775}
12776#endif /* CTL_IO_DELAY */
12777
12778void
12779ctl_datamove(union ctl_io *io)
12780{
12781	void (*fe_datamove)(union ctl_io *io);
12782
12783	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12784
12785	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12786
12787#ifdef CTL_TIME_IO
12788	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12789		char str[256];
12790		char path_str[64];
12791		struct sbuf sb;
12792
12793		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12794		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12795
12796		sbuf_cat(&sb, path_str);
12797		switch (io->io_hdr.io_type) {
12798		case CTL_IO_SCSI:
12799			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12800			sbuf_printf(&sb, "\n");
12801			sbuf_cat(&sb, path_str);
12802			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12803				    io->scsiio.tag_num, io->scsiio.tag_type);
12804			break;
12805		case CTL_IO_TASK:
12806			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12807				    "Tag Type: %d\n", io->taskio.task_action,
12808				    io->taskio.tag_num, io->taskio.tag_type);
12809			break;
12810		default:
12811			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12812			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12813			break;
12814		}
12815		sbuf_cat(&sb, path_str);
12816		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12817			    (intmax_t)time_uptime - io->io_hdr.start_time);
12818		sbuf_finish(&sb);
12819		printf("%s", sbuf_data(&sb));
12820	}
12821#endif /* CTL_TIME_IO */
12822
12823#ifdef CTL_IO_DELAY
12824	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12825		struct ctl_lun *lun;
12826
12827		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12828
12829		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12830	} else {
12831		struct ctl_lun *lun;
12832
12833		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12834		if ((lun != NULL)
12835		 && (lun->delay_info.datamove_delay > 0)) {
12836			struct callout *callout;
12837
12838			callout = (struct callout *)&io->io_hdr.timer_bytes;
12839			callout_init(callout, /*mpsafe*/ 1);
12840			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12841			callout_reset(callout,
12842				      lun->delay_info.datamove_delay * hz,
12843				      ctl_datamove_timer_wakeup, io);
12844			if (lun->delay_info.datamove_type ==
12845			    CTL_DELAY_TYPE_ONESHOT)
12846				lun->delay_info.datamove_delay = 0;
12847			return;
12848		}
12849	}
12850#endif
12851
12852	/*
12853	 * This command has been aborted.  Set the port status, so we fail
12854	 * the data move.
12855	 */
12856	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12857		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12858		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12859		       io->io_hdr.nexus.targ_port,
12860		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12861		       io->io_hdr.nexus.targ_lun);
12862		io->io_hdr.port_status = 31337;
12863		/*
12864		 * Note that the backend, in this case, will get the
12865		 * callback in its context.  In other cases it may get
12866		 * called in the frontend's interrupt thread context.
12867		 */
12868		io->scsiio.be_move_done(io);
12869		return;
12870	}
12871
12872	/* Don't confuse frontend with zero length data move. */
12873	if (io->scsiio.kern_data_len == 0) {
12874		io->scsiio.be_move_done(io);
12875		return;
12876	}
12877
12878	/*
12879	 * If we're in XFER mode and this I/O is from the other shelf
12880	 * controller, we need to send the DMA to the other side to
12881	 * actually transfer the data to/from the host.  In serialize only
12882	 * mode the transfer happens below CTL and ctl_datamove() is only
12883	 * called on the machine that originally received the I/O.
12884	 */
12885	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12886	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12887		union ctl_ha_msg msg;
12888		uint32_t sg_entries_sent;
12889		int do_sg_copy;
12890		int i;
12891
12892		memset(&msg, 0, sizeof(msg));
12893		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12894		msg.hdr.original_sc = io->io_hdr.original_sc;
12895		msg.hdr.serializing_sc = io;
12896		msg.hdr.nexus = io->io_hdr.nexus;
12897		msg.dt.flags = io->io_hdr.flags;
12898		/*
12899		 * We convert everything into a S/G list here.  We can't
12900		 * pass by reference, only by value between controllers.
12901		 * So we can't pass a pointer to the S/G list, only as many
12902		 * S/G entries as we can fit in here.  If it's possible for
12903		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12904		 * then we need to break this up into multiple transfers.
12905		 */
12906		if (io->scsiio.kern_sg_entries == 0) {
12907			msg.dt.kern_sg_entries = 1;
12908			/*
12909			 * If this is in cached memory, flush the cache
12910			 * before we send the DMA request to the other
12911			 * controller.  We want to do this in either the
12912			 * read or the write case.  The read case is
12913			 * straightforward.  In the write case, we want to
12914			 * make sure nothing is in the local cache that
12915			 * could overwrite the DMAed data.
12916			 */
12917			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12918				/*
12919				 * XXX KDM use bus_dmamap_sync() here.
12920				 */
12921			}
12922
12923			/*
12924			 * Convert to a physical address if this is a
12925			 * virtual address.
12926			 */
12927			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12928				msg.dt.sg_list[0].addr =
12929					io->scsiio.kern_data_ptr;
12930			} else {
12931				/*
12932				 * XXX KDM use busdma here!
12933				 */
12934#if 0
12935				msg.dt.sg_list[0].addr = (void *)
12936					vtophys(io->scsiio.kern_data_ptr);
12937#endif
12938			}
12939
12940			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12941			do_sg_copy = 0;
12942		} else {
12943			struct ctl_sg_entry *sgl;
12944
12945			do_sg_copy = 1;
12946			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12947			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12948			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12949				/*
12950				 * XXX KDM use bus_dmamap_sync() here.
12951				 */
12952			}
12953		}
12954
12955		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12956		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12957		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12958		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12959		msg.dt.sg_sequence = 0;
12960
12961		/*
12962		 * Loop until we've sent all of the S/G entries.  On the
12963		 * other end, we'll recompose these S/G entries into one
12964		 * contiguous list before passing it to the
12965		 */
12966		for (sg_entries_sent = 0; sg_entries_sent <
12967		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12968			msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list)/
12969				sizeof(msg.dt.sg_list[0])),
12970				msg.dt.kern_sg_entries - sg_entries_sent);
12971
12972			if (do_sg_copy != 0) {
12973				struct ctl_sg_entry *sgl;
12974				int j;
12975
12976				sgl = (struct ctl_sg_entry *)
12977					io->scsiio.kern_data_ptr;
12978				/*
12979				 * If this is in cached memory, flush the cache
12980				 * before we send the DMA request to the other
12981				 * controller.  We want to do this in either
12982				 * the * read or the write case.  The read
12983				 * case is straightforward.  In the write
12984				 * case, we want to make sure nothing is
12985				 * in the local cache that could overwrite
12986				 * the DMAed data.
12987				 */
12988
12989				for (i = sg_entries_sent, j = 0;
12990				     i < msg.dt.cur_sg_entries; i++, j++) {
12991					if ((io->io_hdr.flags &
12992					     CTL_FLAG_NO_DATASYNC) == 0) {
12993						/*
12994						 * XXX KDM use bus_dmamap_sync()
12995						 */
12996					}
12997					if ((io->io_hdr.flags &
12998					     CTL_FLAG_BUS_ADDR) == 0) {
12999						/*
13000						 * XXX KDM use busdma.
13001						 */
13002#if 0
13003						msg.dt.sg_list[j].addr =(void *)
13004						       vtophys(sgl[i].addr);
13005#endif
13006					} else {
13007						msg.dt.sg_list[j].addr =
13008							sgl[i].addr;
13009					}
13010					msg.dt.sg_list[j].len = sgl[i].len;
13011				}
13012			}
13013
13014			sg_entries_sent += msg.dt.cur_sg_entries;
13015			if (sg_entries_sent >= msg.dt.kern_sg_entries)
13016				msg.dt.sg_last = 1;
13017			else
13018				msg.dt.sg_last = 0;
13019
13020			/*
13021			 * XXX KDM drop and reacquire the lock here?
13022			 */
13023			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13024			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13025				/*
13026				 * XXX do something here.
13027				 */
13028			}
13029
13030			msg.dt.sent_sg_entries = sg_entries_sent;
13031		}
13032		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13033		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
13034			ctl_failover_io(io, /*have_lock*/ 0);
13035
13036	} else {
13037
13038		/*
13039		 * Lookup the fe_datamove() function for this particular
13040		 * front end.
13041		 */
13042		fe_datamove =
13043		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13044
13045		fe_datamove(io);
13046	}
13047}
13048
13049static void
13050ctl_send_datamove_done(union ctl_io *io, int have_lock)
13051{
13052	union ctl_ha_msg msg;
13053	int isc_status;
13054
13055	memset(&msg, 0, sizeof(msg));
13056
13057	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
13058	msg.hdr.original_sc = io;
13059	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13060	msg.hdr.nexus = io->io_hdr.nexus;
13061	msg.hdr.status = io->io_hdr.status;
13062	msg.scsi.tag_num = io->scsiio.tag_num;
13063	msg.scsi.tag_type = io->scsiio.tag_type;
13064	msg.scsi.scsi_status = io->scsiio.scsi_status;
13065	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13066	       sizeof(io->scsiio.sense_data));
13067	msg.scsi.sense_len = io->scsiio.sense_len;
13068	msg.scsi.sense_residual = io->scsiio.sense_residual;
13069	msg.scsi.fetd_status = io->io_hdr.port_status;
13070	msg.scsi.residual = io->scsiio.residual;
13071	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13072
13073	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13074		ctl_failover_io(io, /*have_lock*/ have_lock);
13075		return;
13076	}
13077
13078	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
13079	if (isc_status > CTL_HA_STATUS_SUCCESS) {
13080		/* XXX do something if this fails */
13081	}
13082
13083}
13084
13085/*
13086 * The DMA to the remote side is done, now we need to tell the other side
13087 * we're done so it can continue with its data movement.
13088 */
13089static void
13090ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
13091{
13092	union ctl_io *io;
13093
13094	io = rq->context;
13095
13096	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13097		printf("%s: ISC DMA write failed with error %d", __func__,
13098		       rq->ret);
13099		ctl_set_internal_failure(&io->scsiio,
13100					 /*sks_valid*/ 1,
13101					 /*retry_count*/ rq->ret);
13102	}
13103
13104	ctl_dt_req_free(rq);
13105
13106	/*
13107	 * In this case, we had to malloc the memory locally.  Free it.
13108	 */
13109	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13110		int i;
13111		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13112			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13113	}
13114	/*
13115	 * The data is in local and remote memory, so now we need to send
13116	 * status (good or back) back to the other side.
13117	 */
13118	ctl_send_datamove_done(io, /*have_lock*/ 0);
13119}
13120
13121/*
13122 * We've moved the data from the host/controller into local memory.  Now we
13123 * need to push it over to the remote controller's memory.
13124 */
13125static int
13126ctl_datamove_remote_dm_write_cb(union ctl_io *io)
13127{
13128	int retval;
13129
13130	retval = 0;
13131
13132	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
13133					  ctl_datamove_remote_write_cb);
13134
13135	return (retval);
13136}
13137
13138static void
13139ctl_datamove_remote_write(union ctl_io *io)
13140{
13141	int retval;
13142	void (*fe_datamove)(union ctl_io *io);
13143
13144	/*
13145	 * - Get the data from the host/HBA into local memory.
13146	 * - DMA memory from the local controller to the remote controller.
13147	 * - Send status back to the remote controller.
13148	 */
13149
13150	retval = ctl_datamove_remote_sgl_setup(io);
13151	if (retval != 0)
13152		return;
13153
13154	/* Switch the pointer over so the FETD knows what to do */
13155	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13156
13157	/*
13158	 * Use a custom move done callback, since we need to send completion
13159	 * back to the other controller, not to the backend on this side.
13160	 */
13161	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
13162
13163	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13164
13165	fe_datamove(io);
13166
13167	return;
13168
13169}
13170
13171static int
13172ctl_datamove_remote_dm_read_cb(union ctl_io *io)
13173{
13174#if 0
13175	char str[256];
13176	char path_str[64];
13177	struct sbuf sb;
13178#endif
13179
13180	/*
13181	 * In this case, we had to malloc the memory locally.  Free it.
13182	 */
13183	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13184		int i;
13185		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13186			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13187	}
13188
13189#if 0
13190	scsi_path_string(io, path_str, sizeof(path_str));
13191	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13192	sbuf_cat(&sb, path_str);
13193	scsi_command_string(&io->scsiio, NULL, &sb);
13194	sbuf_printf(&sb, "\n");
13195	sbuf_cat(&sb, path_str);
13196	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13197		    io->scsiio.tag_num, io->scsiio.tag_type);
13198	sbuf_cat(&sb, path_str);
13199	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
13200		    io->io_hdr.flags, io->io_hdr.status);
13201	sbuf_finish(&sb);
13202	printk("%s", sbuf_data(&sb));
13203#endif
13204
13205
13206	/*
13207	 * The read is done, now we need to send status (good or bad) back
13208	 * to the other side.
13209	 */
13210	ctl_send_datamove_done(io, /*have_lock*/ 0);
13211
13212	return (0);
13213}
13214
13215static void
13216ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
13217{
13218	union ctl_io *io;
13219	void (*fe_datamove)(union ctl_io *io);
13220
13221	io = rq->context;
13222
13223	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13224		printf("%s: ISC DMA read failed with error %d", __func__,
13225		       rq->ret);
13226		ctl_set_internal_failure(&io->scsiio,
13227					 /*sks_valid*/ 1,
13228					 /*retry_count*/ rq->ret);
13229	}
13230
13231	ctl_dt_req_free(rq);
13232
13233	/* Switch the pointer over so the FETD knows what to do */
13234	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13235
13236	/*
13237	 * Use a custom move done callback, since we need to send completion
13238	 * back to the other controller, not to the backend on this side.
13239	 */
13240	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
13241
13242	/* XXX KDM add checks like the ones in ctl_datamove? */
13243
13244	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13245
13246	fe_datamove(io);
13247}
13248
13249static int
13250ctl_datamove_remote_sgl_setup(union ctl_io *io)
13251{
13252	struct ctl_sg_entry *local_sglist, *remote_sglist;
13253	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13254	struct ctl_softc *softc;
13255	int retval;
13256	int i;
13257
13258	retval = 0;
13259	softc = control_softc;
13260
13261	local_sglist = io->io_hdr.local_sglist;
13262	local_dma_sglist = io->io_hdr.local_dma_sglist;
13263	remote_sglist = io->io_hdr.remote_sglist;
13264	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13265
13266	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13267		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13268			local_sglist[i].len = remote_sglist[i].len;
13269
13270			/*
13271			 * XXX Detect the situation where the RS-level I/O
13272			 * redirector on the other side has already read the
13273			 * data off of the AOR RS on this side, and
13274			 * transferred it to remote (mirror) memory on the
13275			 * other side.  Since we already have the data in
13276			 * memory here, we just need to use it.
13277			 *
13278			 * XXX KDM this can probably be removed once we
13279			 * get the cache device code in and take the
13280			 * current AOR implementation out.
13281			 */
13282#ifdef NEEDTOPORT
13283			if ((remote_sglist[i].addr >=
13284			     (void *)vtophys(softc->mirr->addr))
13285			 && (remote_sglist[i].addr <
13286			     ((void *)vtophys(softc->mirr->addr) +
13287			     CacheMirrorOffset))) {
13288				local_sglist[i].addr = remote_sglist[i].addr -
13289					CacheMirrorOffset;
13290				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13291				     CTL_FLAG_DATA_IN)
13292					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13293			} else {
13294				local_sglist[i].addr = remote_sglist[i].addr +
13295					CacheMirrorOffset;
13296			}
13297#endif
13298#if 0
13299			printf("%s: local %p, remote %p, len %d\n",
13300			       __func__, local_sglist[i].addr,
13301			       remote_sglist[i].addr, local_sglist[i].len);
13302#endif
13303		}
13304	} else {
13305		uint32_t len_to_go;
13306
13307		/*
13308		 * In this case, we don't have automatically allocated
13309		 * memory for this I/O on this controller.  This typically
13310		 * happens with internal CTL I/O -- e.g. inquiry, mode
13311		 * sense, etc.  Anything coming from RAIDCore will have
13312		 * a mirror area available.
13313		 */
13314		len_to_go = io->scsiio.kern_data_len;
13315
13316		/*
13317		 * Clear the no datasync flag, we have to use malloced
13318		 * buffers.
13319		 */
13320		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13321
13322		/*
13323		 * The difficult thing here is that the size of the various
13324		 * S/G segments may be different than the size from the
13325		 * remote controller.  That'll make it harder when DMAing
13326		 * the data back to the other side.
13327		 */
13328		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13329		     sizeof(io->io_hdr.remote_sglist[0])) &&
13330		     (len_to_go > 0); i++) {
13331			local_sglist[i].len = MIN(len_to_go, 131072);
13332			CTL_SIZE_8B(local_dma_sglist[i].len,
13333				    local_sglist[i].len);
13334			local_sglist[i].addr =
13335				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13336
13337			local_dma_sglist[i].addr = local_sglist[i].addr;
13338
13339			if (local_sglist[i].addr == NULL) {
13340				int j;
13341
13342				printf("malloc failed for %zd bytes!",
13343				       local_dma_sglist[i].len);
13344				for (j = 0; j < i; j++) {
13345					free(local_sglist[j].addr, M_CTL);
13346				}
13347				ctl_set_internal_failure(&io->scsiio,
13348							 /*sks_valid*/ 1,
13349							 /*retry_count*/ 4857);
13350				retval = 1;
13351				goto bailout_error;
13352
13353			}
13354			/* XXX KDM do we need a sync here? */
13355
13356			len_to_go -= local_sglist[i].len;
13357		}
13358		/*
13359		 * Reset the number of S/G entries accordingly.  The
13360		 * original number of S/G entries is available in
13361		 * rem_sg_entries.
13362		 */
13363		io->scsiio.kern_sg_entries = i;
13364
13365#if 0
13366		printf("%s: kern_sg_entries = %d\n", __func__,
13367		       io->scsiio.kern_sg_entries);
13368		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13369			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13370			       local_sglist[i].addr, local_sglist[i].len,
13371			       local_dma_sglist[i].len);
13372#endif
13373	}
13374
13375
13376	return (retval);
13377
13378bailout_error:
13379
13380	ctl_send_datamove_done(io, /*have_lock*/ 0);
13381
13382	return (retval);
13383}
13384
13385static int
13386ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13387			 ctl_ha_dt_cb callback)
13388{
13389	struct ctl_ha_dt_req *rq;
13390	struct ctl_sg_entry *remote_sglist, *local_sglist;
13391	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13392	uint32_t local_used, remote_used, total_used;
13393	int retval;
13394	int i, j;
13395
13396	retval = 0;
13397
13398	rq = ctl_dt_req_alloc();
13399
13400	/*
13401	 * If we failed to allocate the request, and if the DMA didn't fail
13402	 * anyway, set busy status.  This is just a resource allocation
13403	 * failure.
13404	 */
13405	if ((rq == NULL)
13406	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13407		ctl_set_busy(&io->scsiio);
13408
13409	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13410
13411		if (rq != NULL)
13412			ctl_dt_req_free(rq);
13413
13414		/*
13415		 * The data move failed.  We need to return status back
13416		 * to the other controller.  No point in trying to DMA
13417		 * data to the remote controller.
13418		 */
13419
13420		ctl_send_datamove_done(io, /*have_lock*/ 0);
13421
13422		retval = 1;
13423
13424		goto bailout;
13425	}
13426
13427	local_sglist = io->io_hdr.local_sglist;
13428	local_dma_sglist = io->io_hdr.local_dma_sglist;
13429	remote_sglist = io->io_hdr.remote_sglist;
13430	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13431	local_used = 0;
13432	remote_used = 0;
13433	total_used = 0;
13434
13435	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13436		rq->ret = CTL_HA_STATUS_SUCCESS;
13437		rq->context = io;
13438		callback(rq);
13439		goto bailout;
13440	}
13441
13442	/*
13443	 * Pull/push the data over the wire from/to the other controller.
13444	 * This takes into account the possibility that the local and
13445	 * remote sglists may not be identical in terms of the size of
13446	 * the elements and the number of elements.
13447	 *
13448	 * One fundamental assumption here is that the length allocated for
13449	 * both the local and remote sglists is identical.  Otherwise, we've
13450	 * essentially got a coding error of some sort.
13451	 */
13452	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13453		int isc_ret;
13454		uint32_t cur_len, dma_length;
13455		uint8_t *tmp_ptr;
13456
13457		rq->id = CTL_HA_DATA_CTL;
13458		rq->command = command;
13459		rq->context = io;
13460
13461		/*
13462		 * Both pointers should be aligned.  But it is possible
13463		 * that the allocation length is not.  They should both
13464		 * also have enough slack left over at the end, though,
13465		 * to round up to the next 8 byte boundary.
13466		 */
13467		cur_len = MIN(local_sglist[i].len - local_used,
13468			      remote_sglist[j].len - remote_used);
13469
13470		/*
13471		 * In this case, we have a size issue and need to decrease
13472		 * the size, except in the case where we actually have less
13473		 * than 8 bytes left.  In that case, we need to increase
13474		 * the DMA length to get the last bit.
13475		 */
13476		if ((cur_len & 0x7) != 0) {
13477			if (cur_len > 0x7) {
13478				cur_len = cur_len - (cur_len & 0x7);
13479				dma_length = cur_len;
13480			} else {
13481				CTL_SIZE_8B(dma_length, cur_len);
13482			}
13483
13484		} else
13485			dma_length = cur_len;
13486
13487		/*
13488		 * If we had to allocate memory for this I/O, instead of using
13489		 * the non-cached mirror memory, we'll need to flush the cache
13490		 * before trying to DMA to the other controller.
13491		 *
13492		 * We could end up doing this multiple times for the same
13493		 * segment if we have a larger local segment than remote
13494		 * segment.  That shouldn't be an issue.
13495		 */
13496		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13497			/*
13498			 * XXX KDM use bus_dmamap_sync() here.
13499			 */
13500		}
13501
13502		rq->size = dma_length;
13503
13504		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13505		tmp_ptr += local_used;
13506
13507		/* Use physical addresses when talking to ISC hardware */
13508		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13509			/* XXX KDM use busdma */
13510#if 0
13511			rq->local = vtophys(tmp_ptr);
13512#endif
13513		} else
13514			rq->local = tmp_ptr;
13515
13516		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13517		tmp_ptr += remote_used;
13518		rq->remote = tmp_ptr;
13519
13520		rq->callback = NULL;
13521
13522		local_used += cur_len;
13523		if (local_used >= local_sglist[i].len) {
13524			i++;
13525			local_used = 0;
13526		}
13527
13528		remote_used += cur_len;
13529		if (remote_used >= remote_sglist[j].len) {
13530			j++;
13531			remote_used = 0;
13532		}
13533		total_used += cur_len;
13534
13535		if (total_used >= io->scsiio.kern_data_len)
13536			rq->callback = callback;
13537
13538		if ((rq->size & 0x7) != 0) {
13539			printf("%s: warning: size %d is not on 8b boundary\n",
13540			       __func__, rq->size);
13541		}
13542		if (((uintptr_t)rq->local & 0x7) != 0) {
13543			printf("%s: warning: local %p not on 8b boundary\n",
13544			       __func__, rq->local);
13545		}
13546		if (((uintptr_t)rq->remote & 0x7) != 0) {
13547			printf("%s: warning: remote %p not on 8b boundary\n",
13548			       __func__, rq->local);
13549		}
13550#if 0
13551		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13552		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13553		       rq->local, rq->remote, rq->size);
13554#endif
13555
13556		isc_ret = ctl_dt_single(rq);
13557		if (isc_ret == CTL_HA_STATUS_WAIT)
13558			continue;
13559
13560		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13561			rq->ret = CTL_HA_STATUS_SUCCESS;
13562		} else {
13563			rq->ret = isc_ret;
13564		}
13565		callback(rq);
13566		goto bailout;
13567	}
13568
13569bailout:
13570	return (retval);
13571
13572}
13573
13574static void
13575ctl_datamove_remote_read(union ctl_io *io)
13576{
13577	int retval;
13578	int i;
13579
13580	/*
13581	 * This will send an error to the other controller in the case of a
13582	 * failure.
13583	 */
13584	retval = ctl_datamove_remote_sgl_setup(io);
13585	if (retval != 0)
13586		return;
13587
13588	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13589					  ctl_datamove_remote_read_cb);
13590	if ((retval != 0)
13591	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13592		/*
13593		 * Make sure we free memory if there was an error..  The
13594		 * ctl_datamove_remote_xfer() function will send the
13595		 * datamove done message, or call the callback with an
13596		 * error if there is a problem.
13597		 */
13598		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13599			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13600	}
13601
13602	return;
13603}
13604
13605/*
13606 * Process a datamove request from the other controller.  This is used for
13607 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13608 * first.  Once that is complete, the data gets DMAed into the remote
13609 * controller's memory.  For reads, we DMA from the remote controller's
13610 * memory into our memory first, and then move it out to the FETD.
13611 */
13612static void
13613ctl_datamove_remote(union ctl_io *io)
13614{
13615	struct ctl_softc *softc;
13616
13617	softc = control_softc;
13618
13619	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13620
13621	/*
13622	 * Note that we look for an aborted I/O here, but don't do some of
13623	 * the other checks that ctl_datamove() normally does.
13624	 * We don't need to run the datamove delay code, since that should
13625	 * have been done if need be on the other controller.
13626	 */
13627	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13628		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13629		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13630		       io->io_hdr.nexus.targ_port,
13631		       io->io_hdr.nexus.targ_target.id,
13632		       io->io_hdr.nexus.targ_lun);
13633		io->io_hdr.port_status = 31338;
13634		ctl_send_datamove_done(io, /*have_lock*/ 0);
13635		return;
13636	}
13637
13638	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13639		ctl_datamove_remote_write(io);
13640	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13641		ctl_datamove_remote_read(io);
13642	} else {
13643		union ctl_ha_msg msg;
13644		struct scsi_sense_data *sense;
13645		uint8_t sks[3];
13646		int retry_count;
13647
13648		memset(&msg, 0, sizeof(msg));
13649
13650		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13651		msg.hdr.status = CTL_SCSI_ERROR;
13652		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13653
13654		retry_count = 4243;
13655
13656		sense = &msg.scsi.sense_data;
13657		sks[0] = SSD_SCS_VALID;
13658		sks[1] = (retry_count >> 8) & 0xff;
13659		sks[2] = retry_count & 0xff;
13660
13661		/* "Internal target failure" */
13662		scsi_set_sense_data(sense,
13663				    /*sense_format*/ SSD_TYPE_NONE,
13664				    /*current_error*/ 1,
13665				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13666				    /*asc*/ 0x44,
13667				    /*ascq*/ 0x00,
13668				    /*type*/ SSD_ELEM_SKS,
13669				    /*size*/ sizeof(sks),
13670				    /*data*/ sks,
13671				    SSD_ELEM_NONE);
13672
13673		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13674		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13675			ctl_failover_io(io, /*have_lock*/ 1);
13676			return;
13677		}
13678
13679		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13680		    CTL_HA_STATUS_SUCCESS) {
13681			/* XXX KDM what to do if this fails? */
13682		}
13683		return;
13684	}
13685
13686}
13687
13688static int
13689ctl_process_done(union ctl_io *io)
13690{
13691	struct ctl_lun *lun;
13692	struct ctl_softc *softc = control_softc;
13693	void (*fe_done)(union ctl_io *io);
13694	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13695
13696	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13697
13698	fe_done = softc->ctl_ports[targ_port]->fe_done;
13699
13700#ifdef CTL_TIME_IO
13701	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13702		char str[256];
13703		char path_str[64];
13704		struct sbuf sb;
13705
13706		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13707		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13708
13709		sbuf_cat(&sb, path_str);
13710		switch (io->io_hdr.io_type) {
13711		case CTL_IO_SCSI:
13712			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13713			sbuf_printf(&sb, "\n");
13714			sbuf_cat(&sb, path_str);
13715			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13716				    io->scsiio.tag_num, io->scsiio.tag_type);
13717			break;
13718		case CTL_IO_TASK:
13719			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13720				    "Tag Type: %d\n", io->taskio.task_action,
13721				    io->taskio.tag_num, io->taskio.tag_type);
13722			break;
13723		default:
13724			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13725			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13726			break;
13727		}
13728		sbuf_cat(&sb, path_str);
13729		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13730			    (intmax_t)time_uptime - io->io_hdr.start_time);
13731		sbuf_finish(&sb);
13732		printf("%s", sbuf_data(&sb));
13733	}
13734#endif /* CTL_TIME_IO */
13735
13736	switch (io->io_hdr.io_type) {
13737	case CTL_IO_SCSI:
13738		break;
13739	case CTL_IO_TASK:
13740		if (bootverbose || (ctl_debug & CTL_DEBUG_INFO))
13741			ctl_io_error_print(io, NULL);
13742		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13743			ctl_free_io(io);
13744		else
13745			fe_done(io);
13746		return (CTL_RETVAL_COMPLETE);
13747	default:
13748		panic("ctl_process_done: invalid io type %d\n",
13749		      io->io_hdr.io_type);
13750		break; /* NOTREACHED */
13751	}
13752
13753	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13754	if (lun == NULL) {
13755		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13756				 io->io_hdr.nexus.targ_mapped_lun));
13757		goto bailout;
13758	}
13759
13760	mtx_lock(&lun->lun_lock);
13761
13762	/*
13763	 * Check to see if we have any errors to inject here.  We only
13764	 * inject errors for commands that don't already have errors set.
13765	 */
13766	if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
13767	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13768	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13769		ctl_inject_error(lun, io);
13770
13771	/*
13772	 * XXX KDM how do we treat commands that aren't completed
13773	 * successfully?
13774	 *
13775	 * XXX KDM should we also track I/O latency?
13776	 */
13777	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13778	    io->io_hdr.io_type == CTL_IO_SCSI) {
13779#ifdef CTL_TIME_IO
13780		struct bintime cur_bt;
13781#endif
13782		int type;
13783
13784		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13785		    CTL_FLAG_DATA_IN)
13786			type = CTL_STATS_READ;
13787		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13788		    CTL_FLAG_DATA_OUT)
13789			type = CTL_STATS_WRITE;
13790		else
13791			type = CTL_STATS_NO_IO;
13792
13793		lun->stats.ports[targ_port].bytes[type] +=
13794		    io->scsiio.kern_total_len;
13795		lun->stats.ports[targ_port].operations[type]++;
13796#ifdef CTL_TIME_IO
13797		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13798		   &io->io_hdr.dma_bt);
13799		lun->stats.ports[targ_port].num_dmas[type] +=
13800		    io->io_hdr.num_dmas;
13801		getbintime(&cur_bt);
13802		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13803		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13804#endif
13805	}
13806
13807	/*
13808	 * Remove this from the OOA queue.
13809	 */
13810	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13811#ifdef CTL_TIME_IO
13812	if (TAILQ_EMPTY(&lun->ooa_queue))
13813		lun->last_busy = getsbinuptime();
13814#endif
13815
13816	/*
13817	 * Run through the blocked queue on this LUN and see if anything
13818	 * has become unblocked, now that this transaction is done.
13819	 */
13820	ctl_check_blocked(lun);
13821
13822	/*
13823	 * If the LUN has been invalidated, free it if there is nothing
13824	 * left on its OOA queue.
13825	 */
13826	if ((lun->flags & CTL_LUN_INVALID)
13827	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13828		mtx_unlock(&lun->lun_lock);
13829		mtx_lock(&softc->ctl_lock);
13830		ctl_free_lun(lun);
13831		mtx_unlock(&softc->ctl_lock);
13832	} else
13833		mtx_unlock(&lun->lun_lock);
13834
13835bailout:
13836
13837	/*
13838	 * If this command has been aborted, make sure we set the status
13839	 * properly.  The FETD is responsible for freeing the I/O and doing
13840	 * whatever it needs to do to clean up its state.
13841	 */
13842	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13843		ctl_set_task_aborted(&io->scsiio);
13844
13845	/*
13846	 * If enabled, print command error status.
13847	 * We don't print UAs unless debugging was enabled explicitly.
13848	 */
13849	do {
13850		if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)
13851			break;
13852		if (!bootverbose && (ctl_debug & CTL_DEBUG_INFO) == 0)
13853			break;
13854		if ((ctl_debug & CTL_DEBUG_INFO) == 0 &&
13855		    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR) &&
13856		     (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13857			int error_code, sense_key, asc, ascq;
13858
13859			scsi_extract_sense_len(&io->scsiio.sense_data,
13860			    io->scsiio.sense_len, &error_code, &sense_key,
13861			    &asc, &ascq, /*show_errors*/ 0);
13862			if (sense_key == SSD_KEY_UNIT_ATTENTION)
13863				break;
13864		}
13865
13866		ctl_io_error_print(io, NULL);
13867	} while (0);
13868
13869	/*
13870	 * Tell the FETD or the other shelf controller we're done with this
13871	 * command.  Note that only SCSI commands get to this point.  Task
13872	 * management commands are completed above.
13873	 *
13874	 * We only send status to the other controller if we're in XFER
13875	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13876	 * received the I/O (from CTL's perspective), and so the status is
13877	 * generated there.
13878	 *
13879	 * XXX KDM if we hold the lock here, we could cause a deadlock
13880	 * if the frontend comes back in in this context to queue
13881	 * something.
13882	 */
13883	if ((softc->ha_mode == CTL_HA_MODE_XFER)
13884	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13885		union ctl_ha_msg msg;
13886
13887		memset(&msg, 0, sizeof(msg));
13888		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13889		msg.hdr.original_sc = io->io_hdr.original_sc;
13890		msg.hdr.nexus = io->io_hdr.nexus;
13891		msg.hdr.status = io->io_hdr.status;
13892		msg.scsi.scsi_status = io->scsiio.scsi_status;
13893		msg.scsi.tag_num = io->scsiio.tag_num;
13894		msg.scsi.tag_type = io->scsiio.tag_type;
13895		msg.scsi.sense_len = io->scsiio.sense_len;
13896		msg.scsi.sense_residual = io->scsiio.sense_residual;
13897		msg.scsi.residual = io->scsiio.residual;
13898		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13899		       sizeof(io->scsiio.sense_data));
13900		/*
13901		 * We copy this whether or not this is an I/O-related
13902		 * command.  Otherwise, we'd have to go and check to see
13903		 * whether it's a read/write command, and it really isn't
13904		 * worth it.
13905		 */
13906		memcpy(&msg.scsi.lbalen,
13907		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13908		       sizeof(msg.scsi.lbalen));
13909
13910		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13911				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13912			/* XXX do something here */
13913		}
13914
13915		ctl_free_io(io);
13916	} else
13917		fe_done(io);
13918
13919	return (CTL_RETVAL_COMPLETE);
13920}
13921
13922#ifdef CTL_WITH_CA
13923/*
13924 * Front end should call this if it doesn't do autosense.  When the request
13925 * sense comes back in from the initiator, we'll dequeue this and send it.
13926 */
13927int
13928ctl_queue_sense(union ctl_io *io)
13929{
13930	struct ctl_lun *lun;
13931	struct ctl_port *port;
13932	struct ctl_softc *softc;
13933	uint32_t initidx, targ_lun;
13934
13935	softc = control_softc;
13936
13937	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13938
13939	/*
13940	 * LUN lookup will likely move to the ctl_work_thread() once we
13941	 * have our new queueing infrastructure (that doesn't put things on
13942	 * a per-LUN queue initially).  That is so that we can handle
13943	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13944	 * can't deal with that right now.
13945	 */
13946	mtx_lock(&softc->ctl_lock);
13947
13948	/*
13949	 * If we don't have a LUN for this, just toss the sense
13950	 * information.
13951	 */
13952	port = ctl_io_port(&ctsio->io_hdr);
13953	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13954	if ((targ_lun < CTL_MAX_LUNS)
13955	 && (softc->ctl_luns[targ_lun] != NULL))
13956		lun = softc->ctl_luns[targ_lun];
13957	else
13958		goto bailout;
13959
13960	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13961
13962	mtx_lock(&lun->lun_lock);
13963	/*
13964	 * Already have CA set for this LUN...toss the sense information.
13965	 */
13966	if (ctl_is_set(lun->have_ca, initidx)) {
13967		mtx_unlock(&lun->lun_lock);
13968		goto bailout;
13969	}
13970
13971	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13972	       MIN(sizeof(lun->pending_sense[initidx]),
13973	       sizeof(io->scsiio.sense_data)));
13974	ctl_set_mask(lun->have_ca, initidx);
13975	mtx_unlock(&lun->lun_lock);
13976
13977bailout:
13978	mtx_unlock(&softc->ctl_lock);
13979
13980	ctl_free_io(io);
13981
13982	return (CTL_RETVAL_COMPLETE);
13983}
13984#endif
13985
13986/*
13987 * Primary command inlet from frontend ports.  All SCSI and task I/O
13988 * requests must go through this function.
13989 */
13990int
13991ctl_queue(union ctl_io *io)
13992{
13993	struct ctl_port *port;
13994
13995	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13996
13997#ifdef CTL_TIME_IO
13998	io->io_hdr.start_time = time_uptime;
13999	getbintime(&io->io_hdr.start_bt);
14000#endif /* CTL_TIME_IO */
14001
14002	/* Map FE-specific LUN ID into global one. */
14003	port = ctl_io_port(&io->io_hdr);
14004	io->io_hdr.nexus.targ_mapped_lun =
14005	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
14006
14007	switch (io->io_hdr.io_type) {
14008	case CTL_IO_SCSI:
14009	case CTL_IO_TASK:
14010		if (ctl_debug & CTL_DEBUG_CDB)
14011			ctl_io_print(io);
14012		ctl_enqueue_incoming(io);
14013		break;
14014	default:
14015		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
14016		return (EINVAL);
14017	}
14018
14019	return (CTL_RETVAL_COMPLETE);
14020}
14021
14022#ifdef CTL_IO_DELAY
14023static void
14024ctl_done_timer_wakeup(void *arg)
14025{
14026	union ctl_io *io;
14027
14028	io = (union ctl_io *)arg;
14029	ctl_done(io);
14030}
14031#endif /* CTL_IO_DELAY */
14032
14033void
14034ctl_done(union ctl_io *io)
14035{
14036
14037	/*
14038	 * Enable this to catch duplicate completion issues.
14039	 */
14040#if 0
14041	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
14042		printf("%s: type %d msg %d cdb %x iptl: "
14043		       "%d:%d:%d:%d tag 0x%04x "
14044		       "flag %#x status %x\n",
14045			__func__,
14046			io->io_hdr.io_type,
14047			io->io_hdr.msg_type,
14048			io->scsiio.cdb[0],
14049			io->io_hdr.nexus.initid.id,
14050			io->io_hdr.nexus.targ_port,
14051			io->io_hdr.nexus.targ_target.id,
14052			io->io_hdr.nexus.targ_lun,
14053			(io->io_hdr.io_type ==
14054			CTL_IO_TASK) ?
14055			io->taskio.tag_num :
14056			io->scsiio.tag_num,
14057		        io->io_hdr.flags,
14058			io->io_hdr.status);
14059	} else
14060		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
14061#endif
14062
14063	/*
14064	 * This is an internal copy of an I/O, and should not go through
14065	 * the normal done processing logic.
14066	 */
14067	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
14068		return;
14069
14070	/*
14071	 * We need to send a msg to the serializing shelf to finish the IO
14072	 * as well.  We don't send a finish message to the other shelf if
14073	 * this is a task management command.  Task management commands
14074	 * aren't serialized in the OOA queue, but rather just executed on
14075	 * both shelf controllers for commands that originated on that
14076	 * controller.
14077	 */
14078	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
14079	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
14080		union ctl_ha_msg msg_io;
14081
14082		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
14083		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
14084		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
14085		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
14086		}
14087		/* continue on to finish IO */
14088	}
14089#ifdef CTL_IO_DELAY
14090	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
14091		struct ctl_lun *lun;
14092
14093		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14094
14095		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
14096	} else {
14097		struct ctl_lun *lun;
14098
14099		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14100
14101		if ((lun != NULL)
14102		 && (lun->delay_info.done_delay > 0)) {
14103			struct callout *callout;
14104
14105			callout = (struct callout *)&io->io_hdr.timer_bytes;
14106			callout_init(callout, /*mpsafe*/ 1);
14107			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
14108			callout_reset(callout,
14109				      lun->delay_info.done_delay * hz,
14110				      ctl_done_timer_wakeup, io);
14111			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
14112				lun->delay_info.done_delay = 0;
14113			return;
14114		}
14115	}
14116#endif /* CTL_IO_DELAY */
14117
14118	ctl_enqueue_done(io);
14119}
14120
14121int
14122ctl_isc(struct ctl_scsiio *ctsio)
14123{
14124	struct ctl_lun *lun;
14125	int retval;
14126
14127	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14128
14129	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
14130
14131	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
14132
14133	retval = lun->backend->data_submit((union ctl_io *)ctsio);
14134
14135	return (retval);
14136}
14137
14138
14139static void
14140ctl_work_thread(void *arg)
14141{
14142	struct ctl_thread *thr = (struct ctl_thread *)arg;
14143	struct ctl_softc *softc = thr->ctl_softc;
14144	union ctl_io *io;
14145	int retval;
14146
14147	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
14148
14149	for (;;) {
14150		retval = 0;
14151
14152		/*
14153		 * We handle the queues in this order:
14154		 * - ISC
14155		 * - done queue (to free up resources, unblock other commands)
14156		 * - RtR queue
14157		 * - incoming queue
14158		 *
14159		 * If those queues are empty, we break out of the loop and
14160		 * go to sleep.
14161		 */
14162		mtx_lock(&thr->queue_lock);
14163		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
14164		if (io != NULL) {
14165			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
14166			mtx_unlock(&thr->queue_lock);
14167			ctl_handle_isc(io);
14168			continue;
14169		}
14170		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
14171		if (io != NULL) {
14172			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
14173			/* clear any blocked commands, call fe_done */
14174			mtx_unlock(&thr->queue_lock);
14175			retval = ctl_process_done(io);
14176			continue;
14177		}
14178		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
14179		if (io != NULL) {
14180			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
14181			mtx_unlock(&thr->queue_lock);
14182			if (io->io_hdr.io_type == CTL_IO_TASK)
14183				ctl_run_task(io);
14184			else
14185				ctl_scsiio_precheck(softc, &io->scsiio);
14186			continue;
14187		}
14188		if (!ctl_pause_rtr) {
14189			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
14190			if (io != NULL) {
14191				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
14192				mtx_unlock(&thr->queue_lock);
14193				retval = ctl_scsiio(&io->scsiio);
14194				if (retval != CTL_RETVAL_COMPLETE)
14195					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
14196				continue;
14197			}
14198		}
14199
14200		/* Sleep until we have something to do. */
14201		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
14202	}
14203}
14204
14205static void
14206ctl_lun_thread(void *arg)
14207{
14208	struct ctl_softc *softc = (struct ctl_softc *)arg;
14209	struct ctl_be_lun *be_lun;
14210	int retval;
14211
14212	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
14213
14214	for (;;) {
14215		retval = 0;
14216		mtx_lock(&softc->ctl_lock);
14217		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
14218		if (be_lun != NULL) {
14219			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
14220			mtx_unlock(&softc->ctl_lock);
14221			ctl_create_lun(be_lun);
14222			continue;
14223		}
14224
14225		/* Sleep until we have something to do. */
14226		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
14227		    PDROP | PRIBIO, "-", 0);
14228	}
14229}
14230
14231static void
14232ctl_thresh_thread(void *arg)
14233{
14234	struct ctl_softc *softc = (struct ctl_softc *)arg;
14235	struct ctl_lun *lun;
14236	struct ctl_be_lun *be_lun;
14237	struct scsi_da_rw_recovery_page *rwpage;
14238	struct ctl_logical_block_provisioning_page *page;
14239	const char *attr;
14240	uint64_t thres, val;
14241	int i, e;
14242
14243	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
14244
14245	for (;;) {
14246		mtx_lock(&softc->ctl_lock);
14247		STAILQ_FOREACH(lun, &softc->lun_list, links) {
14248			be_lun = lun->be_lun;
14249			if ((lun->flags & CTL_LUN_DISABLED) ||
14250			    (lun->flags & CTL_LUN_OFFLINE) ||
14251			    lun->backend->lun_attr == NULL)
14252				continue;
14253			rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
14254			if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
14255				continue;
14256			e = 0;
14257			page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
14258			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
14259				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
14260					continue;
14261				thres = scsi_4btoul(page->descr[i].count);
14262				thres <<= CTL_LBP_EXPONENT;
14263				switch (page->descr[i].resource) {
14264				case 0x01:
14265					attr = "blocksavail";
14266					break;
14267				case 0x02:
14268					attr = "blocksused";
14269					break;
14270				case 0xf1:
14271					attr = "poolblocksavail";
14272					break;
14273				case 0xf2:
14274					attr = "poolblocksused";
14275					break;
14276				default:
14277					continue;
14278				}
14279				mtx_unlock(&softc->ctl_lock); // XXX
14280				val = lun->backend->lun_attr(
14281				    lun->be_lun->be_lun, attr);
14282				mtx_lock(&softc->ctl_lock);
14283				if (val == UINT64_MAX)
14284					continue;
14285				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
14286				    == SLBPPD_ARMING_INC)
14287					e |= (val >= thres);
14288				else
14289					e |= (val <= thres);
14290			}
14291			mtx_lock(&lun->lun_lock);
14292			if (e) {
14293				if (lun->lasttpt == 0 ||
14294				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
14295					lun->lasttpt = time_uptime;
14296					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14297				}
14298			} else {
14299				lun->lasttpt = 0;
14300				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14301			}
14302			mtx_unlock(&lun->lun_lock);
14303		}
14304		mtx_unlock(&softc->ctl_lock);
14305		pause("-", CTL_LBP_PERIOD * hz);
14306	}
14307}
14308
14309static void
14310ctl_enqueue_incoming(union ctl_io *io)
14311{
14312	struct ctl_softc *softc = control_softc;
14313	struct ctl_thread *thr;
14314	u_int idx;
14315
14316	idx = (io->io_hdr.nexus.targ_port * 127 +
14317	       io->io_hdr.nexus.initid.id) % worker_threads;
14318	thr = &softc->threads[idx];
14319	mtx_lock(&thr->queue_lock);
14320	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14321	mtx_unlock(&thr->queue_lock);
14322	wakeup(thr);
14323}
14324
14325static void
14326ctl_enqueue_rtr(union ctl_io *io)
14327{
14328	struct ctl_softc *softc = control_softc;
14329	struct ctl_thread *thr;
14330
14331	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14332	mtx_lock(&thr->queue_lock);
14333	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14334	mtx_unlock(&thr->queue_lock);
14335	wakeup(thr);
14336}
14337
14338static void
14339ctl_enqueue_done(union ctl_io *io)
14340{
14341	struct ctl_softc *softc = control_softc;
14342	struct ctl_thread *thr;
14343
14344	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14345	mtx_lock(&thr->queue_lock);
14346	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14347	mtx_unlock(&thr->queue_lock);
14348	wakeup(thr);
14349}
14350
14351static void
14352ctl_enqueue_isc(union ctl_io *io)
14353{
14354	struct ctl_softc *softc = control_softc;
14355	struct ctl_thread *thr;
14356
14357	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14358	mtx_lock(&thr->queue_lock);
14359	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14360	mtx_unlock(&thr->queue_lock);
14361	wakeup(thr);
14362}
14363
14364/* Initialization and failover */
14365
14366void
14367ctl_init_isc_msg(void)
14368{
14369	printf("CTL: Still calling this thing\n");
14370}
14371
14372/*
14373 * Init component
14374 * 	Initializes component into configuration defined by bootMode
14375 *	(see hasc-sv.c)
14376 *  	returns hasc_Status:
14377 * 		OK
14378 *		ERROR - fatal error
14379 */
14380static ctl_ha_comp_status
14381ctl_isc_init(struct ctl_ha_component *c)
14382{
14383	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14384
14385	c->status = ret;
14386	return ret;
14387}
14388
14389/* Start component
14390 * 	Starts component in state requested. If component starts successfully,
14391 *	it must set its own state to the requestrd state
14392 *	When requested state is HASC_STATE_HA, the component may refine it
14393 * 	by adding _SLAVE or _MASTER flags.
14394 *	Currently allowed state transitions are:
14395 *	UNKNOWN->HA		- initial startup
14396 *	UNKNOWN->SINGLE - initial startup when no parter detected
14397 *	HA->SINGLE		- failover
14398 * returns ctl_ha_comp_status:
14399 * 		OK	- component successfully started in requested state
14400 *		FAILED  - could not start the requested state, failover may
14401 * 			  be possible
14402 *		ERROR	- fatal error detected, no future startup possible
14403 */
14404static ctl_ha_comp_status
14405ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14406{
14407	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14408
14409	printf("%s: go\n", __func__);
14410
14411	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14412	if (c->state == CTL_HA_STATE_UNKNOWN ) {
14413		control_softc->is_single = 0;
14414		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14415		    != CTL_HA_STATUS_SUCCESS) {
14416			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14417			ret = CTL_HA_COMP_STATUS_ERROR;
14418		}
14419	} else if (CTL_HA_STATE_IS_HA(c->state)
14420		&& CTL_HA_STATE_IS_SINGLE(state)){
14421		// HA->SINGLE transition
14422	        ctl_failover();
14423		control_softc->is_single = 1;
14424	} else {
14425		printf("ctl_isc_start:Invalid state transition %X->%X\n",
14426		       c->state, state);
14427		ret = CTL_HA_COMP_STATUS_ERROR;
14428	}
14429	if (CTL_HA_STATE_IS_SINGLE(state))
14430		control_softc->is_single = 1;
14431
14432	c->state = state;
14433	c->status = ret;
14434	return ret;
14435}
14436
14437/*
14438 * Quiesce component
14439 * The component must clear any error conditions (set status to OK) and
14440 * prepare itself to another Start call
14441 * returns ctl_ha_comp_status:
14442 * 	OK
14443 *	ERROR
14444 */
14445static ctl_ha_comp_status
14446ctl_isc_quiesce(struct ctl_ha_component *c)
14447{
14448	int ret = CTL_HA_COMP_STATUS_OK;
14449
14450	ctl_pause_rtr = 1;
14451	c->status = ret;
14452	return ret;
14453}
14454
14455struct ctl_ha_component ctl_ha_component_ctlisc =
14456{
14457	.name = "CTL ISC",
14458	.state = CTL_HA_STATE_UNKNOWN,
14459	.init = ctl_isc_init,
14460	.start = ctl_isc_start,
14461	.quiesce = ctl_isc_quiesce
14462};
14463
14464/*
14465 *  vim: ts=8
14466 */
14467