ctl.c revision 275959
1/*-
2 * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3 * Copyright (c) 2012 The FreeBSD Foundation
4 * All rights reserved.
5 *
6 * Portions of this software were developed by Edward Tomasz Napierala
7 * under sponsorship from the FreeBSD Foundation.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions, and the following disclaimer,
14 *    without modification.
15 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
16 *    substantially similar to the "NO WARRANTY" disclaimer below
17 *    ("Disclaimer") and any redistribution must be conditioned upon
18 *    including a substantially similar Disclaimer requirement for further
19 *    binary redistribution.
20 *
21 * NO WARRANTY
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
25 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
31 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGES.
33 *
34 * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/ctl.c#8 $
35 */
36/*
37 * CAM Target Layer, a SCSI device emulation subsystem.
38 *
39 * Author: Ken Merry <ken@FreeBSD.org>
40 */
41
42#define _CTL_C
43
44#include <sys/cdefs.h>
45__FBSDID("$FreeBSD: head/sys/cam/ctl/ctl.c 275959 2014-12-20 16:39:56Z 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 uint32_t ctl_map_lun(struct ctl_softc *softc, int port_num, uint32_t lun);
402static uint32_t ctl_map_lun_back(struct ctl_softc *softc, int port_num, uint32_t lun);
403static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
404			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
405static int ctl_free_lun(struct ctl_lun *lun);
406static void ctl_create_lun(struct ctl_be_lun *be_lun);
407/**
408static void ctl_failover_change_pages(struct ctl_softc *softc,
409				      struct ctl_scsiio *ctsio, int master);
410**/
411
412static int ctl_do_mode_select(union ctl_io *io);
413static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
414			   uint64_t res_key, uint64_t sa_res_key,
415			   uint8_t type, uint32_t residx,
416			   struct ctl_scsiio *ctsio,
417			   struct scsi_per_res_out *cdb,
418			   struct scsi_per_res_out_parms* param);
419static void ctl_pro_preempt_other(struct ctl_lun *lun,
420				  union ctl_ha_msg *msg);
421static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
422static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
423static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
424static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
425static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
426static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
427static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
428					 int alloc_len);
429static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
430					 int alloc_len);
431static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
432static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
433static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
434static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
435static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
436static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
437    bool seq);
438static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
439static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
440    union ctl_io *pending_io, union ctl_io *ooa_io);
441static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
442				union ctl_io *starting_io);
443static int ctl_check_blocked(struct ctl_lun *lun);
444static int ctl_scsiio_lun_check(struct ctl_lun *lun,
445				const struct ctl_cmd_entry *entry,
446				struct ctl_scsiio *ctsio);
447//static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
448static void ctl_failover(void);
449static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
450			       struct ctl_scsiio *ctsio);
451static int ctl_scsiio(struct ctl_scsiio *ctsio);
452
453static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
454static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
455			    ctl_ua_type ua_type);
456static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
457			 ctl_ua_type ua_type);
458static int ctl_abort_task(union ctl_io *io);
459static int ctl_abort_task_set(union ctl_io *io);
460static int ctl_i_t_nexus_reset(union ctl_io *io);
461static void ctl_run_task(union ctl_io *io);
462#ifdef CTL_IO_DELAY
463static void ctl_datamove_timer_wakeup(void *arg);
464static void ctl_done_timer_wakeup(void *arg);
465#endif /* CTL_IO_DELAY */
466
467static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
468static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
469static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
470static void ctl_datamove_remote_write(union ctl_io *io);
471static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
472static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
473static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
474static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
475				    ctl_ha_dt_cb callback);
476static void ctl_datamove_remote_read(union ctl_io *io);
477static void ctl_datamove_remote(union ctl_io *io);
478static int ctl_process_done(union ctl_io *io);
479static void ctl_lun_thread(void *arg);
480static void ctl_thresh_thread(void *arg);
481static void ctl_work_thread(void *arg);
482static void ctl_enqueue_incoming(union ctl_io *io);
483static void ctl_enqueue_rtr(union ctl_io *io);
484static void ctl_enqueue_done(union ctl_io *io);
485static void ctl_enqueue_isc(union ctl_io *io);
486static const struct ctl_cmd_entry *
487    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
488static const struct ctl_cmd_entry *
489    ctl_validate_command(struct ctl_scsiio *ctsio);
490static int ctl_cmd_applicable(uint8_t lun_type,
491    const struct ctl_cmd_entry *entry);
492
493/*
494 * Load the serialization table.  This isn't very pretty, but is probably
495 * the easiest way to do it.
496 */
497#include "ctl_ser_table.c"
498
499/*
500 * We only need to define open, close and ioctl routines for this driver.
501 */
502static struct cdevsw ctl_cdevsw = {
503	.d_version =	D_VERSION,
504	.d_flags =	0,
505	.d_open =	ctl_open,
506	.d_close =	ctl_close,
507	.d_ioctl =	ctl_ioctl,
508	.d_name =	"ctl",
509};
510
511
512MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
513MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
514
515static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
516
517static moduledata_t ctl_moduledata = {
518	"ctl",
519	ctl_module_event_handler,
520	NULL
521};
522
523DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
524MODULE_VERSION(ctl, 1);
525
526static struct ctl_frontend ioctl_frontend =
527{
528	.name = "ioctl",
529};
530
531static void
532ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
533			    union ctl_ha_msg *msg_info)
534{
535	struct ctl_scsiio *ctsio;
536
537	if (msg_info->hdr.original_sc == NULL) {
538		printf("%s: original_sc == NULL!\n", __func__);
539		/* XXX KDM now what? */
540		return;
541	}
542
543	ctsio = &msg_info->hdr.original_sc->scsiio;
544	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
545	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
546	ctsio->io_hdr.status = msg_info->hdr.status;
547	ctsio->scsi_status = msg_info->scsi.scsi_status;
548	ctsio->sense_len = msg_info->scsi.sense_len;
549	ctsio->sense_residual = msg_info->scsi.sense_residual;
550	ctsio->residual = msg_info->scsi.residual;
551	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
552	       sizeof(ctsio->sense_data));
553	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
554	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
555	ctl_enqueue_isc((union ctl_io *)ctsio);
556}
557
558static void
559ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
560				union ctl_ha_msg *msg_info)
561{
562	struct ctl_scsiio *ctsio;
563
564	if (msg_info->hdr.serializing_sc == NULL) {
565		printf("%s: serializing_sc == NULL!\n", __func__);
566		/* XXX KDM now what? */
567		return;
568	}
569
570	ctsio = &msg_info->hdr.serializing_sc->scsiio;
571#if 0
572	/*
573	 * Attempt to catch the situation where an I/O has
574	 * been freed, and we're using it again.
575	 */
576	if (ctsio->io_hdr.io_type == 0xff) {
577		union ctl_io *tmp_io;
578		tmp_io = (union ctl_io *)ctsio;
579		printf("%s: %p use after free!\n", __func__,
580		       ctsio);
581		printf("%s: type %d msg %d cdb %x iptl: "
582		       "%d:%d:%d:%d tag 0x%04x "
583		       "flag %#x status %x\n",
584			__func__,
585			tmp_io->io_hdr.io_type,
586			tmp_io->io_hdr.msg_type,
587			tmp_io->scsiio.cdb[0],
588			tmp_io->io_hdr.nexus.initid.id,
589			tmp_io->io_hdr.nexus.targ_port,
590			tmp_io->io_hdr.nexus.targ_target.id,
591			tmp_io->io_hdr.nexus.targ_lun,
592			(tmp_io->io_hdr.io_type ==
593			CTL_IO_TASK) ?
594			tmp_io->taskio.tag_num :
595			tmp_io->scsiio.tag_num,
596		        tmp_io->io_hdr.flags,
597			tmp_io->io_hdr.status);
598	}
599#endif
600	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
601	ctl_enqueue_isc((union ctl_io *)ctsio);
602}
603
604/*
605 * ISC (Inter Shelf Communication) event handler.  Events from the HA
606 * subsystem come in here.
607 */
608static void
609ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
610{
611	struct ctl_softc *softc;
612	union ctl_io *io;
613	struct ctl_prio *presio;
614	ctl_ha_status isc_status;
615
616	softc = control_softc;
617	io = NULL;
618
619
620#if 0
621	printf("CTL: Isc Msg event %d\n", event);
622#endif
623	if (event == CTL_HA_EVT_MSG_RECV) {
624		union ctl_ha_msg msg_info;
625
626		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
627					     sizeof(msg_info), /*wait*/ 0);
628#if 0
629		printf("CTL: msg_type %d\n", msg_info.msg_type);
630#endif
631		if (isc_status != 0) {
632			printf("Error receiving message, status = %d\n",
633			       isc_status);
634			return;
635		}
636
637		switch (msg_info.hdr.msg_type) {
638		case CTL_MSG_SERIALIZE:
639#if 0
640			printf("Serialize\n");
641#endif
642			io = ctl_alloc_io_nowait(softc->othersc_pool);
643			if (io == NULL) {
644				printf("ctl_isc_event_handler: can't allocate "
645				       "ctl_io!\n");
646				/* Bad Juju */
647				/* Need to set busy and send msg back */
648				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
649				msg_info.hdr.status = CTL_SCSI_ERROR;
650				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
651				msg_info.scsi.sense_len = 0;
652			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
653				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
654				}
655				goto bailout;
656			}
657			ctl_zero_io(io);
658			// populate ctsio from msg_info
659			io->io_hdr.io_type = CTL_IO_SCSI;
660			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
661			io->io_hdr.original_sc = msg_info.hdr.original_sc;
662#if 0
663			printf("pOrig %x\n", (int)msg_info.original_sc);
664#endif
665			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
666					    CTL_FLAG_IO_ACTIVE;
667			/*
668			 * If we're in serialization-only mode, we don't
669			 * want to go through full done processing.  Thus
670			 * the COPY flag.
671			 *
672			 * XXX KDM add another flag that is more specific.
673			 */
674			if (softc->ha_mode == CTL_HA_MODE_SER_ONLY)
675				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
676			io->io_hdr.nexus = msg_info.hdr.nexus;
677#if 0
678			printf("targ %d, port %d, iid %d, lun %d\n",
679			       io->io_hdr.nexus.targ_target.id,
680			       io->io_hdr.nexus.targ_port,
681			       io->io_hdr.nexus.initid.id,
682			       io->io_hdr.nexus.targ_lun);
683#endif
684			io->scsiio.tag_num = msg_info.scsi.tag_num;
685			io->scsiio.tag_type = msg_info.scsi.tag_type;
686			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
687			       CTL_MAX_CDBLEN);
688			if (softc->ha_mode == CTL_HA_MODE_XFER) {
689				const struct ctl_cmd_entry *entry;
690
691				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
692				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
693				io->io_hdr.flags |=
694					entry->flags & CTL_FLAG_DATA_MASK;
695			}
696			ctl_enqueue_isc(io);
697			break;
698
699		/* Performed on the Originating SC, XFER mode only */
700		case CTL_MSG_DATAMOVE: {
701			struct ctl_sg_entry *sgl;
702			int i, j;
703
704			io = msg_info.hdr.original_sc;
705			if (io == NULL) {
706				printf("%s: original_sc == NULL!\n", __func__);
707				/* XXX KDM do something here */
708				break;
709			}
710			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
711			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
712			/*
713			 * Keep track of this, we need to send it back over
714			 * when the datamove is complete.
715			 */
716			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
717
718			if (msg_info.dt.sg_sequence == 0) {
719				/*
720				 * XXX KDM we use the preallocated S/G list
721				 * here, but we'll need to change this to
722				 * dynamic allocation if we need larger S/G
723				 * lists.
724				 */
725				if (msg_info.dt.kern_sg_entries >
726				    sizeof(io->io_hdr.remote_sglist) /
727				    sizeof(io->io_hdr.remote_sglist[0])) {
728					printf("%s: number of S/G entries "
729					    "needed %u > allocated num %zd\n",
730					    __func__,
731					    msg_info.dt.kern_sg_entries,
732					    sizeof(io->io_hdr.remote_sglist)/
733					    sizeof(io->io_hdr.remote_sglist[0]));
734
735					/*
736					 * XXX KDM send a message back to
737					 * the other side to shut down the
738					 * DMA.  The error will come back
739					 * through via the normal channel.
740					 */
741					break;
742				}
743				sgl = io->io_hdr.remote_sglist;
744				memset(sgl, 0,
745				       sizeof(io->io_hdr.remote_sglist));
746
747				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
748
749				io->scsiio.kern_sg_entries =
750					msg_info.dt.kern_sg_entries;
751				io->scsiio.rem_sg_entries =
752					msg_info.dt.kern_sg_entries;
753				io->scsiio.kern_data_len =
754					msg_info.dt.kern_data_len;
755				io->scsiio.kern_total_len =
756					msg_info.dt.kern_total_len;
757				io->scsiio.kern_data_resid =
758					msg_info.dt.kern_data_resid;
759				io->scsiio.kern_rel_offset =
760					msg_info.dt.kern_rel_offset;
761				/*
762				 * Clear out per-DMA flags.
763				 */
764				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
765				/*
766				 * Add per-DMA flags that are set for this
767				 * particular DMA request.
768				 */
769				io->io_hdr.flags |= msg_info.dt.flags &
770						    CTL_FLAG_RDMA_MASK;
771			} else
772				sgl = (struct ctl_sg_entry *)
773					io->scsiio.kern_data_ptr;
774
775			for (i = msg_info.dt.sent_sg_entries, j = 0;
776			     i < (msg_info.dt.sent_sg_entries +
777			     msg_info.dt.cur_sg_entries); i++, j++) {
778				sgl[i].addr = msg_info.dt.sg_list[j].addr;
779				sgl[i].len = msg_info.dt.sg_list[j].len;
780
781#if 0
782				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
783				       __func__,
784				       msg_info.dt.sg_list[j].addr,
785				       msg_info.dt.sg_list[j].len,
786				       sgl[i].addr, sgl[i].len, j, i);
787#endif
788			}
789#if 0
790			memcpy(&sgl[msg_info.dt.sent_sg_entries],
791			       msg_info.dt.sg_list,
792			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
793#endif
794
795			/*
796			 * If this is the last piece of the I/O, we've got
797			 * the full S/G list.  Queue processing in the thread.
798			 * Otherwise wait for the next piece.
799			 */
800			if (msg_info.dt.sg_last != 0)
801				ctl_enqueue_isc(io);
802			break;
803		}
804		/* Performed on the Serializing (primary) SC, XFER mode only */
805		case CTL_MSG_DATAMOVE_DONE: {
806			if (msg_info.hdr.serializing_sc == NULL) {
807				printf("%s: serializing_sc == NULL!\n",
808				       __func__);
809				/* XXX KDM now what? */
810				break;
811			}
812			/*
813			 * We grab the sense information here in case
814			 * there was a failure, so we can return status
815			 * back to the initiator.
816			 */
817			io = msg_info.hdr.serializing_sc;
818			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
819			io->io_hdr.status = msg_info.hdr.status;
820			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
821			io->scsiio.sense_len = msg_info.scsi.sense_len;
822			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
823			io->io_hdr.port_status = msg_info.scsi.fetd_status;
824			io->scsiio.residual = msg_info.scsi.residual;
825			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
826			       sizeof(io->scsiio.sense_data));
827			ctl_enqueue_isc(io);
828			break;
829		}
830
831		/* Preformed on Originating SC, SER_ONLY mode */
832		case CTL_MSG_R2R:
833			io = msg_info.hdr.original_sc;
834			if (io == NULL) {
835				printf("%s: Major Bummer\n", __func__);
836				return;
837			} else {
838#if 0
839				printf("pOrig %x\n",(int) ctsio);
840#endif
841			}
842			io->io_hdr.msg_type = CTL_MSG_R2R;
843			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
844			ctl_enqueue_isc(io);
845			break;
846
847		/*
848		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
849		 * mode.
850		 * Performed on the Originating (i.e. secondary) SC in XFER
851		 * mode
852		 */
853		case CTL_MSG_FINISH_IO:
854			if (softc->ha_mode == CTL_HA_MODE_XFER)
855				ctl_isc_handler_finish_xfer(softc,
856							    &msg_info);
857			else
858				ctl_isc_handler_finish_ser_only(softc,
859								&msg_info);
860			break;
861
862		/* Preformed on Originating SC */
863		case CTL_MSG_BAD_JUJU:
864			io = msg_info.hdr.original_sc;
865			if (io == NULL) {
866				printf("%s: Bad JUJU!, original_sc is NULL!\n",
867				       __func__);
868				break;
869			}
870			ctl_copy_sense_data(&msg_info, io);
871			/*
872			 * IO should have already been cleaned up on other
873			 * SC so clear this flag so we won't send a message
874			 * back to finish the IO there.
875			 */
876			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
877			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
878
879			/* io = msg_info.hdr.serializing_sc; */
880			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
881			ctl_enqueue_isc(io);
882			break;
883
884		/* Handle resets sent from the other side */
885		case CTL_MSG_MANAGE_TASKS: {
886			struct ctl_taskio *taskio;
887			taskio = (struct ctl_taskio *)ctl_alloc_io_nowait(
888			    softc->othersc_pool);
889			if (taskio == NULL) {
890				printf("ctl_isc_event_handler: can't allocate "
891				       "ctl_io!\n");
892				/* Bad Juju */
893				/* should I just call the proper reset func
894				   here??? */
895				goto bailout;
896			}
897			ctl_zero_io((union ctl_io *)taskio);
898			taskio->io_hdr.io_type = CTL_IO_TASK;
899			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
900			taskio->io_hdr.nexus = msg_info.hdr.nexus;
901			taskio->task_action = msg_info.task.task_action;
902			taskio->tag_num = msg_info.task.tag_num;
903			taskio->tag_type = msg_info.task.tag_type;
904#ifdef CTL_TIME_IO
905			taskio->io_hdr.start_time = time_uptime;
906			getbintime(&taskio->io_hdr.start_bt);
907#if 0
908			cs_prof_gettime(&taskio->io_hdr.start_ticks);
909#endif
910#endif /* CTL_TIME_IO */
911			ctl_run_task((union ctl_io *)taskio);
912			break;
913		}
914		/* Persistent Reserve action which needs attention */
915		case CTL_MSG_PERS_ACTION:
916			presio = (struct ctl_prio *)ctl_alloc_io_nowait(
917			    softc->othersc_pool);
918			if (presio == NULL) {
919				printf("ctl_isc_event_handler: can't allocate "
920				       "ctl_io!\n");
921				/* Bad Juju */
922				/* Need to set busy and send msg back */
923				goto bailout;
924			}
925			ctl_zero_io((union ctl_io *)presio);
926			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
927			presio->pr_msg = msg_info.pr;
928			ctl_enqueue_isc((union ctl_io *)presio);
929			break;
930		case CTL_MSG_SYNC_FE:
931			rcv_sync_msg = 1;
932			break;
933		default:
934		        printf("How did I get here?\n");
935		}
936	} else if (event == CTL_HA_EVT_MSG_SENT) {
937		if (param != CTL_HA_STATUS_SUCCESS) {
938			printf("Bad status from ctl_ha_msg_send status %d\n",
939			       param);
940		}
941		return;
942	} else if (event == CTL_HA_EVT_DISCONNECT) {
943		printf("CTL: Got a disconnect from Isc\n");
944		return;
945	} else {
946		printf("ctl_isc_event_handler: Unknown event %d\n", event);
947		return;
948	}
949
950bailout:
951	return;
952}
953
954static void
955ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
956{
957	struct scsi_sense_data *sense;
958
959	sense = &dest->scsiio.sense_data;
960	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
961	dest->scsiio.scsi_status = src->scsi.scsi_status;
962	dest->scsiio.sense_len = src->scsi.sense_len;
963	dest->io_hdr.status = src->hdr.status;
964}
965
966static void
967ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
968{
969	ctl_ua_type *pu;
970
971	mtx_assert(&lun->lun_lock, MA_OWNED);
972	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
973	if (pu == NULL)
974		return;
975	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
976}
977
978static void
979ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
980{
981	int i, j;
982
983	mtx_assert(&lun->lun_lock, MA_OWNED);
984	for (i = 0; i < CTL_MAX_PORTS; i++) {
985		if (lun->pending_ua[i] == NULL)
986			continue;
987		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
988			if (i * CTL_MAX_INIT_PER_PORT + j == except)
989				continue;
990			lun->pending_ua[i][j] |= ua;
991		}
992	}
993}
994
995static void
996ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
997{
998	ctl_ua_type *pu;
999
1000	mtx_assert(&lun->lun_lock, MA_OWNED);
1001	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1002	if (pu == NULL)
1003		return;
1004	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1005}
1006
1007static void
1008ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1009{
1010	int i, j;
1011
1012	mtx_assert(&lun->lun_lock, MA_OWNED);
1013	for (i = 0; i < CTL_MAX_PORTS; i++) {
1014		if (lun->pending_ua[i] == NULL)
1015			continue;
1016		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1017			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1018				continue;
1019			lun->pending_ua[i][j] &= ~ua;
1020		}
1021	}
1022}
1023
1024static int
1025ctl_ha_state_sysctl(SYSCTL_HANDLER_ARGS)
1026{
1027	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1028	struct ctl_lun *lun;
1029	int error, value;
1030
1031	if (softc->flags & CTL_FLAG_ACTIVE_SHELF)
1032		value = 0;
1033	else
1034		value = 1;
1035
1036	error = sysctl_handle_int(oidp, &value, 0, req);
1037	if ((error != 0) || (req->newptr == NULL))
1038		return (error);
1039
1040	mtx_lock(&softc->ctl_lock);
1041	if (value == 0)
1042		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1043	else
1044		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1045	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1046		mtx_lock(&lun->lun_lock);
1047		ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1048		mtx_unlock(&lun->lun_lock);
1049	}
1050	mtx_unlock(&softc->ctl_lock);
1051	return (0);
1052}
1053
1054static int
1055ctl_init(void)
1056{
1057	struct ctl_softc *softc;
1058	void *other_pool;
1059	struct ctl_port *port;
1060	int i, error, retval;
1061	//int isc_retval;
1062
1063	retval = 0;
1064	ctl_pause_rtr = 0;
1065        rcv_sync_msg = 0;
1066
1067	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1068			       M_WAITOK | M_ZERO);
1069	softc = control_softc;
1070
1071	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1072			      "cam/ctl");
1073
1074	softc->dev->si_drv1 = softc;
1075
1076	/*
1077	 * By default, return a "bad LUN" peripheral qualifier for unknown
1078	 * LUNs.  The user can override this default using the tunable or
1079	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
1080	 */
1081	softc->inquiry_pq_no_lun = 1;
1082	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
1083			  &softc->inquiry_pq_no_lun);
1084	sysctl_ctx_init(&softc->sysctl_ctx);
1085	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1086		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1087		CTLFLAG_RD, 0, "CAM Target Layer");
1088
1089	if (softc->sysctl_tree == NULL) {
1090		printf("%s: unable to allocate sysctl tree\n", __func__);
1091		destroy_dev(softc->dev);
1092		free(control_softc, M_DEVBUF);
1093		control_softc = NULL;
1094		return (ENOMEM);
1095	}
1096
1097	SYSCTL_ADD_INT(&softc->sysctl_ctx,
1098		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1099		       "inquiry_pq_no_lun", CTLFLAG_RW,
1100		       &softc->inquiry_pq_no_lun, 0,
1101		       "Report no lun possible for invalid LUNs");
1102
1103	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1104	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1105	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1106	softc->open_count = 0;
1107
1108	/*
1109	 * Default to actually sending a SYNCHRONIZE CACHE command down to
1110	 * the drive.
1111	 */
1112	softc->flags = CTL_FLAG_REAL_SYNC;
1113
1114	/*
1115	 * In Copan's HA scheme, the "master" and "slave" roles are
1116	 * figured out through the slot the controller is in.  Although it
1117	 * is an active/active system, someone has to be in charge.
1118	 */
1119	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1120	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1121	    "HA head ID (0 - no HA)");
1122	if (softc->ha_id == 0) {
1123		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1124		softc->is_single = 1;
1125		softc->port_offset = 0;
1126	} else
1127		softc->port_offset = (softc->ha_id - 1) * CTL_MAX_PORTS;
1128	softc->persis_offset = softc->port_offset * CTL_MAX_INIT_PER_PORT;
1129
1130	/*
1131	 * XXX KDM need to figure out where we want to get our target ID
1132	 * and WWID.  Is it different on each port?
1133	 */
1134	softc->target.id = 0;
1135	softc->target.wwid[0] = 0x12345678;
1136	softc->target.wwid[1] = 0x87654321;
1137	STAILQ_INIT(&softc->lun_list);
1138	STAILQ_INIT(&softc->pending_lun_queue);
1139	STAILQ_INIT(&softc->fe_list);
1140	STAILQ_INIT(&softc->port_list);
1141	STAILQ_INIT(&softc->be_list);
1142	ctl_tpc_init(softc);
1143
1144	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1145	                    &other_pool) != 0)
1146	{
1147		printf("ctl: can't allocate %d entry other SC pool, "
1148		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1149		return (ENOMEM);
1150	}
1151	softc->othersc_pool = other_pool;
1152
1153	if (worker_threads <= 0)
1154		worker_threads = max(1, mp_ncpus / 4);
1155	if (worker_threads > CTL_MAX_THREADS)
1156		worker_threads = CTL_MAX_THREADS;
1157
1158	for (i = 0; i < worker_threads; i++) {
1159		struct ctl_thread *thr = &softc->threads[i];
1160
1161		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1162		thr->ctl_softc = softc;
1163		STAILQ_INIT(&thr->incoming_queue);
1164		STAILQ_INIT(&thr->rtr_queue);
1165		STAILQ_INIT(&thr->done_queue);
1166		STAILQ_INIT(&thr->isc_queue);
1167
1168		error = kproc_kthread_add(ctl_work_thread, thr,
1169		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1170		if (error != 0) {
1171			printf("error creating CTL work thread!\n");
1172			ctl_pool_free(other_pool);
1173			return (error);
1174		}
1175	}
1176	error = kproc_kthread_add(ctl_lun_thread, softc,
1177	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1178	if (error != 0) {
1179		printf("error creating CTL lun thread!\n");
1180		ctl_pool_free(other_pool);
1181		return (error);
1182	}
1183	error = kproc_kthread_add(ctl_thresh_thread, softc,
1184	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1185	if (error != 0) {
1186		printf("error creating CTL threshold thread!\n");
1187		ctl_pool_free(other_pool);
1188		return (error);
1189	}
1190	if (bootverbose)
1191		printf("ctl: CAM Target Layer loaded\n");
1192
1193	/*
1194	 * Initialize the ioctl front end.
1195	 */
1196	ctl_frontend_register(&ioctl_frontend);
1197	port = &softc->ioctl_info.port;
1198	port->frontend = &ioctl_frontend;
1199	sprintf(softc->ioctl_info.port_name, "ioctl");
1200	port->port_type = CTL_PORT_IOCTL;
1201	port->num_requested_ctl_io = 100;
1202	port->port_name = softc->ioctl_info.port_name;
1203	port->port_online = ctl_ioctl_online;
1204	port->port_offline = ctl_ioctl_offline;
1205	port->onoff_arg = &softc->ioctl_info;
1206	port->lun_enable = ctl_ioctl_lun_enable;
1207	port->lun_disable = ctl_ioctl_lun_disable;
1208	port->targ_lun_arg = &softc->ioctl_info;
1209	port->fe_datamove = ctl_ioctl_datamove;
1210	port->fe_done = ctl_ioctl_done;
1211	port->max_targets = 15;
1212	port->max_target_id = 15;
1213
1214	if (ctl_port_register(&softc->ioctl_info.port) != 0) {
1215		printf("ctl: ioctl front end registration failed, will "
1216		       "continue anyway\n");
1217	}
1218
1219	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1220	    OID_AUTO, "ha_state", CTLTYPE_INT | CTLFLAG_RWTUN,
1221	    softc, 0, ctl_ha_state_sysctl, "I", "HA state for this head");
1222
1223#ifdef CTL_IO_DELAY
1224	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1225		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1226		       sizeof(struct callout), CTL_TIMER_BYTES);
1227		return (EINVAL);
1228	}
1229#endif /* CTL_IO_DELAY */
1230
1231	return (0);
1232}
1233
1234void
1235ctl_shutdown(void)
1236{
1237	struct ctl_softc *softc;
1238	struct ctl_lun *lun, *next_lun;
1239
1240	softc = (struct ctl_softc *)control_softc;
1241
1242	if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1243		printf("ctl: ioctl front end deregistration failed\n");
1244
1245	mtx_lock(&softc->ctl_lock);
1246
1247	/*
1248	 * Free up each LUN.
1249	 */
1250	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1251		next_lun = STAILQ_NEXT(lun, links);
1252		ctl_free_lun(lun);
1253	}
1254
1255	mtx_unlock(&softc->ctl_lock);
1256
1257	ctl_frontend_deregister(&ioctl_frontend);
1258
1259#if 0
1260	ctl_shutdown_thread(softc->work_thread);
1261	mtx_destroy(&softc->queue_lock);
1262#endif
1263
1264	ctl_tpc_shutdown(softc);
1265	uma_zdestroy(softc->io_zone);
1266	mtx_destroy(&softc->ctl_lock);
1267
1268	destroy_dev(softc->dev);
1269
1270	sysctl_ctx_free(&softc->sysctl_ctx);
1271
1272	free(control_softc, M_DEVBUF);
1273	control_softc = NULL;
1274
1275	if (bootverbose)
1276		printf("ctl: CAM Target Layer unloaded\n");
1277}
1278
1279static int
1280ctl_module_event_handler(module_t mod, int what, void *arg)
1281{
1282
1283	switch (what) {
1284	case MOD_LOAD:
1285		return (ctl_init());
1286	case MOD_UNLOAD:
1287		return (EBUSY);
1288	default:
1289		return (EOPNOTSUPP);
1290	}
1291}
1292
1293/*
1294 * XXX KDM should we do some access checks here?  Bump a reference count to
1295 * prevent a CTL module from being unloaded while someone has it open?
1296 */
1297static int
1298ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1299{
1300	return (0);
1301}
1302
1303static int
1304ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1305{
1306	return (0);
1307}
1308
1309int
1310ctl_port_enable(ctl_port_type port_type)
1311{
1312	struct ctl_softc *softc = control_softc;
1313	struct ctl_port *port;
1314
1315	if (softc->is_single == 0) {
1316		union ctl_ha_msg msg_info;
1317		int isc_retval;
1318
1319#if 0
1320		printf("%s: HA mode, synchronizing frontend enable\n",
1321		        __func__);
1322#endif
1323		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1324	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1325		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1326			printf("Sync msg send error retval %d\n", isc_retval);
1327		}
1328		if (!rcv_sync_msg) {
1329			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1330			        sizeof(msg_info), 1);
1331		}
1332#if 0
1333        	printf("CTL:Frontend Enable\n");
1334	} else {
1335		printf("%s: single mode, skipping frontend synchronization\n",
1336		        __func__);
1337#endif
1338	}
1339
1340	STAILQ_FOREACH(port, &softc->port_list, links) {
1341		if (port_type & port->port_type)
1342		{
1343#if 0
1344			printf("port %d\n", port->targ_port);
1345#endif
1346			ctl_port_online(port);
1347		}
1348	}
1349
1350	return (0);
1351}
1352
1353int
1354ctl_port_disable(ctl_port_type port_type)
1355{
1356	struct ctl_softc *softc;
1357	struct ctl_port *port;
1358
1359	softc = control_softc;
1360
1361	STAILQ_FOREACH(port, &softc->port_list, links) {
1362		if (port_type & port->port_type)
1363			ctl_port_offline(port);
1364	}
1365
1366	return (0);
1367}
1368
1369/*
1370 * Returns 0 for success, 1 for failure.
1371 * Currently the only failure mode is if there aren't enough entries
1372 * allocated.  So, in case of a failure, look at num_entries_dropped,
1373 * reallocate and try again.
1374 */
1375int
1376ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1377	      int *num_entries_filled, int *num_entries_dropped,
1378	      ctl_port_type port_type, int no_virtual)
1379{
1380	struct ctl_softc *softc;
1381	struct ctl_port *port;
1382	int entries_dropped, entries_filled;
1383	int retval;
1384	int i;
1385
1386	softc = control_softc;
1387
1388	retval = 0;
1389	entries_filled = 0;
1390	entries_dropped = 0;
1391
1392	i = 0;
1393	mtx_lock(&softc->ctl_lock);
1394	STAILQ_FOREACH(port, &softc->port_list, links) {
1395		struct ctl_port_entry *entry;
1396
1397		if ((port->port_type & port_type) == 0)
1398			continue;
1399
1400		if ((no_virtual != 0)
1401		 && (port->virtual_port != 0))
1402			continue;
1403
1404		if (entries_filled >= num_entries_alloced) {
1405			entries_dropped++;
1406			continue;
1407		}
1408		entry = &entries[i];
1409
1410		entry->port_type = port->port_type;
1411		strlcpy(entry->port_name, port->port_name,
1412			sizeof(entry->port_name));
1413		entry->physical_port = port->physical_port;
1414		entry->virtual_port = port->virtual_port;
1415		entry->wwnn = port->wwnn;
1416		entry->wwpn = port->wwpn;
1417
1418		i++;
1419		entries_filled++;
1420	}
1421
1422	mtx_unlock(&softc->ctl_lock);
1423
1424	if (entries_dropped > 0)
1425		retval = 1;
1426
1427	*num_entries_dropped = entries_dropped;
1428	*num_entries_filled = entries_filled;
1429
1430	return (retval);
1431}
1432
1433static void
1434ctl_ioctl_online(void *arg)
1435{
1436	struct ctl_ioctl_info *ioctl_info;
1437
1438	ioctl_info = (struct ctl_ioctl_info *)arg;
1439
1440	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1441}
1442
1443static void
1444ctl_ioctl_offline(void *arg)
1445{
1446	struct ctl_ioctl_info *ioctl_info;
1447
1448	ioctl_info = (struct ctl_ioctl_info *)arg;
1449
1450	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1451}
1452
1453/*
1454 * Remove an initiator by port number and initiator ID.
1455 * Returns 0 for success, -1 for failure.
1456 */
1457int
1458ctl_remove_initiator(struct ctl_port *port, int iid)
1459{
1460	struct ctl_softc *softc = control_softc;
1461
1462	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1463
1464	if (iid > CTL_MAX_INIT_PER_PORT) {
1465		printf("%s: initiator ID %u > maximun %u!\n",
1466		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1467		return (-1);
1468	}
1469
1470	mtx_lock(&softc->ctl_lock);
1471	port->wwpn_iid[iid].in_use--;
1472	port->wwpn_iid[iid].last_use = time_uptime;
1473	mtx_unlock(&softc->ctl_lock);
1474
1475	return (0);
1476}
1477
1478/*
1479 * Add an initiator to the initiator map.
1480 * Returns iid for success, < 0 for failure.
1481 */
1482int
1483ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1484{
1485	struct ctl_softc *softc = control_softc;
1486	time_t best_time;
1487	int i, best;
1488
1489	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1490
1491	if (iid >= CTL_MAX_INIT_PER_PORT) {
1492		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1493		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1494		free(name, M_CTL);
1495		return (-1);
1496	}
1497
1498	mtx_lock(&softc->ctl_lock);
1499
1500	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1501		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1502			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1503				iid = i;
1504				break;
1505			}
1506			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1507			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1508				iid = i;
1509				break;
1510			}
1511		}
1512	}
1513
1514	if (iid < 0) {
1515		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1516			if (port->wwpn_iid[i].in_use == 0 &&
1517			    port->wwpn_iid[i].wwpn == 0 &&
1518			    port->wwpn_iid[i].name == NULL) {
1519				iid = i;
1520				break;
1521			}
1522		}
1523	}
1524
1525	if (iid < 0) {
1526		best = -1;
1527		best_time = INT32_MAX;
1528		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1529			if (port->wwpn_iid[i].in_use == 0) {
1530				if (port->wwpn_iid[i].last_use < best_time) {
1531					best = i;
1532					best_time = port->wwpn_iid[i].last_use;
1533				}
1534			}
1535		}
1536		iid = best;
1537	}
1538
1539	if (iid < 0) {
1540		mtx_unlock(&softc->ctl_lock);
1541		free(name, M_CTL);
1542		return (-2);
1543	}
1544
1545	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1546		/*
1547		 * This is not an error yet.
1548		 */
1549		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1550#if 0
1551			printf("%s: port %d iid %u WWPN %#jx arrived"
1552			    " again\n", __func__, port->targ_port,
1553			    iid, (uintmax_t)wwpn);
1554#endif
1555			goto take;
1556		}
1557		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1558		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1559#if 0
1560			printf("%s: port %d iid %u name '%s' arrived"
1561			    " again\n", __func__, port->targ_port,
1562			    iid, name);
1563#endif
1564			goto take;
1565		}
1566
1567		/*
1568		 * This is an error, but what do we do about it?  The
1569		 * driver is telling us we have a new WWPN for this
1570		 * initiator ID, so we pretty much need to use it.
1571		 */
1572		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1573		    " but WWPN %#jx '%s' is still at that address\n",
1574		    __func__, port->targ_port, iid, wwpn, name,
1575		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1576		    port->wwpn_iid[iid].name);
1577
1578		/*
1579		 * XXX KDM clear have_ca and ua_pending on each LUN for
1580		 * this initiator.
1581		 */
1582	}
1583take:
1584	free(port->wwpn_iid[iid].name, M_CTL);
1585	port->wwpn_iid[iid].name = name;
1586	port->wwpn_iid[iid].wwpn = wwpn;
1587	port->wwpn_iid[iid].in_use++;
1588	mtx_unlock(&softc->ctl_lock);
1589
1590	return (iid);
1591}
1592
1593static int
1594ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1595{
1596	int len;
1597
1598	switch (port->port_type) {
1599	case CTL_PORT_FC:
1600	{
1601		struct scsi_transportid_fcp *id =
1602		    (struct scsi_transportid_fcp *)buf;
1603		if (port->wwpn_iid[iid].wwpn == 0)
1604			return (0);
1605		memset(id, 0, sizeof(*id));
1606		id->format_protocol = SCSI_PROTO_FC;
1607		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1608		return (sizeof(*id));
1609	}
1610	case CTL_PORT_ISCSI:
1611	{
1612		struct scsi_transportid_iscsi_port *id =
1613		    (struct scsi_transportid_iscsi_port *)buf;
1614		if (port->wwpn_iid[iid].name == NULL)
1615			return (0);
1616		memset(id, 0, 256);
1617		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1618		    SCSI_PROTO_ISCSI;
1619		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1620		len = roundup2(min(len, 252), 4);
1621		scsi_ulto2b(len, id->additional_length);
1622		return (sizeof(*id) + len);
1623	}
1624	case CTL_PORT_SAS:
1625	{
1626		struct scsi_transportid_sas *id =
1627		    (struct scsi_transportid_sas *)buf;
1628		if (port->wwpn_iid[iid].wwpn == 0)
1629			return (0);
1630		memset(id, 0, sizeof(*id));
1631		id->format_protocol = SCSI_PROTO_SAS;
1632		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1633		return (sizeof(*id));
1634	}
1635	default:
1636	{
1637		struct scsi_transportid_spi *id =
1638		    (struct scsi_transportid_spi *)buf;
1639		memset(id, 0, sizeof(*id));
1640		id->format_protocol = SCSI_PROTO_SPI;
1641		scsi_ulto2b(iid, id->scsi_addr);
1642		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1643		return (sizeof(*id));
1644	}
1645	}
1646}
1647
1648static int
1649ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1650{
1651	return (0);
1652}
1653
1654static int
1655ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1656{
1657	return (0);
1658}
1659
1660/*
1661 * Data movement routine for the CTL ioctl frontend port.
1662 */
1663static int
1664ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1665{
1666	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1667	struct ctl_sg_entry ext_entry, kern_entry;
1668	int ext_sglen, ext_sg_entries, kern_sg_entries;
1669	int ext_sg_start, ext_offset;
1670	int len_to_copy, len_copied;
1671	int kern_watermark, ext_watermark;
1672	int ext_sglist_malloced;
1673	int i, j;
1674
1675	ext_sglist_malloced = 0;
1676	ext_sg_start = 0;
1677	ext_offset = 0;
1678
1679	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1680
1681	/*
1682	 * If this flag is set, fake the data transfer.
1683	 */
1684	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1685		ctsio->ext_data_filled = ctsio->ext_data_len;
1686		goto bailout;
1687	}
1688
1689	/*
1690	 * To simplify things here, if we have a single buffer, stick it in
1691	 * a S/G entry and just make it a single entry S/G list.
1692	 */
1693	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1694		int len_seen;
1695
1696		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1697
1698		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1699							   M_WAITOK);
1700		ext_sglist_malloced = 1;
1701		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1702				   ext_sglen) != 0) {
1703			ctl_set_internal_failure(ctsio,
1704						 /*sks_valid*/ 0,
1705						 /*retry_count*/ 0);
1706			goto bailout;
1707		}
1708		ext_sg_entries = ctsio->ext_sg_entries;
1709		len_seen = 0;
1710		for (i = 0; i < ext_sg_entries; i++) {
1711			if ((len_seen + ext_sglist[i].len) >=
1712			     ctsio->ext_data_filled) {
1713				ext_sg_start = i;
1714				ext_offset = ctsio->ext_data_filled - len_seen;
1715				break;
1716			}
1717			len_seen += ext_sglist[i].len;
1718		}
1719	} else {
1720		ext_sglist = &ext_entry;
1721		ext_sglist->addr = ctsio->ext_data_ptr;
1722		ext_sglist->len = ctsio->ext_data_len;
1723		ext_sg_entries = 1;
1724		ext_sg_start = 0;
1725		ext_offset = ctsio->ext_data_filled;
1726	}
1727
1728	if (ctsio->kern_sg_entries > 0) {
1729		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1730		kern_sg_entries = ctsio->kern_sg_entries;
1731	} else {
1732		kern_sglist = &kern_entry;
1733		kern_sglist->addr = ctsio->kern_data_ptr;
1734		kern_sglist->len = ctsio->kern_data_len;
1735		kern_sg_entries = 1;
1736	}
1737
1738
1739	kern_watermark = 0;
1740	ext_watermark = ext_offset;
1741	len_copied = 0;
1742	for (i = ext_sg_start, j = 0;
1743	     i < ext_sg_entries && j < kern_sg_entries;) {
1744		uint8_t *ext_ptr, *kern_ptr;
1745
1746		len_to_copy = MIN(ext_sglist[i].len - ext_watermark,
1747				  kern_sglist[j].len - kern_watermark);
1748
1749		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1750		ext_ptr = ext_ptr + ext_watermark;
1751		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1752			/*
1753			 * XXX KDM fix this!
1754			 */
1755			panic("need to implement bus address support");
1756#if 0
1757			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1758#endif
1759		} else
1760			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1761		kern_ptr = kern_ptr + kern_watermark;
1762
1763		kern_watermark += len_to_copy;
1764		ext_watermark += len_to_copy;
1765
1766		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1767		     CTL_FLAG_DATA_IN) {
1768			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1769					 "bytes to user\n", len_to_copy));
1770			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1771					 "to %p\n", kern_ptr, ext_ptr));
1772			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1773				ctl_set_internal_failure(ctsio,
1774							 /*sks_valid*/ 0,
1775							 /*retry_count*/ 0);
1776				goto bailout;
1777			}
1778		} else {
1779			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1780					 "bytes from user\n", len_to_copy));
1781			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1782					 "to %p\n", ext_ptr, kern_ptr));
1783			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1784				ctl_set_internal_failure(ctsio,
1785							 /*sks_valid*/ 0,
1786							 /*retry_count*/0);
1787				goto bailout;
1788			}
1789		}
1790
1791		len_copied += len_to_copy;
1792
1793		if (ext_sglist[i].len == ext_watermark) {
1794			i++;
1795			ext_watermark = 0;
1796		}
1797
1798		if (kern_sglist[j].len == kern_watermark) {
1799			j++;
1800			kern_watermark = 0;
1801		}
1802	}
1803
1804	ctsio->ext_data_filled += len_copied;
1805
1806	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1807			 "kern_sg_entries: %d\n", ext_sg_entries,
1808			 kern_sg_entries));
1809	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1810			 "kern_data_len = %d\n", ctsio->ext_data_len,
1811			 ctsio->kern_data_len));
1812
1813
1814	/* XXX KDM set residual?? */
1815bailout:
1816
1817	if (ext_sglist_malloced != 0)
1818		free(ext_sglist, M_CTL);
1819
1820	return (CTL_RETVAL_COMPLETE);
1821}
1822
1823/*
1824 * Serialize a command that went down the "wrong" side, and so was sent to
1825 * this controller for execution.  The logic is a little different than the
1826 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1827 * sent back to the other side, but in the success case, we execute the
1828 * command on this side (XFER mode) or tell the other side to execute it
1829 * (SER_ONLY mode).
1830 */
1831static int
1832ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1833{
1834	struct ctl_softc *softc;
1835	union ctl_ha_msg msg_info;
1836	struct ctl_lun *lun;
1837	int retval = 0;
1838	uint32_t targ_lun;
1839
1840	softc = control_softc;
1841
1842	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1843	lun = softc->ctl_luns[targ_lun];
1844	if (lun==NULL)
1845	{
1846		/*
1847		 * Why isn't LUN defined? The other side wouldn't
1848		 * send a cmd if the LUN is undefined.
1849		 */
1850		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1851
1852		/* "Logical unit not supported" */
1853		ctl_set_sense_data(&msg_info.scsi.sense_data,
1854				   lun,
1855				   /*sense_format*/SSD_TYPE_NONE,
1856				   /*current_error*/ 1,
1857				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1858				   /*asc*/ 0x25,
1859				   /*ascq*/ 0x00,
1860				   SSD_ELEM_NONE);
1861
1862		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1863		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1864		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1865		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1866		msg_info.hdr.serializing_sc = NULL;
1867		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1868	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1869				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1870		}
1871		return(1);
1872
1873	}
1874
1875	mtx_lock(&lun->lun_lock);
1876    	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1877
1878	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1879		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1880		 ooa_links))) {
1881	case CTL_ACTION_BLOCK:
1882		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1883		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1884				  blocked_links);
1885		break;
1886	case CTL_ACTION_PASS:
1887	case CTL_ACTION_SKIP:
1888		if (softc->ha_mode == CTL_HA_MODE_XFER) {
1889			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1890			ctl_enqueue_rtr((union ctl_io *)ctsio);
1891		} else {
1892
1893			/* send msg back to other side */
1894			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1895			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1896			msg_info.hdr.msg_type = CTL_MSG_R2R;
1897#if 0
1898			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1899#endif
1900		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1901			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1902			}
1903		}
1904		break;
1905	case CTL_ACTION_OVERLAP:
1906		/* OVERLAPPED COMMANDS ATTEMPTED */
1907		ctl_set_sense_data(&msg_info.scsi.sense_data,
1908				   lun,
1909				   /*sense_format*/SSD_TYPE_NONE,
1910				   /*current_error*/ 1,
1911				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1912				   /*asc*/ 0x4E,
1913				   /*ascq*/ 0x00,
1914				   SSD_ELEM_NONE);
1915
1916		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1917		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1918		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1919		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1920		msg_info.hdr.serializing_sc = NULL;
1921		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1922#if 0
1923		printf("BAD JUJU:Major Bummer Overlap\n");
1924#endif
1925		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1926		retval = 1;
1927		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1928		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1929		}
1930		break;
1931	case CTL_ACTION_OVERLAP_TAG:
1932		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1933		ctl_set_sense_data(&msg_info.scsi.sense_data,
1934				   lun,
1935				   /*sense_format*/SSD_TYPE_NONE,
1936				   /*current_error*/ 1,
1937				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1938				   /*asc*/ 0x4D,
1939				   /*ascq*/ ctsio->tag_num & 0xff,
1940				   SSD_ELEM_NONE);
1941
1942		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1943		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1944		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1945		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1946		msg_info.hdr.serializing_sc = NULL;
1947		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1948#if 0
1949		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1950#endif
1951		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1952		retval = 1;
1953		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1954		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1955		}
1956		break;
1957	case CTL_ACTION_ERROR:
1958	default:
1959		/* "Internal target failure" */
1960		ctl_set_sense_data(&msg_info.scsi.sense_data,
1961				   lun,
1962				   /*sense_format*/SSD_TYPE_NONE,
1963				   /*current_error*/ 1,
1964				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1965				   /*asc*/ 0x44,
1966				   /*ascq*/ 0x00,
1967				   SSD_ELEM_NONE);
1968
1969		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1970		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1971		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1972		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1973		msg_info.hdr.serializing_sc = NULL;
1974		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1975#if 0
1976		printf("BAD JUJU:Major Bummer HW Error\n");
1977#endif
1978		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1979		retval = 1;
1980		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1981		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1982		}
1983		break;
1984	}
1985	mtx_unlock(&lun->lun_lock);
1986	return (retval);
1987}
1988
1989static int
1990ctl_ioctl_submit_wait(union ctl_io *io)
1991{
1992	struct ctl_fe_ioctl_params params;
1993	ctl_fe_ioctl_state last_state;
1994	int done, retval;
1995
1996	retval = 0;
1997
1998	bzero(&params, sizeof(params));
1999
2000	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
2001	cv_init(&params.sem, "ctlioccv");
2002	params.state = CTL_IOCTL_INPROG;
2003	last_state = params.state;
2004
2005	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
2006
2007	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
2008
2009	/* This shouldn't happen */
2010	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
2011		return (retval);
2012
2013	done = 0;
2014
2015	do {
2016		mtx_lock(&params.ioctl_mtx);
2017		/*
2018		 * Check the state here, and don't sleep if the state has
2019		 * already changed (i.e. wakeup has already occured, but we
2020		 * weren't waiting yet).
2021		 */
2022		if (params.state == last_state) {
2023			/* XXX KDM cv_wait_sig instead? */
2024			cv_wait(&params.sem, &params.ioctl_mtx);
2025		}
2026		last_state = params.state;
2027
2028		switch (params.state) {
2029		case CTL_IOCTL_INPROG:
2030			/* Why did we wake up? */
2031			/* XXX KDM error here? */
2032			mtx_unlock(&params.ioctl_mtx);
2033			break;
2034		case CTL_IOCTL_DATAMOVE:
2035			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
2036
2037			/*
2038			 * change last_state back to INPROG to avoid
2039			 * deadlock on subsequent data moves.
2040			 */
2041			params.state = last_state = CTL_IOCTL_INPROG;
2042
2043			mtx_unlock(&params.ioctl_mtx);
2044			ctl_ioctl_do_datamove(&io->scsiio);
2045			/*
2046			 * Note that in some cases, most notably writes,
2047			 * this will queue the I/O and call us back later.
2048			 * In other cases, generally reads, this routine
2049			 * will immediately call back and wake us up,
2050			 * probably using our own context.
2051			 */
2052			io->scsiio.be_move_done(io);
2053			break;
2054		case CTL_IOCTL_DONE:
2055			mtx_unlock(&params.ioctl_mtx);
2056			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
2057			done = 1;
2058			break;
2059		default:
2060			mtx_unlock(&params.ioctl_mtx);
2061			/* XXX KDM error here? */
2062			break;
2063		}
2064	} while (done == 0);
2065
2066	mtx_destroy(&params.ioctl_mtx);
2067	cv_destroy(&params.sem);
2068
2069	return (CTL_RETVAL_COMPLETE);
2070}
2071
2072static void
2073ctl_ioctl_datamove(union ctl_io *io)
2074{
2075	struct ctl_fe_ioctl_params *params;
2076
2077	params = (struct ctl_fe_ioctl_params *)
2078		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2079
2080	mtx_lock(&params->ioctl_mtx);
2081	params->state = CTL_IOCTL_DATAMOVE;
2082	cv_broadcast(&params->sem);
2083	mtx_unlock(&params->ioctl_mtx);
2084}
2085
2086static void
2087ctl_ioctl_done(union ctl_io *io)
2088{
2089	struct ctl_fe_ioctl_params *params;
2090
2091	params = (struct ctl_fe_ioctl_params *)
2092		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2093
2094	mtx_lock(&params->ioctl_mtx);
2095	params->state = CTL_IOCTL_DONE;
2096	cv_broadcast(&params->sem);
2097	mtx_unlock(&params->ioctl_mtx);
2098}
2099
2100static void
2101ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2102{
2103	struct ctl_fe_ioctl_startstop_info *sd_info;
2104
2105	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2106
2107	sd_info->hs_info.status = metatask->status;
2108	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2109	sd_info->hs_info.luns_complete =
2110		metatask->taskinfo.startstop.luns_complete;
2111	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2112
2113	cv_broadcast(&sd_info->sem);
2114}
2115
2116static void
2117ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2118{
2119	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2120
2121	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2122
2123	mtx_lock(fe_bbr_info->lock);
2124	fe_bbr_info->bbr_info->status = metatask->status;
2125	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2126	fe_bbr_info->wakeup_done = 1;
2127	mtx_unlock(fe_bbr_info->lock);
2128
2129	cv_broadcast(&fe_bbr_info->sem);
2130}
2131
2132/*
2133 * Returns 0 for success, errno for failure.
2134 */
2135static int
2136ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2137		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2138{
2139	union ctl_io *io;
2140	int retval;
2141
2142	retval = 0;
2143
2144	mtx_lock(&lun->lun_lock);
2145	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2146	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2147	     ooa_links)) {
2148		struct ctl_ooa_entry *entry;
2149
2150		/*
2151		 * If we've got more than we can fit, just count the
2152		 * remaining entries.
2153		 */
2154		if (*cur_fill_num >= ooa_hdr->alloc_num)
2155			continue;
2156
2157		entry = &kern_entries[*cur_fill_num];
2158
2159		entry->tag_num = io->scsiio.tag_num;
2160		entry->lun_num = lun->lun;
2161#ifdef CTL_TIME_IO
2162		entry->start_bt = io->io_hdr.start_bt;
2163#endif
2164		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2165		entry->cdb_len = io->scsiio.cdb_len;
2166		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2167			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2168
2169		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2170			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2171
2172		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2173			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2174
2175		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2176			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2177
2178		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2179			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2180	}
2181	mtx_unlock(&lun->lun_lock);
2182
2183	return (retval);
2184}
2185
2186static void *
2187ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2188		 size_t error_str_len)
2189{
2190	void *kptr;
2191
2192	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2193
2194	if (copyin(user_addr, kptr, len) != 0) {
2195		snprintf(error_str, error_str_len, "Error copying %d bytes "
2196			 "from user address %p to kernel address %p", len,
2197			 user_addr, kptr);
2198		free(kptr, M_CTL);
2199		return (NULL);
2200	}
2201
2202	return (kptr);
2203}
2204
2205static void
2206ctl_free_args(int num_args, struct ctl_be_arg *args)
2207{
2208	int i;
2209
2210	if (args == NULL)
2211		return;
2212
2213	for (i = 0; i < num_args; i++) {
2214		free(args[i].kname, M_CTL);
2215		free(args[i].kvalue, M_CTL);
2216	}
2217
2218	free(args, M_CTL);
2219}
2220
2221static struct ctl_be_arg *
2222ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2223		char *error_str, size_t error_str_len)
2224{
2225	struct ctl_be_arg *args;
2226	int i;
2227
2228	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2229				error_str, error_str_len);
2230
2231	if (args == NULL)
2232		goto bailout;
2233
2234	for (i = 0; i < num_args; i++) {
2235		args[i].kname = NULL;
2236		args[i].kvalue = NULL;
2237	}
2238
2239	for (i = 0; i < num_args; i++) {
2240		uint8_t *tmpptr;
2241
2242		args[i].kname = ctl_copyin_alloc(args[i].name,
2243			args[i].namelen, error_str, error_str_len);
2244		if (args[i].kname == NULL)
2245			goto bailout;
2246
2247		if (args[i].kname[args[i].namelen - 1] != '\0') {
2248			snprintf(error_str, error_str_len, "Argument %d "
2249				 "name is not NUL-terminated", i);
2250			goto bailout;
2251		}
2252
2253		if (args[i].flags & CTL_BEARG_RD) {
2254			tmpptr = ctl_copyin_alloc(args[i].value,
2255				args[i].vallen, error_str, error_str_len);
2256			if (tmpptr == NULL)
2257				goto bailout;
2258			if ((args[i].flags & CTL_BEARG_ASCII)
2259			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2260				snprintf(error_str, error_str_len, "Argument "
2261				    "%d value is not NUL-terminated", i);
2262				goto bailout;
2263			}
2264			args[i].kvalue = tmpptr;
2265		} else {
2266			args[i].kvalue = malloc(args[i].vallen,
2267			    M_CTL, M_WAITOK | M_ZERO);
2268		}
2269	}
2270
2271	return (args);
2272bailout:
2273
2274	ctl_free_args(num_args, args);
2275
2276	return (NULL);
2277}
2278
2279static void
2280ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2281{
2282	int i;
2283
2284	for (i = 0; i < num_args; i++) {
2285		if (args[i].flags & CTL_BEARG_WR)
2286			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2287	}
2288}
2289
2290/*
2291 * Escape characters that are illegal or not recommended in XML.
2292 */
2293int
2294ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2295{
2296	char *end = str + size;
2297	int retval;
2298
2299	retval = 0;
2300
2301	for (; *str && str < end; str++) {
2302		switch (*str) {
2303		case '&':
2304			retval = sbuf_printf(sb, "&amp;");
2305			break;
2306		case '>':
2307			retval = sbuf_printf(sb, "&gt;");
2308			break;
2309		case '<':
2310			retval = sbuf_printf(sb, "&lt;");
2311			break;
2312		default:
2313			retval = sbuf_putc(sb, *str);
2314			break;
2315		}
2316
2317		if (retval != 0)
2318			break;
2319
2320	}
2321
2322	return (retval);
2323}
2324
2325static void
2326ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2327{
2328	struct scsi_vpd_id_descriptor *desc;
2329	int i;
2330
2331	if (id == NULL || id->len < 4)
2332		return;
2333	desc = (struct scsi_vpd_id_descriptor *)id->data;
2334	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2335	case SVPD_ID_TYPE_T10:
2336		sbuf_printf(sb, "t10.");
2337		break;
2338	case SVPD_ID_TYPE_EUI64:
2339		sbuf_printf(sb, "eui.");
2340		break;
2341	case SVPD_ID_TYPE_NAA:
2342		sbuf_printf(sb, "naa.");
2343		break;
2344	case SVPD_ID_TYPE_SCSI_NAME:
2345		break;
2346	}
2347	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2348	case SVPD_ID_CODESET_BINARY:
2349		for (i = 0; i < desc->length; i++)
2350			sbuf_printf(sb, "%02x", desc->identifier[i]);
2351		break;
2352	case SVPD_ID_CODESET_ASCII:
2353		sbuf_printf(sb, "%.*s", (int)desc->length,
2354		    (char *)desc->identifier);
2355		break;
2356	case SVPD_ID_CODESET_UTF8:
2357		sbuf_printf(sb, "%s", (char *)desc->identifier);
2358		break;
2359	}
2360}
2361
2362static int
2363ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2364	  struct thread *td)
2365{
2366	struct ctl_softc *softc;
2367	int retval;
2368
2369	softc = control_softc;
2370
2371	retval = 0;
2372
2373	switch (cmd) {
2374	case CTL_IO: {
2375		union ctl_io *io;
2376		void *pool_tmp;
2377
2378		/*
2379		 * If we haven't been "enabled", don't allow any SCSI I/O
2380		 * to this FETD.
2381		 */
2382		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2383			retval = EPERM;
2384			break;
2385		}
2386
2387		io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2388
2389		/*
2390		 * Need to save the pool reference so it doesn't get
2391		 * spammed by the user's ctl_io.
2392		 */
2393		pool_tmp = io->io_hdr.pool;
2394		memcpy(io, (void *)addr, sizeof(*io));
2395		io->io_hdr.pool = pool_tmp;
2396
2397		/*
2398		 * No status yet, so make sure the status is set properly.
2399		 */
2400		io->io_hdr.status = CTL_STATUS_NONE;
2401
2402		/*
2403		 * The user sets the initiator ID, target and LUN IDs.
2404		 */
2405		io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2406		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2407		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2408		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2409			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2410
2411		retval = ctl_ioctl_submit_wait(io);
2412
2413		if (retval != 0) {
2414			ctl_free_io(io);
2415			break;
2416		}
2417
2418		memcpy((void *)addr, io, sizeof(*io));
2419
2420		/* return this to our pool */
2421		ctl_free_io(io);
2422
2423		break;
2424	}
2425	case CTL_ENABLE_PORT:
2426	case CTL_DISABLE_PORT:
2427	case CTL_SET_PORT_WWNS: {
2428		struct ctl_port *port;
2429		struct ctl_port_entry *entry;
2430
2431		entry = (struct ctl_port_entry *)addr;
2432
2433		mtx_lock(&softc->ctl_lock);
2434		STAILQ_FOREACH(port, &softc->port_list, links) {
2435			int action, done;
2436
2437			action = 0;
2438			done = 0;
2439
2440			if ((entry->port_type == CTL_PORT_NONE)
2441			 && (entry->targ_port == port->targ_port)) {
2442				/*
2443				 * If the user only wants to enable or
2444				 * disable or set WWNs on a specific port,
2445				 * do the operation and we're done.
2446				 */
2447				action = 1;
2448				done = 1;
2449			} else if (entry->port_type & port->port_type) {
2450				/*
2451				 * Compare the user's type mask with the
2452				 * particular frontend type to see if we
2453				 * have a match.
2454				 */
2455				action = 1;
2456				done = 0;
2457
2458				/*
2459				 * Make sure the user isn't trying to set
2460				 * WWNs on multiple ports at the same time.
2461				 */
2462				if (cmd == CTL_SET_PORT_WWNS) {
2463					printf("%s: Can't set WWNs on "
2464					       "multiple ports\n", __func__);
2465					retval = EINVAL;
2466					break;
2467				}
2468			}
2469			if (action != 0) {
2470				/*
2471				 * XXX KDM we have to drop the lock here,
2472				 * because the online/offline operations
2473				 * can potentially block.  We need to
2474				 * reference count the frontends so they
2475				 * can't go away,
2476				 */
2477				mtx_unlock(&softc->ctl_lock);
2478
2479				if (cmd == CTL_ENABLE_PORT) {
2480					struct ctl_lun *lun;
2481
2482					STAILQ_FOREACH(lun, &softc->lun_list,
2483						       links) {
2484						port->lun_enable(port->targ_lun_arg,
2485						    lun->target,
2486						    lun->lun);
2487					}
2488
2489					ctl_port_online(port);
2490				} else if (cmd == CTL_DISABLE_PORT) {
2491					struct ctl_lun *lun;
2492
2493					ctl_port_offline(port);
2494
2495					STAILQ_FOREACH(lun, &softc->lun_list,
2496						       links) {
2497						port->lun_disable(
2498						    port->targ_lun_arg,
2499						    lun->target,
2500						    lun->lun);
2501					}
2502				}
2503
2504				mtx_lock(&softc->ctl_lock);
2505
2506				if (cmd == CTL_SET_PORT_WWNS)
2507					ctl_port_set_wwns(port,
2508					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2509					    1 : 0, entry->wwnn,
2510					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2511					    1 : 0, entry->wwpn);
2512			}
2513			if (done != 0)
2514				break;
2515		}
2516		mtx_unlock(&softc->ctl_lock);
2517		break;
2518	}
2519	case CTL_GET_PORT_LIST: {
2520		struct ctl_port *port;
2521		struct ctl_port_list *list;
2522		int i;
2523
2524		list = (struct ctl_port_list *)addr;
2525
2526		if (list->alloc_len != (list->alloc_num *
2527		    sizeof(struct ctl_port_entry))) {
2528			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2529			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2530			       "%zu\n", __func__, list->alloc_len,
2531			       list->alloc_num, sizeof(struct ctl_port_entry));
2532			retval = EINVAL;
2533			break;
2534		}
2535		list->fill_len = 0;
2536		list->fill_num = 0;
2537		list->dropped_num = 0;
2538		i = 0;
2539		mtx_lock(&softc->ctl_lock);
2540		STAILQ_FOREACH(port, &softc->port_list, links) {
2541			struct ctl_port_entry entry, *list_entry;
2542
2543			if (list->fill_num >= list->alloc_num) {
2544				list->dropped_num++;
2545				continue;
2546			}
2547
2548			entry.port_type = port->port_type;
2549			strlcpy(entry.port_name, port->port_name,
2550				sizeof(entry.port_name));
2551			entry.targ_port = port->targ_port;
2552			entry.physical_port = port->physical_port;
2553			entry.virtual_port = port->virtual_port;
2554			entry.wwnn = port->wwnn;
2555			entry.wwpn = port->wwpn;
2556			if (port->status & CTL_PORT_STATUS_ONLINE)
2557				entry.online = 1;
2558			else
2559				entry.online = 0;
2560
2561			list_entry = &list->entries[i];
2562
2563			retval = copyout(&entry, list_entry, sizeof(entry));
2564			if (retval != 0) {
2565				printf("%s: CTL_GET_PORT_LIST: copyout "
2566				       "returned %d\n", __func__, retval);
2567				break;
2568			}
2569			i++;
2570			list->fill_num++;
2571			list->fill_len += sizeof(entry);
2572		}
2573		mtx_unlock(&softc->ctl_lock);
2574
2575		/*
2576		 * If this is non-zero, we had a copyout fault, so there's
2577		 * probably no point in attempting to set the status inside
2578		 * the structure.
2579		 */
2580		if (retval != 0)
2581			break;
2582
2583		if (list->dropped_num > 0)
2584			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2585		else
2586			list->status = CTL_PORT_LIST_OK;
2587		break;
2588	}
2589	case CTL_DUMP_OOA: {
2590		struct ctl_lun *lun;
2591		union ctl_io *io;
2592		char printbuf[128];
2593		struct sbuf sb;
2594
2595		mtx_lock(&softc->ctl_lock);
2596		printf("Dumping OOA queues:\n");
2597		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2598			mtx_lock(&lun->lun_lock);
2599			for (io = (union ctl_io *)TAILQ_FIRST(
2600			     &lun->ooa_queue); io != NULL;
2601			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2602			     ooa_links)) {
2603				sbuf_new(&sb, printbuf, sizeof(printbuf),
2604					 SBUF_FIXEDLEN);
2605				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2606					    (intmax_t)lun->lun,
2607					    io->scsiio.tag_num,
2608					    (io->io_hdr.flags &
2609					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2610					    (io->io_hdr.flags &
2611					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2612					    (io->io_hdr.flags &
2613					    CTL_FLAG_ABORT) ? " ABORT" : "",
2614			                    (io->io_hdr.flags &
2615		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2616				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2617				sbuf_finish(&sb);
2618				printf("%s\n", sbuf_data(&sb));
2619			}
2620			mtx_unlock(&lun->lun_lock);
2621		}
2622		printf("OOA queues dump done\n");
2623		mtx_unlock(&softc->ctl_lock);
2624		break;
2625	}
2626	case CTL_GET_OOA: {
2627		struct ctl_lun *lun;
2628		struct ctl_ooa *ooa_hdr;
2629		struct ctl_ooa_entry *entries;
2630		uint32_t cur_fill_num;
2631
2632		ooa_hdr = (struct ctl_ooa *)addr;
2633
2634		if ((ooa_hdr->alloc_len == 0)
2635		 || (ooa_hdr->alloc_num == 0)) {
2636			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2637			       "must be non-zero\n", __func__,
2638			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2639			retval = EINVAL;
2640			break;
2641		}
2642
2643		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2644		    sizeof(struct ctl_ooa_entry))) {
2645			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2646			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2647			       __func__, ooa_hdr->alloc_len,
2648			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2649			retval = EINVAL;
2650			break;
2651		}
2652
2653		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2654		if (entries == NULL) {
2655			printf("%s: could not allocate %d bytes for OOA "
2656			       "dump\n", __func__, ooa_hdr->alloc_len);
2657			retval = ENOMEM;
2658			break;
2659		}
2660
2661		mtx_lock(&softc->ctl_lock);
2662		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2663		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2664		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2665			mtx_unlock(&softc->ctl_lock);
2666			free(entries, M_CTL);
2667			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2668			       __func__, (uintmax_t)ooa_hdr->lun_num);
2669			retval = EINVAL;
2670			break;
2671		}
2672
2673		cur_fill_num = 0;
2674
2675		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2676			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2677				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2678					ooa_hdr, entries);
2679				if (retval != 0)
2680					break;
2681			}
2682			if (retval != 0) {
2683				mtx_unlock(&softc->ctl_lock);
2684				free(entries, M_CTL);
2685				break;
2686			}
2687		} else {
2688			lun = softc->ctl_luns[ooa_hdr->lun_num];
2689
2690			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2691						    entries);
2692		}
2693		mtx_unlock(&softc->ctl_lock);
2694
2695		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2696		ooa_hdr->fill_len = ooa_hdr->fill_num *
2697			sizeof(struct ctl_ooa_entry);
2698		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2699		if (retval != 0) {
2700			printf("%s: error copying out %d bytes for OOA dump\n",
2701			       __func__, ooa_hdr->fill_len);
2702		}
2703
2704		getbintime(&ooa_hdr->cur_bt);
2705
2706		if (cur_fill_num > ooa_hdr->alloc_num) {
2707			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2708			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2709		} else {
2710			ooa_hdr->dropped_num = 0;
2711			ooa_hdr->status = CTL_OOA_OK;
2712		}
2713
2714		free(entries, M_CTL);
2715		break;
2716	}
2717	case CTL_CHECK_OOA: {
2718		union ctl_io *io;
2719		struct ctl_lun *lun;
2720		struct ctl_ooa_info *ooa_info;
2721
2722
2723		ooa_info = (struct ctl_ooa_info *)addr;
2724
2725		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2726			ooa_info->status = CTL_OOA_INVALID_LUN;
2727			break;
2728		}
2729		mtx_lock(&softc->ctl_lock);
2730		lun = softc->ctl_luns[ooa_info->lun_id];
2731		if (lun == NULL) {
2732			mtx_unlock(&softc->ctl_lock);
2733			ooa_info->status = CTL_OOA_INVALID_LUN;
2734			break;
2735		}
2736		mtx_lock(&lun->lun_lock);
2737		mtx_unlock(&softc->ctl_lock);
2738		ooa_info->num_entries = 0;
2739		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2740		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2741		     &io->io_hdr, ooa_links)) {
2742			ooa_info->num_entries++;
2743		}
2744		mtx_unlock(&lun->lun_lock);
2745
2746		ooa_info->status = CTL_OOA_SUCCESS;
2747
2748		break;
2749	}
2750	case CTL_HARD_START:
2751	case CTL_HARD_STOP: {
2752		struct ctl_fe_ioctl_startstop_info ss_info;
2753		struct cfi_metatask *metatask;
2754		struct mtx hs_mtx;
2755
2756		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2757
2758		cv_init(&ss_info.sem, "hard start/stop cv" );
2759
2760		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2761		if (metatask == NULL) {
2762			retval = ENOMEM;
2763			mtx_destroy(&hs_mtx);
2764			break;
2765		}
2766
2767		if (cmd == CTL_HARD_START)
2768			metatask->tasktype = CFI_TASK_STARTUP;
2769		else
2770			metatask->tasktype = CFI_TASK_SHUTDOWN;
2771
2772		metatask->callback = ctl_ioctl_hard_startstop_callback;
2773		metatask->callback_arg = &ss_info;
2774
2775		cfi_action(metatask);
2776
2777		/* Wait for the callback */
2778		mtx_lock(&hs_mtx);
2779		cv_wait_sig(&ss_info.sem, &hs_mtx);
2780		mtx_unlock(&hs_mtx);
2781
2782		/*
2783		 * All information has been copied from the metatask by the
2784		 * time cv_broadcast() is called, so we free the metatask here.
2785		 */
2786		cfi_free_metatask(metatask);
2787
2788		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2789
2790		mtx_destroy(&hs_mtx);
2791		break;
2792	}
2793	case CTL_BBRREAD: {
2794		struct ctl_bbrread_info *bbr_info;
2795		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2796		struct mtx bbr_mtx;
2797		struct cfi_metatask *metatask;
2798
2799		bbr_info = (struct ctl_bbrread_info *)addr;
2800
2801		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2802
2803		bzero(&bbr_mtx, sizeof(bbr_mtx));
2804		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2805
2806		fe_bbr_info.bbr_info = bbr_info;
2807		fe_bbr_info.lock = &bbr_mtx;
2808
2809		cv_init(&fe_bbr_info.sem, "BBR read cv");
2810		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2811
2812		if (metatask == NULL) {
2813			mtx_destroy(&bbr_mtx);
2814			cv_destroy(&fe_bbr_info.sem);
2815			retval = ENOMEM;
2816			break;
2817		}
2818		metatask->tasktype = CFI_TASK_BBRREAD;
2819		metatask->callback = ctl_ioctl_bbrread_callback;
2820		metatask->callback_arg = &fe_bbr_info;
2821		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2822		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2823		metatask->taskinfo.bbrread.len = bbr_info->len;
2824
2825		cfi_action(metatask);
2826
2827		mtx_lock(&bbr_mtx);
2828		while (fe_bbr_info.wakeup_done == 0)
2829			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2830		mtx_unlock(&bbr_mtx);
2831
2832		bbr_info->status = metatask->status;
2833		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2834		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2835		memcpy(&bbr_info->sense_data,
2836		       &metatask->taskinfo.bbrread.sense_data,
2837		       MIN(sizeof(bbr_info->sense_data),
2838			   sizeof(metatask->taskinfo.bbrread.sense_data)));
2839
2840		cfi_free_metatask(metatask);
2841
2842		mtx_destroy(&bbr_mtx);
2843		cv_destroy(&fe_bbr_info.sem);
2844
2845		break;
2846	}
2847	case CTL_DELAY_IO: {
2848		struct ctl_io_delay_info *delay_info;
2849#ifdef CTL_IO_DELAY
2850		struct ctl_lun *lun;
2851#endif /* CTL_IO_DELAY */
2852
2853		delay_info = (struct ctl_io_delay_info *)addr;
2854
2855#ifdef CTL_IO_DELAY
2856		mtx_lock(&softc->ctl_lock);
2857
2858		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2859		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2860			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2861		} else {
2862			lun = softc->ctl_luns[delay_info->lun_id];
2863			mtx_lock(&lun->lun_lock);
2864
2865			delay_info->status = CTL_DELAY_STATUS_OK;
2866
2867			switch (delay_info->delay_type) {
2868			case CTL_DELAY_TYPE_CONT:
2869				break;
2870			case CTL_DELAY_TYPE_ONESHOT:
2871				break;
2872			default:
2873				delay_info->status =
2874					CTL_DELAY_STATUS_INVALID_TYPE;
2875				break;
2876			}
2877
2878			switch (delay_info->delay_loc) {
2879			case CTL_DELAY_LOC_DATAMOVE:
2880				lun->delay_info.datamove_type =
2881					delay_info->delay_type;
2882				lun->delay_info.datamove_delay =
2883					delay_info->delay_secs;
2884				break;
2885			case CTL_DELAY_LOC_DONE:
2886				lun->delay_info.done_type =
2887					delay_info->delay_type;
2888				lun->delay_info.done_delay =
2889					delay_info->delay_secs;
2890				break;
2891			default:
2892				delay_info->status =
2893					CTL_DELAY_STATUS_INVALID_LOC;
2894				break;
2895			}
2896			mtx_unlock(&lun->lun_lock);
2897		}
2898
2899		mtx_unlock(&softc->ctl_lock);
2900#else
2901		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2902#endif /* CTL_IO_DELAY */
2903		break;
2904	}
2905	case CTL_REALSYNC_SET: {
2906		int *syncstate;
2907
2908		syncstate = (int *)addr;
2909
2910		mtx_lock(&softc->ctl_lock);
2911		switch (*syncstate) {
2912		case 0:
2913			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2914			break;
2915		case 1:
2916			softc->flags |= CTL_FLAG_REAL_SYNC;
2917			break;
2918		default:
2919			retval = EINVAL;
2920			break;
2921		}
2922		mtx_unlock(&softc->ctl_lock);
2923		break;
2924	}
2925	case CTL_REALSYNC_GET: {
2926		int *syncstate;
2927
2928		syncstate = (int*)addr;
2929
2930		mtx_lock(&softc->ctl_lock);
2931		if (softc->flags & CTL_FLAG_REAL_SYNC)
2932			*syncstate = 1;
2933		else
2934			*syncstate = 0;
2935		mtx_unlock(&softc->ctl_lock);
2936
2937		break;
2938	}
2939	case CTL_SETSYNC:
2940	case CTL_GETSYNC: {
2941		struct ctl_sync_info *sync_info;
2942		struct ctl_lun *lun;
2943
2944		sync_info = (struct ctl_sync_info *)addr;
2945
2946		mtx_lock(&softc->ctl_lock);
2947		lun = softc->ctl_luns[sync_info->lun_id];
2948		if (lun == NULL) {
2949			mtx_unlock(&softc->ctl_lock);
2950			sync_info->status = CTL_GS_SYNC_NO_LUN;
2951		}
2952		/*
2953		 * Get or set the sync interval.  We're not bounds checking
2954		 * in the set case, hopefully the user won't do something
2955		 * silly.
2956		 */
2957		mtx_lock(&lun->lun_lock);
2958		mtx_unlock(&softc->ctl_lock);
2959		if (cmd == CTL_GETSYNC)
2960			sync_info->sync_interval = lun->sync_interval;
2961		else
2962			lun->sync_interval = sync_info->sync_interval;
2963		mtx_unlock(&lun->lun_lock);
2964
2965		sync_info->status = CTL_GS_SYNC_OK;
2966
2967		break;
2968	}
2969	case CTL_GETSTATS: {
2970		struct ctl_stats *stats;
2971		struct ctl_lun *lun;
2972		int i;
2973
2974		stats = (struct ctl_stats *)addr;
2975
2976		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2977		     stats->alloc_len) {
2978			stats->status = CTL_SS_NEED_MORE_SPACE;
2979			stats->num_luns = softc->num_luns;
2980			break;
2981		}
2982		/*
2983		 * XXX KDM no locking here.  If the LUN list changes,
2984		 * things can blow up.
2985		 */
2986		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2987		     i++, lun = STAILQ_NEXT(lun, links)) {
2988			retval = copyout(&lun->stats, &stats->lun_stats[i],
2989					 sizeof(lun->stats));
2990			if (retval != 0)
2991				break;
2992		}
2993		stats->num_luns = softc->num_luns;
2994		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2995				 softc->num_luns;
2996		stats->status = CTL_SS_OK;
2997#ifdef CTL_TIME_IO
2998		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2999#else
3000		stats->flags = CTL_STATS_FLAG_NONE;
3001#endif
3002		getnanouptime(&stats->timestamp);
3003		break;
3004	}
3005	case CTL_ERROR_INJECT: {
3006		struct ctl_error_desc *err_desc, *new_err_desc;
3007		struct ctl_lun *lun;
3008
3009		err_desc = (struct ctl_error_desc *)addr;
3010
3011		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
3012				      M_WAITOK | M_ZERO);
3013		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
3014
3015		mtx_lock(&softc->ctl_lock);
3016		lun = softc->ctl_luns[err_desc->lun_id];
3017		if (lun == NULL) {
3018			mtx_unlock(&softc->ctl_lock);
3019			free(new_err_desc, M_CTL);
3020			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
3021			       __func__, (uintmax_t)err_desc->lun_id);
3022			retval = EINVAL;
3023			break;
3024		}
3025		mtx_lock(&lun->lun_lock);
3026		mtx_unlock(&softc->ctl_lock);
3027
3028		/*
3029		 * We could do some checking here to verify the validity
3030		 * of the request, but given the complexity of error
3031		 * injection requests, the checking logic would be fairly
3032		 * complex.
3033		 *
3034		 * For now, if the request is invalid, it just won't get
3035		 * executed and might get deleted.
3036		 */
3037		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
3038
3039		/*
3040		 * XXX KDM check to make sure the serial number is unique,
3041		 * in case we somehow manage to wrap.  That shouldn't
3042		 * happen for a very long time, but it's the right thing to
3043		 * do.
3044		 */
3045		new_err_desc->serial = lun->error_serial;
3046		err_desc->serial = lun->error_serial;
3047		lun->error_serial++;
3048
3049		mtx_unlock(&lun->lun_lock);
3050		break;
3051	}
3052	case CTL_ERROR_INJECT_DELETE: {
3053		struct ctl_error_desc *delete_desc, *desc, *desc2;
3054		struct ctl_lun *lun;
3055		int delete_done;
3056
3057		delete_desc = (struct ctl_error_desc *)addr;
3058		delete_done = 0;
3059
3060		mtx_lock(&softc->ctl_lock);
3061		lun = softc->ctl_luns[delete_desc->lun_id];
3062		if (lun == NULL) {
3063			mtx_unlock(&softc->ctl_lock);
3064			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
3065			       __func__, (uintmax_t)delete_desc->lun_id);
3066			retval = EINVAL;
3067			break;
3068		}
3069		mtx_lock(&lun->lun_lock);
3070		mtx_unlock(&softc->ctl_lock);
3071		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
3072			if (desc->serial != delete_desc->serial)
3073				continue;
3074
3075			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
3076				      links);
3077			free(desc, M_CTL);
3078			delete_done = 1;
3079		}
3080		mtx_unlock(&lun->lun_lock);
3081		if (delete_done == 0) {
3082			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
3083			       "error serial %ju on LUN %u\n", __func__,
3084			       delete_desc->serial, delete_desc->lun_id);
3085			retval = EINVAL;
3086			break;
3087		}
3088		break;
3089	}
3090	case CTL_DUMP_STRUCTS: {
3091		int i, j, k;
3092		struct ctl_port *port;
3093		struct ctl_frontend *fe;
3094
3095		mtx_lock(&softc->ctl_lock);
3096		printf("CTL Persistent Reservation information start:\n");
3097		for (i = 0; i < CTL_MAX_LUNS; i++) {
3098			struct ctl_lun *lun;
3099
3100			lun = softc->ctl_luns[i];
3101
3102			if ((lun == NULL)
3103			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
3104				continue;
3105
3106			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
3107				if (lun->pr_keys[j] == NULL)
3108					continue;
3109				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
3110					if (lun->pr_keys[j][k] == 0)
3111						continue;
3112					printf("  LUN %d port %d iid %d key "
3113					       "%#jx\n", i, j, k,
3114					       (uintmax_t)lun->pr_keys[j][k]);
3115				}
3116			}
3117		}
3118		printf("CTL Persistent Reservation information end\n");
3119		printf("CTL Ports:\n");
3120		STAILQ_FOREACH(port, &softc->port_list, links) {
3121			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3122			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3123			       port->frontend->name, port->port_type,
3124			       port->physical_port, port->virtual_port,
3125			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3126			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3127				if (port->wwpn_iid[j].in_use == 0 &&
3128				    port->wwpn_iid[j].wwpn == 0 &&
3129				    port->wwpn_iid[j].name == NULL)
3130					continue;
3131
3132				printf("    iid %u use %d WWPN %#jx '%s'\n",
3133				    j, port->wwpn_iid[j].in_use,
3134				    (uintmax_t)port->wwpn_iid[j].wwpn,
3135				    port->wwpn_iid[j].name);
3136			}
3137		}
3138		printf("CTL Port information end\n");
3139		mtx_unlock(&softc->ctl_lock);
3140		/*
3141		 * XXX KDM calling this without a lock.  We'd likely want
3142		 * to drop the lock before calling the frontend's dump
3143		 * routine anyway.
3144		 */
3145		printf("CTL Frontends:\n");
3146		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3147			printf("  Frontend '%s'\n", fe->name);
3148			if (fe->fe_dump != NULL)
3149				fe->fe_dump();
3150		}
3151		printf("CTL Frontend information end\n");
3152		break;
3153	}
3154	case CTL_LUN_REQ: {
3155		struct ctl_lun_req *lun_req;
3156		struct ctl_backend_driver *backend;
3157
3158		lun_req = (struct ctl_lun_req *)addr;
3159
3160		backend = ctl_backend_find(lun_req->backend);
3161		if (backend == NULL) {
3162			lun_req->status = CTL_LUN_ERROR;
3163			snprintf(lun_req->error_str,
3164				 sizeof(lun_req->error_str),
3165				 "Backend \"%s\" not found.",
3166				 lun_req->backend);
3167			break;
3168		}
3169		if (lun_req->num_be_args > 0) {
3170			lun_req->kern_be_args = ctl_copyin_args(
3171				lun_req->num_be_args,
3172				lun_req->be_args,
3173				lun_req->error_str,
3174				sizeof(lun_req->error_str));
3175			if (lun_req->kern_be_args == NULL) {
3176				lun_req->status = CTL_LUN_ERROR;
3177				break;
3178			}
3179		}
3180
3181		retval = backend->ioctl(dev, cmd, addr, flag, td);
3182
3183		if (lun_req->num_be_args > 0) {
3184			ctl_copyout_args(lun_req->num_be_args,
3185				      lun_req->kern_be_args);
3186			ctl_free_args(lun_req->num_be_args,
3187				      lun_req->kern_be_args);
3188		}
3189		break;
3190	}
3191	case CTL_LUN_LIST: {
3192		struct sbuf *sb;
3193		struct ctl_lun *lun;
3194		struct ctl_lun_list *list;
3195		struct ctl_option *opt;
3196
3197		list = (struct ctl_lun_list *)addr;
3198
3199		/*
3200		 * Allocate a fixed length sbuf here, based on the length
3201		 * of the user's buffer.  We could allocate an auto-extending
3202		 * buffer, and then tell the user how much larger our
3203		 * amount of data is than his buffer, but that presents
3204		 * some problems:
3205		 *
3206		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3207		 *     we can't hold a lock while calling them with an
3208		 *     auto-extending buffer.
3209 		 *
3210		 * 2.  There is not currently a LUN reference counting
3211		 *     mechanism, outside of outstanding transactions on
3212		 *     the LUN's OOA queue.  So a LUN could go away on us
3213		 *     while we're getting the LUN number, backend-specific
3214		 *     information, etc.  Thus, given the way things
3215		 *     currently work, we need to hold the CTL lock while
3216		 *     grabbing LUN information.
3217		 *
3218		 * So, from the user's standpoint, the best thing to do is
3219		 * allocate what he thinks is a reasonable buffer length,
3220		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3221		 * double the buffer length and try again.  (And repeat
3222		 * that until he succeeds.)
3223		 */
3224		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3225		if (sb == NULL) {
3226			list->status = CTL_LUN_LIST_ERROR;
3227			snprintf(list->error_str, sizeof(list->error_str),
3228				 "Unable to allocate %d bytes for LUN list",
3229				 list->alloc_len);
3230			break;
3231		}
3232
3233		sbuf_printf(sb, "<ctllunlist>\n");
3234
3235		mtx_lock(&softc->ctl_lock);
3236		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3237			mtx_lock(&lun->lun_lock);
3238			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3239					     (uintmax_t)lun->lun);
3240
3241			/*
3242			 * Bail out as soon as we see that we've overfilled
3243			 * the buffer.
3244			 */
3245			if (retval != 0)
3246				break;
3247
3248			retval = sbuf_printf(sb, "\t<backend_type>%s"
3249					     "</backend_type>\n",
3250					     (lun->backend == NULL) ?  "none" :
3251					     lun->backend->name);
3252
3253			if (retval != 0)
3254				break;
3255
3256			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3257					     lun->be_lun->lun_type);
3258
3259			if (retval != 0)
3260				break;
3261
3262			if (lun->backend == NULL) {
3263				retval = sbuf_printf(sb, "</lun>\n");
3264				if (retval != 0)
3265					break;
3266				continue;
3267			}
3268
3269			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3270					     (lun->be_lun->maxlba > 0) ?
3271					     lun->be_lun->maxlba + 1 : 0);
3272
3273			if (retval != 0)
3274				break;
3275
3276			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3277					     lun->be_lun->blocksize);
3278
3279			if (retval != 0)
3280				break;
3281
3282			retval = sbuf_printf(sb, "\t<serial_number>");
3283
3284			if (retval != 0)
3285				break;
3286
3287			retval = ctl_sbuf_printf_esc(sb,
3288			    lun->be_lun->serial_num,
3289			    sizeof(lun->be_lun->serial_num));
3290
3291			if (retval != 0)
3292				break;
3293
3294			retval = sbuf_printf(sb, "</serial_number>\n");
3295
3296			if (retval != 0)
3297				break;
3298
3299			retval = sbuf_printf(sb, "\t<device_id>");
3300
3301			if (retval != 0)
3302				break;
3303
3304			retval = ctl_sbuf_printf_esc(sb,
3305			    lun->be_lun->device_id,
3306			    sizeof(lun->be_lun->device_id));
3307
3308			if (retval != 0)
3309				break;
3310
3311			retval = sbuf_printf(sb, "</device_id>\n");
3312
3313			if (retval != 0)
3314				break;
3315
3316			if (lun->backend->lun_info != NULL) {
3317				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3318				if (retval != 0)
3319					break;
3320			}
3321			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3322				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3323				    opt->name, opt->value, opt->name);
3324				if (retval != 0)
3325					break;
3326			}
3327
3328			retval = sbuf_printf(sb, "</lun>\n");
3329
3330			if (retval != 0)
3331				break;
3332			mtx_unlock(&lun->lun_lock);
3333		}
3334		if (lun != NULL)
3335			mtx_unlock(&lun->lun_lock);
3336		mtx_unlock(&softc->ctl_lock);
3337
3338		if ((retval != 0)
3339		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3340			retval = 0;
3341			sbuf_delete(sb);
3342			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3343			snprintf(list->error_str, sizeof(list->error_str),
3344				 "Out of space, %d bytes is too small",
3345				 list->alloc_len);
3346			break;
3347		}
3348
3349		sbuf_finish(sb);
3350
3351		retval = copyout(sbuf_data(sb), list->lun_xml,
3352				 sbuf_len(sb) + 1);
3353
3354		list->fill_len = sbuf_len(sb) + 1;
3355		list->status = CTL_LUN_LIST_OK;
3356		sbuf_delete(sb);
3357		break;
3358	}
3359	case CTL_ISCSI: {
3360		struct ctl_iscsi *ci;
3361		struct ctl_frontend *fe;
3362
3363		ci = (struct ctl_iscsi *)addr;
3364
3365		fe = ctl_frontend_find("iscsi");
3366		if (fe == NULL) {
3367			ci->status = CTL_ISCSI_ERROR;
3368			snprintf(ci->error_str, sizeof(ci->error_str),
3369			    "Frontend \"iscsi\" not found.");
3370			break;
3371		}
3372
3373		retval = fe->ioctl(dev, cmd, addr, flag, td);
3374		break;
3375	}
3376	case CTL_PORT_REQ: {
3377		struct ctl_req *req;
3378		struct ctl_frontend *fe;
3379
3380		req = (struct ctl_req *)addr;
3381
3382		fe = ctl_frontend_find(req->driver);
3383		if (fe == NULL) {
3384			req->status = CTL_LUN_ERROR;
3385			snprintf(req->error_str, sizeof(req->error_str),
3386			    "Frontend \"%s\" not found.", req->driver);
3387			break;
3388		}
3389		if (req->num_args > 0) {
3390			req->kern_args = ctl_copyin_args(req->num_args,
3391			    req->args, req->error_str, sizeof(req->error_str));
3392			if (req->kern_args == NULL) {
3393				req->status = CTL_LUN_ERROR;
3394				break;
3395			}
3396		}
3397
3398		retval = fe->ioctl(dev, cmd, addr, flag, td);
3399
3400		if (req->num_args > 0) {
3401			ctl_copyout_args(req->num_args, req->kern_args);
3402			ctl_free_args(req->num_args, req->kern_args);
3403		}
3404		break;
3405	}
3406	case CTL_PORT_LIST: {
3407		struct sbuf *sb;
3408		struct ctl_port *port;
3409		struct ctl_lun_list *list;
3410		struct ctl_option *opt;
3411		int j;
3412
3413		list = (struct ctl_lun_list *)addr;
3414
3415		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3416		if (sb == NULL) {
3417			list->status = CTL_LUN_LIST_ERROR;
3418			snprintf(list->error_str, sizeof(list->error_str),
3419				 "Unable to allocate %d bytes for LUN list",
3420				 list->alloc_len);
3421			break;
3422		}
3423
3424		sbuf_printf(sb, "<ctlportlist>\n");
3425
3426		mtx_lock(&softc->ctl_lock);
3427		STAILQ_FOREACH(port, &softc->port_list, links) {
3428			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3429					     (uintmax_t)port->targ_port);
3430
3431			/*
3432			 * Bail out as soon as we see that we've overfilled
3433			 * the buffer.
3434			 */
3435			if (retval != 0)
3436				break;
3437
3438			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3439			    "</frontend_type>\n", port->frontend->name);
3440			if (retval != 0)
3441				break;
3442
3443			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3444					     port->port_type);
3445			if (retval != 0)
3446				break;
3447
3448			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3449			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3450			if (retval != 0)
3451				break;
3452
3453			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3454			    port->port_name);
3455			if (retval != 0)
3456				break;
3457
3458			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3459			    port->physical_port);
3460			if (retval != 0)
3461				break;
3462
3463			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3464			    port->virtual_port);
3465			if (retval != 0)
3466				break;
3467
3468			if (port->target_devid != NULL) {
3469				sbuf_printf(sb, "\t<target>");
3470				ctl_id_sbuf(port->target_devid, sb);
3471				sbuf_printf(sb, "</target>\n");
3472			}
3473
3474			if (port->port_devid != NULL) {
3475				sbuf_printf(sb, "\t<port>");
3476				ctl_id_sbuf(port->port_devid, sb);
3477				sbuf_printf(sb, "</port>\n");
3478			}
3479
3480			if (port->port_info != NULL) {
3481				retval = port->port_info(port->onoff_arg, sb);
3482				if (retval != 0)
3483					break;
3484			}
3485			STAILQ_FOREACH(opt, &port->options, links) {
3486				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3487				    opt->name, opt->value, opt->name);
3488				if (retval != 0)
3489					break;
3490			}
3491
3492			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3493				if (port->wwpn_iid[j].in_use == 0 ||
3494				    (port->wwpn_iid[j].wwpn == 0 &&
3495				     port->wwpn_iid[j].name == NULL))
3496					continue;
3497
3498				if (port->wwpn_iid[j].name != NULL)
3499					retval = sbuf_printf(sb,
3500					    "\t<initiator id=\"%u\">%s</initiator>\n",
3501					    j, port->wwpn_iid[j].name);
3502				else
3503					retval = sbuf_printf(sb,
3504					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3505					    j, port->wwpn_iid[j].wwpn);
3506				if (retval != 0)
3507					break;
3508			}
3509			if (retval != 0)
3510				break;
3511
3512			retval = sbuf_printf(sb, "</targ_port>\n");
3513			if (retval != 0)
3514				break;
3515		}
3516		mtx_unlock(&softc->ctl_lock);
3517
3518		if ((retval != 0)
3519		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3520			retval = 0;
3521			sbuf_delete(sb);
3522			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3523			snprintf(list->error_str, sizeof(list->error_str),
3524				 "Out of space, %d bytes is too small",
3525				 list->alloc_len);
3526			break;
3527		}
3528
3529		sbuf_finish(sb);
3530
3531		retval = copyout(sbuf_data(sb), list->lun_xml,
3532				 sbuf_len(sb) + 1);
3533
3534		list->fill_len = sbuf_len(sb) + 1;
3535		list->status = CTL_LUN_LIST_OK;
3536		sbuf_delete(sb);
3537		break;
3538	}
3539	default: {
3540		/* XXX KDM should we fix this? */
3541#if 0
3542		struct ctl_backend_driver *backend;
3543		unsigned int type;
3544		int found;
3545
3546		found = 0;
3547
3548		/*
3549		 * We encode the backend type as the ioctl type for backend
3550		 * ioctls.  So parse it out here, and then search for a
3551		 * backend of this type.
3552		 */
3553		type = _IOC_TYPE(cmd);
3554
3555		STAILQ_FOREACH(backend, &softc->be_list, links) {
3556			if (backend->type == type) {
3557				found = 1;
3558				break;
3559			}
3560		}
3561		if (found == 0) {
3562			printf("ctl: unknown ioctl command %#lx or backend "
3563			       "%d\n", cmd, type);
3564			retval = EINVAL;
3565			break;
3566		}
3567		retval = backend->ioctl(dev, cmd, addr, flag, td);
3568#endif
3569		retval = ENOTTY;
3570		break;
3571	}
3572	}
3573	return (retval);
3574}
3575
3576uint32_t
3577ctl_get_initindex(struct ctl_nexus *nexus)
3578{
3579	if (nexus->targ_port < CTL_MAX_PORTS)
3580		return (nexus->initid.id +
3581			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3582	else
3583		return (nexus->initid.id +
3584		       ((nexus->targ_port - CTL_MAX_PORTS) *
3585			CTL_MAX_INIT_PER_PORT));
3586}
3587
3588uint32_t
3589ctl_get_resindex(struct ctl_nexus *nexus)
3590{
3591	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3592}
3593
3594uint32_t
3595ctl_port_idx(int port_num)
3596{
3597	if (port_num < CTL_MAX_PORTS)
3598		return(port_num);
3599	else
3600		return(port_num - CTL_MAX_PORTS);
3601}
3602
3603static uint32_t
3604ctl_map_lun(struct ctl_softc *softc, int port_num, uint32_t lun_id)
3605{
3606	struct ctl_port *port;
3607
3608	port = softc->ctl_ports[ctl_port_idx(port_num)];
3609	if (port == NULL)
3610		return (UINT32_MAX);
3611	if (port->lun_map == NULL)
3612		return (lun_id);
3613	return (port->lun_map(port->targ_lun_arg, lun_id));
3614}
3615
3616static uint32_t
3617ctl_map_lun_back(struct ctl_softc *softc, int port_num, uint32_t lun_id)
3618{
3619	struct ctl_port *port;
3620	uint32_t i;
3621
3622	port = softc->ctl_ports[ctl_port_idx(port_num)];
3623	if (port->lun_map == NULL)
3624		return (lun_id);
3625	for (i = 0; i < CTL_MAX_LUNS; i++) {
3626		if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3627			return (i);
3628	}
3629	return (UINT32_MAX);
3630}
3631
3632/*
3633 * Note:  This only works for bitmask sizes that are at least 32 bits, and
3634 * that are a power of 2.
3635 */
3636int
3637ctl_ffz(uint32_t *mask, uint32_t size)
3638{
3639	uint32_t num_chunks, num_pieces;
3640	int i, j;
3641
3642	num_chunks = (size >> 5);
3643	if (num_chunks == 0)
3644		num_chunks++;
3645	num_pieces = MIN((sizeof(uint32_t) * 8), size);
3646
3647	for (i = 0; i < num_chunks; i++) {
3648		for (j = 0; j < num_pieces; j++) {
3649			if ((mask[i] & (1 << j)) == 0)
3650				return ((i << 5) + j);
3651		}
3652	}
3653
3654	return (-1);
3655}
3656
3657int
3658ctl_set_mask(uint32_t *mask, uint32_t bit)
3659{
3660	uint32_t chunk, piece;
3661
3662	chunk = bit >> 5;
3663	piece = bit % (sizeof(uint32_t) * 8);
3664
3665	if ((mask[chunk] & (1 << piece)) != 0)
3666		return (-1);
3667	else
3668		mask[chunk] |= (1 << piece);
3669
3670	return (0);
3671}
3672
3673int
3674ctl_clear_mask(uint32_t *mask, uint32_t bit)
3675{
3676	uint32_t chunk, piece;
3677
3678	chunk = bit >> 5;
3679	piece = bit % (sizeof(uint32_t) * 8);
3680
3681	if ((mask[chunk] & (1 << piece)) == 0)
3682		return (-1);
3683	else
3684		mask[chunk] &= ~(1 << piece);
3685
3686	return (0);
3687}
3688
3689int
3690ctl_is_set(uint32_t *mask, uint32_t bit)
3691{
3692	uint32_t chunk, piece;
3693
3694	chunk = bit >> 5;
3695	piece = bit % (sizeof(uint32_t) * 8);
3696
3697	if ((mask[chunk] & (1 << piece)) == 0)
3698		return (0);
3699	else
3700		return (1);
3701}
3702
3703static uint64_t
3704ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3705{
3706	uint64_t *t;
3707
3708	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3709	if (t == NULL)
3710		return (0);
3711	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3712}
3713
3714static void
3715ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3716{
3717	uint64_t *t;
3718
3719	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3720	if (t == NULL)
3721		return;
3722	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3723}
3724
3725static void
3726ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3727{
3728	uint64_t *p;
3729	u_int i;
3730
3731	i = residx/CTL_MAX_INIT_PER_PORT;
3732	if (lun->pr_keys[i] != NULL)
3733		return;
3734	mtx_unlock(&lun->lun_lock);
3735	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3736	    M_WAITOK | M_ZERO);
3737	mtx_lock(&lun->lun_lock);
3738	if (lun->pr_keys[i] == NULL)
3739		lun->pr_keys[i] = p;
3740	else
3741		free(p, M_CTL);
3742}
3743
3744static void
3745ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3746{
3747	uint64_t *t;
3748
3749	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3750	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3751	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3752}
3753
3754/*
3755 * ctl_softc, pool_name, total_ctl_io are passed in.
3756 * npool is passed out.
3757 */
3758int
3759ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3760		uint32_t total_ctl_io, void **npool)
3761{
3762#ifdef IO_POOLS
3763	struct ctl_io_pool *pool;
3764
3765	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3766					    M_NOWAIT | M_ZERO);
3767	if (pool == NULL)
3768		return (ENOMEM);
3769
3770	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3771	pool->ctl_softc = ctl_softc;
3772	pool->zone = uma_zsecond_create(pool->name, NULL,
3773	    NULL, NULL, NULL, ctl_softc->io_zone);
3774	/* uma_prealloc(pool->zone, total_ctl_io); */
3775
3776	*npool = pool;
3777#else
3778	*npool = ctl_softc->io_zone;
3779#endif
3780	return (0);
3781}
3782
3783void
3784ctl_pool_free(struct ctl_io_pool *pool)
3785{
3786
3787	if (pool == NULL)
3788		return;
3789
3790#ifdef IO_POOLS
3791	uma_zdestroy(pool->zone);
3792	free(pool, M_CTL);
3793#endif
3794}
3795
3796union ctl_io *
3797ctl_alloc_io(void *pool_ref)
3798{
3799	union ctl_io *io;
3800#ifdef IO_POOLS
3801	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3802
3803	io = uma_zalloc(pool->zone, M_WAITOK);
3804#else
3805	io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3806#endif
3807	if (io != NULL)
3808		io->io_hdr.pool = pool_ref;
3809	return (io);
3810}
3811
3812union ctl_io *
3813ctl_alloc_io_nowait(void *pool_ref)
3814{
3815	union ctl_io *io;
3816#ifdef IO_POOLS
3817	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3818
3819	io = uma_zalloc(pool->zone, M_NOWAIT);
3820#else
3821	io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3822#endif
3823	if (io != NULL)
3824		io->io_hdr.pool = pool_ref;
3825	return (io);
3826}
3827
3828void
3829ctl_free_io(union ctl_io *io)
3830{
3831#ifdef IO_POOLS
3832	struct ctl_io_pool *pool;
3833#endif
3834
3835	if (io == NULL)
3836		return;
3837
3838#ifdef IO_POOLS
3839	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3840	uma_zfree(pool->zone, io);
3841#else
3842	uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3843#endif
3844}
3845
3846void
3847ctl_zero_io(union ctl_io *io)
3848{
3849	void *pool_ref;
3850
3851	if (io == NULL)
3852		return;
3853
3854	/*
3855	 * May need to preserve linked list pointers at some point too.
3856	 */
3857	pool_ref = io->io_hdr.pool;
3858	memset(io, 0, sizeof(*io));
3859	io->io_hdr.pool = pool_ref;
3860}
3861
3862/*
3863 * This routine is currently used for internal copies of ctl_ios that need
3864 * to persist for some reason after we've already returned status to the
3865 * FETD.  (Thus the flag set.)
3866 *
3867 * XXX XXX
3868 * Note that this makes a blind copy of all fields in the ctl_io, except
3869 * for the pool reference.  This includes any memory that has been
3870 * allocated!  That memory will no longer be valid after done has been
3871 * called, so this would be VERY DANGEROUS for command that actually does
3872 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3873 * start and stop commands, which don't transfer any data, so this is not a
3874 * problem.  If it is used for anything else, the caller would also need to
3875 * allocate data buffer space and this routine would need to be modified to
3876 * copy the data buffer(s) as well.
3877 */
3878void
3879ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3880{
3881	void *pool_ref;
3882
3883	if ((src == NULL)
3884	 || (dest == NULL))
3885		return;
3886
3887	/*
3888	 * May need to preserve linked list pointers at some point too.
3889	 */
3890	pool_ref = dest->io_hdr.pool;
3891
3892	memcpy(dest, src, MIN(sizeof(*src), sizeof(*dest)));
3893
3894	dest->io_hdr.pool = pool_ref;
3895	/*
3896	 * We need to know that this is an internal copy, and doesn't need
3897	 * to get passed back to the FETD that allocated it.
3898	 */
3899	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3900}
3901
3902int
3903ctl_expand_number(const char *buf, uint64_t *num)
3904{
3905	char *endptr;
3906	uint64_t number;
3907	unsigned shift;
3908
3909	number = strtoq(buf, &endptr, 0);
3910
3911	switch (tolower((unsigned char)*endptr)) {
3912	case 'e':
3913		shift = 60;
3914		break;
3915	case 'p':
3916		shift = 50;
3917		break;
3918	case 't':
3919		shift = 40;
3920		break;
3921	case 'g':
3922		shift = 30;
3923		break;
3924	case 'm':
3925		shift = 20;
3926		break;
3927	case 'k':
3928		shift = 10;
3929		break;
3930	case 'b':
3931	case '\0': /* No unit. */
3932		*num = number;
3933		return (0);
3934	default:
3935		/* Unrecognized unit. */
3936		return (-1);
3937	}
3938
3939	if ((number << shift) >> shift != number) {
3940		/* Overflow */
3941		return (-1);
3942	}
3943	*num = number << shift;
3944	return (0);
3945}
3946
3947
3948/*
3949 * This routine could be used in the future to load default and/or saved
3950 * mode page parameters for a particuar lun.
3951 */
3952static int
3953ctl_init_page_index(struct ctl_lun *lun)
3954{
3955	int i;
3956	struct ctl_page_index *page_index;
3957	const char *value;
3958	uint64_t ival;
3959
3960	memcpy(&lun->mode_pages.index, page_index_template,
3961	       sizeof(page_index_template));
3962
3963	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3964
3965		page_index = &lun->mode_pages.index[i];
3966		/*
3967		 * If this is a disk-only mode page, there's no point in
3968		 * setting it up.  For some pages, we have to have some
3969		 * basic information about the disk in order to calculate the
3970		 * mode page data.
3971		 */
3972		if ((lun->be_lun->lun_type != T_DIRECT)
3973		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3974			continue;
3975
3976		switch (page_index->page_code & SMPH_PC_MASK) {
3977		case SMS_RW_ERROR_RECOVERY_PAGE: {
3978			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3979				panic("subpage is incorrect!");
3980			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3981			       &rw_er_page_default,
3982			       sizeof(rw_er_page_default));
3983			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3984			       &rw_er_page_changeable,
3985			       sizeof(rw_er_page_changeable));
3986			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3987			       &rw_er_page_default,
3988			       sizeof(rw_er_page_default));
3989			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3990			       &rw_er_page_default,
3991			       sizeof(rw_er_page_default));
3992			page_index->page_data =
3993				(uint8_t *)lun->mode_pages.rw_er_page;
3994			break;
3995		}
3996		case SMS_FORMAT_DEVICE_PAGE: {
3997			struct scsi_format_page *format_page;
3998
3999			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4000				panic("subpage is incorrect!");
4001
4002			/*
4003			 * Sectors per track are set above.  Bytes per
4004			 * sector need to be set here on a per-LUN basis.
4005			 */
4006			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4007			       &format_page_default,
4008			       sizeof(format_page_default));
4009			memcpy(&lun->mode_pages.format_page[
4010			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4011			       sizeof(format_page_changeable));
4012			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4013			       &format_page_default,
4014			       sizeof(format_page_default));
4015			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4016			       &format_page_default,
4017			       sizeof(format_page_default));
4018
4019			format_page = &lun->mode_pages.format_page[
4020				CTL_PAGE_CURRENT];
4021			scsi_ulto2b(lun->be_lun->blocksize,
4022				    format_page->bytes_per_sector);
4023
4024			format_page = &lun->mode_pages.format_page[
4025				CTL_PAGE_DEFAULT];
4026			scsi_ulto2b(lun->be_lun->blocksize,
4027				    format_page->bytes_per_sector);
4028
4029			format_page = &lun->mode_pages.format_page[
4030				CTL_PAGE_SAVED];
4031			scsi_ulto2b(lun->be_lun->blocksize,
4032				    format_page->bytes_per_sector);
4033
4034			page_index->page_data =
4035				(uint8_t *)lun->mode_pages.format_page;
4036			break;
4037		}
4038		case SMS_RIGID_DISK_PAGE: {
4039			struct scsi_rigid_disk_page *rigid_disk_page;
4040			uint32_t sectors_per_cylinder;
4041			uint64_t cylinders;
4042#ifndef	__XSCALE__
4043			int shift;
4044#endif /* !__XSCALE__ */
4045
4046			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4047				panic("invalid subpage value %d",
4048				      page_index->subpage);
4049
4050			/*
4051			 * Rotation rate and sectors per track are set
4052			 * above.  We calculate the cylinders here based on
4053			 * capacity.  Due to the number of heads and
4054			 * sectors per track we're using, smaller arrays
4055			 * may turn out to have 0 cylinders.  Linux and
4056			 * FreeBSD don't pay attention to these mode pages
4057			 * to figure out capacity, but Solaris does.  It
4058			 * seems to deal with 0 cylinders just fine, and
4059			 * works out a fake geometry based on the capacity.
4060			 */
4061			memcpy(&lun->mode_pages.rigid_disk_page[
4062			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4063			       sizeof(rigid_disk_page_default));
4064			memcpy(&lun->mode_pages.rigid_disk_page[
4065			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4066			       sizeof(rigid_disk_page_changeable));
4067
4068			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4069				CTL_DEFAULT_HEADS;
4070
4071			/*
4072			 * The divide method here will be more accurate,
4073			 * probably, but results in floating point being
4074			 * used in the kernel on i386 (__udivdi3()).  On the
4075			 * XScale, though, __udivdi3() is implemented in
4076			 * software.
4077			 *
4078			 * The shift method for cylinder calculation is
4079			 * accurate if sectors_per_cylinder is a power of
4080			 * 2.  Otherwise it might be slightly off -- you
4081			 * might have a bit of a truncation problem.
4082			 */
4083#ifdef	__XSCALE__
4084			cylinders = (lun->be_lun->maxlba + 1) /
4085				sectors_per_cylinder;
4086#else
4087			for (shift = 31; shift > 0; shift--) {
4088				if (sectors_per_cylinder & (1 << shift))
4089					break;
4090			}
4091			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4092#endif
4093
4094			/*
4095			 * We've basically got 3 bytes, or 24 bits for the
4096			 * cylinder size in the mode page.  If we're over,
4097			 * just round down to 2^24.
4098			 */
4099			if (cylinders > 0xffffff)
4100				cylinders = 0xffffff;
4101
4102			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4103				CTL_PAGE_DEFAULT];
4104			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4105
4106			if ((value = ctl_get_opt(&lun->be_lun->options,
4107			    "rpm")) != NULL) {
4108				scsi_ulto2b(strtol(value, NULL, 0),
4109				     rigid_disk_page->rotation_rate);
4110			}
4111
4112			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4113			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4114			       sizeof(rigid_disk_page_default));
4115			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4116			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4117			       sizeof(rigid_disk_page_default));
4118
4119			page_index->page_data =
4120				(uint8_t *)lun->mode_pages.rigid_disk_page;
4121			break;
4122		}
4123		case SMS_CACHING_PAGE: {
4124			struct scsi_caching_page *caching_page;
4125
4126			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4127				panic("invalid subpage value %d",
4128				      page_index->subpage);
4129			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4130			       &caching_page_default,
4131			       sizeof(caching_page_default));
4132			memcpy(&lun->mode_pages.caching_page[
4133			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4134			       sizeof(caching_page_changeable));
4135			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4136			       &caching_page_default,
4137			       sizeof(caching_page_default));
4138			caching_page = &lun->mode_pages.caching_page[
4139			    CTL_PAGE_SAVED];
4140			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4141			if (value != NULL && strcmp(value, "off") == 0)
4142				caching_page->flags1 &= ~SCP_WCE;
4143			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4144			if (value != NULL && strcmp(value, "off") == 0)
4145				caching_page->flags1 |= SCP_RCD;
4146			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4147			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4148			       sizeof(caching_page_default));
4149			page_index->page_data =
4150				(uint8_t *)lun->mode_pages.caching_page;
4151			break;
4152		}
4153		case SMS_CONTROL_MODE_PAGE: {
4154			struct scsi_control_page *control_page;
4155
4156			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4157				panic("invalid subpage value %d",
4158				      page_index->subpage);
4159
4160			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4161			       &control_page_default,
4162			       sizeof(control_page_default));
4163			memcpy(&lun->mode_pages.control_page[
4164			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4165			       sizeof(control_page_changeable));
4166			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4167			       &control_page_default,
4168			       sizeof(control_page_default));
4169			control_page = &lun->mode_pages.control_page[
4170			    CTL_PAGE_SAVED];
4171			value = ctl_get_opt(&lun->be_lun->options, "reordering");
4172			if (value != NULL && strcmp(value, "unrestricted") == 0) {
4173				control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4174				control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4175			}
4176			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4177			       &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4178			       sizeof(control_page_default));
4179			page_index->page_data =
4180				(uint8_t *)lun->mode_pages.control_page;
4181			break;
4182
4183		}
4184		case SMS_INFO_EXCEPTIONS_PAGE: {
4185			switch (page_index->subpage) {
4186			case SMS_SUBPAGE_PAGE_0:
4187				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4188				       &ie_page_default,
4189				       sizeof(ie_page_default));
4190				memcpy(&lun->mode_pages.ie_page[
4191				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4192				       sizeof(ie_page_changeable));
4193				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4194				       &ie_page_default,
4195				       sizeof(ie_page_default));
4196				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4197				       &ie_page_default,
4198				       sizeof(ie_page_default));
4199				page_index->page_data =
4200					(uint8_t *)lun->mode_pages.ie_page;
4201				break;
4202			case 0x02: {
4203				struct ctl_logical_block_provisioning_page *page;
4204
4205				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4206				       &lbp_page_default,
4207				       sizeof(lbp_page_default));
4208				memcpy(&lun->mode_pages.lbp_page[
4209				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4210				       sizeof(lbp_page_changeable));
4211				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4212				       &lbp_page_default,
4213				       sizeof(lbp_page_default));
4214				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4215				value = ctl_get_opt(&lun->be_lun->options,
4216				    "avail-threshold");
4217				if (value != NULL &&
4218				    ctl_expand_number(value, &ival) == 0) {
4219					page->descr[0].flags |= SLBPPD_ENABLED |
4220					    SLBPPD_ARMING_DEC;
4221					if (lun->be_lun->blocksize)
4222						ival /= lun->be_lun->blocksize;
4223					else
4224						ival /= 512;
4225					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4226					    page->descr[0].count);
4227				}
4228				value = ctl_get_opt(&lun->be_lun->options,
4229				    "used-threshold");
4230				if (value != NULL &&
4231				    ctl_expand_number(value, &ival) == 0) {
4232					page->descr[1].flags |= SLBPPD_ENABLED |
4233					    SLBPPD_ARMING_INC;
4234					if (lun->be_lun->blocksize)
4235						ival /= lun->be_lun->blocksize;
4236					else
4237						ival /= 512;
4238					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4239					    page->descr[1].count);
4240				}
4241				value = ctl_get_opt(&lun->be_lun->options,
4242				    "pool-avail-threshold");
4243				if (value != NULL &&
4244				    ctl_expand_number(value, &ival) == 0) {
4245					page->descr[2].flags |= SLBPPD_ENABLED |
4246					    SLBPPD_ARMING_DEC;
4247					if (lun->be_lun->blocksize)
4248						ival /= lun->be_lun->blocksize;
4249					else
4250						ival /= 512;
4251					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4252					    page->descr[2].count);
4253				}
4254				value = ctl_get_opt(&lun->be_lun->options,
4255				    "pool-used-threshold");
4256				if (value != NULL &&
4257				    ctl_expand_number(value, &ival) == 0) {
4258					page->descr[3].flags |= SLBPPD_ENABLED |
4259					    SLBPPD_ARMING_INC;
4260					if (lun->be_lun->blocksize)
4261						ival /= lun->be_lun->blocksize;
4262					else
4263						ival /= 512;
4264					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4265					    page->descr[3].count);
4266				}
4267				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4268				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4269				       sizeof(lbp_page_default));
4270				page_index->page_data =
4271					(uint8_t *)lun->mode_pages.lbp_page;
4272			}}
4273			break;
4274		}
4275		case SMS_VENDOR_SPECIFIC_PAGE:{
4276			switch (page_index->subpage) {
4277			case DBGCNF_SUBPAGE_CODE: {
4278				struct copan_debugconf_subpage *current_page,
4279							       *saved_page;
4280
4281				memcpy(&lun->mode_pages.debugconf_subpage[
4282				       CTL_PAGE_CURRENT],
4283				       &debugconf_page_default,
4284				       sizeof(debugconf_page_default));
4285				memcpy(&lun->mode_pages.debugconf_subpage[
4286				       CTL_PAGE_CHANGEABLE],
4287				       &debugconf_page_changeable,
4288				       sizeof(debugconf_page_changeable));
4289				memcpy(&lun->mode_pages.debugconf_subpage[
4290				       CTL_PAGE_DEFAULT],
4291				       &debugconf_page_default,
4292				       sizeof(debugconf_page_default));
4293				memcpy(&lun->mode_pages.debugconf_subpage[
4294				       CTL_PAGE_SAVED],
4295				       &debugconf_page_default,
4296				       sizeof(debugconf_page_default));
4297				page_index->page_data =
4298					(uint8_t *)lun->mode_pages.debugconf_subpage;
4299
4300				current_page = (struct copan_debugconf_subpage *)
4301					(page_index->page_data +
4302					 (page_index->page_len *
4303					  CTL_PAGE_CURRENT));
4304				saved_page = (struct copan_debugconf_subpage *)
4305					(page_index->page_data +
4306					 (page_index->page_len *
4307					  CTL_PAGE_SAVED));
4308				break;
4309			}
4310			default:
4311				panic("invalid subpage value %d",
4312				      page_index->subpage);
4313				break;
4314			}
4315   			break;
4316		}
4317		default:
4318			panic("invalid page value %d",
4319			      page_index->page_code & SMPH_PC_MASK);
4320			break;
4321    	}
4322	}
4323
4324	return (CTL_RETVAL_COMPLETE);
4325}
4326
4327static int
4328ctl_init_log_page_index(struct ctl_lun *lun)
4329{
4330	struct ctl_page_index *page_index;
4331	int i, j, k, prev;
4332
4333	memcpy(&lun->log_pages.index, log_page_index_template,
4334	       sizeof(log_page_index_template));
4335
4336	prev = -1;
4337	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4338
4339		page_index = &lun->log_pages.index[i];
4340		/*
4341		 * If this is a disk-only mode page, there's no point in
4342		 * setting it up.  For some pages, we have to have some
4343		 * basic information about the disk in order to calculate the
4344		 * mode page data.
4345		 */
4346		if ((lun->be_lun->lun_type != T_DIRECT)
4347		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4348			continue;
4349
4350		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4351		     lun->backend->lun_attr == NULL)
4352			continue;
4353
4354		if (page_index->page_code != prev) {
4355			lun->log_pages.pages_page[j] = page_index->page_code;
4356			prev = page_index->page_code;
4357			j++;
4358		}
4359		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4360		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4361		k++;
4362	}
4363	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4364	lun->log_pages.index[0].page_len = j;
4365	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4366	lun->log_pages.index[1].page_len = k * 2;
4367	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4368	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4369
4370	return (CTL_RETVAL_COMPLETE);
4371}
4372
4373static int
4374hex2bin(const char *str, uint8_t *buf, int buf_size)
4375{
4376	int i;
4377	u_char c;
4378
4379	memset(buf, 0, buf_size);
4380	while (isspace(str[0]))
4381		str++;
4382	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4383		str += 2;
4384	buf_size *= 2;
4385	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4386		c = str[i];
4387		if (isdigit(c))
4388			c -= '0';
4389		else if (isalpha(c))
4390			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4391		else
4392			break;
4393		if (c >= 16)
4394			break;
4395		if ((i & 1) == 0)
4396			buf[i / 2] |= (c << 4);
4397		else
4398			buf[i / 2] |= c;
4399	}
4400	return ((i + 1) / 2);
4401}
4402
4403/*
4404 * LUN allocation.
4405 *
4406 * Requirements:
4407 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4408 *   wants us to allocate the LUN and he can block.
4409 * - ctl_softc is always set
4410 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4411 *
4412 * Returns 0 for success, non-zero (errno) for failure.
4413 */
4414static int
4415ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4416	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4417{
4418	struct ctl_lun *nlun, *lun;
4419	struct ctl_port *port;
4420	struct scsi_vpd_id_descriptor *desc;
4421	struct scsi_vpd_id_t10 *t10id;
4422	const char *eui, *naa, *scsiname, *vendor, *value;
4423	int lun_number, i, lun_malloced;
4424	int devidlen, idlen1, idlen2 = 0, len;
4425
4426	if (be_lun == NULL)
4427		return (EINVAL);
4428
4429	/*
4430	 * We currently only support Direct Access or Processor LUN types.
4431	 */
4432	switch (be_lun->lun_type) {
4433	case T_DIRECT:
4434		break;
4435	case T_PROCESSOR:
4436		break;
4437	case T_SEQUENTIAL:
4438	case T_CHANGER:
4439	default:
4440		be_lun->lun_config_status(be_lun->be_lun,
4441					  CTL_LUN_CONFIG_FAILURE);
4442		break;
4443	}
4444	if (ctl_lun == NULL) {
4445		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4446		lun_malloced = 1;
4447	} else {
4448		lun_malloced = 0;
4449		lun = ctl_lun;
4450	}
4451
4452	memset(lun, 0, sizeof(*lun));
4453	if (lun_malloced)
4454		lun->flags = CTL_LUN_MALLOCED;
4455
4456	/* Generate LUN ID. */
4457	devidlen = max(CTL_DEVID_MIN_LEN,
4458	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4459	idlen1 = sizeof(*t10id) + devidlen;
4460	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4461	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4462	if (scsiname != NULL) {
4463		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4464		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4465	}
4466	eui = ctl_get_opt(&be_lun->options, "eui");
4467	if (eui != NULL) {
4468		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4469	}
4470	naa = ctl_get_opt(&be_lun->options, "naa");
4471	if (naa != NULL) {
4472		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4473	}
4474	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4475	    M_CTL, M_WAITOK | M_ZERO);
4476	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4477	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4478	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4479	desc->length = idlen1;
4480	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4481	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4482	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4483		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4484	} else {
4485		strncpy(t10id->vendor, vendor,
4486		    min(sizeof(t10id->vendor), strlen(vendor)));
4487	}
4488	strncpy((char *)t10id->vendor_spec_id,
4489	    (char *)be_lun->device_id, devidlen);
4490	if (scsiname != NULL) {
4491		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4492		    desc->length);
4493		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4494		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4495		    SVPD_ID_TYPE_SCSI_NAME;
4496		desc->length = idlen2;
4497		strlcpy(desc->identifier, scsiname, idlen2);
4498	}
4499	if (eui != NULL) {
4500		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4501		    desc->length);
4502		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4503		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4504		    SVPD_ID_TYPE_EUI64;
4505		desc->length = hex2bin(eui, desc->identifier, 16);
4506		desc->length = desc->length > 12 ? 16 :
4507		    (desc->length > 8 ? 12 : 8);
4508		len -= 16 - desc->length;
4509	}
4510	if (naa != NULL) {
4511		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4512		    desc->length);
4513		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4514		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4515		    SVPD_ID_TYPE_NAA;
4516		desc->length = hex2bin(naa, desc->identifier, 16);
4517		desc->length = desc->length > 8 ? 16 : 8;
4518		len -= 16 - desc->length;
4519	}
4520	lun->lun_devid->len = len;
4521
4522	mtx_lock(&ctl_softc->ctl_lock);
4523	/*
4524	 * See if the caller requested a particular LUN number.  If so, see
4525	 * if it is available.  Otherwise, allocate the first available LUN.
4526	 */
4527	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4528		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4529		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4530			mtx_unlock(&ctl_softc->ctl_lock);
4531			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4532				printf("ctl: requested LUN ID %d is higher "
4533				       "than CTL_MAX_LUNS - 1 (%d)\n",
4534				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4535			} else {
4536				/*
4537				 * XXX KDM return an error, or just assign
4538				 * another LUN ID in this case??
4539				 */
4540				printf("ctl: requested LUN ID %d is already "
4541				       "in use\n", be_lun->req_lun_id);
4542			}
4543			if (lun->flags & CTL_LUN_MALLOCED)
4544				free(lun, M_CTL);
4545			be_lun->lun_config_status(be_lun->be_lun,
4546						  CTL_LUN_CONFIG_FAILURE);
4547			return (ENOSPC);
4548		}
4549		lun_number = be_lun->req_lun_id;
4550	} else {
4551		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4552		if (lun_number == -1) {
4553			mtx_unlock(&ctl_softc->ctl_lock);
4554			printf("ctl: can't allocate LUN on target %ju, out of "
4555			       "LUNs\n", (uintmax_t)target_id.id);
4556			if (lun->flags & CTL_LUN_MALLOCED)
4557				free(lun, M_CTL);
4558			be_lun->lun_config_status(be_lun->be_lun,
4559						  CTL_LUN_CONFIG_FAILURE);
4560			return (ENOSPC);
4561		}
4562	}
4563	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4564
4565	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4566	lun->target = target_id;
4567	lun->lun = lun_number;
4568	lun->be_lun = be_lun;
4569	/*
4570	 * The processor LUN is always enabled.  Disk LUNs come on line
4571	 * disabled, and must be enabled by the backend.
4572	 */
4573	lun->flags |= CTL_LUN_DISABLED;
4574	lun->backend = be_lun->be;
4575	be_lun->ctl_lun = lun;
4576	be_lun->lun_id = lun_number;
4577	atomic_add_int(&be_lun->be->num_luns, 1);
4578	if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4579		lun->flags |= CTL_LUN_OFFLINE;
4580
4581	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4582		lun->flags |= CTL_LUN_STOPPED;
4583
4584	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4585		lun->flags |= CTL_LUN_INOPERABLE;
4586
4587	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4588		lun->flags |= CTL_LUN_PRIMARY_SC;
4589
4590	value = ctl_get_opt(&be_lun->options, "readonly");
4591	if (value != NULL && strcmp(value, "on") == 0)
4592		lun->flags |= CTL_LUN_READONLY;
4593
4594	lun->serseq = CTL_LUN_SERSEQ_OFF;
4595	if (be_lun->flags & CTL_LUN_FLAG_SERSEQ_READ)
4596		lun->serseq = CTL_LUN_SERSEQ_READ;
4597	value = ctl_get_opt(&be_lun->options, "serseq");
4598	if (value != NULL && strcmp(value, "on") == 0)
4599		lun->serseq = CTL_LUN_SERSEQ_ON;
4600	else if (value != NULL && strcmp(value, "read") == 0)
4601		lun->serseq = CTL_LUN_SERSEQ_READ;
4602	else if (value != NULL && strcmp(value, "off") == 0)
4603		lun->serseq = CTL_LUN_SERSEQ_OFF;
4604
4605	lun->ctl_softc = ctl_softc;
4606	TAILQ_INIT(&lun->ooa_queue);
4607	TAILQ_INIT(&lun->blocked_queue);
4608	STAILQ_INIT(&lun->error_list);
4609	ctl_tpc_lun_init(lun);
4610
4611	/*
4612	 * Initialize the mode and log page index.
4613	 */
4614	ctl_init_page_index(lun);
4615	ctl_init_log_page_index(lun);
4616
4617	/*
4618	 * Now, before we insert this lun on the lun list, set the lun
4619	 * inventory changed UA for all other luns.
4620	 */
4621	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4622		mtx_lock(&nlun->lun_lock);
4623		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4624		mtx_unlock(&nlun->lun_lock);
4625	}
4626
4627	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4628
4629	ctl_softc->ctl_luns[lun_number] = lun;
4630
4631	ctl_softc->num_luns++;
4632
4633	/* Setup statistics gathering */
4634	lun->stats.device_type = be_lun->lun_type;
4635	lun->stats.lun_number = lun_number;
4636	if (lun->stats.device_type == T_DIRECT)
4637		lun->stats.blocksize = be_lun->blocksize;
4638	else
4639		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4640	for (i = 0;i < CTL_MAX_PORTS;i++)
4641		lun->stats.ports[i].targ_port = i;
4642
4643	mtx_unlock(&ctl_softc->ctl_lock);
4644
4645	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4646
4647	/*
4648	 * Run through each registered FETD and bring it online if it isn't
4649	 * already.  Enable the target ID if it hasn't been enabled, and
4650	 * enable this particular LUN.
4651	 */
4652	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4653		int retval;
4654
4655		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4656		if (retval != 0) {
4657			printf("ctl_alloc_lun: FETD %s port %d returned error "
4658			       "%d for lun_enable on target %ju lun %d\n",
4659			       port->port_name, port->targ_port, retval,
4660			       (uintmax_t)target_id.id, lun_number);
4661		} else
4662			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4663	}
4664	return (0);
4665}
4666
4667/*
4668 * Delete a LUN.
4669 * Assumptions:
4670 * - LUN has already been marked invalid and any pending I/O has been taken
4671 *   care of.
4672 */
4673static int
4674ctl_free_lun(struct ctl_lun *lun)
4675{
4676	struct ctl_softc *softc;
4677#if 0
4678	struct ctl_port *port;
4679#endif
4680	struct ctl_lun *nlun;
4681	int i;
4682
4683	softc = lun->ctl_softc;
4684
4685	mtx_assert(&softc->ctl_lock, MA_OWNED);
4686
4687	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4688
4689	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4690
4691	softc->ctl_luns[lun->lun] = NULL;
4692
4693	if (!TAILQ_EMPTY(&lun->ooa_queue))
4694		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4695
4696	softc->num_luns--;
4697
4698	/*
4699	 * XXX KDM this scheme only works for a single target/multiple LUN
4700	 * setup.  It needs to be revamped for a multiple target scheme.
4701	 *
4702	 * XXX KDM this results in port->lun_disable() getting called twice,
4703	 * once when ctl_disable_lun() is called, and a second time here.
4704	 * We really need to re-think the LUN disable semantics.  There
4705	 * should probably be several steps/levels to LUN removal:
4706	 *  - disable
4707	 *  - invalidate
4708	 *  - free
4709 	 *
4710	 * Right now we only have a disable method when communicating to
4711	 * the front end ports, at least for individual LUNs.
4712	 */
4713#if 0
4714	STAILQ_FOREACH(port, &softc->port_list, links) {
4715		int retval;
4716
4717		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4718					 lun->lun);
4719		if (retval != 0) {
4720			printf("ctl_free_lun: FETD %s port %d returned error "
4721			       "%d for lun_disable on target %ju lun %jd\n",
4722			       port->port_name, port->targ_port, retval,
4723			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4724		}
4725
4726		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4727			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4728
4729			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4730			if (retval != 0) {
4731				printf("ctl_free_lun: FETD %s port %d "
4732				       "returned error %d for targ_disable on "
4733				       "target %ju\n", port->port_name,
4734				       port->targ_port, retval,
4735				       (uintmax_t)lun->target.id);
4736			} else
4737				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4738
4739			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4740				continue;
4741
4742#if 0
4743			port->port_offline(port->onoff_arg);
4744			port->status &= ~CTL_PORT_STATUS_ONLINE;
4745#endif
4746		}
4747	}
4748#endif
4749
4750	/*
4751	 * Tell the backend to free resources, if this LUN has a backend.
4752	 */
4753	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4754	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4755
4756	ctl_tpc_lun_shutdown(lun);
4757	mtx_destroy(&lun->lun_lock);
4758	free(lun->lun_devid, M_CTL);
4759	for (i = 0; i < CTL_MAX_PORTS; i++)
4760		free(lun->pending_ua[i], M_CTL);
4761	for (i = 0; i < 2 * CTL_MAX_PORTS; i++)
4762		free(lun->pr_keys[i], M_CTL);
4763	free(lun->write_buffer, M_CTL);
4764	if (lun->flags & CTL_LUN_MALLOCED)
4765		free(lun, M_CTL);
4766
4767	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4768		mtx_lock(&nlun->lun_lock);
4769		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4770		mtx_unlock(&nlun->lun_lock);
4771	}
4772
4773	return (0);
4774}
4775
4776static void
4777ctl_create_lun(struct ctl_be_lun *be_lun)
4778{
4779	struct ctl_softc *softc;
4780
4781	softc = control_softc;
4782
4783	/*
4784	 * ctl_alloc_lun() should handle all potential failure cases.
4785	 */
4786	ctl_alloc_lun(softc, NULL, be_lun, softc->target);
4787}
4788
4789int
4790ctl_add_lun(struct ctl_be_lun *be_lun)
4791{
4792	struct ctl_softc *softc = control_softc;
4793
4794	mtx_lock(&softc->ctl_lock);
4795	STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4796	mtx_unlock(&softc->ctl_lock);
4797	wakeup(&softc->pending_lun_queue);
4798
4799	return (0);
4800}
4801
4802int
4803ctl_enable_lun(struct ctl_be_lun *be_lun)
4804{
4805	struct ctl_softc *softc;
4806	struct ctl_port *port, *nport;
4807	struct ctl_lun *lun;
4808	int retval;
4809
4810	lun = (struct ctl_lun *)be_lun->ctl_lun;
4811	softc = lun->ctl_softc;
4812
4813	mtx_lock(&softc->ctl_lock);
4814	mtx_lock(&lun->lun_lock);
4815	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4816		/*
4817		 * eh?  Why did we get called if the LUN is already
4818		 * enabled?
4819		 */
4820		mtx_unlock(&lun->lun_lock);
4821		mtx_unlock(&softc->ctl_lock);
4822		return (0);
4823	}
4824	lun->flags &= ~CTL_LUN_DISABLED;
4825	mtx_unlock(&lun->lun_lock);
4826
4827	for (port = STAILQ_FIRST(&softc->port_list); port != NULL; port = nport) {
4828		nport = STAILQ_NEXT(port, links);
4829
4830		/*
4831		 * Drop the lock while we call the FETD's enable routine.
4832		 * This can lead to a callback into CTL (at least in the
4833		 * case of the internal initiator frontend.
4834		 */
4835		mtx_unlock(&softc->ctl_lock);
4836		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4837		mtx_lock(&softc->ctl_lock);
4838		if (retval != 0) {
4839			printf("%s: FETD %s port %d returned error "
4840			       "%d for lun_enable on target %ju lun %jd\n",
4841			       __func__, port->port_name, port->targ_port, retval,
4842			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4843		}
4844#if 0
4845		 else {
4846            /* NOTE:  TODO:  why does lun enable affect port status? */
4847			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4848		}
4849#endif
4850	}
4851
4852	mtx_unlock(&softc->ctl_lock);
4853
4854	return (0);
4855}
4856
4857int
4858ctl_disable_lun(struct ctl_be_lun *be_lun)
4859{
4860	struct ctl_softc *softc;
4861	struct ctl_port *port;
4862	struct ctl_lun *lun;
4863	int retval;
4864
4865	lun = (struct ctl_lun *)be_lun->ctl_lun;
4866	softc = lun->ctl_softc;
4867
4868	mtx_lock(&softc->ctl_lock);
4869	mtx_lock(&lun->lun_lock);
4870	if (lun->flags & CTL_LUN_DISABLED) {
4871		mtx_unlock(&lun->lun_lock);
4872		mtx_unlock(&softc->ctl_lock);
4873		return (0);
4874	}
4875	lun->flags |= CTL_LUN_DISABLED;
4876	mtx_unlock(&lun->lun_lock);
4877
4878	STAILQ_FOREACH(port, &softc->port_list, links) {
4879		mtx_unlock(&softc->ctl_lock);
4880		/*
4881		 * Drop the lock before we call the frontend's disable
4882		 * routine, to avoid lock order reversals.
4883		 *
4884		 * XXX KDM what happens if the frontend list changes while
4885		 * we're traversing it?  It's unlikely, but should be handled.
4886		 */
4887		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4888					 lun->lun);
4889		mtx_lock(&softc->ctl_lock);
4890		if (retval != 0) {
4891			printf("ctl_alloc_lun: FETD %s port %d returned error "
4892			       "%d for lun_disable on target %ju lun %jd\n",
4893			       port->port_name, port->targ_port, retval,
4894			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4895		}
4896	}
4897
4898	mtx_unlock(&softc->ctl_lock);
4899
4900	return (0);
4901}
4902
4903int
4904ctl_start_lun(struct ctl_be_lun *be_lun)
4905{
4906	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4907
4908	mtx_lock(&lun->lun_lock);
4909	lun->flags &= ~CTL_LUN_STOPPED;
4910	mtx_unlock(&lun->lun_lock);
4911	return (0);
4912}
4913
4914int
4915ctl_stop_lun(struct ctl_be_lun *be_lun)
4916{
4917	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4918
4919	mtx_lock(&lun->lun_lock);
4920	lun->flags |= CTL_LUN_STOPPED;
4921	mtx_unlock(&lun->lun_lock);
4922	return (0);
4923}
4924
4925int
4926ctl_lun_offline(struct ctl_be_lun *be_lun)
4927{
4928	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4929
4930	mtx_lock(&lun->lun_lock);
4931	lun->flags |= CTL_LUN_OFFLINE;
4932	mtx_unlock(&lun->lun_lock);
4933	return (0);
4934}
4935
4936int
4937ctl_lun_online(struct ctl_be_lun *be_lun)
4938{
4939	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4940
4941	mtx_lock(&lun->lun_lock);
4942	lun->flags &= ~CTL_LUN_OFFLINE;
4943	mtx_unlock(&lun->lun_lock);
4944	return (0);
4945}
4946
4947int
4948ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4949{
4950	struct ctl_softc *softc;
4951	struct ctl_lun *lun;
4952
4953	lun = (struct ctl_lun *)be_lun->ctl_lun;
4954	softc = lun->ctl_softc;
4955
4956	mtx_lock(&lun->lun_lock);
4957
4958	/*
4959	 * The LUN needs to be disabled before it can be marked invalid.
4960	 */
4961	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4962		mtx_unlock(&lun->lun_lock);
4963		return (-1);
4964	}
4965	/*
4966	 * Mark the LUN invalid.
4967	 */
4968	lun->flags |= CTL_LUN_INVALID;
4969
4970	/*
4971	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4972	 * If we have something in the OOA queue, we'll free it when the
4973	 * last I/O completes.
4974	 */
4975	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4976		mtx_unlock(&lun->lun_lock);
4977		mtx_lock(&softc->ctl_lock);
4978		ctl_free_lun(lun);
4979		mtx_unlock(&softc->ctl_lock);
4980	} else
4981		mtx_unlock(&lun->lun_lock);
4982
4983	return (0);
4984}
4985
4986int
4987ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4988{
4989	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4990
4991	mtx_lock(&lun->lun_lock);
4992	lun->flags |= CTL_LUN_INOPERABLE;
4993	mtx_unlock(&lun->lun_lock);
4994	return (0);
4995}
4996
4997int
4998ctl_lun_operable(struct ctl_be_lun *be_lun)
4999{
5000	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5001
5002	mtx_lock(&lun->lun_lock);
5003	lun->flags &= ~CTL_LUN_INOPERABLE;
5004	mtx_unlock(&lun->lun_lock);
5005	return (0);
5006}
5007
5008void
5009ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5010{
5011	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5012
5013	mtx_lock(&lun->lun_lock);
5014	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGED);
5015	mtx_unlock(&lun->lun_lock);
5016}
5017
5018/*
5019 * Backend "memory move is complete" callback for requests that never
5020 * make it down to say RAIDCore's configuration code.
5021 */
5022int
5023ctl_config_move_done(union ctl_io *io)
5024{
5025	int retval;
5026
5027	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5028	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5029	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5030
5031	if ((io->io_hdr.port_status != 0) &&
5032	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5033	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5034		/*
5035		 * For hardware error sense keys, the sense key
5036		 * specific value is defined to be a retry count,
5037		 * but we use it to pass back an internal FETD
5038		 * error code.  XXX KDM  Hopefully the FETD is only
5039		 * using 16 bits for an error code, since that's
5040		 * all the space we have in the sks field.
5041		 */
5042		ctl_set_internal_failure(&io->scsiio,
5043					 /*sks_valid*/ 1,
5044					 /*retry_count*/
5045					 io->io_hdr.port_status);
5046	}
5047
5048	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5049	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5050	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5051	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5052		/*
5053		 * XXX KDM just assuming a single pointer here, and not a
5054		 * S/G list.  If we start using S/G lists for config data,
5055		 * we'll need to know how to clean them up here as well.
5056		 */
5057		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5058			free(io->scsiio.kern_data_ptr, M_CTL);
5059		ctl_done(io);
5060		retval = CTL_RETVAL_COMPLETE;
5061	} else {
5062		/*
5063		 * XXX KDM now we need to continue data movement.  Some
5064		 * options:
5065		 * - call ctl_scsiio() again?  We don't do this for data
5066		 *   writes, because for those at least we know ahead of
5067		 *   time where the write will go and how long it is.  For
5068		 *   config writes, though, that information is largely
5069		 *   contained within the write itself, thus we need to
5070		 *   parse out the data again.
5071		 *
5072		 * - Call some other function once the data is in?
5073		 */
5074		if (ctl_debug & CTL_DEBUG_CDB_DATA)
5075			ctl_data_print(io);
5076
5077		/*
5078		 * XXX KDM call ctl_scsiio() again for now, and check flag
5079		 * bits to see whether we're allocated or not.
5080		 */
5081		retval = ctl_scsiio(&io->scsiio);
5082	}
5083	return (retval);
5084}
5085
5086/*
5087 * This gets called by a backend driver when it is done with a
5088 * data_submit method.
5089 */
5090void
5091ctl_data_submit_done(union ctl_io *io)
5092{
5093	/*
5094	 * If the IO_CONT flag is set, we need to call the supplied
5095	 * function to continue processing the I/O, instead of completing
5096	 * the I/O just yet.
5097	 *
5098	 * If there is an error, though, we don't want to keep processing.
5099	 * Instead, just send status back to the initiator.
5100	 */
5101	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5102	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5103	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5104	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5105		io->scsiio.io_cont(io);
5106		return;
5107	}
5108	ctl_done(io);
5109}
5110
5111/*
5112 * This gets called by a backend driver when it is done with a
5113 * configuration write.
5114 */
5115void
5116ctl_config_write_done(union ctl_io *io)
5117{
5118	uint8_t *buf;
5119
5120	/*
5121	 * If the IO_CONT flag is set, we need to call the supplied
5122	 * function to continue processing the I/O, instead of completing
5123	 * the I/O just yet.
5124	 *
5125	 * If there is an error, though, we don't want to keep processing.
5126	 * Instead, just send status back to the initiator.
5127	 */
5128	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5129	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5130	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5131	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5132		io->scsiio.io_cont(io);
5133		return;
5134	}
5135	/*
5136	 * Since a configuration write can be done for commands that actually
5137	 * have data allocated, like write buffer, and commands that have
5138	 * no data, like start/stop unit, we need to check here.
5139	 */
5140	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5141		buf = io->scsiio.kern_data_ptr;
5142	else
5143		buf = NULL;
5144	ctl_done(io);
5145	if (buf)
5146		free(buf, M_CTL);
5147}
5148
5149void
5150ctl_config_read_done(union ctl_io *io)
5151{
5152	uint8_t *buf;
5153
5154	/*
5155	 * If there is some error -- we are done, skip data transfer.
5156	 */
5157	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5158	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5159	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5160		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5161			buf = io->scsiio.kern_data_ptr;
5162		else
5163			buf = NULL;
5164		ctl_done(io);
5165		if (buf)
5166			free(buf, M_CTL);
5167		return;
5168	}
5169
5170	/*
5171	 * If the IO_CONT flag is set, we need to call the supplied
5172	 * function to continue processing the I/O, instead of completing
5173	 * the I/O just yet.
5174	 */
5175	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5176		io->scsiio.io_cont(io);
5177		return;
5178	}
5179
5180	ctl_datamove(io);
5181}
5182
5183/*
5184 * SCSI release command.
5185 */
5186int
5187ctl_scsi_release(struct ctl_scsiio *ctsio)
5188{
5189	int length, longid, thirdparty_id, resv_id;
5190	struct ctl_lun *lun;
5191	uint32_t residx;
5192
5193	length = 0;
5194	resv_id = 0;
5195
5196	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5197
5198	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5199	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5200
5201	switch (ctsio->cdb[0]) {
5202	case RELEASE_10: {
5203		struct scsi_release_10 *cdb;
5204
5205		cdb = (struct scsi_release_10 *)ctsio->cdb;
5206
5207		if (cdb->byte2 & SR10_LONGID)
5208			longid = 1;
5209		else
5210			thirdparty_id = cdb->thirdparty_id;
5211
5212		resv_id = cdb->resv_id;
5213		length = scsi_2btoul(cdb->length);
5214		break;
5215	}
5216	}
5217
5218
5219	/*
5220	 * XXX KDM right now, we only support LUN reservation.  We don't
5221	 * support 3rd party reservations, or extent reservations, which
5222	 * might actually need the parameter list.  If we've gotten this
5223	 * far, we've got a LUN reservation.  Anything else got kicked out
5224	 * above.  So, according to SPC, ignore the length.
5225	 */
5226	length = 0;
5227
5228	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5229	 && (length > 0)) {
5230		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5231		ctsio->kern_data_len = length;
5232		ctsio->kern_total_len = length;
5233		ctsio->kern_data_resid = 0;
5234		ctsio->kern_rel_offset = 0;
5235		ctsio->kern_sg_entries = 0;
5236		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5237		ctsio->be_move_done = ctl_config_move_done;
5238		ctl_datamove((union ctl_io *)ctsio);
5239
5240		return (CTL_RETVAL_COMPLETE);
5241	}
5242
5243	if (length > 0)
5244		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5245
5246	mtx_lock(&lun->lun_lock);
5247
5248	/*
5249	 * According to SPC, it is not an error for an intiator to attempt
5250	 * to release a reservation on a LUN that isn't reserved, or that
5251	 * is reserved by another initiator.  The reservation can only be
5252	 * released, though, by the initiator who made it or by one of
5253	 * several reset type events.
5254	 */
5255	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5256			lun->flags &= ~CTL_LUN_RESERVED;
5257
5258	mtx_unlock(&lun->lun_lock);
5259
5260	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5261		free(ctsio->kern_data_ptr, M_CTL);
5262		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5263	}
5264
5265	ctl_set_success(ctsio);
5266	ctl_done((union ctl_io *)ctsio);
5267	return (CTL_RETVAL_COMPLETE);
5268}
5269
5270int
5271ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5272{
5273	int extent, thirdparty, longid;
5274	int resv_id, length;
5275	uint64_t thirdparty_id;
5276	struct ctl_lun *lun;
5277	uint32_t residx;
5278
5279	extent = 0;
5280	thirdparty = 0;
5281	longid = 0;
5282	resv_id = 0;
5283	length = 0;
5284	thirdparty_id = 0;
5285
5286	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5287
5288	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5289	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5290
5291	switch (ctsio->cdb[0]) {
5292	case RESERVE_10: {
5293		struct scsi_reserve_10 *cdb;
5294
5295		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5296
5297		if (cdb->byte2 & SR10_LONGID)
5298			longid = 1;
5299		else
5300			thirdparty_id = cdb->thirdparty_id;
5301
5302		resv_id = cdb->resv_id;
5303		length = scsi_2btoul(cdb->length);
5304		break;
5305	}
5306	}
5307
5308	/*
5309	 * XXX KDM right now, we only support LUN reservation.  We don't
5310	 * support 3rd party reservations, or extent reservations, which
5311	 * might actually need the parameter list.  If we've gotten this
5312	 * far, we've got a LUN reservation.  Anything else got kicked out
5313	 * above.  So, according to SPC, ignore the length.
5314	 */
5315	length = 0;
5316
5317	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5318	 && (length > 0)) {
5319		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5320		ctsio->kern_data_len = length;
5321		ctsio->kern_total_len = length;
5322		ctsio->kern_data_resid = 0;
5323		ctsio->kern_rel_offset = 0;
5324		ctsio->kern_sg_entries = 0;
5325		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5326		ctsio->be_move_done = ctl_config_move_done;
5327		ctl_datamove((union ctl_io *)ctsio);
5328
5329		return (CTL_RETVAL_COMPLETE);
5330	}
5331
5332	if (length > 0)
5333		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5334
5335	mtx_lock(&lun->lun_lock);
5336	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5337		ctl_set_reservation_conflict(ctsio);
5338		goto bailout;
5339	}
5340
5341	lun->flags |= CTL_LUN_RESERVED;
5342	lun->res_idx = residx;
5343
5344	ctl_set_success(ctsio);
5345
5346bailout:
5347	mtx_unlock(&lun->lun_lock);
5348
5349	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5350		free(ctsio->kern_data_ptr, M_CTL);
5351		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5352	}
5353
5354	ctl_done((union ctl_io *)ctsio);
5355	return (CTL_RETVAL_COMPLETE);
5356}
5357
5358int
5359ctl_start_stop(struct ctl_scsiio *ctsio)
5360{
5361	struct scsi_start_stop_unit *cdb;
5362	struct ctl_lun *lun;
5363	int retval;
5364
5365	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5366
5367	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5368	retval = 0;
5369
5370	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5371
5372	/*
5373	 * XXX KDM
5374	 * We don't support the immediate bit on a stop unit.  In order to
5375	 * do that, we would need to code up a way to know that a stop is
5376	 * pending, and hold off any new commands until it completes, one
5377	 * way or another.  Then we could accept or reject those commands
5378	 * depending on its status.  We would almost need to do the reverse
5379	 * of what we do below for an immediate start -- return the copy of
5380	 * the ctl_io to the FETD with status to send to the host (and to
5381	 * free the copy!) and then free the original I/O once the stop
5382	 * actually completes.  That way, the OOA queue mechanism can work
5383	 * to block commands that shouldn't proceed.  Another alternative
5384	 * would be to put the copy in the queue in place of the original,
5385	 * and return the original back to the caller.  That could be
5386	 * slightly safer..
5387	 */
5388	if ((cdb->byte2 & SSS_IMMED)
5389	 && ((cdb->how & SSS_START) == 0)) {
5390		ctl_set_invalid_field(ctsio,
5391				      /*sks_valid*/ 1,
5392				      /*command*/ 1,
5393				      /*field*/ 1,
5394				      /*bit_valid*/ 1,
5395				      /*bit*/ 0);
5396		ctl_done((union ctl_io *)ctsio);
5397		return (CTL_RETVAL_COMPLETE);
5398	}
5399
5400	if ((lun->flags & CTL_LUN_PR_RESERVED)
5401	 && ((cdb->how & SSS_START)==0)) {
5402		uint32_t residx;
5403
5404		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5405		if (ctl_get_prkey(lun, residx) == 0
5406		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5407
5408			ctl_set_reservation_conflict(ctsio);
5409			ctl_done((union ctl_io *)ctsio);
5410			return (CTL_RETVAL_COMPLETE);
5411		}
5412	}
5413
5414	/*
5415	 * If there is no backend on this device, we can't start or stop
5416	 * it.  In theory we shouldn't get any start/stop commands in the
5417	 * first place at this level if the LUN doesn't have a backend.
5418	 * That should get stopped by the command decode code.
5419	 */
5420	if (lun->backend == NULL) {
5421		ctl_set_invalid_opcode(ctsio);
5422		ctl_done((union ctl_io *)ctsio);
5423		return (CTL_RETVAL_COMPLETE);
5424	}
5425
5426	/*
5427	 * XXX KDM Copan-specific offline behavior.
5428	 * Figure out a reasonable way to port this?
5429	 */
5430#ifdef NEEDTOPORT
5431	mtx_lock(&lun->lun_lock);
5432
5433	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5434	 && (lun->flags & CTL_LUN_OFFLINE)) {
5435		/*
5436		 * If the LUN is offline, and the on/offline bit isn't set,
5437		 * reject the start or stop.  Otherwise, let it through.
5438		 */
5439		mtx_unlock(&lun->lun_lock);
5440		ctl_set_lun_not_ready(ctsio);
5441		ctl_done((union ctl_io *)ctsio);
5442	} else {
5443		mtx_unlock(&lun->lun_lock);
5444#endif /* NEEDTOPORT */
5445		/*
5446		 * This could be a start or a stop when we're online,
5447		 * or a stop/offline or start/online.  A start or stop when
5448		 * we're offline is covered in the case above.
5449		 */
5450		/*
5451		 * In the non-immediate case, we send the request to
5452		 * the backend and return status to the user when
5453		 * it is done.
5454		 *
5455		 * In the immediate case, we allocate a new ctl_io
5456		 * to hold a copy of the request, and send that to
5457		 * the backend.  We then set good status on the
5458		 * user's request and return it immediately.
5459		 */
5460		if (cdb->byte2 & SSS_IMMED) {
5461			union ctl_io *new_io;
5462
5463			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5464			ctl_copy_io((union ctl_io *)ctsio, new_io);
5465			retval = lun->backend->config_write(new_io);
5466			ctl_set_success(ctsio);
5467			ctl_done((union ctl_io *)ctsio);
5468		} else {
5469			retval = lun->backend->config_write(
5470				(union ctl_io *)ctsio);
5471		}
5472#ifdef NEEDTOPORT
5473	}
5474#endif
5475	return (retval);
5476}
5477
5478/*
5479 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5480 * we don't really do anything with the LBA and length fields if the user
5481 * passes them in.  Instead we'll just flush out the cache for the entire
5482 * LUN.
5483 */
5484int
5485ctl_sync_cache(struct ctl_scsiio *ctsio)
5486{
5487	struct ctl_lun *lun;
5488	struct ctl_softc *softc;
5489	uint64_t starting_lba;
5490	uint32_t block_count;
5491	int retval;
5492
5493	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5494
5495	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5496	softc = lun->ctl_softc;
5497	retval = 0;
5498
5499	switch (ctsio->cdb[0]) {
5500	case SYNCHRONIZE_CACHE: {
5501		struct scsi_sync_cache *cdb;
5502		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5503
5504		starting_lba = scsi_4btoul(cdb->begin_lba);
5505		block_count = scsi_2btoul(cdb->lb_count);
5506		break;
5507	}
5508	case SYNCHRONIZE_CACHE_16: {
5509		struct scsi_sync_cache_16 *cdb;
5510		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5511
5512		starting_lba = scsi_8btou64(cdb->begin_lba);
5513		block_count = scsi_4btoul(cdb->lb_count);
5514		break;
5515	}
5516	default:
5517		ctl_set_invalid_opcode(ctsio);
5518		ctl_done((union ctl_io *)ctsio);
5519		goto bailout;
5520		break; /* NOTREACHED */
5521	}
5522
5523	/*
5524	 * We check the LBA and length, but don't do anything with them.
5525	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5526	 * get flushed.  This check will just help satisfy anyone who wants
5527	 * to see an error for an out of range LBA.
5528	 */
5529	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5530		ctl_set_lba_out_of_range(ctsio);
5531		ctl_done((union ctl_io *)ctsio);
5532		goto bailout;
5533	}
5534
5535	/*
5536	 * If this LUN has no backend, we can't flush the cache anyway.
5537	 */
5538	if (lun->backend == NULL) {
5539		ctl_set_invalid_opcode(ctsio);
5540		ctl_done((union ctl_io *)ctsio);
5541		goto bailout;
5542	}
5543
5544	/*
5545	 * Check to see whether we're configured to send the SYNCHRONIZE
5546	 * CACHE command directly to the back end.
5547	 */
5548	mtx_lock(&lun->lun_lock);
5549	if ((softc->flags & CTL_FLAG_REAL_SYNC)
5550	 && (++(lun->sync_count) >= lun->sync_interval)) {
5551		lun->sync_count = 0;
5552		mtx_unlock(&lun->lun_lock);
5553		retval = lun->backend->config_write((union ctl_io *)ctsio);
5554	} else {
5555		mtx_unlock(&lun->lun_lock);
5556		ctl_set_success(ctsio);
5557		ctl_done((union ctl_io *)ctsio);
5558	}
5559
5560bailout:
5561
5562	return (retval);
5563}
5564
5565int
5566ctl_format(struct ctl_scsiio *ctsio)
5567{
5568	struct scsi_format *cdb;
5569	struct ctl_lun *lun;
5570	int length, defect_list_len;
5571
5572	CTL_DEBUG_PRINT(("ctl_format\n"));
5573
5574	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5575
5576	cdb = (struct scsi_format *)ctsio->cdb;
5577
5578	length = 0;
5579	if (cdb->byte2 & SF_FMTDATA) {
5580		if (cdb->byte2 & SF_LONGLIST)
5581			length = sizeof(struct scsi_format_header_long);
5582		else
5583			length = sizeof(struct scsi_format_header_short);
5584	}
5585
5586	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5587	 && (length > 0)) {
5588		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5589		ctsio->kern_data_len = length;
5590		ctsio->kern_total_len = length;
5591		ctsio->kern_data_resid = 0;
5592		ctsio->kern_rel_offset = 0;
5593		ctsio->kern_sg_entries = 0;
5594		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5595		ctsio->be_move_done = ctl_config_move_done;
5596		ctl_datamove((union ctl_io *)ctsio);
5597
5598		return (CTL_RETVAL_COMPLETE);
5599	}
5600
5601	defect_list_len = 0;
5602
5603	if (cdb->byte2 & SF_FMTDATA) {
5604		if (cdb->byte2 & SF_LONGLIST) {
5605			struct scsi_format_header_long *header;
5606
5607			header = (struct scsi_format_header_long *)
5608				ctsio->kern_data_ptr;
5609
5610			defect_list_len = scsi_4btoul(header->defect_list_len);
5611			if (defect_list_len != 0) {
5612				ctl_set_invalid_field(ctsio,
5613						      /*sks_valid*/ 1,
5614						      /*command*/ 0,
5615						      /*field*/ 2,
5616						      /*bit_valid*/ 0,
5617						      /*bit*/ 0);
5618				goto bailout;
5619			}
5620		} else {
5621			struct scsi_format_header_short *header;
5622
5623			header = (struct scsi_format_header_short *)
5624				ctsio->kern_data_ptr;
5625
5626			defect_list_len = scsi_2btoul(header->defect_list_len);
5627			if (defect_list_len != 0) {
5628				ctl_set_invalid_field(ctsio,
5629						      /*sks_valid*/ 1,
5630						      /*command*/ 0,
5631						      /*field*/ 2,
5632						      /*bit_valid*/ 0,
5633						      /*bit*/ 0);
5634				goto bailout;
5635			}
5636		}
5637	}
5638
5639	/*
5640	 * The format command will clear out the "Medium format corrupted"
5641	 * status if set by the configuration code.  That status is really
5642	 * just a way to notify the host that we have lost the media, and
5643	 * get them to issue a command that will basically make them think
5644	 * they're blowing away the media.
5645	 */
5646	mtx_lock(&lun->lun_lock);
5647	lun->flags &= ~CTL_LUN_INOPERABLE;
5648	mtx_unlock(&lun->lun_lock);
5649
5650	ctl_set_success(ctsio);
5651bailout:
5652
5653	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5654		free(ctsio->kern_data_ptr, M_CTL);
5655		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5656	}
5657
5658	ctl_done((union ctl_io *)ctsio);
5659	return (CTL_RETVAL_COMPLETE);
5660}
5661
5662int
5663ctl_read_buffer(struct ctl_scsiio *ctsio)
5664{
5665	struct scsi_read_buffer *cdb;
5666	struct ctl_lun *lun;
5667	int buffer_offset, len;
5668	static uint8_t descr[4];
5669	static uint8_t echo_descr[4] = { 0 };
5670
5671	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5672
5673	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5674	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5675
5676	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5677	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5678	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5679		ctl_set_invalid_field(ctsio,
5680				      /*sks_valid*/ 1,
5681				      /*command*/ 1,
5682				      /*field*/ 1,
5683				      /*bit_valid*/ 1,
5684				      /*bit*/ 4);
5685		ctl_done((union ctl_io *)ctsio);
5686		return (CTL_RETVAL_COMPLETE);
5687	}
5688
5689	len = scsi_3btoul(cdb->length);
5690	buffer_offset = scsi_3btoul(cdb->offset);
5691
5692	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5693		ctl_set_invalid_field(ctsio,
5694				      /*sks_valid*/ 1,
5695				      /*command*/ 1,
5696				      /*field*/ 6,
5697				      /*bit_valid*/ 0,
5698				      /*bit*/ 0);
5699		ctl_done((union ctl_io *)ctsio);
5700		return (CTL_RETVAL_COMPLETE);
5701	}
5702
5703	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5704		descr[0] = 0;
5705		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5706		ctsio->kern_data_ptr = descr;
5707		len = min(len, sizeof(descr));
5708	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5709		ctsio->kern_data_ptr = echo_descr;
5710		len = min(len, sizeof(echo_descr));
5711	} else {
5712		if (lun->write_buffer == NULL) {
5713			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5714			    M_CTL, M_WAITOK);
5715		}
5716		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5717	}
5718	ctsio->kern_data_len = len;
5719	ctsio->kern_total_len = len;
5720	ctsio->kern_data_resid = 0;
5721	ctsio->kern_rel_offset = 0;
5722	ctsio->kern_sg_entries = 0;
5723	ctl_set_success(ctsio);
5724	ctsio->be_move_done = ctl_config_move_done;
5725	ctl_datamove((union ctl_io *)ctsio);
5726	return (CTL_RETVAL_COMPLETE);
5727}
5728
5729int
5730ctl_write_buffer(struct ctl_scsiio *ctsio)
5731{
5732	struct scsi_write_buffer *cdb;
5733	struct ctl_lun *lun;
5734	int buffer_offset, len;
5735
5736	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5737
5738	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5739	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5740
5741	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5742		ctl_set_invalid_field(ctsio,
5743				      /*sks_valid*/ 1,
5744				      /*command*/ 1,
5745				      /*field*/ 1,
5746				      /*bit_valid*/ 1,
5747				      /*bit*/ 4);
5748		ctl_done((union ctl_io *)ctsio);
5749		return (CTL_RETVAL_COMPLETE);
5750	}
5751
5752	len = scsi_3btoul(cdb->length);
5753	buffer_offset = scsi_3btoul(cdb->offset);
5754
5755	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5756		ctl_set_invalid_field(ctsio,
5757				      /*sks_valid*/ 1,
5758				      /*command*/ 1,
5759				      /*field*/ 6,
5760				      /*bit_valid*/ 0,
5761				      /*bit*/ 0);
5762		ctl_done((union ctl_io *)ctsio);
5763		return (CTL_RETVAL_COMPLETE);
5764	}
5765
5766	/*
5767	 * If we've got a kernel request that hasn't been malloced yet,
5768	 * malloc it and tell the caller the data buffer is here.
5769	 */
5770	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5771		if (lun->write_buffer == NULL) {
5772			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5773			    M_CTL, M_WAITOK);
5774		}
5775		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5776		ctsio->kern_data_len = len;
5777		ctsio->kern_total_len = len;
5778		ctsio->kern_data_resid = 0;
5779		ctsio->kern_rel_offset = 0;
5780		ctsio->kern_sg_entries = 0;
5781		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5782		ctsio->be_move_done = ctl_config_move_done;
5783		ctl_datamove((union ctl_io *)ctsio);
5784
5785		return (CTL_RETVAL_COMPLETE);
5786	}
5787
5788	ctl_set_success(ctsio);
5789	ctl_done((union ctl_io *)ctsio);
5790	return (CTL_RETVAL_COMPLETE);
5791}
5792
5793int
5794ctl_write_same(struct ctl_scsiio *ctsio)
5795{
5796	struct ctl_lun *lun;
5797	struct ctl_lba_len_flags *lbalen;
5798	uint64_t lba;
5799	uint32_t num_blocks;
5800	int len, retval;
5801	uint8_t byte2;
5802
5803	retval = CTL_RETVAL_COMPLETE;
5804
5805	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5806
5807	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5808
5809	switch (ctsio->cdb[0]) {
5810	case WRITE_SAME_10: {
5811		struct scsi_write_same_10 *cdb;
5812
5813		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5814
5815		lba = scsi_4btoul(cdb->addr);
5816		num_blocks = scsi_2btoul(cdb->length);
5817		byte2 = cdb->byte2;
5818		break;
5819	}
5820	case WRITE_SAME_16: {
5821		struct scsi_write_same_16 *cdb;
5822
5823		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5824
5825		lba = scsi_8btou64(cdb->addr);
5826		num_blocks = scsi_4btoul(cdb->length);
5827		byte2 = cdb->byte2;
5828		break;
5829	}
5830	default:
5831		/*
5832		 * We got a command we don't support.  This shouldn't
5833		 * happen, commands should be filtered out above us.
5834		 */
5835		ctl_set_invalid_opcode(ctsio);
5836		ctl_done((union ctl_io *)ctsio);
5837
5838		return (CTL_RETVAL_COMPLETE);
5839		break; /* NOTREACHED */
5840	}
5841
5842	/* NDOB and ANCHOR flags can be used only together with UNMAP */
5843	if ((byte2 & SWS_UNMAP) == 0 &&
5844	    (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5845		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5846		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5847		ctl_done((union ctl_io *)ctsio);
5848		return (CTL_RETVAL_COMPLETE);
5849	}
5850
5851	/*
5852	 * The first check is to make sure we're in bounds, the second
5853	 * check is to catch wrap-around problems.  If the lba + num blocks
5854	 * is less than the lba, then we've wrapped around and the block
5855	 * range is invalid anyway.
5856	 */
5857	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5858	 || ((lba + num_blocks) < lba)) {
5859		ctl_set_lba_out_of_range(ctsio);
5860		ctl_done((union ctl_io *)ctsio);
5861		return (CTL_RETVAL_COMPLETE);
5862	}
5863
5864	/* Zero number of blocks means "to the last logical block" */
5865	if (num_blocks == 0) {
5866		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5867			ctl_set_invalid_field(ctsio,
5868					      /*sks_valid*/ 0,
5869					      /*command*/ 1,
5870					      /*field*/ 0,
5871					      /*bit_valid*/ 0,
5872					      /*bit*/ 0);
5873			ctl_done((union ctl_io *)ctsio);
5874			return (CTL_RETVAL_COMPLETE);
5875		}
5876		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5877	}
5878
5879	len = lun->be_lun->blocksize;
5880
5881	/*
5882	 * If we've got a kernel request that hasn't been malloced yet,
5883	 * malloc it and tell the caller the data buffer is here.
5884	 */
5885	if ((byte2 & SWS_NDOB) == 0 &&
5886	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5887		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5888		ctsio->kern_data_len = len;
5889		ctsio->kern_total_len = len;
5890		ctsio->kern_data_resid = 0;
5891		ctsio->kern_rel_offset = 0;
5892		ctsio->kern_sg_entries = 0;
5893		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5894		ctsio->be_move_done = ctl_config_move_done;
5895		ctl_datamove((union ctl_io *)ctsio);
5896
5897		return (CTL_RETVAL_COMPLETE);
5898	}
5899
5900	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5901	lbalen->lba = lba;
5902	lbalen->len = num_blocks;
5903	lbalen->flags = byte2;
5904	retval = lun->backend->config_write((union ctl_io *)ctsio);
5905
5906	return (retval);
5907}
5908
5909int
5910ctl_unmap(struct ctl_scsiio *ctsio)
5911{
5912	struct ctl_lun *lun;
5913	struct scsi_unmap *cdb;
5914	struct ctl_ptr_len_flags *ptrlen;
5915	struct scsi_unmap_header *hdr;
5916	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5917	uint64_t lba;
5918	uint32_t num_blocks;
5919	int len, retval;
5920	uint8_t byte2;
5921
5922	retval = CTL_RETVAL_COMPLETE;
5923
5924	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5925
5926	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5927	cdb = (struct scsi_unmap *)ctsio->cdb;
5928
5929	len = scsi_2btoul(cdb->length);
5930	byte2 = cdb->byte2;
5931
5932	/*
5933	 * If we've got a kernel request that hasn't been malloced yet,
5934	 * malloc it and tell the caller the data buffer is here.
5935	 */
5936	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5937		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5938		ctsio->kern_data_len = len;
5939		ctsio->kern_total_len = len;
5940		ctsio->kern_data_resid = 0;
5941		ctsio->kern_rel_offset = 0;
5942		ctsio->kern_sg_entries = 0;
5943		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5944		ctsio->be_move_done = ctl_config_move_done;
5945		ctl_datamove((union ctl_io *)ctsio);
5946
5947		return (CTL_RETVAL_COMPLETE);
5948	}
5949
5950	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5951	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5952	if (len < sizeof (*hdr) ||
5953	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5954	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5955	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5956		ctl_set_invalid_field(ctsio,
5957				      /*sks_valid*/ 0,
5958				      /*command*/ 0,
5959				      /*field*/ 0,
5960				      /*bit_valid*/ 0,
5961				      /*bit*/ 0);
5962		goto done;
5963	}
5964	len = scsi_2btoul(hdr->desc_length);
5965	buf = (struct scsi_unmap_desc *)(hdr + 1);
5966	end = buf + len / sizeof(*buf);
5967
5968	endnz = buf;
5969	for (range = buf; range < end; range++) {
5970		lba = scsi_8btou64(range->lba);
5971		num_blocks = scsi_4btoul(range->length);
5972		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5973		 || ((lba + num_blocks) < lba)) {
5974			ctl_set_lba_out_of_range(ctsio);
5975			ctl_done((union ctl_io *)ctsio);
5976			return (CTL_RETVAL_COMPLETE);
5977		}
5978		if (num_blocks != 0)
5979			endnz = range + 1;
5980	}
5981
5982	/*
5983	 * Block backend can not handle zero last range.
5984	 * Filter it out and return if there is nothing left.
5985	 */
5986	len = (uint8_t *)endnz - (uint8_t *)buf;
5987	if (len == 0) {
5988		ctl_set_success(ctsio);
5989		goto done;
5990	}
5991
5992	mtx_lock(&lun->lun_lock);
5993	ptrlen = (struct ctl_ptr_len_flags *)
5994	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5995	ptrlen->ptr = (void *)buf;
5996	ptrlen->len = len;
5997	ptrlen->flags = byte2;
5998	ctl_check_blocked(lun);
5999	mtx_unlock(&lun->lun_lock);
6000
6001	retval = lun->backend->config_write((union ctl_io *)ctsio);
6002	return (retval);
6003
6004done:
6005	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
6006		free(ctsio->kern_data_ptr, M_CTL);
6007		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
6008	}
6009	ctl_done((union ctl_io *)ctsio);
6010	return (CTL_RETVAL_COMPLETE);
6011}
6012
6013/*
6014 * Note that this function currently doesn't actually do anything inside
6015 * CTL to enforce things if the DQue bit is turned on.
6016 *
6017 * Also note that this function can't be used in the default case, because
6018 * the DQue bit isn't set in the changeable mask for the control mode page
6019 * anyway.  This is just here as an example for how to implement a page
6020 * handler, and a placeholder in case we want to allow the user to turn
6021 * tagged queueing on and off.
6022 *
6023 * The D_SENSE bit handling is functional, however, and will turn
6024 * descriptor sense on and off for a given LUN.
6025 */
6026int
6027ctl_control_page_handler(struct ctl_scsiio *ctsio,
6028			 struct ctl_page_index *page_index, uint8_t *page_ptr)
6029{
6030	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6031	struct ctl_lun *lun;
6032	int set_ua;
6033	uint32_t initidx;
6034
6035	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6036	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6037	set_ua = 0;
6038
6039	user_cp = (struct scsi_control_page *)page_ptr;
6040	current_cp = (struct scsi_control_page *)
6041		(page_index->page_data + (page_index->page_len *
6042		CTL_PAGE_CURRENT));
6043	saved_cp = (struct scsi_control_page *)
6044		(page_index->page_data + (page_index->page_len *
6045		CTL_PAGE_SAVED));
6046
6047	mtx_lock(&lun->lun_lock);
6048	if (((current_cp->rlec & SCP_DSENSE) == 0)
6049	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6050		/*
6051		 * Descriptor sense is currently turned off and the user
6052		 * wants to turn it on.
6053		 */
6054		current_cp->rlec |= SCP_DSENSE;
6055		saved_cp->rlec |= SCP_DSENSE;
6056		lun->flags |= CTL_LUN_SENSE_DESC;
6057		set_ua = 1;
6058	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6059		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6060		/*
6061		 * Descriptor sense is currently turned on, and the user
6062		 * wants to turn it off.
6063		 */
6064		current_cp->rlec &= ~SCP_DSENSE;
6065		saved_cp->rlec &= ~SCP_DSENSE;
6066		lun->flags &= ~CTL_LUN_SENSE_DESC;
6067		set_ua = 1;
6068	}
6069	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6070	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6071		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6072		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6073		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6074		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6075		set_ua = 1;
6076	}
6077	if ((current_cp->eca_and_aen & SCP_SWP) !=
6078	    (user_cp->eca_and_aen & SCP_SWP)) {
6079		current_cp->eca_and_aen &= ~SCP_SWP;
6080		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6081		saved_cp->eca_and_aen &= ~SCP_SWP;
6082		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6083		set_ua = 1;
6084	}
6085	if (set_ua != 0)
6086		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6087	mtx_unlock(&lun->lun_lock);
6088
6089	return (0);
6090}
6091
6092int
6093ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6094		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6095{
6096	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6097	struct ctl_lun *lun;
6098	int set_ua;
6099	uint32_t initidx;
6100
6101	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6102	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6103	set_ua = 0;
6104
6105	user_cp = (struct scsi_caching_page *)page_ptr;
6106	current_cp = (struct scsi_caching_page *)
6107		(page_index->page_data + (page_index->page_len *
6108		CTL_PAGE_CURRENT));
6109	saved_cp = (struct scsi_caching_page *)
6110		(page_index->page_data + (page_index->page_len *
6111		CTL_PAGE_SAVED));
6112
6113	mtx_lock(&lun->lun_lock);
6114	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6115	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6116		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6117		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6118		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6119		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6120		set_ua = 1;
6121	}
6122	if (set_ua != 0)
6123		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6124	mtx_unlock(&lun->lun_lock);
6125
6126	return (0);
6127}
6128
6129int
6130ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6131				struct ctl_page_index *page_index,
6132				uint8_t *page_ptr)
6133{
6134	uint8_t *c;
6135	int i;
6136
6137	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6138	ctl_time_io_secs =
6139		(c[0] << 8) |
6140		(c[1] << 0) |
6141		0;
6142	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6143	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6144	printf("page data:");
6145	for (i=0; i<8; i++)
6146		printf(" %.2x",page_ptr[i]);
6147	printf("\n");
6148	return (0);
6149}
6150
6151int
6152ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6153			       struct ctl_page_index *page_index,
6154			       int pc)
6155{
6156	struct copan_debugconf_subpage *page;
6157
6158	page = (struct copan_debugconf_subpage *)page_index->page_data +
6159		(page_index->page_len * pc);
6160
6161	switch (pc) {
6162	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6163	case SMS_PAGE_CTRL_DEFAULT >> 6:
6164	case SMS_PAGE_CTRL_SAVED >> 6:
6165		/*
6166		 * We don't update the changable or default bits for this page.
6167		 */
6168		break;
6169	case SMS_PAGE_CTRL_CURRENT >> 6:
6170		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6171		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6172		break;
6173	default:
6174#ifdef NEEDTOPORT
6175		EPRINT(0, "Invalid PC %d!!", pc);
6176#endif /* NEEDTOPORT */
6177		break;
6178	}
6179	return (0);
6180}
6181
6182
6183static int
6184ctl_do_mode_select(union ctl_io *io)
6185{
6186	struct scsi_mode_page_header *page_header;
6187	struct ctl_page_index *page_index;
6188	struct ctl_scsiio *ctsio;
6189	int control_dev, page_len;
6190	int page_len_offset, page_len_size;
6191	union ctl_modepage_info *modepage_info;
6192	struct ctl_lun *lun;
6193	int *len_left, *len_used;
6194	int retval, i;
6195
6196	ctsio = &io->scsiio;
6197	page_index = NULL;
6198	page_len = 0;
6199	retval = CTL_RETVAL_COMPLETE;
6200
6201	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6202
6203	if (lun->be_lun->lun_type != T_DIRECT)
6204		control_dev = 1;
6205	else
6206		control_dev = 0;
6207
6208	modepage_info = (union ctl_modepage_info *)
6209		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6210	len_left = &modepage_info->header.len_left;
6211	len_used = &modepage_info->header.len_used;
6212
6213do_next_page:
6214
6215	page_header = (struct scsi_mode_page_header *)
6216		(ctsio->kern_data_ptr + *len_used);
6217
6218	if (*len_left == 0) {
6219		free(ctsio->kern_data_ptr, M_CTL);
6220		ctl_set_success(ctsio);
6221		ctl_done((union ctl_io *)ctsio);
6222		return (CTL_RETVAL_COMPLETE);
6223	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6224
6225		free(ctsio->kern_data_ptr, M_CTL);
6226		ctl_set_param_len_error(ctsio);
6227		ctl_done((union ctl_io *)ctsio);
6228		return (CTL_RETVAL_COMPLETE);
6229
6230	} else if ((page_header->page_code & SMPH_SPF)
6231		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6232
6233		free(ctsio->kern_data_ptr, M_CTL);
6234		ctl_set_param_len_error(ctsio);
6235		ctl_done((union ctl_io *)ctsio);
6236		return (CTL_RETVAL_COMPLETE);
6237	}
6238
6239
6240	/*
6241	 * XXX KDM should we do something with the block descriptor?
6242	 */
6243	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6244
6245		if ((control_dev != 0)
6246		 && (lun->mode_pages.index[i].page_flags &
6247		     CTL_PAGE_FLAG_DISK_ONLY))
6248			continue;
6249
6250		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6251		    (page_header->page_code & SMPH_PC_MASK))
6252			continue;
6253
6254		/*
6255		 * If neither page has a subpage code, then we've got a
6256		 * match.
6257		 */
6258		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6259		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6260			page_index = &lun->mode_pages.index[i];
6261			page_len = page_header->page_length;
6262			break;
6263		}
6264
6265		/*
6266		 * If both pages have subpages, then the subpage numbers
6267		 * have to match.
6268		 */
6269		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6270		  && (page_header->page_code & SMPH_SPF)) {
6271			struct scsi_mode_page_header_sp *sph;
6272
6273			sph = (struct scsi_mode_page_header_sp *)page_header;
6274
6275			if (lun->mode_pages.index[i].subpage ==
6276			    sph->subpage) {
6277				page_index = &lun->mode_pages.index[i];
6278				page_len = scsi_2btoul(sph->page_length);
6279				break;
6280			}
6281		}
6282	}
6283
6284	/*
6285	 * If we couldn't find the page, or if we don't have a mode select
6286	 * handler for it, send back an error to the user.
6287	 */
6288	if ((page_index == NULL)
6289	 || (page_index->select_handler == NULL)) {
6290		ctl_set_invalid_field(ctsio,
6291				      /*sks_valid*/ 1,
6292				      /*command*/ 0,
6293				      /*field*/ *len_used,
6294				      /*bit_valid*/ 0,
6295				      /*bit*/ 0);
6296		free(ctsio->kern_data_ptr, M_CTL);
6297		ctl_done((union ctl_io *)ctsio);
6298		return (CTL_RETVAL_COMPLETE);
6299	}
6300
6301	if (page_index->page_code & SMPH_SPF) {
6302		page_len_offset = 2;
6303		page_len_size = 2;
6304	} else {
6305		page_len_size = 1;
6306		page_len_offset = 1;
6307	}
6308
6309	/*
6310	 * If the length the initiator gives us isn't the one we specify in
6311	 * the mode page header, or if they didn't specify enough data in
6312	 * the CDB to avoid truncating this page, kick out the request.
6313	 */
6314	if ((page_len != (page_index->page_len - page_len_offset -
6315			  page_len_size))
6316	 || (*len_left < page_index->page_len)) {
6317
6318
6319		ctl_set_invalid_field(ctsio,
6320				      /*sks_valid*/ 1,
6321				      /*command*/ 0,
6322				      /*field*/ *len_used + page_len_offset,
6323				      /*bit_valid*/ 0,
6324				      /*bit*/ 0);
6325		free(ctsio->kern_data_ptr, M_CTL);
6326		ctl_done((union ctl_io *)ctsio);
6327		return (CTL_RETVAL_COMPLETE);
6328	}
6329
6330	/*
6331	 * Run through the mode page, checking to make sure that the bits
6332	 * the user changed are actually legal for him to change.
6333	 */
6334	for (i = 0; i < page_index->page_len; i++) {
6335		uint8_t *user_byte, *change_mask, *current_byte;
6336		int bad_bit;
6337		int j;
6338
6339		user_byte = (uint8_t *)page_header + i;
6340		change_mask = page_index->page_data +
6341			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6342		current_byte = page_index->page_data +
6343			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6344
6345		/*
6346		 * Check to see whether the user set any bits in this byte
6347		 * that he is not allowed to set.
6348		 */
6349		if ((*user_byte & ~(*change_mask)) ==
6350		    (*current_byte & ~(*change_mask)))
6351			continue;
6352
6353		/*
6354		 * Go through bit by bit to determine which one is illegal.
6355		 */
6356		bad_bit = 0;
6357		for (j = 7; j >= 0; j--) {
6358			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6359			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6360				bad_bit = i;
6361				break;
6362			}
6363		}
6364		ctl_set_invalid_field(ctsio,
6365				      /*sks_valid*/ 1,
6366				      /*command*/ 0,
6367				      /*field*/ *len_used + i,
6368				      /*bit_valid*/ 1,
6369				      /*bit*/ bad_bit);
6370		free(ctsio->kern_data_ptr, M_CTL);
6371		ctl_done((union ctl_io *)ctsio);
6372		return (CTL_RETVAL_COMPLETE);
6373	}
6374
6375	/*
6376	 * Decrement these before we call the page handler, since we may
6377	 * end up getting called back one way or another before the handler
6378	 * returns to this context.
6379	 */
6380	*len_left -= page_index->page_len;
6381	*len_used += page_index->page_len;
6382
6383	retval = page_index->select_handler(ctsio, page_index,
6384					    (uint8_t *)page_header);
6385
6386	/*
6387	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6388	 * wait until this queued command completes to finish processing
6389	 * the mode page.  If it returns anything other than
6390	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6391	 * already set the sense information, freed the data pointer, and
6392	 * completed the io for us.
6393	 */
6394	if (retval != CTL_RETVAL_COMPLETE)
6395		goto bailout_no_done;
6396
6397	/*
6398	 * If the initiator sent us more than one page, parse the next one.
6399	 */
6400	if (*len_left > 0)
6401		goto do_next_page;
6402
6403	ctl_set_success(ctsio);
6404	free(ctsio->kern_data_ptr, M_CTL);
6405	ctl_done((union ctl_io *)ctsio);
6406
6407bailout_no_done:
6408
6409	return (CTL_RETVAL_COMPLETE);
6410
6411}
6412
6413int
6414ctl_mode_select(struct ctl_scsiio *ctsio)
6415{
6416	int param_len, pf, sp;
6417	int header_size, bd_len;
6418	int len_left, len_used;
6419	struct ctl_page_index *page_index;
6420	struct ctl_lun *lun;
6421	int control_dev, page_len;
6422	union ctl_modepage_info *modepage_info;
6423	int retval;
6424
6425	pf = 0;
6426	sp = 0;
6427	page_len = 0;
6428	len_used = 0;
6429	len_left = 0;
6430	retval = 0;
6431	bd_len = 0;
6432	page_index = NULL;
6433
6434	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6435
6436	if (lun->be_lun->lun_type != T_DIRECT)
6437		control_dev = 1;
6438	else
6439		control_dev = 0;
6440
6441	switch (ctsio->cdb[0]) {
6442	case MODE_SELECT_6: {
6443		struct scsi_mode_select_6 *cdb;
6444
6445		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6446
6447		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6448		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6449
6450		param_len = cdb->length;
6451		header_size = sizeof(struct scsi_mode_header_6);
6452		break;
6453	}
6454	case MODE_SELECT_10: {
6455		struct scsi_mode_select_10 *cdb;
6456
6457		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6458
6459		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6460		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6461
6462		param_len = scsi_2btoul(cdb->length);
6463		header_size = sizeof(struct scsi_mode_header_10);
6464		break;
6465	}
6466	default:
6467		ctl_set_invalid_opcode(ctsio);
6468		ctl_done((union ctl_io *)ctsio);
6469		return (CTL_RETVAL_COMPLETE);
6470		break; /* NOTREACHED */
6471	}
6472
6473	/*
6474	 * From SPC-3:
6475	 * "A parameter list length of zero indicates that the Data-Out Buffer
6476	 * shall be empty. This condition shall not be considered as an error."
6477	 */
6478	if (param_len == 0) {
6479		ctl_set_success(ctsio);
6480		ctl_done((union ctl_io *)ctsio);
6481		return (CTL_RETVAL_COMPLETE);
6482	}
6483
6484	/*
6485	 * Since we'll hit this the first time through, prior to
6486	 * allocation, we don't need to free a data buffer here.
6487	 */
6488	if (param_len < header_size) {
6489		ctl_set_param_len_error(ctsio);
6490		ctl_done((union ctl_io *)ctsio);
6491		return (CTL_RETVAL_COMPLETE);
6492	}
6493
6494	/*
6495	 * Allocate the data buffer and grab the user's data.  In theory,
6496	 * we shouldn't have to sanity check the parameter list length here
6497	 * because the maximum size is 64K.  We should be able to malloc
6498	 * that much without too many problems.
6499	 */
6500	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6501		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6502		ctsio->kern_data_len = param_len;
6503		ctsio->kern_total_len = param_len;
6504		ctsio->kern_data_resid = 0;
6505		ctsio->kern_rel_offset = 0;
6506		ctsio->kern_sg_entries = 0;
6507		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6508		ctsio->be_move_done = ctl_config_move_done;
6509		ctl_datamove((union ctl_io *)ctsio);
6510
6511		return (CTL_RETVAL_COMPLETE);
6512	}
6513
6514	switch (ctsio->cdb[0]) {
6515	case MODE_SELECT_6: {
6516		struct scsi_mode_header_6 *mh6;
6517
6518		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6519		bd_len = mh6->blk_desc_len;
6520		break;
6521	}
6522	case MODE_SELECT_10: {
6523		struct scsi_mode_header_10 *mh10;
6524
6525		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6526		bd_len = scsi_2btoul(mh10->blk_desc_len);
6527		break;
6528	}
6529	default:
6530		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6531		break;
6532	}
6533
6534	if (param_len < (header_size + bd_len)) {
6535		free(ctsio->kern_data_ptr, M_CTL);
6536		ctl_set_param_len_error(ctsio);
6537		ctl_done((union ctl_io *)ctsio);
6538		return (CTL_RETVAL_COMPLETE);
6539	}
6540
6541	/*
6542	 * Set the IO_CONT flag, so that if this I/O gets passed to
6543	 * ctl_config_write_done(), it'll get passed back to
6544	 * ctl_do_mode_select() for further processing, or completion if
6545	 * we're all done.
6546	 */
6547	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6548	ctsio->io_cont = ctl_do_mode_select;
6549
6550	modepage_info = (union ctl_modepage_info *)
6551		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6552
6553	memset(modepage_info, 0, sizeof(*modepage_info));
6554
6555	len_left = param_len - header_size - bd_len;
6556	len_used = header_size + bd_len;
6557
6558	modepage_info->header.len_left = len_left;
6559	modepage_info->header.len_used = len_used;
6560
6561	return (ctl_do_mode_select((union ctl_io *)ctsio));
6562}
6563
6564int
6565ctl_mode_sense(struct ctl_scsiio *ctsio)
6566{
6567	struct ctl_lun *lun;
6568	int pc, page_code, dbd, llba, subpage;
6569	int alloc_len, page_len, header_len, total_len;
6570	struct scsi_mode_block_descr *block_desc;
6571	struct ctl_page_index *page_index;
6572	int control_dev;
6573
6574	dbd = 0;
6575	llba = 0;
6576	block_desc = NULL;
6577	page_index = NULL;
6578
6579	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6580
6581	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6582
6583	if (lun->be_lun->lun_type != T_DIRECT)
6584		control_dev = 1;
6585	else
6586		control_dev = 0;
6587
6588	switch (ctsio->cdb[0]) {
6589	case MODE_SENSE_6: {
6590		struct scsi_mode_sense_6 *cdb;
6591
6592		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6593
6594		header_len = sizeof(struct scsi_mode_hdr_6);
6595		if (cdb->byte2 & SMS_DBD)
6596			dbd = 1;
6597		else
6598			header_len += sizeof(struct scsi_mode_block_descr);
6599
6600		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6601		page_code = cdb->page & SMS_PAGE_CODE;
6602		subpage = cdb->subpage;
6603		alloc_len = cdb->length;
6604		break;
6605	}
6606	case MODE_SENSE_10: {
6607		struct scsi_mode_sense_10 *cdb;
6608
6609		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6610
6611		header_len = sizeof(struct scsi_mode_hdr_10);
6612
6613		if (cdb->byte2 & SMS_DBD)
6614			dbd = 1;
6615		else
6616			header_len += sizeof(struct scsi_mode_block_descr);
6617		if (cdb->byte2 & SMS10_LLBAA)
6618			llba = 1;
6619		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6620		page_code = cdb->page & SMS_PAGE_CODE;
6621		subpage = cdb->subpage;
6622		alloc_len = scsi_2btoul(cdb->length);
6623		break;
6624	}
6625	default:
6626		ctl_set_invalid_opcode(ctsio);
6627		ctl_done((union ctl_io *)ctsio);
6628		return (CTL_RETVAL_COMPLETE);
6629		break; /* NOTREACHED */
6630	}
6631
6632	/*
6633	 * We have to make a first pass through to calculate the size of
6634	 * the pages that match the user's query.  Then we allocate enough
6635	 * memory to hold it, and actually copy the data into the buffer.
6636	 */
6637	switch (page_code) {
6638	case SMS_ALL_PAGES_PAGE: {
6639		int i;
6640
6641		page_len = 0;
6642
6643		/*
6644		 * At the moment, values other than 0 and 0xff here are
6645		 * reserved according to SPC-3.
6646		 */
6647		if ((subpage != SMS_SUBPAGE_PAGE_0)
6648		 && (subpage != SMS_SUBPAGE_ALL)) {
6649			ctl_set_invalid_field(ctsio,
6650					      /*sks_valid*/ 1,
6651					      /*command*/ 1,
6652					      /*field*/ 3,
6653					      /*bit_valid*/ 0,
6654					      /*bit*/ 0);
6655			ctl_done((union ctl_io *)ctsio);
6656			return (CTL_RETVAL_COMPLETE);
6657		}
6658
6659		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6660			if ((control_dev != 0)
6661			 && (lun->mode_pages.index[i].page_flags &
6662			     CTL_PAGE_FLAG_DISK_ONLY))
6663				continue;
6664
6665			/*
6666			 * We don't use this subpage if the user didn't
6667			 * request all subpages.
6668			 */
6669			if ((lun->mode_pages.index[i].subpage != 0)
6670			 && (subpage == SMS_SUBPAGE_PAGE_0))
6671				continue;
6672
6673#if 0
6674			printf("found page %#x len %d\n",
6675			       lun->mode_pages.index[i].page_code &
6676			       SMPH_PC_MASK,
6677			       lun->mode_pages.index[i].page_len);
6678#endif
6679			page_len += lun->mode_pages.index[i].page_len;
6680		}
6681		break;
6682	}
6683	default: {
6684		int i;
6685
6686		page_len = 0;
6687
6688		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6689			/* Look for the right page code */
6690			if ((lun->mode_pages.index[i].page_code &
6691			     SMPH_PC_MASK) != page_code)
6692				continue;
6693
6694			/* Look for the right subpage or the subpage wildcard*/
6695			if ((lun->mode_pages.index[i].subpage != subpage)
6696			 && (subpage != SMS_SUBPAGE_ALL))
6697				continue;
6698
6699			/* Make sure the page is supported for this dev type */
6700			if ((control_dev != 0)
6701			 && (lun->mode_pages.index[i].page_flags &
6702			     CTL_PAGE_FLAG_DISK_ONLY))
6703				continue;
6704
6705#if 0
6706			printf("found page %#x len %d\n",
6707			       lun->mode_pages.index[i].page_code &
6708			       SMPH_PC_MASK,
6709			       lun->mode_pages.index[i].page_len);
6710#endif
6711
6712			page_len += lun->mode_pages.index[i].page_len;
6713		}
6714
6715		if (page_len == 0) {
6716			ctl_set_invalid_field(ctsio,
6717					      /*sks_valid*/ 1,
6718					      /*command*/ 1,
6719					      /*field*/ 2,
6720					      /*bit_valid*/ 1,
6721					      /*bit*/ 5);
6722			ctl_done((union ctl_io *)ctsio);
6723			return (CTL_RETVAL_COMPLETE);
6724		}
6725		break;
6726	}
6727	}
6728
6729	total_len = header_len + page_len;
6730#if 0
6731	printf("header_len = %d, page_len = %d, total_len = %d\n",
6732	       header_len, page_len, total_len);
6733#endif
6734
6735	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6736	ctsio->kern_sg_entries = 0;
6737	ctsio->kern_data_resid = 0;
6738	ctsio->kern_rel_offset = 0;
6739	if (total_len < alloc_len) {
6740		ctsio->residual = alloc_len - total_len;
6741		ctsio->kern_data_len = total_len;
6742		ctsio->kern_total_len = total_len;
6743	} else {
6744		ctsio->residual = 0;
6745		ctsio->kern_data_len = alloc_len;
6746		ctsio->kern_total_len = alloc_len;
6747	}
6748
6749	switch (ctsio->cdb[0]) {
6750	case MODE_SENSE_6: {
6751		struct scsi_mode_hdr_6 *header;
6752
6753		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6754
6755		header->datalen = MIN(total_len - 1, 254);
6756		if (control_dev == 0) {
6757			header->dev_specific = 0x10; /* DPOFUA */
6758			if ((lun->flags & CTL_LUN_READONLY) ||
6759			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6760			    .eca_and_aen & SCP_SWP) != 0)
6761				    header->dev_specific |= 0x80; /* WP */
6762		}
6763		if (dbd)
6764			header->block_descr_len = 0;
6765		else
6766			header->block_descr_len =
6767				sizeof(struct scsi_mode_block_descr);
6768		block_desc = (struct scsi_mode_block_descr *)&header[1];
6769		break;
6770	}
6771	case MODE_SENSE_10: {
6772		struct scsi_mode_hdr_10 *header;
6773		int datalen;
6774
6775		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6776
6777		datalen = MIN(total_len - 2, 65533);
6778		scsi_ulto2b(datalen, header->datalen);
6779		if (control_dev == 0) {
6780			header->dev_specific = 0x10; /* DPOFUA */
6781			if ((lun->flags & CTL_LUN_READONLY) ||
6782			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6783			    .eca_and_aen & SCP_SWP) != 0)
6784				    header->dev_specific |= 0x80; /* WP */
6785		}
6786		if (dbd)
6787			scsi_ulto2b(0, header->block_descr_len);
6788		else
6789			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6790				    header->block_descr_len);
6791		block_desc = (struct scsi_mode_block_descr *)&header[1];
6792		break;
6793	}
6794	default:
6795		panic("invalid CDB type %#x", ctsio->cdb[0]);
6796		break; /* NOTREACHED */
6797	}
6798
6799	/*
6800	 * If we've got a disk, use its blocksize in the block
6801	 * descriptor.  Otherwise, just set it to 0.
6802	 */
6803	if (dbd == 0) {
6804		if (control_dev == 0)
6805			scsi_ulto3b(lun->be_lun->blocksize,
6806				    block_desc->block_len);
6807		else
6808			scsi_ulto3b(0, block_desc->block_len);
6809	}
6810
6811	switch (page_code) {
6812	case SMS_ALL_PAGES_PAGE: {
6813		int i, data_used;
6814
6815		data_used = header_len;
6816		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6817			struct ctl_page_index *page_index;
6818
6819			page_index = &lun->mode_pages.index[i];
6820
6821			if ((control_dev != 0)
6822			 && (page_index->page_flags &
6823			    CTL_PAGE_FLAG_DISK_ONLY))
6824				continue;
6825
6826			/*
6827			 * We don't use this subpage if the user didn't
6828			 * request all subpages.  We already checked (above)
6829			 * to make sure the user only specified a subpage
6830			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6831			 */
6832			if ((page_index->subpage != 0)
6833			 && (subpage == SMS_SUBPAGE_PAGE_0))
6834				continue;
6835
6836			/*
6837			 * Call the handler, if it exists, to update the
6838			 * page to the latest values.
6839			 */
6840			if (page_index->sense_handler != NULL)
6841				page_index->sense_handler(ctsio, page_index,pc);
6842
6843			memcpy(ctsio->kern_data_ptr + data_used,
6844			       page_index->page_data +
6845			       (page_index->page_len * pc),
6846			       page_index->page_len);
6847			data_used += page_index->page_len;
6848		}
6849		break;
6850	}
6851	default: {
6852		int i, data_used;
6853
6854		data_used = header_len;
6855
6856		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6857			struct ctl_page_index *page_index;
6858
6859			page_index = &lun->mode_pages.index[i];
6860
6861			/* Look for the right page code */
6862			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6863				continue;
6864
6865			/* Look for the right subpage or the subpage wildcard*/
6866			if ((page_index->subpage != subpage)
6867			 && (subpage != SMS_SUBPAGE_ALL))
6868				continue;
6869
6870			/* Make sure the page is supported for this dev type */
6871			if ((control_dev != 0)
6872			 && (page_index->page_flags &
6873			     CTL_PAGE_FLAG_DISK_ONLY))
6874				continue;
6875
6876			/*
6877			 * Call the handler, if it exists, to update the
6878			 * page to the latest values.
6879			 */
6880			if (page_index->sense_handler != NULL)
6881				page_index->sense_handler(ctsio, page_index,pc);
6882
6883			memcpy(ctsio->kern_data_ptr + data_used,
6884			       page_index->page_data +
6885			       (page_index->page_len * pc),
6886			       page_index->page_len);
6887			data_used += page_index->page_len;
6888		}
6889		break;
6890	}
6891	}
6892
6893	ctl_set_success(ctsio);
6894	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6895	ctsio->be_move_done = ctl_config_move_done;
6896	ctl_datamove((union ctl_io *)ctsio);
6897	return (CTL_RETVAL_COMPLETE);
6898}
6899
6900int
6901ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6902			       struct ctl_page_index *page_index,
6903			       int pc)
6904{
6905	struct ctl_lun *lun;
6906	struct scsi_log_param_header *phdr;
6907	uint8_t *data;
6908	uint64_t val;
6909
6910	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6911	data = page_index->page_data;
6912
6913	if (lun->backend->lun_attr != NULL &&
6914	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6915	     != UINT64_MAX) {
6916		phdr = (struct scsi_log_param_header *)data;
6917		scsi_ulto2b(0x0001, phdr->param_code);
6918		phdr->param_control = SLP_LBIN | SLP_LP;
6919		phdr->param_len = 8;
6920		data = (uint8_t *)(phdr + 1);
6921		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6922		data[4] = 0x02; /* per-pool */
6923		data += phdr->param_len;
6924	}
6925
6926	if (lun->backend->lun_attr != NULL &&
6927	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6928	     != UINT64_MAX) {
6929		phdr = (struct scsi_log_param_header *)data;
6930		scsi_ulto2b(0x0002, phdr->param_code);
6931		phdr->param_control = SLP_LBIN | SLP_LP;
6932		phdr->param_len = 8;
6933		data = (uint8_t *)(phdr + 1);
6934		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6935		data[4] = 0x01; /* per-LUN */
6936		data += phdr->param_len;
6937	}
6938
6939	if (lun->backend->lun_attr != NULL &&
6940	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6941	     != UINT64_MAX) {
6942		phdr = (struct scsi_log_param_header *)data;
6943		scsi_ulto2b(0x00f1, phdr->param_code);
6944		phdr->param_control = SLP_LBIN | SLP_LP;
6945		phdr->param_len = 8;
6946		data = (uint8_t *)(phdr + 1);
6947		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6948		data[4] = 0x02; /* per-pool */
6949		data += phdr->param_len;
6950	}
6951
6952	if (lun->backend->lun_attr != NULL &&
6953	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6954	     != UINT64_MAX) {
6955		phdr = (struct scsi_log_param_header *)data;
6956		scsi_ulto2b(0x00f2, phdr->param_code);
6957		phdr->param_control = SLP_LBIN | SLP_LP;
6958		phdr->param_len = 8;
6959		data = (uint8_t *)(phdr + 1);
6960		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6961		data[4] = 0x02; /* per-pool */
6962		data += phdr->param_len;
6963	}
6964
6965	page_index->page_len = data - page_index->page_data;
6966	return (0);
6967}
6968
6969int
6970ctl_log_sense(struct ctl_scsiio *ctsio)
6971{
6972	struct ctl_lun *lun;
6973	int i, pc, page_code, subpage;
6974	int alloc_len, total_len;
6975	struct ctl_page_index *page_index;
6976	struct scsi_log_sense *cdb;
6977	struct scsi_log_header *header;
6978
6979	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6980
6981	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6982	cdb = (struct scsi_log_sense *)ctsio->cdb;
6983	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6984	page_code = cdb->page & SLS_PAGE_CODE;
6985	subpage = cdb->subpage;
6986	alloc_len = scsi_2btoul(cdb->length);
6987
6988	page_index = NULL;
6989	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6990		page_index = &lun->log_pages.index[i];
6991
6992		/* Look for the right page code */
6993		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6994			continue;
6995
6996		/* Look for the right subpage or the subpage wildcard*/
6997		if (page_index->subpage != subpage)
6998			continue;
6999
7000		break;
7001	}
7002	if (i >= CTL_NUM_LOG_PAGES) {
7003		ctl_set_invalid_field(ctsio,
7004				      /*sks_valid*/ 1,
7005				      /*command*/ 1,
7006				      /*field*/ 2,
7007				      /*bit_valid*/ 0,
7008				      /*bit*/ 0);
7009		ctl_done((union ctl_io *)ctsio);
7010		return (CTL_RETVAL_COMPLETE);
7011	}
7012
7013	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
7014
7015	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7016	ctsio->kern_sg_entries = 0;
7017	ctsio->kern_data_resid = 0;
7018	ctsio->kern_rel_offset = 0;
7019	if (total_len < alloc_len) {
7020		ctsio->residual = alloc_len - total_len;
7021		ctsio->kern_data_len = total_len;
7022		ctsio->kern_total_len = total_len;
7023	} else {
7024		ctsio->residual = 0;
7025		ctsio->kern_data_len = alloc_len;
7026		ctsio->kern_total_len = alloc_len;
7027	}
7028
7029	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7030	header->page = page_index->page_code;
7031	if (page_index->subpage) {
7032		header->page |= SL_SPF;
7033		header->subpage = page_index->subpage;
7034	}
7035	scsi_ulto2b(page_index->page_len, header->datalen);
7036
7037	/*
7038	 * Call the handler, if it exists, to update the
7039	 * page to the latest values.
7040	 */
7041	if (page_index->sense_handler != NULL)
7042		page_index->sense_handler(ctsio, page_index, pc);
7043
7044	memcpy(header + 1, page_index->page_data, page_index->page_len);
7045
7046	ctl_set_success(ctsio);
7047	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7048	ctsio->be_move_done = ctl_config_move_done;
7049	ctl_datamove((union ctl_io *)ctsio);
7050	return (CTL_RETVAL_COMPLETE);
7051}
7052
7053int
7054ctl_read_capacity(struct ctl_scsiio *ctsio)
7055{
7056	struct scsi_read_capacity *cdb;
7057	struct scsi_read_capacity_data *data;
7058	struct ctl_lun *lun;
7059	uint32_t lba;
7060
7061	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7062
7063	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7064
7065	lba = scsi_4btoul(cdb->addr);
7066	if (((cdb->pmi & SRC_PMI) == 0)
7067	 && (lba != 0)) {
7068		ctl_set_invalid_field(/*ctsio*/ ctsio,
7069				      /*sks_valid*/ 1,
7070				      /*command*/ 1,
7071				      /*field*/ 2,
7072				      /*bit_valid*/ 0,
7073				      /*bit*/ 0);
7074		ctl_done((union ctl_io *)ctsio);
7075		return (CTL_RETVAL_COMPLETE);
7076	}
7077
7078	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7079
7080	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7081	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7082	ctsio->residual = 0;
7083	ctsio->kern_data_len = sizeof(*data);
7084	ctsio->kern_total_len = sizeof(*data);
7085	ctsio->kern_data_resid = 0;
7086	ctsio->kern_rel_offset = 0;
7087	ctsio->kern_sg_entries = 0;
7088
7089	/*
7090	 * If the maximum LBA is greater than 0xfffffffe, the user must
7091	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7092	 * serivce action set.
7093	 */
7094	if (lun->be_lun->maxlba > 0xfffffffe)
7095		scsi_ulto4b(0xffffffff, data->addr);
7096	else
7097		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7098
7099	/*
7100	 * XXX KDM this may not be 512 bytes...
7101	 */
7102	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7103
7104	ctl_set_success(ctsio);
7105	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7106	ctsio->be_move_done = ctl_config_move_done;
7107	ctl_datamove((union ctl_io *)ctsio);
7108	return (CTL_RETVAL_COMPLETE);
7109}
7110
7111int
7112ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7113{
7114	struct scsi_read_capacity_16 *cdb;
7115	struct scsi_read_capacity_data_long *data;
7116	struct ctl_lun *lun;
7117	uint64_t lba;
7118	uint32_t alloc_len;
7119
7120	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7121
7122	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7123
7124	alloc_len = scsi_4btoul(cdb->alloc_len);
7125	lba = scsi_8btou64(cdb->addr);
7126
7127	if ((cdb->reladr & SRC16_PMI)
7128	 && (lba != 0)) {
7129		ctl_set_invalid_field(/*ctsio*/ ctsio,
7130				      /*sks_valid*/ 1,
7131				      /*command*/ 1,
7132				      /*field*/ 2,
7133				      /*bit_valid*/ 0,
7134				      /*bit*/ 0);
7135		ctl_done((union ctl_io *)ctsio);
7136		return (CTL_RETVAL_COMPLETE);
7137	}
7138
7139	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7140
7141	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7142	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7143
7144	if (sizeof(*data) < alloc_len) {
7145		ctsio->residual = alloc_len - sizeof(*data);
7146		ctsio->kern_data_len = sizeof(*data);
7147		ctsio->kern_total_len = sizeof(*data);
7148	} else {
7149		ctsio->residual = 0;
7150		ctsio->kern_data_len = alloc_len;
7151		ctsio->kern_total_len = alloc_len;
7152	}
7153	ctsio->kern_data_resid = 0;
7154	ctsio->kern_rel_offset = 0;
7155	ctsio->kern_sg_entries = 0;
7156
7157	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7158	/* XXX KDM this may not be 512 bytes... */
7159	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7160	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7161	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7162	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7163		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7164
7165	ctl_set_success(ctsio);
7166	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7167	ctsio->be_move_done = ctl_config_move_done;
7168	ctl_datamove((union ctl_io *)ctsio);
7169	return (CTL_RETVAL_COMPLETE);
7170}
7171
7172int
7173ctl_get_lba_status(struct ctl_scsiio *ctsio)
7174{
7175	struct scsi_get_lba_status *cdb;
7176	struct scsi_get_lba_status_data *data;
7177	struct ctl_lun *lun;
7178	struct ctl_lba_len_flags *lbalen;
7179	uint64_t lba;
7180	uint32_t alloc_len, total_len;
7181	int retval;
7182
7183	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7184
7185	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7186	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7187	lba = scsi_8btou64(cdb->addr);
7188	alloc_len = scsi_4btoul(cdb->alloc_len);
7189
7190	if (lba > lun->be_lun->maxlba) {
7191		ctl_set_lba_out_of_range(ctsio);
7192		ctl_done((union ctl_io *)ctsio);
7193		return (CTL_RETVAL_COMPLETE);
7194	}
7195
7196	total_len = sizeof(*data) + sizeof(data->descr[0]);
7197	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7198	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7199
7200	if (total_len < alloc_len) {
7201		ctsio->residual = alloc_len - total_len;
7202		ctsio->kern_data_len = total_len;
7203		ctsio->kern_total_len = total_len;
7204	} else {
7205		ctsio->residual = 0;
7206		ctsio->kern_data_len = alloc_len;
7207		ctsio->kern_total_len = alloc_len;
7208	}
7209	ctsio->kern_data_resid = 0;
7210	ctsio->kern_rel_offset = 0;
7211	ctsio->kern_sg_entries = 0;
7212
7213	/* Fill dummy data in case backend can't tell anything. */
7214	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7215	scsi_u64to8b(lba, data->descr[0].addr);
7216	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7217	    data->descr[0].length);
7218	data->descr[0].status = 0; /* Mapped or unknown. */
7219
7220	ctl_set_success(ctsio);
7221	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7222	ctsio->be_move_done = ctl_config_move_done;
7223
7224	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7225	lbalen->lba = lba;
7226	lbalen->len = total_len;
7227	lbalen->flags = 0;
7228	retval = lun->backend->config_read((union ctl_io *)ctsio);
7229	return (CTL_RETVAL_COMPLETE);
7230}
7231
7232int
7233ctl_read_defect(struct ctl_scsiio *ctsio)
7234{
7235	struct scsi_read_defect_data_10 *ccb10;
7236	struct scsi_read_defect_data_12 *ccb12;
7237	struct scsi_read_defect_data_hdr_10 *data10;
7238	struct scsi_read_defect_data_hdr_12 *data12;
7239	uint32_t alloc_len, data_len;
7240	uint8_t format;
7241
7242	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7243
7244	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7245		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7246		format = ccb10->format;
7247		alloc_len = scsi_2btoul(ccb10->alloc_length);
7248		data_len = sizeof(*data10);
7249	} else {
7250		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7251		format = ccb12->format;
7252		alloc_len = scsi_4btoul(ccb12->alloc_length);
7253		data_len = sizeof(*data12);
7254	}
7255	if (alloc_len == 0) {
7256		ctl_set_success(ctsio);
7257		ctl_done((union ctl_io *)ctsio);
7258		return (CTL_RETVAL_COMPLETE);
7259	}
7260
7261	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7262	if (data_len < alloc_len) {
7263		ctsio->residual = alloc_len - data_len;
7264		ctsio->kern_data_len = data_len;
7265		ctsio->kern_total_len = data_len;
7266	} else {
7267		ctsio->residual = 0;
7268		ctsio->kern_data_len = alloc_len;
7269		ctsio->kern_total_len = alloc_len;
7270	}
7271	ctsio->kern_data_resid = 0;
7272	ctsio->kern_rel_offset = 0;
7273	ctsio->kern_sg_entries = 0;
7274
7275	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7276		data10 = (struct scsi_read_defect_data_hdr_10 *)
7277		    ctsio->kern_data_ptr;
7278		data10->format = format;
7279		scsi_ulto2b(0, data10->length);
7280	} else {
7281		data12 = (struct scsi_read_defect_data_hdr_12 *)
7282		    ctsio->kern_data_ptr;
7283		data12->format = format;
7284		scsi_ulto2b(0, data12->generation);
7285		scsi_ulto4b(0, data12->length);
7286	}
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_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7297{
7298	struct scsi_maintenance_in *cdb;
7299	int retval;
7300	int alloc_len, ext, total_len = 0, g, p, pc, pg, gs, os;
7301	int num_target_port_groups, num_target_ports;
7302	struct ctl_lun *lun;
7303	struct ctl_softc *softc;
7304	struct ctl_port *port;
7305	struct scsi_target_group_data *rtg_ptr;
7306	struct scsi_target_group_data_extended *rtg_ext_ptr;
7307	struct scsi_target_port_group_descriptor *tpg_desc;
7308
7309	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7310
7311	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7312	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7313	softc = lun->ctl_softc;
7314
7315	retval = CTL_RETVAL_COMPLETE;
7316
7317	switch (cdb->byte2 & STG_PDF_MASK) {
7318	case STG_PDF_LENGTH:
7319		ext = 0;
7320		break;
7321	case STG_PDF_EXTENDED:
7322		ext = 1;
7323		break;
7324	default:
7325		ctl_set_invalid_field(/*ctsio*/ ctsio,
7326				      /*sks_valid*/ 1,
7327				      /*command*/ 1,
7328				      /*field*/ 2,
7329				      /*bit_valid*/ 1,
7330				      /*bit*/ 5);
7331		ctl_done((union ctl_io *)ctsio);
7332		return(retval);
7333	}
7334
7335	if (softc->is_single)
7336		num_target_port_groups = 1;
7337	else
7338		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7339	num_target_ports = 0;
7340	mtx_lock(&softc->ctl_lock);
7341	STAILQ_FOREACH(port, &softc->port_list, links) {
7342		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7343			continue;
7344		if (ctl_map_lun_back(softc, port->targ_port, lun->lun) >=
7345		    CTL_MAX_LUNS)
7346			continue;
7347		num_target_ports++;
7348	}
7349	mtx_unlock(&softc->ctl_lock);
7350
7351	if (ext)
7352		total_len = sizeof(struct scsi_target_group_data_extended);
7353	else
7354		total_len = sizeof(struct scsi_target_group_data);
7355	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7356		num_target_port_groups +
7357	    sizeof(struct scsi_target_port_descriptor) *
7358		num_target_ports * num_target_port_groups;
7359
7360	alloc_len = scsi_4btoul(cdb->length);
7361
7362	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7363
7364	ctsio->kern_sg_entries = 0;
7365
7366	if (total_len < alloc_len) {
7367		ctsio->residual = alloc_len - total_len;
7368		ctsio->kern_data_len = total_len;
7369		ctsio->kern_total_len = total_len;
7370	} else {
7371		ctsio->residual = 0;
7372		ctsio->kern_data_len = alloc_len;
7373		ctsio->kern_total_len = alloc_len;
7374	}
7375	ctsio->kern_data_resid = 0;
7376	ctsio->kern_rel_offset = 0;
7377
7378	if (ext) {
7379		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7380		    ctsio->kern_data_ptr;
7381		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7382		rtg_ext_ptr->format_type = 0x10;
7383		rtg_ext_ptr->implicit_transition_time = 0;
7384		tpg_desc = &rtg_ext_ptr->groups[0];
7385	} else {
7386		rtg_ptr = (struct scsi_target_group_data *)
7387		    ctsio->kern_data_ptr;
7388		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7389		tpg_desc = &rtg_ptr->groups[0];
7390	}
7391
7392	mtx_lock(&softc->ctl_lock);
7393	pg = softc->port_offset / CTL_MAX_PORTS;
7394	if (softc->flags & CTL_FLAG_ACTIVE_SHELF) {
7395		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY) {
7396			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7397			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7398		} else if (lun->flags & CTL_LUN_PRIMARY_SC) {
7399			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7400			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7401		} else {
7402			gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7403			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7404		}
7405	} else {
7406		gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7407		os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7408	}
7409	for (g = 0; g < num_target_port_groups; g++) {
7410		tpg_desc->pref_state = (g == pg) ? gs : os;
7411		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP;
7412		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7413		tpg_desc->status = TPG_IMPLICIT;
7414		pc = 0;
7415		STAILQ_FOREACH(port, &softc->port_list, links) {
7416			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7417				continue;
7418			if (ctl_map_lun_back(softc, port->targ_port, lun->lun)
7419			    >= CTL_MAX_LUNS)
7420				continue;
7421			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7422			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7423			    relative_target_port_identifier);
7424			pc++;
7425		}
7426		tpg_desc->target_port_count = pc;
7427		tpg_desc = (struct scsi_target_port_group_descriptor *)
7428		    &tpg_desc->descriptors[pc];
7429	}
7430	mtx_unlock(&softc->ctl_lock);
7431
7432	ctl_set_success(ctsio);
7433	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7434	ctsio->be_move_done = ctl_config_move_done;
7435	ctl_datamove((union ctl_io *)ctsio);
7436	return(retval);
7437}
7438
7439int
7440ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7441{
7442	struct ctl_lun *lun;
7443	struct scsi_report_supported_opcodes *cdb;
7444	const struct ctl_cmd_entry *entry, *sentry;
7445	struct scsi_report_supported_opcodes_all *all;
7446	struct scsi_report_supported_opcodes_descr *descr;
7447	struct scsi_report_supported_opcodes_one *one;
7448	int retval;
7449	int alloc_len, total_len;
7450	int opcode, service_action, i, j, num;
7451
7452	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7453
7454	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7455	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7456
7457	retval = CTL_RETVAL_COMPLETE;
7458
7459	opcode = cdb->requested_opcode;
7460	service_action = scsi_2btoul(cdb->requested_service_action);
7461	switch (cdb->options & RSO_OPTIONS_MASK) {
7462	case RSO_OPTIONS_ALL:
7463		num = 0;
7464		for (i = 0; i < 256; i++) {
7465			entry = &ctl_cmd_table[i];
7466			if (entry->flags & CTL_CMD_FLAG_SA5) {
7467				for (j = 0; j < 32; j++) {
7468					sentry = &((const struct ctl_cmd_entry *)
7469					    entry->execute)[j];
7470					if (ctl_cmd_applicable(
7471					    lun->be_lun->lun_type, sentry))
7472						num++;
7473				}
7474			} else {
7475				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7476				    entry))
7477					num++;
7478			}
7479		}
7480		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7481		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7482		break;
7483	case RSO_OPTIONS_OC:
7484		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7485			ctl_set_invalid_field(/*ctsio*/ ctsio,
7486					      /*sks_valid*/ 1,
7487					      /*command*/ 1,
7488					      /*field*/ 2,
7489					      /*bit_valid*/ 1,
7490					      /*bit*/ 2);
7491			ctl_done((union ctl_io *)ctsio);
7492			return (CTL_RETVAL_COMPLETE);
7493		}
7494		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7495		break;
7496	case RSO_OPTIONS_OC_SA:
7497		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7498		    service_action >= 32) {
7499			ctl_set_invalid_field(/*ctsio*/ ctsio,
7500					      /*sks_valid*/ 1,
7501					      /*command*/ 1,
7502					      /*field*/ 2,
7503					      /*bit_valid*/ 1,
7504					      /*bit*/ 2);
7505			ctl_done((union ctl_io *)ctsio);
7506			return (CTL_RETVAL_COMPLETE);
7507		}
7508		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7509		break;
7510	default:
7511		ctl_set_invalid_field(/*ctsio*/ ctsio,
7512				      /*sks_valid*/ 1,
7513				      /*command*/ 1,
7514				      /*field*/ 2,
7515				      /*bit_valid*/ 1,
7516				      /*bit*/ 2);
7517		ctl_done((union ctl_io *)ctsio);
7518		return (CTL_RETVAL_COMPLETE);
7519	}
7520
7521	alloc_len = scsi_4btoul(cdb->length);
7522
7523	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7524
7525	ctsio->kern_sg_entries = 0;
7526
7527	if (total_len < alloc_len) {
7528		ctsio->residual = alloc_len - total_len;
7529		ctsio->kern_data_len = total_len;
7530		ctsio->kern_total_len = total_len;
7531	} else {
7532		ctsio->residual = 0;
7533		ctsio->kern_data_len = alloc_len;
7534		ctsio->kern_total_len = alloc_len;
7535	}
7536	ctsio->kern_data_resid = 0;
7537	ctsio->kern_rel_offset = 0;
7538
7539	switch (cdb->options & RSO_OPTIONS_MASK) {
7540	case RSO_OPTIONS_ALL:
7541		all = (struct scsi_report_supported_opcodes_all *)
7542		    ctsio->kern_data_ptr;
7543		num = 0;
7544		for (i = 0; i < 256; i++) {
7545			entry = &ctl_cmd_table[i];
7546			if (entry->flags & CTL_CMD_FLAG_SA5) {
7547				for (j = 0; j < 32; j++) {
7548					sentry = &((const struct ctl_cmd_entry *)
7549					    entry->execute)[j];
7550					if (!ctl_cmd_applicable(
7551					    lun->be_lun->lun_type, sentry))
7552						continue;
7553					descr = &all->descr[num++];
7554					descr->opcode = i;
7555					scsi_ulto2b(j, descr->service_action);
7556					descr->flags = RSO_SERVACTV;
7557					scsi_ulto2b(sentry->length,
7558					    descr->cdb_length);
7559				}
7560			} else {
7561				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7562				    entry))
7563					continue;
7564				descr = &all->descr[num++];
7565				descr->opcode = i;
7566				scsi_ulto2b(0, descr->service_action);
7567				descr->flags = 0;
7568				scsi_ulto2b(entry->length, descr->cdb_length);
7569			}
7570		}
7571		scsi_ulto4b(
7572		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7573		    all->length);
7574		break;
7575	case RSO_OPTIONS_OC:
7576		one = (struct scsi_report_supported_opcodes_one *)
7577		    ctsio->kern_data_ptr;
7578		entry = &ctl_cmd_table[opcode];
7579		goto fill_one;
7580	case RSO_OPTIONS_OC_SA:
7581		one = (struct scsi_report_supported_opcodes_one *)
7582		    ctsio->kern_data_ptr;
7583		entry = &ctl_cmd_table[opcode];
7584		entry = &((const struct ctl_cmd_entry *)
7585		    entry->execute)[service_action];
7586fill_one:
7587		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7588			one->support = 3;
7589			scsi_ulto2b(entry->length, one->cdb_length);
7590			one->cdb_usage[0] = opcode;
7591			memcpy(&one->cdb_usage[1], entry->usage,
7592			    entry->length - 1);
7593		} else
7594			one->support = 1;
7595		break;
7596	}
7597
7598	ctl_set_success(ctsio);
7599	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7600	ctsio->be_move_done = ctl_config_move_done;
7601	ctl_datamove((union ctl_io *)ctsio);
7602	return(retval);
7603}
7604
7605int
7606ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7607{
7608	struct scsi_report_supported_tmf *cdb;
7609	struct scsi_report_supported_tmf_data *data;
7610	int retval;
7611	int alloc_len, total_len;
7612
7613	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7614
7615	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7616
7617	retval = CTL_RETVAL_COMPLETE;
7618
7619	total_len = sizeof(struct scsi_report_supported_tmf_data);
7620	alloc_len = scsi_4btoul(cdb->length);
7621
7622	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7623
7624	ctsio->kern_sg_entries = 0;
7625
7626	if (total_len < alloc_len) {
7627		ctsio->residual = alloc_len - total_len;
7628		ctsio->kern_data_len = total_len;
7629		ctsio->kern_total_len = total_len;
7630	} else {
7631		ctsio->residual = 0;
7632		ctsio->kern_data_len = alloc_len;
7633		ctsio->kern_total_len = alloc_len;
7634	}
7635	ctsio->kern_data_resid = 0;
7636	ctsio->kern_rel_offset = 0;
7637
7638	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7639	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7640	data->byte2 |= RST_ITNRS;
7641
7642	ctl_set_success(ctsio);
7643	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7644	ctsio->be_move_done = ctl_config_move_done;
7645	ctl_datamove((union ctl_io *)ctsio);
7646	return (retval);
7647}
7648
7649int
7650ctl_report_timestamp(struct ctl_scsiio *ctsio)
7651{
7652	struct scsi_report_timestamp *cdb;
7653	struct scsi_report_timestamp_data *data;
7654	struct timeval tv;
7655	int64_t timestamp;
7656	int retval;
7657	int alloc_len, total_len;
7658
7659	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7660
7661	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7662
7663	retval = CTL_RETVAL_COMPLETE;
7664
7665	total_len = sizeof(struct scsi_report_timestamp_data);
7666	alloc_len = scsi_4btoul(cdb->length);
7667
7668	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7669
7670	ctsio->kern_sg_entries = 0;
7671
7672	if (total_len < alloc_len) {
7673		ctsio->residual = alloc_len - total_len;
7674		ctsio->kern_data_len = total_len;
7675		ctsio->kern_total_len = total_len;
7676	} else {
7677		ctsio->residual = 0;
7678		ctsio->kern_data_len = alloc_len;
7679		ctsio->kern_total_len = alloc_len;
7680	}
7681	ctsio->kern_data_resid = 0;
7682	ctsio->kern_rel_offset = 0;
7683
7684	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7685	scsi_ulto2b(sizeof(*data) - 2, data->length);
7686	data->origin = RTS_ORIG_OUTSIDE;
7687	getmicrotime(&tv);
7688	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7689	scsi_ulto4b(timestamp >> 16, data->timestamp);
7690	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7691
7692	ctl_set_success(ctsio);
7693	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7694	ctsio->be_move_done = ctl_config_move_done;
7695	ctl_datamove((union ctl_io *)ctsio);
7696	return (retval);
7697}
7698
7699int
7700ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7701{
7702	struct scsi_per_res_in *cdb;
7703	int alloc_len, total_len = 0;
7704	/* struct scsi_per_res_in_rsrv in_data; */
7705	struct ctl_lun *lun;
7706	struct ctl_softc *softc;
7707	uint64_t key;
7708
7709	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7710
7711	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7712
7713	alloc_len = scsi_2btoul(cdb->length);
7714
7715	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7716	softc = lun->ctl_softc;
7717
7718retry:
7719	mtx_lock(&lun->lun_lock);
7720	switch (cdb->action) {
7721	case SPRI_RK: /* read keys */
7722		total_len = sizeof(struct scsi_per_res_in_keys) +
7723			lun->pr_key_count *
7724			sizeof(struct scsi_per_res_key);
7725		break;
7726	case SPRI_RR: /* read reservation */
7727		if (lun->flags & CTL_LUN_PR_RESERVED)
7728			total_len = sizeof(struct scsi_per_res_in_rsrv);
7729		else
7730			total_len = sizeof(struct scsi_per_res_in_header);
7731		break;
7732	case SPRI_RC: /* report capabilities */
7733		total_len = sizeof(struct scsi_per_res_cap);
7734		break;
7735	case SPRI_RS: /* read full status */
7736		total_len = sizeof(struct scsi_per_res_in_header) +
7737		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7738		    lun->pr_key_count;
7739		break;
7740	default:
7741		panic("Invalid PR type %x", cdb->action);
7742	}
7743	mtx_unlock(&lun->lun_lock);
7744
7745	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7746
7747	if (total_len < alloc_len) {
7748		ctsio->residual = alloc_len - total_len;
7749		ctsio->kern_data_len = total_len;
7750		ctsio->kern_total_len = total_len;
7751	} else {
7752		ctsio->residual = 0;
7753		ctsio->kern_data_len = alloc_len;
7754		ctsio->kern_total_len = alloc_len;
7755	}
7756
7757	ctsio->kern_data_resid = 0;
7758	ctsio->kern_rel_offset = 0;
7759	ctsio->kern_sg_entries = 0;
7760
7761	mtx_lock(&lun->lun_lock);
7762	switch (cdb->action) {
7763	case SPRI_RK: { // read keys
7764        struct scsi_per_res_in_keys *res_keys;
7765		int i, key_count;
7766
7767		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7768
7769		/*
7770		 * We had to drop the lock to allocate our buffer, which
7771		 * leaves time for someone to come in with another
7772		 * persistent reservation.  (That is unlikely, though,
7773		 * since this should be the only persistent reservation
7774		 * command active right now.)
7775		 */
7776		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7777		    (lun->pr_key_count *
7778		     sizeof(struct scsi_per_res_key)))){
7779			mtx_unlock(&lun->lun_lock);
7780			free(ctsio->kern_data_ptr, M_CTL);
7781			printf("%s: reservation length changed, retrying\n",
7782			       __func__);
7783			goto retry;
7784		}
7785
7786		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7787
7788		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7789			     lun->pr_key_count, res_keys->header.length);
7790
7791		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7792			if ((key = ctl_get_prkey(lun, i)) == 0)
7793				continue;
7794
7795			/*
7796			 * We used lun->pr_key_count to calculate the
7797			 * size to allocate.  If it turns out the number of
7798			 * initiators with the registered flag set is
7799			 * larger than that (i.e. they haven't been kept in
7800			 * sync), we've got a problem.
7801			 */
7802			if (key_count >= lun->pr_key_count) {
7803#ifdef NEEDTOPORT
7804				csevent_log(CSC_CTL | CSC_SHELF_SW |
7805					    CTL_PR_ERROR,
7806					    csevent_LogType_Fault,
7807					    csevent_AlertLevel_Yellow,
7808					    csevent_FRU_ShelfController,
7809					    csevent_FRU_Firmware,
7810				        csevent_FRU_Unknown,
7811					    "registered keys %d >= key "
7812					    "count %d", key_count,
7813					    lun->pr_key_count);
7814#endif
7815				key_count++;
7816				continue;
7817			}
7818			scsi_u64to8b(key, res_keys->keys[key_count].key);
7819			key_count++;
7820		}
7821		break;
7822	}
7823	case SPRI_RR: { // read reservation
7824		struct scsi_per_res_in_rsrv *res;
7825		int tmp_len, header_only;
7826
7827		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7828
7829		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7830
7831		if (lun->flags & CTL_LUN_PR_RESERVED)
7832		{
7833			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7834			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7835				    res->header.length);
7836			header_only = 0;
7837		} else {
7838			tmp_len = sizeof(struct scsi_per_res_in_header);
7839			scsi_ulto4b(0, res->header.length);
7840			header_only = 1;
7841		}
7842
7843		/*
7844		 * We had to drop the lock to allocate our buffer, which
7845		 * leaves time for someone to come in with another
7846		 * persistent reservation.  (That is unlikely, though,
7847		 * since this should be the only persistent reservation
7848		 * command active right now.)
7849		 */
7850		if (tmp_len != total_len) {
7851			mtx_unlock(&lun->lun_lock);
7852			free(ctsio->kern_data_ptr, M_CTL);
7853			printf("%s: reservation status changed, retrying\n",
7854			       __func__);
7855			goto retry;
7856		}
7857
7858		/*
7859		 * No reservation held, so we're done.
7860		 */
7861		if (header_only != 0)
7862			break;
7863
7864		/*
7865		 * If the registration is an All Registrants type, the key
7866		 * is 0, since it doesn't really matter.
7867		 */
7868		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7869			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7870			    res->data.reservation);
7871		}
7872		res->data.scopetype = lun->res_type;
7873		break;
7874	}
7875	case SPRI_RC:     //report capabilities
7876	{
7877		struct scsi_per_res_cap *res_cap;
7878		uint16_t type_mask;
7879
7880		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7881		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7882		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7883		type_mask = SPRI_TM_WR_EX_AR |
7884			    SPRI_TM_EX_AC_RO |
7885			    SPRI_TM_WR_EX_RO |
7886			    SPRI_TM_EX_AC |
7887			    SPRI_TM_WR_EX |
7888			    SPRI_TM_EX_AC_AR;
7889		scsi_ulto2b(type_mask, res_cap->type_mask);
7890		break;
7891	}
7892	case SPRI_RS: { // read full status
7893		struct scsi_per_res_in_full *res_status;
7894		struct scsi_per_res_in_full_desc *res_desc;
7895		struct ctl_port *port;
7896		int i, len;
7897
7898		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7899
7900		/*
7901		 * We had to drop the lock to allocate our buffer, which
7902		 * leaves time for someone to come in with another
7903		 * persistent reservation.  (That is unlikely, though,
7904		 * since this should be the only persistent reservation
7905		 * command active right now.)
7906		 */
7907		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7908		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7909		     lun->pr_key_count)){
7910			mtx_unlock(&lun->lun_lock);
7911			free(ctsio->kern_data_ptr, M_CTL);
7912			printf("%s: reservation length changed, retrying\n",
7913			       __func__);
7914			goto retry;
7915		}
7916
7917		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7918
7919		res_desc = &res_status->desc[0];
7920		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7921			if ((key = ctl_get_prkey(lun, i)) == 0)
7922				continue;
7923
7924			scsi_u64to8b(key, res_desc->res_key.key);
7925			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7926			    (lun->pr_res_idx == i ||
7927			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7928				res_desc->flags = SPRI_FULL_R_HOLDER;
7929				res_desc->scopetype = lun->res_type;
7930			}
7931			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7932			    res_desc->rel_trgt_port_id);
7933			len = 0;
7934			port = softc->ctl_ports[
7935			    ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
7936			if (port != NULL)
7937				len = ctl_create_iid(port,
7938				    i % CTL_MAX_INIT_PER_PORT,
7939				    res_desc->transport_id);
7940			scsi_ulto4b(len, res_desc->additional_length);
7941			res_desc = (struct scsi_per_res_in_full_desc *)
7942			    &res_desc->transport_id[len];
7943		}
7944		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7945		    res_status->header.length);
7946		break;
7947	}
7948	default:
7949		/*
7950		 * This is a bug, because we just checked for this above,
7951		 * and should have returned an error.
7952		 */
7953		panic("Invalid PR type %x", cdb->action);
7954		break; /* NOTREACHED */
7955	}
7956	mtx_unlock(&lun->lun_lock);
7957
7958	ctl_set_success(ctsio);
7959	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7960	ctsio->be_move_done = ctl_config_move_done;
7961	ctl_datamove((union ctl_io *)ctsio);
7962	return (CTL_RETVAL_COMPLETE);
7963}
7964
7965static void
7966ctl_est_res_ua(struct ctl_lun *lun, uint32_t residx, ctl_ua_type ua)
7967{
7968	int off = lun->ctl_softc->persis_offset;
7969
7970	if (residx >= off && residx < off + CTL_MAX_INITIATORS)
7971		ctl_est_ua(lun, residx - off, ua);
7972}
7973
7974/*
7975 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7976 * it should return.
7977 */
7978static int
7979ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7980		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7981		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7982		struct scsi_per_res_out_parms* param)
7983{
7984	union ctl_ha_msg persis_io;
7985	int retval, i;
7986	int isc_retval;
7987
7988	retval = 0;
7989
7990	mtx_lock(&lun->lun_lock);
7991	if (sa_res_key == 0) {
7992		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7993			/* validate scope and type */
7994			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7995			     SPR_LU_SCOPE) {
7996				mtx_unlock(&lun->lun_lock);
7997				ctl_set_invalid_field(/*ctsio*/ ctsio,
7998						      /*sks_valid*/ 1,
7999						      /*command*/ 1,
8000						      /*field*/ 2,
8001						      /*bit_valid*/ 1,
8002						      /*bit*/ 4);
8003				ctl_done((union ctl_io *)ctsio);
8004				return (1);
8005			}
8006
8007		        if (type>8 || type==2 || type==4 || type==0) {
8008				mtx_unlock(&lun->lun_lock);
8009				ctl_set_invalid_field(/*ctsio*/ ctsio,
8010       	           				      /*sks_valid*/ 1,
8011						      /*command*/ 1,
8012						      /*field*/ 2,
8013						      /*bit_valid*/ 1,
8014						      /*bit*/ 0);
8015				ctl_done((union ctl_io *)ctsio);
8016				return (1);
8017		        }
8018
8019			/*
8020			 * Unregister everybody else and build UA for
8021			 * them
8022			 */
8023			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8024				if (i == residx || ctl_get_prkey(lun, i) == 0)
8025					continue;
8026
8027				ctl_clr_prkey(lun, i);
8028				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8029			}
8030			lun->pr_key_count = 1;
8031			lun->res_type = type;
8032			if (lun->res_type != SPR_TYPE_WR_EX_AR
8033			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8034				lun->pr_res_idx = residx;
8035
8036			/* send msg to other side */
8037			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8038			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8039			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8040			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8041			persis_io.pr.pr_info.res_type = type;
8042			memcpy(persis_io.pr.pr_info.sa_res_key,
8043			       param->serv_act_res_key,
8044			       sizeof(param->serv_act_res_key));
8045			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8046			     &persis_io, sizeof(persis_io), 0)) >
8047			     CTL_HA_STATUS_SUCCESS) {
8048				printf("CTL:Persis Out error returned "
8049				       "from ctl_ha_msg_send %d\n",
8050				       isc_retval);
8051			}
8052		} else {
8053			/* not all registrants */
8054			mtx_unlock(&lun->lun_lock);
8055			free(ctsio->kern_data_ptr, M_CTL);
8056			ctl_set_invalid_field(ctsio,
8057					      /*sks_valid*/ 1,
8058					      /*command*/ 0,
8059					      /*field*/ 8,
8060					      /*bit_valid*/ 0,
8061					      /*bit*/ 0);
8062			ctl_done((union ctl_io *)ctsio);
8063			return (1);
8064		}
8065	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8066		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8067		int found = 0;
8068
8069		if (res_key == sa_res_key) {
8070			/* special case */
8071			/*
8072			 * The spec implies this is not good but doesn't
8073			 * say what to do. There are two choices either
8074			 * generate a res conflict or check condition
8075			 * with illegal field in parameter data. Since
8076			 * that is what is done when the sa_res_key is
8077			 * zero I'll take that approach since this has
8078			 * to do with the sa_res_key.
8079			 */
8080			mtx_unlock(&lun->lun_lock);
8081			free(ctsio->kern_data_ptr, M_CTL);
8082			ctl_set_invalid_field(ctsio,
8083					      /*sks_valid*/ 1,
8084					      /*command*/ 0,
8085					      /*field*/ 8,
8086					      /*bit_valid*/ 0,
8087					      /*bit*/ 0);
8088			ctl_done((union ctl_io *)ctsio);
8089			return (1);
8090		}
8091
8092		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8093			if (ctl_get_prkey(lun, i) != sa_res_key)
8094				continue;
8095
8096			found = 1;
8097			ctl_clr_prkey(lun, i);
8098			lun->pr_key_count--;
8099			ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8100		}
8101		if (!found) {
8102			mtx_unlock(&lun->lun_lock);
8103			free(ctsio->kern_data_ptr, M_CTL);
8104			ctl_set_reservation_conflict(ctsio);
8105			ctl_done((union ctl_io *)ctsio);
8106			return (CTL_RETVAL_COMPLETE);
8107		}
8108		/* send msg to other side */
8109		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8110		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8111		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8112		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8113		persis_io.pr.pr_info.res_type = type;
8114		memcpy(persis_io.pr.pr_info.sa_res_key,
8115		       param->serv_act_res_key,
8116		       sizeof(param->serv_act_res_key));
8117		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8118		     &persis_io, sizeof(persis_io), 0)) >
8119		     CTL_HA_STATUS_SUCCESS) {
8120			printf("CTL:Persis Out error returned from "
8121			       "ctl_ha_msg_send %d\n", isc_retval);
8122		}
8123	} else {
8124		/* Reserved but not all registrants */
8125		/* sa_res_key is res holder */
8126		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
8127			/* validate scope and type */
8128			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8129			     SPR_LU_SCOPE) {
8130				mtx_unlock(&lun->lun_lock);
8131				ctl_set_invalid_field(/*ctsio*/ ctsio,
8132						      /*sks_valid*/ 1,
8133						      /*command*/ 1,
8134						      /*field*/ 2,
8135						      /*bit_valid*/ 1,
8136						      /*bit*/ 4);
8137				ctl_done((union ctl_io *)ctsio);
8138				return (1);
8139			}
8140
8141			if (type>8 || type==2 || type==4 || type==0) {
8142				mtx_unlock(&lun->lun_lock);
8143				ctl_set_invalid_field(/*ctsio*/ ctsio,
8144						      /*sks_valid*/ 1,
8145						      /*command*/ 1,
8146						      /*field*/ 2,
8147						      /*bit_valid*/ 1,
8148						      /*bit*/ 0);
8149				ctl_done((union ctl_io *)ctsio);
8150				return (1);
8151			}
8152
8153			/*
8154			 * Do the following:
8155			 * if sa_res_key != res_key remove all
8156			 * registrants w/sa_res_key and generate UA
8157			 * for these registrants(Registrations
8158			 * Preempted) if it wasn't an exclusive
8159			 * reservation generate UA(Reservations
8160			 * Preempted) for all other registered nexuses
8161			 * if the type has changed. Establish the new
8162			 * reservation and holder. If res_key and
8163			 * sa_res_key are the same do the above
8164			 * except don't unregister the res holder.
8165			 */
8166
8167			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8168				if (i == residx || ctl_get_prkey(lun, i) == 0)
8169					continue;
8170
8171				if (sa_res_key == ctl_get_prkey(lun, i)) {
8172					ctl_clr_prkey(lun, i);
8173					lun->pr_key_count--;
8174					ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8175				} else if (type != lun->res_type
8176					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8177					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8178					ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
8179				}
8180			}
8181			lun->res_type = type;
8182			if (lun->res_type != SPR_TYPE_WR_EX_AR
8183			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8184				lun->pr_res_idx = residx;
8185			else
8186				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8187
8188			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8189			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8190			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8191			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8192			persis_io.pr.pr_info.res_type = type;
8193			memcpy(persis_io.pr.pr_info.sa_res_key,
8194			       param->serv_act_res_key,
8195			       sizeof(param->serv_act_res_key));
8196			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8197			     &persis_io, sizeof(persis_io), 0)) >
8198			     CTL_HA_STATUS_SUCCESS) {
8199				printf("CTL:Persis Out error returned "
8200				       "from ctl_ha_msg_send %d\n",
8201				       isc_retval);
8202			}
8203		} else {
8204			/*
8205			 * sa_res_key is not the res holder just
8206			 * remove registrants
8207			 */
8208			int found=0;
8209
8210			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8211				if (sa_res_key != ctl_get_prkey(lun, i))
8212					continue;
8213
8214				found = 1;
8215				ctl_clr_prkey(lun, i);
8216				lun->pr_key_count--;
8217				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8218			}
8219
8220			if (!found) {
8221				mtx_unlock(&lun->lun_lock);
8222				free(ctsio->kern_data_ptr, M_CTL);
8223				ctl_set_reservation_conflict(ctsio);
8224				ctl_done((union ctl_io *)ctsio);
8225		        	return (1);
8226			}
8227			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8228			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8229			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8230			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8231			persis_io.pr.pr_info.res_type = type;
8232			memcpy(persis_io.pr.pr_info.sa_res_key,
8233			       param->serv_act_res_key,
8234			       sizeof(param->serv_act_res_key));
8235			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8236			     &persis_io, sizeof(persis_io), 0)) >
8237			     CTL_HA_STATUS_SUCCESS) {
8238				printf("CTL:Persis Out error returned "
8239				       "from ctl_ha_msg_send %d\n",
8240				isc_retval);
8241			}
8242		}
8243	}
8244
8245	lun->PRGeneration++;
8246	mtx_unlock(&lun->lun_lock);
8247
8248	return (retval);
8249}
8250
8251static void
8252ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8253{
8254	uint64_t sa_res_key;
8255	int i;
8256
8257	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8258
8259	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8260	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8261	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8262		if (sa_res_key == 0) {
8263			/*
8264			 * Unregister everybody else and build UA for
8265			 * them
8266			 */
8267			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8268				if (i == msg->pr.pr_info.residx ||
8269				    ctl_get_prkey(lun, i) == 0)
8270					continue;
8271
8272				ctl_clr_prkey(lun, i);
8273				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8274			}
8275
8276			lun->pr_key_count = 1;
8277			lun->res_type = msg->pr.pr_info.res_type;
8278			if (lun->res_type != SPR_TYPE_WR_EX_AR
8279			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8280				lun->pr_res_idx = msg->pr.pr_info.residx;
8281		} else {
8282		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8283				if (sa_res_key == ctl_get_prkey(lun, i))
8284					continue;
8285
8286				ctl_clr_prkey(lun, i);
8287				lun->pr_key_count--;
8288				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8289			}
8290		}
8291	} else {
8292		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8293			if (i == msg->pr.pr_info.residx ||
8294			    ctl_get_prkey(lun, i) == 0)
8295				continue;
8296
8297			if (sa_res_key == ctl_get_prkey(lun, i)) {
8298				ctl_clr_prkey(lun, i);
8299				lun->pr_key_count--;
8300				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8301			} else if (msg->pr.pr_info.res_type != lun->res_type
8302				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8303				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8304				ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
8305			}
8306		}
8307		lun->res_type = msg->pr.pr_info.res_type;
8308		if (lun->res_type != SPR_TYPE_WR_EX_AR
8309		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8310			lun->pr_res_idx = msg->pr.pr_info.residx;
8311		else
8312			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8313	}
8314	lun->PRGeneration++;
8315
8316}
8317
8318
8319int
8320ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8321{
8322	int retval;
8323	int isc_retval;
8324	u_int32_t param_len;
8325	struct scsi_per_res_out *cdb;
8326	struct ctl_lun *lun;
8327	struct scsi_per_res_out_parms* param;
8328	struct ctl_softc *softc;
8329	uint32_t residx;
8330	uint64_t res_key, sa_res_key, key;
8331	uint8_t type;
8332	union ctl_ha_msg persis_io;
8333	int    i;
8334
8335	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8336
8337	retval = CTL_RETVAL_COMPLETE;
8338
8339	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8340	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8341	softc = lun->ctl_softc;
8342
8343	/*
8344	 * We only support whole-LUN scope.  The scope & type are ignored for
8345	 * register, register and ignore existing key and clear.
8346	 * We sometimes ignore scope and type on preempts too!!
8347	 * Verify reservation type here as well.
8348	 */
8349	type = cdb->scope_type & SPR_TYPE_MASK;
8350	if ((cdb->action == SPRO_RESERVE)
8351	 || (cdb->action == SPRO_RELEASE)) {
8352		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8353			ctl_set_invalid_field(/*ctsio*/ ctsio,
8354					      /*sks_valid*/ 1,
8355					      /*command*/ 1,
8356					      /*field*/ 2,
8357					      /*bit_valid*/ 1,
8358					      /*bit*/ 4);
8359			ctl_done((union ctl_io *)ctsio);
8360			return (CTL_RETVAL_COMPLETE);
8361		}
8362
8363		if (type>8 || type==2 || type==4 || type==0) {
8364			ctl_set_invalid_field(/*ctsio*/ ctsio,
8365					      /*sks_valid*/ 1,
8366					      /*command*/ 1,
8367					      /*field*/ 2,
8368					      /*bit_valid*/ 1,
8369					      /*bit*/ 0);
8370			ctl_done((union ctl_io *)ctsio);
8371			return (CTL_RETVAL_COMPLETE);
8372		}
8373	}
8374
8375	param_len = scsi_4btoul(cdb->length);
8376
8377	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8378		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8379		ctsio->kern_data_len = param_len;
8380		ctsio->kern_total_len = param_len;
8381		ctsio->kern_data_resid = 0;
8382		ctsio->kern_rel_offset = 0;
8383		ctsio->kern_sg_entries = 0;
8384		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8385		ctsio->be_move_done = ctl_config_move_done;
8386		ctl_datamove((union ctl_io *)ctsio);
8387
8388		return (CTL_RETVAL_COMPLETE);
8389	}
8390
8391	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8392
8393	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8394	res_key = scsi_8btou64(param->res_key.key);
8395	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8396
8397	/*
8398	 * Validate the reservation key here except for SPRO_REG_IGNO
8399	 * This must be done for all other service actions
8400	 */
8401	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8402		mtx_lock(&lun->lun_lock);
8403		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8404			if (res_key != key) {
8405				/*
8406				 * The current key passed in doesn't match
8407				 * the one the initiator previously
8408				 * registered.
8409				 */
8410				mtx_unlock(&lun->lun_lock);
8411				free(ctsio->kern_data_ptr, M_CTL);
8412				ctl_set_reservation_conflict(ctsio);
8413				ctl_done((union ctl_io *)ctsio);
8414				return (CTL_RETVAL_COMPLETE);
8415			}
8416		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8417			/*
8418			 * We are not registered
8419			 */
8420			mtx_unlock(&lun->lun_lock);
8421			free(ctsio->kern_data_ptr, M_CTL);
8422			ctl_set_reservation_conflict(ctsio);
8423			ctl_done((union ctl_io *)ctsio);
8424			return (CTL_RETVAL_COMPLETE);
8425		} else if (res_key != 0) {
8426			/*
8427			 * We are not registered and trying to register but
8428			 * the register key isn't zero.
8429			 */
8430			mtx_unlock(&lun->lun_lock);
8431			free(ctsio->kern_data_ptr, M_CTL);
8432			ctl_set_reservation_conflict(ctsio);
8433			ctl_done((union ctl_io *)ctsio);
8434			return (CTL_RETVAL_COMPLETE);
8435		}
8436		mtx_unlock(&lun->lun_lock);
8437	}
8438
8439	switch (cdb->action & SPRO_ACTION_MASK) {
8440	case SPRO_REGISTER:
8441	case SPRO_REG_IGNO: {
8442
8443#if 0
8444		printf("Registration received\n");
8445#endif
8446
8447		/*
8448		 * We don't support any of these options, as we report in
8449		 * the read capabilities request (see
8450		 * ctl_persistent_reserve_in(), above).
8451		 */
8452		if ((param->flags & SPR_SPEC_I_PT)
8453		 || (param->flags & SPR_ALL_TG_PT)
8454		 || (param->flags & SPR_APTPL)) {
8455			int bit_ptr;
8456
8457			if (param->flags & SPR_APTPL)
8458				bit_ptr = 0;
8459			else if (param->flags & SPR_ALL_TG_PT)
8460				bit_ptr = 2;
8461			else /* SPR_SPEC_I_PT */
8462				bit_ptr = 3;
8463
8464			free(ctsio->kern_data_ptr, M_CTL);
8465			ctl_set_invalid_field(ctsio,
8466					      /*sks_valid*/ 1,
8467					      /*command*/ 0,
8468					      /*field*/ 20,
8469					      /*bit_valid*/ 1,
8470					      /*bit*/ bit_ptr);
8471			ctl_done((union ctl_io *)ctsio);
8472			return (CTL_RETVAL_COMPLETE);
8473		}
8474
8475		mtx_lock(&lun->lun_lock);
8476
8477		/*
8478		 * The initiator wants to clear the
8479		 * key/unregister.
8480		 */
8481		if (sa_res_key == 0) {
8482			if ((res_key == 0
8483			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8484			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8485			  && ctl_get_prkey(lun, residx) == 0)) {
8486				mtx_unlock(&lun->lun_lock);
8487				goto done;
8488			}
8489
8490			ctl_clr_prkey(lun, residx);
8491			lun->pr_key_count--;
8492
8493			if (residx == lun->pr_res_idx) {
8494				lun->flags &= ~CTL_LUN_PR_RESERVED;
8495				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8496
8497				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8498				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8499				 && lun->pr_key_count) {
8500					/*
8501					 * If the reservation is a registrants
8502					 * only type we need to generate a UA
8503					 * for other registered inits.  The
8504					 * sense code should be RESERVATIONS
8505					 * RELEASED
8506					 */
8507
8508					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8509						if (ctl_get_prkey(lun, i +
8510						    softc->persis_offset) == 0)
8511							continue;
8512						ctl_est_ua(lun, i,
8513						    CTL_UA_RES_RELEASE);
8514					}
8515				}
8516				lun->res_type = 0;
8517			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8518				if (lun->pr_key_count==0) {
8519					lun->flags &= ~CTL_LUN_PR_RESERVED;
8520					lun->res_type = 0;
8521					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8522				}
8523			}
8524			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8525			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8526			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8527			persis_io.pr.pr_info.residx = residx;
8528			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8529			     &persis_io, sizeof(persis_io), 0 )) >
8530			     CTL_HA_STATUS_SUCCESS) {
8531				printf("CTL:Persis Out error returned from "
8532				       "ctl_ha_msg_send %d\n", isc_retval);
8533			}
8534		} else /* sa_res_key != 0 */ {
8535
8536			/*
8537			 * If we aren't registered currently then increment
8538			 * the key count and set the registered flag.
8539			 */
8540			ctl_alloc_prkey(lun, residx);
8541			if (ctl_get_prkey(lun, residx) == 0)
8542				lun->pr_key_count++;
8543			ctl_set_prkey(lun, residx, sa_res_key);
8544
8545			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8546			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8547			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8548			persis_io.pr.pr_info.residx = residx;
8549			memcpy(persis_io.pr.pr_info.sa_res_key,
8550			       param->serv_act_res_key,
8551			       sizeof(param->serv_act_res_key));
8552			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8553			     &persis_io, sizeof(persis_io), 0)) >
8554			     CTL_HA_STATUS_SUCCESS) {
8555				printf("CTL:Persis Out error returned from "
8556				       "ctl_ha_msg_send %d\n", isc_retval);
8557			}
8558		}
8559		lun->PRGeneration++;
8560		mtx_unlock(&lun->lun_lock);
8561
8562		break;
8563	}
8564	case SPRO_RESERVE:
8565#if 0
8566                printf("Reserve executed type %d\n", type);
8567#endif
8568		mtx_lock(&lun->lun_lock);
8569		if (lun->flags & CTL_LUN_PR_RESERVED) {
8570			/*
8571			 * if this isn't the reservation holder and it's
8572			 * not a "all registrants" type or if the type is
8573			 * different then we have a conflict
8574			 */
8575			if ((lun->pr_res_idx != residx
8576			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8577			 || lun->res_type != type) {
8578				mtx_unlock(&lun->lun_lock);
8579				free(ctsio->kern_data_ptr, M_CTL);
8580				ctl_set_reservation_conflict(ctsio);
8581				ctl_done((union ctl_io *)ctsio);
8582				return (CTL_RETVAL_COMPLETE);
8583			}
8584			mtx_unlock(&lun->lun_lock);
8585		} else /* create a reservation */ {
8586			/*
8587			 * If it's not an "all registrants" type record
8588			 * reservation holder
8589			 */
8590			if (type != SPR_TYPE_WR_EX_AR
8591			 && type != SPR_TYPE_EX_AC_AR)
8592				lun->pr_res_idx = residx; /* Res holder */
8593			else
8594				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8595
8596			lun->flags |= CTL_LUN_PR_RESERVED;
8597			lun->res_type = type;
8598
8599			mtx_unlock(&lun->lun_lock);
8600
8601			/* send msg to other side */
8602			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8603			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8604			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8605			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8606			persis_io.pr.pr_info.res_type = type;
8607			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8608			     &persis_io, sizeof(persis_io), 0)) >
8609			     CTL_HA_STATUS_SUCCESS) {
8610				printf("CTL:Persis Out error returned from "
8611				       "ctl_ha_msg_send %d\n", isc_retval);
8612			}
8613		}
8614		break;
8615
8616	case SPRO_RELEASE:
8617		mtx_lock(&lun->lun_lock);
8618		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8619			/* No reservation exists return good status */
8620			mtx_unlock(&lun->lun_lock);
8621			goto done;
8622		}
8623		/*
8624		 * Is this nexus a reservation holder?
8625		 */
8626		if (lun->pr_res_idx != residx
8627		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8628			/*
8629			 * not a res holder return good status but
8630			 * do nothing
8631			 */
8632			mtx_unlock(&lun->lun_lock);
8633			goto done;
8634		}
8635
8636		if (lun->res_type != type) {
8637			mtx_unlock(&lun->lun_lock);
8638			free(ctsio->kern_data_ptr, M_CTL);
8639			ctl_set_illegal_pr_release(ctsio);
8640			ctl_done((union ctl_io *)ctsio);
8641			return (CTL_RETVAL_COMPLETE);
8642		}
8643
8644		/* okay to release */
8645		lun->flags &= ~CTL_LUN_PR_RESERVED;
8646		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8647		lun->res_type = 0;
8648
8649		/*
8650		 * if this isn't an exclusive access
8651		 * res generate UA for all other
8652		 * registrants.
8653		 */
8654		if (type != SPR_TYPE_EX_AC
8655		 && type != SPR_TYPE_WR_EX) {
8656			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8657				if (i == residx ||
8658				    ctl_get_prkey(lun,
8659				     i + softc->persis_offset) == 0)
8660					continue;
8661				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8662			}
8663		}
8664		mtx_unlock(&lun->lun_lock);
8665		/* Send msg to other side */
8666		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8667		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8668		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8669		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8670		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8671			printf("CTL:Persis Out error returned from "
8672			       "ctl_ha_msg_send %d\n", isc_retval);
8673		}
8674		break;
8675
8676	case SPRO_CLEAR:
8677		/* send msg to other side */
8678
8679		mtx_lock(&lun->lun_lock);
8680		lun->flags &= ~CTL_LUN_PR_RESERVED;
8681		lun->res_type = 0;
8682		lun->pr_key_count = 0;
8683		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8684
8685		ctl_clr_prkey(lun, residx);
8686		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8687			if (ctl_get_prkey(lun, i) != 0) {
8688				ctl_clr_prkey(lun, i);
8689				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8690			}
8691		lun->PRGeneration++;
8692		mtx_unlock(&lun->lun_lock);
8693		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8694		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8695		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8696		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8697		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8698			printf("CTL:Persis Out error returned from "
8699			       "ctl_ha_msg_send %d\n", isc_retval);
8700		}
8701		break;
8702
8703	case SPRO_PREEMPT:
8704	case SPRO_PRE_ABO: {
8705		int nretval;
8706
8707		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8708					  residx, ctsio, cdb, param);
8709		if (nretval != 0)
8710			return (CTL_RETVAL_COMPLETE);
8711		break;
8712	}
8713	default:
8714		panic("Invalid PR type %x", cdb->action);
8715	}
8716
8717done:
8718	free(ctsio->kern_data_ptr, M_CTL);
8719	ctl_set_success(ctsio);
8720	ctl_done((union ctl_io *)ctsio);
8721
8722	return (retval);
8723}
8724
8725/*
8726 * This routine is for handling a message from the other SC pertaining to
8727 * persistent reserve out. All the error checking will have been done
8728 * so only perorming the action need be done here to keep the two
8729 * in sync.
8730 */
8731static void
8732ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8733{
8734	struct ctl_lun *lun;
8735	struct ctl_softc *softc;
8736	int i;
8737	uint32_t targ_lun;
8738
8739	softc = control_softc;
8740
8741	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8742	lun = softc->ctl_luns[targ_lun];
8743	mtx_lock(&lun->lun_lock);
8744	switch(msg->pr.pr_info.action) {
8745	case CTL_PR_REG_KEY:
8746		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8747		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8748			lun->pr_key_count++;
8749		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8750		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8751		lun->PRGeneration++;
8752		break;
8753
8754	case CTL_PR_UNREG_KEY:
8755		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8756		lun->pr_key_count--;
8757
8758		/* XXX Need to see if the reservation has been released */
8759		/* if so do we need to generate UA? */
8760		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8761			lun->flags &= ~CTL_LUN_PR_RESERVED;
8762			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8763
8764			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8765			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8766			 && lun->pr_key_count) {
8767				/*
8768				 * If the reservation is a registrants
8769				 * only type we need to generate a UA
8770				 * for other registered inits.  The
8771				 * sense code should be RESERVATIONS
8772				 * RELEASED
8773				 */
8774
8775				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8776					if (ctl_get_prkey(lun, i +
8777					    softc->persis_offset) == 0)
8778						continue;
8779
8780					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8781				}
8782			}
8783			lun->res_type = 0;
8784		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8785			if (lun->pr_key_count==0) {
8786				lun->flags &= ~CTL_LUN_PR_RESERVED;
8787				lun->res_type = 0;
8788				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8789			}
8790		}
8791		lun->PRGeneration++;
8792		break;
8793
8794	case CTL_PR_RESERVE:
8795		lun->flags |= CTL_LUN_PR_RESERVED;
8796		lun->res_type = msg->pr.pr_info.res_type;
8797		lun->pr_res_idx = msg->pr.pr_info.residx;
8798
8799		break;
8800
8801	case CTL_PR_RELEASE:
8802		/*
8803		 * if this isn't an exclusive access res generate UA for all
8804		 * other registrants.
8805		 */
8806		if (lun->res_type != SPR_TYPE_EX_AC
8807		 && lun->res_type != SPR_TYPE_WR_EX) {
8808			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8809				if (ctl_get_prkey(lun, i + softc->persis_offset) != 0)
8810					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8811		}
8812
8813		lun->flags &= ~CTL_LUN_PR_RESERVED;
8814		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8815		lun->res_type = 0;
8816		break;
8817
8818	case CTL_PR_PREEMPT:
8819		ctl_pro_preempt_other(lun, msg);
8820		break;
8821	case CTL_PR_CLEAR:
8822		lun->flags &= ~CTL_LUN_PR_RESERVED;
8823		lun->res_type = 0;
8824		lun->pr_key_count = 0;
8825		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8826
8827		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8828			if (ctl_get_prkey(lun, i) == 0)
8829				continue;
8830			ctl_clr_prkey(lun, i);
8831			ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8832		}
8833		lun->PRGeneration++;
8834		break;
8835	}
8836
8837	mtx_unlock(&lun->lun_lock);
8838}
8839
8840int
8841ctl_read_write(struct ctl_scsiio *ctsio)
8842{
8843	struct ctl_lun *lun;
8844	struct ctl_lba_len_flags *lbalen;
8845	uint64_t lba;
8846	uint32_t num_blocks;
8847	int flags, retval;
8848	int isread;
8849
8850	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8851
8852	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8853
8854	flags = 0;
8855	retval = CTL_RETVAL_COMPLETE;
8856
8857	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8858	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8859	switch (ctsio->cdb[0]) {
8860	case READ_6:
8861	case WRITE_6: {
8862		struct scsi_rw_6 *cdb;
8863
8864		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8865
8866		lba = scsi_3btoul(cdb->addr);
8867		/* only 5 bits are valid in the most significant address byte */
8868		lba &= 0x1fffff;
8869		num_blocks = cdb->length;
8870		/*
8871		 * This is correct according to SBC-2.
8872		 */
8873		if (num_blocks == 0)
8874			num_blocks = 256;
8875		break;
8876	}
8877	case READ_10:
8878	case WRITE_10: {
8879		struct scsi_rw_10 *cdb;
8880
8881		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8882		if (cdb->byte2 & SRW10_FUA)
8883			flags |= CTL_LLF_FUA;
8884		if (cdb->byte2 & SRW10_DPO)
8885			flags |= CTL_LLF_DPO;
8886		lba = scsi_4btoul(cdb->addr);
8887		num_blocks = scsi_2btoul(cdb->length);
8888		break;
8889	}
8890	case WRITE_VERIFY_10: {
8891		struct scsi_write_verify_10 *cdb;
8892
8893		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8894		flags |= CTL_LLF_FUA;
8895		if (cdb->byte2 & SWV_DPO)
8896			flags |= CTL_LLF_DPO;
8897		lba = scsi_4btoul(cdb->addr);
8898		num_blocks = scsi_2btoul(cdb->length);
8899		break;
8900	}
8901	case READ_12:
8902	case WRITE_12: {
8903		struct scsi_rw_12 *cdb;
8904
8905		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8906		if (cdb->byte2 & SRW12_FUA)
8907			flags |= CTL_LLF_FUA;
8908		if (cdb->byte2 & SRW12_DPO)
8909			flags |= CTL_LLF_DPO;
8910		lba = scsi_4btoul(cdb->addr);
8911		num_blocks = scsi_4btoul(cdb->length);
8912		break;
8913	}
8914	case WRITE_VERIFY_12: {
8915		struct scsi_write_verify_12 *cdb;
8916
8917		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8918		flags |= CTL_LLF_FUA;
8919		if (cdb->byte2 & SWV_DPO)
8920			flags |= CTL_LLF_DPO;
8921		lba = scsi_4btoul(cdb->addr);
8922		num_blocks = scsi_4btoul(cdb->length);
8923		break;
8924	}
8925	case READ_16:
8926	case WRITE_16: {
8927		struct scsi_rw_16 *cdb;
8928
8929		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8930		if (cdb->byte2 & SRW12_FUA)
8931			flags |= CTL_LLF_FUA;
8932		if (cdb->byte2 & SRW12_DPO)
8933			flags |= CTL_LLF_DPO;
8934		lba = scsi_8btou64(cdb->addr);
8935		num_blocks = scsi_4btoul(cdb->length);
8936		break;
8937	}
8938	case WRITE_ATOMIC_16: {
8939		struct scsi_rw_16 *cdb;
8940
8941		if (lun->be_lun->atomicblock == 0) {
8942			ctl_set_invalid_opcode(ctsio);
8943			ctl_done((union ctl_io *)ctsio);
8944			return (CTL_RETVAL_COMPLETE);
8945		}
8946
8947		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8948		if (cdb->byte2 & SRW12_FUA)
8949			flags |= CTL_LLF_FUA;
8950		if (cdb->byte2 & SRW12_DPO)
8951			flags |= CTL_LLF_DPO;
8952		lba = scsi_8btou64(cdb->addr);
8953		num_blocks = scsi_4btoul(cdb->length);
8954		if (num_blocks > lun->be_lun->atomicblock) {
8955			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8956			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8957			    /*bit*/ 0);
8958			ctl_done((union ctl_io *)ctsio);
8959			return (CTL_RETVAL_COMPLETE);
8960		}
8961		break;
8962	}
8963	case WRITE_VERIFY_16: {
8964		struct scsi_write_verify_16 *cdb;
8965
8966		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8967		flags |= CTL_LLF_FUA;
8968		if (cdb->byte2 & SWV_DPO)
8969			flags |= CTL_LLF_DPO;
8970		lba = scsi_8btou64(cdb->addr);
8971		num_blocks = scsi_4btoul(cdb->length);
8972		break;
8973	}
8974	default:
8975		/*
8976		 * We got a command we don't support.  This shouldn't
8977		 * happen, commands should be filtered out above us.
8978		 */
8979		ctl_set_invalid_opcode(ctsio);
8980		ctl_done((union ctl_io *)ctsio);
8981
8982		return (CTL_RETVAL_COMPLETE);
8983		break; /* NOTREACHED */
8984	}
8985
8986	/*
8987	 * The first check is to make sure we're in bounds, the second
8988	 * check is to catch wrap-around problems.  If the lba + num blocks
8989	 * is less than the lba, then we've wrapped around and the block
8990	 * range is invalid anyway.
8991	 */
8992	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8993	 || ((lba + num_blocks) < lba)) {
8994		ctl_set_lba_out_of_range(ctsio);
8995		ctl_done((union ctl_io *)ctsio);
8996		return (CTL_RETVAL_COMPLETE);
8997	}
8998
8999	/*
9000	 * According to SBC-3, a transfer length of 0 is not an error.
9001	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
9002	 * translates to 256 blocks for those commands.
9003	 */
9004	if (num_blocks == 0) {
9005		ctl_set_success(ctsio);
9006		ctl_done((union ctl_io *)ctsio);
9007		return (CTL_RETVAL_COMPLETE);
9008	}
9009
9010	/* Set FUA and/or DPO if caches are disabled. */
9011	if (isread) {
9012		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9013		    SCP_RCD) != 0)
9014			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9015	} else {
9016		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9017		    SCP_WCE) == 0)
9018			flags |= CTL_LLF_FUA;
9019	}
9020
9021	lbalen = (struct ctl_lba_len_flags *)
9022	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9023	lbalen->lba = lba;
9024	lbalen->len = num_blocks;
9025	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9026
9027	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9028	ctsio->kern_rel_offset = 0;
9029
9030	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9031
9032	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9033
9034	return (retval);
9035}
9036
9037static int
9038ctl_cnw_cont(union ctl_io *io)
9039{
9040	struct ctl_scsiio *ctsio;
9041	struct ctl_lun *lun;
9042	struct ctl_lba_len_flags *lbalen;
9043	int retval;
9044
9045	ctsio = &io->scsiio;
9046	ctsio->io_hdr.status = CTL_STATUS_NONE;
9047	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9048	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9049	lbalen = (struct ctl_lba_len_flags *)
9050	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9051	lbalen->flags &= ~CTL_LLF_COMPARE;
9052	lbalen->flags |= CTL_LLF_WRITE;
9053
9054	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9055	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9056	return (retval);
9057}
9058
9059int
9060ctl_cnw(struct ctl_scsiio *ctsio)
9061{
9062	struct ctl_lun *lun;
9063	struct ctl_lba_len_flags *lbalen;
9064	uint64_t lba;
9065	uint32_t num_blocks;
9066	int flags, retval;
9067
9068	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9069
9070	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9071
9072	flags = 0;
9073	retval = CTL_RETVAL_COMPLETE;
9074
9075	switch (ctsio->cdb[0]) {
9076	case COMPARE_AND_WRITE: {
9077		struct scsi_compare_and_write *cdb;
9078
9079		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9080		if (cdb->byte2 & SRW10_FUA)
9081			flags |= CTL_LLF_FUA;
9082		if (cdb->byte2 & SRW10_DPO)
9083			flags |= CTL_LLF_DPO;
9084		lba = scsi_8btou64(cdb->addr);
9085		num_blocks = cdb->length;
9086		break;
9087	}
9088	default:
9089		/*
9090		 * We got a command we don't support.  This shouldn't
9091		 * happen, commands should be filtered out above us.
9092		 */
9093		ctl_set_invalid_opcode(ctsio);
9094		ctl_done((union ctl_io *)ctsio);
9095
9096		return (CTL_RETVAL_COMPLETE);
9097		break; /* NOTREACHED */
9098	}
9099
9100	/*
9101	 * The first check is to make sure we're in bounds, the second
9102	 * check is to catch wrap-around problems.  If the lba + num blocks
9103	 * is less than the lba, then we've wrapped around and the block
9104	 * range is invalid anyway.
9105	 */
9106	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9107	 || ((lba + num_blocks) < lba)) {
9108		ctl_set_lba_out_of_range(ctsio);
9109		ctl_done((union ctl_io *)ctsio);
9110		return (CTL_RETVAL_COMPLETE);
9111	}
9112
9113	/*
9114	 * According to SBC-3, a transfer length of 0 is not an error.
9115	 */
9116	if (num_blocks == 0) {
9117		ctl_set_success(ctsio);
9118		ctl_done((union ctl_io *)ctsio);
9119		return (CTL_RETVAL_COMPLETE);
9120	}
9121
9122	/* Set FUA if write cache is disabled. */
9123	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9124	    SCP_WCE) == 0)
9125		flags |= CTL_LLF_FUA;
9126
9127	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9128	ctsio->kern_rel_offset = 0;
9129
9130	/*
9131	 * Set the IO_CONT flag, so that if this I/O gets passed to
9132	 * ctl_data_submit_done(), it'll get passed back to
9133	 * ctl_ctl_cnw_cont() for further processing.
9134	 */
9135	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9136	ctsio->io_cont = ctl_cnw_cont;
9137
9138	lbalen = (struct ctl_lba_len_flags *)
9139	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9140	lbalen->lba = lba;
9141	lbalen->len = num_blocks;
9142	lbalen->flags = CTL_LLF_COMPARE | flags;
9143
9144	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9145	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9146	return (retval);
9147}
9148
9149int
9150ctl_verify(struct ctl_scsiio *ctsio)
9151{
9152	struct ctl_lun *lun;
9153	struct ctl_lba_len_flags *lbalen;
9154	uint64_t lba;
9155	uint32_t num_blocks;
9156	int bytchk, flags;
9157	int retval;
9158
9159	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9160
9161	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9162
9163	bytchk = 0;
9164	flags = CTL_LLF_FUA;
9165	retval = CTL_RETVAL_COMPLETE;
9166
9167	switch (ctsio->cdb[0]) {
9168	case VERIFY_10: {
9169		struct scsi_verify_10 *cdb;
9170
9171		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9172		if (cdb->byte2 & SVFY_BYTCHK)
9173			bytchk = 1;
9174		if (cdb->byte2 & SVFY_DPO)
9175			flags |= CTL_LLF_DPO;
9176		lba = scsi_4btoul(cdb->addr);
9177		num_blocks = scsi_2btoul(cdb->length);
9178		break;
9179	}
9180	case VERIFY_12: {
9181		struct scsi_verify_12 *cdb;
9182
9183		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9184		if (cdb->byte2 & SVFY_BYTCHK)
9185			bytchk = 1;
9186		if (cdb->byte2 & SVFY_DPO)
9187			flags |= CTL_LLF_DPO;
9188		lba = scsi_4btoul(cdb->addr);
9189		num_blocks = scsi_4btoul(cdb->length);
9190		break;
9191	}
9192	case VERIFY_16: {
9193		struct scsi_rw_16 *cdb;
9194
9195		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9196		if (cdb->byte2 & SVFY_BYTCHK)
9197			bytchk = 1;
9198		if (cdb->byte2 & SVFY_DPO)
9199			flags |= CTL_LLF_DPO;
9200		lba = scsi_8btou64(cdb->addr);
9201		num_blocks = scsi_4btoul(cdb->length);
9202		break;
9203	}
9204	default:
9205		/*
9206		 * We got a command we don't support.  This shouldn't
9207		 * happen, commands should be filtered out above us.
9208		 */
9209		ctl_set_invalid_opcode(ctsio);
9210		ctl_done((union ctl_io *)ctsio);
9211		return (CTL_RETVAL_COMPLETE);
9212	}
9213
9214	/*
9215	 * The first check is to make sure we're in bounds, the second
9216	 * check is to catch wrap-around problems.  If the lba + num blocks
9217	 * is less than the lba, then we've wrapped around and the block
9218	 * range is invalid anyway.
9219	 */
9220	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9221	 || ((lba + num_blocks) < lba)) {
9222		ctl_set_lba_out_of_range(ctsio);
9223		ctl_done((union ctl_io *)ctsio);
9224		return (CTL_RETVAL_COMPLETE);
9225	}
9226
9227	/*
9228	 * According to SBC-3, a transfer length of 0 is not an error.
9229	 */
9230	if (num_blocks == 0) {
9231		ctl_set_success(ctsio);
9232		ctl_done((union ctl_io *)ctsio);
9233		return (CTL_RETVAL_COMPLETE);
9234	}
9235
9236	lbalen = (struct ctl_lba_len_flags *)
9237	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9238	lbalen->lba = lba;
9239	lbalen->len = num_blocks;
9240	if (bytchk) {
9241		lbalen->flags = CTL_LLF_COMPARE | flags;
9242		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9243	} else {
9244		lbalen->flags = CTL_LLF_VERIFY | flags;
9245		ctsio->kern_total_len = 0;
9246	}
9247	ctsio->kern_rel_offset = 0;
9248
9249	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9250	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9251	return (retval);
9252}
9253
9254int
9255ctl_report_luns(struct ctl_scsiio *ctsio)
9256{
9257	struct ctl_softc *softc = control_softc;
9258	struct scsi_report_luns *cdb;
9259	struct scsi_report_luns_data *lun_data;
9260	struct ctl_lun *lun, *request_lun;
9261	int num_luns, retval;
9262	uint32_t alloc_len, lun_datalen;
9263	int num_filled, well_known;
9264	uint32_t initidx, targ_lun_id, lun_id;
9265
9266	retval = CTL_RETVAL_COMPLETE;
9267	well_known = 0;
9268
9269	cdb = (struct scsi_report_luns *)ctsio->cdb;
9270
9271	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9272
9273	mtx_lock(&softc->ctl_lock);
9274	num_luns = softc->num_luns;
9275	mtx_unlock(&softc->ctl_lock);
9276
9277	switch (cdb->select_report) {
9278	case RPL_REPORT_DEFAULT:
9279	case RPL_REPORT_ALL:
9280		break;
9281	case RPL_REPORT_WELLKNOWN:
9282		well_known = 1;
9283		num_luns = 0;
9284		break;
9285	default:
9286		ctl_set_invalid_field(ctsio,
9287				      /*sks_valid*/ 1,
9288				      /*command*/ 1,
9289				      /*field*/ 2,
9290				      /*bit_valid*/ 0,
9291				      /*bit*/ 0);
9292		ctl_done((union ctl_io *)ctsio);
9293		return (retval);
9294		break; /* NOTREACHED */
9295	}
9296
9297	alloc_len = scsi_4btoul(cdb->length);
9298	/*
9299	 * The initiator has to allocate at least 16 bytes for this request,
9300	 * so he can at least get the header and the first LUN.  Otherwise
9301	 * we reject the request (per SPC-3 rev 14, section 6.21).
9302	 */
9303	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9304	    sizeof(struct scsi_report_luns_lundata))) {
9305		ctl_set_invalid_field(ctsio,
9306				      /*sks_valid*/ 1,
9307				      /*command*/ 1,
9308				      /*field*/ 6,
9309				      /*bit_valid*/ 0,
9310				      /*bit*/ 0);
9311		ctl_done((union ctl_io *)ctsio);
9312		return (retval);
9313	}
9314
9315	request_lun = (struct ctl_lun *)
9316		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9317
9318	lun_datalen = sizeof(*lun_data) +
9319		(num_luns * sizeof(struct scsi_report_luns_lundata));
9320
9321	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9322	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9323	ctsio->kern_sg_entries = 0;
9324
9325	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9326
9327	mtx_lock(&softc->ctl_lock);
9328	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9329		lun_id = ctl_map_lun(softc, ctsio->io_hdr.nexus.targ_port,
9330		    targ_lun_id);
9331		if (lun_id >= CTL_MAX_LUNS)
9332			continue;
9333		lun = softc->ctl_luns[lun_id];
9334		if (lun == NULL)
9335			continue;
9336
9337		if (targ_lun_id <= 0xff) {
9338			/*
9339			 * Peripheral addressing method, bus number 0.
9340			 */
9341			lun_data->luns[num_filled].lundata[0] =
9342				RPL_LUNDATA_ATYP_PERIPH;
9343			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9344			num_filled++;
9345		} else if (targ_lun_id <= 0x3fff) {
9346			/*
9347			 * Flat addressing method.
9348			 */
9349			lun_data->luns[num_filled].lundata[0] =
9350				RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9351			lun_data->luns[num_filled].lundata[1] =
9352				(targ_lun_id & 0xff);
9353			num_filled++;
9354		} else if (targ_lun_id <= 0xffffff) {
9355			/*
9356			 * Extended flat addressing method.
9357			 */
9358			lun_data->luns[num_filled].lundata[0] =
9359			    RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9360			scsi_ulto3b(targ_lun_id,
9361			    &lun_data->luns[num_filled].lundata[1]);
9362			num_filled++;
9363		} else {
9364			printf("ctl_report_luns: bogus LUN number %jd, "
9365			       "skipping\n", (intmax_t)targ_lun_id);
9366		}
9367		/*
9368		 * According to SPC-3, rev 14 section 6.21:
9369		 *
9370		 * "The execution of a REPORT LUNS command to any valid and
9371		 * installed logical unit shall clear the REPORTED LUNS DATA
9372		 * HAS CHANGED unit attention condition for all logical
9373		 * units of that target with respect to the requesting
9374		 * initiator. A valid and installed logical unit is one
9375		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9376		 * INQUIRY data (see 6.4.2)."
9377		 *
9378		 * If request_lun is NULL, the LUN this report luns command
9379		 * was issued to is either disabled or doesn't exist. In that
9380		 * case, we shouldn't clear any pending lun change unit
9381		 * attention.
9382		 */
9383		if (request_lun != NULL) {
9384			mtx_lock(&lun->lun_lock);
9385			ctl_clr_ua(lun, initidx, CTL_UA_RES_RELEASE);
9386			mtx_unlock(&lun->lun_lock);
9387		}
9388	}
9389	mtx_unlock(&softc->ctl_lock);
9390
9391	/*
9392	 * It's quite possible that we've returned fewer LUNs than we allocated
9393	 * space for.  Trim it.
9394	 */
9395	lun_datalen = sizeof(*lun_data) +
9396		(num_filled * sizeof(struct scsi_report_luns_lundata));
9397
9398	if (lun_datalen < alloc_len) {
9399		ctsio->residual = alloc_len - lun_datalen;
9400		ctsio->kern_data_len = lun_datalen;
9401		ctsio->kern_total_len = lun_datalen;
9402	} else {
9403		ctsio->residual = 0;
9404		ctsio->kern_data_len = alloc_len;
9405		ctsio->kern_total_len = alloc_len;
9406	}
9407	ctsio->kern_data_resid = 0;
9408	ctsio->kern_rel_offset = 0;
9409	ctsio->kern_sg_entries = 0;
9410
9411	/*
9412	 * We set this to the actual data length, regardless of how much
9413	 * space we actually have to return results.  If the user looks at
9414	 * this value, he'll know whether or not he allocated enough space
9415	 * and reissue the command if necessary.  We don't support well
9416	 * known logical units, so if the user asks for that, return none.
9417	 */
9418	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9419
9420	/*
9421	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9422	 * this request.
9423	 */
9424	ctl_set_success(ctsio);
9425	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9426	ctsio->be_move_done = ctl_config_move_done;
9427	ctl_datamove((union ctl_io *)ctsio);
9428	return (retval);
9429}
9430
9431int
9432ctl_request_sense(struct ctl_scsiio *ctsio)
9433{
9434	struct scsi_request_sense *cdb;
9435	struct scsi_sense_data *sense_ptr;
9436	struct ctl_lun *lun;
9437	uint32_t initidx;
9438	int have_error;
9439	scsi_sense_data_type sense_format;
9440	ctl_ua_type ua_type;
9441
9442	cdb = (struct scsi_request_sense *)ctsio->cdb;
9443
9444	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9445
9446	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9447
9448	/*
9449	 * Determine which sense format the user wants.
9450	 */
9451	if (cdb->byte2 & SRS_DESC)
9452		sense_format = SSD_TYPE_DESC;
9453	else
9454		sense_format = SSD_TYPE_FIXED;
9455
9456	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9457	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9458	ctsio->kern_sg_entries = 0;
9459
9460	/*
9461	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9462	 * larger than the largest allowed value for the length field in the
9463	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9464	 */
9465	ctsio->residual = 0;
9466	ctsio->kern_data_len = cdb->length;
9467	ctsio->kern_total_len = cdb->length;
9468
9469	ctsio->kern_data_resid = 0;
9470	ctsio->kern_rel_offset = 0;
9471	ctsio->kern_sg_entries = 0;
9472
9473	/*
9474	 * If we don't have a LUN, we don't have any pending sense.
9475	 */
9476	if (lun == NULL)
9477		goto no_sense;
9478
9479	have_error = 0;
9480	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9481	/*
9482	 * Check for pending sense, and then for pending unit attentions.
9483	 * Pending sense gets returned first, then pending unit attentions.
9484	 */
9485	mtx_lock(&lun->lun_lock);
9486#ifdef CTL_WITH_CA
9487	if (ctl_is_set(lun->have_ca, initidx)) {
9488		scsi_sense_data_type stored_format;
9489
9490		/*
9491		 * Check to see which sense format was used for the stored
9492		 * sense data.
9493		 */
9494		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9495
9496		/*
9497		 * If the user requested a different sense format than the
9498		 * one we stored, then we need to convert it to the other
9499		 * format.  If we're going from descriptor to fixed format
9500		 * sense data, we may lose things in translation, depending
9501		 * on what options were used.
9502		 *
9503		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9504		 * for some reason we'll just copy it out as-is.
9505		 */
9506		if ((stored_format == SSD_TYPE_FIXED)
9507		 && (sense_format == SSD_TYPE_DESC))
9508			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9509			    &lun->pending_sense[initidx],
9510			    (struct scsi_sense_data_desc *)sense_ptr);
9511		else if ((stored_format == SSD_TYPE_DESC)
9512		      && (sense_format == SSD_TYPE_FIXED))
9513			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9514			    &lun->pending_sense[initidx],
9515			    (struct scsi_sense_data_fixed *)sense_ptr);
9516		else
9517			memcpy(sense_ptr, &lun->pending_sense[initidx],
9518			       MIN(sizeof(*sense_ptr),
9519			       sizeof(lun->pending_sense[initidx])));
9520
9521		ctl_clear_mask(lun->have_ca, initidx);
9522		have_error = 1;
9523	} else
9524#endif
9525	{
9526		ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9527		if (ua_type != CTL_UA_NONE)
9528			have_error = 1;
9529	}
9530	mtx_unlock(&lun->lun_lock);
9531
9532	/*
9533	 * We already have a pending error, return it.
9534	 */
9535	if (have_error != 0) {
9536		/*
9537		 * We report the SCSI status as OK, since the status of the
9538		 * request sense command itself is OK.
9539		 * We report 0 for the sense length, because we aren't doing
9540		 * autosense in this case.  We're reporting sense as
9541		 * parameter data.
9542		 */
9543		ctl_set_success(ctsio);
9544		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9545		ctsio->be_move_done = ctl_config_move_done;
9546		ctl_datamove((union ctl_io *)ctsio);
9547		return (CTL_RETVAL_COMPLETE);
9548	}
9549
9550no_sense:
9551
9552	/*
9553	 * No sense information to report, so we report that everything is
9554	 * okay.
9555	 */
9556	ctl_set_sense_data(sense_ptr,
9557			   lun,
9558			   sense_format,
9559			   /*current_error*/ 1,
9560			   /*sense_key*/ SSD_KEY_NO_SENSE,
9561			   /*asc*/ 0x00,
9562			   /*ascq*/ 0x00,
9563			   SSD_ELEM_NONE);
9564
9565	/*
9566	 * We report 0 for the sense length, because we aren't doing
9567	 * autosense in this case.  We're reporting sense as parameter data.
9568	 */
9569	ctl_set_success(ctsio);
9570	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9571	ctsio->be_move_done = ctl_config_move_done;
9572	ctl_datamove((union ctl_io *)ctsio);
9573	return (CTL_RETVAL_COMPLETE);
9574}
9575
9576int
9577ctl_tur(struct ctl_scsiio *ctsio)
9578{
9579
9580	CTL_DEBUG_PRINT(("ctl_tur\n"));
9581
9582	ctl_set_success(ctsio);
9583	ctl_done((union ctl_io *)ctsio);
9584
9585	return (CTL_RETVAL_COMPLETE);
9586}
9587
9588#ifdef notyet
9589static int
9590ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9591{
9592
9593}
9594#endif
9595
9596static int
9597ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9598{
9599	struct scsi_vpd_supported_pages *pages;
9600	int sup_page_size;
9601	struct ctl_lun *lun;
9602
9603	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9604
9605	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9606	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9607	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9608	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9609	ctsio->kern_sg_entries = 0;
9610
9611	if (sup_page_size < alloc_len) {
9612		ctsio->residual = alloc_len - sup_page_size;
9613		ctsio->kern_data_len = sup_page_size;
9614		ctsio->kern_total_len = sup_page_size;
9615	} else {
9616		ctsio->residual = 0;
9617		ctsio->kern_data_len = alloc_len;
9618		ctsio->kern_total_len = alloc_len;
9619	}
9620	ctsio->kern_data_resid = 0;
9621	ctsio->kern_rel_offset = 0;
9622	ctsio->kern_sg_entries = 0;
9623
9624	/*
9625	 * The control device is always connected.  The disk device, on the
9626	 * other hand, may not be online all the time.  Need to change this
9627	 * to figure out whether the disk device is actually online or not.
9628	 */
9629	if (lun != NULL)
9630		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9631				lun->be_lun->lun_type;
9632	else
9633		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9634
9635	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9636	/* Supported VPD pages */
9637	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9638	/* Serial Number */
9639	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9640	/* Device Identification */
9641	pages->page_list[2] = SVPD_DEVICE_ID;
9642	/* Extended INQUIRY Data */
9643	pages->page_list[3] = SVPD_EXTENDED_INQUIRY_DATA;
9644	/* Mode Page Policy */
9645	pages->page_list[4] = SVPD_MODE_PAGE_POLICY;
9646	/* SCSI Ports */
9647	pages->page_list[5] = SVPD_SCSI_PORTS;
9648	/* Third-party Copy */
9649	pages->page_list[6] = SVPD_SCSI_TPC;
9650	/* Block limits */
9651	pages->page_list[7] = SVPD_BLOCK_LIMITS;
9652	/* Block Device Characteristics */
9653	pages->page_list[8] = SVPD_BDC;
9654	/* Logical Block Provisioning */
9655	pages->page_list[9] = SVPD_LBP;
9656
9657	ctl_set_success(ctsio);
9658	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9659	ctsio->be_move_done = ctl_config_move_done;
9660	ctl_datamove((union ctl_io *)ctsio);
9661	return (CTL_RETVAL_COMPLETE);
9662}
9663
9664static int
9665ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9666{
9667	struct scsi_vpd_unit_serial_number *sn_ptr;
9668	struct ctl_lun *lun;
9669	int data_len;
9670
9671	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9672
9673	data_len = 4 + CTL_SN_LEN;
9674	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9675	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9676	if (data_len < alloc_len) {
9677		ctsio->residual = alloc_len - data_len;
9678		ctsio->kern_data_len = data_len;
9679		ctsio->kern_total_len = data_len;
9680	} else {
9681		ctsio->residual = 0;
9682		ctsio->kern_data_len = alloc_len;
9683		ctsio->kern_total_len = alloc_len;
9684	}
9685	ctsio->kern_data_resid = 0;
9686	ctsio->kern_rel_offset = 0;
9687	ctsio->kern_sg_entries = 0;
9688
9689	/*
9690	 * The control device is always connected.  The disk device, on the
9691	 * other hand, may not be online all the time.  Need to change this
9692	 * to figure out whether the disk device is actually online or not.
9693	 */
9694	if (lun != NULL)
9695		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9696				  lun->be_lun->lun_type;
9697	else
9698		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9699
9700	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9701	sn_ptr->length = CTL_SN_LEN;
9702	/*
9703	 * If we don't have a LUN, we just leave the serial number as
9704	 * all spaces.
9705	 */
9706	if (lun != NULL) {
9707		strncpy((char *)sn_ptr->serial_num,
9708			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9709	} else
9710		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9711
9712	ctl_set_success(ctsio);
9713	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9714	ctsio->be_move_done = ctl_config_move_done;
9715	ctl_datamove((union ctl_io *)ctsio);
9716	return (CTL_RETVAL_COMPLETE);
9717}
9718
9719
9720static int
9721ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9722{
9723	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9724	struct ctl_lun *lun;
9725	int data_len;
9726
9727	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9728
9729	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9730	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9731	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9732	ctsio->kern_sg_entries = 0;
9733
9734	if (data_len < alloc_len) {
9735		ctsio->residual = alloc_len - data_len;
9736		ctsio->kern_data_len = data_len;
9737		ctsio->kern_total_len = data_len;
9738	} else {
9739		ctsio->residual = 0;
9740		ctsio->kern_data_len = alloc_len;
9741		ctsio->kern_total_len = alloc_len;
9742	}
9743	ctsio->kern_data_resid = 0;
9744	ctsio->kern_rel_offset = 0;
9745	ctsio->kern_sg_entries = 0;
9746
9747	/*
9748	 * The control device is always connected.  The disk device, on the
9749	 * other hand, may not be online all the time.
9750	 */
9751	if (lun != NULL)
9752		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9753				     lun->be_lun->lun_type;
9754	else
9755		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9756	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9757	eid_ptr->page_length = data_len - 4;
9758	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9759	eid_ptr->flags3 = SVPD_EID_V_SUP;
9760
9761	ctl_set_success(ctsio);
9762	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9763	ctsio->be_move_done = ctl_config_move_done;
9764	ctl_datamove((union ctl_io *)ctsio);
9765	return (CTL_RETVAL_COMPLETE);
9766}
9767
9768static int
9769ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9770{
9771	struct scsi_vpd_mode_page_policy *mpp_ptr;
9772	struct ctl_lun *lun;
9773	int data_len;
9774
9775	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9776
9777	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9778	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9779
9780	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9781	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9782	ctsio->kern_sg_entries = 0;
9783
9784	if (data_len < alloc_len) {
9785		ctsio->residual = alloc_len - data_len;
9786		ctsio->kern_data_len = data_len;
9787		ctsio->kern_total_len = data_len;
9788	} else {
9789		ctsio->residual = 0;
9790		ctsio->kern_data_len = alloc_len;
9791		ctsio->kern_total_len = alloc_len;
9792	}
9793	ctsio->kern_data_resid = 0;
9794	ctsio->kern_rel_offset = 0;
9795	ctsio->kern_sg_entries = 0;
9796
9797	/*
9798	 * The control device is always connected.  The disk device, on the
9799	 * other hand, may not be online all the time.
9800	 */
9801	if (lun != NULL)
9802		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9803				     lun->be_lun->lun_type;
9804	else
9805		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9806	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9807	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9808	mpp_ptr->descr[0].page_code = 0x3f;
9809	mpp_ptr->descr[0].subpage_code = 0xff;
9810	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9811
9812	ctl_set_success(ctsio);
9813	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9814	ctsio->be_move_done = ctl_config_move_done;
9815	ctl_datamove((union ctl_io *)ctsio);
9816	return (CTL_RETVAL_COMPLETE);
9817}
9818
9819static int
9820ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9821{
9822	struct scsi_vpd_device_id *devid_ptr;
9823	struct scsi_vpd_id_descriptor *desc;
9824	struct ctl_softc *softc;
9825	struct ctl_lun *lun;
9826	struct ctl_port *port;
9827	int data_len;
9828	uint8_t proto;
9829
9830	softc = control_softc;
9831
9832	port = softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9833	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9834
9835	data_len = sizeof(struct scsi_vpd_device_id) +
9836	    sizeof(struct scsi_vpd_id_descriptor) +
9837		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9838	    sizeof(struct scsi_vpd_id_descriptor) +
9839		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9840	if (lun && lun->lun_devid)
9841		data_len += lun->lun_devid->len;
9842	if (port->port_devid)
9843		data_len += port->port_devid->len;
9844	if (port->target_devid)
9845		data_len += port->target_devid->len;
9846
9847	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9848	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9849	ctsio->kern_sg_entries = 0;
9850
9851	if (data_len < alloc_len) {
9852		ctsio->residual = alloc_len - data_len;
9853		ctsio->kern_data_len = data_len;
9854		ctsio->kern_total_len = data_len;
9855	} else {
9856		ctsio->residual = 0;
9857		ctsio->kern_data_len = alloc_len;
9858		ctsio->kern_total_len = alloc_len;
9859	}
9860	ctsio->kern_data_resid = 0;
9861	ctsio->kern_rel_offset = 0;
9862	ctsio->kern_sg_entries = 0;
9863
9864	/*
9865	 * The control device is always connected.  The disk device, on the
9866	 * other hand, may not be online all the time.
9867	 */
9868	if (lun != NULL)
9869		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9870				     lun->be_lun->lun_type;
9871	else
9872		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9873	devid_ptr->page_code = SVPD_DEVICE_ID;
9874	scsi_ulto2b(data_len - 4, devid_ptr->length);
9875
9876	if (port->port_type == CTL_PORT_FC)
9877		proto = SCSI_PROTO_FC << 4;
9878	else if (port->port_type == CTL_PORT_ISCSI)
9879		proto = SCSI_PROTO_ISCSI << 4;
9880	else
9881		proto = SCSI_PROTO_SPI << 4;
9882	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9883
9884	/*
9885	 * We're using a LUN association here.  i.e., this device ID is a
9886	 * per-LUN identifier.
9887	 */
9888	if (lun && lun->lun_devid) {
9889		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9890		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9891		    lun->lun_devid->len);
9892	}
9893
9894	/*
9895	 * This is for the WWPN which is a port association.
9896	 */
9897	if (port->port_devid) {
9898		memcpy(desc, port->port_devid->data, port->port_devid->len);
9899		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9900		    port->port_devid->len);
9901	}
9902
9903	/*
9904	 * This is for the Relative Target Port(type 4h) identifier
9905	 */
9906	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9907	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9908	    SVPD_ID_TYPE_RELTARG;
9909	desc->length = 4;
9910	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9911	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9912	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9913
9914	/*
9915	 * This is for the Target Port Group(type 5h) identifier
9916	 */
9917	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9918	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9919	    SVPD_ID_TYPE_TPORTGRP;
9920	desc->length = 4;
9921	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
9922	    &desc->identifier[2]);
9923	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9924	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9925
9926	/*
9927	 * This is for the Target identifier
9928	 */
9929	if (port->target_devid) {
9930		memcpy(desc, port->target_devid->data, port->target_devid->len);
9931	}
9932
9933	ctl_set_success(ctsio);
9934	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9935	ctsio->be_move_done = ctl_config_move_done;
9936	ctl_datamove((union ctl_io *)ctsio);
9937	return (CTL_RETVAL_COMPLETE);
9938}
9939
9940static int
9941ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9942{
9943	struct ctl_softc *softc = control_softc;
9944	struct scsi_vpd_scsi_ports *sp;
9945	struct scsi_vpd_port_designation *pd;
9946	struct scsi_vpd_port_designation_cont *pdc;
9947	struct ctl_lun *lun;
9948	struct ctl_port *port;
9949	int data_len, num_target_ports, iid_len, id_len, g, pg, p;
9950	int num_target_port_groups;
9951
9952	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9953
9954	if (softc->is_single)
9955		num_target_port_groups = 1;
9956	else
9957		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
9958	num_target_ports = 0;
9959	iid_len = 0;
9960	id_len = 0;
9961	mtx_lock(&softc->ctl_lock);
9962	STAILQ_FOREACH(port, &softc->port_list, links) {
9963		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9964			continue;
9965		if (lun != NULL &&
9966		    ctl_map_lun_back(softc, port->targ_port, lun->lun) >=
9967		    CTL_MAX_LUNS)
9968			continue;
9969		num_target_ports++;
9970		if (port->init_devid)
9971			iid_len += port->init_devid->len;
9972		if (port->port_devid)
9973			id_len += port->port_devid->len;
9974	}
9975	mtx_unlock(&softc->ctl_lock);
9976
9977	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
9978	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9979	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9980	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9981	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9982	ctsio->kern_sg_entries = 0;
9983
9984	if (data_len < alloc_len) {
9985		ctsio->residual = alloc_len - data_len;
9986		ctsio->kern_data_len = data_len;
9987		ctsio->kern_total_len = data_len;
9988	} else {
9989		ctsio->residual = 0;
9990		ctsio->kern_data_len = alloc_len;
9991		ctsio->kern_total_len = alloc_len;
9992	}
9993	ctsio->kern_data_resid = 0;
9994	ctsio->kern_rel_offset = 0;
9995	ctsio->kern_sg_entries = 0;
9996
9997	/*
9998	 * The control device is always connected.  The disk device, on the
9999	 * other hand, may not be online all the time.  Need to change this
10000	 * to figure out whether the disk device is actually online or not.
10001	 */
10002	if (lun != NULL)
10003		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10004				  lun->be_lun->lun_type;
10005	else
10006		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10007
10008	sp->page_code = SVPD_SCSI_PORTS;
10009	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10010	    sp->page_length);
10011	pd = &sp->design[0];
10012
10013	mtx_lock(&softc->ctl_lock);
10014	pg = softc->port_offset / CTL_MAX_PORTS;
10015	for (g = 0; g < num_target_port_groups; g++) {
10016		STAILQ_FOREACH(port, &softc->port_list, links) {
10017			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10018				continue;
10019			if (lun != NULL &&
10020			    ctl_map_lun_back(softc, port->targ_port, lun->lun)
10021			    >= CTL_MAX_LUNS)
10022				continue;
10023			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10024			scsi_ulto2b(p, pd->relative_port_id);
10025			if (port->init_devid && g == pg) {
10026				iid_len = port->init_devid->len;
10027				memcpy(pd->initiator_transportid,
10028				    port->init_devid->data, port->init_devid->len);
10029			} else
10030				iid_len = 0;
10031			scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10032			pdc = (struct scsi_vpd_port_designation_cont *)
10033			    (&pd->initiator_transportid[iid_len]);
10034			if (port->port_devid && g == pg) {
10035				id_len = port->port_devid->len;
10036				memcpy(pdc->target_port_descriptors,
10037				    port->port_devid->data, port->port_devid->len);
10038			} else
10039				id_len = 0;
10040			scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10041			pd = (struct scsi_vpd_port_designation *)
10042			    ((uint8_t *)pdc->target_port_descriptors + id_len);
10043		}
10044	}
10045	mtx_unlock(&softc->ctl_lock);
10046
10047	ctl_set_success(ctsio);
10048	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10049	ctsio->be_move_done = ctl_config_move_done;
10050	ctl_datamove((union ctl_io *)ctsio);
10051	return (CTL_RETVAL_COMPLETE);
10052}
10053
10054static int
10055ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10056{
10057	struct scsi_vpd_block_limits *bl_ptr;
10058	struct ctl_lun *lun;
10059	int bs;
10060
10061	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10062
10063	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10064	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10065	ctsio->kern_sg_entries = 0;
10066
10067	if (sizeof(*bl_ptr) < alloc_len) {
10068		ctsio->residual = alloc_len - sizeof(*bl_ptr);
10069		ctsio->kern_data_len = sizeof(*bl_ptr);
10070		ctsio->kern_total_len = sizeof(*bl_ptr);
10071	} else {
10072		ctsio->residual = 0;
10073		ctsio->kern_data_len = alloc_len;
10074		ctsio->kern_total_len = alloc_len;
10075	}
10076	ctsio->kern_data_resid = 0;
10077	ctsio->kern_rel_offset = 0;
10078	ctsio->kern_sg_entries = 0;
10079
10080	/*
10081	 * The control device is always connected.  The disk device, on the
10082	 * other hand, may not be online all the time.  Need to change this
10083	 * to figure out whether the disk device is actually online or not.
10084	 */
10085	if (lun != NULL)
10086		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10087				  lun->be_lun->lun_type;
10088	else
10089		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10090
10091	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10092	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10093	bl_ptr->max_cmp_write_len = 0xff;
10094	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10095	if (lun != NULL) {
10096		bs = lun->be_lun->blocksize;
10097		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
10098		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10099			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10100			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10101			if (lun->be_lun->ublockexp != 0) {
10102				scsi_ulto4b((1 << lun->be_lun->ublockexp),
10103				    bl_ptr->opt_unmap_grain);
10104				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
10105				    bl_ptr->unmap_grain_align);
10106			}
10107		}
10108		scsi_ulto4b(lun->be_lun->atomicblock,
10109		    bl_ptr->max_atomic_transfer_length);
10110		scsi_ulto4b(0, bl_ptr->atomic_alignment);
10111		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10112	}
10113	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10114
10115	ctl_set_success(ctsio);
10116	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10117	ctsio->be_move_done = ctl_config_move_done;
10118	ctl_datamove((union ctl_io *)ctsio);
10119	return (CTL_RETVAL_COMPLETE);
10120}
10121
10122static int
10123ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10124{
10125	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10126	struct ctl_lun *lun;
10127	const char *value;
10128	u_int i;
10129
10130	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10131
10132	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10133	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10134	ctsio->kern_sg_entries = 0;
10135
10136	if (sizeof(*bdc_ptr) < alloc_len) {
10137		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10138		ctsio->kern_data_len = sizeof(*bdc_ptr);
10139		ctsio->kern_total_len = sizeof(*bdc_ptr);
10140	} else {
10141		ctsio->residual = 0;
10142		ctsio->kern_data_len = alloc_len;
10143		ctsio->kern_total_len = alloc_len;
10144	}
10145	ctsio->kern_data_resid = 0;
10146	ctsio->kern_rel_offset = 0;
10147	ctsio->kern_sg_entries = 0;
10148
10149	/*
10150	 * The control device is always connected.  The disk device, on the
10151	 * other hand, may not be online all the time.  Need to change this
10152	 * to figure out whether the disk device is actually online or not.
10153	 */
10154	if (lun != NULL)
10155		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10156				  lun->be_lun->lun_type;
10157	else
10158		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10159	bdc_ptr->page_code = SVPD_BDC;
10160	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10161	if (lun != NULL &&
10162	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10163		i = strtol(value, NULL, 0);
10164	else
10165		i = CTL_DEFAULT_ROTATION_RATE;
10166	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10167	if (lun != NULL &&
10168	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10169		i = strtol(value, NULL, 0);
10170	else
10171		i = 0;
10172	bdc_ptr->wab_wac_ff = (i & 0x0f);
10173	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10174
10175	ctl_set_success(ctsio);
10176	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10177	ctsio->be_move_done = ctl_config_move_done;
10178	ctl_datamove((union ctl_io *)ctsio);
10179	return (CTL_RETVAL_COMPLETE);
10180}
10181
10182static int
10183ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10184{
10185	struct scsi_vpd_logical_block_prov *lbp_ptr;
10186	struct ctl_lun *lun;
10187
10188	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10189
10190	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10191	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10192	ctsio->kern_sg_entries = 0;
10193
10194	if (sizeof(*lbp_ptr) < alloc_len) {
10195		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10196		ctsio->kern_data_len = sizeof(*lbp_ptr);
10197		ctsio->kern_total_len = sizeof(*lbp_ptr);
10198	} else {
10199		ctsio->residual = 0;
10200		ctsio->kern_data_len = alloc_len;
10201		ctsio->kern_total_len = alloc_len;
10202	}
10203	ctsio->kern_data_resid = 0;
10204	ctsio->kern_rel_offset = 0;
10205	ctsio->kern_sg_entries = 0;
10206
10207	/*
10208	 * The control device is always connected.  The disk device, on the
10209	 * other hand, may not be online all the time.  Need to change this
10210	 * to figure out whether the disk device is actually online or not.
10211	 */
10212	if (lun != NULL)
10213		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10214				  lun->be_lun->lun_type;
10215	else
10216		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10217
10218	lbp_ptr->page_code = SVPD_LBP;
10219	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10220	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10221	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10222		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10223		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10224		lbp_ptr->prov_type = SVPD_LBP_THIN;
10225	}
10226
10227	ctl_set_success(ctsio);
10228	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10229	ctsio->be_move_done = ctl_config_move_done;
10230	ctl_datamove((union ctl_io *)ctsio);
10231	return (CTL_RETVAL_COMPLETE);
10232}
10233
10234static int
10235ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10236{
10237	struct scsi_inquiry *cdb;
10238	int alloc_len, retval;
10239
10240	cdb = (struct scsi_inquiry *)ctsio->cdb;
10241
10242	retval = CTL_RETVAL_COMPLETE;
10243
10244	alloc_len = scsi_2btoul(cdb->length);
10245
10246	switch (cdb->page_code) {
10247	case SVPD_SUPPORTED_PAGES:
10248		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10249		break;
10250	case SVPD_UNIT_SERIAL_NUMBER:
10251		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10252		break;
10253	case SVPD_DEVICE_ID:
10254		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10255		break;
10256	case SVPD_EXTENDED_INQUIRY_DATA:
10257		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10258		break;
10259	case SVPD_MODE_PAGE_POLICY:
10260		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10261		break;
10262	case SVPD_SCSI_PORTS:
10263		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10264		break;
10265	case SVPD_SCSI_TPC:
10266		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10267		break;
10268	case SVPD_BLOCK_LIMITS:
10269		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10270		break;
10271	case SVPD_BDC:
10272		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10273		break;
10274	case SVPD_LBP:
10275		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10276		break;
10277	default:
10278		ctl_set_invalid_field(ctsio,
10279				      /*sks_valid*/ 1,
10280				      /*command*/ 1,
10281				      /*field*/ 2,
10282				      /*bit_valid*/ 0,
10283				      /*bit*/ 0);
10284		ctl_done((union ctl_io *)ctsio);
10285		retval = CTL_RETVAL_COMPLETE;
10286		break;
10287	}
10288
10289	return (retval);
10290}
10291
10292static int
10293ctl_inquiry_std(struct ctl_scsiio *ctsio)
10294{
10295	struct scsi_inquiry_data *inq_ptr;
10296	struct scsi_inquiry *cdb;
10297	struct ctl_softc *softc;
10298	struct ctl_lun *lun;
10299	char *val;
10300	uint32_t alloc_len, data_len;
10301	ctl_port_type port_type;
10302
10303	softc = control_softc;
10304
10305	/*
10306	 * Figure out whether we're talking to a Fibre Channel port or not.
10307	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10308	 * SCSI front ends.
10309	 */
10310	port_type = softc->ctl_ports[
10311	    ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10312	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10313		port_type = CTL_PORT_SCSI;
10314
10315	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10316	cdb = (struct scsi_inquiry *)ctsio->cdb;
10317	alloc_len = scsi_2btoul(cdb->length);
10318
10319	/*
10320	 * We malloc the full inquiry data size here and fill it
10321	 * in.  If the user only asks for less, we'll give him
10322	 * that much.
10323	 */
10324	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10325	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10326	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10327	ctsio->kern_sg_entries = 0;
10328	ctsio->kern_data_resid = 0;
10329	ctsio->kern_rel_offset = 0;
10330
10331	if (data_len < alloc_len) {
10332		ctsio->residual = alloc_len - data_len;
10333		ctsio->kern_data_len = data_len;
10334		ctsio->kern_total_len = data_len;
10335	} else {
10336		ctsio->residual = 0;
10337		ctsio->kern_data_len = alloc_len;
10338		ctsio->kern_total_len = alloc_len;
10339	}
10340
10341	/*
10342	 * If we have a LUN configured, report it as connected.  Otherwise,
10343	 * report that it is offline or no device is supported, depending
10344	 * on the value of inquiry_pq_no_lun.
10345	 *
10346	 * According to the spec (SPC-4 r34), the peripheral qualifier
10347	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10348	 *
10349	 * "A peripheral device having the specified peripheral device type
10350	 * is not connected to this logical unit. However, the device
10351	 * server is capable of supporting the specified peripheral device
10352	 * type on this logical unit."
10353	 *
10354	 * According to the same spec, the peripheral qualifier
10355	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10356	 *
10357	 * "The device server is not capable of supporting a peripheral
10358	 * device on this logical unit. For this peripheral qualifier the
10359	 * peripheral device type shall be set to 1Fh. All other peripheral
10360	 * device type values are reserved for this peripheral qualifier."
10361	 *
10362	 * Given the text, it would seem that we probably want to report that
10363	 * the LUN is offline here.  There is no LUN connected, but we can
10364	 * support a LUN at the given LUN number.
10365	 *
10366	 * In the real world, though, it sounds like things are a little
10367	 * different:
10368	 *
10369	 * - Linux, when presented with a LUN with the offline peripheral
10370	 *   qualifier, will create an sg driver instance for it.  So when
10371	 *   you attach it to CTL, you wind up with a ton of sg driver
10372	 *   instances.  (One for every LUN that Linux bothered to probe.)
10373	 *   Linux does this despite the fact that it issues a REPORT LUNs
10374	 *   to LUN 0 to get the inventory of supported LUNs.
10375	 *
10376	 * - There is other anecdotal evidence (from Emulex folks) about
10377	 *   arrays that use the offline peripheral qualifier for LUNs that
10378	 *   are on the "passive" path in an active/passive array.
10379	 *
10380	 * So the solution is provide a hopefully reasonable default
10381	 * (return bad/no LUN) and allow the user to change the behavior
10382	 * with a tunable/sysctl variable.
10383	 */
10384	if (lun != NULL)
10385		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10386				  lun->be_lun->lun_type;
10387	else if (softc->inquiry_pq_no_lun == 0)
10388		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10389	else
10390		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10391
10392	/* RMB in byte 2 is 0 */
10393	inq_ptr->version = SCSI_REV_SPC4;
10394
10395	/*
10396	 * According to SAM-3, even if a device only supports a single
10397	 * level of LUN addressing, it should still set the HISUP bit:
10398	 *
10399	 * 4.9.1 Logical unit numbers overview
10400	 *
10401	 * All logical unit number formats described in this standard are
10402	 * hierarchical in structure even when only a single level in that
10403	 * hierarchy is used. The HISUP bit shall be set to one in the
10404	 * standard INQUIRY data (see SPC-2) when any logical unit number
10405	 * format described in this standard is used.  Non-hierarchical
10406	 * formats are outside the scope of this standard.
10407	 *
10408	 * Therefore we set the HiSup bit here.
10409	 *
10410	 * The reponse format is 2, per SPC-3.
10411	 */
10412	inq_ptr->response_format = SID_HiSup | 2;
10413
10414	inq_ptr->additional_length = data_len -
10415	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10416	CTL_DEBUG_PRINT(("additional_length = %d\n",
10417			 inq_ptr->additional_length));
10418
10419	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10420	/* 16 bit addressing */
10421	if (port_type == CTL_PORT_SCSI)
10422		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10423	/* XXX set the SID_MultiP bit here if we're actually going to
10424	   respond on multiple ports */
10425	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10426
10427	/* 16 bit data bus, synchronous transfers */
10428	if (port_type == CTL_PORT_SCSI)
10429		inq_ptr->flags = SID_WBus16 | SID_Sync;
10430	/*
10431	 * XXX KDM do we want to support tagged queueing on the control
10432	 * device at all?
10433	 */
10434	if ((lun == NULL)
10435	 || (lun->be_lun->lun_type != T_PROCESSOR))
10436		inq_ptr->flags |= SID_CmdQue;
10437	/*
10438	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10439	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10440	 * name and 4 bytes for the revision.
10441	 */
10442	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10443	    "vendor")) == NULL) {
10444		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10445	} else {
10446		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10447		strncpy(inq_ptr->vendor, val,
10448		    min(sizeof(inq_ptr->vendor), strlen(val)));
10449	}
10450	if (lun == NULL) {
10451		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10452		    sizeof(inq_ptr->product));
10453	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10454		switch (lun->be_lun->lun_type) {
10455		case T_DIRECT:
10456			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10457			    sizeof(inq_ptr->product));
10458			break;
10459		case T_PROCESSOR:
10460			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10461			    sizeof(inq_ptr->product));
10462			break;
10463		default:
10464			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10465			    sizeof(inq_ptr->product));
10466			break;
10467		}
10468	} else {
10469		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10470		strncpy(inq_ptr->product, val,
10471		    min(sizeof(inq_ptr->product), strlen(val)));
10472	}
10473
10474	/*
10475	 * XXX make this a macro somewhere so it automatically gets
10476	 * incremented when we make changes.
10477	 */
10478	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10479	    "revision")) == NULL) {
10480		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10481	} else {
10482		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10483		strncpy(inq_ptr->revision, val,
10484		    min(sizeof(inq_ptr->revision), strlen(val)));
10485	}
10486
10487	/*
10488	 * For parallel SCSI, we support double transition and single
10489	 * transition clocking.  We also support QAS (Quick Arbitration
10490	 * and Selection) and Information Unit transfers on both the
10491	 * control and array devices.
10492	 */
10493	if (port_type == CTL_PORT_SCSI)
10494		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10495				    SID_SPI_IUS;
10496
10497	/* SAM-5 (no version claimed) */
10498	scsi_ulto2b(0x00A0, inq_ptr->version1);
10499	/* SPC-4 (no version claimed) */
10500	scsi_ulto2b(0x0460, inq_ptr->version2);
10501	if (port_type == CTL_PORT_FC) {
10502		/* FCP-2 ANSI INCITS.350:2003 */
10503		scsi_ulto2b(0x0917, inq_ptr->version3);
10504	} else if (port_type == CTL_PORT_SCSI) {
10505		/* SPI-4 ANSI INCITS.362:200x */
10506		scsi_ulto2b(0x0B56, inq_ptr->version3);
10507	} else if (port_type == CTL_PORT_ISCSI) {
10508		/* iSCSI (no version claimed) */
10509		scsi_ulto2b(0x0960, inq_ptr->version3);
10510	} else if (port_type == CTL_PORT_SAS) {
10511		/* SAS (no version claimed) */
10512		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10513	}
10514
10515	if (lun == NULL) {
10516		/* SBC-4 (no version claimed) */
10517		scsi_ulto2b(0x0600, inq_ptr->version4);
10518	} else {
10519		switch (lun->be_lun->lun_type) {
10520		case T_DIRECT:
10521			/* SBC-4 (no version claimed) */
10522			scsi_ulto2b(0x0600, inq_ptr->version4);
10523			break;
10524		case T_PROCESSOR:
10525		default:
10526			break;
10527		}
10528	}
10529
10530	ctl_set_success(ctsio);
10531	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10532	ctsio->be_move_done = ctl_config_move_done;
10533	ctl_datamove((union ctl_io *)ctsio);
10534	return (CTL_RETVAL_COMPLETE);
10535}
10536
10537int
10538ctl_inquiry(struct ctl_scsiio *ctsio)
10539{
10540	struct scsi_inquiry *cdb;
10541	int retval;
10542
10543	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10544
10545	cdb = (struct scsi_inquiry *)ctsio->cdb;
10546	if (cdb->byte2 & SI_EVPD)
10547		retval = ctl_inquiry_evpd(ctsio);
10548	else if (cdb->page_code == 0)
10549		retval = ctl_inquiry_std(ctsio);
10550	else {
10551		ctl_set_invalid_field(ctsio,
10552				      /*sks_valid*/ 1,
10553				      /*command*/ 1,
10554				      /*field*/ 2,
10555				      /*bit_valid*/ 0,
10556				      /*bit*/ 0);
10557		ctl_done((union ctl_io *)ctsio);
10558		return (CTL_RETVAL_COMPLETE);
10559	}
10560
10561	return (retval);
10562}
10563
10564/*
10565 * For known CDB types, parse the LBA and length.
10566 */
10567static int
10568ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10569{
10570	if (io->io_hdr.io_type != CTL_IO_SCSI)
10571		return (1);
10572
10573	switch (io->scsiio.cdb[0]) {
10574	case COMPARE_AND_WRITE: {
10575		struct scsi_compare_and_write *cdb;
10576
10577		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10578
10579		*lba = scsi_8btou64(cdb->addr);
10580		*len = cdb->length;
10581		break;
10582	}
10583	case READ_6:
10584	case WRITE_6: {
10585		struct scsi_rw_6 *cdb;
10586
10587		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10588
10589		*lba = scsi_3btoul(cdb->addr);
10590		/* only 5 bits are valid in the most significant address byte */
10591		*lba &= 0x1fffff;
10592		*len = cdb->length;
10593		break;
10594	}
10595	case READ_10:
10596	case WRITE_10: {
10597		struct scsi_rw_10 *cdb;
10598
10599		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10600
10601		*lba = scsi_4btoul(cdb->addr);
10602		*len = scsi_2btoul(cdb->length);
10603		break;
10604	}
10605	case WRITE_VERIFY_10: {
10606		struct scsi_write_verify_10 *cdb;
10607
10608		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10609
10610		*lba = scsi_4btoul(cdb->addr);
10611		*len = scsi_2btoul(cdb->length);
10612		break;
10613	}
10614	case READ_12:
10615	case WRITE_12: {
10616		struct scsi_rw_12 *cdb;
10617
10618		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10619
10620		*lba = scsi_4btoul(cdb->addr);
10621		*len = scsi_4btoul(cdb->length);
10622		break;
10623	}
10624	case WRITE_VERIFY_12: {
10625		struct scsi_write_verify_12 *cdb;
10626
10627		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10628
10629		*lba = scsi_4btoul(cdb->addr);
10630		*len = scsi_4btoul(cdb->length);
10631		break;
10632	}
10633	case READ_16:
10634	case WRITE_16:
10635	case WRITE_ATOMIC_16: {
10636		struct scsi_rw_16 *cdb;
10637
10638		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10639
10640		*lba = scsi_8btou64(cdb->addr);
10641		*len = scsi_4btoul(cdb->length);
10642		break;
10643	}
10644	case WRITE_VERIFY_16: {
10645		struct scsi_write_verify_16 *cdb;
10646
10647		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10648
10649		*lba = scsi_8btou64(cdb->addr);
10650		*len = scsi_4btoul(cdb->length);
10651		break;
10652	}
10653	case WRITE_SAME_10: {
10654		struct scsi_write_same_10 *cdb;
10655
10656		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10657
10658		*lba = scsi_4btoul(cdb->addr);
10659		*len = scsi_2btoul(cdb->length);
10660		break;
10661	}
10662	case WRITE_SAME_16: {
10663		struct scsi_write_same_16 *cdb;
10664
10665		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10666
10667		*lba = scsi_8btou64(cdb->addr);
10668		*len = scsi_4btoul(cdb->length);
10669		break;
10670	}
10671	case VERIFY_10: {
10672		struct scsi_verify_10 *cdb;
10673
10674		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10675
10676		*lba = scsi_4btoul(cdb->addr);
10677		*len = scsi_2btoul(cdb->length);
10678		break;
10679	}
10680	case VERIFY_12: {
10681		struct scsi_verify_12 *cdb;
10682
10683		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10684
10685		*lba = scsi_4btoul(cdb->addr);
10686		*len = scsi_4btoul(cdb->length);
10687		break;
10688	}
10689	case VERIFY_16: {
10690		struct scsi_verify_16 *cdb;
10691
10692		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10693
10694		*lba = scsi_8btou64(cdb->addr);
10695		*len = scsi_4btoul(cdb->length);
10696		break;
10697	}
10698	case UNMAP: {
10699		*lba = 0;
10700		*len = UINT64_MAX;
10701		break;
10702	}
10703	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10704		struct scsi_get_lba_status *cdb;
10705
10706		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10707		*lba = scsi_8btou64(cdb->addr);
10708		*len = UINT32_MAX;
10709		break;
10710	}
10711	default:
10712		return (1);
10713		break; /* NOTREACHED */
10714	}
10715
10716	return (0);
10717}
10718
10719static ctl_action
10720ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10721    bool seq)
10722{
10723	uint64_t endlba1, endlba2;
10724
10725	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10726	endlba2 = lba2 + len2 - 1;
10727
10728	if ((endlba1 < lba2) || (endlba2 < lba1))
10729		return (CTL_ACTION_PASS);
10730	else
10731		return (CTL_ACTION_BLOCK);
10732}
10733
10734static int
10735ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10736{
10737	struct ctl_ptr_len_flags *ptrlen;
10738	struct scsi_unmap_desc *buf, *end, *range;
10739	uint64_t lba;
10740	uint32_t len;
10741
10742	/* If not UNMAP -- go other way. */
10743	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10744	    io->scsiio.cdb[0] != UNMAP)
10745		return (CTL_ACTION_ERROR);
10746
10747	/* If UNMAP without data -- block and wait for data. */
10748	ptrlen = (struct ctl_ptr_len_flags *)
10749	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10750	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10751	    ptrlen->ptr == NULL)
10752		return (CTL_ACTION_BLOCK);
10753
10754	/* UNMAP with data -- check for collision. */
10755	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10756	end = buf + ptrlen->len / sizeof(*buf);
10757	for (range = buf; range < end; range++) {
10758		lba = scsi_8btou64(range->lba);
10759		len = scsi_4btoul(range->length);
10760		if ((lba < lba2 + len2) && (lba + len > lba2))
10761			return (CTL_ACTION_BLOCK);
10762	}
10763	return (CTL_ACTION_PASS);
10764}
10765
10766static ctl_action
10767ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10768{
10769	uint64_t lba1, lba2;
10770	uint64_t len1, len2;
10771	int retval;
10772
10773	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10774		return (CTL_ACTION_ERROR);
10775
10776	retval = ctl_extent_check_unmap(io1, lba2, len2);
10777	if (retval != CTL_ACTION_ERROR)
10778		return (retval);
10779
10780	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10781		return (CTL_ACTION_ERROR);
10782
10783	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10784}
10785
10786static ctl_action
10787ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10788{
10789	uint64_t lba1, lba2;
10790	uint64_t len1, len2;
10791
10792	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10793		return (CTL_ACTION_ERROR);
10794	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10795		return (CTL_ACTION_ERROR);
10796
10797	if (lba1 + len1 == lba2)
10798		return (CTL_ACTION_BLOCK);
10799	return (CTL_ACTION_PASS);
10800}
10801
10802static ctl_action
10803ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10804    union ctl_io *ooa_io)
10805{
10806	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10807	ctl_serialize_action *serialize_row;
10808
10809	/*
10810	 * The initiator attempted multiple untagged commands at the same
10811	 * time.  Can't do that.
10812	 */
10813	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10814	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10815	 && ((pending_io->io_hdr.nexus.targ_port ==
10816	      ooa_io->io_hdr.nexus.targ_port)
10817	  && (pending_io->io_hdr.nexus.initid.id ==
10818	      ooa_io->io_hdr.nexus.initid.id))
10819	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10820		return (CTL_ACTION_OVERLAP);
10821
10822	/*
10823	 * The initiator attempted to send multiple tagged commands with
10824	 * the same ID.  (It's fine if different initiators have the same
10825	 * tag ID.)
10826	 *
10827	 * Even if all of those conditions are true, we don't kill the I/O
10828	 * if the command ahead of us has been aborted.  We won't end up
10829	 * sending it to the FETD, and it's perfectly legal to resend a
10830	 * command with the same tag number as long as the previous
10831	 * instance of this tag number has been aborted somehow.
10832	 */
10833	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10834	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10835	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10836	 && ((pending_io->io_hdr.nexus.targ_port ==
10837	      ooa_io->io_hdr.nexus.targ_port)
10838	  && (pending_io->io_hdr.nexus.initid.id ==
10839	      ooa_io->io_hdr.nexus.initid.id))
10840	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10841		return (CTL_ACTION_OVERLAP_TAG);
10842
10843	/*
10844	 * If we get a head of queue tag, SAM-3 says that we should
10845	 * immediately execute it.
10846	 *
10847	 * What happens if this command would normally block for some other
10848	 * reason?  e.g. a request sense with a head of queue tag
10849	 * immediately after a write.  Normally that would block, but this
10850	 * will result in its getting executed immediately...
10851	 *
10852	 * We currently return "pass" instead of "skip", so we'll end up
10853	 * going through the rest of the queue to check for overlapped tags.
10854	 *
10855	 * XXX KDM check for other types of blockage first??
10856	 */
10857	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10858		return (CTL_ACTION_PASS);
10859
10860	/*
10861	 * Ordered tags have to block until all items ahead of them
10862	 * have completed.  If we get called with an ordered tag, we always
10863	 * block, if something else is ahead of us in the queue.
10864	 */
10865	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10866		return (CTL_ACTION_BLOCK);
10867
10868	/*
10869	 * Simple tags get blocked until all head of queue and ordered tags
10870	 * ahead of them have completed.  I'm lumping untagged commands in
10871	 * with simple tags here.  XXX KDM is that the right thing to do?
10872	 */
10873	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10874	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10875	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10876	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10877		return (CTL_ACTION_BLOCK);
10878
10879	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10880	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10881
10882	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10883
10884	switch (serialize_row[pending_entry->seridx]) {
10885	case CTL_SER_BLOCK:
10886		return (CTL_ACTION_BLOCK);
10887	case CTL_SER_EXTENT:
10888		return (ctl_extent_check(ooa_io, pending_io,
10889		    (lun->serseq == CTL_LUN_SERSEQ_ON)));
10890	case CTL_SER_EXTENTOPT:
10891		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10892		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10893			return (ctl_extent_check(ooa_io, pending_io,
10894			    (lun->serseq == CTL_LUN_SERSEQ_ON)));
10895		return (CTL_ACTION_PASS);
10896	case CTL_SER_EXTENTSEQ:
10897		if (lun->serseq != CTL_LUN_SERSEQ_OFF)
10898			return (ctl_extent_check_seq(ooa_io, pending_io));
10899		return (CTL_ACTION_PASS);
10900	case CTL_SER_PASS:
10901		return (CTL_ACTION_PASS);
10902	case CTL_SER_BLOCKOPT:
10903		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10904		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10905			return (CTL_ACTION_BLOCK);
10906		return (CTL_ACTION_PASS);
10907	case CTL_SER_SKIP:
10908		return (CTL_ACTION_SKIP);
10909	default:
10910		panic("invalid serialization value %d",
10911		      serialize_row[pending_entry->seridx]);
10912	}
10913
10914	return (CTL_ACTION_ERROR);
10915}
10916
10917/*
10918 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10919 * Assumptions:
10920 * - pending_io is generally either incoming, or on the blocked queue
10921 * - starting I/O is the I/O we want to start the check with.
10922 */
10923static ctl_action
10924ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10925	      union ctl_io *starting_io)
10926{
10927	union ctl_io *ooa_io;
10928	ctl_action action;
10929
10930	mtx_assert(&lun->lun_lock, MA_OWNED);
10931
10932	/*
10933	 * Run back along the OOA queue, starting with the current
10934	 * blocked I/O and going through every I/O before it on the
10935	 * queue.  If starting_io is NULL, we'll just end up returning
10936	 * CTL_ACTION_PASS.
10937	 */
10938	for (ooa_io = starting_io; ooa_io != NULL;
10939	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10940	     ooa_links)){
10941
10942		/*
10943		 * This routine just checks to see whether
10944		 * cur_blocked is blocked by ooa_io, which is ahead
10945		 * of it in the queue.  It doesn't queue/dequeue
10946		 * cur_blocked.
10947		 */
10948		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10949		switch (action) {
10950		case CTL_ACTION_BLOCK:
10951		case CTL_ACTION_OVERLAP:
10952		case CTL_ACTION_OVERLAP_TAG:
10953		case CTL_ACTION_SKIP:
10954		case CTL_ACTION_ERROR:
10955			return (action);
10956			break; /* NOTREACHED */
10957		case CTL_ACTION_PASS:
10958			break;
10959		default:
10960			panic("invalid action %d", action);
10961			break;  /* NOTREACHED */
10962		}
10963	}
10964
10965	return (CTL_ACTION_PASS);
10966}
10967
10968/*
10969 * Assumptions:
10970 * - An I/O has just completed, and has been removed from the per-LUN OOA
10971 *   queue, so some items on the blocked queue may now be unblocked.
10972 */
10973static int
10974ctl_check_blocked(struct ctl_lun *lun)
10975{
10976	union ctl_io *cur_blocked, *next_blocked;
10977
10978	mtx_assert(&lun->lun_lock, MA_OWNED);
10979
10980	/*
10981	 * Run forward from the head of the blocked queue, checking each
10982	 * entry against the I/Os prior to it on the OOA queue to see if
10983	 * there is still any blockage.
10984	 *
10985	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10986	 * with our removing a variable on it while it is traversing the
10987	 * list.
10988	 */
10989	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10990	     cur_blocked != NULL; cur_blocked = next_blocked) {
10991		union ctl_io *prev_ooa;
10992		ctl_action action;
10993
10994		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10995							  blocked_links);
10996
10997		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10998						      ctl_ooaq, ooa_links);
10999
11000		/*
11001		 * If cur_blocked happens to be the first item in the OOA
11002		 * queue now, prev_ooa will be NULL, and the action
11003		 * returned will just be CTL_ACTION_PASS.
11004		 */
11005		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11006
11007		switch (action) {
11008		case CTL_ACTION_BLOCK:
11009			/* Nothing to do here, still blocked */
11010			break;
11011		case CTL_ACTION_OVERLAP:
11012		case CTL_ACTION_OVERLAP_TAG:
11013			/*
11014			 * This shouldn't happen!  In theory we've already
11015			 * checked this command for overlap...
11016			 */
11017			break;
11018		case CTL_ACTION_PASS:
11019		case CTL_ACTION_SKIP: {
11020			const struct ctl_cmd_entry *entry;
11021			int isc_retval;
11022
11023			/*
11024			 * The skip case shouldn't happen, this transaction
11025			 * should have never made it onto the blocked queue.
11026			 */
11027			/*
11028			 * This I/O is no longer blocked, we can remove it
11029			 * from the blocked queue.  Since this is a TAILQ
11030			 * (doubly linked list), we can do O(1) removals
11031			 * from any place on the list.
11032			 */
11033			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11034				     blocked_links);
11035			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11036
11037			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11038				/*
11039				 * Need to send IO back to original side to
11040				 * run
11041				 */
11042				union ctl_ha_msg msg_info;
11043
11044				msg_info.hdr.original_sc =
11045					cur_blocked->io_hdr.original_sc;
11046				msg_info.hdr.serializing_sc = cur_blocked;
11047				msg_info.hdr.msg_type = CTL_MSG_R2R;
11048				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11049				     &msg_info, sizeof(msg_info), 0)) >
11050				     CTL_HA_STATUS_SUCCESS) {
11051					printf("CTL:Check Blocked error from "
11052					       "ctl_ha_msg_send %d\n",
11053					       isc_retval);
11054				}
11055				break;
11056			}
11057			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11058
11059			/*
11060			 * Check this I/O for LUN state changes that may
11061			 * have happened while this command was blocked.
11062			 * The LUN state may have been changed by a command
11063			 * ahead of us in the queue, so we need to re-check
11064			 * for any states that can be caused by SCSI
11065			 * commands.
11066			 */
11067			if (ctl_scsiio_lun_check(lun, entry,
11068						 &cur_blocked->scsiio) == 0) {
11069				cur_blocked->io_hdr.flags |=
11070				                      CTL_FLAG_IS_WAS_ON_RTR;
11071				ctl_enqueue_rtr(cur_blocked);
11072			} else
11073				ctl_done(cur_blocked);
11074			break;
11075		}
11076		default:
11077			/*
11078			 * This probably shouldn't happen -- we shouldn't
11079			 * get CTL_ACTION_ERROR, or anything else.
11080			 */
11081			break;
11082		}
11083	}
11084
11085	return (CTL_RETVAL_COMPLETE);
11086}
11087
11088/*
11089 * This routine (with one exception) checks LUN flags that can be set by
11090 * commands ahead of us in the OOA queue.  These flags have to be checked
11091 * when a command initially comes in, and when we pull a command off the
11092 * blocked queue and are preparing to execute it.  The reason we have to
11093 * check these flags for commands on the blocked queue is that the LUN
11094 * state may have been changed by a command ahead of us while we're on the
11095 * blocked queue.
11096 *
11097 * Ordering is somewhat important with these checks, so please pay
11098 * careful attention to the placement of any new checks.
11099 */
11100static int
11101ctl_scsiio_lun_check(struct ctl_lun *lun,
11102    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11103{
11104	struct ctl_softc *softc = lun->ctl_softc;
11105	int retval;
11106	uint32_t residx;
11107
11108	retval = 0;
11109
11110	mtx_assert(&lun->lun_lock, MA_OWNED);
11111
11112	/*
11113	 * If this shelf is a secondary shelf controller, we have to reject
11114	 * any media access commands.
11115	 */
11116	if ((softc->flags & CTL_FLAG_ACTIVE_SHELF) == 0 &&
11117	    (entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0) {
11118		ctl_set_lun_standby(ctsio);
11119		retval = 1;
11120		goto bailout;
11121	}
11122
11123	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11124		if (lun->flags & CTL_LUN_READONLY) {
11125			ctl_set_sense(ctsio, /*current_error*/ 1,
11126			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11127			    /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11128			retval = 1;
11129			goto bailout;
11130		}
11131		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11132		    .eca_and_aen & SCP_SWP) != 0) {
11133			ctl_set_sense(ctsio, /*current_error*/ 1,
11134			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11135			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11136			retval = 1;
11137			goto bailout;
11138		}
11139	}
11140
11141	/*
11142	 * Check for a reservation conflict.  If this command isn't allowed
11143	 * even on reserved LUNs, and if this initiator isn't the one who
11144	 * reserved us, reject the command with a reservation conflict.
11145	 */
11146	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11147	if ((lun->flags & CTL_LUN_RESERVED)
11148	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11149		if (lun->res_idx != residx) {
11150			ctl_set_reservation_conflict(ctsio);
11151			retval = 1;
11152			goto bailout;
11153		}
11154	}
11155
11156	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11157	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11158		/* No reservation or command is allowed. */;
11159	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11160	    (lun->res_type == SPR_TYPE_WR_EX ||
11161	     lun->res_type == SPR_TYPE_WR_EX_RO ||
11162	     lun->res_type == SPR_TYPE_WR_EX_AR)) {
11163		/* The command is allowed for Write Exclusive resv. */;
11164	} else {
11165		/*
11166		 * if we aren't registered or it's a res holder type
11167		 * reservation and this isn't the res holder then set a
11168		 * conflict.
11169		 */
11170		if (ctl_get_prkey(lun, residx) == 0
11171		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11172			ctl_set_reservation_conflict(ctsio);
11173			retval = 1;
11174			goto bailout;
11175		}
11176
11177	}
11178
11179	if ((lun->flags & CTL_LUN_OFFLINE)
11180	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11181		ctl_set_lun_not_ready(ctsio);
11182		retval = 1;
11183		goto bailout;
11184	}
11185
11186	/*
11187	 * If the LUN is stopped, see if this particular command is allowed
11188	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11189	 */
11190	if ((lun->flags & CTL_LUN_STOPPED)
11191	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11192		/* "Logical unit not ready, initializing cmd. required" */
11193		ctl_set_lun_stopped(ctsio);
11194		retval = 1;
11195		goto bailout;
11196	}
11197
11198	if ((lun->flags & CTL_LUN_INOPERABLE)
11199	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11200		/* "Medium format corrupted" */
11201		ctl_set_medium_format_corrupted(ctsio);
11202		retval = 1;
11203		goto bailout;
11204	}
11205
11206bailout:
11207	return (retval);
11208
11209}
11210
11211static void
11212ctl_failover_io(union ctl_io *io, int have_lock)
11213{
11214	ctl_set_busy(&io->scsiio);
11215	ctl_done(io);
11216}
11217
11218static void
11219ctl_failover(void)
11220{
11221	struct ctl_lun *lun;
11222	struct ctl_softc *softc;
11223	union ctl_io *next_io, *pending_io;
11224	union ctl_io *io;
11225	int lun_idx;
11226
11227	softc = control_softc;
11228
11229	mtx_lock(&softc->ctl_lock);
11230	/*
11231	 * Remove any cmds from the other SC from the rtr queue.  These
11232	 * will obviously only be for LUNs for which we're the primary.
11233	 * We can't send status or get/send data for these commands.
11234	 * Since they haven't been executed yet, we can just remove them.
11235	 * We'll either abort them or delete them below, depending on
11236	 * which HA mode we're in.
11237	 */
11238#ifdef notyet
11239	mtx_lock(&softc->queue_lock);
11240	for (io = (union ctl_io *)STAILQ_FIRST(&softc->rtr_queue);
11241	     io != NULL; io = next_io) {
11242		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11243		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11244			STAILQ_REMOVE(&softc->rtr_queue, &io->io_hdr,
11245				      ctl_io_hdr, links);
11246	}
11247	mtx_unlock(&softc->queue_lock);
11248#endif
11249
11250	for (lun_idx=0; lun_idx < softc->num_luns; lun_idx++) {
11251		lun = softc->ctl_luns[lun_idx];
11252		if (lun==NULL)
11253			continue;
11254
11255		/*
11256		 * Processor LUNs are primary on both sides.
11257		 * XXX will this always be true?
11258		 */
11259		if (lun->be_lun->lun_type == T_PROCESSOR)
11260			continue;
11261
11262		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11263		 && (softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11264			printf("FAILOVER: primary lun %d\n", lun_idx);
11265		        /*
11266			 * Remove all commands from the other SC. First from the
11267			 * blocked queue then from the ooa queue. Once we have
11268			 * removed them. Call ctl_check_blocked to see if there
11269			 * is anything that can run.
11270			 */
11271			for (io = (union ctl_io *)TAILQ_FIRST(
11272			     &lun->blocked_queue); io != NULL; io = next_io) {
11273
11274		        	next_io = (union ctl_io *)TAILQ_NEXT(
11275				    &io->io_hdr, blocked_links);
11276
11277				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11278					TAILQ_REMOVE(&lun->blocked_queue,
11279						     &io->io_hdr,blocked_links);
11280					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11281					TAILQ_REMOVE(&lun->ooa_queue,
11282						     &io->io_hdr, ooa_links);
11283
11284					ctl_free_io(io);
11285				}
11286			}
11287
11288			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11289	     		     io != NULL; io = next_io) {
11290
11291		        	next_io = (union ctl_io *)TAILQ_NEXT(
11292				    &io->io_hdr, ooa_links);
11293
11294				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11295
11296					TAILQ_REMOVE(&lun->ooa_queue,
11297						&io->io_hdr,
11298					     	ooa_links);
11299
11300					ctl_free_io(io);
11301				}
11302			}
11303			ctl_check_blocked(lun);
11304		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11305			&& (softc->ha_mode == CTL_HA_MODE_XFER)) {
11306
11307			printf("FAILOVER: primary lun %d\n", lun_idx);
11308			/*
11309			 * Abort all commands from the other SC.  We can't
11310			 * send status back for them now.  These should get
11311			 * cleaned up when they are completed or come out
11312			 * for a datamove operation.
11313			 */
11314			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11315	     		     io != NULL; io = next_io) {
11316		        	next_io = (union ctl_io *)TAILQ_NEXT(
11317					&io->io_hdr, ooa_links);
11318
11319				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11320					io->io_hdr.flags |= CTL_FLAG_ABORT;
11321			}
11322		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11323			&& (softc->ha_mode == CTL_HA_MODE_XFER)) {
11324
11325			printf("FAILOVER: secondary lun %d\n", lun_idx);
11326
11327			lun->flags |= CTL_LUN_PRIMARY_SC;
11328
11329			/*
11330			 * We send all I/O that was sent to this controller
11331			 * and redirected to the other side back with
11332			 * busy status, and have the initiator retry it.
11333			 * Figuring out how much data has been transferred,
11334			 * etc. and picking up where we left off would be
11335			 * very tricky.
11336			 *
11337			 * XXX KDM need to remove I/O from the blocked
11338			 * queue as well!
11339			 */
11340			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11341			     &lun->ooa_queue); pending_io != NULL;
11342			     pending_io = next_io) {
11343
11344				next_io =  (union ctl_io *)TAILQ_NEXT(
11345					&pending_io->io_hdr, ooa_links);
11346
11347				pending_io->io_hdr.flags &=
11348					~CTL_FLAG_SENT_2OTHER_SC;
11349
11350				if (pending_io->io_hdr.flags &
11351				    CTL_FLAG_IO_ACTIVE) {
11352					pending_io->io_hdr.flags |=
11353						CTL_FLAG_FAILOVER;
11354				} else {
11355					ctl_set_busy(&pending_io->scsiio);
11356					ctl_done(pending_io);
11357				}
11358			}
11359
11360			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11361		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11362			&& (softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11363			printf("FAILOVER: secondary lun %d\n", lun_idx);
11364			/*
11365			 * if the first io on the OOA is not on the RtR queue
11366			 * add it.
11367			 */
11368			lun->flags |= CTL_LUN_PRIMARY_SC;
11369
11370			pending_io = (union ctl_io *)TAILQ_FIRST(
11371			    &lun->ooa_queue);
11372			if (pending_io==NULL) {
11373				printf("Nothing on OOA queue\n");
11374				continue;
11375			}
11376
11377			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11378			if ((pending_io->io_hdr.flags &
11379			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11380				pending_io->io_hdr.flags |=
11381				    CTL_FLAG_IS_WAS_ON_RTR;
11382				ctl_enqueue_rtr(pending_io);
11383			}
11384#if 0
11385			else
11386			{
11387				printf("Tag 0x%04x is running\n",
11388				      pending_io->scsiio.tag_num);
11389			}
11390#endif
11391
11392			next_io = (union ctl_io *)TAILQ_NEXT(
11393			    &pending_io->io_hdr, ooa_links);
11394			for (pending_io=next_io; pending_io != NULL;
11395			     pending_io = next_io) {
11396				pending_io->io_hdr.flags &=
11397				    ~CTL_FLAG_SENT_2OTHER_SC;
11398				next_io = (union ctl_io *)TAILQ_NEXT(
11399					&pending_io->io_hdr, ooa_links);
11400				if (pending_io->io_hdr.flags &
11401				    CTL_FLAG_IS_WAS_ON_RTR) {
11402#if 0
11403				        printf("Tag 0x%04x is running\n",
11404				      		pending_io->scsiio.tag_num);
11405#endif
11406					continue;
11407				}
11408
11409				switch (ctl_check_ooa(lun, pending_io,
11410			            (union ctl_io *)TAILQ_PREV(
11411				    &pending_io->io_hdr, ctl_ooaq,
11412				    ooa_links))) {
11413
11414				case CTL_ACTION_BLOCK:
11415					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11416							  &pending_io->io_hdr,
11417							  blocked_links);
11418					pending_io->io_hdr.flags |=
11419					    CTL_FLAG_BLOCKED;
11420					break;
11421				case CTL_ACTION_PASS:
11422				case CTL_ACTION_SKIP:
11423					pending_io->io_hdr.flags |=
11424					    CTL_FLAG_IS_WAS_ON_RTR;
11425					ctl_enqueue_rtr(pending_io);
11426					break;
11427				case CTL_ACTION_OVERLAP:
11428					ctl_set_overlapped_cmd(
11429					    (struct ctl_scsiio *)pending_io);
11430					ctl_done(pending_io);
11431					break;
11432				case CTL_ACTION_OVERLAP_TAG:
11433					ctl_set_overlapped_tag(
11434					    (struct ctl_scsiio *)pending_io,
11435					    pending_io->scsiio.tag_num & 0xff);
11436					ctl_done(pending_io);
11437					break;
11438				case CTL_ACTION_ERROR:
11439				default:
11440					ctl_set_internal_failure(
11441						(struct ctl_scsiio *)pending_io,
11442						0,  // sks_valid
11443						0); //retry count
11444					ctl_done(pending_io);
11445					break;
11446				}
11447			}
11448
11449			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11450		} else {
11451			panic("Unhandled HA mode failover, LUN flags = %#x, "
11452			      "ha_mode = #%x", lun->flags, softc->ha_mode);
11453		}
11454	}
11455	ctl_pause_rtr = 0;
11456	mtx_unlock(&softc->ctl_lock);
11457}
11458
11459static int
11460ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11461{
11462	struct ctl_lun *lun;
11463	const struct ctl_cmd_entry *entry;
11464	uint32_t initidx, targ_lun;
11465	int retval;
11466
11467	retval = 0;
11468
11469	lun = NULL;
11470
11471	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11472	if ((targ_lun < CTL_MAX_LUNS)
11473	 && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11474		/*
11475		 * If the LUN is invalid, pretend that it doesn't exist.
11476		 * It will go away as soon as all pending I/O has been
11477		 * completed.
11478		 */
11479		mtx_lock(&lun->lun_lock);
11480		if (lun->flags & CTL_LUN_DISABLED) {
11481			mtx_unlock(&lun->lun_lock);
11482			lun = NULL;
11483			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11484			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11485		} else {
11486			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11487			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11488				lun->be_lun;
11489			if (lun->be_lun->lun_type == T_PROCESSOR) {
11490				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11491			}
11492
11493			/*
11494			 * Every I/O goes into the OOA queue for a
11495			 * particular LUN, and stays there until completion.
11496			 */
11497			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11498			    ooa_links);
11499		}
11500	} else {
11501		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11502		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11503	}
11504
11505	/* Get command entry and return error if it is unsuppotyed. */
11506	entry = ctl_validate_command(ctsio);
11507	if (entry == NULL) {
11508		if (lun)
11509			mtx_unlock(&lun->lun_lock);
11510		return (retval);
11511	}
11512
11513	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11514	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11515
11516	/*
11517	 * Check to see whether we can send this command to LUNs that don't
11518	 * exist.  This should pretty much only be the case for inquiry
11519	 * and request sense.  Further checks, below, really require having
11520	 * a LUN, so we can't really check the command anymore.  Just put
11521	 * it on the rtr queue.
11522	 */
11523	if (lun == NULL) {
11524		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11525			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11526			ctl_enqueue_rtr((union ctl_io *)ctsio);
11527			return (retval);
11528		}
11529
11530		ctl_set_unsupported_lun(ctsio);
11531		ctl_done((union ctl_io *)ctsio);
11532		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11533		return (retval);
11534	} else {
11535		/*
11536		 * Make sure we support this particular command on this LUN.
11537		 * e.g., we don't support writes to the control LUN.
11538		 */
11539		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11540			mtx_unlock(&lun->lun_lock);
11541			ctl_set_invalid_opcode(ctsio);
11542			ctl_done((union ctl_io *)ctsio);
11543			return (retval);
11544		}
11545	}
11546
11547	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11548
11549#ifdef CTL_WITH_CA
11550	/*
11551	 * If we've got a request sense, it'll clear the contingent
11552	 * allegiance condition.  Otherwise, if we have a CA condition for
11553	 * this initiator, clear it, because it sent down a command other
11554	 * than request sense.
11555	 */
11556	if ((ctsio->cdb[0] != REQUEST_SENSE)
11557	 && (ctl_is_set(lun->have_ca, initidx)))
11558		ctl_clear_mask(lun->have_ca, initidx);
11559#endif
11560
11561	/*
11562	 * If the command has this flag set, it handles its own unit
11563	 * attention reporting, we shouldn't do anything.  Otherwise we
11564	 * check for any pending unit attentions, and send them back to the
11565	 * initiator.  We only do this when a command initially comes in,
11566	 * not when we pull it off the blocked queue.
11567	 *
11568	 * According to SAM-3, section 5.3.2, the order that things get
11569	 * presented back to the host is basically unit attentions caused
11570	 * by some sort of reset event, busy status, reservation conflicts
11571	 * or task set full, and finally any other status.
11572	 *
11573	 * One issue here is that some of the unit attentions we report
11574	 * don't fall into the "reset" category (e.g. "reported luns data
11575	 * has changed").  So reporting it here, before the reservation
11576	 * check, may be technically wrong.  I guess the only thing to do
11577	 * would be to check for and report the reset events here, and then
11578	 * check for the other unit attention types after we check for a
11579	 * reservation conflict.
11580	 *
11581	 * XXX KDM need to fix this
11582	 */
11583	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11584		ctl_ua_type ua_type;
11585		scsi_sense_data_type sense_format;
11586
11587		if (lun->flags & CTL_LUN_SENSE_DESC)
11588			sense_format = SSD_TYPE_DESC;
11589		else
11590			sense_format = SSD_TYPE_FIXED;
11591
11592		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11593		    sense_format);
11594		if (ua_type != CTL_UA_NONE) {
11595			mtx_unlock(&lun->lun_lock);
11596			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11597			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11598			ctsio->sense_len = SSD_FULL_SIZE;
11599			ctl_done((union ctl_io *)ctsio);
11600			return (retval);
11601		}
11602	}
11603
11604
11605	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11606		mtx_unlock(&lun->lun_lock);
11607		ctl_done((union ctl_io *)ctsio);
11608		return (retval);
11609	}
11610
11611	/*
11612	 * XXX CHD this is where we want to send IO to other side if
11613	 * this LUN is secondary on this SC. We will need to make a copy
11614	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11615	 * the copy we send as FROM_OTHER.
11616	 * We also need to stuff the address of the original IO so we can
11617	 * find it easily. Something similar will need be done on the other
11618	 * side so when we are done we can find the copy.
11619	 */
11620	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11621		union ctl_ha_msg msg_info;
11622		int isc_retval;
11623
11624		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11625
11626		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11627		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11628#if 0
11629		printf("1. ctsio %p\n", ctsio);
11630#endif
11631		msg_info.hdr.serializing_sc = NULL;
11632		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11633		msg_info.scsi.tag_num = ctsio->tag_num;
11634		msg_info.scsi.tag_type = ctsio->tag_type;
11635		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11636
11637		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11638
11639		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11640		    (void *)&msg_info, sizeof(msg_info), 0)) >
11641		    CTL_HA_STATUS_SUCCESS) {
11642			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11643			       isc_retval);
11644			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11645		} else {
11646#if 0
11647			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11648#endif
11649		}
11650
11651		/*
11652		 * XXX KDM this I/O is off the incoming queue, but hasn't
11653		 * been inserted on any other queue.  We may need to come
11654		 * up with a holding queue while we wait for serialization
11655		 * so that we have an idea of what we're waiting for from
11656		 * the other side.
11657		 */
11658		mtx_unlock(&lun->lun_lock);
11659		return (retval);
11660	}
11661
11662	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11663			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11664			      ctl_ooaq, ooa_links))) {
11665	case CTL_ACTION_BLOCK:
11666		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11667		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11668				  blocked_links);
11669		mtx_unlock(&lun->lun_lock);
11670		return (retval);
11671	case CTL_ACTION_PASS:
11672	case CTL_ACTION_SKIP:
11673		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11674		mtx_unlock(&lun->lun_lock);
11675		ctl_enqueue_rtr((union ctl_io *)ctsio);
11676		break;
11677	case CTL_ACTION_OVERLAP:
11678		mtx_unlock(&lun->lun_lock);
11679		ctl_set_overlapped_cmd(ctsio);
11680		ctl_done((union ctl_io *)ctsio);
11681		break;
11682	case CTL_ACTION_OVERLAP_TAG:
11683		mtx_unlock(&lun->lun_lock);
11684		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11685		ctl_done((union ctl_io *)ctsio);
11686		break;
11687	case CTL_ACTION_ERROR:
11688	default:
11689		mtx_unlock(&lun->lun_lock);
11690		ctl_set_internal_failure(ctsio,
11691					 /*sks_valid*/ 0,
11692					 /*retry_count*/ 0);
11693		ctl_done((union ctl_io *)ctsio);
11694		break;
11695	}
11696	return (retval);
11697}
11698
11699const struct ctl_cmd_entry *
11700ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11701{
11702	const struct ctl_cmd_entry *entry;
11703	int service_action;
11704
11705	entry = &ctl_cmd_table[ctsio->cdb[0]];
11706	if (sa)
11707		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11708	if (entry->flags & CTL_CMD_FLAG_SA5) {
11709		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11710		entry = &((const struct ctl_cmd_entry *)
11711		    entry->execute)[service_action];
11712	}
11713	return (entry);
11714}
11715
11716const struct ctl_cmd_entry *
11717ctl_validate_command(struct ctl_scsiio *ctsio)
11718{
11719	const struct ctl_cmd_entry *entry;
11720	int i, sa;
11721	uint8_t diff;
11722
11723	entry = ctl_get_cmd_entry(ctsio, &sa);
11724	if (entry->execute == NULL) {
11725		if (sa)
11726			ctl_set_invalid_field(ctsio,
11727					      /*sks_valid*/ 1,
11728					      /*command*/ 1,
11729					      /*field*/ 1,
11730					      /*bit_valid*/ 1,
11731					      /*bit*/ 4);
11732		else
11733			ctl_set_invalid_opcode(ctsio);
11734		ctl_done((union ctl_io *)ctsio);
11735		return (NULL);
11736	}
11737	KASSERT(entry->length > 0,
11738	    ("Not defined length for command 0x%02x/0x%02x",
11739	     ctsio->cdb[0], ctsio->cdb[1]));
11740	for (i = 1; i < entry->length; i++) {
11741		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11742		if (diff == 0)
11743			continue;
11744		ctl_set_invalid_field(ctsio,
11745				      /*sks_valid*/ 1,
11746				      /*command*/ 1,
11747				      /*field*/ i,
11748				      /*bit_valid*/ 1,
11749				      /*bit*/ fls(diff) - 1);
11750		ctl_done((union ctl_io *)ctsio);
11751		return (NULL);
11752	}
11753	return (entry);
11754}
11755
11756static int
11757ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11758{
11759
11760	switch (lun_type) {
11761	case T_PROCESSOR:
11762		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11763		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11764			return (0);
11765		break;
11766	case T_DIRECT:
11767		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11768		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11769			return (0);
11770		break;
11771	default:
11772		return (0);
11773	}
11774	return (1);
11775}
11776
11777static int
11778ctl_scsiio(struct ctl_scsiio *ctsio)
11779{
11780	int retval;
11781	const struct ctl_cmd_entry *entry;
11782
11783	retval = CTL_RETVAL_COMPLETE;
11784
11785	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11786
11787	entry = ctl_get_cmd_entry(ctsio, NULL);
11788
11789	/*
11790	 * If this I/O has been aborted, just send it straight to
11791	 * ctl_done() without executing it.
11792	 */
11793	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11794		ctl_done((union ctl_io *)ctsio);
11795		goto bailout;
11796	}
11797
11798	/*
11799	 * All the checks should have been handled by ctl_scsiio_precheck().
11800	 * We should be clear now to just execute the I/O.
11801	 */
11802	retval = entry->execute(ctsio);
11803
11804bailout:
11805	return (retval);
11806}
11807
11808/*
11809 * Since we only implement one target right now, a bus reset simply resets
11810 * our single target.
11811 */
11812static int
11813ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11814{
11815	return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11816}
11817
11818static int
11819ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11820		 ctl_ua_type ua_type)
11821{
11822	struct ctl_lun *lun;
11823	int retval;
11824
11825	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11826		union ctl_ha_msg msg_info;
11827
11828		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11829		msg_info.hdr.nexus = io->io_hdr.nexus;
11830		if (ua_type==CTL_UA_TARG_RESET)
11831			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11832		else
11833			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11834		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11835		msg_info.hdr.original_sc = NULL;
11836		msg_info.hdr.serializing_sc = NULL;
11837		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11838		    (void *)&msg_info, sizeof(msg_info), 0)) {
11839		}
11840	}
11841	retval = 0;
11842
11843	mtx_lock(&softc->ctl_lock);
11844	STAILQ_FOREACH(lun, &softc->lun_list, links)
11845		retval += ctl_lun_reset(lun, io, ua_type);
11846	mtx_unlock(&softc->ctl_lock);
11847
11848	return (retval);
11849}
11850
11851/*
11852 * The LUN should always be set.  The I/O is optional, and is used to
11853 * distinguish between I/Os sent by this initiator, and by other
11854 * initiators.  We set unit attention for initiators other than this one.
11855 * SAM-3 is vague on this point.  It does say that a unit attention should
11856 * be established for other initiators when a LUN is reset (see section
11857 * 5.7.3), but it doesn't specifically say that the unit attention should
11858 * be established for this particular initiator when a LUN is reset.  Here
11859 * is the relevant text, from SAM-3 rev 8:
11860 *
11861 * 5.7.2 When a SCSI initiator port aborts its own tasks
11862 *
11863 * When a SCSI initiator port causes its own task(s) to be aborted, no
11864 * notification that the task(s) have been aborted shall be returned to
11865 * the SCSI initiator port other than the completion response for the
11866 * command or task management function action that caused the task(s) to
11867 * be aborted and notification(s) associated with related effects of the
11868 * action (e.g., a reset unit attention condition).
11869 *
11870 * XXX KDM for now, we're setting unit attention for all initiators.
11871 */
11872static int
11873ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11874{
11875	union ctl_io *xio;
11876#if 0
11877	uint32_t initidx;
11878#endif
11879#ifdef CTL_WITH_CA
11880	int i;
11881#endif
11882
11883	mtx_lock(&lun->lun_lock);
11884	/*
11885	 * Run through the OOA queue and abort each I/O.
11886	 */
11887#if 0
11888	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11889#endif
11890	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11891	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11892		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11893	}
11894
11895	/*
11896	 * This version sets unit attention for every
11897	 */
11898#if 0
11899	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11900	ctl_est_ua_all(lun, initidx, ua_type);
11901#else
11902	ctl_est_ua_all(lun, -1, ua_type);
11903#endif
11904
11905	/*
11906	 * A reset (any kind, really) clears reservations established with
11907	 * RESERVE/RELEASE.  It does not clear reservations established
11908	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11909	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11910	 * reservations made with the RESERVE/RELEASE commands, because
11911	 * those commands are obsolete in SPC-3.
11912	 */
11913	lun->flags &= ~CTL_LUN_RESERVED;
11914
11915#ifdef CTL_WITH_CA
11916	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11917		ctl_clear_mask(lun->have_ca, i);
11918#endif
11919	mtx_unlock(&lun->lun_lock);
11920
11921	return (0);
11922}
11923
11924static void
11925ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11926    int other_sc)
11927{
11928	union ctl_io *xio;
11929
11930	mtx_assert(&lun->lun_lock, MA_OWNED);
11931
11932	/*
11933	 * Run through the OOA queue and attempt to find the given I/O.
11934	 * The target port, initiator ID, tag type and tag number have to
11935	 * match the values that we got from the initiator.  If we have an
11936	 * untagged command to abort, simply abort the first untagged command
11937	 * we come to.  We only allow one untagged command at a time of course.
11938	 */
11939	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11940	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11941
11942		if ((targ_port == UINT32_MAX ||
11943		     targ_port == xio->io_hdr.nexus.targ_port) &&
11944		    (init_id == UINT32_MAX ||
11945		     init_id == xio->io_hdr.nexus.initid.id)) {
11946			if (targ_port != xio->io_hdr.nexus.targ_port ||
11947			    init_id != xio->io_hdr.nexus.initid.id)
11948				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11949			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11950			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11951				union ctl_ha_msg msg_info;
11952
11953				msg_info.hdr.nexus = xio->io_hdr.nexus;
11954				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11955				msg_info.task.tag_num = xio->scsiio.tag_num;
11956				msg_info.task.tag_type = xio->scsiio.tag_type;
11957				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11958				msg_info.hdr.original_sc = NULL;
11959				msg_info.hdr.serializing_sc = NULL;
11960				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11961				    (void *)&msg_info, sizeof(msg_info), 0);
11962			}
11963		}
11964	}
11965}
11966
11967static int
11968ctl_abort_task_set(union ctl_io *io)
11969{
11970	struct ctl_softc *softc = control_softc;
11971	struct ctl_lun *lun;
11972	uint32_t targ_lun;
11973
11974	/*
11975	 * Look up the LUN.
11976	 */
11977	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11978	mtx_lock(&softc->ctl_lock);
11979	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
11980		lun = softc->ctl_luns[targ_lun];
11981	else {
11982		mtx_unlock(&softc->ctl_lock);
11983		return (1);
11984	}
11985
11986	mtx_lock(&lun->lun_lock);
11987	mtx_unlock(&softc->ctl_lock);
11988	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11989		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11990		    io->io_hdr.nexus.initid.id,
11991		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11992	} else { /* CTL_TASK_CLEAR_TASK_SET */
11993		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11994		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11995	}
11996	mtx_unlock(&lun->lun_lock);
11997	return (0);
11998}
11999
12000static int
12001ctl_i_t_nexus_reset(union ctl_io *io)
12002{
12003	struct ctl_softc *softc = control_softc;
12004	struct ctl_lun *lun;
12005	uint32_t initidx, residx;
12006
12007	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12008	residx = ctl_get_resindex(&io->io_hdr.nexus);
12009	mtx_lock(&softc->ctl_lock);
12010	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12011		mtx_lock(&lun->lun_lock);
12012		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12013		    io->io_hdr.nexus.initid.id,
12014		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12015#ifdef CTL_WITH_CA
12016		ctl_clear_mask(lun->have_ca, initidx);
12017#endif
12018		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
12019			lun->flags &= ~CTL_LUN_RESERVED;
12020		ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12021		mtx_unlock(&lun->lun_lock);
12022	}
12023	mtx_unlock(&softc->ctl_lock);
12024	return (0);
12025}
12026
12027static int
12028ctl_abort_task(union ctl_io *io)
12029{
12030	union ctl_io *xio;
12031	struct ctl_lun *lun;
12032	struct ctl_softc *softc;
12033#if 0
12034	struct sbuf sb;
12035	char printbuf[128];
12036#endif
12037	int found;
12038	uint32_t targ_lun;
12039
12040	softc = control_softc;
12041	found = 0;
12042
12043	/*
12044	 * Look up the LUN.
12045	 */
12046	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12047	mtx_lock(&softc->ctl_lock);
12048	if ((targ_lun < CTL_MAX_LUNS)
12049	 && (softc->ctl_luns[targ_lun] != NULL))
12050		lun = softc->ctl_luns[targ_lun];
12051	else {
12052		mtx_unlock(&softc->ctl_lock);
12053		return (1);
12054	}
12055
12056#if 0
12057	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12058	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12059#endif
12060
12061	mtx_lock(&lun->lun_lock);
12062	mtx_unlock(&softc->ctl_lock);
12063	/*
12064	 * Run through the OOA queue and attempt to find the given I/O.
12065	 * The target port, initiator ID, tag type and tag number have to
12066	 * match the values that we got from the initiator.  If we have an
12067	 * untagged command to abort, simply abort the first untagged command
12068	 * we come to.  We only allow one untagged command at a time of course.
12069	 */
12070#if 0
12071	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12072#endif
12073	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12074	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12075#if 0
12076		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12077
12078		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12079			    lun->lun, xio->scsiio.tag_num,
12080			    xio->scsiio.tag_type,
12081			    (xio->io_hdr.blocked_links.tqe_prev
12082			    == NULL) ? "" : " BLOCKED",
12083			    (xio->io_hdr.flags &
12084			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12085			    (xio->io_hdr.flags &
12086			    CTL_FLAG_ABORT) ? " ABORT" : "",
12087			    (xio->io_hdr.flags &
12088			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12089		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12090		sbuf_finish(&sb);
12091		printf("%s\n", sbuf_data(&sb));
12092#endif
12093
12094		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12095		 && (xio->io_hdr.nexus.initid.id ==
12096		     io->io_hdr.nexus.initid.id)) {
12097			/*
12098			 * If the abort says that the task is untagged, the
12099			 * task in the queue must be untagged.  Otherwise,
12100			 * we just check to see whether the tag numbers
12101			 * match.  This is because the QLogic firmware
12102			 * doesn't pass back the tag type in an abort
12103			 * request.
12104			 */
12105#if 0
12106			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12107			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12108			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12109#endif
12110			/*
12111			 * XXX KDM we've got problems with FC, because it
12112			 * doesn't send down a tag type with aborts.  So we
12113			 * can only really go by the tag number...
12114			 * This may cause problems with parallel SCSI.
12115			 * Need to figure that out!!
12116			 */
12117			if (xio->scsiio.tag_num == io->taskio.tag_num) {
12118				xio->io_hdr.flags |= CTL_FLAG_ABORT;
12119				found = 1;
12120				if ((io->io_hdr.flags &
12121				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
12122				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12123					union ctl_ha_msg msg_info;
12124
12125					io->io_hdr.flags |=
12126					                CTL_FLAG_SENT_2OTHER_SC;
12127					msg_info.hdr.nexus = io->io_hdr.nexus;
12128					msg_info.task.task_action =
12129						CTL_TASK_ABORT_TASK;
12130					msg_info.task.tag_num =
12131						io->taskio.tag_num;
12132					msg_info.task.tag_type =
12133						io->taskio.tag_type;
12134					msg_info.hdr.msg_type =
12135						CTL_MSG_MANAGE_TASKS;
12136					msg_info.hdr.original_sc = NULL;
12137					msg_info.hdr.serializing_sc = NULL;
12138#if 0
12139					printf("Sent Abort to other side\n");
12140#endif
12141					if (CTL_HA_STATUS_SUCCESS !=
12142					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12143		    				(void *)&msg_info,
12144						sizeof(msg_info), 0)) {
12145					}
12146				}
12147#if 0
12148				printf("ctl_abort_task: found I/O to abort\n");
12149#endif
12150				break;
12151			}
12152		}
12153	}
12154	mtx_unlock(&lun->lun_lock);
12155
12156	if (found == 0) {
12157		/*
12158		 * This isn't really an error.  It's entirely possible for
12159		 * the abort and command completion to cross on the wire.
12160		 * This is more of an informative/diagnostic error.
12161		 */
12162#if 0
12163		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12164		       "%d:%d:%d:%d tag %d type %d\n",
12165		       io->io_hdr.nexus.initid.id,
12166		       io->io_hdr.nexus.targ_port,
12167		       io->io_hdr.nexus.targ_target.id,
12168		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12169		       io->taskio.tag_type);
12170#endif
12171	}
12172	return (0);
12173}
12174
12175static void
12176ctl_run_task(union ctl_io *io)
12177{
12178	struct ctl_softc *softc = control_softc;
12179	int retval = 1;
12180	const char *task_desc;
12181
12182	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12183
12184	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12185	    ("ctl_run_task: Unextected io_type %d\n",
12186	     io->io_hdr.io_type));
12187
12188	task_desc = ctl_scsi_task_string(&io->taskio);
12189	if (task_desc != NULL) {
12190#ifdef NEEDTOPORT
12191		csevent_log(CSC_CTL | CSC_SHELF_SW |
12192			    CTL_TASK_REPORT,
12193			    csevent_LogType_Trace,
12194			    csevent_Severity_Information,
12195			    csevent_AlertLevel_Green,
12196			    csevent_FRU_Firmware,
12197			    csevent_FRU_Unknown,
12198			    "CTL: received task: %s",task_desc);
12199#endif
12200	} else {
12201#ifdef NEEDTOPORT
12202		csevent_log(CSC_CTL | CSC_SHELF_SW |
12203			    CTL_TASK_REPORT,
12204			    csevent_LogType_Trace,
12205			    csevent_Severity_Information,
12206			    csevent_AlertLevel_Green,
12207			    csevent_FRU_Firmware,
12208			    csevent_FRU_Unknown,
12209			    "CTL: received unknown task "
12210			    "type: %d (%#x)",
12211			    io->taskio.task_action,
12212			    io->taskio.task_action);
12213#endif
12214	}
12215	switch (io->taskio.task_action) {
12216	case CTL_TASK_ABORT_TASK:
12217		retval = ctl_abort_task(io);
12218		break;
12219	case CTL_TASK_ABORT_TASK_SET:
12220	case CTL_TASK_CLEAR_TASK_SET:
12221		retval = ctl_abort_task_set(io);
12222		break;
12223	case CTL_TASK_CLEAR_ACA:
12224		break;
12225	case CTL_TASK_I_T_NEXUS_RESET:
12226		retval = ctl_i_t_nexus_reset(io);
12227		break;
12228	case CTL_TASK_LUN_RESET: {
12229		struct ctl_lun *lun;
12230		uint32_t targ_lun;
12231
12232		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12233		mtx_lock(&softc->ctl_lock);
12234		if ((targ_lun < CTL_MAX_LUNS)
12235		 && (softc->ctl_luns[targ_lun] != NULL))
12236			lun = softc->ctl_luns[targ_lun];
12237		else {
12238			mtx_unlock(&softc->ctl_lock);
12239			retval = 1;
12240			break;
12241		}
12242
12243		if (!(io->io_hdr.flags &
12244		    CTL_FLAG_FROM_OTHER_SC)) {
12245			union ctl_ha_msg msg_info;
12246
12247			io->io_hdr.flags |=
12248				CTL_FLAG_SENT_2OTHER_SC;
12249			msg_info.hdr.msg_type =
12250				CTL_MSG_MANAGE_TASKS;
12251			msg_info.hdr.nexus = io->io_hdr.nexus;
12252			msg_info.task.task_action =
12253				CTL_TASK_LUN_RESET;
12254			msg_info.hdr.original_sc = NULL;
12255			msg_info.hdr.serializing_sc = NULL;
12256			if (CTL_HA_STATUS_SUCCESS !=
12257			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12258			    (void *)&msg_info,
12259			    sizeof(msg_info), 0)) {
12260			}
12261		}
12262
12263		retval = ctl_lun_reset(lun, io,
12264				       CTL_UA_LUN_RESET);
12265		mtx_unlock(&softc->ctl_lock);
12266		break;
12267	}
12268	case CTL_TASK_TARGET_RESET:
12269		retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12270		break;
12271	case CTL_TASK_BUS_RESET:
12272		retval = ctl_bus_reset(softc, io);
12273		break;
12274	case CTL_TASK_PORT_LOGIN:
12275		break;
12276	case CTL_TASK_PORT_LOGOUT:
12277		break;
12278	default:
12279		printf("ctl_run_task: got unknown task management event %d\n",
12280		       io->taskio.task_action);
12281		break;
12282	}
12283	if (retval == 0)
12284		io->io_hdr.status = CTL_SUCCESS;
12285	else
12286		io->io_hdr.status = CTL_ERROR;
12287	ctl_done(io);
12288}
12289
12290/*
12291 * For HA operation.  Handle commands that come in from the other
12292 * controller.
12293 */
12294static void
12295ctl_handle_isc(union ctl_io *io)
12296{
12297	int free_io;
12298	struct ctl_lun *lun;
12299	struct ctl_softc *softc;
12300	uint32_t targ_lun;
12301
12302	softc = control_softc;
12303
12304	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12305	lun = softc->ctl_luns[targ_lun];
12306
12307	switch (io->io_hdr.msg_type) {
12308	case CTL_MSG_SERIALIZE:
12309		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12310		break;
12311	case CTL_MSG_R2R: {
12312		const struct ctl_cmd_entry *entry;
12313
12314		/*
12315		 * This is only used in SER_ONLY mode.
12316		 */
12317		free_io = 0;
12318		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12319		mtx_lock(&lun->lun_lock);
12320		if (ctl_scsiio_lun_check(lun,
12321		    entry, (struct ctl_scsiio *)io) != 0) {
12322			mtx_unlock(&lun->lun_lock);
12323			ctl_done(io);
12324			break;
12325		}
12326		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12327		mtx_unlock(&lun->lun_lock);
12328		ctl_enqueue_rtr(io);
12329		break;
12330	}
12331	case CTL_MSG_FINISH_IO:
12332		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12333			free_io = 0;
12334			ctl_done(io);
12335		} else {
12336			free_io = 1;
12337			mtx_lock(&lun->lun_lock);
12338			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12339				     ooa_links);
12340			ctl_check_blocked(lun);
12341			mtx_unlock(&lun->lun_lock);
12342		}
12343		break;
12344	case CTL_MSG_PERS_ACTION:
12345		ctl_hndl_per_res_out_on_other_sc(
12346			(union ctl_ha_msg *)&io->presio.pr_msg);
12347		free_io = 1;
12348		break;
12349	case CTL_MSG_BAD_JUJU:
12350		free_io = 0;
12351		ctl_done(io);
12352		break;
12353	case CTL_MSG_DATAMOVE:
12354		/* Only used in XFER mode */
12355		free_io = 0;
12356		ctl_datamove_remote(io);
12357		break;
12358	case CTL_MSG_DATAMOVE_DONE:
12359		/* Only used in XFER mode */
12360		free_io = 0;
12361		io->scsiio.be_move_done(io);
12362		break;
12363	default:
12364		free_io = 1;
12365		printf("%s: Invalid message type %d\n",
12366		       __func__, io->io_hdr.msg_type);
12367		break;
12368	}
12369	if (free_io)
12370		ctl_free_io(io);
12371
12372}
12373
12374
12375/*
12376 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12377 * there is no match.
12378 */
12379static ctl_lun_error_pattern
12380ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12381{
12382	const struct ctl_cmd_entry *entry;
12383	ctl_lun_error_pattern filtered_pattern, pattern;
12384
12385	pattern = desc->error_pattern;
12386
12387	/*
12388	 * XXX KDM we need more data passed into this function to match a
12389	 * custom pattern, and we actually need to implement custom pattern
12390	 * matching.
12391	 */
12392	if (pattern & CTL_LUN_PAT_CMD)
12393		return (CTL_LUN_PAT_CMD);
12394
12395	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12396		return (CTL_LUN_PAT_ANY);
12397
12398	entry = ctl_get_cmd_entry(ctsio, NULL);
12399
12400	filtered_pattern = entry->pattern & pattern;
12401
12402	/*
12403	 * If the user requested specific flags in the pattern (e.g.
12404	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12405	 * flags.
12406	 *
12407	 * If the user did not specify any flags, it doesn't matter whether
12408	 * or not the command supports the flags.
12409	 */
12410	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12411	     (pattern & ~CTL_LUN_PAT_MASK))
12412		return (CTL_LUN_PAT_NONE);
12413
12414	/*
12415	 * If the user asked for a range check, see if the requested LBA
12416	 * range overlaps with this command's LBA range.
12417	 */
12418	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12419		uint64_t lba1;
12420		uint64_t len1;
12421		ctl_action action;
12422		int retval;
12423
12424		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12425		if (retval != 0)
12426			return (CTL_LUN_PAT_NONE);
12427
12428		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12429					      desc->lba_range.len, FALSE);
12430		/*
12431		 * A "pass" means that the LBA ranges don't overlap, so
12432		 * this doesn't match the user's range criteria.
12433		 */
12434		if (action == CTL_ACTION_PASS)
12435			return (CTL_LUN_PAT_NONE);
12436	}
12437
12438	return (filtered_pattern);
12439}
12440
12441static void
12442ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12443{
12444	struct ctl_error_desc *desc, *desc2;
12445
12446	mtx_assert(&lun->lun_lock, MA_OWNED);
12447
12448	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12449		ctl_lun_error_pattern pattern;
12450		/*
12451		 * Check to see whether this particular command matches
12452		 * the pattern in the descriptor.
12453		 */
12454		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12455		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12456			continue;
12457
12458		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12459		case CTL_LUN_INJ_ABORTED:
12460			ctl_set_aborted(&io->scsiio);
12461			break;
12462		case CTL_LUN_INJ_MEDIUM_ERR:
12463			ctl_set_medium_error(&io->scsiio);
12464			break;
12465		case CTL_LUN_INJ_UA:
12466			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12467			 * OCCURRED */
12468			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12469			break;
12470		case CTL_LUN_INJ_CUSTOM:
12471			/*
12472			 * We're assuming the user knows what he is doing.
12473			 * Just copy the sense information without doing
12474			 * checks.
12475			 */
12476			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12477			      MIN(sizeof(desc->custom_sense),
12478				  sizeof(io->scsiio.sense_data)));
12479			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12480			io->scsiio.sense_len = SSD_FULL_SIZE;
12481			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12482			break;
12483		case CTL_LUN_INJ_NONE:
12484		default:
12485			/*
12486			 * If this is an error injection type we don't know
12487			 * about, clear the continuous flag (if it is set)
12488			 * so it will get deleted below.
12489			 */
12490			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12491			break;
12492		}
12493		/*
12494		 * By default, each error injection action is a one-shot
12495		 */
12496		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12497			continue;
12498
12499		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12500
12501		free(desc, M_CTL);
12502	}
12503}
12504
12505#ifdef CTL_IO_DELAY
12506static void
12507ctl_datamove_timer_wakeup(void *arg)
12508{
12509	union ctl_io *io;
12510
12511	io = (union ctl_io *)arg;
12512
12513	ctl_datamove(io);
12514}
12515#endif /* CTL_IO_DELAY */
12516
12517void
12518ctl_datamove(union ctl_io *io)
12519{
12520	void (*fe_datamove)(union ctl_io *io);
12521
12522	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12523
12524	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12525
12526#ifdef CTL_TIME_IO
12527	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12528		char str[256];
12529		char path_str[64];
12530		struct sbuf sb;
12531
12532		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12533		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12534
12535		sbuf_cat(&sb, path_str);
12536		switch (io->io_hdr.io_type) {
12537		case CTL_IO_SCSI:
12538			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12539			sbuf_printf(&sb, "\n");
12540			sbuf_cat(&sb, path_str);
12541			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12542				    io->scsiio.tag_num, io->scsiio.tag_type);
12543			break;
12544		case CTL_IO_TASK:
12545			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12546				    "Tag Type: %d\n", io->taskio.task_action,
12547				    io->taskio.tag_num, io->taskio.tag_type);
12548			break;
12549		default:
12550			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12551			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12552			break;
12553		}
12554		sbuf_cat(&sb, path_str);
12555		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12556			    (intmax_t)time_uptime - io->io_hdr.start_time);
12557		sbuf_finish(&sb);
12558		printf("%s", sbuf_data(&sb));
12559	}
12560#endif /* CTL_TIME_IO */
12561
12562#ifdef CTL_IO_DELAY
12563	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12564		struct ctl_lun *lun;
12565
12566		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12567
12568		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12569	} else {
12570		struct ctl_lun *lun;
12571
12572		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12573		if ((lun != NULL)
12574		 && (lun->delay_info.datamove_delay > 0)) {
12575			struct callout *callout;
12576
12577			callout = (struct callout *)&io->io_hdr.timer_bytes;
12578			callout_init(callout, /*mpsafe*/ 1);
12579			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12580			callout_reset(callout,
12581				      lun->delay_info.datamove_delay * hz,
12582				      ctl_datamove_timer_wakeup, io);
12583			if (lun->delay_info.datamove_type ==
12584			    CTL_DELAY_TYPE_ONESHOT)
12585				lun->delay_info.datamove_delay = 0;
12586			return;
12587		}
12588	}
12589#endif
12590
12591	/*
12592	 * This command has been aborted.  Set the port status, so we fail
12593	 * the data move.
12594	 */
12595	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12596		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12597		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12598		       io->io_hdr.nexus.targ_port,
12599		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12600		       io->io_hdr.nexus.targ_lun);
12601		io->io_hdr.port_status = 31337;
12602		/*
12603		 * Note that the backend, in this case, will get the
12604		 * callback in its context.  In other cases it may get
12605		 * called in the frontend's interrupt thread context.
12606		 */
12607		io->scsiio.be_move_done(io);
12608		return;
12609	}
12610
12611	/* Don't confuse frontend with zero length data move. */
12612	if (io->scsiio.kern_data_len == 0) {
12613		io->scsiio.be_move_done(io);
12614		return;
12615	}
12616
12617	/*
12618	 * If we're in XFER mode and this I/O is from the other shelf
12619	 * controller, we need to send the DMA to the other side to
12620	 * actually transfer the data to/from the host.  In serialize only
12621	 * mode the transfer happens below CTL and ctl_datamove() is only
12622	 * called on the machine that originally received the I/O.
12623	 */
12624	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12625	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12626		union ctl_ha_msg msg;
12627		uint32_t sg_entries_sent;
12628		int do_sg_copy;
12629		int i;
12630
12631		memset(&msg, 0, sizeof(msg));
12632		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12633		msg.hdr.original_sc = io->io_hdr.original_sc;
12634		msg.hdr.serializing_sc = io;
12635		msg.hdr.nexus = io->io_hdr.nexus;
12636		msg.dt.flags = io->io_hdr.flags;
12637		/*
12638		 * We convert everything into a S/G list here.  We can't
12639		 * pass by reference, only by value between controllers.
12640		 * So we can't pass a pointer to the S/G list, only as many
12641		 * S/G entries as we can fit in here.  If it's possible for
12642		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12643		 * then we need to break this up into multiple transfers.
12644		 */
12645		if (io->scsiio.kern_sg_entries == 0) {
12646			msg.dt.kern_sg_entries = 1;
12647			/*
12648			 * If this is in cached memory, flush the cache
12649			 * before we send the DMA request to the other
12650			 * controller.  We want to do this in either the
12651			 * read or the write case.  The read case is
12652			 * straightforward.  In the write case, we want to
12653			 * make sure nothing is in the local cache that
12654			 * could overwrite the DMAed data.
12655			 */
12656			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12657				/*
12658				 * XXX KDM use bus_dmamap_sync() here.
12659				 */
12660			}
12661
12662			/*
12663			 * Convert to a physical address if this is a
12664			 * virtual address.
12665			 */
12666			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12667				msg.dt.sg_list[0].addr =
12668					io->scsiio.kern_data_ptr;
12669			} else {
12670				/*
12671				 * XXX KDM use busdma here!
12672				 */
12673#if 0
12674				msg.dt.sg_list[0].addr = (void *)
12675					vtophys(io->scsiio.kern_data_ptr);
12676#endif
12677			}
12678
12679			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12680			do_sg_copy = 0;
12681		} else {
12682			struct ctl_sg_entry *sgl;
12683
12684			do_sg_copy = 1;
12685			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12686			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12687			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12688				/*
12689				 * XXX KDM use bus_dmamap_sync() here.
12690				 */
12691			}
12692		}
12693
12694		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12695		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12696		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12697		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12698		msg.dt.sg_sequence = 0;
12699
12700		/*
12701		 * Loop until we've sent all of the S/G entries.  On the
12702		 * other end, we'll recompose these S/G entries into one
12703		 * contiguous list before passing it to the
12704		 */
12705		for (sg_entries_sent = 0; sg_entries_sent <
12706		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12707			msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list)/
12708				sizeof(msg.dt.sg_list[0])),
12709				msg.dt.kern_sg_entries - sg_entries_sent);
12710
12711			if (do_sg_copy != 0) {
12712				struct ctl_sg_entry *sgl;
12713				int j;
12714
12715				sgl = (struct ctl_sg_entry *)
12716					io->scsiio.kern_data_ptr;
12717				/*
12718				 * If this is in cached memory, flush the cache
12719				 * before we send the DMA request to the other
12720				 * controller.  We want to do this in either
12721				 * the * read or the write case.  The read
12722				 * case is straightforward.  In the write
12723				 * case, we want to make sure nothing is
12724				 * in the local cache that could overwrite
12725				 * the DMAed data.
12726				 */
12727
12728				for (i = sg_entries_sent, j = 0;
12729				     i < msg.dt.cur_sg_entries; i++, j++) {
12730					if ((io->io_hdr.flags &
12731					     CTL_FLAG_NO_DATASYNC) == 0) {
12732						/*
12733						 * XXX KDM use bus_dmamap_sync()
12734						 */
12735					}
12736					if ((io->io_hdr.flags &
12737					     CTL_FLAG_BUS_ADDR) == 0) {
12738						/*
12739						 * XXX KDM use busdma.
12740						 */
12741#if 0
12742						msg.dt.sg_list[j].addr =(void *)
12743						       vtophys(sgl[i].addr);
12744#endif
12745					} else {
12746						msg.dt.sg_list[j].addr =
12747							sgl[i].addr;
12748					}
12749					msg.dt.sg_list[j].len = sgl[i].len;
12750				}
12751			}
12752
12753			sg_entries_sent += msg.dt.cur_sg_entries;
12754			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12755				msg.dt.sg_last = 1;
12756			else
12757				msg.dt.sg_last = 0;
12758
12759			/*
12760			 * XXX KDM drop and reacquire the lock here?
12761			 */
12762			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12763			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12764				/*
12765				 * XXX do something here.
12766				 */
12767			}
12768
12769			msg.dt.sent_sg_entries = sg_entries_sent;
12770		}
12771		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12772		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12773			ctl_failover_io(io, /*have_lock*/ 0);
12774
12775	} else {
12776
12777		/*
12778		 * Lookup the fe_datamove() function for this particular
12779		 * front end.
12780		 */
12781		fe_datamove =
12782		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12783
12784		fe_datamove(io);
12785	}
12786}
12787
12788static void
12789ctl_send_datamove_done(union ctl_io *io, int have_lock)
12790{
12791	union ctl_ha_msg msg;
12792	int isc_status;
12793
12794	memset(&msg, 0, sizeof(msg));
12795
12796	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12797	msg.hdr.original_sc = io;
12798	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12799	msg.hdr.nexus = io->io_hdr.nexus;
12800	msg.hdr.status = io->io_hdr.status;
12801	msg.scsi.tag_num = io->scsiio.tag_num;
12802	msg.scsi.tag_type = io->scsiio.tag_type;
12803	msg.scsi.scsi_status = io->scsiio.scsi_status;
12804	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12805	       sizeof(io->scsiio.sense_data));
12806	msg.scsi.sense_len = io->scsiio.sense_len;
12807	msg.scsi.sense_residual = io->scsiio.sense_residual;
12808	msg.scsi.fetd_status = io->io_hdr.port_status;
12809	msg.scsi.residual = io->scsiio.residual;
12810	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12811
12812	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12813		ctl_failover_io(io, /*have_lock*/ have_lock);
12814		return;
12815	}
12816
12817	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12818	if (isc_status > CTL_HA_STATUS_SUCCESS) {
12819		/* XXX do something if this fails */
12820	}
12821
12822}
12823
12824/*
12825 * The DMA to the remote side is done, now we need to tell the other side
12826 * we're done so it can continue with its data movement.
12827 */
12828static void
12829ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12830{
12831	union ctl_io *io;
12832
12833	io = rq->context;
12834
12835	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12836		printf("%s: ISC DMA write failed with error %d", __func__,
12837		       rq->ret);
12838		ctl_set_internal_failure(&io->scsiio,
12839					 /*sks_valid*/ 1,
12840					 /*retry_count*/ rq->ret);
12841	}
12842
12843	ctl_dt_req_free(rq);
12844
12845	/*
12846	 * In this case, we had to malloc the memory locally.  Free it.
12847	 */
12848	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12849		int i;
12850		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12851			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12852	}
12853	/*
12854	 * The data is in local and remote memory, so now we need to send
12855	 * status (good or back) back to the other side.
12856	 */
12857	ctl_send_datamove_done(io, /*have_lock*/ 0);
12858}
12859
12860/*
12861 * We've moved the data from the host/controller into local memory.  Now we
12862 * need to push it over to the remote controller's memory.
12863 */
12864static int
12865ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12866{
12867	int retval;
12868
12869	retval = 0;
12870
12871	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12872					  ctl_datamove_remote_write_cb);
12873
12874	return (retval);
12875}
12876
12877static void
12878ctl_datamove_remote_write(union ctl_io *io)
12879{
12880	int retval;
12881	void (*fe_datamove)(union ctl_io *io);
12882
12883	/*
12884	 * - Get the data from the host/HBA into local memory.
12885	 * - DMA memory from the local controller to the remote controller.
12886	 * - Send status back to the remote controller.
12887	 */
12888
12889	retval = ctl_datamove_remote_sgl_setup(io);
12890	if (retval != 0)
12891		return;
12892
12893	/* Switch the pointer over so the FETD knows what to do */
12894	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12895
12896	/*
12897	 * Use a custom move done callback, since we need to send completion
12898	 * back to the other controller, not to the backend on this side.
12899	 */
12900	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12901
12902	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12903
12904	fe_datamove(io);
12905
12906	return;
12907
12908}
12909
12910static int
12911ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12912{
12913#if 0
12914	char str[256];
12915	char path_str[64];
12916	struct sbuf sb;
12917#endif
12918
12919	/*
12920	 * In this case, we had to malloc the memory locally.  Free it.
12921	 */
12922	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12923		int i;
12924		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12925			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12926	}
12927
12928#if 0
12929	scsi_path_string(io, path_str, sizeof(path_str));
12930	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12931	sbuf_cat(&sb, path_str);
12932	scsi_command_string(&io->scsiio, NULL, &sb);
12933	sbuf_printf(&sb, "\n");
12934	sbuf_cat(&sb, path_str);
12935	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12936		    io->scsiio.tag_num, io->scsiio.tag_type);
12937	sbuf_cat(&sb, path_str);
12938	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12939		    io->io_hdr.flags, io->io_hdr.status);
12940	sbuf_finish(&sb);
12941	printk("%s", sbuf_data(&sb));
12942#endif
12943
12944
12945	/*
12946	 * The read is done, now we need to send status (good or bad) back
12947	 * to the other side.
12948	 */
12949	ctl_send_datamove_done(io, /*have_lock*/ 0);
12950
12951	return (0);
12952}
12953
12954static void
12955ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12956{
12957	union ctl_io *io;
12958	void (*fe_datamove)(union ctl_io *io);
12959
12960	io = rq->context;
12961
12962	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12963		printf("%s: ISC DMA read failed with error %d", __func__,
12964		       rq->ret);
12965		ctl_set_internal_failure(&io->scsiio,
12966					 /*sks_valid*/ 1,
12967					 /*retry_count*/ rq->ret);
12968	}
12969
12970	ctl_dt_req_free(rq);
12971
12972	/* Switch the pointer over so the FETD knows what to do */
12973	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12974
12975	/*
12976	 * Use a custom move done callback, since we need to send completion
12977	 * back to the other controller, not to the backend on this side.
12978	 */
12979	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12980
12981	/* XXX KDM add checks like the ones in ctl_datamove? */
12982
12983	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12984
12985	fe_datamove(io);
12986}
12987
12988static int
12989ctl_datamove_remote_sgl_setup(union ctl_io *io)
12990{
12991	struct ctl_sg_entry *local_sglist, *remote_sglist;
12992	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
12993	struct ctl_softc *softc;
12994	int retval;
12995	int i;
12996
12997	retval = 0;
12998	softc = control_softc;
12999
13000	local_sglist = io->io_hdr.local_sglist;
13001	local_dma_sglist = io->io_hdr.local_dma_sglist;
13002	remote_sglist = io->io_hdr.remote_sglist;
13003	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13004
13005	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13006		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13007			local_sglist[i].len = remote_sglist[i].len;
13008
13009			/*
13010			 * XXX Detect the situation where the RS-level I/O
13011			 * redirector on the other side has already read the
13012			 * data off of the AOR RS on this side, and
13013			 * transferred it to remote (mirror) memory on the
13014			 * other side.  Since we already have the data in
13015			 * memory here, we just need to use it.
13016			 *
13017			 * XXX KDM this can probably be removed once we
13018			 * get the cache device code in and take the
13019			 * current AOR implementation out.
13020			 */
13021#ifdef NEEDTOPORT
13022			if ((remote_sglist[i].addr >=
13023			     (void *)vtophys(softc->mirr->addr))
13024			 && (remote_sglist[i].addr <
13025			     ((void *)vtophys(softc->mirr->addr) +
13026			     CacheMirrorOffset))) {
13027				local_sglist[i].addr = remote_sglist[i].addr -
13028					CacheMirrorOffset;
13029				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13030				     CTL_FLAG_DATA_IN)
13031					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13032			} else {
13033				local_sglist[i].addr = remote_sglist[i].addr +
13034					CacheMirrorOffset;
13035			}
13036#endif
13037#if 0
13038			printf("%s: local %p, remote %p, len %d\n",
13039			       __func__, local_sglist[i].addr,
13040			       remote_sglist[i].addr, local_sglist[i].len);
13041#endif
13042		}
13043	} else {
13044		uint32_t len_to_go;
13045
13046		/*
13047		 * In this case, we don't have automatically allocated
13048		 * memory for this I/O on this controller.  This typically
13049		 * happens with internal CTL I/O -- e.g. inquiry, mode
13050		 * sense, etc.  Anything coming from RAIDCore will have
13051		 * a mirror area available.
13052		 */
13053		len_to_go = io->scsiio.kern_data_len;
13054
13055		/*
13056		 * Clear the no datasync flag, we have to use malloced
13057		 * buffers.
13058		 */
13059		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13060
13061		/*
13062		 * The difficult thing here is that the size of the various
13063		 * S/G segments may be different than the size from the
13064		 * remote controller.  That'll make it harder when DMAing
13065		 * the data back to the other side.
13066		 */
13067		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13068		     sizeof(io->io_hdr.remote_sglist[0])) &&
13069		     (len_to_go > 0); i++) {
13070			local_sglist[i].len = MIN(len_to_go, 131072);
13071			CTL_SIZE_8B(local_dma_sglist[i].len,
13072				    local_sglist[i].len);
13073			local_sglist[i].addr =
13074				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13075
13076			local_dma_sglist[i].addr = local_sglist[i].addr;
13077
13078			if (local_sglist[i].addr == NULL) {
13079				int j;
13080
13081				printf("malloc failed for %zd bytes!",
13082				       local_dma_sglist[i].len);
13083				for (j = 0; j < i; j++) {
13084					free(local_sglist[j].addr, M_CTL);
13085				}
13086				ctl_set_internal_failure(&io->scsiio,
13087							 /*sks_valid*/ 1,
13088							 /*retry_count*/ 4857);
13089				retval = 1;
13090				goto bailout_error;
13091
13092			}
13093			/* XXX KDM do we need a sync here? */
13094
13095			len_to_go -= local_sglist[i].len;
13096		}
13097		/*
13098		 * Reset the number of S/G entries accordingly.  The
13099		 * original number of S/G entries is available in
13100		 * rem_sg_entries.
13101		 */
13102		io->scsiio.kern_sg_entries = i;
13103
13104#if 0
13105		printf("%s: kern_sg_entries = %d\n", __func__,
13106		       io->scsiio.kern_sg_entries);
13107		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13108			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13109			       local_sglist[i].addr, local_sglist[i].len,
13110			       local_dma_sglist[i].len);
13111#endif
13112	}
13113
13114
13115	return (retval);
13116
13117bailout_error:
13118
13119	ctl_send_datamove_done(io, /*have_lock*/ 0);
13120
13121	return (retval);
13122}
13123
13124static int
13125ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13126			 ctl_ha_dt_cb callback)
13127{
13128	struct ctl_ha_dt_req *rq;
13129	struct ctl_sg_entry *remote_sglist, *local_sglist;
13130	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13131	uint32_t local_used, remote_used, total_used;
13132	int retval;
13133	int i, j;
13134
13135	retval = 0;
13136
13137	rq = ctl_dt_req_alloc();
13138
13139	/*
13140	 * If we failed to allocate the request, and if the DMA didn't fail
13141	 * anyway, set busy status.  This is just a resource allocation
13142	 * failure.
13143	 */
13144	if ((rq == NULL)
13145	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13146		ctl_set_busy(&io->scsiio);
13147
13148	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13149
13150		if (rq != NULL)
13151			ctl_dt_req_free(rq);
13152
13153		/*
13154		 * The data move failed.  We need to return status back
13155		 * to the other controller.  No point in trying to DMA
13156		 * data to the remote controller.
13157		 */
13158
13159		ctl_send_datamove_done(io, /*have_lock*/ 0);
13160
13161		retval = 1;
13162
13163		goto bailout;
13164	}
13165
13166	local_sglist = io->io_hdr.local_sglist;
13167	local_dma_sglist = io->io_hdr.local_dma_sglist;
13168	remote_sglist = io->io_hdr.remote_sglist;
13169	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13170	local_used = 0;
13171	remote_used = 0;
13172	total_used = 0;
13173
13174	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13175		rq->ret = CTL_HA_STATUS_SUCCESS;
13176		rq->context = io;
13177		callback(rq);
13178		goto bailout;
13179	}
13180
13181	/*
13182	 * Pull/push the data over the wire from/to the other controller.
13183	 * This takes into account the possibility that the local and
13184	 * remote sglists may not be identical in terms of the size of
13185	 * the elements and the number of elements.
13186	 *
13187	 * One fundamental assumption here is that the length allocated for
13188	 * both the local and remote sglists is identical.  Otherwise, we've
13189	 * essentially got a coding error of some sort.
13190	 */
13191	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13192		int isc_ret;
13193		uint32_t cur_len, dma_length;
13194		uint8_t *tmp_ptr;
13195
13196		rq->id = CTL_HA_DATA_CTL;
13197		rq->command = command;
13198		rq->context = io;
13199
13200		/*
13201		 * Both pointers should be aligned.  But it is possible
13202		 * that the allocation length is not.  They should both
13203		 * also have enough slack left over at the end, though,
13204		 * to round up to the next 8 byte boundary.
13205		 */
13206		cur_len = MIN(local_sglist[i].len - local_used,
13207			      remote_sglist[j].len - remote_used);
13208
13209		/*
13210		 * In this case, we have a size issue and need to decrease
13211		 * the size, except in the case where we actually have less
13212		 * than 8 bytes left.  In that case, we need to increase
13213		 * the DMA length to get the last bit.
13214		 */
13215		if ((cur_len & 0x7) != 0) {
13216			if (cur_len > 0x7) {
13217				cur_len = cur_len - (cur_len & 0x7);
13218				dma_length = cur_len;
13219			} else {
13220				CTL_SIZE_8B(dma_length, cur_len);
13221			}
13222
13223		} else
13224			dma_length = cur_len;
13225
13226		/*
13227		 * If we had to allocate memory for this I/O, instead of using
13228		 * the non-cached mirror memory, we'll need to flush the cache
13229		 * before trying to DMA to the other controller.
13230		 *
13231		 * We could end up doing this multiple times for the same
13232		 * segment if we have a larger local segment than remote
13233		 * segment.  That shouldn't be an issue.
13234		 */
13235		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13236			/*
13237			 * XXX KDM use bus_dmamap_sync() here.
13238			 */
13239		}
13240
13241		rq->size = dma_length;
13242
13243		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13244		tmp_ptr += local_used;
13245
13246		/* Use physical addresses when talking to ISC hardware */
13247		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13248			/* XXX KDM use busdma */
13249#if 0
13250			rq->local = vtophys(tmp_ptr);
13251#endif
13252		} else
13253			rq->local = tmp_ptr;
13254
13255		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13256		tmp_ptr += remote_used;
13257		rq->remote = tmp_ptr;
13258
13259		rq->callback = NULL;
13260
13261		local_used += cur_len;
13262		if (local_used >= local_sglist[i].len) {
13263			i++;
13264			local_used = 0;
13265		}
13266
13267		remote_used += cur_len;
13268		if (remote_used >= remote_sglist[j].len) {
13269			j++;
13270			remote_used = 0;
13271		}
13272		total_used += cur_len;
13273
13274		if (total_used >= io->scsiio.kern_data_len)
13275			rq->callback = callback;
13276
13277		if ((rq->size & 0x7) != 0) {
13278			printf("%s: warning: size %d is not on 8b boundary\n",
13279			       __func__, rq->size);
13280		}
13281		if (((uintptr_t)rq->local & 0x7) != 0) {
13282			printf("%s: warning: local %p not on 8b boundary\n",
13283			       __func__, rq->local);
13284		}
13285		if (((uintptr_t)rq->remote & 0x7) != 0) {
13286			printf("%s: warning: remote %p not on 8b boundary\n",
13287			       __func__, rq->local);
13288		}
13289#if 0
13290		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13291		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13292		       rq->local, rq->remote, rq->size);
13293#endif
13294
13295		isc_ret = ctl_dt_single(rq);
13296		if (isc_ret == CTL_HA_STATUS_WAIT)
13297			continue;
13298
13299		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13300			rq->ret = CTL_HA_STATUS_SUCCESS;
13301		} else {
13302			rq->ret = isc_ret;
13303		}
13304		callback(rq);
13305		goto bailout;
13306	}
13307
13308bailout:
13309	return (retval);
13310
13311}
13312
13313static void
13314ctl_datamove_remote_read(union ctl_io *io)
13315{
13316	int retval;
13317	int i;
13318
13319	/*
13320	 * This will send an error to the other controller in the case of a
13321	 * failure.
13322	 */
13323	retval = ctl_datamove_remote_sgl_setup(io);
13324	if (retval != 0)
13325		return;
13326
13327	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13328					  ctl_datamove_remote_read_cb);
13329	if ((retval != 0)
13330	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13331		/*
13332		 * Make sure we free memory if there was an error..  The
13333		 * ctl_datamove_remote_xfer() function will send the
13334		 * datamove done message, or call the callback with an
13335		 * error if there is a problem.
13336		 */
13337		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13338			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13339	}
13340
13341	return;
13342}
13343
13344/*
13345 * Process a datamove request from the other controller.  This is used for
13346 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13347 * first.  Once that is complete, the data gets DMAed into the remote
13348 * controller's memory.  For reads, we DMA from the remote controller's
13349 * memory into our memory first, and then move it out to the FETD.
13350 */
13351static void
13352ctl_datamove_remote(union ctl_io *io)
13353{
13354	struct ctl_softc *softc;
13355
13356	softc = control_softc;
13357
13358	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13359
13360	/*
13361	 * Note that we look for an aborted I/O here, but don't do some of
13362	 * the other checks that ctl_datamove() normally does.
13363	 * We don't need to run the datamove delay code, since that should
13364	 * have been done if need be on the other controller.
13365	 */
13366	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13367		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13368		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13369		       io->io_hdr.nexus.targ_port,
13370		       io->io_hdr.nexus.targ_target.id,
13371		       io->io_hdr.nexus.targ_lun);
13372		io->io_hdr.port_status = 31338;
13373		ctl_send_datamove_done(io, /*have_lock*/ 0);
13374		return;
13375	}
13376
13377	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13378		ctl_datamove_remote_write(io);
13379	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13380		ctl_datamove_remote_read(io);
13381	} else {
13382		union ctl_ha_msg msg;
13383		struct scsi_sense_data *sense;
13384		uint8_t sks[3];
13385		int retry_count;
13386
13387		memset(&msg, 0, sizeof(msg));
13388
13389		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13390		msg.hdr.status = CTL_SCSI_ERROR;
13391		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13392
13393		retry_count = 4243;
13394
13395		sense = &msg.scsi.sense_data;
13396		sks[0] = SSD_SCS_VALID;
13397		sks[1] = (retry_count >> 8) & 0xff;
13398		sks[2] = retry_count & 0xff;
13399
13400		/* "Internal target failure" */
13401		scsi_set_sense_data(sense,
13402				    /*sense_format*/ SSD_TYPE_NONE,
13403				    /*current_error*/ 1,
13404				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13405				    /*asc*/ 0x44,
13406				    /*ascq*/ 0x00,
13407				    /*type*/ SSD_ELEM_SKS,
13408				    /*size*/ sizeof(sks),
13409				    /*data*/ sks,
13410				    SSD_ELEM_NONE);
13411
13412		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13413		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13414			ctl_failover_io(io, /*have_lock*/ 1);
13415			return;
13416		}
13417
13418		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13419		    CTL_HA_STATUS_SUCCESS) {
13420			/* XXX KDM what to do if this fails? */
13421		}
13422		return;
13423	}
13424
13425}
13426
13427static int
13428ctl_process_done(union ctl_io *io)
13429{
13430	struct ctl_lun *lun;
13431	struct ctl_softc *softc = control_softc;
13432	void (*fe_done)(union ctl_io *io);
13433	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13434
13435	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13436
13437	fe_done = softc->ctl_ports[targ_port]->fe_done;
13438
13439#ifdef CTL_TIME_IO
13440	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13441		char str[256];
13442		char path_str[64];
13443		struct sbuf sb;
13444
13445		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13446		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13447
13448		sbuf_cat(&sb, path_str);
13449		switch (io->io_hdr.io_type) {
13450		case CTL_IO_SCSI:
13451			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13452			sbuf_printf(&sb, "\n");
13453			sbuf_cat(&sb, path_str);
13454			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13455				    io->scsiio.tag_num, io->scsiio.tag_type);
13456			break;
13457		case CTL_IO_TASK:
13458			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13459				    "Tag Type: %d\n", io->taskio.task_action,
13460				    io->taskio.tag_num, io->taskio.tag_type);
13461			break;
13462		default:
13463			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13464			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13465			break;
13466		}
13467		sbuf_cat(&sb, path_str);
13468		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13469			    (intmax_t)time_uptime - io->io_hdr.start_time);
13470		sbuf_finish(&sb);
13471		printf("%s", sbuf_data(&sb));
13472	}
13473#endif /* CTL_TIME_IO */
13474
13475	switch (io->io_hdr.io_type) {
13476	case CTL_IO_SCSI:
13477		break;
13478	case CTL_IO_TASK:
13479		if (bootverbose || (ctl_debug & CTL_DEBUG_INFO))
13480			ctl_io_error_print(io, NULL);
13481		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13482			ctl_free_io(io);
13483		else
13484			fe_done(io);
13485		return (CTL_RETVAL_COMPLETE);
13486	default:
13487		panic("ctl_process_done: invalid io type %d\n",
13488		      io->io_hdr.io_type);
13489		break; /* NOTREACHED */
13490	}
13491
13492	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13493	if (lun == NULL) {
13494		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13495				 io->io_hdr.nexus.targ_mapped_lun));
13496		goto bailout;
13497	}
13498
13499	mtx_lock(&lun->lun_lock);
13500
13501	/*
13502	 * Check to see if we have any errors to inject here.  We only
13503	 * inject errors for commands that don't already have errors set.
13504	 */
13505	if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
13506	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13507	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13508		ctl_inject_error(lun, io);
13509
13510	/*
13511	 * XXX KDM how do we treat commands that aren't completed
13512	 * successfully?
13513	 *
13514	 * XXX KDM should we also track I/O latency?
13515	 */
13516	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13517	    io->io_hdr.io_type == CTL_IO_SCSI) {
13518#ifdef CTL_TIME_IO
13519		struct bintime cur_bt;
13520#endif
13521		int type;
13522
13523		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13524		    CTL_FLAG_DATA_IN)
13525			type = CTL_STATS_READ;
13526		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13527		    CTL_FLAG_DATA_OUT)
13528			type = CTL_STATS_WRITE;
13529		else
13530			type = CTL_STATS_NO_IO;
13531
13532		lun->stats.ports[targ_port].bytes[type] +=
13533		    io->scsiio.kern_total_len;
13534		lun->stats.ports[targ_port].operations[type]++;
13535#ifdef CTL_TIME_IO
13536		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13537		   &io->io_hdr.dma_bt);
13538		lun->stats.ports[targ_port].num_dmas[type] +=
13539		    io->io_hdr.num_dmas;
13540		getbintime(&cur_bt);
13541		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13542		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13543#endif
13544	}
13545
13546	/*
13547	 * Remove this from the OOA queue.
13548	 */
13549	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13550
13551	/*
13552	 * Run through the blocked queue on this LUN and see if anything
13553	 * has become unblocked, now that this transaction is done.
13554	 */
13555	ctl_check_blocked(lun);
13556
13557	/*
13558	 * If the LUN has been invalidated, free it if there is nothing
13559	 * left on its OOA queue.
13560	 */
13561	if ((lun->flags & CTL_LUN_INVALID)
13562	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13563		mtx_unlock(&lun->lun_lock);
13564		mtx_lock(&softc->ctl_lock);
13565		ctl_free_lun(lun);
13566		mtx_unlock(&softc->ctl_lock);
13567	} else
13568		mtx_unlock(&lun->lun_lock);
13569
13570bailout:
13571
13572	/*
13573	 * If this command has been aborted, make sure we set the status
13574	 * properly.  The FETD is responsible for freeing the I/O and doing
13575	 * whatever it needs to do to clean up its state.
13576	 */
13577	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13578		ctl_set_task_aborted(&io->scsiio);
13579
13580	/*
13581	 * If enabled, print command error status.
13582	 * We don't print UAs unless debugging was enabled explicitly.
13583	 */
13584	do {
13585		if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)
13586			break;
13587		if (!bootverbose && (ctl_debug & CTL_DEBUG_INFO) == 0)
13588			break;
13589		if ((ctl_debug & CTL_DEBUG_INFO) == 0 &&
13590		    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR) &&
13591		     (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13592			int error_code, sense_key, asc, ascq;
13593
13594			scsi_extract_sense_len(&io->scsiio.sense_data,
13595			    io->scsiio.sense_len, &error_code, &sense_key,
13596			    &asc, &ascq, /*show_errors*/ 0);
13597			if (sense_key == SSD_KEY_UNIT_ATTENTION)
13598				break;
13599		}
13600
13601		ctl_io_error_print(io, NULL);
13602	} while (0);
13603
13604	/*
13605	 * Tell the FETD or the other shelf controller we're done with this
13606	 * command.  Note that only SCSI commands get to this point.  Task
13607	 * management commands are completed above.
13608	 *
13609	 * We only send status to the other controller if we're in XFER
13610	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13611	 * received the I/O (from CTL's perspective), and so the status is
13612	 * generated there.
13613	 *
13614	 * XXX KDM if we hold the lock here, we could cause a deadlock
13615	 * if the frontend comes back in in this context to queue
13616	 * something.
13617	 */
13618	if ((softc->ha_mode == CTL_HA_MODE_XFER)
13619	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13620		union ctl_ha_msg msg;
13621
13622		memset(&msg, 0, sizeof(msg));
13623		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13624		msg.hdr.original_sc = io->io_hdr.original_sc;
13625		msg.hdr.nexus = io->io_hdr.nexus;
13626		msg.hdr.status = io->io_hdr.status;
13627		msg.scsi.scsi_status = io->scsiio.scsi_status;
13628		msg.scsi.tag_num = io->scsiio.tag_num;
13629		msg.scsi.tag_type = io->scsiio.tag_type;
13630		msg.scsi.sense_len = io->scsiio.sense_len;
13631		msg.scsi.sense_residual = io->scsiio.sense_residual;
13632		msg.scsi.residual = io->scsiio.residual;
13633		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13634		       sizeof(io->scsiio.sense_data));
13635		/*
13636		 * We copy this whether or not this is an I/O-related
13637		 * command.  Otherwise, we'd have to go and check to see
13638		 * whether it's a read/write command, and it really isn't
13639		 * worth it.
13640		 */
13641		memcpy(&msg.scsi.lbalen,
13642		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13643		       sizeof(msg.scsi.lbalen));
13644
13645		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13646				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13647			/* XXX do something here */
13648		}
13649
13650		ctl_free_io(io);
13651	} else
13652		fe_done(io);
13653
13654	return (CTL_RETVAL_COMPLETE);
13655}
13656
13657#ifdef CTL_WITH_CA
13658/*
13659 * Front end should call this if it doesn't do autosense.  When the request
13660 * sense comes back in from the initiator, we'll dequeue this and send it.
13661 */
13662int
13663ctl_queue_sense(union ctl_io *io)
13664{
13665	struct ctl_lun *lun;
13666	struct ctl_softc *softc;
13667	uint32_t initidx, targ_lun;
13668
13669	softc = control_softc;
13670
13671	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13672
13673	/*
13674	 * LUN lookup will likely move to the ctl_work_thread() once we
13675	 * have our new queueing infrastructure (that doesn't put things on
13676	 * a per-LUN queue initially).  That is so that we can handle
13677	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13678	 * can't deal with that right now.
13679	 */
13680	mtx_lock(&softc->ctl_lock);
13681
13682	/*
13683	 * If we don't have a LUN for this, just toss the sense
13684	 * information.
13685	 */
13686	targ_lun = io->io_hdr.nexus.targ_lun;
13687	targ_lun = ctl_map_lun(softc, io->io_hdr.nexus.targ_port, targ_lun);
13688	if ((targ_lun < CTL_MAX_LUNS)
13689	 && (softc->ctl_luns[targ_lun] != NULL))
13690		lun = softc->ctl_luns[targ_lun];
13691	else
13692		goto bailout;
13693
13694	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13695
13696	mtx_lock(&lun->lun_lock);
13697	/*
13698	 * Already have CA set for this LUN...toss the sense information.
13699	 */
13700	if (ctl_is_set(lun->have_ca, initidx)) {
13701		mtx_unlock(&lun->lun_lock);
13702		goto bailout;
13703	}
13704
13705	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13706	       MIN(sizeof(lun->pending_sense[initidx]),
13707	       sizeof(io->scsiio.sense_data)));
13708	ctl_set_mask(lun->have_ca, initidx);
13709	mtx_unlock(&lun->lun_lock);
13710
13711bailout:
13712	mtx_unlock(&softc->ctl_lock);
13713
13714	ctl_free_io(io);
13715
13716	return (CTL_RETVAL_COMPLETE);
13717}
13718#endif
13719
13720/*
13721 * Primary command inlet from frontend ports.  All SCSI and task I/O
13722 * requests must go through this function.
13723 */
13724int
13725ctl_queue(union ctl_io *io)
13726{
13727
13728	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13729
13730#ifdef CTL_TIME_IO
13731	io->io_hdr.start_time = time_uptime;
13732	getbintime(&io->io_hdr.start_bt);
13733#endif /* CTL_TIME_IO */
13734
13735	/* Map FE-specific LUN ID into global one. */
13736	io->io_hdr.nexus.targ_mapped_lun =
13737	    ctl_map_lun(control_softc, io->io_hdr.nexus.targ_port,
13738	     io->io_hdr.nexus.targ_lun);
13739
13740	switch (io->io_hdr.io_type) {
13741	case CTL_IO_SCSI:
13742	case CTL_IO_TASK:
13743		if (ctl_debug & CTL_DEBUG_CDB)
13744			ctl_io_print(io);
13745		ctl_enqueue_incoming(io);
13746		break;
13747	default:
13748		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13749		return (EINVAL);
13750	}
13751
13752	return (CTL_RETVAL_COMPLETE);
13753}
13754
13755#ifdef CTL_IO_DELAY
13756static void
13757ctl_done_timer_wakeup(void *arg)
13758{
13759	union ctl_io *io;
13760
13761	io = (union ctl_io *)arg;
13762	ctl_done(io);
13763}
13764#endif /* CTL_IO_DELAY */
13765
13766void
13767ctl_done(union ctl_io *io)
13768{
13769
13770	/*
13771	 * Enable this to catch duplicate completion issues.
13772	 */
13773#if 0
13774	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13775		printf("%s: type %d msg %d cdb %x iptl: "
13776		       "%d:%d:%d:%d tag 0x%04x "
13777		       "flag %#x status %x\n",
13778			__func__,
13779			io->io_hdr.io_type,
13780			io->io_hdr.msg_type,
13781			io->scsiio.cdb[0],
13782			io->io_hdr.nexus.initid.id,
13783			io->io_hdr.nexus.targ_port,
13784			io->io_hdr.nexus.targ_target.id,
13785			io->io_hdr.nexus.targ_lun,
13786			(io->io_hdr.io_type ==
13787			CTL_IO_TASK) ?
13788			io->taskio.tag_num :
13789			io->scsiio.tag_num,
13790		        io->io_hdr.flags,
13791			io->io_hdr.status);
13792	} else
13793		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13794#endif
13795
13796	/*
13797	 * This is an internal copy of an I/O, and should not go through
13798	 * the normal done processing logic.
13799	 */
13800	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13801		return;
13802
13803	/*
13804	 * We need to send a msg to the serializing shelf to finish the IO
13805	 * as well.  We don't send a finish message to the other shelf if
13806	 * this is a task management command.  Task management commands
13807	 * aren't serialized in the OOA queue, but rather just executed on
13808	 * both shelf controllers for commands that originated on that
13809	 * controller.
13810	 */
13811	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13812	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
13813		union ctl_ha_msg msg_io;
13814
13815		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13816		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13817		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13818		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13819		}
13820		/* continue on to finish IO */
13821	}
13822#ifdef CTL_IO_DELAY
13823	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13824		struct ctl_lun *lun;
13825
13826		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13827
13828		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13829	} else {
13830		struct ctl_lun *lun;
13831
13832		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13833
13834		if ((lun != NULL)
13835		 && (lun->delay_info.done_delay > 0)) {
13836			struct callout *callout;
13837
13838			callout = (struct callout *)&io->io_hdr.timer_bytes;
13839			callout_init(callout, /*mpsafe*/ 1);
13840			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13841			callout_reset(callout,
13842				      lun->delay_info.done_delay * hz,
13843				      ctl_done_timer_wakeup, io);
13844			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13845				lun->delay_info.done_delay = 0;
13846			return;
13847		}
13848	}
13849#endif /* CTL_IO_DELAY */
13850
13851	ctl_enqueue_done(io);
13852}
13853
13854int
13855ctl_isc(struct ctl_scsiio *ctsio)
13856{
13857	struct ctl_lun *lun;
13858	int retval;
13859
13860	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13861
13862	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13863
13864	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13865
13866	retval = lun->backend->data_submit((union ctl_io *)ctsio);
13867
13868	return (retval);
13869}
13870
13871
13872static void
13873ctl_work_thread(void *arg)
13874{
13875	struct ctl_thread *thr = (struct ctl_thread *)arg;
13876	struct ctl_softc *softc = thr->ctl_softc;
13877	union ctl_io *io;
13878	int retval;
13879
13880	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13881
13882	for (;;) {
13883		retval = 0;
13884
13885		/*
13886		 * We handle the queues in this order:
13887		 * - ISC
13888		 * - done queue (to free up resources, unblock other commands)
13889		 * - RtR queue
13890		 * - incoming queue
13891		 *
13892		 * If those queues are empty, we break out of the loop and
13893		 * go to sleep.
13894		 */
13895		mtx_lock(&thr->queue_lock);
13896		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13897		if (io != NULL) {
13898			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13899			mtx_unlock(&thr->queue_lock);
13900			ctl_handle_isc(io);
13901			continue;
13902		}
13903		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13904		if (io != NULL) {
13905			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13906			/* clear any blocked commands, call fe_done */
13907			mtx_unlock(&thr->queue_lock);
13908			retval = ctl_process_done(io);
13909			continue;
13910		}
13911		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13912		if (io != NULL) {
13913			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13914			mtx_unlock(&thr->queue_lock);
13915			if (io->io_hdr.io_type == CTL_IO_TASK)
13916				ctl_run_task(io);
13917			else
13918				ctl_scsiio_precheck(softc, &io->scsiio);
13919			continue;
13920		}
13921		if (!ctl_pause_rtr) {
13922			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13923			if (io != NULL) {
13924				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13925				mtx_unlock(&thr->queue_lock);
13926				retval = ctl_scsiio(&io->scsiio);
13927				if (retval != CTL_RETVAL_COMPLETE)
13928					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13929				continue;
13930			}
13931		}
13932
13933		/* Sleep until we have something to do. */
13934		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13935	}
13936}
13937
13938static void
13939ctl_lun_thread(void *arg)
13940{
13941	struct ctl_softc *softc = (struct ctl_softc *)arg;
13942	struct ctl_be_lun *be_lun;
13943	int retval;
13944
13945	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13946
13947	for (;;) {
13948		retval = 0;
13949		mtx_lock(&softc->ctl_lock);
13950		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13951		if (be_lun != NULL) {
13952			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13953			mtx_unlock(&softc->ctl_lock);
13954			ctl_create_lun(be_lun);
13955			continue;
13956		}
13957
13958		/* Sleep until we have something to do. */
13959		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13960		    PDROP | PRIBIO, "-", 0);
13961	}
13962}
13963
13964static void
13965ctl_thresh_thread(void *arg)
13966{
13967	struct ctl_softc *softc = (struct ctl_softc *)arg;
13968	struct ctl_lun *lun;
13969	struct ctl_be_lun *be_lun;
13970	struct scsi_da_rw_recovery_page *rwpage;
13971	struct ctl_logical_block_provisioning_page *page;
13972	const char *attr;
13973	uint64_t thres, val;
13974	int i, e;
13975
13976	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13977
13978	for (;;) {
13979		mtx_lock(&softc->ctl_lock);
13980		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13981			be_lun = lun->be_lun;
13982			if ((lun->flags & CTL_LUN_DISABLED) ||
13983			    (lun->flags & CTL_LUN_OFFLINE) ||
13984			    lun->backend->lun_attr == NULL)
13985				continue;
13986			rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13987			if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13988				continue;
13989			e = 0;
13990			page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13991			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13992				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13993					continue;
13994				thres = scsi_4btoul(page->descr[i].count);
13995				thres <<= CTL_LBP_EXPONENT;
13996				switch (page->descr[i].resource) {
13997				case 0x01:
13998					attr = "blocksavail";
13999					break;
14000				case 0x02:
14001					attr = "blocksused";
14002					break;
14003				case 0xf1:
14004					attr = "poolblocksavail";
14005					break;
14006				case 0xf2:
14007					attr = "poolblocksused";
14008					break;
14009				default:
14010					continue;
14011				}
14012				mtx_unlock(&softc->ctl_lock); // XXX
14013				val = lun->backend->lun_attr(
14014				    lun->be_lun->be_lun, attr);
14015				mtx_lock(&softc->ctl_lock);
14016				if (val == UINT64_MAX)
14017					continue;
14018				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
14019				    == SLBPPD_ARMING_INC)
14020					e |= (val >= thres);
14021				else
14022					e |= (val <= thres);
14023			}
14024			mtx_lock(&lun->lun_lock);
14025			if (e) {
14026				if (lun->lasttpt == 0 ||
14027				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
14028					lun->lasttpt = time_uptime;
14029					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14030				}
14031			} else {
14032				lun->lasttpt = 0;
14033				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14034			}
14035			mtx_unlock(&lun->lun_lock);
14036		}
14037		mtx_unlock(&softc->ctl_lock);
14038		pause("-", CTL_LBP_PERIOD * hz);
14039	}
14040}
14041
14042static void
14043ctl_enqueue_incoming(union ctl_io *io)
14044{
14045	struct ctl_softc *softc = control_softc;
14046	struct ctl_thread *thr;
14047	u_int idx;
14048
14049	idx = (io->io_hdr.nexus.targ_port * 127 +
14050	       io->io_hdr.nexus.initid.id) % worker_threads;
14051	thr = &softc->threads[idx];
14052	mtx_lock(&thr->queue_lock);
14053	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14054	mtx_unlock(&thr->queue_lock);
14055	wakeup(thr);
14056}
14057
14058static void
14059ctl_enqueue_rtr(union ctl_io *io)
14060{
14061	struct ctl_softc *softc = control_softc;
14062	struct ctl_thread *thr;
14063
14064	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14065	mtx_lock(&thr->queue_lock);
14066	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14067	mtx_unlock(&thr->queue_lock);
14068	wakeup(thr);
14069}
14070
14071static void
14072ctl_enqueue_done(union ctl_io *io)
14073{
14074	struct ctl_softc *softc = control_softc;
14075	struct ctl_thread *thr;
14076
14077	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14078	mtx_lock(&thr->queue_lock);
14079	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14080	mtx_unlock(&thr->queue_lock);
14081	wakeup(thr);
14082}
14083
14084static void
14085ctl_enqueue_isc(union ctl_io *io)
14086{
14087	struct ctl_softc *softc = control_softc;
14088	struct ctl_thread *thr;
14089
14090	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14091	mtx_lock(&thr->queue_lock);
14092	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14093	mtx_unlock(&thr->queue_lock);
14094	wakeup(thr);
14095}
14096
14097/* Initialization and failover */
14098
14099void
14100ctl_init_isc_msg(void)
14101{
14102	printf("CTL: Still calling this thing\n");
14103}
14104
14105/*
14106 * Init component
14107 * 	Initializes component into configuration defined by bootMode
14108 *	(see hasc-sv.c)
14109 *  	returns hasc_Status:
14110 * 		OK
14111 *		ERROR - fatal error
14112 */
14113static ctl_ha_comp_status
14114ctl_isc_init(struct ctl_ha_component *c)
14115{
14116	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14117
14118	c->status = ret;
14119	return ret;
14120}
14121
14122/* Start component
14123 * 	Starts component in state requested. If component starts successfully,
14124 *	it must set its own state to the requestrd state
14125 *	When requested state is HASC_STATE_HA, the component may refine it
14126 * 	by adding _SLAVE or _MASTER flags.
14127 *	Currently allowed state transitions are:
14128 *	UNKNOWN->HA		- initial startup
14129 *	UNKNOWN->SINGLE - initial startup when no parter detected
14130 *	HA->SINGLE		- failover
14131 * returns ctl_ha_comp_status:
14132 * 		OK	- component successfully started in requested state
14133 *		FAILED  - could not start the requested state, failover may
14134 * 			  be possible
14135 *		ERROR	- fatal error detected, no future startup possible
14136 */
14137static ctl_ha_comp_status
14138ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14139{
14140	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14141
14142	printf("%s: go\n", __func__);
14143
14144	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14145	if (c->state == CTL_HA_STATE_UNKNOWN ) {
14146		control_softc->is_single = 0;
14147		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14148		    != CTL_HA_STATUS_SUCCESS) {
14149			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14150			ret = CTL_HA_COMP_STATUS_ERROR;
14151		}
14152	} else if (CTL_HA_STATE_IS_HA(c->state)
14153		&& CTL_HA_STATE_IS_SINGLE(state)){
14154		// HA->SINGLE transition
14155	        ctl_failover();
14156		control_softc->is_single = 1;
14157	} else {
14158		printf("ctl_isc_start:Invalid state transition %X->%X\n",
14159		       c->state, state);
14160		ret = CTL_HA_COMP_STATUS_ERROR;
14161	}
14162	if (CTL_HA_STATE_IS_SINGLE(state))
14163		control_softc->is_single = 1;
14164
14165	c->state = state;
14166	c->status = ret;
14167	return ret;
14168}
14169
14170/*
14171 * Quiesce component
14172 * The component must clear any error conditions (set status to OK) and
14173 * prepare itself to another Start call
14174 * returns ctl_ha_comp_status:
14175 * 	OK
14176 *	ERROR
14177 */
14178static ctl_ha_comp_status
14179ctl_isc_quiesce(struct ctl_ha_component *c)
14180{
14181	int ret = CTL_HA_COMP_STATUS_OK;
14182
14183	ctl_pause_rtr = 1;
14184	c->status = ret;
14185	return ret;
14186}
14187
14188struct ctl_ha_component ctl_ha_component_ctlisc =
14189{
14190	.name = "CTL ISC",
14191	.state = CTL_HA_STATE_UNKNOWN,
14192	.init = ctl_isc_init,
14193	.start = ctl_isc_start,
14194	.quiesce = ctl_isc_quiesce
14195};
14196
14197/*
14198 *  vim: ts=8
14199 */
14200