ctl.c revision 277918
1/*-
2 * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3 * Copyright (c) 2012 The FreeBSD Foundation
4 * All rights reserved.
5 *
6 * Portions of this software were developed by Edward Tomasz Napierala
7 * under sponsorship from the FreeBSD Foundation.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions, and the following disclaimer,
14 *    without modification.
15 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
16 *    substantially similar to the "NO WARRANTY" disclaimer below
17 *    ("Disclaimer") and any redistribution must be conditioned upon
18 *    including a substantially similar Disclaimer requirement for further
19 *    binary redistribution.
20 *
21 * NO WARRANTY
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
25 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
31 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGES.
33 *
34 * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/ctl.c#8 $
35 */
36/*
37 * CAM Target Layer, a SCSI device emulation subsystem.
38 *
39 * Author: Ken Merry <ken@FreeBSD.org>
40 */
41
42#define _CTL_C
43
44#include <sys/cdefs.h>
45__FBSDID("$FreeBSD: stable/10/sys/cam/ctl/ctl.c 277918 2015-01-30 09:04:20Z 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;
363TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
364SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
365    &worker_threads, 1, "Number of worker threads");
366static int ctl_debug = CTL_DEBUG_NONE;
367TUNABLE_INT("kern.cam.ctl.debug", &ctl_debug);
368SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
369    &ctl_debug, 0, "Enabled debug flags");
370
371/*
372 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
373 * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
374 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
375 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
376 */
377#define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
378
379static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
380				  int param);
381static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
382static int ctl_init(void);
383void ctl_shutdown(void);
384static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
385static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
386static void ctl_ioctl_online(void *arg);
387static void ctl_ioctl_offline(void *arg);
388static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
389static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
390static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
391static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
392static int ctl_ioctl_submit_wait(union ctl_io *io);
393static void ctl_ioctl_datamove(union ctl_io *io);
394static void ctl_ioctl_done(union ctl_io *io);
395static void ctl_ioctl_hard_startstop_callback(void *arg,
396					      struct cfi_metatask *metatask);
397static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
398static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
399			      struct ctl_ooa *ooa_hdr,
400			      struct ctl_ooa_entry *kern_entries);
401static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
402		     struct thread *td);
403static uint32_t ctl_map_lun(struct ctl_softc *softc, int port_num, uint32_t lun);
404static uint32_t ctl_map_lun_back(struct ctl_softc *softc, int port_num, uint32_t lun);
405static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
406			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
407static int ctl_free_lun(struct ctl_lun *lun);
408static void ctl_create_lun(struct ctl_be_lun *be_lun);
409/**
410static void ctl_failover_change_pages(struct ctl_softc *softc,
411				      struct ctl_scsiio *ctsio, int master);
412**/
413
414static int ctl_do_mode_select(union ctl_io *io);
415static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
416			   uint64_t res_key, uint64_t sa_res_key,
417			   uint8_t type, uint32_t residx,
418			   struct ctl_scsiio *ctsio,
419			   struct scsi_per_res_out *cdb,
420			   struct scsi_per_res_out_parms* param);
421static void ctl_pro_preempt_other(struct ctl_lun *lun,
422				  union ctl_ha_msg *msg);
423static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
424static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
425static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
426static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
427static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
428static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
429static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
430					 int alloc_len);
431static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
432					 int alloc_len);
433static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
434static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
435static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
436static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
437static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
438static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
439    bool seq);
440static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
441static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
442    union ctl_io *pending_io, union ctl_io *ooa_io);
443static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
444				union ctl_io *starting_io);
445static int ctl_check_blocked(struct ctl_lun *lun);
446static int ctl_scsiio_lun_check(struct ctl_lun *lun,
447				const struct ctl_cmd_entry *entry,
448				struct ctl_scsiio *ctsio);
449//static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
450static void ctl_failover(void);
451static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
452			       struct ctl_scsiio *ctsio);
453static int ctl_scsiio(struct ctl_scsiio *ctsio);
454
455static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
456static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
457			    ctl_ua_type ua_type);
458static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
459			 ctl_ua_type ua_type);
460static int ctl_abort_task(union ctl_io *io);
461static int ctl_abort_task_set(union ctl_io *io);
462static int ctl_i_t_nexus_reset(union ctl_io *io);
463static void ctl_run_task(union ctl_io *io);
464#ifdef CTL_IO_DELAY
465static void ctl_datamove_timer_wakeup(void *arg);
466static void ctl_done_timer_wakeup(void *arg);
467#endif /* CTL_IO_DELAY */
468
469static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
470static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
471static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
472static void ctl_datamove_remote_write(union ctl_io *io);
473static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
474static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
475static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
476static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
477				    ctl_ha_dt_cb callback);
478static void ctl_datamove_remote_read(union ctl_io *io);
479static void ctl_datamove_remote(union ctl_io *io);
480static int ctl_process_done(union ctl_io *io);
481static void ctl_lun_thread(void *arg);
482static void ctl_thresh_thread(void *arg);
483static void ctl_work_thread(void *arg);
484static void ctl_enqueue_incoming(union ctl_io *io);
485static void ctl_enqueue_rtr(union ctl_io *io);
486static void ctl_enqueue_done(union ctl_io *io);
487static void ctl_enqueue_isc(union ctl_io *io);
488static const struct ctl_cmd_entry *
489    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
490static const struct ctl_cmd_entry *
491    ctl_validate_command(struct ctl_scsiio *ctsio);
492static int ctl_cmd_applicable(uint8_t lun_type,
493    const struct ctl_cmd_entry *entry);
494
495/*
496 * Load the serialization table.  This isn't very pretty, but is probably
497 * the easiest way to do it.
498 */
499#include "ctl_ser_table.c"
500
501/*
502 * We only need to define open, close and ioctl routines for this driver.
503 */
504static struct cdevsw ctl_cdevsw = {
505	.d_version =	D_VERSION,
506	.d_flags =	0,
507	.d_open =	ctl_open,
508	.d_close =	ctl_close,
509	.d_ioctl =	ctl_ioctl,
510	.d_name =	"ctl",
511};
512
513
514MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
515MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
516
517static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
518
519static moduledata_t ctl_moduledata = {
520	"ctl",
521	ctl_module_event_handler,
522	NULL
523};
524
525DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
526MODULE_VERSION(ctl, 1);
527
528static struct ctl_frontend ioctl_frontend =
529{
530	.name = "ioctl",
531};
532
533static void
534ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
535			    union ctl_ha_msg *msg_info)
536{
537	struct ctl_scsiio *ctsio;
538
539	if (msg_info->hdr.original_sc == NULL) {
540		printf("%s: original_sc == NULL!\n", __func__);
541		/* XXX KDM now what? */
542		return;
543	}
544
545	ctsio = &msg_info->hdr.original_sc->scsiio;
546	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
547	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
548	ctsio->io_hdr.status = msg_info->hdr.status;
549	ctsio->scsi_status = msg_info->scsi.scsi_status;
550	ctsio->sense_len = msg_info->scsi.sense_len;
551	ctsio->sense_residual = msg_info->scsi.sense_residual;
552	ctsio->residual = msg_info->scsi.residual;
553	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
554	       sizeof(ctsio->sense_data));
555	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
556	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
557	ctl_enqueue_isc((union ctl_io *)ctsio);
558}
559
560static void
561ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
562				union ctl_ha_msg *msg_info)
563{
564	struct ctl_scsiio *ctsio;
565
566	if (msg_info->hdr.serializing_sc == NULL) {
567		printf("%s: serializing_sc == NULL!\n", __func__);
568		/* XXX KDM now what? */
569		return;
570	}
571
572	ctsio = &msg_info->hdr.serializing_sc->scsiio;
573#if 0
574	/*
575	 * Attempt to catch the situation where an I/O has
576	 * been freed, and we're using it again.
577	 */
578	if (ctsio->io_hdr.io_type == 0xff) {
579		union ctl_io *tmp_io;
580		tmp_io = (union ctl_io *)ctsio;
581		printf("%s: %p use after free!\n", __func__,
582		       ctsio);
583		printf("%s: type %d msg %d cdb %x iptl: "
584		       "%d:%d:%d:%d tag 0x%04x "
585		       "flag %#x status %x\n",
586			__func__,
587			tmp_io->io_hdr.io_type,
588			tmp_io->io_hdr.msg_type,
589			tmp_io->scsiio.cdb[0],
590			tmp_io->io_hdr.nexus.initid.id,
591			tmp_io->io_hdr.nexus.targ_port,
592			tmp_io->io_hdr.nexus.targ_target.id,
593			tmp_io->io_hdr.nexus.targ_lun,
594			(tmp_io->io_hdr.io_type ==
595			CTL_IO_TASK) ?
596			tmp_io->taskio.tag_num :
597			tmp_io->scsiio.tag_num,
598		        tmp_io->io_hdr.flags,
599			tmp_io->io_hdr.status);
600	}
601#endif
602	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
603	ctl_enqueue_isc((union ctl_io *)ctsio);
604}
605
606/*
607 * ISC (Inter Shelf Communication) event handler.  Events from the HA
608 * subsystem come in here.
609 */
610static void
611ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
612{
613	struct ctl_softc *softc;
614	union ctl_io *io;
615	struct ctl_prio *presio;
616	ctl_ha_status isc_status;
617
618	softc = control_softc;
619	io = NULL;
620
621
622#if 0
623	printf("CTL: Isc Msg event %d\n", event);
624#endif
625	if (event == CTL_HA_EVT_MSG_RECV) {
626		union ctl_ha_msg msg_info;
627
628		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
629					     sizeof(msg_info), /*wait*/ 0);
630#if 0
631		printf("CTL: msg_type %d\n", msg_info.msg_type);
632#endif
633		if (isc_status != 0) {
634			printf("Error receiving message, status = %d\n",
635			       isc_status);
636			return;
637		}
638
639		switch (msg_info.hdr.msg_type) {
640		case CTL_MSG_SERIALIZE:
641#if 0
642			printf("Serialize\n");
643#endif
644			io = ctl_alloc_io_nowait(softc->othersc_pool);
645			if (io == NULL) {
646				printf("ctl_isc_event_handler: can't allocate "
647				       "ctl_io!\n");
648				/* Bad Juju */
649				/* Need to set busy and send msg back */
650				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
651				msg_info.hdr.status = CTL_SCSI_ERROR;
652				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
653				msg_info.scsi.sense_len = 0;
654			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
655				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
656				}
657				goto bailout;
658			}
659			ctl_zero_io(io);
660			// populate ctsio from msg_info
661			io->io_hdr.io_type = CTL_IO_SCSI;
662			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
663			io->io_hdr.original_sc = msg_info.hdr.original_sc;
664#if 0
665			printf("pOrig %x\n", (int)msg_info.original_sc);
666#endif
667			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
668					    CTL_FLAG_IO_ACTIVE;
669			/*
670			 * If we're in serialization-only mode, we don't
671			 * want to go through full done processing.  Thus
672			 * the COPY flag.
673			 *
674			 * XXX KDM add another flag that is more specific.
675			 */
676			if (softc->ha_mode == CTL_HA_MODE_SER_ONLY)
677				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
678			io->io_hdr.nexus = msg_info.hdr.nexus;
679#if 0
680			printf("targ %d, port %d, iid %d, lun %d\n",
681			       io->io_hdr.nexus.targ_target.id,
682			       io->io_hdr.nexus.targ_port,
683			       io->io_hdr.nexus.initid.id,
684			       io->io_hdr.nexus.targ_lun);
685#endif
686			io->scsiio.tag_num = msg_info.scsi.tag_num;
687			io->scsiio.tag_type = msg_info.scsi.tag_type;
688			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
689			       CTL_MAX_CDBLEN);
690			if (softc->ha_mode == CTL_HA_MODE_XFER) {
691				const struct ctl_cmd_entry *entry;
692
693				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
694				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
695				io->io_hdr.flags |=
696					entry->flags & CTL_FLAG_DATA_MASK;
697			}
698			ctl_enqueue_isc(io);
699			break;
700
701		/* Performed on the Originating SC, XFER mode only */
702		case CTL_MSG_DATAMOVE: {
703			struct ctl_sg_entry *sgl;
704			int i, j;
705
706			io = msg_info.hdr.original_sc;
707			if (io == NULL) {
708				printf("%s: original_sc == NULL!\n", __func__);
709				/* XXX KDM do something here */
710				break;
711			}
712			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
713			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
714			/*
715			 * Keep track of this, we need to send it back over
716			 * when the datamove is complete.
717			 */
718			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
719
720			if (msg_info.dt.sg_sequence == 0) {
721				/*
722				 * XXX KDM we use the preallocated S/G list
723				 * here, but we'll need to change this to
724				 * dynamic allocation if we need larger S/G
725				 * lists.
726				 */
727				if (msg_info.dt.kern_sg_entries >
728				    sizeof(io->io_hdr.remote_sglist) /
729				    sizeof(io->io_hdr.remote_sglist[0])) {
730					printf("%s: number of S/G entries "
731					    "needed %u > allocated num %zd\n",
732					    __func__,
733					    msg_info.dt.kern_sg_entries,
734					    sizeof(io->io_hdr.remote_sglist)/
735					    sizeof(io->io_hdr.remote_sglist[0]));
736
737					/*
738					 * XXX KDM send a message back to
739					 * the other side to shut down the
740					 * DMA.  The error will come back
741					 * through via the normal channel.
742					 */
743					break;
744				}
745				sgl = io->io_hdr.remote_sglist;
746				memset(sgl, 0,
747				       sizeof(io->io_hdr.remote_sglist));
748
749				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
750
751				io->scsiio.kern_sg_entries =
752					msg_info.dt.kern_sg_entries;
753				io->scsiio.rem_sg_entries =
754					msg_info.dt.kern_sg_entries;
755				io->scsiio.kern_data_len =
756					msg_info.dt.kern_data_len;
757				io->scsiio.kern_total_len =
758					msg_info.dt.kern_total_len;
759				io->scsiio.kern_data_resid =
760					msg_info.dt.kern_data_resid;
761				io->scsiio.kern_rel_offset =
762					msg_info.dt.kern_rel_offset;
763				/*
764				 * Clear out per-DMA flags.
765				 */
766				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
767				/*
768				 * Add per-DMA flags that are set for this
769				 * particular DMA request.
770				 */
771				io->io_hdr.flags |= msg_info.dt.flags &
772						    CTL_FLAG_RDMA_MASK;
773			} else
774				sgl = (struct ctl_sg_entry *)
775					io->scsiio.kern_data_ptr;
776
777			for (i = msg_info.dt.sent_sg_entries, j = 0;
778			     i < (msg_info.dt.sent_sg_entries +
779			     msg_info.dt.cur_sg_entries); i++, j++) {
780				sgl[i].addr = msg_info.dt.sg_list[j].addr;
781				sgl[i].len = msg_info.dt.sg_list[j].len;
782
783#if 0
784				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
785				       __func__,
786				       msg_info.dt.sg_list[j].addr,
787				       msg_info.dt.sg_list[j].len,
788				       sgl[i].addr, sgl[i].len, j, i);
789#endif
790			}
791#if 0
792			memcpy(&sgl[msg_info.dt.sent_sg_entries],
793			       msg_info.dt.sg_list,
794			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
795#endif
796
797			/*
798			 * If this is the last piece of the I/O, we've got
799			 * the full S/G list.  Queue processing in the thread.
800			 * Otherwise wait for the next piece.
801			 */
802			if (msg_info.dt.sg_last != 0)
803				ctl_enqueue_isc(io);
804			break;
805		}
806		/* Performed on the Serializing (primary) SC, XFER mode only */
807		case CTL_MSG_DATAMOVE_DONE: {
808			if (msg_info.hdr.serializing_sc == NULL) {
809				printf("%s: serializing_sc == NULL!\n",
810				       __func__);
811				/* XXX KDM now what? */
812				break;
813			}
814			/*
815			 * We grab the sense information here in case
816			 * there was a failure, so we can return status
817			 * back to the initiator.
818			 */
819			io = msg_info.hdr.serializing_sc;
820			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
821			io->io_hdr.status = msg_info.hdr.status;
822			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
823			io->scsiio.sense_len = msg_info.scsi.sense_len;
824			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
825			io->io_hdr.port_status = msg_info.scsi.fetd_status;
826			io->scsiio.residual = msg_info.scsi.residual;
827			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
828			       sizeof(io->scsiio.sense_data));
829			ctl_enqueue_isc(io);
830			break;
831		}
832
833		/* Preformed on Originating SC, SER_ONLY mode */
834		case CTL_MSG_R2R:
835			io = msg_info.hdr.original_sc;
836			if (io == NULL) {
837				printf("%s: Major Bummer\n", __func__);
838				return;
839			} else {
840#if 0
841				printf("pOrig %x\n",(int) ctsio);
842#endif
843			}
844			io->io_hdr.msg_type = CTL_MSG_R2R;
845			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
846			ctl_enqueue_isc(io);
847			break;
848
849		/*
850		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
851		 * mode.
852		 * Performed on the Originating (i.e. secondary) SC in XFER
853		 * mode
854		 */
855		case CTL_MSG_FINISH_IO:
856			if (softc->ha_mode == CTL_HA_MODE_XFER)
857				ctl_isc_handler_finish_xfer(softc,
858							    &msg_info);
859			else
860				ctl_isc_handler_finish_ser_only(softc,
861								&msg_info);
862			break;
863
864		/* Preformed on Originating SC */
865		case CTL_MSG_BAD_JUJU:
866			io = msg_info.hdr.original_sc;
867			if (io == NULL) {
868				printf("%s: Bad JUJU!, original_sc is NULL!\n",
869				       __func__);
870				break;
871			}
872			ctl_copy_sense_data(&msg_info, io);
873			/*
874			 * IO should have already been cleaned up on other
875			 * SC so clear this flag so we won't send a message
876			 * back to finish the IO there.
877			 */
878			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
879			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
880
881			/* io = msg_info.hdr.serializing_sc; */
882			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
883			ctl_enqueue_isc(io);
884			break;
885
886		/* Handle resets sent from the other side */
887		case CTL_MSG_MANAGE_TASKS: {
888			struct ctl_taskio *taskio;
889			taskio = (struct ctl_taskio *)ctl_alloc_io_nowait(
890			    softc->othersc_pool);
891			if (taskio == NULL) {
892				printf("ctl_isc_event_handler: can't allocate "
893				       "ctl_io!\n");
894				/* Bad Juju */
895				/* should I just call the proper reset func
896				   here??? */
897				goto bailout;
898			}
899			ctl_zero_io((union ctl_io *)taskio);
900			taskio->io_hdr.io_type = CTL_IO_TASK;
901			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
902			taskio->io_hdr.nexus = msg_info.hdr.nexus;
903			taskio->task_action = msg_info.task.task_action;
904			taskio->tag_num = msg_info.task.tag_num;
905			taskio->tag_type = msg_info.task.tag_type;
906#ifdef CTL_TIME_IO
907			taskio->io_hdr.start_time = time_uptime;
908			getbintime(&taskio->io_hdr.start_bt);
909#if 0
910			cs_prof_gettime(&taskio->io_hdr.start_ticks);
911#endif
912#endif /* CTL_TIME_IO */
913			ctl_run_task((union ctl_io *)taskio);
914			break;
915		}
916		/* Persistent Reserve action which needs attention */
917		case CTL_MSG_PERS_ACTION:
918			presio = (struct ctl_prio *)ctl_alloc_io_nowait(
919			    softc->othersc_pool);
920			if (presio == NULL) {
921				printf("ctl_isc_event_handler: can't allocate "
922				       "ctl_io!\n");
923				/* Bad Juju */
924				/* Need to set busy and send msg back */
925				goto bailout;
926			}
927			ctl_zero_io((union ctl_io *)presio);
928			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
929			presio->pr_msg = msg_info.pr;
930			ctl_enqueue_isc((union ctl_io *)presio);
931			break;
932		case CTL_MSG_SYNC_FE:
933			rcv_sync_msg = 1;
934			break;
935		default:
936		        printf("How did I get here?\n");
937		}
938	} else if (event == CTL_HA_EVT_MSG_SENT) {
939		if (param != CTL_HA_STATUS_SUCCESS) {
940			printf("Bad status from ctl_ha_msg_send status %d\n",
941			       param);
942		}
943		return;
944	} else if (event == CTL_HA_EVT_DISCONNECT) {
945		printf("CTL: Got a disconnect from Isc\n");
946		return;
947	} else {
948		printf("ctl_isc_event_handler: Unknown event %d\n", event);
949		return;
950	}
951
952bailout:
953	return;
954}
955
956static void
957ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
958{
959	struct scsi_sense_data *sense;
960
961	sense = &dest->scsiio.sense_data;
962	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
963	dest->scsiio.scsi_status = src->scsi.scsi_status;
964	dest->scsiio.sense_len = src->scsi.sense_len;
965	dest->io_hdr.status = src->hdr.status;
966}
967
968static void
969ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
970{
971	ctl_ua_type *pu;
972
973	mtx_assert(&lun->lun_lock, MA_OWNED);
974	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
975	if (pu == NULL)
976		return;
977	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
978}
979
980static void
981ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
982{
983	int i, j;
984
985	mtx_assert(&lun->lun_lock, MA_OWNED);
986	for (i = 0; i < CTL_MAX_PORTS; i++) {
987		if (lun->pending_ua[i] == NULL)
988			continue;
989		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
990			if (i * CTL_MAX_INIT_PER_PORT + j == except)
991				continue;
992			lun->pending_ua[i][j] |= ua;
993		}
994	}
995}
996
997static void
998ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
999{
1000	ctl_ua_type *pu;
1001
1002	mtx_assert(&lun->lun_lock, MA_OWNED);
1003	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1004	if (pu == NULL)
1005		return;
1006	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1007}
1008
1009static void
1010ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1011{
1012	int i, j;
1013
1014	mtx_assert(&lun->lun_lock, MA_OWNED);
1015	for (i = 0; i < CTL_MAX_PORTS; i++) {
1016		if (lun->pending_ua[i] == NULL)
1017			continue;
1018		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1019			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1020				continue;
1021			lun->pending_ua[i][j] &= ~ua;
1022		}
1023	}
1024}
1025
1026static int
1027ctl_ha_state_sysctl(SYSCTL_HANDLER_ARGS)
1028{
1029	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1030	struct ctl_lun *lun;
1031	int error, value;
1032
1033	if (softc->flags & CTL_FLAG_ACTIVE_SHELF)
1034		value = 0;
1035	else
1036		value = 1;
1037
1038	error = sysctl_handle_int(oidp, &value, 0, req);
1039	if ((error != 0) || (req->newptr == NULL))
1040		return (error);
1041
1042	mtx_lock(&softc->ctl_lock);
1043	if (value == 0)
1044		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1045	else
1046		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1047	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1048		mtx_lock(&lun->lun_lock);
1049		ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1050		mtx_unlock(&lun->lun_lock);
1051	}
1052	mtx_unlock(&softc->ctl_lock);
1053	return (0);
1054}
1055
1056static int
1057ctl_init(void)
1058{
1059	struct ctl_softc *softc;
1060	void *other_pool;
1061	struct ctl_port *port;
1062	int i, error, retval;
1063	//int isc_retval;
1064
1065	retval = 0;
1066	ctl_pause_rtr = 0;
1067        rcv_sync_msg = 0;
1068
1069	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1070			       M_WAITOK | M_ZERO);
1071	softc = control_softc;
1072
1073	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1074			      "cam/ctl");
1075
1076	softc->dev->si_drv1 = softc;
1077
1078	/*
1079	 * By default, return a "bad LUN" peripheral qualifier for unknown
1080	 * LUNs.  The user can override this default using the tunable or
1081	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
1082	 */
1083	softc->inquiry_pq_no_lun = 1;
1084	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
1085			  &softc->inquiry_pq_no_lun);
1086	sysctl_ctx_init(&softc->sysctl_ctx);
1087	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1088		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1089		CTLFLAG_RD, 0, "CAM Target Layer");
1090
1091	if (softc->sysctl_tree == NULL) {
1092		printf("%s: unable to allocate sysctl tree\n", __func__);
1093		destroy_dev(softc->dev);
1094		free(control_softc, M_DEVBUF);
1095		control_softc = NULL;
1096		return (ENOMEM);
1097	}
1098
1099	SYSCTL_ADD_INT(&softc->sysctl_ctx,
1100		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1101		       "inquiry_pq_no_lun", CTLFLAG_RW,
1102		       &softc->inquiry_pq_no_lun, 0,
1103		       "Report no lun possible for invalid LUNs");
1104
1105	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1106	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1107	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1108	softc->open_count = 0;
1109
1110	/*
1111	 * Default to actually sending a SYNCHRONIZE CACHE command down to
1112	 * the drive.
1113	 */
1114	softc->flags = CTL_FLAG_REAL_SYNC;
1115
1116	/*
1117	 * In Copan's HA scheme, the "master" and "slave" roles are
1118	 * figured out through the slot the controller is in.  Although it
1119	 * is an active/active system, someone has to be in charge.
1120	 */
1121	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1122	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1123	    "HA head ID (0 - no HA)");
1124	if (softc->ha_id == 0) {
1125		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1126		softc->is_single = 1;
1127		softc->port_offset = 0;
1128	} else
1129		softc->port_offset = (softc->ha_id - 1) * CTL_MAX_PORTS;
1130	softc->persis_offset = softc->port_offset * CTL_MAX_INIT_PER_PORT;
1131
1132	/*
1133	 * XXX KDM need to figure out where we want to get our target ID
1134	 * and WWID.  Is it different on each port?
1135	 */
1136	softc->target.id = 0;
1137	softc->target.wwid[0] = 0x12345678;
1138	softc->target.wwid[1] = 0x87654321;
1139	STAILQ_INIT(&softc->lun_list);
1140	STAILQ_INIT(&softc->pending_lun_queue);
1141	STAILQ_INIT(&softc->fe_list);
1142	STAILQ_INIT(&softc->port_list);
1143	STAILQ_INIT(&softc->be_list);
1144	ctl_tpc_init(softc);
1145
1146	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1147	                    &other_pool) != 0)
1148	{
1149		printf("ctl: can't allocate %d entry other SC pool, "
1150		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1151		return (ENOMEM);
1152	}
1153	softc->othersc_pool = other_pool;
1154
1155	if (worker_threads <= 0)
1156		worker_threads = max(1, mp_ncpus / 4);
1157	if (worker_threads > CTL_MAX_THREADS)
1158		worker_threads = CTL_MAX_THREADS;
1159
1160	for (i = 0; i < worker_threads; i++) {
1161		struct ctl_thread *thr = &softc->threads[i];
1162
1163		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1164		thr->ctl_softc = softc;
1165		STAILQ_INIT(&thr->incoming_queue);
1166		STAILQ_INIT(&thr->rtr_queue);
1167		STAILQ_INIT(&thr->done_queue);
1168		STAILQ_INIT(&thr->isc_queue);
1169
1170		error = kproc_kthread_add(ctl_work_thread, thr,
1171		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1172		if (error != 0) {
1173			printf("error creating CTL work thread!\n");
1174			ctl_pool_free(other_pool);
1175			return (error);
1176		}
1177	}
1178	error = kproc_kthread_add(ctl_lun_thread, softc,
1179	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1180	if (error != 0) {
1181		printf("error creating CTL lun thread!\n");
1182		ctl_pool_free(other_pool);
1183		return (error);
1184	}
1185	error = kproc_kthread_add(ctl_thresh_thread, softc,
1186	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1187	if (error != 0) {
1188		printf("error creating CTL threshold thread!\n");
1189		ctl_pool_free(other_pool);
1190		return (error);
1191	}
1192	if (bootverbose)
1193		printf("ctl: CAM Target Layer loaded\n");
1194
1195	/*
1196	 * Initialize the ioctl front end.
1197	 */
1198	ctl_frontend_register(&ioctl_frontend);
1199	port = &softc->ioctl_info.port;
1200	port->frontend = &ioctl_frontend;
1201	sprintf(softc->ioctl_info.port_name, "ioctl");
1202	port->port_type = CTL_PORT_IOCTL;
1203	port->num_requested_ctl_io = 100;
1204	port->port_name = softc->ioctl_info.port_name;
1205	port->port_online = ctl_ioctl_online;
1206	port->port_offline = ctl_ioctl_offline;
1207	port->onoff_arg = &softc->ioctl_info;
1208	port->lun_enable = ctl_ioctl_lun_enable;
1209	port->lun_disable = ctl_ioctl_lun_disable;
1210	port->targ_lun_arg = &softc->ioctl_info;
1211	port->fe_datamove = ctl_ioctl_datamove;
1212	port->fe_done = ctl_ioctl_done;
1213	port->max_targets = 15;
1214	port->max_target_id = 15;
1215
1216	if (ctl_port_register(&softc->ioctl_info.port) != 0) {
1217		printf("ctl: ioctl front end registration failed, will "
1218		       "continue anyway\n");
1219	}
1220
1221	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1222	    OID_AUTO, "ha_state", CTLTYPE_INT | CTLFLAG_RWTUN,
1223	    softc, 0, ctl_ha_state_sysctl, "I", "HA state for this head");
1224
1225#ifdef CTL_IO_DELAY
1226	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1227		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1228		       sizeof(struct callout), CTL_TIMER_BYTES);
1229		return (EINVAL);
1230	}
1231#endif /* CTL_IO_DELAY */
1232
1233	return (0);
1234}
1235
1236void
1237ctl_shutdown(void)
1238{
1239	struct ctl_softc *softc;
1240	struct ctl_lun *lun, *next_lun;
1241
1242	softc = (struct ctl_softc *)control_softc;
1243
1244	if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1245		printf("ctl: ioctl front end deregistration failed\n");
1246
1247	mtx_lock(&softc->ctl_lock);
1248
1249	/*
1250	 * Free up each LUN.
1251	 */
1252	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1253		next_lun = STAILQ_NEXT(lun, links);
1254		ctl_free_lun(lun);
1255	}
1256
1257	mtx_unlock(&softc->ctl_lock);
1258
1259	ctl_frontend_deregister(&ioctl_frontend);
1260
1261#if 0
1262	ctl_shutdown_thread(softc->work_thread);
1263	mtx_destroy(&softc->queue_lock);
1264#endif
1265
1266	ctl_tpc_shutdown(softc);
1267	uma_zdestroy(softc->io_zone);
1268	mtx_destroy(&softc->ctl_lock);
1269
1270	destroy_dev(softc->dev);
1271
1272	sysctl_ctx_free(&softc->sysctl_ctx);
1273
1274	free(control_softc, M_DEVBUF);
1275	control_softc = NULL;
1276
1277	if (bootverbose)
1278		printf("ctl: CAM Target Layer unloaded\n");
1279}
1280
1281static int
1282ctl_module_event_handler(module_t mod, int what, void *arg)
1283{
1284
1285	switch (what) {
1286	case MOD_LOAD:
1287		return (ctl_init());
1288	case MOD_UNLOAD:
1289		return (EBUSY);
1290	default:
1291		return (EOPNOTSUPP);
1292	}
1293}
1294
1295/*
1296 * XXX KDM should we do some access checks here?  Bump a reference count to
1297 * prevent a CTL module from being unloaded while someone has it open?
1298 */
1299static int
1300ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1301{
1302	return (0);
1303}
1304
1305static int
1306ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1307{
1308	return (0);
1309}
1310
1311int
1312ctl_port_enable(ctl_port_type port_type)
1313{
1314	struct ctl_softc *softc = control_softc;
1315	struct ctl_port *port;
1316
1317	if (softc->is_single == 0) {
1318		union ctl_ha_msg msg_info;
1319		int isc_retval;
1320
1321#if 0
1322		printf("%s: HA mode, synchronizing frontend enable\n",
1323		        __func__);
1324#endif
1325		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1326	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1327		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1328			printf("Sync msg send error retval %d\n", isc_retval);
1329		}
1330		if (!rcv_sync_msg) {
1331			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1332			        sizeof(msg_info), 1);
1333		}
1334#if 0
1335        	printf("CTL:Frontend Enable\n");
1336	} else {
1337		printf("%s: single mode, skipping frontend synchronization\n",
1338		        __func__);
1339#endif
1340	}
1341
1342	STAILQ_FOREACH(port, &softc->port_list, links) {
1343		if (port_type & port->port_type)
1344		{
1345#if 0
1346			printf("port %d\n", port->targ_port);
1347#endif
1348			ctl_port_online(port);
1349		}
1350	}
1351
1352	return (0);
1353}
1354
1355int
1356ctl_port_disable(ctl_port_type port_type)
1357{
1358	struct ctl_softc *softc;
1359	struct ctl_port *port;
1360
1361	softc = control_softc;
1362
1363	STAILQ_FOREACH(port, &softc->port_list, links) {
1364		if (port_type & port->port_type)
1365			ctl_port_offline(port);
1366	}
1367
1368	return (0);
1369}
1370
1371/*
1372 * Returns 0 for success, 1 for failure.
1373 * Currently the only failure mode is if there aren't enough entries
1374 * allocated.  So, in case of a failure, look at num_entries_dropped,
1375 * reallocate and try again.
1376 */
1377int
1378ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1379	      int *num_entries_filled, int *num_entries_dropped,
1380	      ctl_port_type port_type, int no_virtual)
1381{
1382	struct ctl_softc *softc;
1383	struct ctl_port *port;
1384	int entries_dropped, entries_filled;
1385	int retval;
1386	int i;
1387
1388	softc = control_softc;
1389
1390	retval = 0;
1391	entries_filled = 0;
1392	entries_dropped = 0;
1393
1394	i = 0;
1395	mtx_lock(&softc->ctl_lock);
1396	STAILQ_FOREACH(port, &softc->port_list, links) {
1397		struct ctl_port_entry *entry;
1398
1399		if ((port->port_type & port_type) == 0)
1400			continue;
1401
1402		if ((no_virtual != 0)
1403		 && (port->virtual_port != 0))
1404			continue;
1405
1406		if (entries_filled >= num_entries_alloced) {
1407			entries_dropped++;
1408			continue;
1409		}
1410		entry = &entries[i];
1411
1412		entry->port_type = port->port_type;
1413		strlcpy(entry->port_name, port->port_name,
1414			sizeof(entry->port_name));
1415		entry->physical_port = port->physical_port;
1416		entry->virtual_port = port->virtual_port;
1417		entry->wwnn = port->wwnn;
1418		entry->wwpn = port->wwpn;
1419
1420		i++;
1421		entries_filled++;
1422	}
1423
1424	mtx_unlock(&softc->ctl_lock);
1425
1426	if (entries_dropped > 0)
1427		retval = 1;
1428
1429	*num_entries_dropped = entries_dropped;
1430	*num_entries_filled = entries_filled;
1431
1432	return (retval);
1433}
1434
1435static void
1436ctl_ioctl_online(void *arg)
1437{
1438	struct ctl_ioctl_info *ioctl_info;
1439
1440	ioctl_info = (struct ctl_ioctl_info *)arg;
1441
1442	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1443}
1444
1445static void
1446ctl_ioctl_offline(void *arg)
1447{
1448	struct ctl_ioctl_info *ioctl_info;
1449
1450	ioctl_info = (struct ctl_ioctl_info *)arg;
1451
1452	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1453}
1454
1455/*
1456 * Remove an initiator by port number and initiator ID.
1457 * Returns 0 for success, -1 for failure.
1458 */
1459int
1460ctl_remove_initiator(struct ctl_port *port, int iid)
1461{
1462	struct ctl_softc *softc = control_softc;
1463
1464	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1465
1466	if (iid > CTL_MAX_INIT_PER_PORT) {
1467		printf("%s: initiator ID %u > maximun %u!\n",
1468		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1469		return (-1);
1470	}
1471
1472	mtx_lock(&softc->ctl_lock);
1473	port->wwpn_iid[iid].in_use--;
1474	port->wwpn_iid[iid].last_use = time_uptime;
1475	mtx_unlock(&softc->ctl_lock);
1476
1477	return (0);
1478}
1479
1480/*
1481 * Add an initiator to the initiator map.
1482 * Returns iid for success, < 0 for failure.
1483 */
1484int
1485ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1486{
1487	struct ctl_softc *softc = control_softc;
1488	time_t best_time;
1489	int i, best;
1490
1491	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1492
1493	if (iid >= CTL_MAX_INIT_PER_PORT) {
1494		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1495		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1496		free(name, M_CTL);
1497		return (-1);
1498	}
1499
1500	mtx_lock(&softc->ctl_lock);
1501
1502	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1503		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1504			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1505				iid = i;
1506				break;
1507			}
1508			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1509			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1510				iid = i;
1511				break;
1512			}
1513		}
1514	}
1515
1516	if (iid < 0) {
1517		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1518			if (port->wwpn_iid[i].in_use == 0 &&
1519			    port->wwpn_iid[i].wwpn == 0 &&
1520			    port->wwpn_iid[i].name == NULL) {
1521				iid = i;
1522				break;
1523			}
1524		}
1525	}
1526
1527	if (iid < 0) {
1528		best = -1;
1529		best_time = INT32_MAX;
1530		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1531			if (port->wwpn_iid[i].in_use == 0) {
1532				if (port->wwpn_iid[i].last_use < best_time) {
1533					best = i;
1534					best_time = port->wwpn_iid[i].last_use;
1535				}
1536			}
1537		}
1538		iid = best;
1539	}
1540
1541	if (iid < 0) {
1542		mtx_unlock(&softc->ctl_lock);
1543		free(name, M_CTL);
1544		return (-2);
1545	}
1546
1547	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1548		/*
1549		 * This is not an error yet.
1550		 */
1551		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1552#if 0
1553			printf("%s: port %d iid %u WWPN %#jx arrived"
1554			    " again\n", __func__, port->targ_port,
1555			    iid, (uintmax_t)wwpn);
1556#endif
1557			goto take;
1558		}
1559		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1560		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1561#if 0
1562			printf("%s: port %d iid %u name '%s' arrived"
1563			    " again\n", __func__, port->targ_port,
1564			    iid, name);
1565#endif
1566			goto take;
1567		}
1568
1569		/*
1570		 * This is an error, but what do we do about it?  The
1571		 * driver is telling us we have a new WWPN for this
1572		 * initiator ID, so we pretty much need to use it.
1573		 */
1574		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1575		    " but WWPN %#jx '%s' is still at that address\n",
1576		    __func__, port->targ_port, iid, wwpn, name,
1577		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1578		    port->wwpn_iid[iid].name);
1579
1580		/*
1581		 * XXX KDM clear have_ca and ua_pending on each LUN for
1582		 * this initiator.
1583		 */
1584	}
1585take:
1586	free(port->wwpn_iid[iid].name, M_CTL);
1587	port->wwpn_iid[iid].name = name;
1588	port->wwpn_iid[iid].wwpn = wwpn;
1589	port->wwpn_iid[iid].in_use++;
1590	mtx_unlock(&softc->ctl_lock);
1591
1592	return (iid);
1593}
1594
1595static int
1596ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1597{
1598	int len;
1599
1600	switch (port->port_type) {
1601	case CTL_PORT_FC:
1602	{
1603		struct scsi_transportid_fcp *id =
1604		    (struct scsi_transportid_fcp *)buf;
1605		if (port->wwpn_iid[iid].wwpn == 0)
1606			return (0);
1607		memset(id, 0, sizeof(*id));
1608		id->format_protocol = SCSI_PROTO_FC;
1609		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1610		return (sizeof(*id));
1611	}
1612	case CTL_PORT_ISCSI:
1613	{
1614		struct scsi_transportid_iscsi_port *id =
1615		    (struct scsi_transportid_iscsi_port *)buf;
1616		if (port->wwpn_iid[iid].name == NULL)
1617			return (0);
1618		memset(id, 0, 256);
1619		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1620		    SCSI_PROTO_ISCSI;
1621		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1622		len = roundup2(min(len, 252), 4);
1623		scsi_ulto2b(len, id->additional_length);
1624		return (sizeof(*id) + len);
1625	}
1626	case CTL_PORT_SAS:
1627	{
1628		struct scsi_transportid_sas *id =
1629		    (struct scsi_transportid_sas *)buf;
1630		if (port->wwpn_iid[iid].wwpn == 0)
1631			return (0);
1632		memset(id, 0, sizeof(*id));
1633		id->format_protocol = SCSI_PROTO_SAS;
1634		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1635		return (sizeof(*id));
1636	}
1637	default:
1638	{
1639		struct scsi_transportid_spi *id =
1640		    (struct scsi_transportid_spi *)buf;
1641		memset(id, 0, sizeof(*id));
1642		id->format_protocol = SCSI_PROTO_SPI;
1643		scsi_ulto2b(iid, id->scsi_addr);
1644		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1645		return (sizeof(*id));
1646	}
1647	}
1648}
1649
1650static int
1651ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1652{
1653	return (0);
1654}
1655
1656static int
1657ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1658{
1659	return (0);
1660}
1661
1662/*
1663 * Data movement routine for the CTL ioctl frontend port.
1664 */
1665static int
1666ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1667{
1668	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1669	struct ctl_sg_entry ext_entry, kern_entry;
1670	int ext_sglen, ext_sg_entries, kern_sg_entries;
1671	int ext_sg_start, ext_offset;
1672	int len_to_copy, len_copied;
1673	int kern_watermark, ext_watermark;
1674	int ext_sglist_malloced;
1675	int i, j;
1676
1677	ext_sglist_malloced = 0;
1678	ext_sg_start = 0;
1679	ext_offset = 0;
1680
1681	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1682
1683	/*
1684	 * If this flag is set, fake the data transfer.
1685	 */
1686	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1687		ctsio->ext_data_filled = ctsio->ext_data_len;
1688		goto bailout;
1689	}
1690
1691	/*
1692	 * To simplify things here, if we have a single buffer, stick it in
1693	 * a S/G entry and just make it a single entry S/G list.
1694	 */
1695	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1696		int len_seen;
1697
1698		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1699
1700		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1701							   M_WAITOK);
1702		ext_sglist_malloced = 1;
1703		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1704				   ext_sglen) != 0) {
1705			ctl_set_internal_failure(ctsio,
1706						 /*sks_valid*/ 0,
1707						 /*retry_count*/ 0);
1708			goto bailout;
1709		}
1710		ext_sg_entries = ctsio->ext_sg_entries;
1711		len_seen = 0;
1712		for (i = 0; i < ext_sg_entries; i++) {
1713			if ((len_seen + ext_sglist[i].len) >=
1714			     ctsio->ext_data_filled) {
1715				ext_sg_start = i;
1716				ext_offset = ctsio->ext_data_filled - len_seen;
1717				break;
1718			}
1719			len_seen += ext_sglist[i].len;
1720		}
1721	} else {
1722		ext_sglist = &ext_entry;
1723		ext_sglist->addr = ctsio->ext_data_ptr;
1724		ext_sglist->len = ctsio->ext_data_len;
1725		ext_sg_entries = 1;
1726		ext_sg_start = 0;
1727		ext_offset = ctsio->ext_data_filled;
1728	}
1729
1730	if (ctsio->kern_sg_entries > 0) {
1731		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1732		kern_sg_entries = ctsio->kern_sg_entries;
1733	} else {
1734		kern_sglist = &kern_entry;
1735		kern_sglist->addr = ctsio->kern_data_ptr;
1736		kern_sglist->len = ctsio->kern_data_len;
1737		kern_sg_entries = 1;
1738	}
1739
1740
1741	kern_watermark = 0;
1742	ext_watermark = ext_offset;
1743	len_copied = 0;
1744	for (i = ext_sg_start, j = 0;
1745	     i < ext_sg_entries && j < kern_sg_entries;) {
1746		uint8_t *ext_ptr, *kern_ptr;
1747
1748		len_to_copy = MIN(ext_sglist[i].len - ext_watermark,
1749				  kern_sglist[j].len - kern_watermark);
1750
1751		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1752		ext_ptr = ext_ptr + ext_watermark;
1753		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1754			/*
1755			 * XXX KDM fix this!
1756			 */
1757			panic("need to implement bus address support");
1758#if 0
1759			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1760#endif
1761		} else
1762			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1763		kern_ptr = kern_ptr + kern_watermark;
1764
1765		kern_watermark += len_to_copy;
1766		ext_watermark += len_to_copy;
1767
1768		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1769		     CTL_FLAG_DATA_IN) {
1770			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1771					 "bytes to user\n", len_to_copy));
1772			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1773					 "to %p\n", kern_ptr, ext_ptr));
1774			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1775				ctl_set_internal_failure(ctsio,
1776							 /*sks_valid*/ 0,
1777							 /*retry_count*/ 0);
1778				goto bailout;
1779			}
1780		} else {
1781			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1782					 "bytes from user\n", len_to_copy));
1783			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1784					 "to %p\n", ext_ptr, kern_ptr));
1785			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1786				ctl_set_internal_failure(ctsio,
1787							 /*sks_valid*/ 0,
1788							 /*retry_count*/0);
1789				goto bailout;
1790			}
1791		}
1792
1793		len_copied += len_to_copy;
1794
1795		if (ext_sglist[i].len == ext_watermark) {
1796			i++;
1797			ext_watermark = 0;
1798		}
1799
1800		if (kern_sglist[j].len == kern_watermark) {
1801			j++;
1802			kern_watermark = 0;
1803		}
1804	}
1805
1806	ctsio->ext_data_filled += len_copied;
1807
1808	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1809			 "kern_sg_entries: %d\n", ext_sg_entries,
1810			 kern_sg_entries));
1811	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1812			 "kern_data_len = %d\n", ctsio->ext_data_len,
1813			 ctsio->kern_data_len));
1814
1815
1816	/* XXX KDM set residual?? */
1817bailout:
1818
1819	if (ext_sglist_malloced != 0)
1820		free(ext_sglist, M_CTL);
1821
1822	return (CTL_RETVAL_COMPLETE);
1823}
1824
1825/*
1826 * Serialize a command that went down the "wrong" side, and so was sent to
1827 * this controller for execution.  The logic is a little different than the
1828 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1829 * sent back to the other side, but in the success case, we execute the
1830 * command on this side (XFER mode) or tell the other side to execute it
1831 * (SER_ONLY mode).
1832 */
1833static int
1834ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1835{
1836	struct ctl_softc *softc;
1837	union ctl_ha_msg msg_info;
1838	struct ctl_lun *lun;
1839	int retval = 0;
1840	uint32_t targ_lun;
1841
1842	softc = control_softc;
1843
1844	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1845	lun = softc->ctl_luns[targ_lun];
1846	if (lun==NULL)
1847	{
1848		/*
1849		 * Why isn't LUN defined? The other side wouldn't
1850		 * send a cmd if the LUN is undefined.
1851		 */
1852		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1853
1854		/* "Logical unit not supported" */
1855		ctl_set_sense_data(&msg_info.scsi.sense_data,
1856				   lun,
1857				   /*sense_format*/SSD_TYPE_NONE,
1858				   /*current_error*/ 1,
1859				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1860				   /*asc*/ 0x25,
1861				   /*ascq*/ 0x00,
1862				   SSD_ELEM_NONE);
1863
1864		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1865		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1866		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1867		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1868		msg_info.hdr.serializing_sc = NULL;
1869		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1870	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1871				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1872		}
1873		return(1);
1874
1875	}
1876
1877	mtx_lock(&lun->lun_lock);
1878    	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1879
1880	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1881		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1882		 ooa_links))) {
1883	case CTL_ACTION_BLOCK:
1884		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1885		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1886				  blocked_links);
1887		break;
1888	case CTL_ACTION_PASS:
1889	case CTL_ACTION_SKIP:
1890		if (softc->ha_mode == CTL_HA_MODE_XFER) {
1891			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1892			ctl_enqueue_rtr((union ctl_io *)ctsio);
1893		} else {
1894
1895			/* send msg back to other side */
1896			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1897			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1898			msg_info.hdr.msg_type = CTL_MSG_R2R;
1899#if 0
1900			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1901#endif
1902		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1903			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1904			}
1905		}
1906		break;
1907	case CTL_ACTION_OVERLAP:
1908		/* OVERLAPPED COMMANDS ATTEMPTED */
1909		ctl_set_sense_data(&msg_info.scsi.sense_data,
1910				   lun,
1911				   /*sense_format*/SSD_TYPE_NONE,
1912				   /*current_error*/ 1,
1913				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1914				   /*asc*/ 0x4E,
1915				   /*ascq*/ 0x00,
1916				   SSD_ELEM_NONE);
1917
1918		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1919		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1920		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1921		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1922		msg_info.hdr.serializing_sc = NULL;
1923		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1924#if 0
1925		printf("BAD JUJU:Major Bummer Overlap\n");
1926#endif
1927		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1928		retval = 1;
1929		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1930		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1931		}
1932		break;
1933	case CTL_ACTION_OVERLAP_TAG:
1934		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1935		ctl_set_sense_data(&msg_info.scsi.sense_data,
1936				   lun,
1937				   /*sense_format*/SSD_TYPE_NONE,
1938				   /*current_error*/ 1,
1939				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1940				   /*asc*/ 0x4D,
1941				   /*ascq*/ ctsio->tag_num & 0xff,
1942				   SSD_ELEM_NONE);
1943
1944		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1945		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1946		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1947		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1948		msg_info.hdr.serializing_sc = NULL;
1949		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1950#if 0
1951		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1952#endif
1953		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1954		retval = 1;
1955		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1956		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1957		}
1958		break;
1959	case CTL_ACTION_ERROR:
1960	default:
1961		/* "Internal target failure" */
1962		ctl_set_sense_data(&msg_info.scsi.sense_data,
1963				   lun,
1964				   /*sense_format*/SSD_TYPE_NONE,
1965				   /*current_error*/ 1,
1966				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1967				   /*asc*/ 0x44,
1968				   /*ascq*/ 0x00,
1969				   SSD_ELEM_NONE);
1970
1971		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1972		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1973		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1974		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1975		msg_info.hdr.serializing_sc = NULL;
1976		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1977#if 0
1978		printf("BAD JUJU:Major Bummer HW Error\n");
1979#endif
1980		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1981		retval = 1;
1982		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1983		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1984		}
1985		break;
1986	}
1987	mtx_unlock(&lun->lun_lock);
1988	return (retval);
1989}
1990
1991static int
1992ctl_ioctl_submit_wait(union ctl_io *io)
1993{
1994	struct ctl_fe_ioctl_params params;
1995	ctl_fe_ioctl_state last_state;
1996	int done, retval;
1997
1998	retval = 0;
1999
2000	bzero(&params, sizeof(params));
2001
2002	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
2003	cv_init(&params.sem, "ctlioccv");
2004	params.state = CTL_IOCTL_INPROG;
2005	last_state = params.state;
2006
2007	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
2008
2009	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
2010
2011	/* This shouldn't happen */
2012	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
2013		return (retval);
2014
2015	done = 0;
2016
2017	do {
2018		mtx_lock(&params.ioctl_mtx);
2019		/*
2020		 * Check the state here, and don't sleep if the state has
2021		 * already changed (i.e. wakeup has already occured, but we
2022		 * weren't waiting yet).
2023		 */
2024		if (params.state == last_state) {
2025			/* XXX KDM cv_wait_sig instead? */
2026			cv_wait(&params.sem, &params.ioctl_mtx);
2027		}
2028		last_state = params.state;
2029
2030		switch (params.state) {
2031		case CTL_IOCTL_INPROG:
2032			/* Why did we wake up? */
2033			/* XXX KDM error here? */
2034			mtx_unlock(&params.ioctl_mtx);
2035			break;
2036		case CTL_IOCTL_DATAMOVE:
2037			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
2038
2039			/*
2040			 * change last_state back to INPROG to avoid
2041			 * deadlock on subsequent data moves.
2042			 */
2043			params.state = last_state = CTL_IOCTL_INPROG;
2044
2045			mtx_unlock(&params.ioctl_mtx);
2046			ctl_ioctl_do_datamove(&io->scsiio);
2047			/*
2048			 * Note that in some cases, most notably writes,
2049			 * this will queue the I/O and call us back later.
2050			 * In other cases, generally reads, this routine
2051			 * will immediately call back and wake us up,
2052			 * probably using our own context.
2053			 */
2054			io->scsiio.be_move_done(io);
2055			break;
2056		case CTL_IOCTL_DONE:
2057			mtx_unlock(&params.ioctl_mtx);
2058			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
2059			done = 1;
2060			break;
2061		default:
2062			mtx_unlock(&params.ioctl_mtx);
2063			/* XXX KDM error here? */
2064			break;
2065		}
2066	} while (done == 0);
2067
2068	mtx_destroy(&params.ioctl_mtx);
2069	cv_destroy(&params.sem);
2070
2071	return (CTL_RETVAL_COMPLETE);
2072}
2073
2074static void
2075ctl_ioctl_datamove(union ctl_io *io)
2076{
2077	struct ctl_fe_ioctl_params *params;
2078
2079	params = (struct ctl_fe_ioctl_params *)
2080		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2081
2082	mtx_lock(&params->ioctl_mtx);
2083	params->state = CTL_IOCTL_DATAMOVE;
2084	cv_broadcast(&params->sem);
2085	mtx_unlock(&params->ioctl_mtx);
2086}
2087
2088static void
2089ctl_ioctl_done(union ctl_io *io)
2090{
2091	struct ctl_fe_ioctl_params *params;
2092
2093	params = (struct ctl_fe_ioctl_params *)
2094		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2095
2096	mtx_lock(&params->ioctl_mtx);
2097	params->state = CTL_IOCTL_DONE;
2098	cv_broadcast(&params->sem);
2099	mtx_unlock(&params->ioctl_mtx);
2100}
2101
2102static void
2103ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2104{
2105	struct ctl_fe_ioctl_startstop_info *sd_info;
2106
2107	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2108
2109	sd_info->hs_info.status = metatask->status;
2110	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2111	sd_info->hs_info.luns_complete =
2112		metatask->taskinfo.startstop.luns_complete;
2113	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2114
2115	cv_broadcast(&sd_info->sem);
2116}
2117
2118static void
2119ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2120{
2121	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2122
2123	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2124
2125	mtx_lock(fe_bbr_info->lock);
2126	fe_bbr_info->bbr_info->status = metatask->status;
2127	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2128	fe_bbr_info->wakeup_done = 1;
2129	mtx_unlock(fe_bbr_info->lock);
2130
2131	cv_broadcast(&fe_bbr_info->sem);
2132}
2133
2134/*
2135 * Returns 0 for success, errno for failure.
2136 */
2137static int
2138ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2139		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2140{
2141	union ctl_io *io;
2142	int retval;
2143
2144	retval = 0;
2145
2146	mtx_lock(&lun->lun_lock);
2147	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2148	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2149	     ooa_links)) {
2150		struct ctl_ooa_entry *entry;
2151
2152		/*
2153		 * If we've got more than we can fit, just count the
2154		 * remaining entries.
2155		 */
2156		if (*cur_fill_num >= ooa_hdr->alloc_num)
2157			continue;
2158
2159		entry = &kern_entries[*cur_fill_num];
2160
2161		entry->tag_num = io->scsiio.tag_num;
2162		entry->lun_num = lun->lun;
2163#ifdef CTL_TIME_IO
2164		entry->start_bt = io->io_hdr.start_bt;
2165#endif
2166		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2167		entry->cdb_len = io->scsiio.cdb_len;
2168		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2169			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2170
2171		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2172			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2173
2174		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2175			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2176
2177		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2178			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2179
2180		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2181			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2182	}
2183	mtx_unlock(&lun->lun_lock);
2184
2185	return (retval);
2186}
2187
2188static void *
2189ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2190		 size_t error_str_len)
2191{
2192	void *kptr;
2193
2194	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2195
2196	if (copyin(user_addr, kptr, len) != 0) {
2197		snprintf(error_str, error_str_len, "Error copying %d bytes "
2198			 "from user address %p to kernel address %p", len,
2199			 user_addr, kptr);
2200		free(kptr, M_CTL);
2201		return (NULL);
2202	}
2203
2204	return (kptr);
2205}
2206
2207static void
2208ctl_free_args(int num_args, struct ctl_be_arg *args)
2209{
2210	int i;
2211
2212	if (args == NULL)
2213		return;
2214
2215	for (i = 0; i < num_args; i++) {
2216		free(args[i].kname, M_CTL);
2217		free(args[i].kvalue, M_CTL);
2218	}
2219
2220	free(args, M_CTL);
2221}
2222
2223static struct ctl_be_arg *
2224ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2225		char *error_str, size_t error_str_len)
2226{
2227	struct ctl_be_arg *args;
2228	int i;
2229
2230	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2231				error_str, error_str_len);
2232
2233	if (args == NULL)
2234		goto bailout;
2235
2236	for (i = 0; i < num_args; i++) {
2237		args[i].kname = NULL;
2238		args[i].kvalue = NULL;
2239	}
2240
2241	for (i = 0; i < num_args; i++) {
2242		uint8_t *tmpptr;
2243
2244		args[i].kname = ctl_copyin_alloc(args[i].name,
2245			args[i].namelen, error_str, error_str_len);
2246		if (args[i].kname == NULL)
2247			goto bailout;
2248
2249		if (args[i].kname[args[i].namelen - 1] != '\0') {
2250			snprintf(error_str, error_str_len, "Argument %d "
2251				 "name is not NUL-terminated", i);
2252			goto bailout;
2253		}
2254
2255		if (args[i].flags & CTL_BEARG_RD) {
2256			tmpptr = ctl_copyin_alloc(args[i].value,
2257				args[i].vallen, error_str, error_str_len);
2258			if (tmpptr == NULL)
2259				goto bailout;
2260			if ((args[i].flags & CTL_BEARG_ASCII)
2261			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2262				snprintf(error_str, error_str_len, "Argument "
2263				    "%d value is not NUL-terminated", i);
2264				goto bailout;
2265			}
2266			args[i].kvalue = tmpptr;
2267		} else {
2268			args[i].kvalue = malloc(args[i].vallen,
2269			    M_CTL, M_WAITOK | M_ZERO);
2270		}
2271	}
2272
2273	return (args);
2274bailout:
2275
2276	ctl_free_args(num_args, args);
2277
2278	return (NULL);
2279}
2280
2281static void
2282ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2283{
2284	int i;
2285
2286	for (i = 0; i < num_args; i++) {
2287		if (args[i].flags & CTL_BEARG_WR)
2288			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2289	}
2290}
2291
2292/*
2293 * Escape characters that are illegal or not recommended in XML.
2294 */
2295int
2296ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2297{
2298	char *end = str + size;
2299	int retval;
2300
2301	retval = 0;
2302
2303	for (; *str && str < end; str++) {
2304		switch (*str) {
2305		case '&':
2306			retval = sbuf_printf(sb, "&amp;");
2307			break;
2308		case '>':
2309			retval = sbuf_printf(sb, "&gt;");
2310			break;
2311		case '<':
2312			retval = sbuf_printf(sb, "&lt;");
2313			break;
2314		default:
2315			retval = sbuf_putc(sb, *str);
2316			break;
2317		}
2318
2319		if (retval != 0)
2320			break;
2321
2322	}
2323
2324	return (retval);
2325}
2326
2327static void
2328ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2329{
2330	struct scsi_vpd_id_descriptor *desc;
2331	int i;
2332
2333	if (id == NULL || id->len < 4)
2334		return;
2335	desc = (struct scsi_vpd_id_descriptor *)id->data;
2336	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2337	case SVPD_ID_TYPE_T10:
2338		sbuf_printf(sb, "t10.");
2339		break;
2340	case SVPD_ID_TYPE_EUI64:
2341		sbuf_printf(sb, "eui.");
2342		break;
2343	case SVPD_ID_TYPE_NAA:
2344		sbuf_printf(sb, "naa.");
2345		break;
2346	case SVPD_ID_TYPE_SCSI_NAME:
2347		break;
2348	}
2349	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2350	case SVPD_ID_CODESET_BINARY:
2351		for (i = 0; i < desc->length; i++)
2352			sbuf_printf(sb, "%02x", desc->identifier[i]);
2353		break;
2354	case SVPD_ID_CODESET_ASCII:
2355		sbuf_printf(sb, "%.*s", (int)desc->length,
2356		    (char *)desc->identifier);
2357		break;
2358	case SVPD_ID_CODESET_UTF8:
2359		sbuf_printf(sb, "%s", (char *)desc->identifier);
2360		break;
2361	}
2362}
2363
2364static int
2365ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2366	  struct thread *td)
2367{
2368	struct ctl_softc *softc;
2369	int retval;
2370
2371	softc = control_softc;
2372
2373	retval = 0;
2374
2375	switch (cmd) {
2376	case CTL_IO: {
2377		union ctl_io *io;
2378		void *pool_tmp;
2379
2380		/*
2381		 * If we haven't been "enabled", don't allow any SCSI I/O
2382		 * to this FETD.
2383		 */
2384		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2385			retval = EPERM;
2386			break;
2387		}
2388
2389		io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2390
2391		/*
2392		 * Need to save the pool reference so it doesn't get
2393		 * spammed by the user's ctl_io.
2394		 */
2395		pool_tmp = io->io_hdr.pool;
2396		memcpy(io, (void *)addr, sizeof(*io));
2397		io->io_hdr.pool = pool_tmp;
2398
2399		/*
2400		 * No status yet, so make sure the status is set properly.
2401		 */
2402		io->io_hdr.status = CTL_STATUS_NONE;
2403
2404		/*
2405		 * The user sets the initiator ID, target and LUN IDs.
2406		 */
2407		io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2408		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2409		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2410		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2411			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2412
2413		retval = ctl_ioctl_submit_wait(io);
2414
2415		if (retval != 0) {
2416			ctl_free_io(io);
2417			break;
2418		}
2419
2420		memcpy((void *)addr, io, sizeof(*io));
2421
2422		/* return this to our pool */
2423		ctl_free_io(io);
2424
2425		break;
2426	}
2427	case CTL_ENABLE_PORT:
2428	case CTL_DISABLE_PORT:
2429	case CTL_SET_PORT_WWNS: {
2430		struct ctl_port *port;
2431		struct ctl_port_entry *entry;
2432
2433		entry = (struct ctl_port_entry *)addr;
2434
2435		mtx_lock(&softc->ctl_lock);
2436		STAILQ_FOREACH(port, &softc->port_list, links) {
2437			int action, done;
2438
2439			action = 0;
2440			done = 0;
2441
2442			if ((entry->port_type == CTL_PORT_NONE)
2443			 && (entry->targ_port == port->targ_port)) {
2444				/*
2445				 * If the user only wants to enable or
2446				 * disable or set WWNs on a specific port,
2447				 * do the operation and we're done.
2448				 */
2449				action = 1;
2450				done = 1;
2451			} else if (entry->port_type & port->port_type) {
2452				/*
2453				 * Compare the user's type mask with the
2454				 * particular frontend type to see if we
2455				 * have a match.
2456				 */
2457				action = 1;
2458				done = 0;
2459
2460				/*
2461				 * Make sure the user isn't trying to set
2462				 * WWNs on multiple ports at the same time.
2463				 */
2464				if (cmd == CTL_SET_PORT_WWNS) {
2465					printf("%s: Can't set WWNs on "
2466					       "multiple ports\n", __func__);
2467					retval = EINVAL;
2468					break;
2469				}
2470			}
2471			if (action != 0) {
2472				/*
2473				 * XXX KDM we have to drop the lock here,
2474				 * because the online/offline operations
2475				 * can potentially block.  We need to
2476				 * reference count the frontends so they
2477				 * can't go away,
2478				 */
2479				mtx_unlock(&softc->ctl_lock);
2480
2481				if (cmd == CTL_ENABLE_PORT) {
2482					struct ctl_lun *lun;
2483
2484					STAILQ_FOREACH(lun, &softc->lun_list,
2485						       links) {
2486						port->lun_enable(port->targ_lun_arg,
2487						    lun->target,
2488						    lun->lun);
2489					}
2490
2491					ctl_port_online(port);
2492				} else if (cmd == CTL_DISABLE_PORT) {
2493					struct ctl_lun *lun;
2494
2495					ctl_port_offline(port);
2496
2497					STAILQ_FOREACH(lun, &softc->lun_list,
2498						       links) {
2499						port->lun_disable(
2500						    port->targ_lun_arg,
2501						    lun->target,
2502						    lun->lun);
2503					}
2504				}
2505
2506				mtx_lock(&softc->ctl_lock);
2507
2508				if (cmd == CTL_SET_PORT_WWNS)
2509					ctl_port_set_wwns(port,
2510					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2511					    1 : 0, entry->wwnn,
2512					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2513					    1 : 0, entry->wwpn);
2514			}
2515			if (done != 0)
2516				break;
2517		}
2518		mtx_unlock(&softc->ctl_lock);
2519		break;
2520	}
2521	case CTL_GET_PORT_LIST: {
2522		struct ctl_port *port;
2523		struct ctl_port_list *list;
2524		int i;
2525
2526		list = (struct ctl_port_list *)addr;
2527
2528		if (list->alloc_len != (list->alloc_num *
2529		    sizeof(struct ctl_port_entry))) {
2530			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2531			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2532			       "%zu\n", __func__, list->alloc_len,
2533			       list->alloc_num, sizeof(struct ctl_port_entry));
2534			retval = EINVAL;
2535			break;
2536		}
2537		list->fill_len = 0;
2538		list->fill_num = 0;
2539		list->dropped_num = 0;
2540		i = 0;
2541		mtx_lock(&softc->ctl_lock);
2542		STAILQ_FOREACH(port, &softc->port_list, links) {
2543			struct ctl_port_entry entry, *list_entry;
2544
2545			if (list->fill_num >= list->alloc_num) {
2546				list->dropped_num++;
2547				continue;
2548			}
2549
2550			entry.port_type = port->port_type;
2551			strlcpy(entry.port_name, port->port_name,
2552				sizeof(entry.port_name));
2553			entry.targ_port = port->targ_port;
2554			entry.physical_port = port->physical_port;
2555			entry.virtual_port = port->virtual_port;
2556			entry.wwnn = port->wwnn;
2557			entry.wwpn = port->wwpn;
2558			if (port->status & CTL_PORT_STATUS_ONLINE)
2559				entry.online = 1;
2560			else
2561				entry.online = 0;
2562
2563			list_entry = &list->entries[i];
2564
2565			retval = copyout(&entry, list_entry, sizeof(entry));
2566			if (retval != 0) {
2567				printf("%s: CTL_GET_PORT_LIST: copyout "
2568				       "returned %d\n", __func__, retval);
2569				break;
2570			}
2571			i++;
2572			list->fill_num++;
2573			list->fill_len += sizeof(entry);
2574		}
2575		mtx_unlock(&softc->ctl_lock);
2576
2577		/*
2578		 * If this is non-zero, we had a copyout fault, so there's
2579		 * probably no point in attempting to set the status inside
2580		 * the structure.
2581		 */
2582		if (retval != 0)
2583			break;
2584
2585		if (list->dropped_num > 0)
2586			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2587		else
2588			list->status = CTL_PORT_LIST_OK;
2589		break;
2590	}
2591	case CTL_DUMP_OOA: {
2592		struct ctl_lun *lun;
2593		union ctl_io *io;
2594		char printbuf[128];
2595		struct sbuf sb;
2596
2597		mtx_lock(&softc->ctl_lock);
2598		printf("Dumping OOA queues:\n");
2599		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2600			mtx_lock(&lun->lun_lock);
2601			for (io = (union ctl_io *)TAILQ_FIRST(
2602			     &lun->ooa_queue); io != NULL;
2603			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2604			     ooa_links)) {
2605				sbuf_new(&sb, printbuf, sizeof(printbuf),
2606					 SBUF_FIXEDLEN);
2607				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2608					    (intmax_t)lun->lun,
2609					    io->scsiio.tag_num,
2610					    (io->io_hdr.flags &
2611					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2612					    (io->io_hdr.flags &
2613					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2614					    (io->io_hdr.flags &
2615					    CTL_FLAG_ABORT) ? " ABORT" : "",
2616			                    (io->io_hdr.flags &
2617		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2618				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2619				sbuf_finish(&sb);
2620				printf("%s\n", sbuf_data(&sb));
2621			}
2622			mtx_unlock(&lun->lun_lock);
2623		}
2624		printf("OOA queues dump done\n");
2625		mtx_unlock(&softc->ctl_lock);
2626		break;
2627	}
2628	case CTL_GET_OOA: {
2629		struct ctl_lun *lun;
2630		struct ctl_ooa *ooa_hdr;
2631		struct ctl_ooa_entry *entries;
2632		uint32_t cur_fill_num;
2633
2634		ooa_hdr = (struct ctl_ooa *)addr;
2635
2636		if ((ooa_hdr->alloc_len == 0)
2637		 || (ooa_hdr->alloc_num == 0)) {
2638			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2639			       "must be non-zero\n", __func__,
2640			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2641			retval = EINVAL;
2642			break;
2643		}
2644
2645		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2646		    sizeof(struct ctl_ooa_entry))) {
2647			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2648			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2649			       __func__, ooa_hdr->alloc_len,
2650			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2651			retval = EINVAL;
2652			break;
2653		}
2654
2655		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2656		if (entries == NULL) {
2657			printf("%s: could not allocate %d bytes for OOA "
2658			       "dump\n", __func__, ooa_hdr->alloc_len);
2659			retval = ENOMEM;
2660			break;
2661		}
2662
2663		mtx_lock(&softc->ctl_lock);
2664		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2665		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2666		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2667			mtx_unlock(&softc->ctl_lock);
2668			free(entries, M_CTL);
2669			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2670			       __func__, (uintmax_t)ooa_hdr->lun_num);
2671			retval = EINVAL;
2672			break;
2673		}
2674
2675		cur_fill_num = 0;
2676
2677		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2678			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2679				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2680					ooa_hdr, entries);
2681				if (retval != 0)
2682					break;
2683			}
2684			if (retval != 0) {
2685				mtx_unlock(&softc->ctl_lock);
2686				free(entries, M_CTL);
2687				break;
2688			}
2689		} else {
2690			lun = softc->ctl_luns[ooa_hdr->lun_num];
2691
2692			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2693						    entries);
2694		}
2695		mtx_unlock(&softc->ctl_lock);
2696
2697		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2698		ooa_hdr->fill_len = ooa_hdr->fill_num *
2699			sizeof(struct ctl_ooa_entry);
2700		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2701		if (retval != 0) {
2702			printf("%s: error copying out %d bytes for OOA dump\n",
2703			       __func__, ooa_hdr->fill_len);
2704		}
2705
2706		getbintime(&ooa_hdr->cur_bt);
2707
2708		if (cur_fill_num > ooa_hdr->alloc_num) {
2709			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2710			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2711		} else {
2712			ooa_hdr->dropped_num = 0;
2713			ooa_hdr->status = CTL_OOA_OK;
2714		}
2715
2716		free(entries, M_CTL);
2717		break;
2718	}
2719	case CTL_CHECK_OOA: {
2720		union ctl_io *io;
2721		struct ctl_lun *lun;
2722		struct ctl_ooa_info *ooa_info;
2723
2724
2725		ooa_info = (struct ctl_ooa_info *)addr;
2726
2727		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2728			ooa_info->status = CTL_OOA_INVALID_LUN;
2729			break;
2730		}
2731		mtx_lock(&softc->ctl_lock);
2732		lun = softc->ctl_luns[ooa_info->lun_id];
2733		if (lun == NULL) {
2734			mtx_unlock(&softc->ctl_lock);
2735			ooa_info->status = CTL_OOA_INVALID_LUN;
2736			break;
2737		}
2738		mtx_lock(&lun->lun_lock);
2739		mtx_unlock(&softc->ctl_lock);
2740		ooa_info->num_entries = 0;
2741		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2742		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2743		     &io->io_hdr, ooa_links)) {
2744			ooa_info->num_entries++;
2745		}
2746		mtx_unlock(&lun->lun_lock);
2747
2748		ooa_info->status = CTL_OOA_SUCCESS;
2749
2750		break;
2751	}
2752	case CTL_HARD_START:
2753	case CTL_HARD_STOP: {
2754		struct ctl_fe_ioctl_startstop_info ss_info;
2755		struct cfi_metatask *metatask;
2756		struct mtx hs_mtx;
2757
2758		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2759
2760		cv_init(&ss_info.sem, "hard start/stop cv" );
2761
2762		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2763		if (metatask == NULL) {
2764			retval = ENOMEM;
2765			mtx_destroy(&hs_mtx);
2766			break;
2767		}
2768
2769		if (cmd == CTL_HARD_START)
2770			metatask->tasktype = CFI_TASK_STARTUP;
2771		else
2772			metatask->tasktype = CFI_TASK_SHUTDOWN;
2773
2774		metatask->callback = ctl_ioctl_hard_startstop_callback;
2775		metatask->callback_arg = &ss_info;
2776
2777		cfi_action(metatask);
2778
2779		/* Wait for the callback */
2780		mtx_lock(&hs_mtx);
2781		cv_wait_sig(&ss_info.sem, &hs_mtx);
2782		mtx_unlock(&hs_mtx);
2783
2784		/*
2785		 * All information has been copied from the metatask by the
2786		 * time cv_broadcast() is called, so we free the metatask here.
2787		 */
2788		cfi_free_metatask(metatask);
2789
2790		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2791
2792		mtx_destroy(&hs_mtx);
2793		break;
2794	}
2795	case CTL_BBRREAD: {
2796		struct ctl_bbrread_info *bbr_info;
2797		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2798		struct mtx bbr_mtx;
2799		struct cfi_metatask *metatask;
2800
2801		bbr_info = (struct ctl_bbrread_info *)addr;
2802
2803		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2804
2805		bzero(&bbr_mtx, sizeof(bbr_mtx));
2806		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2807
2808		fe_bbr_info.bbr_info = bbr_info;
2809		fe_bbr_info.lock = &bbr_mtx;
2810
2811		cv_init(&fe_bbr_info.sem, "BBR read cv");
2812		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2813
2814		if (metatask == NULL) {
2815			mtx_destroy(&bbr_mtx);
2816			cv_destroy(&fe_bbr_info.sem);
2817			retval = ENOMEM;
2818			break;
2819		}
2820		metatask->tasktype = CFI_TASK_BBRREAD;
2821		metatask->callback = ctl_ioctl_bbrread_callback;
2822		metatask->callback_arg = &fe_bbr_info;
2823		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2824		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2825		metatask->taskinfo.bbrread.len = bbr_info->len;
2826
2827		cfi_action(metatask);
2828
2829		mtx_lock(&bbr_mtx);
2830		while (fe_bbr_info.wakeup_done == 0)
2831			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2832		mtx_unlock(&bbr_mtx);
2833
2834		bbr_info->status = metatask->status;
2835		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2836		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2837		memcpy(&bbr_info->sense_data,
2838		       &metatask->taskinfo.bbrread.sense_data,
2839		       MIN(sizeof(bbr_info->sense_data),
2840			   sizeof(metatask->taskinfo.bbrread.sense_data)));
2841
2842		cfi_free_metatask(metatask);
2843
2844		mtx_destroy(&bbr_mtx);
2845		cv_destroy(&fe_bbr_info.sem);
2846
2847		break;
2848	}
2849	case CTL_DELAY_IO: {
2850		struct ctl_io_delay_info *delay_info;
2851#ifdef CTL_IO_DELAY
2852		struct ctl_lun *lun;
2853#endif /* CTL_IO_DELAY */
2854
2855		delay_info = (struct ctl_io_delay_info *)addr;
2856
2857#ifdef CTL_IO_DELAY
2858		mtx_lock(&softc->ctl_lock);
2859
2860		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2861		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2862			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2863		} else {
2864			lun = softc->ctl_luns[delay_info->lun_id];
2865			mtx_lock(&lun->lun_lock);
2866
2867			delay_info->status = CTL_DELAY_STATUS_OK;
2868
2869			switch (delay_info->delay_type) {
2870			case CTL_DELAY_TYPE_CONT:
2871				break;
2872			case CTL_DELAY_TYPE_ONESHOT:
2873				break;
2874			default:
2875				delay_info->status =
2876					CTL_DELAY_STATUS_INVALID_TYPE;
2877				break;
2878			}
2879
2880			switch (delay_info->delay_loc) {
2881			case CTL_DELAY_LOC_DATAMOVE:
2882				lun->delay_info.datamove_type =
2883					delay_info->delay_type;
2884				lun->delay_info.datamove_delay =
2885					delay_info->delay_secs;
2886				break;
2887			case CTL_DELAY_LOC_DONE:
2888				lun->delay_info.done_type =
2889					delay_info->delay_type;
2890				lun->delay_info.done_delay =
2891					delay_info->delay_secs;
2892				break;
2893			default:
2894				delay_info->status =
2895					CTL_DELAY_STATUS_INVALID_LOC;
2896				break;
2897			}
2898			mtx_unlock(&lun->lun_lock);
2899		}
2900
2901		mtx_unlock(&softc->ctl_lock);
2902#else
2903		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2904#endif /* CTL_IO_DELAY */
2905		break;
2906	}
2907	case CTL_REALSYNC_SET: {
2908		int *syncstate;
2909
2910		syncstate = (int *)addr;
2911
2912		mtx_lock(&softc->ctl_lock);
2913		switch (*syncstate) {
2914		case 0:
2915			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2916			break;
2917		case 1:
2918			softc->flags |= CTL_FLAG_REAL_SYNC;
2919			break;
2920		default:
2921			retval = EINVAL;
2922			break;
2923		}
2924		mtx_unlock(&softc->ctl_lock);
2925		break;
2926	}
2927	case CTL_REALSYNC_GET: {
2928		int *syncstate;
2929
2930		syncstate = (int*)addr;
2931
2932		mtx_lock(&softc->ctl_lock);
2933		if (softc->flags & CTL_FLAG_REAL_SYNC)
2934			*syncstate = 1;
2935		else
2936			*syncstate = 0;
2937		mtx_unlock(&softc->ctl_lock);
2938
2939		break;
2940	}
2941	case CTL_SETSYNC:
2942	case CTL_GETSYNC: {
2943		struct ctl_sync_info *sync_info;
2944		struct ctl_lun *lun;
2945
2946		sync_info = (struct ctl_sync_info *)addr;
2947
2948		mtx_lock(&softc->ctl_lock);
2949		lun = softc->ctl_luns[sync_info->lun_id];
2950		if (lun == NULL) {
2951			mtx_unlock(&softc->ctl_lock);
2952			sync_info->status = CTL_GS_SYNC_NO_LUN;
2953		}
2954		/*
2955		 * Get or set the sync interval.  We're not bounds checking
2956		 * in the set case, hopefully the user won't do something
2957		 * silly.
2958		 */
2959		mtx_lock(&lun->lun_lock);
2960		mtx_unlock(&softc->ctl_lock);
2961		if (cmd == CTL_GETSYNC)
2962			sync_info->sync_interval = lun->sync_interval;
2963		else
2964			lun->sync_interval = sync_info->sync_interval;
2965		mtx_unlock(&lun->lun_lock);
2966
2967		sync_info->status = CTL_GS_SYNC_OK;
2968
2969		break;
2970	}
2971	case CTL_GETSTATS: {
2972		struct ctl_stats *stats;
2973		struct ctl_lun *lun;
2974		int i;
2975
2976		stats = (struct ctl_stats *)addr;
2977
2978		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2979		     stats->alloc_len) {
2980			stats->status = CTL_SS_NEED_MORE_SPACE;
2981			stats->num_luns = softc->num_luns;
2982			break;
2983		}
2984		/*
2985		 * XXX KDM no locking here.  If the LUN list changes,
2986		 * things can blow up.
2987		 */
2988		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2989		     i++, lun = STAILQ_NEXT(lun, links)) {
2990			retval = copyout(&lun->stats, &stats->lun_stats[i],
2991					 sizeof(lun->stats));
2992			if (retval != 0)
2993				break;
2994		}
2995		stats->num_luns = softc->num_luns;
2996		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2997				 softc->num_luns;
2998		stats->status = CTL_SS_OK;
2999#ifdef CTL_TIME_IO
3000		stats->flags = CTL_STATS_FLAG_TIME_VALID;
3001#else
3002		stats->flags = CTL_STATS_FLAG_NONE;
3003#endif
3004		getnanouptime(&stats->timestamp);
3005		break;
3006	}
3007	case CTL_ERROR_INJECT: {
3008		struct ctl_error_desc *err_desc, *new_err_desc;
3009		struct ctl_lun *lun;
3010
3011		err_desc = (struct ctl_error_desc *)addr;
3012
3013		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
3014				      M_WAITOK | M_ZERO);
3015		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
3016
3017		mtx_lock(&softc->ctl_lock);
3018		lun = softc->ctl_luns[err_desc->lun_id];
3019		if (lun == NULL) {
3020			mtx_unlock(&softc->ctl_lock);
3021			free(new_err_desc, M_CTL);
3022			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
3023			       __func__, (uintmax_t)err_desc->lun_id);
3024			retval = EINVAL;
3025			break;
3026		}
3027		mtx_lock(&lun->lun_lock);
3028		mtx_unlock(&softc->ctl_lock);
3029
3030		/*
3031		 * We could do some checking here to verify the validity
3032		 * of the request, but given the complexity of error
3033		 * injection requests, the checking logic would be fairly
3034		 * complex.
3035		 *
3036		 * For now, if the request is invalid, it just won't get
3037		 * executed and might get deleted.
3038		 */
3039		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
3040
3041		/*
3042		 * XXX KDM check to make sure the serial number is unique,
3043		 * in case we somehow manage to wrap.  That shouldn't
3044		 * happen for a very long time, but it's the right thing to
3045		 * do.
3046		 */
3047		new_err_desc->serial = lun->error_serial;
3048		err_desc->serial = lun->error_serial;
3049		lun->error_serial++;
3050
3051		mtx_unlock(&lun->lun_lock);
3052		break;
3053	}
3054	case CTL_ERROR_INJECT_DELETE: {
3055		struct ctl_error_desc *delete_desc, *desc, *desc2;
3056		struct ctl_lun *lun;
3057		int delete_done;
3058
3059		delete_desc = (struct ctl_error_desc *)addr;
3060		delete_done = 0;
3061
3062		mtx_lock(&softc->ctl_lock);
3063		lun = softc->ctl_luns[delete_desc->lun_id];
3064		if (lun == NULL) {
3065			mtx_unlock(&softc->ctl_lock);
3066			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
3067			       __func__, (uintmax_t)delete_desc->lun_id);
3068			retval = EINVAL;
3069			break;
3070		}
3071		mtx_lock(&lun->lun_lock);
3072		mtx_unlock(&softc->ctl_lock);
3073		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
3074			if (desc->serial != delete_desc->serial)
3075				continue;
3076
3077			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
3078				      links);
3079			free(desc, M_CTL);
3080			delete_done = 1;
3081		}
3082		mtx_unlock(&lun->lun_lock);
3083		if (delete_done == 0) {
3084			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
3085			       "error serial %ju on LUN %u\n", __func__,
3086			       delete_desc->serial, delete_desc->lun_id);
3087			retval = EINVAL;
3088			break;
3089		}
3090		break;
3091	}
3092	case CTL_DUMP_STRUCTS: {
3093		int i, j, k;
3094		struct ctl_port *port;
3095		struct ctl_frontend *fe;
3096
3097		mtx_lock(&softc->ctl_lock);
3098		printf("CTL Persistent Reservation information start:\n");
3099		for (i = 0; i < CTL_MAX_LUNS; i++) {
3100			struct ctl_lun *lun;
3101
3102			lun = softc->ctl_luns[i];
3103
3104			if ((lun == NULL)
3105			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
3106				continue;
3107
3108			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
3109				if (lun->pr_keys[j] == NULL)
3110					continue;
3111				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
3112					if (lun->pr_keys[j][k] == 0)
3113						continue;
3114					printf("  LUN %d port %d iid %d key "
3115					       "%#jx\n", i, j, k,
3116					       (uintmax_t)lun->pr_keys[j][k]);
3117				}
3118			}
3119		}
3120		printf("CTL Persistent Reservation information end\n");
3121		printf("CTL Ports:\n");
3122		STAILQ_FOREACH(port, &softc->port_list, links) {
3123			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3124			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3125			       port->frontend->name, port->port_type,
3126			       port->physical_port, port->virtual_port,
3127			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3128			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3129				if (port->wwpn_iid[j].in_use == 0 &&
3130				    port->wwpn_iid[j].wwpn == 0 &&
3131				    port->wwpn_iid[j].name == NULL)
3132					continue;
3133
3134				printf("    iid %u use %d WWPN %#jx '%s'\n",
3135				    j, port->wwpn_iid[j].in_use,
3136				    (uintmax_t)port->wwpn_iid[j].wwpn,
3137				    port->wwpn_iid[j].name);
3138			}
3139		}
3140		printf("CTL Port information end\n");
3141		mtx_unlock(&softc->ctl_lock);
3142		/*
3143		 * XXX KDM calling this without a lock.  We'd likely want
3144		 * to drop the lock before calling the frontend's dump
3145		 * routine anyway.
3146		 */
3147		printf("CTL Frontends:\n");
3148		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3149			printf("  Frontend '%s'\n", fe->name);
3150			if (fe->fe_dump != NULL)
3151				fe->fe_dump();
3152		}
3153		printf("CTL Frontend information end\n");
3154		break;
3155	}
3156	case CTL_LUN_REQ: {
3157		struct ctl_lun_req *lun_req;
3158		struct ctl_backend_driver *backend;
3159
3160		lun_req = (struct ctl_lun_req *)addr;
3161
3162		backend = ctl_backend_find(lun_req->backend);
3163		if (backend == NULL) {
3164			lun_req->status = CTL_LUN_ERROR;
3165			snprintf(lun_req->error_str,
3166				 sizeof(lun_req->error_str),
3167				 "Backend \"%s\" not found.",
3168				 lun_req->backend);
3169			break;
3170		}
3171		if (lun_req->num_be_args > 0) {
3172			lun_req->kern_be_args = ctl_copyin_args(
3173				lun_req->num_be_args,
3174				lun_req->be_args,
3175				lun_req->error_str,
3176				sizeof(lun_req->error_str));
3177			if (lun_req->kern_be_args == NULL) {
3178				lun_req->status = CTL_LUN_ERROR;
3179				break;
3180			}
3181		}
3182
3183		retval = backend->ioctl(dev, cmd, addr, flag, td);
3184
3185		if (lun_req->num_be_args > 0) {
3186			ctl_copyout_args(lun_req->num_be_args,
3187				      lun_req->kern_be_args);
3188			ctl_free_args(lun_req->num_be_args,
3189				      lun_req->kern_be_args);
3190		}
3191		break;
3192	}
3193	case CTL_LUN_LIST: {
3194		struct sbuf *sb;
3195		struct ctl_lun *lun;
3196		struct ctl_lun_list *list;
3197		struct ctl_option *opt;
3198
3199		list = (struct ctl_lun_list *)addr;
3200
3201		/*
3202		 * Allocate a fixed length sbuf here, based on the length
3203		 * of the user's buffer.  We could allocate an auto-extending
3204		 * buffer, and then tell the user how much larger our
3205		 * amount of data is than his buffer, but that presents
3206		 * some problems:
3207		 *
3208		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3209		 *     we can't hold a lock while calling them with an
3210		 *     auto-extending buffer.
3211 		 *
3212		 * 2.  There is not currently a LUN reference counting
3213		 *     mechanism, outside of outstanding transactions on
3214		 *     the LUN's OOA queue.  So a LUN could go away on us
3215		 *     while we're getting the LUN number, backend-specific
3216		 *     information, etc.  Thus, given the way things
3217		 *     currently work, we need to hold the CTL lock while
3218		 *     grabbing LUN information.
3219		 *
3220		 * So, from the user's standpoint, the best thing to do is
3221		 * allocate what he thinks is a reasonable buffer length,
3222		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3223		 * double the buffer length and try again.  (And repeat
3224		 * that until he succeeds.)
3225		 */
3226		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3227		if (sb == NULL) {
3228			list->status = CTL_LUN_LIST_ERROR;
3229			snprintf(list->error_str, sizeof(list->error_str),
3230				 "Unable to allocate %d bytes for LUN list",
3231				 list->alloc_len);
3232			break;
3233		}
3234
3235		sbuf_printf(sb, "<ctllunlist>\n");
3236
3237		mtx_lock(&softc->ctl_lock);
3238		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3239			mtx_lock(&lun->lun_lock);
3240			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3241					     (uintmax_t)lun->lun);
3242
3243			/*
3244			 * Bail out as soon as we see that we've overfilled
3245			 * the buffer.
3246			 */
3247			if (retval != 0)
3248				break;
3249
3250			retval = sbuf_printf(sb, "\t<backend_type>%s"
3251					     "</backend_type>\n",
3252					     (lun->backend == NULL) ?  "none" :
3253					     lun->backend->name);
3254
3255			if (retval != 0)
3256				break;
3257
3258			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3259					     lun->be_lun->lun_type);
3260
3261			if (retval != 0)
3262				break;
3263
3264			if (lun->backend == NULL) {
3265				retval = sbuf_printf(sb, "</lun>\n");
3266				if (retval != 0)
3267					break;
3268				continue;
3269			}
3270
3271			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3272					     (lun->be_lun->maxlba > 0) ?
3273					     lun->be_lun->maxlba + 1 : 0);
3274
3275			if (retval != 0)
3276				break;
3277
3278			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3279					     lun->be_lun->blocksize);
3280
3281			if (retval != 0)
3282				break;
3283
3284			retval = sbuf_printf(sb, "\t<serial_number>");
3285
3286			if (retval != 0)
3287				break;
3288
3289			retval = ctl_sbuf_printf_esc(sb,
3290			    lun->be_lun->serial_num,
3291			    sizeof(lun->be_lun->serial_num));
3292
3293			if (retval != 0)
3294				break;
3295
3296			retval = sbuf_printf(sb, "</serial_number>\n");
3297
3298			if (retval != 0)
3299				break;
3300
3301			retval = sbuf_printf(sb, "\t<device_id>");
3302
3303			if (retval != 0)
3304				break;
3305
3306			retval = ctl_sbuf_printf_esc(sb,
3307			    lun->be_lun->device_id,
3308			    sizeof(lun->be_lun->device_id));
3309
3310			if (retval != 0)
3311				break;
3312
3313			retval = sbuf_printf(sb, "</device_id>\n");
3314
3315			if (retval != 0)
3316				break;
3317
3318			if (lun->backend->lun_info != NULL) {
3319				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3320				if (retval != 0)
3321					break;
3322			}
3323			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3324				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3325				    opt->name, opt->value, opt->name);
3326				if (retval != 0)
3327					break;
3328			}
3329
3330			retval = sbuf_printf(sb, "</lun>\n");
3331
3332			if (retval != 0)
3333				break;
3334			mtx_unlock(&lun->lun_lock);
3335		}
3336		if (lun != NULL)
3337			mtx_unlock(&lun->lun_lock);
3338		mtx_unlock(&softc->ctl_lock);
3339
3340		if ((retval != 0)
3341		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3342			retval = 0;
3343			sbuf_delete(sb);
3344			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3345			snprintf(list->error_str, sizeof(list->error_str),
3346				 "Out of space, %d bytes is too small",
3347				 list->alloc_len);
3348			break;
3349		}
3350
3351		sbuf_finish(sb);
3352
3353		retval = copyout(sbuf_data(sb), list->lun_xml,
3354				 sbuf_len(sb) + 1);
3355
3356		list->fill_len = sbuf_len(sb) + 1;
3357		list->status = CTL_LUN_LIST_OK;
3358		sbuf_delete(sb);
3359		break;
3360	}
3361	case CTL_ISCSI: {
3362		struct ctl_iscsi *ci;
3363		struct ctl_frontend *fe;
3364
3365		ci = (struct ctl_iscsi *)addr;
3366
3367		fe = ctl_frontend_find("iscsi");
3368		if (fe == NULL) {
3369			ci->status = CTL_ISCSI_ERROR;
3370			snprintf(ci->error_str, sizeof(ci->error_str),
3371			    "Frontend \"iscsi\" not found.");
3372			break;
3373		}
3374
3375		retval = fe->ioctl(dev, cmd, addr, flag, td);
3376		break;
3377	}
3378	case CTL_PORT_REQ: {
3379		struct ctl_req *req;
3380		struct ctl_frontend *fe;
3381
3382		req = (struct ctl_req *)addr;
3383
3384		fe = ctl_frontend_find(req->driver);
3385		if (fe == NULL) {
3386			req->status = CTL_LUN_ERROR;
3387			snprintf(req->error_str, sizeof(req->error_str),
3388			    "Frontend \"%s\" not found.", req->driver);
3389			break;
3390		}
3391		if (req->num_args > 0) {
3392			req->kern_args = ctl_copyin_args(req->num_args,
3393			    req->args, req->error_str, sizeof(req->error_str));
3394			if (req->kern_args == NULL) {
3395				req->status = CTL_LUN_ERROR;
3396				break;
3397			}
3398		}
3399
3400		retval = fe->ioctl(dev, cmd, addr, flag, td);
3401
3402		if (req->num_args > 0) {
3403			ctl_copyout_args(req->num_args, req->kern_args);
3404			ctl_free_args(req->num_args, req->kern_args);
3405		}
3406		break;
3407	}
3408	case CTL_PORT_LIST: {
3409		struct sbuf *sb;
3410		struct ctl_port *port;
3411		struct ctl_lun_list *list;
3412		struct ctl_option *opt;
3413		int j;
3414
3415		list = (struct ctl_lun_list *)addr;
3416
3417		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3418		if (sb == NULL) {
3419			list->status = CTL_LUN_LIST_ERROR;
3420			snprintf(list->error_str, sizeof(list->error_str),
3421				 "Unable to allocate %d bytes for LUN list",
3422				 list->alloc_len);
3423			break;
3424		}
3425
3426		sbuf_printf(sb, "<ctlportlist>\n");
3427
3428		mtx_lock(&softc->ctl_lock);
3429		STAILQ_FOREACH(port, &softc->port_list, links) {
3430			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3431					     (uintmax_t)port->targ_port);
3432
3433			/*
3434			 * Bail out as soon as we see that we've overfilled
3435			 * the buffer.
3436			 */
3437			if (retval != 0)
3438				break;
3439
3440			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3441			    "</frontend_type>\n", port->frontend->name);
3442			if (retval != 0)
3443				break;
3444
3445			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3446					     port->port_type);
3447			if (retval != 0)
3448				break;
3449
3450			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3451			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3452			if (retval != 0)
3453				break;
3454
3455			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3456			    port->port_name);
3457			if (retval != 0)
3458				break;
3459
3460			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3461			    port->physical_port);
3462			if (retval != 0)
3463				break;
3464
3465			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3466			    port->virtual_port);
3467			if (retval != 0)
3468				break;
3469
3470			if (port->target_devid != NULL) {
3471				sbuf_printf(sb, "\t<target>");
3472				ctl_id_sbuf(port->target_devid, sb);
3473				sbuf_printf(sb, "</target>\n");
3474			}
3475
3476			if (port->port_devid != NULL) {
3477				sbuf_printf(sb, "\t<port>");
3478				ctl_id_sbuf(port->port_devid, sb);
3479				sbuf_printf(sb, "</port>\n");
3480			}
3481
3482			if (port->port_info != NULL) {
3483				retval = port->port_info(port->onoff_arg, sb);
3484				if (retval != 0)
3485					break;
3486			}
3487			STAILQ_FOREACH(opt, &port->options, links) {
3488				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3489				    opt->name, opt->value, opt->name);
3490				if (retval != 0)
3491					break;
3492			}
3493
3494			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3495				if (port->wwpn_iid[j].in_use == 0 ||
3496				    (port->wwpn_iid[j].wwpn == 0 &&
3497				     port->wwpn_iid[j].name == NULL))
3498					continue;
3499
3500				if (port->wwpn_iid[j].name != NULL)
3501					retval = sbuf_printf(sb,
3502					    "\t<initiator id=\"%u\">%s</initiator>\n",
3503					    j, port->wwpn_iid[j].name);
3504				else
3505					retval = sbuf_printf(sb,
3506					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3507					    j, port->wwpn_iid[j].wwpn);
3508				if (retval != 0)
3509					break;
3510			}
3511			if (retval != 0)
3512				break;
3513
3514			retval = sbuf_printf(sb, "</targ_port>\n");
3515			if (retval != 0)
3516				break;
3517		}
3518		mtx_unlock(&softc->ctl_lock);
3519
3520		if ((retval != 0)
3521		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3522			retval = 0;
3523			sbuf_delete(sb);
3524			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3525			snprintf(list->error_str, sizeof(list->error_str),
3526				 "Out of space, %d bytes is too small",
3527				 list->alloc_len);
3528			break;
3529		}
3530
3531		sbuf_finish(sb);
3532
3533		retval = copyout(sbuf_data(sb), list->lun_xml,
3534				 sbuf_len(sb) + 1);
3535
3536		list->fill_len = sbuf_len(sb) + 1;
3537		list->status = CTL_LUN_LIST_OK;
3538		sbuf_delete(sb);
3539		break;
3540	}
3541	default: {
3542		/* XXX KDM should we fix this? */
3543#if 0
3544		struct ctl_backend_driver *backend;
3545		unsigned int type;
3546		int found;
3547
3548		found = 0;
3549
3550		/*
3551		 * We encode the backend type as the ioctl type for backend
3552		 * ioctls.  So parse it out here, and then search for a
3553		 * backend of this type.
3554		 */
3555		type = _IOC_TYPE(cmd);
3556
3557		STAILQ_FOREACH(backend, &softc->be_list, links) {
3558			if (backend->type == type) {
3559				found = 1;
3560				break;
3561			}
3562		}
3563		if (found == 0) {
3564			printf("ctl: unknown ioctl command %#lx or backend "
3565			       "%d\n", cmd, type);
3566			retval = EINVAL;
3567			break;
3568		}
3569		retval = backend->ioctl(dev, cmd, addr, flag, td);
3570#endif
3571		retval = ENOTTY;
3572		break;
3573	}
3574	}
3575	return (retval);
3576}
3577
3578uint32_t
3579ctl_get_initindex(struct ctl_nexus *nexus)
3580{
3581	if (nexus->targ_port < CTL_MAX_PORTS)
3582		return (nexus->initid.id +
3583			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3584	else
3585		return (nexus->initid.id +
3586		       ((nexus->targ_port - CTL_MAX_PORTS) *
3587			CTL_MAX_INIT_PER_PORT));
3588}
3589
3590uint32_t
3591ctl_get_resindex(struct ctl_nexus *nexus)
3592{
3593	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3594}
3595
3596uint32_t
3597ctl_port_idx(int port_num)
3598{
3599	if (port_num < CTL_MAX_PORTS)
3600		return(port_num);
3601	else
3602		return(port_num - CTL_MAX_PORTS);
3603}
3604
3605static uint32_t
3606ctl_map_lun(struct ctl_softc *softc, int port_num, uint32_t lun_id)
3607{
3608	struct ctl_port *port;
3609
3610	port = softc->ctl_ports[ctl_port_idx(port_num)];
3611	if (port == NULL)
3612		return (UINT32_MAX);
3613	if (port->lun_map == NULL)
3614		return (lun_id);
3615	return (port->lun_map(port->targ_lun_arg, lun_id));
3616}
3617
3618static uint32_t
3619ctl_map_lun_back(struct ctl_softc *softc, int port_num, uint32_t lun_id)
3620{
3621	struct ctl_port *port;
3622	uint32_t i;
3623
3624	port = softc->ctl_ports[ctl_port_idx(port_num)];
3625	if (port->lun_map == NULL)
3626		return (lun_id);
3627	for (i = 0; i < CTL_MAX_LUNS; i++) {
3628		if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3629			return (i);
3630	}
3631	return (UINT32_MAX);
3632}
3633
3634/*
3635 * Note:  This only works for bitmask sizes that are at least 32 bits, and
3636 * that are a power of 2.
3637 */
3638int
3639ctl_ffz(uint32_t *mask, uint32_t size)
3640{
3641	uint32_t num_chunks, num_pieces;
3642	int i, j;
3643
3644	num_chunks = (size >> 5);
3645	if (num_chunks == 0)
3646		num_chunks++;
3647	num_pieces = MIN((sizeof(uint32_t) * 8), size);
3648
3649	for (i = 0; i < num_chunks; i++) {
3650		for (j = 0; j < num_pieces; j++) {
3651			if ((mask[i] & (1 << j)) == 0)
3652				return ((i << 5) + j);
3653		}
3654	}
3655
3656	return (-1);
3657}
3658
3659int
3660ctl_set_mask(uint32_t *mask, uint32_t bit)
3661{
3662	uint32_t chunk, piece;
3663
3664	chunk = bit >> 5;
3665	piece = bit % (sizeof(uint32_t) * 8);
3666
3667	if ((mask[chunk] & (1 << piece)) != 0)
3668		return (-1);
3669	else
3670		mask[chunk] |= (1 << piece);
3671
3672	return (0);
3673}
3674
3675int
3676ctl_clear_mask(uint32_t *mask, uint32_t bit)
3677{
3678	uint32_t chunk, piece;
3679
3680	chunk = bit >> 5;
3681	piece = bit % (sizeof(uint32_t) * 8);
3682
3683	if ((mask[chunk] & (1 << piece)) == 0)
3684		return (-1);
3685	else
3686		mask[chunk] &= ~(1 << piece);
3687
3688	return (0);
3689}
3690
3691int
3692ctl_is_set(uint32_t *mask, uint32_t bit)
3693{
3694	uint32_t chunk, piece;
3695
3696	chunk = bit >> 5;
3697	piece = bit % (sizeof(uint32_t) * 8);
3698
3699	if ((mask[chunk] & (1 << piece)) == 0)
3700		return (0);
3701	else
3702		return (1);
3703}
3704
3705static uint64_t
3706ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3707{
3708	uint64_t *t;
3709
3710	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3711	if (t == NULL)
3712		return (0);
3713	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3714}
3715
3716static void
3717ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3718{
3719	uint64_t *t;
3720
3721	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3722	if (t == NULL)
3723		return;
3724	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3725}
3726
3727static void
3728ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3729{
3730	uint64_t *p;
3731	u_int i;
3732
3733	i = residx/CTL_MAX_INIT_PER_PORT;
3734	if (lun->pr_keys[i] != NULL)
3735		return;
3736	mtx_unlock(&lun->lun_lock);
3737	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3738	    M_WAITOK | M_ZERO);
3739	mtx_lock(&lun->lun_lock);
3740	if (lun->pr_keys[i] == NULL)
3741		lun->pr_keys[i] = p;
3742	else
3743		free(p, M_CTL);
3744}
3745
3746static void
3747ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3748{
3749	uint64_t *t;
3750
3751	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3752	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3753	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3754}
3755
3756/*
3757 * ctl_softc, pool_name, total_ctl_io are passed in.
3758 * npool is passed out.
3759 */
3760int
3761ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3762		uint32_t total_ctl_io, void **npool)
3763{
3764#ifdef IO_POOLS
3765	struct ctl_io_pool *pool;
3766
3767	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3768					    M_NOWAIT | M_ZERO);
3769	if (pool == NULL)
3770		return (ENOMEM);
3771
3772	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3773	pool->ctl_softc = ctl_softc;
3774	pool->zone = uma_zsecond_create(pool->name, NULL,
3775	    NULL, NULL, NULL, ctl_softc->io_zone);
3776	/* uma_prealloc(pool->zone, total_ctl_io); */
3777
3778	*npool = pool;
3779#else
3780	*npool = ctl_softc->io_zone;
3781#endif
3782	return (0);
3783}
3784
3785void
3786ctl_pool_free(struct ctl_io_pool *pool)
3787{
3788
3789	if (pool == NULL)
3790		return;
3791
3792#ifdef IO_POOLS
3793	uma_zdestroy(pool->zone);
3794	free(pool, M_CTL);
3795#endif
3796}
3797
3798union ctl_io *
3799ctl_alloc_io(void *pool_ref)
3800{
3801	union ctl_io *io;
3802#ifdef IO_POOLS
3803	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3804
3805	io = uma_zalloc(pool->zone, M_WAITOK);
3806#else
3807	io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3808#endif
3809	if (io != NULL)
3810		io->io_hdr.pool = pool_ref;
3811	return (io);
3812}
3813
3814union ctl_io *
3815ctl_alloc_io_nowait(void *pool_ref)
3816{
3817	union ctl_io *io;
3818#ifdef IO_POOLS
3819	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3820
3821	io = uma_zalloc(pool->zone, M_NOWAIT);
3822#else
3823	io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3824#endif
3825	if (io != NULL)
3826		io->io_hdr.pool = pool_ref;
3827	return (io);
3828}
3829
3830void
3831ctl_free_io(union ctl_io *io)
3832{
3833#ifdef IO_POOLS
3834	struct ctl_io_pool *pool;
3835#endif
3836
3837	if (io == NULL)
3838		return;
3839
3840#ifdef IO_POOLS
3841	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3842	uma_zfree(pool->zone, io);
3843#else
3844	uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3845#endif
3846}
3847
3848void
3849ctl_zero_io(union ctl_io *io)
3850{
3851	void *pool_ref;
3852
3853	if (io == NULL)
3854		return;
3855
3856	/*
3857	 * May need to preserve linked list pointers at some point too.
3858	 */
3859	pool_ref = io->io_hdr.pool;
3860	memset(io, 0, sizeof(*io));
3861	io->io_hdr.pool = pool_ref;
3862}
3863
3864/*
3865 * This routine is currently used for internal copies of ctl_ios that need
3866 * to persist for some reason after we've already returned status to the
3867 * FETD.  (Thus the flag set.)
3868 *
3869 * XXX XXX
3870 * Note that this makes a blind copy of all fields in the ctl_io, except
3871 * for the pool reference.  This includes any memory that has been
3872 * allocated!  That memory will no longer be valid after done has been
3873 * called, so this would be VERY DANGEROUS for command that actually does
3874 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3875 * start and stop commands, which don't transfer any data, so this is not a
3876 * problem.  If it is used for anything else, the caller would also need to
3877 * allocate data buffer space and this routine would need to be modified to
3878 * copy the data buffer(s) as well.
3879 */
3880void
3881ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3882{
3883	void *pool_ref;
3884
3885	if ((src == NULL)
3886	 || (dest == NULL))
3887		return;
3888
3889	/*
3890	 * May need to preserve linked list pointers at some point too.
3891	 */
3892	pool_ref = dest->io_hdr.pool;
3893
3894	memcpy(dest, src, MIN(sizeof(*src), sizeof(*dest)));
3895
3896	dest->io_hdr.pool = pool_ref;
3897	/*
3898	 * We need to know that this is an internal copy, and doesn't need
3899	 * to get passed back to the FETD that allocated it.
3900	 */
3901	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3902}
3903
3904int
3905ctl_expand_number(const char *buf, uint64_t *num)
3906{
3907	char *endptr;
3908	uint64_t number;
3909	unsigned shift;
3910
3911	number = strtoq(buf, &endptr, 0);
3912
3913	switch (tolower((unsigned char)*endptr)) {
3914	case 'e':
3915		shift = 60;
3916		break;
3917	case 'p':
3918		shift = 50;
3919		break;
3920	case 't':
3921		shift = 40;
3922		break;
3923	case 'g':
3924		shift = 30;
3925		break;
3926	case 'm':
3927		shift = 20;
3928		break;
3929	case 'k':
3930		shift = 10;
3931		break;
3932	case 'b':
3933	case '\0': /* No unit. */
3934		*num = number;
3935		return (0);
3936	default:
3937		/* Unrecognized unit. */
3938		return (-1);
3939	}
3940
3941	if ((number << shift) >> shift != number) {
3942		/* Overflow */
3943		return (-1);
3944	}
3945	*num = number << shift;
3946	return (0);
3947}
3948
3949
3950/*
3951 * This routine could be used in the future to load default and/or saved
3952 * mode page parameters for a particuar lun.
3953 */
3954static int
3955ctl_init_page_index(struct ctl_lun *lun)
3956{
3957	int i;
3958	struct ctl_page_index *page_index;
3959	const char *value;
3960	uint64_t ival;
3961
3962	memcpy(&lun->mode_pages.index, page_index_template,
3963	       sizeof(page_index_template));
3964
3965	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3966
3967		page_index = &lun->mode_pages.index[i];
3968		/*
3969		 * If this is a disk-only mode page, there's no point in
3970		 * setting it up.  For some pages, we have to have some
3971		 * basic information about the disk in order to calculate the
3972		 * mode page data.
3973		 */
3974		if ((lun->be_lun->lun_type != T_DIRECT)
3975		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3976			continue;
3977
3978		switch (page_index->page_code & SMPH_PC_MASK) {
3979		case SMS_RW_ERROR_RECOVERY_PAGE: {
3980			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3981				panic("subpage is incorrect!");
3982			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3983			       &rw_er_page_default,
3984			       sizeof(rw_er_page_default));
3985			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3986			       &rw_er_page_changeable,
3987			       sizeof(rw_er_page_changeable));
3988			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3989			       &rw_er_page_default,
3990			       sizeof(rw_er_page_default));
3991			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3992			       &rw_er_page_default,
3993			       sizeof(rw_er_page_default));
3994			page_index->page_data =
3995				(uint8_t *)lun->mode_pages.rw_er_page;
3996			break;
3997		}
3998		case SMS_FORMAT_DEVICE_PAGE: {
3999			struct scsi_format_page *format_page;
4000
4001			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4002				panic("subpage is incorrect!");
4003
4004			/*
4005			 * Sectors per track are set above.  Bytes per
4006			 * sector need to be set here on a per-LUN basis.
4007			 */
4008			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4009			       &format_page_default,
4010			       sizeof(format_page_default));
4011			memcpy(&lun->mode_pages.format_page[
4012			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4013			       sizeof(format_page_changeable));
4014			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4015			       &format_page_default,
4016			       sizeof(format_page_default));
4017			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4018			       &format_page_default,
4019			       sizeof(format_page_default));
4020
4021			format_page = &lun->mode_pages.format_page[
4022				CTL_PAGE_CURRENT];
4023			scsi_ulto2b(lun->be_lun->blocksize,
4024				    format_page->bytes_per_sector);
4025
4026			format_page = &lun->mode_pages.format_page[
4027				CTL_PAGE_DEFAULT];
4028			scsi_ulto2b(lun->be_lun->blocksize,
4029				    format_page->bytes_per_sector);
4030
4031			format_page = &lun->mode_pages.format_page[
4032				CTL_PAGE_SAVED];
4033			scsi_ulto2b(lun->be_lun->blocksize,
4034				    format_page->bytes_per_sector);
4035
4036			page_index->page_data =
4037				(uint8_t *)lun->mode_pages.format_page;
4038			break;
4039		}
4040		case SMS_RIGID_DISK_PAGE: {
4041			struct scsi_rigid_disk_page *rigid_disk_page;
4042			uint32_t sectors_per_cylinder;
4043			uint64_t cylinders;
4044#ifndef	__XSCALE__
4045			int shift;
4046#endif /* !__XSCALE__ */
4047
4048			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4049				panic("invalid subpage value %d",
4050				      page_index->subpage);
4051
4052			/*
4053			 * Rotation rate and sectors per track are set
4054			 * above.  We calculate the cylinders here based on
4055			 * capacity.  Due to the number of heads and
4056			 * sectors per track we're using, smaller arrays
4057			 * may turn out to have 0 cylinders.  Linux and
4058			 * FreeBSD don't pay attention to these mode pages
4059			 * to figure out capacity, but Solaris does.  It
4060			 * seems to deal with 0 cylinders just fine, and
4061			 * works out a fake geometry based on the capacity.
4062			 */
4063			memcpy(&lun->mode_pages.rigid_disk_page[
4064			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4065			       sizeof(rigid_disk_page_default));
4066			memcpy(&lun->mode_pages.rigid_disk_page[
4067			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4068			       sizeof(rigid_disk_page_changeable));
4069
4070			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4071				CTL_DEFAULT_HEADS;
4072
4073			/*
4074			 * The divide method here will be more accurate,
4075			 * probably, but results in floating point being
4076			 * used in the kernel on i386 (__udivdi3()).  On the
4077			 * XScale, though, __udivdi3() is implemented in
4078			 * software.
4079			 *
4080			 * The shift method for cylinder calculation is
4081			 * accurate if sectors_per_cylinder is a power of
4082			 * 2.  Otherwise it might be slightly off -- you
4083			 * might have a bit of a truncation problem.
4084			 */
4085#ifdef	__XSCALE__
4086			cylinders = (lun->be_lun->maxlba + 1) /
4087				sectors_per_cylinder;
4088#else
4089			for (shift = 31; shift > 0; shift--) {
4090				if (sectors_per_cylinder & (1 << shift))
4091					break;
4092			}
4093			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4094#endif
4095
4096			/*
4097			 * We've basically got 3 bytes, or 24 bits for the
4098			 * cylinder size in the mode page.  If we're over,
4099			 * just round down to 2^24.
4100			 */
4101			if (cylinders > 0xffffff)
4102				cylinders = 0xffffff;
4103
4104			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4105				CTL_PAGE_DEFAULT];
4106			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4107
4108			if ((value = ctl_get_opt(&lun->be_lun->options,
4109			    "rpm")) != NULL) {
4110				scsi_ulto2b(strtol(value, NULL, 0),
4111				     rigid_disk_page->rotation_rate);
4112			}
4113
4114			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4115			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4116			       sizeof(rigid_disk_page_default));
4117			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4118			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4119			       sizeof(rigid_disk_page_default));
4120
4121			page_index->page_data =
4122				(uint8_t *)lun->mode_pages.rigid_disk_page;
4123			break;
4124		}
4125		case SMS_CACHING_PAGE: {
4126			struct scsi_caching_page *caching_page;
4127
4128			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4129				panic("invalid subpage value %d",
4130				      page_index->subpage);
4131			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4132			       &caching_page_default,
4133			       sizeof(caching_page_default));
4134			memcpy(&lun->mode_pages.caching_page[
4135			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4136			       sizeof(caching_page_changeable));
4137			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4138			       &caching_page_default,
4139			       sizeof(caching_page_default));
4140			caching_page = &lun->mode_pages.caching_page[
4141			    CTL_PAGE_SAVED];
4142			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4143			if (value != NULL && strcmp(value, "off") == 0)
4144				caching_page->flags1 &= ~SCP_WCE;
4145			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4146			if (value != NULL && strcmp(value, "off") == 0)
4147				caching_page->flags1 |= SCP_RCD;
4148			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4149			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4150			       sizeof(caching_page_default));
4151			page_index->page_data =
4152				(uint8_t *)lun->mode_pages.caching_page;
4153			break;
4154		}
4155		case SMS_CONTROL_MODE_PAGE: {
4156			struct scsi_control_page *control_page;
4157
4158			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4159				panic("invalid subpage value %d",
4160				      page_index->subpage);
4161
4162			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4163			       &control_page_default,
4164			       sizeof(control_page_default));
4165			memcpy(&lun->mode_pages.control_page[
4166			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4167			       sizeof(control_page_changeable));
4168			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4169			       &control_page_default,
4170			       sizeof(control_page_default));
4171			control_page = &lun->mode_pages.control_page[
4172			    CTL_PAGE_SAVED];
4173			value = ctl_get_opt(&lun->be_lun->options, "reordering");
4174			if (value != NULL && strcmp(value, "unrestricted") == 0) {
4175				control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4176				control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4177			}
4178			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4179			       &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4180			       sizeof(control_page_default));
4181			page_index->page_data =
4182				(uint8_t *)lun->mode_pages.control_page;
4183			break;
4184
4185		}
4186		case SMS_INFO_EXCEPTIONS_PAGE: {
4187			switch (page_index->subpage) {
4188			case SMS_SUBPAGE_PAGE_0:
4189				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4190				       &ie_page_default,
4191				       sizeof(ie_page_default));
4192				memcpy(&lun->mode_pages.ie_page[
4193				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4194				       sizeof(ie_page_changeable));
4195				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4196				       &ie_page_default,
4197				       sizeof(ie_page_default));
4198				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4199				       &ie_page_default,
4200				       sizeof(ie_page_default));
4201				page_index->page_data =
4202					(uint8_t *)lun->mode_pages.ie_page;
4203				break;
4204			case 0x02: {
4205				struct ctl_logical_block_provisioning_page *page;
4206
4207				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4208				       &lbp_page_default,
4209				       sizeof(lbp_page_default));
4210				memcpy(&lun->mode_pages.lbp_page[
4211				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4212				       sizeof(lbp_page_changeable));
4213				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4214				       &lbp_page_default,
4215				       sizeof(lbp_page_default));
4216				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4217				value = ctl_get_opt(&lun->be_lun->options,
4218				    "avail-threshold");
4219				if (value != NULL &&
4220				    ctl_expand_number(value, &ival) == 0) {
4221					page->descr[0].flags |= SLBPPD_ENABLED |
4222					    SLBPPD_ARMING_DEC;
4223					if (lun->be_lun->blocksize)
4224						ival /= lun->be_lun->blocksize;
4225					else
4226						ival /= 512;
4227					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4228					    page->descr[0].count);
4229				}
4230				value = ctl_get_opt(&lun->be_lun->options,
4231				    "used-threshold");
4232				if (value != NULL &&
4233				    ctl_expand_number(value, &ival) == 0) {
4234					page->descr[1].flags |= SLBPPD_ENABLED |
4235					    SLBPPD_ARMING_INC;
4236					if (lun->be_lun->blocksize)
4237						ival /= lun->be_lun->blocksize;
4238					else
4239						ival /= 512;
4240					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4241					    page->descr[1].count);
4242				}
4243				value = ctl_get_opt(&lun->be_lun->options,
4244				    "pool-avail-threshold");
4245				if (value != NULL &&
4246				    ctl_expand_number(value, &ival) == 0) {
4247					page->descr[2].flags |= SLBPPD_ENABLED |
4248					    SLBPPD_ARMING_DEC;
4249					if (lun->be_lun->blocksize)
4250						ival /= lun->be_lun->blocksize;
4251					else
4252						ival /= 512;
4253					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4254					    page->descr[2].count);
4255				}
4256				value = ctl_get_opt(&lun->be_lun->options,
4257				    "pool-used-threshold");
4258				if (value != NULL &&
4259				    ctl_expand_number(value, &ival) == 0) {
4260					page->descr[3].flags |= SLBPPD_ENABLED |
4261					    SLBPPD_ARMING_INC;
4262					if (lun->be_lun->blocksize)
4263						ival /= lun->be_lun->blocksize;
4264					else
4265						ival /= 512;
4266					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4267					    page->descr[3].count);
4268				}
4269				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4270				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4271				       sizeof(lbp_page_default));
4272				page_index->page_data =
4273					(uint8_t *)lun->mode_pages.lbp_page;
4274			}}
4275			break;
4276		}
4277		case SMS_VENDOR_SPECIFIC_PAGE:{
4278			switch (page_index->subpage) {
4279			case DBGCNF_SUBPAGE_CODE: {
4280				struct copan_debugconf_subpage *current_page,
4281							       *saved_page;
4282
4283				memcpy(&lun->mode_pages.debugconf_subpage[
4284				       CTL_PAGE_CURRENT],
4285				       &debugconf_page_default,
4286				       sizeof(debugconf_page_default));
4287				memcpy(&lun->mode_pages.debugconf_subpage[
4288				       CTL_PAGE_CHANGEABLE],
4289				       &debugconf_page_changeable,
4290				       sizeof(debugconf_page_changeable));
4291				memcpy(&lun->mode_pages.debugconf_subpage[
4292				       CTL_PAGE_DEFAULT],
4293				       &debugconf_page_default,
4294				       sizeof(debugconf_page_default));
4295				memcpy(&lun->mode_pages.debugconf_subpage[
4296				       CTL_PAGE_SAVED],
4297				       &debugconf_page_default,
4298				       sizeof(debugconf_page_default));
4299				page_index->page_data =
4300					(uint8_t *)lun->mode_pages.debugconf_subpage;
4301
4302				current_page = (struct copan_debugconf_subpage *)
4303					(page_index->page_data +
4304					 (page_index->page_len *
4305					  CTL_PAGE_CURRENT));
4306				saved_page = (struct copan_debugconf_subpage *)
4307					(page_index->page_data +
4308					 (page_index->page_len *
4309					  CTL_PAGE_SAVED));
4310				break;
4311			}
4312			default:
4313				panic("invalid subpage value %d",
4314				      page_index->subpage);
4315				break;
4316			}
4317   			break;
4318		}
4319		default:
4320			panic("invalid page value %d",
4321			      page_index->page_code & SMPH_PC_MASK);
4322			break;
4323    	}
4324	}
4325
4326	return (CTL_RETVAL_COMPLETE);
4327}
4328
4329static int
4330ctl_init_log_page_index(struct ctl_lun *lun)
4331{
4332	struct ctl_page_index *page_index;
4333	int i, j, k, prev;
4334
4335	memcpy(&lun->log_pages.index, log_page_index_template,
4336	       sizeof(log_page_index_template));
4337
4338	prev = -1;
4339	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4340
4341		page_index = &lun->log_pages.index[i];
4342		/*
4343		 * If this is a disk-only mode page, there's no point in
4344		 * setting it up.  For some pages, we have to have some
4345		 * basic information about the disk in order to calculate the
4346		 * mode page data.
4347		 */
4348		if ((lun->be_lun->lun_type != T_DIRECT)
4349		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4350			continue;
4351
4352		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4353		     lun->backend->lun_attr == NULL)
4354			continue;
4355
4356		if (page_index->page_code != prev) {
4357			lun->log_pages.pages_page[j] = page_index->page_code;
4358			prev = page_index->page_code;
4359			j++;
4360		}
4361		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4362		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4363		k++;
4364	}
4365	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4366	lun->log_pages.index[0].page_len = j;
4367	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4368	lun->log_pages.index[1].page_len = k * 2;
4369	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4370	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4371
4372	return (CTL_RETVAL_COMPLETE);
4373}
4374
4375static int
4376hex2bin(const char *str, uint8_t *buf, int buf_size)
4377{
4378	int i;
4379	u_char c;
4380
4381	memset(buf, 0, buf_size);
4382	while (isspace(str[0]))
4383		str++;
4384	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4385		str += 2;
4386	buf_size *= 2;
4387	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4388		c = str[i];
4389		if (isdigit(c))
4390			c -= '0';
4391		else if (isalpha(c))
4392			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4393		else
4394			break;
4395		if (c >= 16)
4396			break;
4397		if ((i & 1) == 0)
4398			buf[i / 2] |= (c << 4);
4399		else
4400			buf[i / 2] |= c;
4401	}
4402	return ((i + 1) / 2);
4403}
4404
4405/*
4406 * LUN allocation.
4407 *
4408 * Requirements:
4409 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4410 *   wants us to allocate the LUN and he can block.
4411 * - ctl_softc is always set
4412 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4413 *
4414 * Returns 0 for success, non-zero (errno) for failure.
4415 */
4416static int
4417ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4418	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4419{
4420	struct ctl_lun *nlun, *lun;
4421	struct ctl_port *port;
4422	struct scsi_vpd_id_descriptor *desc;
4423	struct scsi_vpd_id_t10 *t10id;
4424	const char *eui, *naa, *scsiname, *vendor, *value;
4425	int lun_number, i, lun_malloced;
4426	int devidlen, idlen1, idlen2 = 0, len;
4427
4428	if (be_lun == NULL)
4429		return (EINVAL);
4430
4431	/*
4432	 * We currently only support Direct Access or Processor LUN types.
4433	 */
4434	switch (be_lun->lun_type) {
4435	case T_DIRECT:
4436		break;
4437	case T_PROCESSOR:
4438		break;
4439	case T_SEQUENTIAL:
4440	case T_CHANGER:
4441	default:
4442		be_lun->lun_config_status(be_lun->be_lun,
4443					  CTL_LUN_CONFIG_FAILURE);
4444		break;
4445	}
4446	if (ctl_lun == NULL) {
4447		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4448		lun_malloced = 1;
4449	} else {
4450		lun_malloced = 0;
4451		lun = ctl_lun;
4452	}
4453
4454	memset(lun, 0, sizeof(*lun));
4455	if (lun_malloced)
4456		lun->flags = CTL_LUN_MALLOCED;
4457
4458	/* Generate LUN ID. */
4459	devidlen = max(CTL_DEVID_MIN_LEN,
4460	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4461	idlen1 = sizeof(*t10id) + devidlen;
4462	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4463	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4464	if (scsiname != NULL) {
4465		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4466		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4467	}
4468	eui = ctl_get_opt(&be_lun->options, "eui");
4469	if (eui != NULL) {
4470		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4471	}
4472	naa = ctl_get_opt(&be_lun->options, "naa");
4473	if (naa != NULL) {
4474		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4475	}
4476	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4477	    M_CTL, M_WAITOK | M_ZERO);
4478	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4479	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4480	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4481	desc->length = idlen1;
4482	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4483	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4484	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4485		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4486	} else {
4487		strncpy(t10id->vendor, vendor,
4488		    min(sizeof(t10id->vendor), strlen(vendor)));
4489	}
4490	strncpy((char *)t10id->vendor_spec_id,
4491	    (char *)be_lun->device_id, devidlen);
4492	if (scsiname != NULL) {
4493		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4494		    desc->length);
4495		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4496		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4497		    SVPD_ID_TYPE_SCSI_NAME;
4498		desc->length = idlen2;
4499		strlcpy(desc->identifier, scsiname, idlen2);
4500	}
4501	if (eui != NULL) {
4502		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4503		    desc->length);
4504		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4505		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4506		    SVPD_ID_TYPE_EUI64;
4507		desc->length = hex2bin(eui, desc->identifier, 16);
4508		desc->length = desc->length > 12 ? 16 :
4509		    (desc->length > 8 ? 12 : 8);
4510		len -= 16 - desc->length;
4511	}
4512	if (naa != NULL) {
4513		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4514		    desc->length);
4515		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4516		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4517		    SVPD_ID_TYPE_NAA;
4518		desc->length = hex2bin(naa, desc->identifier, 16);
4519		desc->length = desc->length > 8 ? 16 : 8;
4520		len -= 16 - desc->length;
4521	}
4522	lun->lun_devid->len = len;
4523
4524	mtx_lock(&ctl_softc->ctl_lock);
4525	/*
4526	 * See if the caller requested a particular LUN number.  If so, see
4527	 * if it is available.  Otherwise, allocate the first available LUN.
4528	 */
4529	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4530		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4531		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4532			mtx_unlock(&ctl_softc->ctl_lock);
4533			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4534				printf("ctl: requested LUN ID %d is higher "
4535				       "than CTL_MAX_LUNS - 1 (%d)\n",
4536				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4537			} else {
4538				/*
4539				 * XXX KDM return an error, or just assign
4540				 * another LUN ID in this case??
4541				 */
4542				printf("ctl: requested LUN ID %d is already "
4543				       "in use\n", be_lun->req_lun_id);
4544			}
4545			if (lun->flags & CTL_LUN_MALLOCED)
4546				free(lun, M_CTL);
4547			be_lun->lun_config_status(be_lun->be_lun,
4548						  CTL_LUN_CONFIG_FAILURE);
4549			return (ENOSPC);
4550		}
4551		lun_number = be_lun->req_lun_id;
4552	} else {
4553		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4554		if (lun_number == -1) {
4555			mtx_unlock(&ctl_softc->ctl_lock);
4556			printf("ctl: can't allocate LUN on target %ju, out of "
4557			       "LUNs\n", (uintmax_t)target_id.id);
4558			if (lun->flags & CTL_LUN_MALLOCED)
4559				free(lun, M_CTL);
4560			be_lun->lun_config_status(be_lun->be_lun,
4561						  CTL_LUN_CONFIG_FAILURE);
4562			return (ENOSPC);
4563		}
4564	}
4565	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4566
4567	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4568	lun->target = target_id;
4569	lun->lun = lun_number;
4570	lun->be_lun = be_lun;
4571	/*
4572	 * The processor LUN is always enabled.  Disk LUNs come on line
4573	 * disabled, and must be enabled by the backend.
4574	 */
4575	lun->flags |= CTL_LUN_DISABLED;
4576	lun->backend = be_lun->be;
4577	be_lun->ctl_lun = lun;
4578	be_lun->lun_id = lun_number;
4579	atomic_add_int(&be_lun->be->num_luns, 1);
4580	if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4581		lun->flags |= CTL_LUN_OFFLINE;
4582
4583	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4584		lun->flags |= CTL_LUN_STOPPED;
4585
4586	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4587		lun->flags |= CTL_LUN_INOPERABLE;
4588
4589	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4590		lun->flags |= CTL_LUN_PRIMARY_SC;
4591
4592	value = ctl_get_opt(&be_lun->options, "readonly");
4593	if (value != NULL && strcmp(value, "on") == 0)
4594		lun->flags |= CTL_LUN_READONLY;
4595
4596	lun->serseq = CTL_LUN_SERSEQ_OFF;
4597	if (be_lun->flags & CTL_LUN_FLAG_SERSEQ_READ)
4598		lun->serseq = CTL_LUN_SERSEQ_READ;
4599	value = ctl_get_opt(&be_lun->options, "serseq");
4600	if (value != NULL && strcmp(value, "on") == 0)
4601		lun->serseq = CTL_LUN_SERSEQ_ON;
4602	else if (value != NULL && strcmp(value, "read") == 0)
4603		lun->serseq = CTL_LUN_SERSEQ_READ;
4604	else if (value != NULL && strcmp(value, "off") == 0)
4605		lun->serseq = CTL_LUN_SERSEQ_OFF;
4606
4607	lun->ctl_softc = ctl_softc;
4608	TAILQ_INIT(&lun->ooa_queue);
4609	TAILQ_INIT(&lun->blocked_queue);
4610	STAILQ_INIT(&lun->error_list);
4611	ctl_tpc_lun_init(lun);
4612
4613	/*
4614	 * Initialize the mode and log page index.
4615	 */
4616	ctl_init_page_index(lun);
4617	ctl_init_log_page_index(lun);
4618
4619	/*
4620	 * Now, before we insert this lun on the lun list, set the lun
4621	 * inventory changed UA for all other luns.
4622	 */
4623	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4624		mtx_lock(&nlun->lun_lock);
4625		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4626		mtx_unlock(&nlun->lun_lock);
4627	}
4628
4629	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4630
4631	ctl_softc->ctl_luns[lun_number] = lun;
4632
4633	ctl_softc->num_luns++;
4634
4635	/* Setup statistics gathering */
4636	lun->stats.device_type = be_lun->lun_type;
4637	lun->stats.lun_number = lun_number;
4638	if (lun->stats.device_type == T_DIRECT)
4639		lun->stats.blocksize = be_lun->blocksize;
4640	else
4641		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4642	for (i = 0;i < CTL_MAX_PORTS;i++)
4643		lun->stats.ports[i].targ_port = i;
4644
4645	mtx_unlock(&ctl_softc->ctl_lock);
4646
4647	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4648
4649	/*
4650	 * Run through each registered FETD and bring it online if it isn't
4651	 * already.  Enable the target ID if it hasn't been enabled, and
4652	 * enable this particular LUN.
4653	 */
4654	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4655		int retval;
4656
4657		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4658		if (retval != 0) {
4659			printf("ctl_alloc_lun: FETD %s port %d returned error "
4660			       "%d for lun_enable on target %ju lun %d\n",
4661			       port->port_name, port->targ_port, retval,
4662			       (uintmax_t)target_id.id, lun_number);
4663		} else
4664			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4665	}
4666	return (0);
4667}
4668
4669/*
4670 * Delete a LUN.
4671 * Assumptions:
4672 * - LUN has already been marked invalid and any pending I/O has been taken
4673 *   care of.
4674 */
4675static int
4676ctl_free_lun(struct ctl_lun *lun)
4677{
4678	struct ctl_softc *softc;
4679#if 0
4680	struct ctl_port *port;
4681#endif
4682	struct ctl_lun *nlun;
4683	int i;
4684
4685	softc = lun->ctl_softc;
4686
4687	mtx_assert(&softc->ctl_lock, MA_OWNED);
4688
4689	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4690
4691	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4692
4693	softc->ctl_luns[lun->lun] = NULL;
4694
4695	if (!TAILQ_EMPTY(&lun->ooa_queue))
4696		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4697
4698	softc->num_luns--;
4699
4700	/*
4701	 * XXX KDM this scheme only works for a single target/multiple LUN
4702	 * setup.  It needs to be revamped for a multiple target scheme.
4703	 *
4704	 * XXX KDM this results in port->lun_disable() getting called twice,
4705	 * once when ctl_disable_lun() is called, and a second time here.
4706	 * We really need to re-think the LUN disable semantics.  There
4707	 * should probably be several steps/levels to LUN removal:
4708	 *  - disable
4709	 *  - invalidate
4710	 *  - free
4711 	 *
4712	 * Right now we only have a disable method when communicating to
4713	 * the front end ports, at least for individual LUNs.
4714	 */
4715#if 0
4716	STAILQ_FOREACH(port, &softc->port_list, links) {
4717		int retval;
4718
4719		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4720					 lun->lun);
4721		if (retval != 0) {
4722			printf("ctl_free_lun: FETD %s port %d returned error "
4723			       "%d for lun_disable on target %ju lun %jd\n",
4724			       port->port_name, port->targ_port, retval,
4725			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4726		}
4727
4728		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4729			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4730
4731			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4732			if (retval != 0) {
4733				printf("ctl_free_lun: FETD %s port %d "
4734				       "returned error %d for targ_disable on "
4735				       "target %ju\n", port->port_name,
4736				       port->targ_port, retval,
4737				       (uintmax_t)lun->target.id);
4738			} else
4739				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4740
4741			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4742				continue;
4743
4744#if 0
4745			port->port_offline(port->onoff_arg);
4746			port->status &= ~CTL_PORT_STATUS_ONLINE;
4747#endif
4748		}
4749	}
4750#endif
4751
4752	/*
4753	 * Tell the backend to free resources, if this LUN has a backend.
4754	 */
4755	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4756	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4757
4758	ctl_tpc_lun_shutdown(lun);
4759	mtx_destroy(&lun->lun_lock);
4760	free(lun->lun_devid, M_CTL);
4761	for (i = 0; i < CTL_MAX_PORTS; i++)
4762		free(lun->pending_ua[i], M_CTL);
4763	for (i = 0; i < 2 * CTL_MAX_PORTS; i++)
4764		free(lun->pr_keys[i], M_CTL);
4765	free(lun->write_buffer, M_CTL);
4766	if (lun->flags & CTL_LUN_MALLOCED)
4767		free(lun, M_CTL);
4768
4769	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4770		mtx_lock(&nlun->lun_lock);
4771		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4772		mtx_unlock(&nlun->lun_lock);
4773	}
4774
4775	return (0);
4776}
4777
4778static void
4779ctl_create_lun(struct ctl_be_lun *be_lun)
4780{
4781	struct ctl_softc *softc;
4782
4783	softc = control_softc;
4784
4785	/*
4786	 * ctl_alloc_lun() should handle all potential failure cases.
4787	 */
4788	ctl_alloc_lun(softc, NULL, be_lun, softc->target);
4789}
4790
4791int
4792ctl_add_lun(struct ctl_be_lun *be_lun)
4793{
4794	struct ctl_softc *softc = control_softc;
4795
4796	mtx_lock(&softc->ctl_lock);
4797	STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4798	mtx_unlock(&softc->ctl_lock);
4799	wakeup(&softc->pending_lun_queue);
4800
4801	return (0);
4802}
4803
4804int
4805ctl_enable_lun(struct ctl_be_lun *be_lun)
4806{
4807	struct ctl_softc *softc;
4808	struct ctl_port *port, *nport;
4809	struct ctl_lun *lun;
4810	int retval;
4811
4812	lun = (struct ctl_lun *)be_lun->ctl_lun;
4813	softc = lun->ctl_softc;
4814
4815	mtx_lock(&softc->ctl_lock);
4816	mtx_lock(&lun->lun_lock);
4817	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4818		/*
4819		 * eh?  Why did we get called if the LUN is already
4820		 * enabled?
4821		 */
4822		mtx_unlock(&lun->lun_lock);
4823		mtx_unlock(&softc->ctl_lock);
4824		return (0);
4825	}
4826	lun->flags &= ~CTL_LUN_DISABLED;
4827	mtx_unlock(&lun->lun_lock);
4828
4829	for (port = STAILQ_FIRST(&softc->port_list); port != NULL; port = nport) {
4830		nport = STAILQ_NEXT(port, links);
4831
4832		/*
4833		 * Drop the lock while we call the FETD's enable routine.
4834		 * This can lead to a callback into CTL (at least in the
4835		 * case of the internal initiator frontend.
4836		 */
4837		mtx_unlock(&softc->ctl_lock);
4838		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4839		mtx_lock(&softc->ctl_lock);
4840		if (retval != 0) {
4841			printf("%s: FETD %s port %d returned error "
4842			       "%d for lun_enable on target %ju lun %jd\n",
4843			       __func__, port->port_name, port->targ_port, retval,
4844			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4845		}
4846#if 0
4847		 else {
4848            /* NOTE:  TODO:  why does lun enable affect port status? */
4849			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4850		}
4851#endif
4852	}
4853
4854	mtx_unlock(&softc->ctl_lock);
4855
4856	return (0);
4857}
4858
4859int
4860ctl_disable_lun(struct ctl_be_lun *be_lun)
4861{
4862	struct ctl_softc *softc;
4863	struct ctl_port *port;
4864	struct ctl_lun *lun;
4865	int retval;
4866
4867	lun = (struct ctl_lun *)be_lun->ctl_lun;
4868	softc = lun->ctl_softc;
4869
4870	mtx_lock(&softc->ctl_lock);
4871	mtx_lock(&lun->lun_lock);
4872	if (lun->flags & CTL_LUN_DISABLED) {
4873		mtx_unlock(&lun->lun_lock);
4874		mtx_unlock(&softc->ctl_lock);
4875		return (0);
4876	}
4877	lun->flags |= CTL_LUN_DISABLED;
4878	mtx_unlock(&lun->lun_lock);
4879
4880	STAILQ_FOREACH(port, &softc->port_list, links) {
4881		mtx_unlock(&softc->ctl_lock);
4882		/*
4883		 * Drop the lock before we call the frontend's disable
4884		 * routine, to avoid lock order reversals.
4885		 *
4886		 * XXX KDM what happens if the frontend list changes while
4887		 * we're traversing it?  It's unlikely, but should be handled.
4888		 */
4889		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4890					 lun->lun);
4891		mtx_lock(&softc->ctl_lock);
4892		if (retval != 0) {
4893			printf("ctl_alloc_lun: FETD %s port %d returned error "
4894			       "%d for lun_disable on target %ju lun %jd\n",
4895			       port->port_name, port->targ_port, retval,
4896			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4897		}
4898	}
4899
4900	mtx_unlock(&softc->ctl_lock);
4901
4902	return (0);
4903}
4904
4905int
4906ctl_start_lun(struct ctl_be_lun *be_lun)
4907{
4908	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4909
4910	mtx_lock(&lun->lun_lock);
4911	lun->flags &= ~CTL_LUN_STOPPED;
4912	mtx_unlock(&lun->lun_lock);
4913	return (0);
4914}
4915
4916int
4917ctl_stop_lun(struct ctl_be_lun *be_lun)
4918{
4919	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4920
4921	mtx_lock(&lun->lun_lock);
4922	lun->flags |= CTL_LUN_STOPPED;
4923	mtx_unlock(&lun->lun_lock);
4924	return (0);
4925}
4926
4927int
4928ctl_lun_offline(struct ctl_be_lun *be_lun)
4929{
4930	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4931
4932	mtx_lock(&lun->lun_lock);
4933	lun->flags |= CTL_LUN_OFFLINE;
4934	mtx_unlock(&lun->lun_lock);
4935	return (0);
4936}
4937
4938int
4939ctl_lun_online(struct ctl_be_lun *be_lun)
4940{
4941	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4942
4943	mtx_lock(&lun->lun_lock);
4944	lun->flags &= ~CTL_LUN_OFFLINE;
4945	mtx_unlock(&lun->lun_lock);
4946	return (0);
4947}
4948
4949int
4950ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4951{
4952	struct ctl_softc *softc;
4953	struct ctl_lun *lun;
4954
4955	lun = (struct ctl_lun *)be_lun->ctl_lun;
4956	softc = lun->ctl_softc;
4957
4958	mtx_lock(&lun->lun_lock);
4959
4960	/*
4961	 * The LUN needs to be disabled before it can be marked invalid.
4962	 */
4963	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4964		mtx_unlock(&lun->lun_lock);
4965		return (-1);
4966	}
4967	/*
4968	 * Mark the LUN invalid.
4969	 */
4970	lun->flags |= CTL_LUN_INVALID;
4971
4972	/*
4973	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4974	 * If we have something in the OOA queue, we'll free it when the
4975	 * last I/O completes.
4976	 */
4977	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4978		mtx_unlock(&lun->lun_lock);
4979		mtx_lock(&softc->ctl_lock);
4980		ctl_free_lun(lun);
4981		mtx_unlock(&softc->ctl_lock);
4982	} else
4983		mtx_unlock(&lun->lun_lock);
4984
4985	return (0);
4986}
4987
4988int
4989ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4990{
4991	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4992
4993	mtx_lock(&lun->lun_lock);
4994	lun->flags |= CTL_LUN_INOPERABLE;
4995	mtx_unlock(&lun->lun_lock);
4996	return (0);
4997}
4998
4999int
5000ctl_lun_operable(struct ctl_be_lun *be_lun)
5001{
5002	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5003
5004	mtx_lock(&lun->lun_lock);
5005	lun->flags &= ~CTL_LUN_INOPERABLE;
5006	mtx_unlock(&lun->lun_lock);
5007	return (0);
5008}
5009
5010void
5011ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5012{
5013	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5014
5015	mtx_lock(&lun->lun_lock);
5016	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGED);
5017	mtx_unlock(&lun->lun_lock);
5018}
5019
5020/*
5021 * Backend "memory move is complete" callback for requests that never
5022 * make it down to say RAIDCore's configuration code.
5023 */
5024int
5025ctl_config_move_done(union ctl_io *io)
5026{
5027	int retval;
5028
5029	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5030	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5031	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5032
5033	if ((io->io_hdr.port_status != 0) &&
5034	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5035	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5036		/*
5037		 * For hardware error sense keys, the sense key
5038		 * specific value is defined to be a retry count,
5039		 * but we use it to pass back an internal FETD
5040		 * error code.  XXX KDM  Hopefully the FETD is only
5041		 * using 16 bits for an error code, since that's
5042		 * all the space we have in the sks field.
5043		 */
5044		ctl_set_internal_failure(&io->scsiio,
5045					 /*sks_valid*/ 1,
5046					 /*retry_count*/
5047					 io->io_hdr.port_status);
5048	}
5049
5050	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5051	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5052	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5053	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5054		/*
5055		 * XXX KDM just assuming a single pointer here, and not a
5056		 * S/G list.  If we start using S/G lists for config data,
5057		 * we'll need to know how to clean them up here as well.
5058		 */
5059		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5060			free(io->scsiio.kern_data_ptr, M_CTL);
5061		ctl_done(io);
5062		retval = CTL_RETVAL_COMPLETE;
5063	} else {
5064		/*
5065		 * XXX KDM now we need to continue data movement.  Some
5066		 * options:
5067		 * - call ctl_scsiio() again?  We don't do this for data
5068		 *   writes, because for those at least we know ahead of
5069		 *   time where the write will go and how long it is.  For
5070		 *   config writes, though, that information is largely
5071		 *   contained within the write itself, thus we need to
5072		 *   parse out the data again.
5073		 *
5074		 * - Call some other function once the data is in?
5075		 */
5076		if (ctl_debug & CTL_DEBUG_CDB_DATA)
5077			ctl_data_print(io);
5078
5079		/*
5080		 * XXX KDM call ctl_scsiio() again for now, and check flag
5081		 * bits to see whether we're allocated or not.
5082		 */
5083		retval = ctl_scsiio(&io->scsiio);
5084	}
5085	return (retval);
5086}
5087
5088/*
5089 * This gets called by a backend driver when it is done with a
5090 * data_submit method.
5091 */
5092void
5093ctl_data_submit_done(union ctl_io *io)
5094{
5095	/*
5096	 * If the IO_CONT flag is set, we need to call the supplied
5097	 * function to continue processing the I/O, instead of completing
5098	 * the I/O just yet.
5099	 *
5100	 * If there is an error, though, we don't want to keep processing.
5101	 * Instead, just send status back to the initiator.
5102	 */
5103	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5104	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5105	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5106	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5107		io->scsiio.io_cont(io);
5108		return;
5109	}
5110	ctl_done(io);
5111}
5112
5113/*
5114 * This gets called by a backend driver when it is done with a
5115 * configuration write.
5116 */
5117void
5118ctl_config_write_done(union ctl_io *io)
5119{
5120	uint8_t *buf;
5121
5122	/*
5123	 * If the IO_CONT flag is set, we need to call the supplied
5124	 * function to continue processing the I/O, instead of completing
5125	 * the I/O just yet.
5126	 *
5127	 * If there is an error, though, we don't want to keep processing.
5128	 * Instead, just send status back to the initiator.
5129	 */
5130	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5131	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5132	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5133	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5134		io->scsiio.io_cont(io);
5135		return;
5136	}
5137	/*
5138	 * Since a configuration write can be done for commands that actually
5139	 * have data allocated, like write buffer, and commands that have
5140	 * no data, like start/stop unit, we need to check here.
5141	 */
5142	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5143		buf = io->scsiio.kern_data_ptr;
5144	else
5145		buf = NULL;
5146	ctl_done(io);
5147	if (buf)
5148		free(buf, M_CTL);
5149}
5150
5151void
5152ctl_config_read_done(union ctl_io *io)
5153{
5154	uint8_t *buf;
5155
5156	/*
5157	 * If there is some error -- we are done, skip data transfer.
5158	 */
5159	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5160	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5161	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5162		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5163			buf = io->scsiio.kern_data_ptr;
5164		else
5165			buf = NULL;
5166		ctl_done(io);
5167		if (buf)
5168			free(buf, M_CTL);
5169		return;
5170	}
5171
5172	/*
5173	 * If the IO_CONT flag is set, we need to call the supplied
5174	 * function to continue processing the I/O, instead of completing
5175	 * the I/O just yet.
5176	 */
5177	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5178		io->scsiio.io_cont(io);
5179		return;
5180	}
5181
5182	ctl_datamove(io);
5183}
5184
5185/*
5186 * SCSI release command.
5187 */
5188int
5189ctl_scsi_release(struct ctl_scsiio *ctsio)
5190{
5191	int length, longid, thirdparty_id, resv_id;
5192	struct ctl_lun *lun;
5193	uint32_t residx;
5194
5195	length = 0;
5196	resv_id = 0;
5197
5198	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5199
5200	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5201	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5202
5203	switch (ctsio->cdb[0]) {
5204	case RELEASE_10: {
5205		struct scsi_release_10 *cdb;
5206
5207		cdb = (struct scsi_release_10 *)ctsio->cdb;
5208
5209		if (cdb->byte2 & SR10_LONGID)
5210			longid = 1;
5211		else
5212			thirdparty_id = cdb->thirdparty_id;
5213
5214		resv_id = cdb->resv_id;
5215		length = scsi_2btoul(cdb->length);
5216		break;
5217	}
5218	}
5219
5220
5221	/*
5222	 * XXX KDM right now, we only support LUN reservation.  We don't
5223	 * support 3rd party reservations, or extent reservations, which
5224	 * might actually need the parameter list.  If we've gotten this
5225	 * far, we've got a LUN reservation.  Anything else got kicked out
5226	 * above.  So, according to SPC, ignore the length.
5227	 */
5228	length = 0;
5229
5230	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5231	 && (length > 0)) {
5232		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5233		ctsio->kern_data_len = length;
5234		ctsio->kern_total_len = length;
5235		ctsio->kern_data_resid = 0;
5236		ctsio->kern_rel_offset = 0;
5237		ctsio->kern_sg_entries = 0;
5238		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5239		ctsio->be_move_done = ctl_config_move_done;
5240		ctl_datamove((union ctl_io *)ctsio);
5241
5242		return (CTL_RETVAL_COMPLETE);
5243	}
5244
5245	if (length > 0)
5246		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5247
5248	mtx_lock(&lun->lun_lock);
5249
5250	/*
5251	 * According to SPC, it is not an error for an intiator to attempt
5252	 * to release a reservation on a LUN that isn't reserved, or that
5253	 * is reserved by another initiator.  The reservation can only be
5254	 * released, though, by the initiator who made it or by one of
5255	 * several reset type events.
5256	 */
5257	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5258			lun->flags &= ~CTL_LUN_RESERVED;
5259
5260	mtx_unlock(&lun->lun_lock);
5261
5262	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5263		free(ctsio->kern_data_ptr, M_CTL);
5264		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5265	}
5266
5267	ctl_set_success(ctsio);
5268	ctl_done((union ctl_io *)ctsio);
5269	return (CTL_RETVAL_COMPLETE);
5270}
5271
5272int
5273ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5274{
5275	int extent, thirdparty, longid;
5276	int resv_id, length;
5277	uint64_t thirdparty_id;
5278	struct ctl_lun *lun;
5279	uint32_t residx;
5280
5281	extent = 0;
5282	thirdparty = 0;
5283	longid = 0;
5284	resv_id = 0;
5285	length = 0;
5286	thirdparty_id = 0;
5287
5288	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5289
5290	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5291	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5292
5293	switch (ctsio->cdb[0]) {
5294	case RESERVE_10: {
5295		struct scsi_reserve_10 *cdb;
5296
5297		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5298
5299		if (cdb->byte2 & SR10_LONGID)
5300			longid = 1;
5301		else
5302			thirdparty_id = cdb->thirdparty_id;
5303
5304		resv_id = cdb->resv_id;
5305		length = scsi_2btoul(cdb->length);
5306		break;
5307	}
5308	}
5309
5310	/*
5311	 * XXX KDM right now, we only support LUN reservation.  We don't
5312	 * support 3rd party reservations, or extent reservations, which
5313	 * might actually need the parameter list.  If we've gotten this
5314	 * far, we've got a LUN reservation.  Anything else got kicked out
5315	 * above.  So, according to SPC, ignore the length.
5316	 */
5317	length = 0;
5318
5319	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5320	 && (length > 0)) {
5321		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5322		ctsio->kern_data_len = length;
5323		ctsio->kern_total_len = length;
5324		ctsio->kern_data_resid = 0;
5325		ctsio->kern_rel_offset = 0;
5326		ctsio->kern_sg_entries = 0;
5327		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5328		ctsio->be_move_done = ctl_config_move_done;
5329		ctl_datamove((union ctl_io *)ctsio);
5330
5331		return (CTL_RETVAL_COMPLETE);
5332	}
5333
5334	if (length > 0)
5335		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5336
5337	mtx_lock(&lun->lun_lock);
5338	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5339		ctl_set_reservation_conflict(ctsio);
5340		goto bailout;
5341	}
5342
5343	lun->flags |= CTL_LUN_RESERVED;
5344	lun->res_idx = residx;
5345
5346	ctl_set_success(ctsio);
5347
5348bailout:
5349	mtx_unlock(&lun->lun_lock);
5350
5351	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5352		free(ctsio->kern_data_ptr, M_CTL);
5353		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5354	}
5355
5356	ctl_done((union ctl_io *)ctsio);
5357	return (CTL_RETVAL_COMPLETE);
5358}
5359
5360int
5361ctl_start_stop(struct ctl_scsiio *ctsio)
5362{
5363	struct scsi_start_stop_unit *cdb;
5364	struct ctl_lun *lun;
5365	int retval;
5366
5367	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5368
5369	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5370	retval = 0;
5371
5372	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5373
5374	/*
5375	 * XXX KDM
5376	 * We don't support the immediate bit on a stop unit.  In order to
5377	 * do that, we would need to code up a way to know that a stop is
5378	 * pending, and hold off any new commands until it completes, one
5379	 * way or another.  Then we could accept or reject those commands
5380	 * depending on its status.  We would almost need to do the reverse
5381	 * of what we do below for an immediate start -- return the copy of
5382	 * the ctl_io to the FETD with status to send to the host (and to
5383	 * free the copy!) and then free the original I/O once the stop
5384	 * actually completes.  That way, the OOA queue mechanism can work
5385	 * to block commands that shouldn't proceed.  Another alternative
5386	 * would be to put the copy in the queue in place of the original,
5387	 * and return the original back to the caller.  That could be
5388	 * slightly safer..
5389	 */
5390	if ((cdb->byte2 & SSS_IMMED)
5391	 && ((cdb->how & SSS_START) == 0)) {
5392		ctl_set_invalid_field(ctsio,
5393				      /*sks_valid*/ 1,
5394				      /*command*/ 1,
5395				      /*field*/ 1,
5396				      /*bit_valid*/ 1,
5397				      /*bit*/ 0);
5398		ctl_done((union ctl_io *)ctsio);
5399		return (CTL_RETVAL_COMPLETE);
5400	}
5401
5402	if ((lun->flags & CTL_LUN_PR_RESERVED)
5403	 && ((cdb->how & SSS_START)==0)) {
5404		uint32_t residx;
5405
5406		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5407		if (ctl_get_prkey(lun, residx) == 0
5408		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5409
5410			ctl_set_reservation_conflict(ctsio);
5411			ctl_done((union ctl_io *)ctsio);
5412			return (CTL_RETVAL_COMPLETE);
5413		}
5414	}
5415
5416	/*
5417	 * If there is no backend on this device, we can't start or stop
5418	 * it.  In theory we shouldn't get any start/stop commands in the
5419	 * first place at this level if the LUN doesn't have a backend.
5420	 * That should get stopped by the command decode code.
5421	 */
5422	if (lun->backend == NULL) {
5423		ctl_set_invalid_opcode(ctsio);
5424		ctl_done((union ctl_io *)ctsio);
5425		return (CTL_RETVAL_COMPLETE);
5426	}
5427
5428	/*
5429	 * XXX KDM Copan-specific offline behavior.
5430	 * Figure out a reasonable way to port this?
5431	 */
5432#ifdef NEEDTOPORT
5433	mtx_lock(&lun->lun_lock);
5434
5435	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5436	 && (lun->flags & CTL_LUN_OFFLINE)) {
5437		/*
5438		 * If the LUN is offline, and the on/offline bit isn't set,
5439		 * reject the start or stop.  Otherwise, let it through.
5440		 */
5441		mtx_unlock(&lun->lun_lock);
5442		ctl_set_lun_not_ready(ctsio);
5443		ctl_done((union ctl_io *)ctsio);
5444	} else {
5445		mtx_unlock(&lun->lun_lock);
5446#endif /* NEEDTOPORT */
5447		/*
5448		 * This could be a start or a stop when we're online,
5449		 * or a stop/offline or start/online.  A start or stop when
5450		 * we're offline is covered in the case above.
5451		 */
5452		/*
5453		 * In the non-immediate case, we send the request to
5454		 * the backend and return status to the user when
5455		 * it is done.
5456		 *
5457		 * In the immediate case, we allocate a new ctl_io
5458		 * to hold a copy of the request, and send that to
5459		 * the backend.  We then set good status on the
5460		 * user's request and return it immediately.
5461		 */
5462		if (cdb->byte2 & SSS_IMMED) {
5463			union ctl_io *new_io;
5464
5465			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5466			ctl_copy_io((union ctl_io *)ctsio, new_io);
5467			retval = lun->backend->config_write(new_io);
5468			ctl_set_success(ctsio);
5469			ctl_done((union ctl_io *)ctsio);
5470		} else {
5471			retval = lun->backend->config_write(
5472				(union ctl_io *)ctsio);
5473		}
5474#ifdef NEEDTOPORT
5475	}
5476#endif
5477	return (retval);
5478}
5479
5480/*
5481 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5482 * we don't really do anything with the LBA and length fields if the user
5483 * passes them in.  Instead we'll just flush out the cache for the entire
5484 * LUN.
5485 */
5486int
5487ctl_sync_cache(struct ctl_scsiio *ctsio)
5488{
5489	struct ctl_lun *lun;
5490	struct ctl_softc *softc;
5491	uint64_t starting_lba;
5492	uint32_t block_count;
5493	int retval;
5494
5495	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5496
5497	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5498	softc = lun->ctl_softc;
5499	retval = 0;
5500
5501	switch (ctsio->cdb[0]) {
5502	case SYNCHRONIZE_CACHE: {
5503		struct scsi_sync_cache *cdb;
5504		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5505
5506		starting_lba = scsi_4btoul(cdb->begin_lba);
5507		block_count = scsi_2btoul(cdb->lb_count);
5508		break;
5509	}
5510	case SYNCHRONIZE_CACHE_16: {
5511		struct scsi_sync_cache_16 *cdb;
5512		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5513
5514		starting_lba = scsi_8btou64(cdb->begin_lba);
5515		block_count = scsi_4btoul(cdb->lb_count);
5516		break;
5517	}
5518	default:
5519		ctl_set_invalid_opcode(ctsio);
5520		ctl_done((union ctl_io *)ctsio);
5521		goto bailout;
5522		break; /* NOTREACHED */
5523	}
5524
5525	/*
5526	 * We check the LBA and length, but don't do anything with them.
5527	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5528	 * get flushed.  This check will just help satisfy anyone who wants
5529	 * to see an error for an out of range LBA.
5530	 */
5531	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5532		ctl_set_lba_out_of_range(ctsio);
5533		ctl_done((union ctl_io *)ctsio);
5534		goto bailout;
5535	}
5536
5537	/*
5538	 * If this LUN has no backend, we can't flush the cache anyway.
5539	 */
5540	if (lun->backend == NULL) {
5541		ctl_set_invalid_opcode(ctsio);
5542		ctl_done((union ctl_io *)ctsio);
5543		goto bailout;
5544	}
5545
5546	/*
5547	 * Check to see whether we're configured to send the SYNCHRONIZE
5548	 * CACHE command directly to the back end.
5549	 */
5550	mtx_lock(&lun->lun_lock);
5551	if ((softc->flags & CTL_FLAG_REAL_SYNC)
5552	 && (++(lun->sync_count) >= lun->sync_interval)) {
5553		lun->sync_count = 0;
5554		mtx_unlock(&lun->lun_lock);
5555		retval = lun->backend->config_write((union ctl_io *)ctsio);
5556	} else {
5557		mtx_unlock(&lun->lun_lock);
5558		ctl_set_success(ctsio);
5559		ctl_done((union ctl_io *)ctsio);
5560	}
5561
5562bailout:
5563
5564	return (retval);
5565}
5566
5567int
5568ctl_format(struct ctl_scsiio *ctsio)
5569{
5570	struct scsi_format *cdb;
5571	struct ctl_lun *lun;
5572	int length, defect_list_len;
5573
5574	CTL_DEBUG_PRINT(("ctl_format\n"));
5575
5576	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5577
5578	cdb = (struct scsi_format *)ctsio->cdb;
5579
5580	length = 0;
5581	if (cdb->byte2 & SF_FMTDATA) {
5582		if (cdb->byte2 & SF_LONGLIST)
5583			length = sizeof(struct scsi_format_header_long);
5584		else
5585			length = sizeof(struct scsi_format_header_short);
5586	}
5587
5588	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5589	 && (length > 0)) {
5590		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5591		ctsio->kern_data_len = length;
5592		ctsio->kern_total_len = length;
5593		ctsio->kern_data_resid = 0;
5594		ctsio->kern_rel_offset = 0;
5595		ctsio->kern_sg_entries = 0;
5596		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5597		ctsio->be_move_done = ctl_config_move_done;
5598		ctl_datamove((union ctl_io *)ctsio);
5599
5600		return (CTL_RETVAL_COMPLETE);
5601	}
5602
5603	defect_list_len = 0;
5604
5605	if (cdb->byte2 & SF_FMTDATA) {
5606		if (cdb->byte2 & SF_LONGLIST) {
5607			struct scsi_format_header_long *header;
5608
5609			header = (struct scsi_format_header_long *)
5610				ctsio->kern_data_ptr;
5611
5612			defect_list_len = scsi_4btoul(header->defect_list_len);
5613			if (defect_list_len != 0) {
5614				ctl_set_invalid_field(ctsio,
5615						      /*sks_valid*/ 1,
5616						      /*command*/ 0,
5617						      /*field*/ 2,
5618						      /*bit_valid*/ 0,
5619						      /*bit*/ 0);
5620				goto bailout;
5621			}
5622		} else {
5623			struct scsi_format_header_short *header;
5624
5625			header = (struct scsi_format_header_short *)
5626				ctsio->kern_data_ptr;
5627
5628			defect_list_len = scsi_2btoul(header->defect_list_len);
5629			if (defect_list_len != 0) {
5630				ctl_set_invalid_field(ctsio,
5631						      /*sks_valid*/ 1,
5632						      /*command*/ 0,
5633						      /*field*/ 2,
5634						      /*bit_valid*/ 0,
5635						      /*bit*/ 0);
5636				goto bailout;
5637			}
5638		}
5639	}
5640
5641	/*
5642	 * The format command will clear out the "Medium format corrupted"
5643	 * status if set by the configuration code.  That status is really
5644	 * just a way to notify the host that we have lost the media, and
5645	 * get them to issue a command that will basically make them think
5646	 * they're blowing away the media.
5647	 */
5648	mtx_lock(&lun->lun_lock);
5649	lun->flags &= ~CTL_LUN_INOPERABLE;
5650	mtx_unlock(&lun->lun_lock);
5651
5652	ctl_set_success(ctsio);
5653bailout:
5654
5655	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5656		free(ctsio->kern_data_ptr, M_CTL);
5657		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5658	}
5659
5660	ctl_done((union ctl_io *)ctsio);
5661	return (CTL_RETVAL_COMPLETE);
5662}
5663
5664int
5665ctl_read_buffer(struct ctl_scsiio *ctsio)
5666{
5667	struct scsi_read_buffer *cdb;
5668	struct ctl_lun *lun;
5669	int buffer_offset, len;
5670	static uint8_t descr[4];
5671	static uint8_t echo_descr[4] = { 0 };
5672
5673	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5674
5675	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5676	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5677
5678	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5679	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5680	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5681		ctl_set_invalid_field(ctsio,
5682				      /*sks_valid*/ 1,
5683				      /*command*/ 1,
5684				      /*field*/ 1,
5685				      /*bit_valid*/ 1,
5686				      /*bit*/ 4);
5687		ctl_done((union ctl_io *)ctsio);
5688		return (CTL_RETVAL_COMPLETE);
5689	}
5690
5691	len = scsi_3btoul(cdb->length);
5692	buffer_offset = scsi_3btoul(cdb->offset);
5693
5694	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5695		ctl_set_invalid_field(ctsio,
5696				      /*sks_valid*/ 1,
5697				      /*command*/ 1,
5698				      /*field*/ 6,
5699				      /*bit_valid*/ 0,
5700				      /*bit*/ 0);
5701		ctl_done((union ctl_io *)ctsio);
5702		return (CTL_RETVAL_COMPLETE);
5703	}
5704
5705	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5706		descr[0] = 0;
5707		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5708		ctsio->kern_data_ptr = descr;
5709		len = min(len, sizeof(descr));
5710	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5711		ctsio->kern_data_ptr = echo_descr;
5712		len = min(len, sizeof(echo_descr));
5713	} else {
5714		if (lun->write_buffer == NULL) {
5715			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5716			    M_CTL, M_WAITOK);
5717		}
5718		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5719	}
5720	ctsio->kern_data_len = len;
5721	ctsio->kern_total_len = len;
5722	ctsio->kern_data_resid = 0;
5723	ctsio->kern_rel_offset = 0;
5724	ctsio->kern_sg_entries = 0;
5725	ctl_set_success(ctsio);
5726	ctsio->be_move_done = ctl_config_move_done;
5727	ctl_datamove((union ctl_io *)ctsio);
5728	return (CTL_RETVAL_COMPLETE);
5729}
5730
5731int
5732ctl_write_buffer(struct ctl_scsiio *ctsio)
5733{
5734	struct scsi_write_buffer *cdb;
5735	struct ctl_lun *lun;
5736	int buffer_offset, len;
5737
5738	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5739
5740	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5741	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5742
5743	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5744		ctl_set_invalid_field(ctsio,
5745				      /*sks_valid*/ 1,
5746				      /*command*/ 1,
5747				      /*field*/ 1,
5748				      /*bit_valid*/ 1,
5749				      /*bit*/ 4);
5750		ctl_done((union ctl_io *)ctsio);
5751		return (CTL_RETVAL_COMPLETE);
5752	}
5753
5754	len = scsi_3btoul(cdb->length);
5755	buffer_offset = scsi_3btoul(cdb->offset);
5756
5757	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5758		ctl_set_invalid_field(ctsio,
5759				      /*sks_valid*/ 1,
5760				      /*command*/ 1,
5761				      /*field*/ 6,
5762				      /*bit_valid*/ 0,
5763				      /*bit*/ 0);
5764		ctl_done((union ctl_io *)ctsio);
5765		return (CTL_RETVAL_COMPLETE);
5766	}
5767
5768	/*
5769	 * If we've got a kernel request that hasn't been malloced yet,
5770	 * malloc it and tell the caller the data buffer is here.
5771	 */
5772	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5773		if (lun->write_buffer == NULL) {
5774			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5775			    M_CTL, M_WAITOK);
5776		}
5777		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5778		ctsio->kern_data_len = len;
5779		ctsio->kern_total_len = len;
5780		ctsio->kern_data_resid = 0;
5781		ctsio->kern_rel_offset = 0;
5782		ctsio->kern_sg_entries = 0;
5783		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5784		ctsio->be_move_done = ctl_config_move_done;
5785		ctl_datamove((union ctl_io *)ctsio);
5786
5787		return (CTL_RETVAL_COMPLETE);
5788	}
5789
5790	ctl_set_success(ctsio);
5791	ctl_done((union ctl_io *)ctsio);
5792	return (CTL_RETVAL_COMPLETE);
5793}
5794
5795int
5796ctl_write_same(struct ctl_scsiio *ctsio)
5797{
5798	struct ctl_lun *lun;
5799	struct ctl_lba_len_flags *lbalen;
5800	uint64_t lba;
5801	uint32_t num_blocks;
5802	int len, retval;
5803	uint8_t byte2;
5804
5805	retval = CTL_RETVAL_COMPLETE;
5806
5807	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5808
5809	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5810
5811	switch (ctsio->cdb[0]) {
5812	case WRITE_SAME_10: {
5813		struct scsi_write_same_10 *cdb;
5814
5815		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5816
5817		lba = scsi_4btoul(cdb->addr);
5818		num_blocks = scsi_2btoul(cdb->length);
5819		byte2 = cdb->byte2;
5820		break;
5821	}
5822	case WRITE_SAME_16: {
5823		struct scsi_write_same_16 *cdb;
5824
5825		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5826
5827		lba = scsi_8btou64(cdb->addr);
5828		num_blocks = scsi_4btoul(cdb->length);
5829		byte2 = cdb->byte2;
5830		break;
5831	}
5832	default:
5833		/*
5834		 * We got a command we don't support.  This shouldn't
5835		 * happen, commands should be filtered out above us.
5836		 */
5837		ctl_set_invalid_opcode(ctsio);
5838		ctl_done((union ctl_io *)ctsio);
5839
5840		return (CTL_RETVAL_COMPLETE);
5841		break; /* NOTREACHED */
5842	}
5843
5844	/* NDOB and ANCHOR flags can be used only together with UNMAP */
5845	if ((byte2 & SWS_UNMAP) == 0 &&
5846	    (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5847		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5848		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5849		ctl_done((union ctl_io *)ctsio);
5850		return (CTL_RETVAL_COMPLETE);
5851	}
5852
5853	/*
5854	 * The first check is to make sure we're in bounds, the second
5855	 * check is to catch wrap-around problems.  If the lba + num blocks
5856	 * is less than the lba, then we've wrapped around and the block
5857	 * range is invalid anyway.
5858	 */
5859	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5860	 || ((lba + num_blocks) < lba)) {
5861		ctl_set_lba_out_of_range(ctsio);
5862		ctl_done((union ctl_io *)ctsio);
5863		return (CTL_RETVAL_COMPLETE);
5864	}
5865
5866	/* Zero number of blocks means "to the last logical block" */
5867	if (num_blocks == 0) {
5868		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5869			ctl_set_invalid_field(ctsio,
5870					      /*sks_valid*/ 0,
5871					      /*command*/ 1,
5872					      /*field*/ 0,
5873					      /*bit_valid*/ 0,
5874					      /*bit*/ 0);
5875			ctl_done((union ctl_io *)ctsio);
5876			return (CTL_RETVAL_COMPLETE);
5877		}
5878		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5879	}
5880
5881	len = lun->be_lun->blocksize;
5882
5883	/*
5884	 * If we've got a kernel request that hasn't been malloced yet,
5885	 * malloc it and tell the caller the data buffer is here.
5886	 */
5887	if ((byte2 & SWS_NDOB) == 0 &&
5888	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5889		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5890		ctsio->kern_data_len = len;
5891		ctsio->kern_total_len = len;
5892		ctsio->kern_data_resid = 0;
5893		ctsio->kern_rel_offset = 0;
5894		ctsio->kern_sg_entries = 0;
5895		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5896		ctsio->be_move_done = ctl_config_move_done;
5897		ctl_datamove((union ctl_io *)ctsio);
5898
5899		return (CTL_RETVAL_COMPLETE);
5900	}
5901
5902	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5903	lbalen->lba = lba;
5904	lbalen->len = num_blocks;
5905	lbalen->flags = byte2;
5906	retval = lun->backend->config_write((union ctl_io *)ctsio);
5907
5908	return (retval);
5909}
5910
5911int
5912ctl_unmap(struct ctl_scsiio *ctsio)
5913{
5914	struct ctl_lun *lun;
5915	struct scsi_unmap *cdb;
5916	struct ctl_ptr_len_flags *ptrlen;
5917	struct scsi_unmap_header *hdr;
5918	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5919	uint64_t lba;
5920	uint32_t num_blocks;
5921	int len, retval;
5922	uint8_t byte2;
5923
5924	retval = CTL_RETVAL_COMPLETE;
5925
5926	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5927
5928	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5929	cdb = (struct scsi_unmap *)ctsio->cdb;
5930
5931	len = scsi_2btoul(cdb->length);
5932	byte2 = cdb->byte2;
5933
5934	/*
5935	 * If we've got a kernel request that hasn't been malloced yet,
5936	 * malloc it and tell the caller the data buffer is here.
5937	 */
5938	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5939		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5940		ctsio->kern_data_len = len;
5941		ctsio->kern_total_len = len;
5942		ctsio->kern_data_resid = 0;
5943		ctsio->kern_rel_offset = 0;
5944		ctsio->kern_sg_entries = 0;
5945		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5946		ctsio->be_move_done = ctl_config_move_done;
5947		ctl_datamove((union ctl_io *)ctsio);
5948
5949		return (CTL_RETVAL_COMPLETE);
5950	}
5951
5952	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5953	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5954	if (len < sizeof (*hdr) ||
5955	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5956	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5957	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5958		ctl_set_invalid_field(ctsio,
5959				      /*sks_valid*/ 0,
5960				      /*command*/ 0,
5961				      /*field*/ 0,
5962				      /*bit_valid*/ 0,
5963				      /*bit*/ 0);
5964		goto done;
5965	}
5966	len = scsi_2btoul(hdr->desc_length);
5967	buf = (struct scsi_unmap_desc *)(hdr + 1);
5968	end = buf + len / sizeof(*buf);
5969
5970	endnz = buf;
5971	for (range = buf; range < end; range++) {
5972		lba = scsi_8btou64(range->lba);
5973		num_blocks = scsi_4btoul(range->length);
5974		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5975		 || ((lba + num_blocks) < lba)) {
5976			ctl_set_lba_out_of_range(ctsio);
5977			ctl_done((union ctl_io *)ctsio);
5978			return (CTL_RETVAL_COMPLETE);
5979		}
5980		if (num_blocks != 0)
5981			endnz = range + 1;
5982	}
5983
5984	/*
5985	 * Block backend can not handle zero last range.
5986	 * Filter it out and return if there is nothing left.
5987	 */
5988	len = (uint8_t *)endnz - (uint8_t *)buf;
5989	if (len == 0) {
5990		ctl_set_success(ctsio);
5991		goto done;
5992	}
5993
5994	mtx_lock(&lun->lun_lock);
5995	ptrlen = (struct ctl_ptr_len_flags *)
5996	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5997	ptrlen->ptr = (void *)buf;
5998	ptrlen->len = len;
5999	ptrlen->flags = byte2;
6000	ctl_check_blocked(lun);
6001	mtx_unlock(&lun->lun_lock);
6002
6003	retval = lun->backend->config_write((union ctl_io *)ctsio);
6004	return (retval);
6005
6006done:
6007	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
6008		free(ctsio->kern_data_ptr, M_CTL);
6009		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
6010	}
6011	ctl_done((union ctl_io *)ctsio);
6012	return (CTL_RETVAL_COMPLETE);
6013}
6014
6015/*
6016 * Note that this function currently doesn't actually do anything inside
6017 * CTL to enforce things if the DQue bit is turned on.
6018 *
6019 * Also note that this function can't be used in the default case, because
6020 * the DQue bit isn't set in the changeable mask for the control mode page
6021 * anyway.  This is just here as an example for how to implement a page
6022 * handler, and a placeholder in case we want to allow the user to turn
6023 * tagged queueing on and off.
6024 *
6025 * The D_SENSE bit handling is functional, however, and will turn
6026 * descriptor sense on and off for a given LUN.
6027 */
6028int
6029ctl_control_page_handler(struct ctl_scsiio *ctsio,
6030			 struct ctl_page_index *page_index, uint8_t *page_ptr)
6031{
6032	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6033	struct ctl_lun *lun;
6034	int set_ua;
6035	uint32_t initidx;
6036
6037	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6038	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6039	set_ua = 0;
6040
6041	user_cp = (struct scsi_control_page *)page_ptr;
6042	current_cp = (struct scsi_control_page *)
6043		(page_index->page_data + (page_index->page_len *
6044		CTL_PAGE_CURRENT));
6045	saved_cp = (struct scsi_control_page *)
6046		(page_index->page_data + (page_index->page_len *
6047		CTL_PAGE_SAVED));
6048
6049	mtx_lock(&lun->lun_lock);
6050	if (((current_cp->rlec & SCP_DSENSE) == 0)
6051	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6052		/*
6053		 * Descriptor sense is currently turned off and the user
6054		 * wants to turn it on.
6055		 */
6056		current_cp->rlec |= SCP_DSENSE;
6057		saved_cp->rlec |= SCP_DSENSE;
6058		lun->flags |= CTL_LUN_SENSE_DESC;
6059		set_ua = 1;
6060	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6061		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6062		/*
6063		 * Descriptor sense is currently turned on, and the user
6064		 * wants to turn it off.
6065		 */
6066		current_cp->rlec &= ~SCP_DSENSE;
6067		saved_cp->rlec &= ~SCP_DSENSE;
6068		lun->flags &= ~CTL_LUN_SENSE_DESC;
6069		set_ua = 1;
6070	}
6071	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6072	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6073		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6074		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6075		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6076		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6077		set_ua = 1;
6078	}
6079	if ((current_cp->eca_and_aen & SCP_SWP) !=
6080	    (user_cp->eca_and_aen & SCP_SWP)) {
6081		current_cp->eca_and_aen &= ~SCP_SWP;
6082		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6083		saved_cp->eca_and_aen &= ~SCP_SWP;
6084		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6085		set_ua = 1;
6086	}
6087	if (set_ua != 0)
6088		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6089	mtx_unlock(&lun->lun_lock);
6090
6091	return (0);
6092}
6093
6094int
6095ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6096		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6097{
6098	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6099	struct ctl_lun *lun;
6100	int set_ua;
6101	uint32_t initidx;
6102
6103	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6104	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6105	set_ua = 0;
6106
6107	user_cp = (struct scsi_caching_page *)page_ptr;
6108	current_cp = (struct scsi_caching_page *)
6109		(page_index->page_data + (page_index->page_len *
6110		CTL_PAGE_CURRENT));
6111	saved_cp = (struct scsi_caching_page *)
6112		(page_index->page_data + (page_index->page_len *
6113		CTL_PAGE_SAVED));
6114
6115	mtx_lock(&lun->lun_lock);
6116	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6117	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6118		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6119		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6120		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6121		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6122		set_ua = 1;
6123	}
6124	if (set_ua != 0)
6125		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6126	mtx_unlock(&lun->lun_lock);
6127
6128	return (0);
6129}
6130
6131int
6132ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6133				struct ctl_page_index *page_index,
6134				uint8_t *page_ptr)
6135{
6136	uint8_t *c;
6137	int i;
6138
6139	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6140	ctl_time_io_secs =
6141		(c[0] << 8) |
6142		(c[1] << 0) |
6143		0;
6144	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6145	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6146	printf("page data:");
6147	for (i=0; i<8; i++)
6148		printf(" %.2x",page_ptr[i]);
6149	printf("\n");
6150	return (0);
6151}
6152
6153int
6154ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6155			       struct ctl_page_index *page_index,
6156			       int pc)
6157{
6158	struct copan_debugconf_subpage *page;
6159
6160	page = (struct copan_debugconf_subpage *)page_index->page_data +
6161		(page_index->page_len * pc);
6162
6163	switch (pc) {
6164	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6165	case SMS_PAGE_CTRL_DEFAULT >> 6:
6166	case SMS_PAGE_CTRL_SAVED >> 6:
6167		/*
6168		 * We don't update the changable or default bits for this page.
6169		 */
6170		break;
6171	case SMS_PAGE_CTRL_CURRENT >> 6:
6172		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6173		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6174		break;
6175	default:
6176#ifdef NEEDTOPORT
6177		EPRINT(0, "Invalid PC %d!!", pc);
6178#endif /* NEEDTOPORT */
6179		break;
6180	}
6181	return (0);
6182}
6183
6184
6185static int
6186ctl_do_mode_select(union ctl_io *io)
6187{
6188	struct scsi_mode_page_header *page_header;
6189	struct ctl_page_index *page_index;
6190	struct ctl_scsiio *ctsio;
6191	int control_dev, page_len;
6192	int page_len_offset, page_len_size;
6193	union ctl_modepage_info *modepage_info;
6194	struct ctl_lun *lun;
6195	int *len_left, *len_used;
6196	int retval, i;
6197
6198	ctsio = &io->scsiio;
6199	page_index = NULL;
6200	page_len = 0;
6201	retval = CTL_RETVAL_COMPLETE;
6202
6203	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6204
6205	if (lun->be_lun->lun_type != T_DIRECT)
6206		control_dev = 1;
6207	else
6208		control_dev = 0;
6209
6210	modepage_info = (union ctl_modepage_info *)
6211		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6212	len_left = &modepage_info->header.len_left;
6213	len_used = &modepage_info->header.len_used;
6214
6215do_next_page:
6216
6217	page_header = (struct scsi_mode_page_header *)
6218		(ctsio->kern_data_ptr + *len_used);
6219
6220	if (*len_left == 0) {
6221		free(ctsio->kern_data_ptr, M_CTL);
6222		ctl_set_success(ctsio);
6223		ctl_done((union ctl_io *)ctsio);
6224		return (CTL_RETVAL_COMPLETE);
6225	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6226
6227		free(ctsio->kern_data_ptr, M_CTL);
6228		ctl_set_param_len_error(ctsio);
6229		ctl_done((union ctl_io *)ctsio);
6230		return (CTL_RETVAL_COMPLETE);
6231
6232	} else if ((page_header->page_code & SMPH_SPF)
6233		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6234
6235		free(ctsio->kern_data_ptr, M_CTL);
6236		ctl_set_param_len_error(ctsio);
6237		ctl_done((union ctl_io *)ctsio);
6238		return (CTL_RETVAL_COMPLETE);
6239	}
6240
6241
6242	/*
6243	 * XXX KDM should we do something with the block descriptor?
6244	 */
6245	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6246
6247		if ((control_dev != 0)
6248		 && (lun->mode_pages.index[i].page_flags &
6249		     CTL_PAGE_FLAG_DISK_ONLY))
6250			continue;
6251
6252		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6253		    (page_header->page_code & SMPH_PC_MASK))
6254			continue;
6255
6256		/*
6257		 * If neither page has a subpage code, then we've got a
6258		 * match.
6259		 */
6260		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6261		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6262			page_index = &lun->mode_pages.index[i];
6263			page_len = page_header->page_length;
6264			break;
6265		}
6266
6267		/*
6268		 * If both pages have subpages, then the subpage numbers
6269		 * have to match.
6270		 */
6271		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6272		  && (page_header->page_code & SMPH_SPF)) {
6273			struct scsi_mode_page_header_sp *sph;
6274
6275			sph = (struct scsi_mode_page_header_sp *)page_header;
6276
6277			if (lun->mode_pages.index[i].subpage ==
6278			    sph->subpage) {
6279				page_index = &lun->mode_pages.index[i];
6280				page_len = scsi_2btoul(sph->page_length);
6281				break;
6282			}
6283		}
6284	}
6285
6286	/*
6287	 * If we couldn't find the page, or if we don't have a mode select
6288	 * handler for it, send back an error to the user.
6289	 */
6290	if ((page_index == NULL)
6291	 || (page_index->select_handler == NULL)) {
6292		ctl_set_invalid_field(ctsio,
6293				      /*sks_valid*/ 1,
6294				      /*command*/ 0,
6295				      /*field*/ *len_used,
6296				      /*bit_valid*/ 0,
6297				      /*bit*/ 0);
6298		free(ctsio->kern_data_ptr, M_CTL);
6299		ctl_done((union ctl_io *)ctsio);
6300		return (CTL_RETVAL_COMPLETE);
6301	}
6302
6303	if (page_index->page_code & SMPH_SPF) {
6304		page_len_offset = 2;
6305		page_len_size = 2;
6306	} else {
6307		page_len_size = 1;
6308		page_len_offset = 1;
6309	}
6310
6311	/*
6312	 * If the length the initiator gives us isn't the one we specify in
6313	 * the mode page header, or if they didn't specify enough data in
6314	 * the CDB to avoid truncating this page, kick out the request.
6315	 */
6316	if ((page_len != (page_index->page_len - page_len_offset -
6317			  page_len_size))
6318	 || (*len_left < page_index->page_len)) {
6319
6320
6321		ctl_set_invalid_field(ctsio,
6322				      /*sks_valid*/ 1,
6323				      /*command*/ 0,
6324				      /*field*/ *len_used + page_len_offset,
6325				      /*bit_valid*/ 0,
6326				      /*bit*/ 0);
6327		free(ctsio->kern_data_ptr, M_CTL);
6328		ctl_done((union ctl_io *)ctsio);
6329		return (CTL_RETVAL_COMPLETE);
6330	}
6331
6332	/*
6333	 * Run through the mode page, checking to make sure that the bits
6334	 * the user changed are actually legal for him to change.
6335	 */
6336	for (i = 0; i < page_index->page_len; i++) {
6337		uint8_t *user_byte, *change_mask, *current_byte;
6338		int bad_bit;
6339		int j;
6340
6341		user_byte = (uint8_t *)page_header + i;
6342		change_mask = page_index->page_data +
6343			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6344		current_byte = page_index->page_data +
6345			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6346
6347		/*
6348		 * Check to see whether the user set any bits in this byte
6349		 * that he is not allowed to set.
6350		 */
6351		if ((*user_byte & ~(*change_mask)) ==
6352		    (*current_byte & ~(*change_mask)))
6353			continue;
6354
6355		/*
6356		 * Go through bit by bit to determine which one is illegal.
6357		 */
6358		bad_bit = 0;
6359		for (j = 7; j >= 0; j--) {
6360			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6361			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6362				bad_bit = i;
6363				break;
6364			}
6365		}
6366		ctl_set_invalid_field(ctsio,
6367				      /*sks_valid*/ 1,
6368				      /*command*/ 0,
6369				      /*field*/ *len_used + i,
6370				      /*bit_valid*/ 1,
6371				      /*bit*/ bad_bit);
6372		free(ctsio->kern_data_ptr, M_CTL);
6373		ctl_done((union ctl_io *)ctsio);
6374		return (CTL_RETVAL_COMPLETE);
6375	}
6376
6377	/*
6378	 * Decrement these before we call the page handler, since we may
6379	 * end up getting called back one way or another before the handler
6380	 * returns to this context.
6381	 */
6382	*len_left -= page_index->page_len;
6383	*len_used += page_index->page_len;
6384
6385	retval = page_index->select_handler(ctsio, page_index,
6386					    (uint8_t *)page_header);
6387
6388	/*
6389	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6390	 * wait until this queued command completes to finish processing
6391	 * the mode page.  If it returns anything other than
6392	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6393	 * already set the sense information, freed the data pointer, and
6394	 * completed the io for us.
6395	 */
6396	if (retval != CTL_RETVAL_COMPLETE)
6397		goto bailout_no_done;
6398
6399	/*
6400	 * If the initiator sent us more than one page, parse the next one.
6401	 */
6402	if (*len_left > 0)
6403		goto do_next_page;
6404
6405	ctl_set_success(ctsio);
6406	free(ctsio->kern_data_ptr, M_CTL);
6407	ctl_done((union ctl_io *)ctsio);
6408
6409bailout_no_done:
6410
6411	return (CTL_RETVAL_COMPLETE);
6412
6413}
6414
6415int
6416ctl_mode_select(struct ctl_scsiio *ctsio)
6417{
6418	int param_len, pf, sp;
6419	int header_size, bd_len;
6420	int len_left, len_used;
6421	struct ctl_page_index *page_index;
6422	struct ctl_lun *lun;
6423	int control_dev, page_len;
6424	union ctl_modepage_info *modepage_info;
6425	int retval;
6426
6427	pf = 0;
6428	sp = 0;
6429	page_len = 0;
6430	len_used = 0;
6431	len_left = 0;
6432	retval = 0;
6433	bd_len = 0;
6434	page_index = NULL;
6435
6436	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6437
6438	if (lun->be_lun->lun_type != T_DIRECT)
6439		control_dev = 1;
6440	else
6441		control_dev = 0;
6442
6443	switch (ctsio->cdb[0]) {
6444	case MODE_SELECT_6: {
6445		struct scsi_mode_select_6 *cdb;
6446
6447		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6448
6449		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6450		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6451
6452		param_len = cdb->length;
6453		header_size = sizeof(struct scsi_mode_header_6);
6454		break;
6455	}
6456	case MODE_SELECT_10: {
6457		struct scsi_mode_select_10 *cdb;
6458
6459		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6460
6461		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6462		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6463
6464		param_len = scsi_2btoul(cdb->length);
6465		header_size = sizeof(struct scsi_mode_header_10);
6466		break;
6467	}
6468	default:
6469		ctl_set_invalid_opcode(ctsio);
6470		ctl_done((union ctl_io *)ctsio);
6471		return (CTL_RETVAL_COMPLETE);
6472		break; /* NOTREACHED */
6473	}
6474
6475	/*
6476	 * From SPC-3:
6477	 * "A parameter list length of zero indicates that the Data-Out Buffer
6478	 * shall be empty. This condition shall not be considered as an error."
6479	 */
6480	if (param_len == 0) {
6481		ctl_set_success(ctsio);
6482		ctl_done((union ctl_io *)ctsio);
6483		return (CTL_RETVAL_COMPLETE);
6484	}
6485
6486	/*
6487	 * Since we'll hit this the first time through, prior to
6488	 * allocation, we don't need to free a data buffer here.
6489	 */
6490	if (param_len < header_size) {
6491		ctl_set_param_len_error(ctsio);
6492		ctl_done((union ctl_io *)ctsio);
6493		return (CTL_RETVAL_COMPLETE);
6494	}
6495
6496	/*
6497	 * Allocate the data buffer and grab the user's data.  In theory,
6498	 * we shouldn't have to sanity check the parameter list length here
6499	 * because the maximum size is 64K.  We should be able to malloc
6500	 * that much without too many problems.
6501	 */
6502	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6503		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6504		ctsio->kern_data_len = param_len;
6505		ctsio->kern_total_len = param_len;
6506		ctsio->kern_data_resid = 0;
6507		ctsio->kern_rel_offset = 0;
6508		ctsio->kern_sg_entries = 0;
6509		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6510		ctsio->be_move_done = ctl_config_move_done;
6511		ctl_datamove((union ctl_io *)ctsio);
6512
6513		return (CTL_RETVAL_COMPLETE);
6514	}
6515
6516	switch (ctsio->cdb[0]) {
6517	case MODE_SELECT_6: {
6518		struct scsi_mode_header_6 *mh6;
6519
6520		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6521		bd_len = mh6->blk_desc_len;
6522		break;
6523	}
6524	case MODE_SELECT_10: {
6525		struct scsi_mode_header_10 *mh10;
6526
6527		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6528		bd_len = scsi_2btoul(mh10->blk_desc_len);
6529		break;
6530	}
6531	default:
6532		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6533		break;
6534	}
6535
6536	if (param_len < (header_size + bd_len)) {
6537		free(ctsio->kern_data_ptr, M_CTL);
6538		ctl_set_param_len_error(ctsio);
6539		ctl_done((union ctl_io *)ctsio);
6540		return (CTL_RETVAL_COMPLETE);
6541	}
6542
6543	/*
6544	 * Set the IO_CONT flag, so that if this I/O gets passed to
6545	 * ctl_config_write_done(), it'll get passed back to
6546	 * ctl_do_mode_select() for further processing, or completion if
6547	 * we're all done.
6548	 */
6549	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6550	ctsio->io_cont = ctl_do_mode_select;
6551
6552	modepage_info = (union ctl_modepage_info *)
6553		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6554
6555	memset(modepage_info, 0, sizeof(*modepage_info));
6556
6557	len_left = param_len - header_size - bd_len;
6558	len_used = header_size + bd_len;
6559
6560	modepage_info->header.len_left = len_left;
6561	modepage_info->header.len_used = len_used;
6562
6563	return (ctl_do_mode_select((union ctl_io *)ctsio));
6564}
6565
6566int
6567ctl_mode_sense(struct ctl_scsiio *ctsio)
6568{
6569	struct ctl_lun *lun;
6570	int pc, page_code, dbd, llba, subpage;
6571	int alloc_len, page_len, header_len, total_len;
6572	struct scsi_mode_block_descr *block_desc;
6573	struct ctl_page_index *page_index;
6574	int control_dev;
6575
6576	dbd = 0;
6577	llba = 0;
6578	block_desc = NULL;
6579	page_index = NULL;
6580
6581	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6582
6583	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6584
6585	if (lun->be_lun->lun_type != T_DIRECT)
6586		control_dev = 1;
6587	else
6588		control_dev = 0;
6589
6590	switch (ctsio->cdb[0]) {
6591	case MODE_SENSE_6: {
6592		struct scsi_mode_sense_6 *cdb;
6593
6594		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6595
6596		header_len = sizeof(struct scsi_mode_hdr_6);
6597		if (cdb->byte2 & SMS_DBD)
6598			dbd = 1;
6599		else
6600			header_len += sizeof(struct scsi_mode_block_descr);
6601
6602		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6603		page_code = cdb->page & SMS_PAGE_CODE;
6604		subpage = cdb->subpage;
6605		alloc_len = cdb->length;
6606		break;
6607	}
6608	case MODE_SENSE_10: {
6609		struct scsi_mode_sense_10 *cdb;
6610
6611		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6612
6613		header_len = sizeof(struct scsi_mode_hdr_10);
6614
6615		if (cdb->byte2 & SMS_DBD)
6616			dbd = 1;
6617		else
6618			header_len += sizeof(struct scsi_mode_block_descr);
6619		if (cdb->byte2 & SMS10_LLBAA)
6620			llba = 1;
6621		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6622		page_code = cdb->page & SMS_PAGE_CODE;
6623		subpage = cdb->subpage;
6624		alloc_len = scsi_2btoul(cdb->length);
6625		break;
6626	}
6627	default:
6628		ctl_set_invalid_opcode(ctsio);
6629		ctl_done((union ctl_io *)ctsio);
6630		return (CTL_RETVAL_COMPLETE);
6631		break; /* NOTREACHED */
6632	}
6633
6634	/*
6635	 * We have to make a first pass through to calculate the size of
6636	 * the pages that match the user's query.  Then we allocate enough
6637	 * memory to hold it, and actually copy the data into the buffer.
6638	 */
6639	switch (page_code) {
6640	case SMS_ALL_PAGES_PAGE: {
6641		int i;
6642
6643		page_len = 0;
6644
6645		/*
6646		 * At the moment, values other than 0 and 0xff here are
6647		 * reserved according to SPC-3.
6648		 */
6649		if ((subpage != SMS_SUBPAGE_PAGE_0)
6650		 && (subpage != SMS_SUBPAGE_ALL)) {
6651			ctl_set_invalid_field(ctsio,
6652					      /*sks_valid*/ 1,
6653					      /*command*/ 1,
6654					      /*field*/ 3,
6655					      /*bit_valid*/ 0,
6656					      /*bit*/ 0);
6657			ctl_done((union ctl_io *)ctsio);
6658			return (CTL_RETVAL_COMPLETE);
6659		}
6660
6661		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6662			if ((control_dev != 0)
6663			 && (lun->mode_pages.index[i].page_flags &
6664			     CTL_PAGE_FLAG_DISK_ONLY))
6665				continue;
6666
6667			/*
6668			 * We don't use this subpage if the user didn't
6669			 * request all subpages.
6670			 */
6671			if ((lun->mode_pages.index[i].subpage != 0)
6672			 && (subpage == SMS_SUBPAGE_PAGE_0))
6673				continue;
6674
6675#if 0
6676			printf("found page %#x len %d\n",
6677			       lun->mode_pages.index[i].page_code &
6678			       SMPH_PC_MASK,
6679			       lun->mode_pages.index[i].page_len);
6680#endif
6681			page_len += lun->mode_pages.index[i].page_len;
6682		}
6683		break;
6684	}
6685	default: {
6686		int i;
6687
6688		page_len = 0;
6689
6690		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6691			/* Look for the right page code */
6692			if ((lun->mode_pages.index[i].page_code &
6693			     SMPH_PC_MASK) != page_code)
6694				continue;
6695
6696			/* Look for the right subpage or the subpage wildcard*/
6697			if ((lun->mode_pages.index[i].subpage != subpage)
6698			 && (subpage != SMS_SUBPAGE_ALL))
6699				continue;
6700
6701			/* Make sure the page is supported for this dev type */
6702			if ((control_dev != 0)
6703			 && (lun->mode_pages.index[i].page_flags &
6704			     CTL_PAGE_FLAG_DISK_ONLY))
6705				continue;
6706
6707#if 0
6708			printf("found page %#x len %d\n",
6709			       lun->mode_pages.index[i].page_code &
6710			       SMPH_PC_MASK,
6711			       lun->mode_pages.index[i].page_len);
6712#endif
6713
6714			page_len += lun->mode_pages.index[i].page_len;
6715		}
6716
6717		if (page_len == 0) {
6718			ctl_set_invalid_field(ctsio,
6719					      /*sks_valid*/ 1,
6720					      /*command*/ 1,
6721					      /*field*/ 2,
6722					      /*bit_valid*/ 1,
6723					      /*bit*/ 5);
6724			ctl_done((union ctl_io *)ctsio);
6725			return (CTL_RETVAL_COMPLETE);
6726		}
6727		break;
6728	}
6729	}
6730
6731	total_len = header_len + page_len;
6732#if 0
6733	printf("header_len = %d, page_len = %d, total_len = %d\n",
6734	       header_len, page_len, total_len);
6735#endif
6736
6737	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6738	ctsio->kern_sg_entries = 0;
6739	ctsio->kern_data_resid = 0;
6740	ctsio->kern_rel_offset = 0;
6741	if (total_len < alloc_len) {
6742		ctsio->residual = alloc_len - total_len;
6743		ctsio->kern_data_len = total_len;
6744		ctsio->kern_total_len = total_len;
6745	} else {
6746		ctsio->residual = 0;
6747		ctsio->kern_data_len = alloc_len;
6748		ctsio->kern_total_len = alloc_len;
6749	}
6750
6751	switch (ctsio->cdb[0]) {
6752	case MODE_SENSE_6: {
6753		struct scsi_mode_hdr_6 *header;
6754
6755		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6756
6757		header->datalen = MIN(total_len - 1, 254);
6758		if (control_dev == 0) {
6759			header->dev_specific = 0x10; /* DPOFUA */
6760			if ((lun->flags & CTL_LUN_READONLY) ||
6761			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6762			    .eca_and_aen & SCP_SWP) != 0)
6763				    header->dev_specific |= 0x80; /* WP */
6764		}
6765		if (dbd)
6766			header->block_descr_len = 0;
6767		else
6768			header->block_descr_len =
6769				sizeof(struct scsi_mode_block_descr);
6770		block_desc = (struct scsi_mode_block_descr *)&header[1];
6771		break;
6772	}
6773	case MODE_SENSE_10: {
6774		struct scsi_mode_hdr_10 *header;
6775		int datalen;
6776
6777		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6778
6779		datalen = MIN(total_len - 2, 65533);
6780		scsi_ulto2b(datalen, header->datalen);
6781		if (control_dev == 0) {
6782			header->dev_specific = 0x10; /* DPOFUA */
6783			if ((lun->flags & CTL_LUN_READONLY) ||
6784			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6785			    .eca_and_aen & SCP_SWP) != 0)
6786				    header->dev_specific |= 0x80; /* WP */
6787		}
6788		if (dbd)
6789			scsi_ulto2b(0, header->block_descr_len);
6790		else
6791			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6792				    header->block_descr_len);
6793		block_desc = (struct scsi_mode_block_descr *)&header[1];
6794		break;
6795	}
6796	default:
6797		panic("invalid CDB type %#x", ctsio->cdb[0]);
6798		break; /* NOTREACHED */
6799	}
6800
6801	/*
6802	 * If we've got a disk, use its blocksize in the block
6803	 * descriptor.  Otherwise, just set it to 0.
6804	 */
6805	if (dbd == 0) {
6806		if (control_dev == 0)
6807			scsi_ulto3b(lun->be_lun->blocksize,
6808				    block_desc->block_len);
6809		else
6810			scsi_ulto3b(0, block_desc->block_len);
6811	}
6812
6813	switch (page_code) {
6814	case SMS_ALL_PAGES_PAGE: {
6815		int i, data_used;
6816
6817		data_used = header_len;
6818		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6819			struct ctl_page_index *page_index;
6820
6821			page_index = &lun->mode_pages.index[i];
6822
6823			if ((control_dev != 0)
6824			 && (page_index->page_flags &
6825			    CTL_PAGE_FLAG_DISK_ONLY))
6826				continue;
6827
6828			/*
6829			 * We don't use this subpage if the user didn't
6830			 * request all subpages.  We already checked (above)
6831			 * to make sure the user only specified a subpage
6832			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6833			 */
6834			if ((page_index->subpage != 0)
6835			 && (subpage == SMS_SUBPAGE_PAGE_0))
6836				continue;
6837
6838			/*
6839			 * Call the handler, if it exists, to update the
6840			 * page to the latest values.
6841			 */
6842			if (page_index->sense_handler != NULL)
6843				page_index->sense_handler(ctsio, page_index,pc);
6844
6845			memcpy(ctsio->kern_data_ptr + data_used,
6846			       page_index->page_data +
6847			       (page_index->page_len * pc),
6848			       page_index->page_len);
6849			data_used += page_index->page_len;
6850		}
6851		break;
6852	}
6853	default: {
6854		int i, data_used;
6855
6856		data_used = header_len;
6857
6858		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6859			struct ctl_page_index *page_index;
6860
6861			page_index = &lun->mode_pages.index[i];
6862
6863			/* Look for the right page code */
6864			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6865				continue;
6866
6867			/* Look for the right subpage or the subpage wildcard*/
6868			if ((page_index->subpage != subpage)
6869			 && (subpage != SMS_SUBPAGE_ALL))
6870				continue;
6871
6872			/* Make sure the page is supported for this dev type */
6873			if ((control_dev != 0)
6874			 && (page_index->page_flags &
6875			     CTL_PAGE_FLAG_DISK_ONLY))
6876				continue;
6877
6878			/*
6879			 * Call the handler, if it exists, to update the
6880			 * page to the latest values.
6881			 */
6882			if (page_index->sense_handler != NULL)
6883				page_index->sense_handler(ctsio, page_index,pc);
6884
6885			memcpy(ctsio->kern_data_ptr + data_used,
6886			       page_index->page_data +
6887			       (page_index->page_len * pc),
6888			       page_index->page_len);
6889			data_used += page_index->page_len;
6890		}
6891		break;
6892	}
6893	}
6894
6895	ctl_set_success(ctsio);
6896	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6897	ctsio->be_move_done = ctl_config_move_done;
6898	ctl_datamove((union ctl_io *)ctsio);
6899	return (CTL_RETVAL_COMPLETE);
6900}
6901
6902int
6903ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6904			       struct ctl_page_index *page_index,
6905			       int pc)
6906{
6907	struct ctl_lun *lun;
6908	struct scsi_log_param_header *phdr;
6909	uint8_t *data;
6910	uint64_t val;
6911
6912	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6913	data = page_index->page_data;
6914
6915	if (lun->backend->lun_attr != NULL &&
6916	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6917	     != UINT64_MAX) {
6918		phdr = (struct scsi_log_param_header *)data;
6919		scsi_ulto2b(0x0001, phdr->param_code);
6920		phdr->param_control = SLP_LBIN | SLP_LP;
6921		phdr->param_len = 8;
6922		data = (uint8_t *)(phdr + 1);
6923		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6924		data[4] = 0x02; /* per-pool */
6925		data += phdr->param_len;
6926	}
6927
6928	if (lun->backend->lun_attr != NULL &&
6929	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6930	     != UINT64_MAX) {
6931		phdr = (struct scsi_log_param_header *)data;
6932		scsi_ulto2b(0x0002, phdr->param_code);
6933		phdr->param_control = SLP_LBIN | SLP_LP;
6934		phdr->param_len = 8;
6935		data = (uint8_t *)(phdr + 1);
6936		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6937		data[4] = 0x01; /* per-LUN */
6938		data += phdr->param_len;
6939	}
6940
6941	if (lun->backend->lun_attr != NULL &&
6942	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6943	     != UINT64_MAX) {
6944		phdr = (struct scsi_log_param_header *)data;
6945		scsi_ulto2b(0x00f1, phdr->param_code);
6946		phdr->param_control = SLP_LBIN | SLP_LP;
6947		phdr->param_len = 8;
6948		data = (uint8_t *)(phdr + 1);
6949		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6950		data[4] = 0x02; /* per-pool */
6951		data += phdr->param_len;
6952	}
6953
6954	if (lun->backend->lun_attr != NULL &&
6955	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6956	     != UINT64_MAX) {
6957		phdr = (struct scsi_log_param_header *)data;
6958		scsi_ulto2b(0x00f2, phdr->param_code);
6959		phdr->param_control = SLP_LBIN | SLP_LP;
6960		phdr->param_len = 8;
6961		data = (uint8_t *)(phdr + 1);
6962		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6963		data[4] = 0x02; /* per-pool */
6964		data += phdr->param_len;
6965	}
6966
6967	page_index->page_len = data - page_index->page_data;
6968	return (0);
6969}
6970
6971int
6972ctl_log_sense(struct ctl_scsiio *ctsio)
6973{
6974	struct ctl_lun *lun;
6975	int i, pc, page_code, subpage;
6976	int alloc_len, total_len;
6977	struct ctl_page_index *page_index;
6978	struct scsi_log_sense *cdb;
6979	struct scsi_log_header *header;
6980
6981	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6982
6983	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6984	cdb = (struct scsi_log_sense *)ctsio->cdb;
6985	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6986	page_code = cdb->page & SLS_PAGE_CODE;
6987	subpage = cdb->subpage;
6988	alloc_len = scsi_2btoul(cdb->length);
6989
6990	page_index = NULL;
6991	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6992		page_index = &lun->log_pages.index[i];
6993
6994		/* Look for the right page code */
6995		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6996			continue;
6997
6998		/* Look for the right subpage or the subpage wildcard*/
6999		if (page_index->subpage != subpage)
7000			continue;
7001
7002		break;
7003	}
7004	if (i >= CTL_NUM_LOG_PAGES) {
7005		ctl_set_invalid_field(ctsio,
7006				      /*sks_valid*/ 1,
7007				      /*command*/ 1,
7008				      /*field*/ 2,
7009				      /*bit_valid*/ 0,
7010				      /*bit*/ 0);
7011		ctl_done((union ctl_io *)ctsio);
7012		return (CTL_RETVAL_COMPLETE);
7013	}
7014
7015	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
7016
7017	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7018	ctsio->kern_sg_entries = 0;
7019	ctsio->kern_data_resid = 0;
7020	ctsio->kern_rel_offset = 0;
7021	if (total_len < alloc_len) {
7022		ctsio->residual = alloc_len - total_len;
7023		ctsio->kern_data_len = total_len;
7024		ctsio->kern_total_len = total_len;
7025	} else {
7026		ctsio->residual = 0;
7027		ctsio->kern_data_len = alloc_len;
7028		ctsio->kern_total_len = alloc_len;
7029	}
7030
7031	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7032	header->page = page_index->page_code;
7033	if (page_index->subpage) {
7034		header->page |= SL_SPF;
7035		header->subpage = page_index->subpage;
7036	}
7037	scsi_ulto2b(page_index->page_len, header->datalen);
7038
7039	/*
7040	 * Call the handler, if it exists, to update the
7041	 * page to the latest values.
7042	 */
7043	if (page_index->sense_handler != NULL)
7044		page_index->sense_handler(ctsio, page_index, pc);
7045
7046	memcpy(header + 1, page_index->page_data, page_index->page_len);
7047
7048	ctl_set_success(ctsio);
7049	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7050	ctsio->be_move_done = ctl_config_move_done;
7051	ctl_datamove((union ctl_io *)ctsio);
7052	return (CTL_RETVAL_COMPLETE);
7053}
7054
7055int
7056ctl_read_capacity(struct ctl_scsiio *ctsio)
7057{
7058	struct scsi_read_capacity *cdb;
7059	struct scsi_read_capacity_data *data;
7060	struct ctl_lun *lun;
7061	uint32_t lba;
7062
7063	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7064
7065	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7066
7067	lba = scsi_4btoul(cdb->addr);
7068	if (((cdb->pmi & SRC_PMI) == 0)
7069	 && (lba != 0)) {
7070		ctl_set_invalid_field(/*ctsio*/ ctsio,
7071				      /*sks_valid*/ 1,
7072				      /*command*/ 1,
7073				      /*field*/ 2,
7074				      /*bit_valid*/ 0,
7075				      /*bit*/ 0);
7076		ctl_done((union ctl_io *)ctsio);
7077		return (CTL_RETVAL_COMPLETE);
7078	}
7079
7080	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7081
7082	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7083	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7084	ctsio->residual = 0;
7085	ctsio->kern_data_len = sizeof(*data);
7086	ctsio->kern_total_len = sizeof(*data);
7087	ctsio->kern_data_resid = 0;
7088	ctsio->kern_rel_offset = 0;
7089	ctsio->kern_sg_entries = 0;
7090
7091	/*
7092	 * If the maximum LBA is greater than 0xfffffffe, the user must
7093	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7094	 * serivce action set.
7095	 */
7096	if (lun->be_lun->maxlba > 0xfffffffe)
7097		scsi_ulto4b(0xffffffff, data->addr);
7098	else
7099		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7100
7101	/*
7102	 * XXX KDM this may not be 512 bytes...
7103	 */
7104	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7105
7106	ctl_set_success(ctsio);
7107	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7108	ctsio->be_move_done = ctl_config_move_done;
7109	ctl_datamove((union ctl_io *)ctsio);
7110	return (CTL_RETVAL_COMPLETE);
7111}
7112
7113int
7114ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7115{
7116	struct scsi_read_capacity_16 *cdb;
7117	struct scsi_read_capacity_data_long *data;
7118	struct ctl_lun *lun;
7119	uint64_t lba;
7120	uint32_t alloc_len;
7121
7122	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7123
7124	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7125
7126	alloc_len = scsi_4btoul(cdb->alloc_len);
7127	lba = scsi_8btou64(cdb->addr);
7128
7129	if ((cdb->reladr & SRC16_PMI)
7130	 && (lba != 0)) {
7131		ctl_set_invalid_field(/*ctsio*/ ctsio,
7132				      /*sks_valid*/ 1,
7133				      /*command*/ 1,
7134				      /*field*/ 2,
7135				      /*bit_valid*/ 0,
7136				      /*bit*/ 0);
7137		ctl_done((union ctl_io *)ctsio);
7138		return (CTL_RETVAL_COMPLETE);
7139	}
7140
7141	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7142
7143	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7144	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7145
7146	if (sizeof(*data) < alloc_len) {
7147		ctsio->residual = alloc_len - sizeof(*data);
7148		ctsio->kern_data_len = sizeof(*data);
7149		ctsio->kern_total_len = sizeof(*data);
7150	} else {
7151		ctsio->residual = 0;
7152		ctsio->kern_data_len = alloc_len;
7153		ctsio->kern_total_len = alloc_len;
7154	}
7155	ctsio->kern_data_resid = 0;
7156	ctsio->kern_rel_offset = 0;
7157	ctsio->kern_sg_entries = 0;
7158
7159	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7160	/* XXX KDM this may not be 512 bytes... */
7161	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7162	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7163	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7164	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7165		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7166
7167	ctl_set_success(ctsio);
7168	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7169	ctsio->be_move_done = ctl_config_move_done;
7170	ctl_datamove((union ctl_io *)ctsio);
7171	return (CTL_RETVAL_COMPLETE);
7172}
7173
7174int
7175ctl_get_lba_status(struct ctl_scsiio *ctsio)
7176{
7177	struct scsi_get_lba_status *cdb;
7178	struct scsi_get_lba_status_data *data;
7179	struct ctl_lun *lun;
7180	struct ctl_lba_len_flags *lbalen;
7181	uint64_t lba;
7182	uint32_t alloc_len, total_len;
7183	int retval;
7184
7185	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7186
7187	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7188	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7189	lba = scsi_8btou64(cdb->addr);
7190	alloc_len = scsi_4btoul(cdb->alloc_len);
7191
7192	if (lba > lun->be_lun->maxlba) {
7193		ctl_set_lba_out_of_range(ctsio);
7194		ctl_done((union ctl_io *)ctsio);
7195		return (CTL_RETVAL_COMPLETE);
7196	}
7197
7198	total_len = sizeof(*data) + sizeof(data->descr[0]);
7199	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7200	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7201
7202	if (total_len < alloc_len) {
7203		ctsio->residual = alloc_len - total_len;
7204		ctsio->kern_data_len = total_len;
7205		ctsio->kern_total_len = total_len;
7206	} else {
7207		ctsio->residual = 0;
7208		ctsio->kern_data_len = alloc_len;
7209		ctsio->kern_total_len = alloc_len;
7210	}
7211	ctsio->kern_data_resid = 0;
7212	ctsio->kern_rel_offset = 0;
7213	ctsio->kern_sg_entries = 0;
7214
7215	/* Fill dummy data in case backend can't tell anything. */
7216	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7217	scsi_u64to8b(lba, data->descr[0].addr);
7218	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7219	    data->descr[0].length);
7220	data->descr[0].status = 0; /* Mapped or unknown. */
7221
7222	ctl_set_success(ctsio);
7223	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7224	ctsio->be_move_done = ctl_config_move_done;
7225
7226	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7227	lbalen->lba = lba;
7228	lbalen->len = total_len;
7229	lbalen->flags = 0;
7230	retval = lun->backend->config_read((union ctl_io *)ctsio);
7231	return (CTL_RETVAL_COMPLETE);
7232}
7233
7234int
7235ctl_read_defect(struct ctl_scsiio *ctsio)
7236{
7237	struct scsi_read_defect_data_10 *ccb10;
7238	struct scsi_read_defect_data_12 *ccb12;
7239	struct scsi_read_defect_data_hdr_10 *data10;
7240	struct scsi_read_defect_data_hdr_12 *data12;
7241	uint32_t alloc_len, data_len;
7242	uint8_t format;
7243
7244	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7245
7246	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7247		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7248		format = ccb10->format;
7249		alloc_len = scsi_2btoul(ccb10->alloc_length);
7250		data_len = sizeof(*data10);
7251	} else {
7252		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7253		format = ccb12->format;
7254		alloc_len = scsi_4btoul(ccb12->alloc_length);
7255		data_len = sizeof(*data12);
7256	}
7257	if (alloc_len == 0) {
7258		ctl_set_success(ctsio);
7259		ctl_done((union ctl_io *)ctsio);
7260		return (CTL_RETVAL_COMPLETE);
7261	}
7262
7263	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7264	if (data_len < alloc_len) {
7265		ctsio->residual = alloc_len - data_len;
7266		ctsio->kern_data_len = data_len;
7267		ctsio->kern_total_len = data_len;
7268	} else {
7269		ctsio->residual = 0;
7270		ctsio->kern_data_len = alloc_len;
7271		ctsio->kern_total_len = alloc_len;
7272	}
7273	ctsio->kern_data_resid = 0;
7274	ctsio->kern_rel_offset = 0;
7275	ctsio->kern_sg_entries = 0;
7276
7277	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7278		data10 = (struct scsi_read_defect_data_hdr_10 *)
7279		    ctsio->kern_data_ptr;
7280		data10->format = format;
7281		scsi_ulto2b(0, data10->length);
7282	} else {
7283		data12 = (struct scsi_read_defect_data_hdr_12 *)
7284		    ctsio->kern_data_ptr;
7285		data12->format = format;
7286		scsi_ulto2b(0, data12->generation);
7287		scsi_ulto4b(0, data12->length);
7288	}
7289
7290	ctl_set_success(ctsio);
7291	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7292	ctsio->be_move_done = ctl_config_move_done;
7293	ctl_datamove((union ctl_io *)ctsio);
7294	return (CTL_RETVAL_COMPLETE);
7295}
7296
7297int
7298ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7299{
7300	struct scsi_maintenance_in *cdb;
7301	int retval;
7302	int alloc_len, ext, total_len = 0, g, p, pc, pg, gs, os;
7303	int num_target_port_groups, num_target_ports;
7304	struct ctl_lun *lun;
7305	struct ctl_softc *softc;
7306	struct ctl_port *port;
7307	struct scsi_target_group_data *rtg_ptr;
7308	struct scsi_target_group_data_extended *rtg_ext_ptr;
7309	struct scsi_target_port_group_descriptor *tpg_desc;
7310
7311	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7312
7313	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7314	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7315	softc = lun->ctl_softc;
7316
7317	retval = CTL_RETVAL_COMPLETE;
7318
7319	switch (cdb->byte2 & STG_PDF_MASK) {
7320	case STG_PDF_LENGTH:
7321		ext = 0;
7322		break;
7323	case STG_PDF_EXTENDED:
7324		ext = 1;
7325		break;
7326	default:
7327		ctl_set_invalid_field(/*ctsio*/ ctsio,
7328				      /*sks_valid*/ 1,
7329				      /*command*/ 1,
7330				      /*field*/ 2,
7331				      /*bit_valid*/ 1,
7332				      /*bit*/ 5);
7333		ctl_done((union ctl_io *)ctsio);
7334		return(retval);
7335	}
7336
7337	if (softc->is_single)
7338		num_target_port_groups = 1;
7339	else
7340		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7341	num_target_ports = 0;
7342	mtx_lock(&softc->ctl_lock);
7343	STAILQ_FOREACH(port, &softc->port_list, links) {
7344		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7345			continue;
7346		if (ctl_map_lun_back(softc, port->targ_port, lun->lun) >=
7347		    CTL_MAX_LUNS)
7348			continue;
7349		num_target_ports++;
7350	}
7351	mtx_unlock(&softc->ctl_lock);
7352
7353	if (ext)
7354		total_len = sizeof(struct scsi_target_group_data_extended);
7355	else
7356		total_len = sizeof(struct scsi_target_group_data);
7357	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7358		num_target_port_groups +
7359	    sizeof(struct scsi_target_port_descriptor) *
7360		num_target_ports * num_target_port_groups;
7361
7362	alloc_len = scsi_4btoul(cdb->length);
7363
7364	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7365
7366	ctsio->kern_sg_entries = 0;
7367
7368	if (total_len < alloc_len) {
7369		ctsio->residual = alloc_len - total_len;
7370		ctsio->kern_data_len = total_len;
7371		ctsio->kern_total_len = total_len;
7372	} else {
7373		ctsio->residual = 0;
7374		ctsio->kern_data_len = alloc_len;
7375		ctsio->kern_total_len = alloc_len;
7376	}
7377	ctsio->kern_data_resid = 0;
7378	ctsio->kern_rel_offset = 0;
7379
7380	if (ext) {
7381		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7382		    ctsio->kern_data_ptr;
7383		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7384		rtg_ext_ptr->format_type = 0x10;
7385		rtg_ext_ptr->implicit_transition_time = 0;
7386		tpg_desc = &rtg_ext_ptr->groups[0];
7387	} else {
7388		rtg_ptr = (struct scsi_target_group_data *)
7389		    ctsio->kern_data_ptr;
7390		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7391		tpg_desc = &rtg_ptr->groups[0];
7392	}
7393
7394	mtx_lock(&softc->ctl_lock);
7395	pg = softc->port_offset / CTL_MAX_PORTS;
7396	if (softc->flags & CTL_FLAG_ACTIVE_SHELF) {
7397		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY) {
7398			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7399			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7400		} else if (lun->flags & CTL_LUN_PRIMARY_SC) {
7401			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7402			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7403		} else {
7404			gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7405			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7406		}
7407	} else {
7408		gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7409		os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7410	}
7411	for (g = 0; g < num_target_port_groups; g++) {
7412		tpg_desc->pref_state = (g == pg) ? gs : os;
7413		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP;
7414		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7415		tpg_desc->status = TPG_IMPLICIT;
7416		pc = 0;
7417		STAILQ_FOREACH(port, &softc->port_list, links) {
7418			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7419				continue;
7420			if (ctl_map_lun_back(softc, port->targ_port, lun->lun)
7421			    >= CTL_MAX_LUNS)
7422				continue;
7423			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7424			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7425			    relative_target_port_identifier);
7426			pc++;
7427		}
7428		tpg_desc->target_port_count = pc;
7429		tpg_desc = (struct scsi_target_port_group_descriptor *)
7430		    &tpg_desc->descriptors[pc];
7431	}
7432	mtx_unlock(&softc->ctl_lock);
7433
7434	ctl_set_success(ctsio);
7435	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7436	ctsio->be_move_done = ctl_config_move_done;
7437	ctl_datamove((union ctl_io *)ctsio);
7438	return(retval);
7439}
7440
7441int
7442ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7443{
7444	struct ctl_lun *lun;
7445	struct scsi_report_supported_opcodes *cdb;
7446	const struct ctl_cmd_entry *entry, *sentry;
7447	struct scsi_report_supported_opcodes_all *all;
7448	struct scsi_report_supported_opcodes_descr *descr;
7449	struct scsi_report_supported_opcodes_one *one;
7450	int retval;
7451	int alloc_len, total_len;
7452	int opcode, service_action, i, j, num;
7453
7454	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7455
7456	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7457	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7458
7459	retval = CTL_RETVAL_COMPLETE;
7460
7461	opcode = cdb->requested_opcode;
7462	service_action = scsi_2btoul(cdb->requested_service_action);
7463	switch (cdb->options & RSO_OPTIONS_MASK) {
7464	case RSO_OPTIONS_ALL:
7465		num = 0;
7466		for (i = 0; i < 256; i++) {
7467			entry = &ctl_cmd_table[i];
7468			if (entry->flags & CTL_CMD_FLAG_SA5) {
7469				for (j = 0; j < 32; j++) {
7470					sentry = &((const struct ctl_cmd_entry *)
7471					    entry->execute)[j];
7472					if (ctl_cmd_applicable(
7473					    lun->be_lun->lun_type, sentry))
7474						num++;
7475				}
7476			} else {
7477				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7478				    entry))
7479					num++;
7480			}
7481		}
7482		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7483		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7484		break;
7485	case RSO_OPTIONS_OC:
7486		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7487			ctl_set_invalid_field(/*ctsio*/ ctsio,
7488					      /*sks_valid*/ 1,
7489					      /*command*/ 1,
7490					      /*field*/ 2,
7491					      /*bit_valid*/ 1,
7492					      /*bit*/ 2);
7493			ctl_done((union ctl_io *)ctsio);
7494			return (CTL_RETVAL_COMPLETE);
7495		}
7496		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7497		break;
7498	case RSO_OPTIONS_OC_SA:
7499		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7500		    service_action >= 32) {
7501			ctl_set_invalid_field(/*ctsio*/ ctsio,
7502					      /*sks_valid*/ 1,
7503					      /*command*/ 1,
7504					      /*field*/ 2,
7505					      /*bit_valid*/ 1,
7506					      /*bit*/ 2);
7507			ctl_done((union ctl_io *)ctsio);
7508			return (CTL_RETVAL_COMPLETE);
7509		}
7510		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7511		break;
7512	default:
7513		ctl_set_invalid_field(/*ctsio*/ ctsio,
7514				      /*sks_valid*/ 1,
7515				      /*command*/ 1,
7516				      /*field*/ 2,
7517				      /*bit_valid*/ 1,
7518				      /*bit*/ 2);
7519		ctl_done((union ctl_io *)ctsio);
7520		return (CTL_RETVAL_COMPLETE);
7521	}
7522
7523	alloc_len = scsi_4btoul(cdb->length);
7524
7525	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7526
7527	ctsio->kern_sg_entries = 0;
7528
7529	if (total_len < alloc_len) {
7530		ctsio->residual = alloc_len - total_len;
7531		ctsio->kern_data_len = total_len;
7532		ctsio->kern_total_len = total_len;
7533	} else {
7534		ctsio->residual = 0;
7535		ctsio->kern_data_len = alloc_len;
7536		ctsio->kern_total_len = alloc_len;
7537	}
7538	ctsio->kern_data_resid = 0;
7539	ctsio->kern_rel_offset = 0;
7540
7541	switch (cdb->options & RSO_OPTIONS_MASK) {
7542	case RSO_OPTIONS_ALL:
7543		all = (struct scsi_report_supported_opcodes_all *)
7544		    ctsio->kern_data_ptr;
7545		num = 0;
7546		for (i = 0; i < 256; i++) {
7547			entry = &ctl_cmd_table[i];
7548			if (entry->flags & CTL_CMD_FLAG_SA5) {
7549				for (j = 0; j < 32; j++) {
7550					sentry = &((const struct ctl_cmd_entry *)
7551					    entry->execute)[j];
7552					if (!ctl_cmd_applicable(
7553					    lun->be_lun->lun_type, sentry))
7554						continue;
7555					descr = &all->descr[num++];
7556					descr->opcode = i;
7557					scsi_ulto2b(j, descr->service_action);
7558					descr->flags = RSO_SERVACTV;
7559					scsi_ulto2b(sentry->length,
7560					    descr->cdb_length);
7561				}
7562			} else {
7563				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7564				    entry))
7565					continue;
7566				descr = &all->descr[num++];
7567				descr->opcode = i;
7568				scsi_ulto2b(0, descr->service_action);
7569				descr->flags = 0;
7570				scsi_ulto2b(entry->length, descr->cdb_length);
7571			}
7572		}
7573		scsi_ulto4b(
7574		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7575		    all->length);
7576		break;
7577	case RSO_OPTIONS_OC:
7578		one = (struct scsi_report_supported_opcodes_one *)
7579		    ctsio->kern_data_ptr;
7580		entry = &ctl_cmd_table[opcode];
7581		goto fill_one;
7582	case RSO_OPTIONS_OC_SA:
7583		one = (struct scsi_report_supported_opcodes_one *)
7584		    ctsio->kern_data_ptr;
7585		entry = &ctl_cmd_table[opcode];
7586		entry = &((const struct ctl_cmd_entry *)
7587		    entry->execute)[service_action];
7588fill_one:
7589		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7590			one->support = 3;
7591			scsi_ulto2b(entry->length, one->cdb_length);
7592			one->cdb_usage[0] = opcode;
7593			memcpy(&one->cdb_usage[1], entry->usage,
7594			    entry->length - 1);
7595		} else
7596			one->support = 1;
7597		break;
7598	}
7599
7600	ctl_set_success(ctsio);
7601	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7602	ctsio->be_move_done = ctl_config_move_done;
7603	ctl_datamove((union ctl_io *)ctsio);
7604	return(retval);
7605}
7606
7607int
7608ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7609{
7610	struct scsi_report_supported_tmf *cdb;
7611	struct scsi_report_supported_tmf_data *data;
7612	int retval;
7613	int alloc_len, total_len;
7614
7615	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7616
7617	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7618
7619	retval = CTL_RETVAL_COMPLETE;
7620
7621	total_len = sizeof(struct scsi_report_supported_tmf_data);
7622	alloc_len = scsi_4btoul(cdb->length);
7623
7624	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7625
7626	ctsio->kern_sg_entries = 0;
7627
7628	if (total_len < alloc_len) {
7629		ctsio->residual = alloc_len - total_len;
7630		ctsio->kern_data_len = total_len;
7631		ctsio->kern_total_len = total_len;
7632	} else {
7633		ctsio->residual = 0;
7634		ctsio->kern_data_len = alloc_len;
7635		ctsio->kern_total_len = alloc_len;
7636	}
7637	ctsio->kern_data_resid = 0;
7638	ctsio->kern_rel_offset = 0;
7639
7640	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7641	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7642	data->byte2 |= RST_ITNRS;
7643
7644	ctl_set_success(ctsio);
7645	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7646	ctsio->be_move_done = ctl_config_move_done;
7647	ctl_datamove((union ctl_io *)ctsio);
7648	return (retval);
7649}
7650
7651int
7652ctl_report_timestamp(struct ctl_scsiio *ctsio)
7653{
7654	struct scsi_report_timestamp *cdb;
7655	struct scsi_report_timestamp_data *data;
7656	struct timeval tv;
7657	int64_t timestamp;
7658	int retval;
7659	int alloc_len, total_len;
7660
7661	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7662
7663	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7664
7665	retval = CTL_RETVAL_COMPLETE;
7666
7667	total_len = sizeof(struct scsi_report_timestamp_data);
7668	alloc_len = scsi_4btoul(cdb->length);
7669
7670	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7671
7672	ctsio->kern_sg_entries = 0;
7673
7674	if (total_len < alloc_len) {
7675		ctsio->residual = alloc_len - total_len;
7676		ctsio->kern_data_len = total_len;
7677		ctsio->kern_total_len = total_len;
7678	} else {
7679		ctsio->residual = 0;
7680		ctsio->kern_data_len = alloc_len;
7681		ctsio->kern_total_len = alloc_len;
7682	}
7683	ctsio->kern_data_resid = 0;
7684	ctsio->kern_rel_offset = 0;
7685
7686	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7687	scsi_ulto2b(sizeof(*data) - 2, data->length);
7688	data->origin = RTS_ORIG_OUTSIDE;
7689	getmicrotime(&tv);
7690	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7691	scsi_ulto4b(timestamp >> 16, data->timestamp);
7692	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7693
7694	ctl_set_success(ctsio);
7695	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7696	ctsio->be_move_done = ctl_config_move_done;
7697	ctl_datamove((union ctl_io *)ctsio);
7698	return (retval);
7699}
7700
7701int
7702ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7703{
7704	struct scsi_per_res_in *cdb;
7705	int alloc_len, total_len = 0;
7706	/* struct scsi_per_res_in_rsrv in_data; */
7707	struct ctl_lun *lun;
7708	struct ctl_softc *softc;
7709	uint64_t key;
7710
7711	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7712
7713	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7714
7715	alloc_len = scsi_2btoul(cdb->length);
7716
7717	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7718	softc = lun->ctl_softc;
7719
7720retry:
7721	mtx_lock(&lun->lun_lock);
7722	switch (cdb->action) {
7723	case SPRI_RK: /* read keys */
7724		total_len = sizeof(struct scsi_per_res_in_keys) +
7725			lun->pr_key_count *
7726			sizeof(struct scsi_per_res_key);
7727		break;
7728	case SPRI_RR: /* read reservation */
7729		if (lun->flags & CTL_LUN_PR_RESERVED)
7730			total_len = sizeof(struct scsi_per_res_in_rsrv);
7731		else
7732			total_len = sizeof(struct scsi_per_res_in_header);
7733		break;
7734	case SPRI_RC: /* report capabilities */
7735		total_len = sizeof(struct scsi_per_res_cap);
7736		break;
7737	case SPRI_RS: /* read full status */
7738		total_len = sizeof(struct scsi_per_res_in_header) +
7739		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7740		    lun->pr_key_count;
7741		break;
7742	default:
7743		panic("Invalid PR type %x", cdb->action);
7744	}
7745	mtx_unlock(&lun->lun_lock);
7746
7747	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7748
7749	if (total_len < alloc_len) {
7750		ctsio->residual = alloc_len - total_len;
7751		ctsio->kern_data_len = total_len;
7752		ctsio->kern_total_len = total_len;
7753	} else {
7754		ctsio->residual = 0;
7755		ctsio->kern_data_len = alloc_len;
7756		ctsio->kern_total_len = alloc_len;
7757	}
7758
7759	ctsio->kern_data_resid = 0;
7760	ctsio->kern_rel_offset = 0;
7761	ctsio->kern_sg_entries = 0;
7762
7763	mtx_lock(&lun->lun_lock);
7764	switch (cdb->action) {
7765	case SPRI_RK: { // read keys
7766        struct scsi_per_res_in_keys *res_keys;
7767		int i, key_count;
7768
7769		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7770
7771		/*
7772		 * We had to drop the lock to allocate our buffer, which
7773		 * leaves time for someone to come in with another
7774		 * persistent reservation.  (That is unlikely, though,
7775		 * since this should be the only persistent reservation
7776		 * command active right now.)
7777		 */
7778		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7779		    (lun->pr_key_count *
7780		     sizeof(struct scsi_per_res_key)))){
7781			mtx_unlock(&lun->lun_lock);
7782			free(ctsio->kern_data_ptr, M_CTL);
7783			printf("%s: reservation length changed, retrying\n",
7784			       __func__);
7785			goto retry;
7786		}
7787
7788		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7789
7790		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7791			     lun->pr_key_count, res_keys->header.length);
7792
7793		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7794			if ((key = ctl_get_prkey(lun, i)) == 0)
7795				continue;
7796
7797			/*
7798			 * We used lun->pr_key_count to calculate the
7799			 * size to allocate.  If it turns out the number of
7800			 * initiators with the registered flag set is
7801			 * larger than that (i.e. they haven't been kept in
7802			 * sync), we've got a problem.
7803			 */
7804			if (key_count >= lun->pr_key_count) {
7805#ifdef NEEDTOPORT
7806				csevent_log(CSC_CTL | CSC_SHELF_SW |
7807					    CTL_PR_ERROR,
7808					    csevent_LogType_Fault,
7809					    csevent_AlertLevel_Yellow,
7810					    csevent_FRU_ShelfController,
7811					    csevent_FRU_Firmware,
7812				        csevent_FRU_Unknown,
7813					    "registered keys %d >= key "
7814					    "count %d", key_count,
7815					    lun->pr_key_count);
7816#endif
7817				key_count++;
7818				continue;
7819			}
7820			scsi_u64to8b(key, res_keys->keys[key_count].key);
7821			key_count++;
7822		}
7823		break;
7824	}
7825	case SPRI_RR: { // read reservation
7826		struct scsi_per_res_in_rsrv *res;
7827		int tmp_len, header_only;
7828
7829		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7830
7831		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7832
7833		if (lun->flags & CTL_LUN_PR_RESERVED)
7834		{
7835			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7836			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7837				    res->header.length);
7838			header_only = 0;
7839		} else {
7840			tmp_len = sizeof(struct scsi_per_res_in_header);
7841			scsi_ulto4b(0, res->header.length);
7842			header_only = 1;
7843		}
7844
7845		/*
7846		 * We had to drop the lock to allocate our buffer, which
7847		 * leaves time for someone to come in with another
7848		 * persistent reservation.  (That is unlikely, though,
7849		 * since this should be the only persistent reservation
7850		 * command active right now.)
7851		 */
7852		if (tmp_len != total_len) {
7853			mtx_unlock(&lun->lun_lock);
7854			free(ctsio->kern_data_ptr, M_CTL);
7855			printf("%s: reservation status changed, retrying\n",
7856			       __func__);
7857			goto retry;
7858		}
7859
7860		/*
7861		 * No reservation held, so we're done.
7862		 */
7863		if (header_only != 0)
7864			break;
7865
7866		/*
7867		 * If the registration is an All Registrants type, the key
7868		 * is 0, since it doesn't really matter.
7869		 */
7870		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7871			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7872			    res->data.reservation);
7873		}
7874		res->data.scopetype = lun->res_type;
7875		break;
7876	}
7877	case SPRI_RC:     //report capabilities
7878	{
7879		struct scsi_per_res_cap *res_cap;
7880		uint16_t type_mask;
7881
7882		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7883		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7884		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7885		type_mask = SPRI_TM_WR_EX_AR |
7886			    SPRI_TM_EX_AC_RO |
7887			    SPRI_TM_WR_EX_RO |
7888			    SPRI_TM_EX_AC |
7889			    SPRI_TM_WR_EX |
7890			    SPRI_TM_EX_AC_AR;
7891		scsi_ulto2b(type_mask, res_cap->type_mask);
7892		break;
7893	}
7894	case SPRI_RS: { // read full status
7895		struct scsi_per_res_in_full *res_status;
7896		struct scsi_per_res_in_full_desc *res_desc;
7897		struct ctl_port *port;
7898		int i, len;
7899
7900		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7901
7902		/*
7903		 * We had to drop the lock to allocate our buffer, which
7904		 * leaves time for someone to come in with another
7905		 * persistent reservation.  (That is unlikely, though,
7906		 * since this should be the only persistent reservation
7907		 * command active right now.)
7908		 */
7909		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7910		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7911		     lun->pr_key_count)){
7912			mtx_unlock(&lun->lun_lock);
7913			free(ctsio->kern_data_ptr, M_CTL);
7914			printf("%s: reservation length changed, retrying\n",
7915			       __func__);
7916			goto retry;
7917		}
7918
7919		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7920
7921		res_desc = &res_status->desc[0];
7922		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7923			if ((key = ctl_get_prkey(lun, i)) == 0)
7924				continue;
7925
7926			scsi_u64to8b(key, res_desc->res_key.key);
7927			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7928			    (lun->pr_res_idx == i ||
7929			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7930				res_desc->flags = SPRI_FULL_R_HOLDER;
7931				res_desc->scopetype = lun->res_type;
7932			}
7933			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7934			    res_desc->rel_trgt_port_id);
7935			len = 0;
7936			port = softc->ctl_ports[
7937			    ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
7938			if (port != NULL)
7939				len = ctl_create_iid(port,
7940				    i % CTL_MAX_INIT_PER_PORT,
7941				    res_desc->transport_id);
7942			scsi_ulto4b(len, res_desc->additional_length);
7943			res_desc = (struct scsi_per_res_in_full_desc *)
7944			    &res_desc->transport_id[len];
7945		}
7946		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7947		    res_status->header.length);
7948		break;
7949	}
7950	default:
7951		/*
7952		 * This is a bug, because we just checked for this above,
7953		 * and should have returned an error.
7954		 */
7955		panic("Invalid PR type %x", cdb->action);
7956		break; /* NOTREACHED */
7957	}
7958	mtx_unlock(&lun->lun_lock);
7959
7960	ctl_set_success(ctsio);
7961	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7962	ctsio->be_move_done = ctl_config_move_done;
7963	ctl_datamove((union ctl_io *)ctsio);
7964	return (CTL_RETVAL_COMPLETE);
7965}
7966
7967static void
7968ctl_est_res_ua(struct ctl_lun *lun, uint32_t residx, ctl_ua_type ua)
7969{
7970	int off = lun->ctl_softc->persis_offset;
7971
7972	if (residx >= off && residx < off + CTL_MAX_INITIATORS)
7973		ctl_est_ua(lun, residx - off, ua);
7974}
7975
7976/*
7977 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7978 * it should return.
7979 */
7980static int
7981ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7982		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7983		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7984		struct scsi_per_res_out_parms* param)
7985{
7986	union ctl_ha_msg persis_io;
7987	int retval, i;
7988	int isc_retval;
7989
7990	retval = 0;
7991
7992	mtx_lock(&lun->lun_lock);
7993	if (sa_res_key == 0) {
7994		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7995			/* validate scope and type */
7996			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7997			     SPR_LU_SCOPE) {
7998				mtx_unlock(&lun->lun_lock);
7999				ctl_set_invalid_field(/*ctsio*/ ctsio,
8000						      /*sks_valid*/ 1,
8001						      /*command*/ 1,
8002						      /*field*/ 2,
8003						      /*bit_valid*/ 1,
8004						      /*bit*/ 4);
8005				ctl_done((union ctl_io *)ctsio);
8006				return (1);
8007			}
8008
8009		        if (type>8 || type==2 || type==4 || type==0) {
8010				mtx_unlock(&lun->lun_lock);
8011				ctl_set_invalid_field(/*ctsio*/ ctsio,
8012       	           				      /*sks_valid*/ 1,
8013						      /*command*/ 1,
8014						      /*field*/ 2,
8015						      /*bit_valid*/ 1,
8016						      /*bit*/ 0);
8017				ctl_done((union ctl_io *)ctsio);
8018				return (1);
8019		        }
8020
8021			/*
8022			 * Unregister everybody else and build UA for
8023			 * them
8024			 */
8025			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8026				if (i == residx || ctl_get_prkey(lun, i) == 0)
8027					continue;
8028
8029				ctl_clr_prkey(lun, i);
8030				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8031			}
8032			lun->pr_key_count = 1;
8033			lun->res_type = type;
8034			if (lun->res_type != SPR_TYPE_WR_EX_AR
8035			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8036				lun->pr_res_idx = residx;
8037
8038			/* send msg to other side */
8039			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8040			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8041			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8042			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8043			persis_io.pr.pr_info.res_type = type;
8044			memcpy(persis_io.pr.pr_info.sa_res_key,
8045			       param->serv_act_res_key,
8046			       sizeof(param->serv_act_res_key));
8047			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8048			     &persis_io, sizeof(persis_io), 0)) >
8049			     CTL_HA_STATUS_SUCCESS) {
8050				printf("CTL:Persis Out error returned "
8051				       "from ctl_ha_msg_send %d\n",
8052				       isc_retval);
8053			}
8054		} else {
8055			/* not all registrants */
8056			mtx_unlock(&lun->lun_lock);
8057			free(ctsio->kern_data_ptr, M_CTL);
8058			ctl_set_invalid_field(ctsio,
8059					      /*sks_valid*/ 1,
8060					      /*command*/ 0,
8061					      /*field*/ 8,
8062					      /*bit_valid*/ 0,
8063					      /*bit*/ 0);
8064			ctl_done((union ctl_io *)ctsio);
8065			return (1);
8066		}
8067	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8068		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8069		int found = 0;
8070
8071		if (res_key == sa_res_key) {
8072			/* special case */
8073			/*
8074			 * The spec implies this is not good but doesn't
8075			 * say what to do. There are two choices either
8076			 * generate a res conflict or check condition
8077			 * with illegal field in parameter data. Since
8078			 * that is what is done when the sa_res_key is
8079			 * zero I'll take that approach since this has
8080			 * to do with the sa_res_key.
8081			 */
8082			mtx_unlock(&lun->lun_lock);
8083			free(ctsio->kern_data_ptr, M_CTL);
8084			ctl_set_invalid_field(ctsio,
8085					      /*sks_valid*/ 1,
8086					      /*command*/ 0,
8087					      /*field*/ 8,
8088					      /*bit_valid*/ 0,
8089					      /*bit*/ 0);
8090			ctl_done((union ctl_io *)ctsio);
8091			return (1);
8092		}
8093
8094		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8095			if (ctl_get_prkey(lun, i) != sa_res_key)
8096				continue;
8097
8098			found = 1;
8099			ctl_clr_prkey(lun, i);
8100			lun->pr_key_count--;
8101			ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8102		}
8103		if (!found) {
8104			mtx_unlock(&lun->lun_lock);
8105			free(ctsio->kern_data_ptr, M_CTL);
8106			ctl_set_reservation_conflict(ctsio);
8107			ctl_done((union ctl_io *)ctsio);
8108			return (CTL_RETVAL_COMPLETE);
8109		}
8110		/* send msg to other side */
8111		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8112		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8113		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8114		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8115		persis_io.pr.pr_info.res_type = type;
8116		memcpy(persis_io.pr.pr_info.sa_res_key,
8117		       param->serv_act_res_key,
8118		       sizeof(param->serv_act_res_key));
8119		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8120		     &persis_io, sizeof(persis_io), 0)) >
8121		     CTL_HA_STATUS_SUCCESS) {
8122			printf("CTL:Persis Out error returned from "
8123			       "ctl_ha_msg_send %d\n", isc_retval);
8124		}
8125	} else {
8126		/* Reserved but not all registrants */
8127		/* sa_res_key is res holder */
8128		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
8129			/* validate scope and type */
8130			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8131			     SPR_LU_SCOPE) {
8132				mtx_unlock(&lun->lun_lock);
8133				ctl_set_invalid_field(/*ctsio*/ ctsio,
8134						      /*sks_valid*/ 1,
8135						      /*command*/ 1,
8136						      /*field*/ 2,
8137						      /*bit_valid*/ 1,
8138						      /*bit*/ 4);
8139				ctl_done((union ctl_io *)ctsio);
8140				return (1);
8141			}
8142
8143			if (type>8 || type==2 || type==4 || type==0) {
8144				mtx_unlock(&lun->lun_lock);
8145				ctl_set_invalid_field(/*ctsio*/ ctsio,
8146						      /*sks_valid*/ 1,
8147						      /*command*/ 1,
8148						      /*field*/ 2,
8149						      /*bit_valid*/ 1,
8150						      /*bit*/ 0);
8151				ctl_done((union ctl_io *)ctsio);
8152				return (1);
8153			}
8154
8155			/*
8156			 * Do the following:
8157			 * if sa_res_key != res_key remove all
8158			 * registrants w/sa_res_key and generate UA
8159			 * for these registrants(Registrations
8160			 * Preempted) if it wasn't an exclusive
8161			 * reservation generate UA(Reservations
8162			 * Preempted) for all other registered nexuses
8163			 * if the type has changed. Establish the new
8164			 * reservation and holder. If res_key and
8165			 * sa_res_key are the same do the above
8166			 * except don't unregister the res holder.
8167			 */
8168
8169			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8170				if (i == residx || ctl_get_prkey(lun, i) == 0)
8171					continue;
8172
8173				if (sa_res_key == ctl_get_prkey(lun, i)) {
8174					ctl_clr_prkey(lun, i);
8175					lun->pr_key_count--;
8176					ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8177				} else if (type != lun->res_type
8178					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8179					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8180					ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
8181				}
8182			}
8183			lun->res_type = type;
8184			if (lun->res_type != SPR_TYPE_WR_EX_AR
8185			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8186				lun->pr_res_idx = residx;
8187			else
8188				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8189
8190			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8191			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8192			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8193			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8194			persis_io.pr.pr_info.res_type = type;
8195			memcpy(persis_io.pr.pr_info.sa_res_key,
8196			       param->serv_act_res_key,
8197			       sizeof(param->serv_act_res_key));
8198			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8199			     &persis_io, sizeof(persis_io), 0)) >
8200			     CTL_HA_STATUS_SUCCESS) {
8201				printf("CTL:Persis Out error returned "
8202				       "from ctl_ha_msg_send %d\n",
8203				       isc_retval);
8204			}
8205		} else {
8206			/*
8207			 * sa_res_key is not the res holder just
8208			 * remove registrants
8209			 */
8210			int found=0;
8211
8212			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8213				if (sa_res_key != ctl_get_prkey(lun, i))
8214					continue;
8215
8216				found = 1;
8217				ctl_clr_prkey(lun, i);
8218				lun->pr_key_count--;
8219				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8220			}
8221
8222			if (!found) {
8223				mtx_unlock(&lun->lun_lock);
8224				free(ctsio->kern_data_ptr, M_CTL);
8225				ctl_set_reservation_conflict(ctsio);
8226				ctl_done((union ctl_io *)ctsio);
8227		        	return (1);
8228			}
8229			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8230			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8231			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8232			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8233			persis_io.pr.pr_info.res_type = type;
8234			memcpy(persis_io.pr.pr_info.sa_res_key,
8235			       param->serv_act_res_key,
8236			       sizeof(param->serv_act_res_key));
8237			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8238			     &persis_io, sizeof(persis_io), 0)) >
8239			     CTL_HA_STATUS_SUCCESS) {
8240				printf("CTL:Persis Out error returned "
8241				       "from ctl_ha_msg_send %d\n",
8242				isc_retval);
8243			}
8244		}
8245	}
8246
8247	lun->PRGeneration++;
8248	mtx_unlock(&lun->lun_lock);
8249
8250	return (retval);
8251}
8252
8253static void
8254ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8255{
8256	uint64_t sa_res_key;
8257	int i;
8258
8259	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8260
8261	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8262	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8263	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8264		if (sa_res_key == 0) {
8265			/*
8266			 * Unregister everybody else and build UA for
8267			 * them
8268			 */
8269			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8270				if (i == msg->pr.pr_info.residx ||
8271				    ctl_get_prkey(lun, i) == 0)
8272					continue;
8273
8274				ctl_clr_prkey(lun, i);
8275				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8276			}
8277
8278			lun->pr_key_count = 1;
8279			lun->res_type = msg->pr.pr_info.res_type;
8280			if (lun->res_type != SPR_TYPE_WR_EX_AR
8281			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8282				lun->pr_res_idx = msg->pr.pr_info.residx;
8283		} else {
8284		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8285				if (sa_res_key == ctl_get_prkey(lun, i))
8286					continue;
8287
8288				ctl_clr_prkey(lun, i);
8289				lun->pr_key_count--;
8290				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8291			}
8292		}
8293	} else {
8294		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8295			if (i == msg->pr.pr_info.residx ||
8296			    ctl_get_prkey(lun, i) == 0)
8297				continue;
8298
8299			if (sa_res_key == ctl_get_prkey(lun, i)) {
8300				ctl_clr_prkey(lun, i);
8301				lun->pr_key_count--;
8302				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8303			} else if (msg->pr.pr_info.res_type != lun->res_type
8304				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8305				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8306				ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
8307			}
8308		}
8309		lun->res_type = msg->pr.pr_info.res_type;
8310		if (lun->res_type != SPR_TYPE_WR_EX_AR
8311		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8312			lun->pr_res_idx = msg->pr.pr_info.residx;
8313		else
8314			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8315	}
8316	lun->PRGeneration++;
8317
8318}
8319
8320
8321int
8322ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8323{
8324	int retval;
8325	int isc_retval;
8326	u_int32_t param_len;
8327	struct scsi_per_res_out *cdb;
8328	struct ctl_lun *lun;
8329	struct scsi_per_res_out_parms* param;
8330	struct ctl_softc *softc;
8331	uint32_t residx;
8332	uint64_t res_key, sa_res_key, key;
8333	uint8_t type;
8334	union ctl_ha_msg persis_io;
8335	int    i;
8336
8337	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8338
8339	retval = CTL_RETVAL_COMPLETE;
8340
8341	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8342	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8343	softc = lun->ctl_softc;
8344
8345	/*
8346	 * We only support whole-LUN scope.  The scope & type are ignored for
8347	 * register, register and ignore existing key and clear.
8348	 * We sometimes ignore scope and type on preempts too!!
8349	 * Verify reservation type here as well.
8350	 */
8351	type = cdb->scope_type & SPR_TYPE_MASK;
8352	if ((cdb->action == SPRO_RESERVE)
8353	 || (cdb->action == SPRO_RELEASE)) {
8354		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8355			ctl_set_invalid_field(/*ctsio*/ ctsio,
8356					      /*sks_valid*/ 1,
8357					      /*command*/ 1,
8358					      /*field*/ 2,
8359					      /*bit_valid*/ 1,
8360					      /*bit*/ 4);
8361			ctl_done((union ctl_io *)ctsio);
8362			return (CTL_RETVAL_COMPLETE);
8363		}
8364
8365		if (type>8 || type==2 || type==4 || type==0) {
8366			ctl_set_invalid_field(/*ctsio*/ ctsio,
8367					      /*sks_valid*/ 1,
8368					      /*command*/ 1,
8369					      /*field*/ 2,
8370					      /*bit_valid*/ 1,
8371					      /*bit*/ 0);
8372			ctl_done((union ctl_io *)ctsio);
8373			return (CTL_RETVAL_COMPLETE);
8374		}
8375	}
8376
8377	param_len = scsi_4btoul(cdb->length);
8378
8379	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8380		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8381		ctsio->kern_data_len = param_len;
8382		ctsio->kern_total_len = param_len;
8383		ctsio->kern_data_resid = 0;
8384		ctsio->kern_rel_offset = 0;
8385		ctsio->kern_sg_entries = 0;
8386		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8387		ctsio->be_move_done = ctl_config_move_done;
8388		ctl_datamove((union ctl_io *)ctsio);
8389
8390		return (CTL_RETVAL_COMPLETE);
8391	}
8392
8393	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8394
8395	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8396	res_key = scsi_8btou64(param->res_key.key);
8397	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8398
8399	/*
8400	 * Validate the reservation key here except for SPRO_REG_IGNO
8401	 * This must be done for all other service actions
8402	 */
8403	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8404		mtx_lock(&lun->lun_lock);
8405		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8406			if (res_key != key) {
8407				/*
8408				 * The current key passed in doesn't match
8409				 * the one the initiator previously
8410				 * registered.
8411				 */
8412				mtx_unlock(&lun->lun_lock);
8413				free(ctsio->kern_data_ptr, M_CTL);
8414				ctl_set_reservation_conflict(ctsio);
8415				ctl_done((union ctl_io *)ctsio);
8416				return (CTL_RETVAL_COMPLETE);
8417			}
8418		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8419			/*
8420			 * We are not registered
8421			 */
8422			mtx_unlock(&lun->lun_lock);
8423			free(ctsio->kern_data_ptr, M_CTL);
8424			ctl_set_reservation_conflict(ctsio);
8425			ctl_done((union ctl_io *)ctsio);
8426			return (CTL_RETVAL_COMPLETE);
8427		} else if (res_key != 0) {
8428			/*
8429			 * We are not registered and trying to register but
8430			 * the register key isn't zero.
8431			 */
8432			mtx_unlock(&lun->lun_lock);
8433			free(ctsio->kern_data_ptr, M_CTL);
8434			ctl_set_reservation_conflict(ctsio);
8435			ctl_done((union ctl_io *)ctsio);
8436			return (CTL_RETVAL_COMPLETE);
8437		}
8438		mtx_unlock(&lun->lun_lock);
8439	}
8440
8441	switch (cdb->action & SPRO_ACTION_MASK) {
8442	case SPRO_REGISTER:
8443	case SPRO_REG_IGNO: {
8444
8445#if 0
8446		printf("Registration received\n");
8447#endif
8448
8449		/*
8450		 * We don't support any of these options, as we report in
8451		 * the read capabilities request (see
8452		 * ctl_persistent_reserve_in(), above).
8453		 */
8454		if ((param->flags & SPR_SPEC_I_PT)
8455		 || (param->flags & SPR_ALL_TG_PT)
8456		 || (param->flags & SPR_APTPL)) {
8457			int bit_ptr;
8458
8459			if (param->flags & SPR_APTPL)
8460				bit_ptr = 0;
8461			else if (param->flags & SPR_ALL_TG_PT)
8462				bit_ptr = 2;
8463			else /* SPR_SPEC_I_PT */
8464				bit_ptr = 3;
8465
8466			free(ctsio->kern_data_ptr, M_CTL);
8467			ctl_set_invalid_field(ctsio,
8468					      /*sks_valid*/ 1,
8469					      /*command*/ 0,
8470					      /*field*/ 20,
8471					      /*bit_valid*/ 1,
8472					      /*bit*/ bit_ptr);
8473			ctl_done((union ctl_io *)ctsio);
8474			return (CTL_RETVAL_COMPLETE);
8475		}
8476
8477		mtx_lock(&lun->lun_lock);
8478
8479		/*
8480		 * The initiator wants to clear the
8481		 * key/unregister.
8482		 */
8483		if (sa_res_key == 0) {
8484			if ((res_key == 0
8485			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8486			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8487			  && ctl_get_prkey(lun, residx) == 0)) {
8488				mtx_unlock(&lun->lun_lock);
8489				goto done;
8490			}
8491
8492			ctl_clr_prkey(lun, residx);
8493			lun->pr_key_count--;
8494
8495			if (residx == lun->pr_res_idx) {
8496				lun->flags &= ~CTL_LUN_PR_RESERVED;
8497				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8498
8499				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8500				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8501				 && lun->pr_key_count) {
8502					/*
8503					 * If the reservation is a registrants
8504					 * only type we need to generate a UA
8505					 * for other registered inits.  The
8506					 * sense code should be RESERVATIONS
8507					 * RELEASED
8508					 */
8509
8510					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8511						if (ctl_get_prkey(lun, i +
8512						    softc->persis_offset) == 0)
8513							continue;
8514						ctl_est_ua(lun, i,
8515						    CTL_UA_RES_RELEASE);
8516					}
8517				}
8518				lun->res_type = 0;
8519			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8520				if (lun->pr_key_count==0) {
8521					lun->flags &= ~CTL_LUN_PR_RESERVED;
8522					lun->res_type = 0;
8523					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8524				}
8525			}
8526			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8527			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8528			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8529			persis_io.pr.pr_info.residx = residx;
8530			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8531			     &persis_io, sizeof(persis_io), 0 )) >
8532			     CTL_HA_STATUS_SUCCESS) {
8533				printf("CTL:Persis Out error returned from "
8534				       "ctl_ha_msg_send %d\n", isc_retval);
8535			}
8536		} else /* sa_res_key != 0 */ {
8537
8538			/*
8539			 * If we aren't registered currently then increment
8540			 * the key count and set the registered flag.
8541			 */
8542			ctl_alloc_prkey(lun, residx);
8543			if (ctl_get_prkey(lun, residx) == 0)
8544				lun->pr_key_count++;
8545			ctl_set_prkey(lun, residx, sa_res_key);
8546
8547			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8548			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8549			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8550			persis_io.pr.pr_info.residx = residx;
8551			memcpy(persis_io.pr.pr_info.sa_res_key,
8552			       param->serv_act_res_key,
8553			       sizeof(param->serv_act_res_key));
8554			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8555			     &persis_io, sizeof(persis_io), 0)) >
8556			     CTL_HA_STATUS_SUCCESS) {
8557				printf("CTL:Persis Out error returned from "
8558				       "ctl_ha_msg_send %d\n", isc_retval);
8559			}
8560		}
8561		lun->PRGeneration++;
8562		mtx_unlock(&lun->lun_lock);
8563
8564		break;
8565	}
8566	case SPRO_RESERVE:
8567#if 0
8568                printf("Reserve executed type %d\n", type);
8569#endif
8570		mtx_lock(&lun->lun_lock);
8571		if (lun->flags & CTL_LUN_PR_RESERVED) {
8572			/*
8573			 * if this isn't the reservation holder and it's
8574			 * not a "all registrants" type or if the type is
8575			 * different then we have a conflict
8576			 */
8577			if ((lun->pr_res_idx != residx
8578			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8579			 || lun->res_type != type) {
8580				mtx_unlock(&lun->lun_lock);
8581				free(ctsio->kern_data_ptr, M_CTL);
8582				ctl_set_reservation_conflict(ctsio);
8583				ctl_done((union ctl_io *)ctsio);
8584				return (CTL_RETVAL_COMPLETE);
8585			}
8586			mtx_unlock(&lun->lun_lock);
8587		} else /* create a reservation */ {
8588			/*
8589			 * If it's not an "all registrants" type record
8590			 * reservation holder
8591			 */
8592			if (type != SPR_TYPE_WR_EX_AR
8593			 && type != SPR_TYPE_EX_AC_AR)
8594				lun->pr_res_idx = residx; /* Res holder */
8595			else
8596				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8597
8598			lun->flags |= CTL_LUN_PR_RESERVED;
8599			lun->res_type = type;
8600
8601			mtx_unlock(&lun->lun_lock);
8602
8603			/* send msg to other side */
8604			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8605			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8606			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8607			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8608			persis_io.pr.pr_info.res_type = type;
8609			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8610			     &persis_io, sizeof(persis_io), 0)) >
8611			     CTL_HA_STATUS_SUCCESS) {
8612				printf("CTL:Persis Out error returned from "
8613				       "ctl_ha_msg_send %d\n", isc_retval);
8614			}
8615		}
8616		break;
8617
8618	case SPRO_RELEASE:
8619		mtx_lock(&lun->lun_lock);
8620		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8621			/* No reservation exists return good status */
8622			mtx_unlock(&lun->lun_lock);
8623			goto done;
8624		}
8625		/*
8626		 * Is this nexus a reservation holder?
8627		 */
8628		if (lun->pr_res_idx != residx
8629		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8630			/*
8631			 * not a res holder return good status but
8632			 * do nothing
8633			 */
8634			mtx_unlock(&lun->lun_lock);
8635			goto done;
8636		}
8637
8638		if (lun->res_type != type) {
8639			mtx_unlock(&lun->lun_lock);
8640			free(ctsio->kern_data_ptr, M_CTL);
8641			ctl_set_illegal_pr_release(ctsio);
8642			ctl_done((union ctl_io *)ctsio);
8643			return (CTL_RETVAL_COMPLETE);
8644		}
8645
8646		/* okay to release */
8647		lun->flags &= ~CTL_LUN_PR_RESERVED;
8648		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8649		lun->res_type = 0;
8650
8651		/*
8652		 * if this isn't an exclusive access
8653		 * res generate UA for all other
8654		 * registrants.
8655		 */
8656		if (type != SPR_TYPE_EX_AC
8657		 && type != SPR_TYPE_WR_EX) {
8658			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8659				if (i == residx ||
8660				    ctl_get_prkey(lun,
8661				     i + softc->persis_offset) == 0)
8662					continue;
8663				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8664			}
8665		}
8666		mtx_unlock(&lun->lun_lock);
8667		/* Send msg to other side */
8668		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8669		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8670		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8671		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8672		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8673			printf("CTL:Persis Out error returned from "
8674			       "ctl_ha_msg_send %d\n", isc_retval);
8675		}
8676		break;
8677
8678	case SPRO_CLEAR:
8679		/* send msg to other side */
8680
8681		mtx_lock(&lun->lun_lock);
8682		lun->flags &= ~CTL_LUN_PR_RESERVED;
8683		lun->res_type = 0;
8684		lun->pr_key_count = 0;
8685		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8686
8687		ctl_clr_prkey(lun, residx);
8688		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8689			if (ctl_get_prkey(lun, i) != 0) {
8690				ctl_clr_prkey(lun, i);
8691				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8692			}
8693		lun->PRGeneration++;
8694		mtx_unlock(&lun->lun_lock);
8695		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8696		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8697		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8698		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8699		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8700			printf("CTL:Persis Out error returned from "
8701			       "ctl_ha_msg_send %d\n", isc_retval);
8702		}
8703		break;
8704
8705	case SPRO_PREEMPT:
8706	case SPRO_PRE_ABO: {
8707		int nretval;
8708
8709		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8710					  residx, ctsio, cdb, param);
8711		if (nretval != 0)
8712			return (CTL_RETVAL_COMPLETE);
8713		break;
8714	}
8715	default:
8716		panic("Invalid PR type %x", cdb->action);
8717	}
8718
8719done:
8720	free(ctsio->kern_data_ptr, M_CTL);
8721	ctl_set_success(ctsio);
8722	ctl_done((union ctl_io *)ctsio);
8723
8724	return (retval);
8725}
8726
8727/*
8728 * This routine is for handling a message from the other SC pertaining to
8729 * persistent reserve out. All the error checking will have been done
8730 * so only perorming the action need be done here to keep the two
8731 * in sync.
8732 */
8733static void
8734ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8735{
8736	struct ctl_lun *lun;
8737	struct ctl_softc *softc;
8738	int i;
8739	uint32_t targ_lun;
8740
8741	softc = control_softc;
8742
8743	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8744	lun = softc->ctl_luns[targ_lun];
8745	mtx_lock(&lun->lun_lock);
8746	switch(msg->pr.pr_info.action) {
8747	case CTL_PR_REG_KEY:
8748		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8749		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8750			lun->pr_key_count++;
8751		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8752		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8753		lun->PRGeneration++;
8754		break;
8755
8756	case CTL_PR_UNREG_KEY:
8757		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8758		lun->pr_key_count--;
8759
8760		/* XXX Need to see if the reservation has been released */
8761		/* if so do we need to generate UA? */
8762		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8763			lun->flags &= ~CTL_LUN_PR_RESERVED;
8764			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8765
8766			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8767			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8768			 && lun->pr_key_count) {
8769				/*
8770				 * If the reservation is a registrants
8771				 * only type we need to generate a UA
8772				 * for other registered inits.  The
8773				 * sense code should be RESERVATIONS
8774				 * RELEASED
8775				 */
8776
8777				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8778					if (ctl_get_prkey(lun, i +
8779					    softc->persis_offset) == 0)
8780						continue;
8781
8782					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8783				}
8784			}
8785			lun->res_type = 0;
8786		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8787			if (lun->pr_key_count==0) {
8788				lun->flags &= ~CTL_LUN_PR_RESERVED;
8789				lun->res_type = 0;
8790				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8791			}
8792		}
8793		lun->PRGeneration++;
8794		break;
8795
8796	case CTL_PR_RESERVE:
8797		lun->flags |= CTL_LUN_PR_RESERVED;
8798		lun->res_type = msg->pr.pr_info.res_type;
8799		lun->pr_res_idx = msg->pr.pr_info.residx;
8800
8801		break;
8802
8803	case CTL_PR_RELEASE:
8804		/*
8805		 * if this isn't an exclusive access res generate UA for all
8806		 * other registrants.
8807		 */
8808		if (lun->res_type != SPR_TYPE_EX_AC
8809		 && lun->res_type != SPR_TYPE_WR_EX) {
8810			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8811				if (ctl_get_prkey(lun, i + softc->persis_offset) != 0)
8812					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8813		}
8814
8815		lun->flags &= ~CTL_LUN_PR_RESERVED;
8816		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8817		lun->res_type = 0;
8818		break;
8819
8820	case CTL_PR_PREEMPT:
8821		ctl_pro_preempt_other(lun, msg);
8822		break;
8823	case CTL_PR_CLEAR:
8824		lun->flags &= ~CTL_LUN_PR_RESERVED;
8825		lun->res_type = 0;
8826		lun->pr_key_count = 0;
8827		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8828
8829		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8830			if (ctl_get_prkey(lun, i) == 0)
8831				continue;
8832			ctl_clr_prkey(lun, i);
8833			ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8834		}
8835		lun->PRGeneration++;
8836		break;
8837	}
8838
8839	mtx_unlock(&lun->lun_lock);
8840}
8841
8842int
8843ctl_read_write(struct ctl_scsiio *ctsio)
8844{
8845	struct ctl_lun *lun;
8846	struct ctl_lba_len_flags *lbalen;
8847	uint64_t lba;
8848	uint32_t num_blocks;
8849	int flags, retval;
8850	int isread;
8851
8852	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8853
8854	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8855
8856	flags = 0;
8857	retval = CTL_RETVAL_COMPLETE;
8858
8859	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8860	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8861	switch (ctsio->cdb[0]) {
8862	case READ_6:
8863	case WRITE_6: {
8864		struct scsi_rw_6 *cdb;
8865
8866		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8867
8868		lba = scsi_3btoul(cdb->addr);
8869		/* only 5 bits are valid in the most significant address byte */
8870		lba &= 0x1fffff;
8871		num_blocks = cdb->length;
8872		/*
8873		 * This is correct according to SBC-2.
8874		 */
8875		if (num_blocks == 0)
8876			num_blocks = 256;
8877		break;
8878	}
8879	case READ_10:
8880	case WRITE_10: {
8881		struct scsi_rw_10 *cdb;
8882
8883		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8884		if (cdb->byte2 & SRW10_FUA)
8885			flags |= CTL_LLF_FUA;
8886		if (cdb->byte2 & SRW10_DPO)
8887			flags |= CTL_LLF_DPO;
8888		lba = scsi_4btoul(cdb->addr);
8889		num_blocks = scsi_2btoul(cdb->length);
8890		break;
8891	}
8892	case WRITE_VERIFY_10: {
8893		struct scsi_write_verify_10 *cdb;
8894
8895		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8896		flags |= CTL_LLF_FUA;
8897		if (cdb->byte2 & SWV_DPO)
8898			flags |= CTL_LLF_DPO;
8899		lba = scsi_4btoul(cdb->addr);
8900		num_blocks = scsi_2btoul(cdb->length);
8901		break;
8902	}
8903	case READ_12:
8904	case WRITE_12: {
8905		struct scsi_rw_12 *cdb;
8906
8907		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8908		if (cdb->byte2 & SRW12_FUA)
8909			flags |= CTL_LLF_FUA;
8910		if (cdb->byte2 & SRW12_DPO)
8911			flags |= CTL_LLF_DPO;
8912		lba = scsi_4btoul(cdb->addr);
8913		num_blocks = scsi_4btoul(cdb->length);
8914		break;
8915	}
8916	case WRITE_VERIFY_12: {
8917		struct scsi_write_verify_12 *cdb;
8918
8919		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8920		flags |= CTL_LLF_FUA;
8921		if (cdb->byte2 & SWV_DPO)
8922			flags |= CTL_LLF_DPO;
8923		lba = scsi_4btoul(cdb->addr);
8924		num_blocks = scsi_4btoul(cdb->length);
8925		break;
8926	}
8927	case READ_16:
8928	case WRITE_16: {
8929		struct scsi_rw_16 *cdb;
8930
8931		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8932		if (cdb->byte2 & SRW12_FUA)
8933			flags |= CTL_LLF_FUA;
8934		if (cdb->byte2 & SRW12_DPO)
8935			flags |= CTL_LLF_DPO;
8936		lba = scsi_8btou64(cdb->addr);
8937		num_blocks = scsi_4btoul(cdb->length);
8938		break;
8939	}
8940	case WRITE_ATOMIC_16: {
8941		struct scsi_rw_16 *cdb;
8942
8943		if (lun->be_lun->atomicblock == 0) {
8944			ctl_set_invalid_opcode(ctsio);
8945			ctl_done((union ctl_io *)ctsio);
8946			return (CTL_RETVAL_COMPLETE);
8947		}
8948
8949		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8950		if (cdb->byte2 & SRW12_FUA)
8951			flags |= CTL_LLF_FUA;
8952		if (cdb->byte2 & SRW12_DPO)
8953			flags |= CTL_LLF_DPO;
8954		lba = scsi_8btou64(cdb->addr);
8955		num_blocks = scsi_4btoul(cdb->length);
8956		if (num_blocks > lun->be_lun->atomicblock) {
8957			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8958			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8959			    /*bit*/ 0);
8960			ctl_done((union ctl_io *)ctsio);
8961			return (CTL_RETVAL_COMPLETE);
8962		}
8963		break;
8964	}
8965	case WRITE_VERIFY_16: {
8966		struct scsi_write_verify_16 *cdb;
8967
8968		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8969		flags |= CTL_LLF_FUA;
8970		if (cdb->byte2 & SWV_DPO)
8971			flags |= CTL_LLF_DPO;
8972		lba = scsi_8btou64(cdb->addr);
8973		num_blocks = scsi_4btoul(cdb->length);
8974		break;
8975	}
8976	default:
8977		/*
8978		 * We got a command we don't support.  This shouldn't
8979		 * happen, commands should be filtered out above us.
8980		 */
8981		ctl_set_invalid_opcode(ctsio);
8982		ctl_done((union ctl_io *)ctsio);
8983
8984		return (CTL_RETVAL_COMPLETE);
8985		break; /* NOTREACHED */
8986	}
8987
8988	/*
8989	 * The first check is to make sure we're in bounds, the second
8990	 * check is to catch wrap-around problems.  If the lba + num blocks
8991	 * is less than the lba, then we've wrapped around and the block
8992	 * range is invalid anyway.
8993	 */
8994	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8995	 || ((lba + num_blocks) < lba)) {
8996		ctl_set_lba_out_of_range(ctsio);
8997		ctl_done((union ctl_io *)ctsio);
8998		return (CTL_RETVAL_COMPLETE);
8999	}
9000
9001	/*
9002	 * According to SBC-3, a transfer length of 0 is not an error.
9003	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
9004	 * translates to 256 blocks for those commands.
9005	 */
9006	if (num_blocks == 0) {
9007		ctl_set_success(ctsio);
9008		ctl_done((union ctl_io *)ctsio);
9009		return (CTL_RETVAL_COMPLETE);
9010	}
9011
9012	/* Set FUA and/or DPO if caches are disabled. */
9013	if (isread) {
9014		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9015		    SCP_RCD) != 0)
9016			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9017	} else {
9018		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9019		    SCP_WCE) == 0)
9020			flags |= CTL_LLF_FUA;
9021	}
9022
9023	lbalen = (struct ctl_lba_len_flags *)
9024	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9025	lbalen->lba = lba;
9026	lbalen->len = num_blocks;
9027	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9028
9029	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9030	ctsio->kern_rel_offset = 0;
9031
9032	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9033
9034	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9035
9036	return (retval);
9037}
9038
9039static int
9040ctl_cnw_cont(union ctl_io *io)
9041{
9042	struct ctl_scsiio *ctsio;
9043	struct ctl_lun *lun;
9044	struct ctl_lba_len_flags *lbalen;
9045	int retval;
9046
9047	ctsio = &io->scsiio;
9048	ctsio->io_hdr.status = CTL_STATUS_NONE;
9049	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9050	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9051	lbalen = (struct ctl_lba_len_flags *)
9052	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9053	lbalen->flags &= ~CTL_LLF_COMPARE;
9054	lbalen->flags |= CTL_LLF_WRITE;
9055
9056	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9057	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9058	return (retval);
9059}
9060
9061int
9062ctl_cnw(struct ctl_scsiio *ctsio)
9063{
9064	struct ctl_lun *lun;
9065	struct ctl_lba_len_flags *lbalen;
9066	uint64_t lba;
9067	uint32_t num_blocks;
9068	int flags, retval;
9069
9070	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9071
9072	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9073
9074	flags = 0;
9075	retval = CTL_RETVAL_COMPLETE;
9076
9077	switch (ctsio->cdb[0]) {
9078	case COMPARE_AND_WRITE: {
9079		struct scsi_compare_and_write *cdb;
9080
9081		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9082		if (cdb->byte2 & SRW10_FUA)
9083			flags |= CTL_LLF_FUA;
9084		if (cdb->byte2 & SRW10_DPO)
9085			flags |= CTL_LLF_DPO;
9086		lba = scsi_8btou64(cdb->addr);
9087		num_blocks = cdb->length;
9088		break;
9089	}
9090	default:
9091		/*
9092		 * We got a command we don't support.  This shouldn't
9093		 * happen, commands should be filtered out above us.
9094		 */
9095		ctl_set_invalid_opcode(ctsio);
9096		ctl_done((union ctl_io *)ctsio);
9097
9098		return (CTL_RETVAL_COMPLETE);
9099		break; /* NOTREACHED */
9100	}
9101
9102	/*
9103	 * The first check is to make sure we're in bounds, the second
9104	 * check is to catch wrap-around problems.  If the lba + num blocks
9105	 * is less than the lba, then we've wrapped around and the block
9106	 * range is invalid anyway.
9107	 */
9108	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9109	 || ((lba + num_blocks) < lba)) {
9110		ctl_set_lba_out_of_range(ctsio);
9111		ctl_done((union ctl_io *)ctsio);
9112		return (CTL_RETVAL_COMPLETE);
9113	}
9114
9115	/*
9116	 * According to SBC-3, a transfer length of 0 is not an error.
9117	 */
9118	if (num_blocks == 0) {
9119		ctl_set_success(ctsio);
9120		ctl_done((union ctl_io *)ctsio);
9121		return (CTL_RETVAL_COMPLETE);
9122	}
9123
9124	/* Set FUA if write cache is disabled. */
9125	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9126	    SCP_WCE) == 0)
9127		flags |= CTL_LLF_FUA;
9128
9129	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9130	ctsio->kern_rel_offset = 0;
9131
9132	/*
9133	 * Set the IO_CONT flag, so that if this I/O gets passed to
9134	 * ctl_data_submit_done(), it'll get passed back to
9135	 * ctl_ctl_cnw_cont() for further processing.
9136	 */
9137	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9138	ctsio->io_cont = ctl_cnw_cont;
9139
9140	lbalen = (struct ctl_lba_len_flags *)
9141	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9142	lbalen->lba = lba;
9143	lbalen->len = num_blocks;
9144	lbalen->flags = CTL_LLF_COMPARE | flags;
9145
9146	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9147	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9148	return (retval);
9149}
9150
9151int
9152ctl_verify(struct ctl_scsiio *ctsio)
9153{
9154	struct ctl_lun *lun;
9155	struct ctl_lba_len_flags *lbalen;
9156	uint64_t lba;
9157	uint32_t num_blocks;
9158	int bytchk, flags;
9159	int retval;
9160
9161	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9162
9163	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9164
9165	bytchk = 0;
9166	flags = CTL_LLF_FUA;
9167	retval = CTL_RETVAL_COMPLETE;
9168
9169	switch (ctsio->cdb[0]) {
9170	case VERIFY_10: {
9171		struct scsi_verify_10 *cdb;
9172
9173		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9174		if (cdb->byte2 & SVFY_BYTCHK)
9175			bytchk = 1;
9176		if (cdb->byte2 & SVFY_DPO)
9177			flags |= CTL_LLF_DPO;
9178		lba = scsi_4btoul(cdb->addr);
9179		num_blocks = scsi_2btoul(cdb->length);
9180		break;
9181	}
9182	case VERIFY_12: {
9183		struct scsi_verify_12 *cdb;
9184
9185		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9186		if (cdb->byte2 & SVFY_BYTCHK)
9187			bytchk = 1;
9188		if (cdb->byte2 & SVFY_DPO)
9189			flags |= CTL_LLF_DPO;
9190		lba = scsi_4btoul(cdb->addr);
9191		num_blocks = scsi_4btoul(cdb->length);
9192		break;
9193	}
9194	case VERIFY_16: {
9195		struct scsi_rw_16 *cdb;
9196
9197		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9198		if (cdb->byte2 & SVFY_BYTCHK)
9199			bytchk = 1;
9200		if (cdb->byte2 & SVFY_DPO)
9201			flags |= CTL_LLF_DPO;
9202		lba = scsi_8btou64(cdb->addr);
9203		num_blocks = scsi_4btoul(cdb->length);
9204		break;
9205	}
9206	default:
9207		/*
9208		 * We got a command we don't support.  This shouldn't
9209		 * happen, commands should be filtered out above us.
9210		 */
9211		ctl_set_invalid_opcode(ctsio);
9212		ctl_done((union ctl_io *)ctsio);
9213		return (CTL_RETVAL_COMPLETE);
9214	}
9215
9216	/*
9217	 * The first check is to make sure we're in bounds, the second
9218	 * check is to catch wrap-around problems.  If the lba + num blocks
9219	 * is less than the lba, then we've wrapped around and the block
9220	 * range is invalid anyway.
9221	 */
9222	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9223	 || ((lba + num_blocks) < lba)) {
9224		ctl_set_lba_out_of_range(ctsio);
9225		ctl_done((union ctl_io *)ctsio);
9226		return (CTL_RETVAL_COMPLETE);
9227	}
9228
9229	/*
9230	 * According to SBC-3, a transfer length of 0 is not an error.
9231	 */
9232	if (num_blocks == 0) {
9233		ctl_set_success(ctsio);
9234		ctl_done((union ctl_io *)ctsio);
9235		return (CTL_RETVAL_COMPLETE);
9236	}
9237
9238	lbalen = (struct ctl_lba_len_flags *)
9239	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9240	lbalen->lba = lba;
9241	lbalen->len = num_blocks;
9242	if (bytchk) {
9243		lbalen->flags = CTL_LLF_COMPARE | flags;
9244		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9245	} else {
9246		lbalen->flags = CTL_LLF_VERIFY | flags;
9247		ctsio->kern_total_len = 0;
9248	}
9249	ctsio->kern_rel_offset = 0;
9250
9251	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9252	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9253	return (retval);
9254}
9255
9256int
9257ctl_report_luns(struct ctl_scsiio *ctsio)
9258{
9259	struct ctl_softc *softc = control_softc;
9260	struct scsi_report_luns *cdb;
9261	struct scsi_report_luns_data *lun_data;
9262	struct ctl_lun *lun, *request_lun;
9263	int num_luns, retval;
9264	uint32_t alloc_len, lun_datalen;
9265	int num_filled, well_known;
9266	uint32_t initidx, targ_lun_id, lun_id;
9267
9268	retval = CTL_RETVAL_COMPLETE;
9269	well_known = 0;
9270
9271	cdb = (struct scsi_report_luns *)ctsio->cdb;
9272
9273	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9274
9275	mtx_lock(&softc->ctl_lock);
9276	num_luns = softc->num_luns;
9277	mtx_unlock(&softc->ctl_lock);
9278
9279	switch (cdb->select_report) {
9280	case RPL_REPORT_DEFAULT:
9281	case RPL_REPORT_ALL:
9282		break;
9283	case RPL_REPORT_WELLKNOWN:
9284		well_known = 1;
9285		num_luns = 0;
9286		break;
9287	default:
9288		ctl_set_invalid_field(ctsio,
9289				      /*sks_valid*/ 1,
9290				      /*command*/ 1,
9291				      /*field*/ 2,
9292				      /*bit_valid*/ 0,
9293				      /*bit*/ 0);
9294		ctl_done((union ctl_io *)ctsio);
9295		return (retval);
9296		break; /* NOTREACHED */
9297	}
9298
9299	alloc_len = scsi_4btoul(cdb->length);
9300	/*
9301	 * The initiator has to allocate at least 16 bytes for this request,
9302	 * so he can at least get the header and the first LUN.  Otherwise
9303	 * we reject the request (per SPC-3 rev 14, section 6.21).
9304	 */
9305	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9306	    sizeof(struct scsi_report_luns_lundata))) {
9307		ctl_set_invalid_field(ctsio,
9308				      /*sks_valid*/ 1,
9309				      /*command*/ 1,
9310				      /*field*/ 6,
9311				      /*bit_valid*/ 0,
9312				      /*bit*/ 0);
9313		ctl_done((union ctl_io *)ctsio);
9314		return (retval);
9315	}
9316
9317	request_lun = (struct ctl_lun *)
9318		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9319
9320	lun_datalen = sizeof(*lun_data) +
9321		(num_luns * sizeof(struct scsi_report_luns_lundata));
9322
9323	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9324	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9325	ctsio->kern_sg_entries = 0;
9326
9327	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9328
9329	mtx_lock(&softc->ctl_lock);
9330	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9331		lun_id = ctl_map_lun(softc, ctsio->io_hdr.nexus.targ_port,
9332		    targ_lun_id);
9333		if (lun_id >= CTL_MAX_LUNS)
9334			continue;
9335		lun = softc->ctl_luns[lun_id];
9336		if (lun == NULL)
9337			continue;
9338
9339		if (targ_lun_id <= 0xff) {
9340			/*
9341			 * Peripheral addressing method, bus number 0.
9342			 */
9343			lun_data->luns[num_filled].lundata[0] =
9344				RPL_LUNDATA_ATYP_PERIPH;
9345			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9346			num_filled++;
9347		} else if (targ_lun_id <= 0x3fff) {
9348			/*
9349			 * Flat addressing method.
9350			 */
9351			lun_data->luns[num_filled].lundata[0] =
9352				RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9353			lun_data->luns[num_filled].lundata[1] =
9354				(targ_lun_id & 0xff);
9355			num_filled++;
9356		} else if (targ_lun_id <= 0xffffff) {
9357			/*
9358			 * Extended flat addressing method.
9359			 */
9360			lun_data->luns[num_filled].lundata[0] =
9361			    RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9362			scsi_ulto3b(targ_lun_id,
9363			    &lun_data->luns[num_filled].lundata[1]);
9364			num_filled++;
9365		} else {
9366			printf("ctl_report_luns: bogus LUN number %jd, "
9367			       "skipping\n", (intmax_t)targ_lun_id);
9368		}
9369		/*
9370		 * According to SPC-3, rev 14 section 6.21:
9371		 *
9372		 * "The execution of a REPORT LUNS command to any valid and
9373		 * installed logical unit shall clear the REPORTED LUNS DATA
9374		 * HAS CHANGED unit attention condition for all logical
9375		 * units of that target with respect to the requesting
9376		 * initiator. A valid and installed logical unit is one
9377		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9378		 * INQUIRY data (see 6.4.2)."
9379		 *
9380		 * If request_lun is NULL, the LUN this report luns command
9381		 * was issued to is either disabled or doesn't exist. In that
9382		 * case, we shouldn't clear any pending lun change unit
9383		 * attention.
9384		 */
9385		if (request_lun != NULL) {
9386			mtx_lock(&lun->lun_lock);
9387			ctl_clr_ua(lun, initidx, CTL_UA_RES_RELEASE);
9388			mtx_unlock(&lun->lun_lock);
9389		}
9390	}
9391	mtx_unlock(&softc->ctl_lock);
9392
9393	/*
9394	 * It's quite possible that we've returned fewer LUNs than we allocated
9395	 * space for.  Trim it.
9396	 */
9397	lun_datalen = sizeof(*lun_data) +
9398		(num_filled * sizeof(struct scsi_report_luns_lundata));
9399
9400	if (lun_datalen < alloc_len) {
9401		ctsio->residual = alloc_len - lun_datalen;
9402		ctsio->kern_data_len = lun_datalen;
9403		ctsio->kern_total_len = lun_datalen;
9404	} else {
9405		ctsio->residual = 0;
9406		ctsio->kern_data_len = alloc_len;
9407		ctsio->kern_total_len = alloc_len;
9408	}
9409	ctsio->kern_data_resid = 0;
9410	ctsio->kern_rel_offset = 0;
9411	ctsio->kern_sg_entries = 0;
9412
9413	/*
9414	 * We set this to the actual data length, regardless of how much
9415	 * space we actually have to return results.  If the user looks at
9416	 * this value, he'll know whether or not he allocated enough space
9417	 * and reissue the command if necessary.  We don't support well
9418	 * known logical units, so if the user asks for that, return none.
9419	 */
9420	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9421
9422	/*
9423	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9424	 * this request.
9425	 */
9426	ctl_set_success(ctsio);
9427	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9428	ctsio->be_move_done = ctl_config_move_done;
9429	ctl_datamove((union ctl_io *)ctsio);
9430	return (retval);
9431}
9432
9433int
9434ctl_request_sense(struct ctl_scsiio *ctsio)
9435{
9436	struct scsi_request_sense *cdb;
9437	struct scsi_sense_data *sense_ptr;
9438	struct ctl_lun *lun;
9439	uint32_t initidx;
9440	int have_error;
9441	scsi_sense_data_type sense_format;
9442	ctl_ua_type ua_type;
9443
9444	cdb = (struct scsi_request_sense *)ctsio->cdb;
9445
9446	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9447
9448	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9449
9450	/*
9451	 * Determine which sense format the user wants.
9452	 */
9453	if (cdb->byte2 & SRS_DESC)
9454		sense_format = SSD_TYPE_DESC;
9455	else
9456		sense_format = SSD_TYPE_FIXED;
9457
9458	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9459	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9460	ctsio->kern_sg_entries = 0;
9461
9462	/*
9463	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9464	 * larger than the largest allowed value for the length field in the
9465	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9466	 */
9467	ctsio->residual = 0;
9468	ctsio->kern_data_len = cdb->length;
9469	ctsio->kern_total_len = cdb->length;
9470
9471	ctsio->kern_data_resid = 0;
9472	ctsio->kern_rel_offset = 0;
9473	ctsio->kern_sg_entries = 0;
9474
9475	/*
9476	 * If we don't have a LUN, we don't have any pending sense.
9477	 */
9478	if (lun == NULL)
9479		goto no_sense;
9480
9481	have_error = 0;
9482	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9483	/*
9484	 * Check for pending sense, and then for pending unit attentions.
9485	 * Pending sense gets returned first, then pending unit attentions.
9486	 */
9487	mtx_lock(&lun->lun_lock);
9488#ifdef CTL_WITH_CA
9489	if (ctl_is_set(lun->have_ca, initidx)) {
9490		scsi_sense_data_type stored_format;
9491
9492		/*
9493		 * Check to see which sense format was used for the stored
9494		 * sense data.
9495		 */
9496		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9497
9498		/*
9499		 * If the user requested a different sense format than the
9500		 * one we stored, then we need to convert it to the other
9501		 * format.  If we're going from descriptor to fixed format
9502		 * sense data, we may lose things in translation, depending
9503		 * on what options were used.
9504		 *
9505		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9506		 * for some reason we'll just copy it out as-is.
9507		 */
9508		if ((stored_format == SSD_TYPE_FIXED)
9509		 && (sense_format == SSD_TYPE_DESC))
9510			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9511			    &lun->pending_sense[initidx],
9512			    (struct scsi_sense_data_desc *)sense_ptr);
9513		else if ((stored_format == SSD_TYPE_DESC)
9514		      && (sense_format == SSD_TYPE_FIXED))
9515			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9516			    &lun->pending_sense[initidx],
9517			    (struct scsi_sense_data_fixed *)sense_ptr);
9518		else
9519			memcpy(sense_ptr, &lun->pending_sense[initidx],
9520			       MIN(sizeof(*sense_ptr),
9521			       sizeof(lun->pending_sense[initidx])));
9522
9523		ctl_clear_mask(lun->have_ca, initidx);
9524		have_error = 1;
9525	} else
9526#endif
9527	{
9528		ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9529		if (ua_type != CTL_UA_NONE)
9530			have_error = 1;
9531	}
9532	mtx_unlock(&lun->lun_lock);
9533
9534	/*
9535	 * We already have a pending error, return it.
9536	 */
9537	if (have_error != 0) {
9538		/*
9539		 * We report the SCSI status as OK, since the status of the
9540		 * request sense command itself is OK.
9541		 * We report 0 for the sense length, because we aren't doing
9542		 * autosense in this case.  We're reporting sense as
9543		 * parameter data.
9544		 */
9545		ctl_set_success(ctsio);
9546		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9547		ctsio->be_move_done = ctl_config_move_done;
9548		ctl_datamove((union ctl_io *)ctsio);
9549		return (CTL_RETVAL_COMPLETE);
9550	}
9551
9552no_sense:
9553
9554	/*
9555	 * No sense information to report, so we report that everything is
9556	 * okay.
9557	 */
9558	ctl_set_sense_data(sense_ptr,
9559			   lun,
9560			   sense_format,
9561			   /*current_error*/ 1,
9562			   /*sense_key*/ SSD_KEY_NO_SENSE,
9563			   /*asc*/ 0x00,
9564			   /*ascq*/ 0x00,
9565			   SSD_ELEM_NONE);
9566
9567	/*
9568	 * We report 0 for the sense length, because we aren't doing
9569	 * autosense in this case.  We're reporting sense as parameter data.
9570	 */
9571	ctl_set_success(ctsio);
9572	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9573	ctsio->be_move_done = ctl_config_move_done;
9574	ctl_datamove((union ctl_io *)ctsio);
9575	return (CTL_RETVAL_COMPLETE);
9576}
9577
9578int
9579ctl_tur(struct ctl_scsiio *ctsio)
9580{
9581
9582	CTL_DEBUG_PRINT(("ctl_tur\n"));
9583
9584	ctl_set_success(ctsio);
9585	ctl_done((union ctl_io *)ctsio);
9586
9587	return (CTL_RETVAL_COMPLETE);
9588}
9589
9590#ifdef notyet
9591static int
9592ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9593{
9594
9595}
9596#endif
9597
9598static int
9599ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9600{
9601	struct scsi_vpd_supported_pages *pages;
9602	int sup_page_size;
9603	struct ctl_lun *lun;
9604	int p;
9605
9606	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9607
9608	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9609	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9610	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9611	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9612	ctsio->kern_sg_entries = 0;
9613
9614	if (sup_page_size < alloc_len) {
9615		ctsio->residual = alloc_len - sup_page_size;
9616		ctsio->kern_data_len = sup_page_size;
9617		ctsio->kern_total_len = sup_page_size;
9618	} else {
9619		ctsio->residual = 0;
9620		ctsio->kern_data_len = alloc_len;
9621		ctsio->kern_total_len = alloc_len;
9622	}
9623	ctsio->kern_data_resid = 0;
9624	ctsio->kern_rel_offset = 0;
9625	ctsio->kern_sg_entries = 0;
9626
9627	/*
9628	 * The control device is always connected.  The disk device, on the
9629	 * other hand, may not be online all the time.  Need to change this
9630	 * to figure out whether the disk device is actually online or not.
9631	 */
9632	if (lun != NULL)
9633		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9634				lun->be_lun->lun_type;
9635	else
9636		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9637
9638	p = 0;
9639	/* Supported VPD pages */
9640	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9641	/* Serial Number */
9642	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9643	/* Device Identification */
9644	pages->page_list[p++] = SVPD_DEVICE_ID;
9645	/* Extended INQUIRY Data */
9646	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9647	/* Mode Page Policy */
9648	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9649	/* SCSI Ports */
9650	pages->page_list[p++] = SVPD_SCSI_PORTS;
9651	/* Third-party Copy */
9652	pages->page_list[p++] = SVPD_SCSI_TPC;
9653	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9654		/* Block limits */
9655		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9656		/* Block Device Characteristics */
9657		pages->page_list[p++] = SVPD_BDC;
9658		/* Logical Block Provisioning */
9659		pages->page_list[p++] = SVPD_LBP;
9660	}
9661	pages->length = p;
9662
9663	ctl_set_success(ctsio);
9664	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9665	ctsio->be_move_done = ctl_config_move_done;
9666	ctl_datamove((union ctl_io *)ctsio);
9667	return (CTL_RETVAL_COMPLETE);
9668}
9669
9670static int
9671ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9672{
9673	struct scsi_vpd_unit_serial_number *sn_ptr;
9674	struct ctl_lun *lun;
9675	int data_len;
9676
9677	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9678
9679	data_len = 4 + CTL_SN_LEN;
9680	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9681	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9682	if (data_len < alloc_len) {
9683		ctsio->residual = alloc_len - data_len;
9684		ctsio->kern_data_len = data_len;
9685		ctsio->kern_total_len = data_len;
9686	} else {
9687		ctsio->residual = 0;
9688		ctsio->kern_data_len = alloc_len;
9689		ctsio->kern_total_len = alloc_len;
9690	}
9691	ctsio->kern_data_resid = 0;
9692	ctsio->kern_rel_offset = 0;
9693	ctsio->kern_sg_entries = 0;
9694
9695	/*
9696	 * The control device is always connected.  The disk device, on the
9697	 * other hand, may not be online all the time.  Need to change this
9698	 * to figure out whether the disk device is actually online or not.
9699	 */
9700	if (lun != NULL)
9701		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9702				  lun->be_lun->lun_type;
9703	else
9704		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9705
9706	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9707	sn_ptr->length = CTL_SN_LEN;
9708	/*
9709	 * If we don't have a LUN, we just leave the serial number as
9710	 * all spaces.
9711	 */
9712	if (lun != NULL) {
9713		strncpy((char *)sn_ptr->serial_num,
9714			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9715	} else
9716		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9717
9718	ctl_set_success(ctsio);
9719	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9720	ctsio->be_move_done = ctl_config_move_done;
9721	ctl_datamove((union ctl_io *)ctsio);
9722	return (CTL_RETVAL_COMPLETE);
9723}
9724
9725
9726static int
9727ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9728{
9729	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9730	struct ctl_lun *lun;
9731	int data_len;
9732
9733	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9734
9735	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9736	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9737	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9738	ctsio->kern_sg_entries = 0;
9739
9740	if (data_len < alloc_len) {
9741		ctsio->residual = alloc_len - data_len;
9742		ctsio->kern_data_len = data_len;
9743		ctsio->kern_total_len = data_len;
9744	} else {
9745		ctsio->residual = 0;
9746		ctsio->kern_data_len = alloc_len;
9747		ctsio->kern_total_len = alloc_len;
9748	}
9749	ctsio->kern_data_resid = 0;
9750	ctsio->kern_rel_offset = 0;
9751	ctsio->kern_sg_entries = 0;
9752
9753	/*
9754	 * The control device is always connected.  The disk device, on the
9755	 * other hand, may not be online all the time.
9756	 */
9757	if (lun != NULL)
9758		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9759				     lun->be_lun->lun_type;
9760	else
9761		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9762	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9763	eid_ptr->page_length = data_len - 4;
9764	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9765	eid_ptr->flags3 = SVPD_EID_V_SUP;
9766
9767	ctl_set_success(ctsio);
9768	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9769	ctsio->be_move_done = ctl_config_move_done;
9770	ctl_datamove((union ctl_io *)ctsio);
9771	return (CTL_RETVAL_COMPLETE);
9772}
9773
9774static int
9775ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9776{
9777	struct scsi_vpd_mode_page_policy *mpp_ptr;
9778	struct ctl_lun *lun;
9779	int data_len;
9780
9781	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9782
9783	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9784	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9785
9786	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9787	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9788	ctsio->kern_sg_entries = 0;
9789
9790	if (data_len < alloc_len) {
9791		ctsio->residual = alloc_len - data_len;
9792		ctsio->kern_data_len = data_len;
9793		ctsio->kern_total_len = data_len;
9794	} else {
9795		ctsio->residual = 0;
9796		ctsio->kern_data_len = alloc_len;
9797		ctsio->kern_total_len = alloc_len;
9798	}
9799	ctsio->kern_data_resid = 0;
9800	ctsio->kern_rel_offset = 0;
9801	ctsio->kern_sg_entries = 0;
9802
9803	/*
9804	 * The control device is always connected.  The disk device, on the
9805	 * other hand, may not be online all the time.
9806	 */
9807	if (lun != NULL)
9808		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9809				     lun->be_lun->lun_type;
9810	else
9811		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9812	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9813	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9814	mpp_ptr->descr[0].page_code = 0x3f;
9815	mpp_ptr->descr[0].subpage_code = 0xff;
9816	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9817
9818	ctl_set_success(ctsio);
9819	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9820	ctsio->be_move_done = ctl_config_move_done;
9821	ctl_datamove((union ctl_io *)ctsio);
9822	return (CTL_RETVAL_COMPLETE);
9823}
9824
9825static int
9826ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9827{
9828	struct scsi_vpd_device_id *devid_ptr;
9829	struct scsi_vpd_id_descriptor *desc;
9830	struct ctl_softc *softc;
9831	struct ctl_lun *lun;
9832	struct ctl_port *port;
9833	int data_len;
9834	uint8_t proto;
9835
9836	softc = control_softc;
9837
9838	port = softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9839	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9840
9841	data_len = sizeof(struct scsi_vpd_device_id) +
9842	    sizeof(struct scsi_vpd_id_descriptor) +
9843		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9844	    sizeof(struct scsi_vpd_id_descriptor) +
9845		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9846	if (lun && lun->lun_devid)
9847		data_len += lun->lun_devid->len;
9848	if (port->port_devid)
9849		data_len += port->port_devid->len;
9850	if (port->target_devid)
9851		data_len += port->target_devid->len;
9852
9853	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9854	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9855	ctsio->kern_sg_entries = 0;
9856
9857	if (data_len < alloc_len) {
9858		ctsio->residual = alloc_len - data_len;
9859		ctsio->kern_data_len = data_len;
9860		ctsio->kern_total_len = data_len;
9861	} else {
9862		ctsio->residual = 0;
9863		ctsio->kern_data_len = alloc_len;
9864		ctsio->kern_total_len = alloc_len;
9865	}
9866	ctsio->kern_data_resid = 0;
9867	ctsio->kern_rel_offset = 0;
9868	ctsio->kern_sg_entries = 0;
9869
9870	/*
9871	 * The control device is always connected.  The disk device, on the
9872	 * other hand, may not be online all the time.
9873	 */
9874	if (lun != NULL)
9875		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9876				     lun->be_lun->lun_type;
9877	else
9878		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9879	devid_ptr->page_code = SVPD_DEVICE_ID;
9880	scsi_ulto2b(data_len - 4, devid_ptr->length);
9881
9882	if (port->port_type == CTL_PORT_FC)
9883		proto = SCSI_PROTO_FC << 4;
9884	else if (port->port_type == CTL_PORT_ISCSI)
9885		proto = SCSI_PROTO_ISCSI << 4;
9886	else
9887		proto = SCSI_PROTO_SPI << 4;
9888	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9889
9890	/*
9891	 * We're using a LUN association here.  i.e., this device ID is a
9892	 * per-LUN identifier.
9893	 */
9894	if (lun && lun->lun_devid) {
9895		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9896		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9897		    lun->lun_devid->len);
9898	}
9899
9900	/*
9901	 * This is for the WWPN which is a port association.
9902	 */
9903	if (port->port_devid) {
9904		memcpy(desc, port->port_devid->data, port->port_devid->len);
9905		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9906		    port->port_devid->len);
9907	}
9908
9909	/*
9910	 * This is for the Relative Target Port(type 4h) identifier
9911	 */
9912	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9913	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9914	    SVPD_ID_TYPE_RELTARG;
9915	desc->length = 4;
9916	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9917	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9918	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9919
9920	/*
9921	 * This is for the Target Port Group(type 5h) identifier
9922	 */
9923	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9924	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9925	    SVPD_ID_TYPE_TPORTGRP;
9926	desc->length = 4;
9927	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
9928	    &desc->identifier[2]);
9929	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9930	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9931
9932	/*
9933	 * This is for the Target identifier
9934	 */
9935	if (port->target_devid) {
9936		memcpy(desc, port->target_devid->data, port->target_devid->len);
9937	}
9938
9939	ctl_set_success(ctsio);
9940	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9941	ctsio->be_move_done = ctl_config_move_done;
9942	ctl_datamove((union ctl_io *)ctsio);
9943	return (CTL_RETVAL_COMPLETE);
9944}
9945
9946static int
9947ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9948{
9949	struct ctl_softc *softc = control_softc;
9950	struct scsi_vpd_scsi_ports *sp;
9951	struct scsi_vpd_port_designation *pd;
9952	struct scsi_vpd_port_designation_cont *pdc;
9953	struct ctl_lun *lun;
9954	struct ctl_port *port;
9955	int data_len, num_target_ports, iid_len, id_len, g, pg, p;
9956	int num_target_port_groups;
9957
9958	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9959
9960	if (softc->is_single)
9961		num_target_port_groups = 1;
9962	else
9963		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
9964	num_target_ports = 0;
9965	iid_len = 0;
9966	id_len = 0;
9967	mtx_lock(&softc->ctl_lock);
9968	STAILQ_FOREACH(port, &softc->port_list, links) {
9969		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9970			continue;
9971		if (lun != NULL &&
9972		    ctl_map_lun_back(softc, port->targ_port, lun->lun) >=
9973		    CTL_MAX_LUNS)
9974			continue;
9975		num_target_ports++;
9976		if (port->init_devid)
9977			iid_len += port->init_devid->len;
9978		if (port->port_devid)
9979			id_len += port->port_devid->len;
9980	}
9981	mtx_unlock(&softc->ctl_lock);
9982
9983	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
9984	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9985	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9986	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9987	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9988	ctsio->kern_sg_entries = 0;
9989
9990	if (data_len < alloc_len) {
9991		ctsio->residual = alloc_len - data_len;
9992		ctsio->kern_data_len = data_len;
9993		ctsio->kern_total_len = data_len;
9994	} else {
9995		ctsio->residual = 0;
9996		ctsio->kern_data_len = alloc_len;
9997		ctsio->kern_total_len = alloc_len;
9998	}
9999	ctsio->kern_data_resid = 0;
10000	ctsio->kern_rel_offset = 0;
10001	ctsio->kern_sg_entries = 0;
10002
10003	/*
10004	 * The control device is always connected.  The disk device, on the
10005	 * other hand, may not be online all the time.  Need to change this
10006	 * to figure out whether the disk device is actually online or not.
10007	 */
10008	if (lun != NULL)
10009		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10010				  lun->be_lun->lun_type;
10011	else
10012		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10013
10014	sp->page_code = SVPD_SCSI_PORTS;
10015	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10016	    sp->page_length);
10017	pd = &sp->design[0];
10018
10019	mtx_lock(&softc->ctl_lock);
10020	pg = softc->port_offset / CTL_MAX_PORTS;
10021	for (g = 0; g < num_target_port_groups; g++) {
10022		STAILQ_FOREACH(port, &softc->port_list, links) {
10023			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10024				continue;
10025			if (lun != NULL &&
10026			    ctl_map_lun_back(softc, port->targ_port, lun->lun)
10027			    >= CTL_MAX_LUNS)
10028				continue;
10029			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10030			scsi_ulto2b(p, pd->relative_port_id);
10031			if (port->init_devid && g == pg) {
10032				iid_len = port->init_devid->len;
10033				memcpy(pd->initiator_transportid,
10034				    port->init_devid->data, port->init_devid->len);
10035			} else
10036				iid_len = 0;
10037			scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10038			pdc = (struct scsi_vpd_port_designation_cont *)
10039			    (&pd->initiator_transportid[iid_len]);
10040			if (port->port_devid && g == pg) {
10041				id_len = port->port_devid->len;
10042				memcpy(pdc->target_port_descriptors,
10043				    port->port_devid->data, port->port_devid->len);
10044			} else
10045				id_len = 0;
10046			scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10047			pd = (struct scsi_vpd_port_designation *)
10048			    ((uint8_t *)pdc->target_port_descriptors + id_len);
10049		}
10050	}
10051	mtx_unlock(&softc->ctl_lock);
10052
10053	ctl_set_success(ctsio);
10054	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10055	ctsio->be_move_done = ctl_config_move_done;
10056	ctl_datamove((union ctl_io *)ctsio);
10057	return (CTL_RETVAL_COMPLETE);
10058}
10059
10060static int
10061ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10062{
10063	struct scsi_vpd_block_limits *bl_ptr;
10064	struct ctl_lun *lun;
10065	int bs;
10066
10067	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10068
10069	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10070	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10071	ctsio->kern_sg_entries = 0;
10072
10073	if (sizeof(*bl_ptr) < alloc_len) {
10074		ctsio->residual = alloc_len - sizeof(*bl_ptr);
10075		ctsio->kern_data_len = sizeof(*bl_ptr);
10076		ctsio->kern_total_len = sizeof(*bl_ptr);
10077	} else {
10078		ctsio->residual = 0;
10079		ctsio->kern_data_len = alloc_len;
10080		ctsio->kern_total_len = alloc_len;
10081	}
10082	ctsio->kern_data_resid = 0;
10083	ctsio->kern_rel_offset = 0;
10084	ctsio->kern_sg_entries = 0;
10085
10086	/*
10087	 * The control device is always connected.  The disk device, on the
10088	 * other hand, may not be online all the time.  Need to change this
10089	 * to figure out whether the disk device is actually online or not.
10090	 */
10091	if (lun != NULL)
10092		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10093				  lun->be_lun->lun_type;
10094	else
10095		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10096
10097	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10098	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10099	bl_ptr->max_cmp_write_len = 0xff;
10100	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10101	if (lun != NULL) {
10102		bs = lun->be_lun->blocksize;
10103		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
10104		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10105			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10106			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10107			if (lun->be_lun->ublockexp != 0) {
10108				scsi_ulto4b((1 << lun->be_lun->ublockexp),
10109				    bl_ptr->opt_unmap_grain);
10110				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
10111				    bl_ptr->unmap_grain_align);
10112			}
10113		}
10114		scsi_ulto4b(lun->be_lun->atomicblock,
10115		    bl_ptr->max_atomic_transfer_length);
10116		scsi_ulto4b(0, bl_ptr->atomic_alignment);
10117		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10118	}
10119	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10120
10121	ctl_set_success(ctsio);
10122	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10123	ctsio->be_move_done = ctl_config_move_done;
10124	ctl_datamove((union ctl_io *)ctsio);
10125	return (CTL_RETVAL_COMPLETE);
10126}
10127
10128static int
10129ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10130{
10131	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10132	struct ctl_lun *lun;
10133	const char *value;
10134	u_int i;
10135
10136	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10137
10138	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10139	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10140	ctsio->kern_sg_entries = 0;
10141
10142	if (sizeof(*bdc_ptr) < alloc_len) {
10143		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10144		ctsio->kern_data_len = sizeof(*bdc_ptr);
10145		ctsio->kern_total_len = sizeof(*bdc_ptr);
10146	} else {
10147		ctsio->residual = 0;
10148		ctsio->kern_data_len = alloc_len;
10149		ctsio->kern_total_len = alloc_len;
10150	}
10151	ctsio->kern_data_resid = 0;
10152	ctsio->kern_rel_offset = 0;
10153	ctsio->kern_sg_entries = 0;
10154
10155	/*
10156	 * The control device is always connected.  The disk device, on the
10157	 * other hand, may not be online all the time.  Need to change this
10158	 * to figure out whether the disk device is actually online or not.
10159	 */
10160	if (lun != NULL)
10161		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10162				  lun->be_lun->lun_type;
10163	else
10164		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10165	bdc_ptr->page_code = SVPD_BDC;
10166	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10167	if (lun != NULL &&
10168	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10169		i = strtol(value, NULL, 0);
10170	else
10171		i = CTL_DEFAULT_ROTATION_RATE;
10172	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10173	if (lun != NULL &&
10174	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10175		i = strtol(value, NULL, 0);
10176	else
10177		i = 0;
10178	bdc_ptr->wab_wac_ff = (i & 0x0f);
10179	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10180
10181	ctl_set_success(ctsio);
10182	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10183	ctsio->be_move_done = ctl_config_move_done;
10184	ctl_datamove((union ctl_io *)ctsio);
10185	return (CTL_RETVAL_COMPLETE);
10186}
10187
10188static int
10189ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10190{
10191	struct scsi_vpd_logical_block_prov *lbp_ptr;
10192	struct ctl_lun *lun;
10193
10194	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10195
10196	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10197	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10198	ctsio->kern_sg_entries = 0;
10199
10200	if (sizeof(*lbp_ptr) < alloc_len) {
10201		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10202		ctsio->kern_data_len = sizeof(*lbp_ptr);
10203		ctsio->kern_total_len = sizeof(*lbp_ptr);
10204	} else {
10205		ctsio->residual = 0;
10206		ctsio->kern_data_len = alloc_len;
10207		ctsio->kern_total_len = alloc_len;
10208	}
10209	ctsio->kern_data_resid = 0;
10210	ctsio->kern_rel_offset = 0;
10211	ctsio->kern_sg_entries = 0;
10212
10213	/*
10214	 * The control device is always connected.  The disk device, on the
10215	 * other hand, may not be online all the time.  Need to change this
10216	 * to figure out whether the disk device is actually online or not.
10217	 */
10218	if (lun != NULL)
10219		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10220				  lun->be_lun->lun_type;
10221	else
10222		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10223
10224	lbp_ptr->page_code = SVPD_LBP;
10225	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10226	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10227	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10228		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10229		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10230		lbp_ptr->prov_type = SVPD_LBP_THIN;
10231	}
10232
10233	ctl_set_success(ctsio);
10234	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10235	ctsio->be_move_done = ctl_config_move_done;
10236	ctl_datamove((union ctl_io *)ctsio);
10237	return (CTL_RETVAL_COMPLETE);
10238}
10239
10240static int
10241ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10242{
10243	struct ctl_lun *lun;
10244	struct scsi_inquiry *cdb;
10245	int alloc_len, retval;
10246
10247	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10248	cdb = (struct scsi_inquiry *)ctsio->cdb;
10249	alloc_len = scsi_2btoul(cdb->length);
10250
10251	switch (cdb->page_code) {
10252	case SVPD_SUPPORTED_PAGES:
10253		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10254		break;
10255	case SVPD_UNIT_SERIAL_NUMBER:
10256		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10257		break;
10258	case SVPD_DEVICE_ID:
10259		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10260		break;
10261	case SVPD_EXTENDED_INQUIRY_DATA:
10262		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10263		break;
10264	case SVPD_MODE_PAGE_POLICY:
10265		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10266		break;
10267	case SVPD_SCSI_PORTS:
10268		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10269		break;
10270	case SVPD_SCSI_TPC:
10271		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10272		break;
10273	case SVPD_BLOCK_LIMITS:
10274		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10275			goto err;
10276		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10277		break;
10278	case SVPD_BDC:
10279		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10280			goto err;
10281		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10282		break;
10283	case SVPD_LBP:
10284		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10285			goto err;
10286		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10287		break;
10288	default:
10289err:
10290		ctl_set_invalid_field(ctsio,
10291				      /*sks_valid*/ 1,
10292				      /*command*/ 1,
10293				      /*field*/ 2,
10294				      /*bit_valid*/ 0,
10295				      /*bit*/ 0);
10296		ctl_done((union ctl_io *)ctsio);
10297		retval = CTL_RETVAL_COMPLETE;
10298		break;
10299	}
10300
10301	return (retval);
10302}
10303
10304static int
10305ctl_inquiry_std(struct ctl_scsiio *ctsio)
10306{
10307	struct scsi_inquiry_data *inq_ptr;
10308	struct scsi_inquiry *cdb;
10309	struct ctl_softc *softc;
10310	struct ctl_lun *lun;
10311	char *val;
10312	uint32_t alloc_len, data_len;
10313	ctl_port_type port_type;
10314
10315	softc = control_softc;
10316
10317	/*
10318	 * Figure out whether we're talking to a Fibre Channel port or not.
10319	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10320	 * SCSI front ends.
10321	 */
10322	port_type = softc->ctl_ports[
10323	    ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10324	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10325		port_type = CTL_PORT_SCSI;
10326
10327	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10328	cdb = (struct scsi_inquiry *)ctsio->cdb;
10329	alloc_len = scsi_2btoul(cdb->length);
10330
10331	/*
10332	 * We malloc the full inquiry data size here and fill it
10333	 * in.  If the user only asks for less, we'll give him
10334	 * that much.
10335	 */
10336	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10337	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10338	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10339	ctsio->kern_sg_entries = 0;
10340	ctsio->kern_data_resid = 0;
10341	ctsio->kern_rel_offset = 0;
10342
10343	if (data_len < alloc_len) {
10344		ctsio->residual = alloc_len - data_len;
10345		ctsio->kern_data_len = data_len;
10346		ctsio->kern_total_len = data_len;
10347	} else {
10348		ctsio->residual = 0;
10349		ctsio->kern_data_len = alloc_len;
10350		ctsio->kern_total_len = alloc_len;
10351	}
10352
10353	/*
10354	 * If we have a LUN configured, report it as connected.  Otherwise,
10355	 * report that it is offline or no device is supported, depending
10356	 * on the value of inquiry_pq_no_lun.
10357	 *
10358	 * According to the spec (SPC-4 r34), the peripheral qualifier
10359	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10360	 *
10361	 * "A peripheral device having the specified peripheral device type
10362	 * is not connected to this logical unit. However, the device
10363	 * server is capable of supporting the specified peripheral device
10364	 * type on this logical unit."
10365	 *
10366	 * According to the same spec, the peripheral qualifier
10367	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10368	 *
10369	 * "The device server is not capable of supporting a peripheral
10370	 * device on this logical unit. For this peripheral qualifier the
10371	 * peripheral device type shall be set to 1Fh. All other peripheral
10372	 * device type values are reserved for this peripheral qualifier."
10373	 *
10374	 * Given the text, it would seem that we probably want to report that
10375	 * the LUN is offline here.  There is no LUN connected, but we can
10376	 * support a LUN at the given LUN number.
10377	 *
10378	 * In the real world, though, it sounds like things are a little
10379	 * different:
10380	 *
10381	 * - Linux, when presented with a LUN with the offline peripheral
10382	 *   qualifier, will create an sg driver instance for it.  So when
10383	 *   you attach it to CTL, you wind up with a ton of sg driver
10384	 *   instances.  (One for every LUN that Linux bothered to probe.)
10385	 *   Linux does this despite the fact that it issues a REPORT LUNs
10386	 *   to LUN 0 to get the inventory of supported LUNs.
10387	 *
10388	 * - There is other anecdotal evidence (from Emulex folks) about
10389	 *   arrays that use the offline peripheral qualifier for LUNs that
10390	 *   are on the "passive" path in an active/passive array.
10391	 *
10392	 * So the solution is provide a hopefully reasonable default
10393	 * (return bad/no LUN) and allow the user to change the behavior
10394	 * with a tunable/sysctl variable.
10395	 */
10396	if (lun != NULL)
10397		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10398				  lun->be_lun->lun_type;
10399	else if (softc->inquiry_pq_no_lun == 0)
10400		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10401	else
10402		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10403
10404	/* RMB in byte 2 is 0 */
10405	inq_ptr->version = SCSI_REV_SPC4;
10406
10407	/*
10408	 * According to SAM-3, even if a device only supports a single
10409	 * level of LUN addressing, it should still set the HISUP bit:
10410	 *
10411	 * 4.9.1 Logical unit numbers overview
10412	 *
10413	 * All logical unit number formats described in this standard are
10414	 * hierarchical in structure even when only a single level in that
10415	 * hierarchy is used. The HISUP bit shall be set to one in the
10416	 * standard INQUIRY data (see SPC-2) when any logical unit number
10417	 * format described in this standard is used.  Non-hierarchical
10418	 * formats are outside the scope of this standard.
10419	 *
10420	 * Therefore we set the HiSup bit here.
10421	 *
10422	 * The reponse format is 2, per SPC-3.
10423	 */
10424	inq_ptr->response_format = SID_HiSup | 2;
10425
10426	inq_ptr->additional_length = data_len -
10427	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10428	CTL_DEBUG_PRINT(("additional_length = %d\n",
10429			 inq_ptr->additional_length));
10430
10431	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10432	/* 16 bit addressing */
10433	if (port_type == CTL_PORT_SCSI)
10434		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10435	/* XXX set the SID_MultiP bit here if we're actually going to
10436	   respond on multiple ports */
10437	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10438
10439	/* 16 bit data bus, synchronous transfers */
10440	if (port_type == CTL_PORT_SCSI)
10441		inq_ptr->flags = SID_WBus16 | SID_Sync;
10442	/*
10443	 * XXX KDM do we want to support tagged queueing on the control
10444	 * device at all?
10445	 */
10446	if ((lun == NULL)
10447	 || (lun->be_lun->lun_type != T_PROCESSOR))
10448		inq_ptr->flags |= SID_CmdQue;
10449	/*
10450	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10451	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10452	 * name and 4 bytes for the revision.
10453	 */
10454	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10455	    "vendor")) == NULL) {
10456		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10457	} else {
10458		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10459		strncpy(inq_ptr->vendor, val,
10460		    min(sizeof(inq_ptr->vendor), strlen(val)));
10461	}
10462	if (lun == NULL) {
10463		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10464		    sizeof(inq_ptr->product));
10465	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10466		switch (lun->be_lun->lun_type) {
10467		case T_DIRECT:
10468			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10469			    sizeof(inq_ptr->product));
10470			break;
10471		case T_PROCESSOR:
10472			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10473			    sizeof(inq_ptr->product));
10474			break;
10475		default:
10476			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10477			    sizeof(inq_ptr->product));
10478			break;
10479		}
10480	} else {
10481		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10482		strncpy(inq_ptr->product, val,
10483		    min(sizeof(inq_ptr->product), strlen(val)));
10484	}
10485
10486	/*
10487	 * XXX make this a macro somewhere so it automatically gets
10488	 * incremented when we make changes.
10489	 */
10490	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10491	    "revision")) == NULL) {
10492		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10493	} else {
10494		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10495		strncpy(inq_ptr->revision, val,
10496		    min(sizeof(inq_ptr->revision), strlen(val)));
10497	}
10498
10499	/*
10500	 * For parallel SCSI, we support double transition and single
10501	 * transition clocking.  We also support QAS (Quick Arbitration
10502	 * and Selection) and Information Unit transfers on both the
10503	 * control and array devices.
10504	 */
10505	if (port_type == CTL_PORT_SCSI)
10506		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10507				    SID_SPI_IUS;
10508
10509	/* SAM-5 (no version claimed) */
10510	scsi_ulto2b(0x00A0, inq_ptr->version1);
10511	/* SPC-4 (no version claimed) */
10512	scsi_ulto2b(0x0460, inq_ptr->version2);
10513	if (port_type == CTL_PORT_FC) {
10514		/* FCP-2 ANSI INCITS.350:2003 */
10515		scsi_ulto2b(0x0917, inq_ptr->version3);
10516	} else if (port_type == CTL_PORT_SCSI) {
10517		/* SPI-4 ANSI INCITS.362:200x */
10518		scsi_ulto2b(0x0B56, inq_ptr->version3);
10519	} else if (port_type == CTL_PORT_ISCSI) {
10520		/* iSCSI (no version claimed) */
10521		scsi_ulto2b(0x0960, inq_ptr->version3);
10522	} else if (port_type == CTL_PORT_SAS) {
10523		/* SAS (no version claimed) */
10524		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10525	}
10526
10527	if (lun == NULL) {
10528		/* SBC-4 (no version claimed) */
10529		scsi_ulto2b(0x0600, inq_ptr->version4);
10530	} else {
10531		switch (lun->be_lun->lun_type) {
10532		case T_DIRECT:
10533			/* SBC-4 (no version claimed) */
10534			scsi_ulto2b(0x0600, inq_ptr->version4);
10535			break;
10536		case T_PROCESSOR:
10537		default:
10538			break;
10539		}
10540	}
10541
10542	ctl_set_success(ctsio);
10543	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10544	ctsio->be_move_done = ctl_config_move_done;
10545	ctl_datamove((union ctl_io *)ctsio);
10546	return (CTL_RETVAL_COMPLETE);
10547}
10548
10549int
10550ctl_inquiry(struct ctl_scsiio *ctsio)
10551{
10552	struct scsi_inquiry *cdb;
10553	int retval;
10554
10555	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10556
10557	cdb = (struct scsi_inquiry *)ctsio->cdb;
10558	if (cdb->byte2 & SI_EVPD)
10559		retval = ctl_inquiry_evpd(ctsio);
10560	else if (cdb->page_code == 0)
10561		retval = ctl_inquiry_std(ctsio);
10562	else {
10563		ctl_set_invalid_field(ctsio,
10564				      /*sks_valid*/ 1,
10565				      /*command*/ 1,
10566				      /*field*/ 2,
10567				      /*bit_valid*/ 0,
10568				      /*bit*/ 0);
10569		ctl_done((union ctl_io *)ctsio);
10570		return (CTL_RETVAL_COMPLETE);
10571	}
10572
10573	return (retval);
10574}
10575
10576/*
10577 * For known CDB types, parse the LBA and length.
10578 */
10579static int
10580ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10581{
10582	if (io->io_hdr.io_type != CTL_IO_SCSI)
10583		return (1);
10584
10585	switch (io->scsiio.cdb[0]) {
10586	case COMPARE_AND_WRITE: {
10587		struct scsi_compare_and_write *cdb;
10588
10589		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10590
10591		*lba = scsi_8btou64(cdb->addr);
10592		*len = cdb->length;
10593		break;
10594	}
10595	case READ_6:
10596	case WRITE_6: {
10597		struct scsi_rw_6 *cdb;
10598
10599		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10600
10601		*lba = scsi_3btoul(cdb->addr);
10602		/* only 5 bits are valid in the most significant address byte */
10603		*lba &= 0x1fffff;
10604		*len = cdb->length;
10605		break;
10606	}
10607	case READ_10:
10608	case WRITE_10: {
10609		struct scsi_rw_10 *cdb;
10610
10611		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10612
10613		*lba = scsi_4btoul(cdb->addr);
10614		*len = scsi_2btoul(cdb->length);
10615		break;
10616	}
10617	case WRITE_VERIFY_10: {
10618		struct scsi_write_verify_10 *cdb;
10619
10620		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10621
10622		*lba = scsi_4btoul(cdb->addr);
10623		*len = scsi_2btoul(cdb->length);
10624		break;
10625	}
10626	case READ_12:
10627	case WRITE_12: {
10628		struct scsi_rw_12 *cdb;
10629
10630		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10631
10632		*lba = scsi_4btoul(cdb->addr);
10633		*len = scsi_4btoul(cdb->length);
10634		break;
10635	}
10636	case WRITE_VERIFY_12: {
10637		struct scsi_write_verify_12 *cdb;
10638
10639		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10640
10641		*lba = scsi_4btoul(cdb->addr);
10642		*len = scsi_4btoul(cdb->length);
10643		break;
10644	}
10645	case READ_16:
10646	case WRITE_16:
10647	case WRITE_ATOMIC_16: {
10648		struct scsi_rw_16 *cdb;
10649
10650		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10651
10652		*lba = scsi_8btou64(cdb->addr);
10653		*len = scsi_4btoul(cdb->length);
10654		break;
10655	}
10656	case WRITE_VERIFY_16: {
10657		struct scsi_write_verify_16 *cdb;
10658
10659		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10660
10661		*lba = scsi_8btou64(cdb->addr);
10662		*len = scsi_4btoul(cdb->length);
10663		break;
10664	}
10665	case WRITE_SAME_10: {
10666		struct scsi_write_same_10 *cdb;
10667
10668		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10669
10670		*lba = scsi_4btoul(cdb->addr);
10671		*len = scsi_2btoul(cdb->length);
10672		break;
10673	}
10674	case WRITE_SAME_16: {
10675		struct scsi_write_same_16 *cdb;
10676
10677		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10678
10679		*lba = scsi_8btou64(cdb->addr);
10680		*len = scsi_4btoul(cdb->length);
10681		break;
10682	}
10683	case VERIFY_10: {
10684		struct scsi_verify_10 *cdb;
10685
10686		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10687
10688		*lba = scsi_4btoul(cdb->addr);
10689		*len = scsi_2btoul(cdb->length);
10690		break;
10691	}
10692	case VERIFY_12: {
10693		struct scsi_verify_12 *cdb;
10694
10695		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10696
10697		*lba = scsi_4btoul(cdb->addr);
10698		*len = scsi_4btoul(cdb->length);
10699		break;
10700	}
10701	case VERIFY_16: {
10702		struct scsi_verify_16 *cdb;
10703
10704		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10705
10706		*lba = scsi_8btou64(cdb->addr);
10707		*len = scsi_4btoul(cdb->length);
10708		break;
10709	}
10710	case UNMAP: {
10711		*lba = 0;
10712		*len = UINT64_MAX;
10713		break;
10714	}
10715	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10716		struct scsi_get_lba_status *cdb;
10717
10718		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10719		*lba = scsi_8btou64(cdb->addr);
10720		*len = UINT32_MAX;
10721		break;
10722	}
10723	default:
10724		return (1);
10725		break; /* NOTREACHED */
10726	}
10727
10728	return (0);
10729}
10730
10731static ctl_action
10732ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10733    bool seq)
10734{
10735	uint64_t endlba1, endlba2;
10736
10737	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10738	endlba2 = lba2 + len2 - 1;
10739
10740	if ((endlba1 < lba2) || (endlba2 < lba1))
10741		return (CTL_ACTION_PASS);
10742	else
10743		return (CTL_ACTION_BLOCK);
10744}
10745
10746static int
10747ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10748{
10749	struct ctl_ptr_len_flags *ptrlen;
10750	struct scsi_unmap_desc *buf, *end, *range;
10751	uint64_t lba;
10752	uint32_t len;
10753
10754	/* If not UNMAP -- go other way. */
10755	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10756	    io->scsiio.cdb[0] != UNMAP)
10757		return (CTL_ACTION_ERROR);
10758
10759	/* If UNMAP without data -- block and wait for data. */
10760	ptrlen = (struct ctl_ptr_len_flags *)
10761	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10762	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10763	    ptrlen->ptr == NULL)
10764		return (CTL_ACTION_BLOCK);
10765
10766	/* UNMAP with data -- check for collision. */
10767	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10768	end = buf + ptrlen->len / sizeof(*buf);
10769	for (range = buf; range < end; range++) {
10770		lba = scsi_8btou64(range->lba);
10771		len = scsi_4btoul(range->length);
10772		if ((lba < lba2 + len2) && (lba + len > lba2))
10773			return (CTL_ACTION_BLOCK);
10774	}
10775	return (CTL_ACTION_PASS);
10776}
10777
10778static ctl_action
10779ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10780{
10781	uint64_t lba1, lba2;
10782	uint64_t len1, len2;
10783	int retval;
10784
10785	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10786		return (CTL_ACTION_ERROR);
10787
10788	retval = ctl_extent_check_unmap(io1, lba2, len2);
10789	if (retval != CTL_ACTION_ERROR)
10790		return (retval);
10791
10792	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10793		return (CTL_ACTION_ERROR);
10794
10795	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10796}
10797
10798static ctl_action
10799ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10800{
10801	uint64_t lba1, lba2;
10802	uint64_t len1, len2;
10803
10804	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10805		return (CTL_ACTION_ERROR);
10806	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10807		return (CTL_ACTION_ERROR);
10808
10809	if (lba1 + len1 == lba2)
10810		return (CTL_ACTION_BLOCK);
10811	return (CTL_ACTION_PASS);
10812}
10813
10814static ctl_action
10815ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10816    union ctl_io *ooa_io)
10817{
10818	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10819	ctl_serialize_action *serialize_row;
10820
10821	/*
10822	 * The initiator attempted multiple untagged commands at the same
10823	 * time.  Can't do that.
10824	 */
10825	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10826	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10827	 && ((pending_io->io_hdr.nexus.targ_port ==
10828	      ooa_io->io_hdr.nexus.targ_port)
10829	  && (pending_io->io_hdr.nexus.initid.id ==
10830	      ooa_io->io_hdr.nexus.initid.id))
10831	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10832	      CTL_FLAG_STATUS_SENT)) == 0))
10833		return (CTL_ACTION_OVERLAP);
10834
10835	/*
10836	 * The initiator attempted to send multiple tagged commands with
10837	 * the same ID.  (It's fine if different initiators have the same
10838	 * tag ID.)
10839	 *
10840	 * Even if all of those conditions are true, we don't kill the I/O
10841	 * if the command ahead of us has been aborted.  We won't end up
10842	 * sending it to the FETD, and it's perfectly legal to resend a
10843	 * command with the same tag number as long as the previous
10844	 * instance of this tag number has been aborted somehow.
10845	 */
10846	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10847	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10848	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10849	 && ((pending_io->io_hdr.nexus.targ_port ==
10850	      ooa_io->io_hdr.nexus.targ_port)
10851	  && (pending_io->io_hdr.nexus.initid.id ==
10852	      ooa_io->io_hdr.nexus.initid.id))
10853	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10854	      CTL_FLAG_STATUS_SENT)) == 0))
10855		return (CTL_ACTION_OVERLAP_TAG);
10856
10857	/*
10858	 * If we get a head of queue tag, SAM-3 says that we should
10859	 * immediately execute it.
10860	 *
10861	 * What happens if this command would normally block for some other
10862	 * reason?  e.g. a request sense with a head of queue tag
10863	 * immediately after a write.  Normally that would block, but this
10864	 * will result in its getting executed immediately...
10865	 *
10866	 * We currently return "pass" instead of "skip", so we'll end up
10867	 * going through the rest of the queue to check for overlapped tags.
10868	 *
10869	 * XXX KDM check for other types of blockage first??
10870	 */
10871	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10872		return (CTL_ACTION_PASS);
10873
10874	/*
10875	 * Ordered tags have to block until all items ahead of them
10876	 * have completed.  If we get called with an ordered tag, we always
10877	 * block, if something else is ahead of us in the queue.
10878	 */
10879	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10880		return (CTL_ACTION_BLOCK);
10881
10882	/*
10883	 * Simple tags get blocked until all head of queue and ordered tags
10884	 * ahead of them have completed.  I'm lumping untagged commands in
10885	 * with simple tags here.  XXX KDM is that the right thing to do?
10886	 */
10887	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10888	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10889	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10890	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10891		return (CTL_ACTION_BLOCK);
10892
10893	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10894	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10895
10896	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10897
10898	switch (serialize_row[pending_entry->seridx]) {
10899	case CTL_SER_BLOCK:
10900		return (CTL_ACTION_BLOCK);
10901	case CTL_SER_EXTENT:
10902		return (ctl_extent_check(ooa_io, pending_io,
10903		    (lun->serseq == CTL_LUN_SERSEQ_ON)));
10904	case CTL_SER_EXTENTOPT:
10905		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10906		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10907			return (ctl_extent_check(ooa_io, pending_io,
10908			    (lun->serseq == CTL_LUN_SERSEQ_ON)));
10909		return (CTL_ACTION_PASS);
10910	case CTL_SER_EXTENTSEQ:
10911		if (lun->serseq != CTL_LUN_SERSEQ_OFF)
10912			return (ctl_extent_check_seq(ooa_io, pending_io));
10913		return (CTL_ACTION_PASS);
10914	case CTL_SER_PASS:
10915		return (CTL_ACTION_PASS);
10916	case CTL_SER_BLOCKOPT:
10917		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10918		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10919			return (CTL_ACTION_BLOCK);
10920		return (CTL_ACTION_PASS);
10921	case CTL_SER_SKIP:
10922		return (CTL_ACTION_SKIP);
10923	default:
10924		panic("invalid serialization value %d",
10925		      serialize_row[pending_entry->seridx]);
10926	}
10927
10928	return (CTL_ACTION_ERROR);
10929}
10930
10931/*
10932 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10933 * Assumptions:
10934 * - pending_io is generally either incoming, or on the blocked queue
10935 * - starting I/O is the I/O we want to start the check with.
10936 */
10937static ctl_action
10938ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10939	      union ctl_io *starting_io)
10940{
10941	union ctl_io *ooa_io;
10942	ctl_action action;
10943
10944	mtx_assert(&lun->lun_lock, MA_OWNED);
10945
10946	/*
10947	 * Run back along the OOA queue, starting with the current
10948	 * blocked I/O and going through every I/O before it on the
10949	 * queue.  If starting_io is NULL, we'll just end up returning
10950	 * CTL_ACTION_PASS.
10951	 */
10952	for (ooa_io = starting_io; ooa_io != NULL;
10953	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10954	     ooa_links)){
10955
10956		/*
10957		 * This routine just checks to see whether
10958		 * cur_blocked is blocked by ooa_io, which is ahead
10959		 * of it in the queue.  It doesn't queue/dequeue
10960		 * cur_blocked.
10961		 */
10962		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10963		switch (action) {
10964		case CTL_ACTION_BLOCK:
10965		case CTL_ACTION_OVERLAP:
10966		case CTL_ACTION_OVERLAP_TAG:
10967		case CTL_ACTION_SKIP:
10968		case CTL_ACTION_ERROR:
10969			return (action);
10970			break; /* NOTREACHED */
10971		case CTL_ACTION_PASS:
10972			break;
10973		default:
10974			panic("invalid action %d", action);
10975			break;  /* NOTREACHED */
10976		}
10977	}
10978
10979	return (CTL_ACTION_PASS);
10980}
10981
10982/*
10983 * Assumptions:
10984 * - An I/O has just completed, and has been removed from the per-LUN OOA
10985 *   queue, so some items on the blocked queue may now be unblocked.
10986 */
10987static int
10988ctl_check_blocked(struct ctl_lun *lun)
10989{
10990	union ctl_io *cur_blocked, *next_blocked;
10991
10992	mtx_assert(&lun->lun_lock, MA_OWNED);
10993
10994	/*
10995	 * Run forward from the head of the blocked queue, checking each
10996	 * entry against the I/Os prior to it on the OOA queue to see if
10997	 * there is still any blockage.
10998	 *
10999	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11000	 * with our removing a variable on it while it is traversing the
11001	 * list.
11002	 */
11003	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11004	     cur_blocked != NULL; cur_blocked = next_blocked) {
11005		union ctl_io *prev_ooa;
11006		ctl_action action;
11007
11008		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11009							  blocked_links);
11010
11011		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11012						      ctl_ooaq, ooa_links);
11013
11014		/*
11015		 * If cur_blocked happens to be the first item in the OOA
11016		 * queue now, prev_ooa will be NULL, and the action
11017		 * returned will just be CTL_ACTION_PASS.
11018		 */
11019		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11020
11021		switch (action) {
11022		case CTL_ACTION_BLOCK:
11023			/* Nothing to do here, still blocked */
11024			break;
11025		case CTL_ACTION_OVERLAP:
11026		case CTL_ACTION_OVERLAP_TAG:
11027			/*
11028			 * This shouldn't happen!  In theory we've already
11029			 * checked this command for overlap...
11030			 */
11031			break;
11032		case CTL_ACTION_PASS:
11033		case CTL_ACTION_SKIP: {
11034			const struct ctl_cmd_entry *entry;
11035			int isc_retval;
11036
11037			/*
11038			 * The skip case shouldn't happen, this transaction
11039			 * should have never made it onto the blocked queue.
11040			 */
11041			/*
11042			 * This I/O is no longer blocked, we can remove it
11043			 * from the blocked queue.  Since this is a TAILQ
11044			 * (doubly linked list), we can do O(1) removals
11045			 * from any place on the list.
11046			 */
11047			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11048				     blocked_links);
11049			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11050
11051			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11052				/*
11053				 * Need to send IO back to original side to
11054				 * run
11055				 */
11056				union ctl_ha_msg msg_info;
11057
11058				msg_info.hdr.original_sc =
11059					cur_blocked->io_hdr.original_sc;
11060				msg_info.hdr.serializing_sc = cur_blocked;
11061				msg_info.hdr.msg_type = CTL_MSG_R2R;
11062				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11063				     &msg_info, sizeof(msg_info), 0)) >
11064				     CTL_HA_STATUS_SUCCESS) {
11065					printf("CTL:Check Blocked error from "
11066					       "ctl_ha_msg_send %d\n",
11067					       isc_retval);
11068				}
11069				break;
11070			}
11071			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11072
11073			/*
11074			 * Check this I/O for LUN state changes that may
11075			 * have happened while this command was blocked.
11076			 * The LUN state may have been changed by a command
11077			 * ahead of us in the queue, so we need to re-check
11078			 * for any states that can be caused by SCSI
11079			 * commands.
11080			 */
11081			if (ctl_scsiio_lun_check(lun, entry,
11082						 &cur_blocked->scsiio) == 0) {
11083				cur_blocked->io_hdr.flags |=
11084				                      CTL_FLAG_IS_WAS_ON_RTR;
11085				ctl_enqueue_rtr(cur_blocked);
11086			} else
11087				ctl_done(cur_blocked);
11088			break;
11089		}
11090		default:
11091			/*
11092			 * This probably shouldn't happen -- we shouldn't
11093			 * get CTL_ACTION_ERROR, or anything else.
11094			 */
11095			break;
11096		}
11097	}
11098
11099	return (CTL_RETVAL_COMPLETE);
11100}
11101
11102/*
11103 * This routine (with one exception) checks LUN flags that can be set by
11104 * commands ahead of us in the OOA queue.  These flags have to be checked
11105 * when a command initially comes in, and when we pull a command off the
11106 * blocked queue and are preparing to execute it.  The reason we have to
11107 * check these flags for commands on the blocked queue is that the LUN
11108 * state may have been changed by a command ahead of us while we're on the
11109 * blocked queue.
11110 *
11111 * Ordering is somewhat important with these checks, so please pay
11112 * careful attention to the placement of any new checks.
11113 */
11114static int
11115ctl_scsiio_lun_check(struct ctl_lun *lun,
11116    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11117{
11118	struct ctl_softc *softc = lun->ctl_softc;
11119	int retval;
11120	uint32_t residx;
11121
11122	retval = 0;
11123
11124	mtx_assert(&lun->lun_lock, MA_OWNED);
11125
11126	/*
11127	 * If this shelf is a secondary shelf controller, we have to reject
11128	 * any media access commands.
11129	 */
11130	if ((softc->flags & CTL_FLAG_ACTIVE_SHELF) == 0 &&
11131	    (entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0) {
11132		ctl_set_lun_standby(ctsio);
11133		retval = 1;
11134		goto bailout;
11135	}
11136
11137	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11138		if (lun->flags & CTL_LUN_READONLY) {
11139			ctl_set_sense(ctsio, /*current_error*/ 1,
11140			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11141			    /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11142			retval = 1;
11143			goto bailout;
11144		}
11145		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11146		    .eca_and_aen & SCP_SWP) != 0) {
11147			ctl_set_sense(ctsio, /*current_error*/ 1,
11148			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11149			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11150			retval = 1;
11151			goto bailout;
11152		}
11153	}
11154
11155	/*
11156	 * Check for a reservation conflict.  If this command isn't allowed
11157	 * even on reserved LUNs, and if this initiator isn't the one who
11158	 * reserved us, reject the command with a reservation conflict.
11159	 */
11160	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11161	if ((lun->flags & CTL_LUN_RESERVED)
11162	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11163		if (lun->res_idx != residx) {
11164			ctl_set_reservation_conflict(ctsio);
11165			retval = 1;
11166			goto bailout;
11167		}
11168	}
11169
11170	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11171	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11172		/* No reservation or command is allowed. */;
11173	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11174	    (lun->res_type == SPR_TYPE_WR_EX ||
11175	     lun->res_type == SPR_TYPE_WR_EX_RO ||
11176	     lun->res_type == SPR_TYPE_WR_EX_AR)) {
11177		/* The command is allowed for Write Exclusive resv. */;
11178	} else {
11179		/*
11180		 * if we aren't registered or it's a res holder type
11181		 * reservation and this isn't the res holder then set a
11182		 * conflict.
11183		 */
11184		if (ctl_get_prkey(lun, residx) == 0
11185		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11186			ctl_set_reservation_conflict(ctsio);
11187			retval = 1;
11188			goto bailout;
11189		}
11190
11191	}
11192
11193	if ((lun->flags & CTL_LUN_OFFLINE)
11194	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11195		ctl_set_lun_not_ready(ctsio);
11196		retval = 1;
11197		goto bailout;
11198	}
11199
11200	/*
11201	 * If the LUN is stopped, see if this particular command is allowed
11202	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11203	 */
11204	if ((lun->flags & CTL_LUN_STOPPED)
11205	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11206		/* "Logical unit not ready, initializing cmd. required" */
11207		ctl_set_lun_stopped(ctsio);
11208		retval = 1;
11209		goto bailout;
11210	}
11211
11212	if ((lun->flags & CTL_LUN_INOPERABLE)
11213	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11214		/* "Medium format corrupted" */
11215		ctl_set_medium_format_corrupted(ctsio);
11216		retval = 1;
11217		goto bailout;
11218	}
11219
11220bailout:
11221	return (retval);
11222
11223}
11224
11225static void
11226ctl_failover_io(union ctl_io *io, int have_lock)
11227{
11228	ctl_set_busy(&io->scsiio);
11229	ctl_done(io);
11230}
11231
11232static void
11233ctl_failover(void)
11234{
11235	struct ctl_lun *lun;
11236	struct ctl_softc *softc;
11237	union ctl_io *next_io, *pending_io;
11238	union ctl_io *io;
11239	int lun_idx;
11240
11241	softc = control_softc;
11242
11243	mtx_lock(&softc->ctl_lock);
11244	/*
11245	 * Remove any cmds from the other SC from the rtr queue.  These
11246	 * will obviously only be for LUNs for which we're the primary.
11247	 * We can't send status or get/send data for these commands.
11248	 * Since they haven't been executed yet, we can just remove them.
11249	 * We'll either abort them or delete them below, depending on
11250	 * which HA mode we're in.
11251	 */
11252#ifdef notyet
11253	mtx_lock(&softc->queue_lock);
11254	for (io = (union ctl_io *)STAILQ_FIRST(&softc->rtr_queue);
11255	     io != NULL; io = next_io) {
11256		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11257		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11258			STAILQ_REMOVE(&softc->rtr_queue, &io->io_hdr,
11259				      ctl_io_hdr, links);
11260	}
11261	mtx_unlock(&softc->queue_lock);
11262#endif
11263
11264	for (lun_idx=0; lun_idx < softc->num_luns; lun_idx++) {
11265		lun = softc->ctl_luns[lun_idx];
11266		if (lun==NULL)
11267			continue;
11268
11269		/*
11270		 * Processor LUNs are primary on both sides.
11271		 * XXX will this always be true?
11272		 */
11273		if (lun->be_lun->lun_type == T_PROCESSOR)
11274			continue;
11275
11276		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11277		 && (softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11278			printf("FAILOVER: primary lun %d\n", lun_idx);
11279		        /*
11280			 * Remove all commands from the other SC. First from the
11281			 * blocked queue then from the ooa queue. Once we have
11282			 * removed them. Call ctl_check_blocked to see if there
11283			 * is anything that can run.
11284			 */
11285			for (io = (union ctl_io *)TAILQ_FIRST(
11286			     &lun->blocked_queue); io != NULL; io = next_io) {
11287
11288		        	next_io = (union ctl_io *)TAILQ_NEXT(
11289				    &io->io_hdr, blocked_links);
11290
11291				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11292					TAILQ_REMOVE(&lun->blocked_queue,
11293						     &io->io_hdr,blocked_links);
11294					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11295					TAILQ_REMOVE(&lun->ooa_queue,
11296						     &io->io_hdr, ooa_links);
11297
11298					ctl_free_io(io);
11299				}
11300			}
11301
11302			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11303	     		     io != NULL; io = next_io) {
11304
11305		        	next_io = (union ctl_io *)TAILQ_NEXT(
11306				    &io->io_hdr, ooa_links);
11307
11308				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11309
11310					TAILQ_REMOVE(&lun->ooa_queue,
11311						&io->io_hdr,
11312					     	ooa_links);
11313
11314					ctl_free_io(io);
11315				}
11316			}
11317			ctl_check_blocked(lun);
11318		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11319			&& (softc->ha_mode == CTL_HA_MODE_XFER)) {
11320
11321			printf("FAILOVER: primary lun %d\n", lun_idx);
11322			/*
11323			 * Abort all commands from the other SC.  We can't
11324			 * send status back for them now.  These should get
11325			 * cleaned up when they are completed or come out
11326			 * for a datamove operation.
11327			 */
11328			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11329	     		     io != NULL; io = next_io) {
11330		        	next_io = (union ctl_io *)TAILQ_NEXT(
11331					&io->io_hdr, ooa_links);
11332
11333				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11334					io->io_hdr.flags |= CTL_FLAG_ABORT;
11335			}
11336		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11337			&& (softc->ha_mode == CTL_HA_MODE_XFER)) {
11338
11339			printf("FAILOVER: secondary lun %d\n", lun_idx);
11340
11341			lun->flags |= CTL_LUN_PRIMARY_SC;
11342
11343			/*
11344			 * We send all I/O that was sent to this controller
11345			 * and redirected to the other side back with
11346			 * busy status, and have the initiator retry it.
11347			 * Figuring out how much data has been transferred,
11348			 * etc. and picking up where we left off would be
11349			 * very tricky.
11350			 *
11351			 * XXX KDM need to remove I/O from the blocked
11352			 * queue as well!
11353			 */
11354			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11355			     &lun->ooa_queue); pending_io != NULL;
11356			     pending_io = next_io) {
11357
11358				next_io =  (union ctl_io *)TAILQ_NEXT(
11359					&pending_io->io_hdr, ooa_links);
11360
11361				pending_io->io_hdr.flags &=
11362					~CTL_FLAG_SENT_2OTHER_SC;
11363
11364				if (pending_io->io_hdr.flags &
11365				    CTL_FLAG_IO_ACTIVE) {
11366					pending_io->io_hdr.flags |=
11367						CTL_FLAG_FAILOVER;
11368				} else {
11369					ctl_set_busy(&pending_io->scsiio);
11370					ctl_done(pending_io);
11371				}
11372			}
11373
11374			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11375		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11376			&& (softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11377			printf("FAILOVER: secondary lun %d\n", lun_idx);
11378			/*
11379			 * if the first io on the OOA is not on the RtR queue
11380			 * add it.
11381			 */
11382			lun->flags |= CTL_LUN_PRIMARY_SC;
11383
11384			pending_io = (union ctl_io *)TAILQ_FIRST(
11385			    &lun->ooa_queue);
11386			if (pending_io==NULL) {
11387				printf("Nothing on OOA queue\n");
11388				continue;
11389			}
11390
11391			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11392			if ((pending_io->io_hdr.flags &
11393			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11394				pending_io->io_hdr.flags |=
11395				    CTL_FLAG_IS_WAS_ON_RTR;
11396				ctl_enqueue_rtr(pending_io);
11397			}
11398#if 0
11399			else
11400			{
11401				printf("Tag 0x%04x is running\n",
11402				      pending_io->scsiio.tag_num);
11403			}
11404#endif
11405
11406			next_io = (union ctl_io *)TAILQ_NEXT(
11407			    &pending_io->io_hdr, ooa_links);
11408			for (pending_io=next_io; pending_io != NULL;
11409			     pending_io = next_io) {
11410				pending_io->io_hdr.flags &=
11411				    ~CTL_FLAG_SENT_2OTHER_SC;
11412				next_io = (union ctl_io *)TAILQ_NEXT(
11413					&pending_io->io_hdr, ooa_links);
11414				if (pending_io->io_hdr.flags &
11415				    CTL_FLAG_IS_WAS_ON_RTR) {
11416#if 0
11417				        printf("Tag 0x%04x is running\n",
11418				      		pending_io->scsiio.tag_num);
11419#endif
11420					continue;
11421				}
11422
11423				switch (ctl_check_ooa(lun, pending_io,
11424			            (union ctl_io *)TAILQ_PREV(
11425				    &pending_io->io_hdr, ctl_ooaq,
11426				    ooa_links))) {
11427
11428				case CTL_ACTION_BLOCK:
11429					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11430							  &pending_io->io_hdr,
11431							  blocked_links);
11432					pending_io->io_hdr.flags |=
11433					    CTL_FLAG_BLOCKED;
11434					break;
11435				case CTL_ACTION_PASS:
11436				case CTL_ACTION_SKIP:
11437					pending_io->io_hdr.flags |=
11438					    CTL_FLAG_IS_WAS_ON_RTR;
11439					ctl_enqueue_rtr(pending_io);
11440					break;
11441				case CTL_ACTION_OVERLAP:
11442					ctl_set_overlapped_cmd(
11443					    (struct ctl_scsiio *)pending_io);
11444					ctl_done(pending_io);
11445					break;
11446				case CTL_ACTION_OVERLAP_TAG:
11447					ctl_set_overlapped_tag(
11448					    (struct ctl_scsiio *)pending_io,
11449					    pending_io->scsiio.tag_num & 0xff);
11450					ctl_done(pending_io);
11451					break;
11452				case CTL_ACTION_ERROR:
11453				default:
11454					ctl_set_internal_failure(
11455						(struct ctl_scsiio *)pending_io,
11456						0,  // sks_valid
11457						0); //retry count
11458					ctl_done(pending_io);
11459					break;
11460				}
11461			}
11462
11463			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11464		} else {
11465			panic("Unhandled HA mode failover, LUN flags = %#x, "
11466			      "ha_mode = #%x", lun->flags, softc->ha_mode);
11467		}
11468	}
11469	ctl_pause_rtr = 0;
11470	mtx_unlock(&softc->ctl_lock);
11471}
11472
11473static int
11474ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11475{
11476	struct ctl_lun *lun;
11477	const struct ctl_cmd_entry *entry;
11478	uint32_t initidx, targ_lun;
11479	int retval;
11480
11481	retval = 0;
11482
11483	lun = NULL;
11484
11485	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11486	if ((targ_lun < CTL_MAX_LUNS)
11487	 && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11488		/*
11489		 * If the LUN is invalid, pretend that it doesn't exist.
11490		 * It will go away as soon as all pending I/O has been
11491		 * completed.
11492		 */
11493		mtx_lock(&lun->lun_lock);
11494		if (lun->flags & CTL_LUN_DISABLED) {
11495			mtx_unlock(&lun->lun_lock);
11496			lun = NULL;
11497			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11498			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11499		} else {
11500			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11501			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11502				lun->be_lun;
11503			if (lun->be_lun->lun_type == T_PROCESSOR) {
11504				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11505			}
11506
11507			/*
11508			 * Every I/O goes into the OOA queue for a
11509			 * particular LUN, and stays there until completion.
11510			 */
11511			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11512			    ooa_links);
11513		}
11514	} else {
11515		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11516		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11517	}
11518
11519	/* Get command entry and return error if it is unsuppotyed. */
11520	entry = ctl_validate_command(ctsio);
11521	if (entry == NULL) {
11522		if (lun)
11523			mtx_unlock(&lun->lun_lock);
11524		return (retval);
11525	}
11526
11527	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11528	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11529
11530	/*
11531	 * Check to see whether we can send this command to LUNs that don't
11532	 * exist.  This should pretty much only be the case for inquiry
11533	 * and request sense.  Further checks, below, really require having
11534	 * a LUN, so we can't really check the command anymore.  Just put
11535	 * it on the rtr queue.
11536	 */
11537	if (lun == NULL) {
11538		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11539			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11540			ctl_enqueue_rtr((union ctl_io *)ctsio);
11541			return (retval);
11542		}
11543
11544		ctl_set_unsupported_lun(ctsio);
11545		ctl_done((union ctl_io *)ctsio);
11546		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11547		return (retval);
11548	} else {
11549		/*
11550		 * Make sure we support this particular command on this LUN.
11551		 * e.g., we don't support writes to the control LUN.
11552		 */
11553		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11554			mtx_unlock(&lun->lun_lock);
11555			ctl_set_invalid_opcode(ctsio);
11556			ctl_done((union ctl_io *)ctsio);
11557			return (retval);
11558		}
11559	}
11560
11561	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11562
11563#ifdef CTL_WITH_CA
11564	/*
11565	 * If we've got a request sense, it'll clear the contingent
11566	 * allegiance condition.  Otherwise, if we have a CA condition for
11567	 * this initiator, clear it, because it sent down a command other
11568	 * than request sense.
11569	 */
11570	if ((ctsio->cdb[0] != REQUEST_SENSE)
11571	 && (ctl_is_set(lun->have_ca, initidx)))
11572		ctl_clear_mask(lun->have_ca, initidx);
11573#endif
11574
11575	/*
11576	 * If the command has this flag set, it handles its own unit
11577	 * attention reporting, we shouldn't do anything.  Otherwise we
11578	 * check for any pending unit attentions, and send them back to the
11579	 * initiator.  We only do this when a command initially comes in,
11580	 * not when we pull it off the blocked queue.
11581	 *
11582	 * According to SAM-3, section 5.3.2, the order that things get
11583	 * presented back to the host is basically unit attentions caused
11584	 * by some sort of reset event, busy status, reservation conflicts
11585	 * or task set full, and finally any other status.
11586	 *
11587	 * One issue here is that some of the unit attentions we report
11588	 * don't fall into the "reset" category (e.g. "reported luns data
11589	 * has changed").  So reporting it here, before the reservation
11590	 * check, may be technically wrong.  I guess the only thing to do
11591	 * would be to check for and report the reset events here, and then
11592	 * check for the other unit attention types after we check for a
11593	 * reservation conflict.
11594	 *
11595	 * XXX KDM need to fix this
11596	 */
11597	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11598		ctl_ua_type ua_type;
11599		scsi_sense_data_type sense_format;
11600
11601		if (lun->flags & CTL_LUN_SENSE_DESC)
11602			sense_format = SSD_TYPE_DESC;
11603		else
11604			sense_format = SSD_TYPE_FIXED;
11605
11606		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11607		    sense_format);
11608		if (ua_type != CTL_UA_NONE) {
11609			mtx_unlock(&lun->lun_lock);
11610			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11611			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11612			ctsio->sense_len = SSD_FULL_SIZE;
11613			ctl_done((union ctl_io *)ctsio);
11614			return (retval);
11615		}
11616	}
11617
11618
11619	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11620		mtx_unlock(&lun->lun_lock);
11621		ctl_done((union ctl_io *)ctsio);
11622		return (retval);
11623	}
11624
11625	/*
11626	 * XXX CHD this is where we want to send IO to other side if
11627	 * this LUN is secondary on this SC. We will need to make a copy
11628	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11629	 * the copy we send as FROM_OTHER.
11630	 * We also need to stuff the address of the original IO so we can
11631	 * find it easily. Something similar will need be done on the other
11632	 * side so when we are done we can find the copy.
11633	 */
11634	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11635		union ctl_ha_msg msg_info;
11636		int isc_retval;
11637
11638		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11639
11640		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11641		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11642#if 0
11643		printf("1. ctsio %p\n", ctsio);
11644#endif
11645		msg_info.hdr.serializing_sc = NULL;
11646		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11647		msg_info.scsi.tag_num = ctsio->tag_num;
11648		msg_info.scsi.tag_type = ctsio->tag_type;
11649		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11650
11651		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11652
11653		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11654		    (void *)&msg_info, sizeof(msg_info), 0)) >
11655		    CTL_HA_STATUS_SUCCESS) {
11656			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11657			       isc_retval);
11658			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11659		} else {
11660#if 0
11661			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11662#endif
11663		}
11664
11665		/*
11666		 * XXX KDM this I/O is off the incoming queue, but hasn't
11667		 * been inserted on any other queue.  We may need to come
11668		 * up with a holding queue while we wait for serialization
11669		 * so that we have an idea of what we're waiting for from
11670		 * the other side.
11671		 */
11672		mtx_unlock(&lun->lun_lock);
11673		return (retval);
11674	}
11675
11676	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11677			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11678			      ctl_ooaq, ooa_links))) {
11679	case CTL_ACTION_BLOCK:
11680		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11681		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11682				  blocked_links);
11683		mtx_unlock(&lun->lun_lock);
11684		return (retval);
11685	case CTL_ACTION_PASS:
11686	case CTL_ACTION_SKIP:
11687		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11688		mtx_unlock(&lun->lun_lock);
11689		ctl_enqueue_rtr((union ctl_io *)ctsio);
11690		break;
11691	case CTL_ACTION_OVERLAP:
11692		mtx_unlock(&lun->lun_lock);
11693		ctl_set_overlapped_cmd(ctsio);
11694		ctl_done((union ctl_io *)ctsio);
11695		break;
11696	case CTL_ACTION_OVERLAP_TAG:
11697		mtx_unlock(&lun->lun_lock);
11698		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11699		ctl_done((union ctl_io *)ctsio);
11700		break;
11701	case CTL_ACTION_ERROR:
11702	default:
11703		mtx_unlock(&lun->lun_lock);
11704		ctl_set_internal_failure(ctsio,
11705					 /*sks_valid*/ 0,
11706					 /*retry_count*/ 0);
11707		ctl_done((union ctl_io *)ctsio);
11708		break;
11709	}
11710	return (retval);
11711}
11712
11713const struct ctl_cmd_entry *
11714ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11715{
11716	const struct ctl_cmd_entry *entry;
11717	int service_action;
11718
11719	entry = &ctl_cmd_table[ctsio->cdb[0]];
11720	if (sa)
11721		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11722	if (entry->flags & CTL_CMD_FLAG_SA5) {
11723		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11724		entry = &((const struct ctl_cmd_entry *)
11725		    entry->execute)[service_action];
11726	}
11727	return (entry);
11728}
11729
11730const struct ctl_cmd_entry *
11731ctl_validate_command(struct ctl_scsiio *ctsio)
11732{
11733	const struct ctl_cmd_entry *entry;
11734	int i, sa;
11735	uint8_t diff;
11736
11737	entry = ctl_get_cmd_entry(ctsio, &sa);
11738	if (entry->execute == NULL) {
11739		if (sa)
11740			ctl_set_invalid_field(ctsio,
11741					      /*sks_valid*/ 1,
11742					      /*command*/ 1,
11743					      /*field*/ 1,
11744					      /*bit_valid*/ 1,
11745					      /*bit*/ 4);
11746		else
11747			ctl_set_invalid_opcode(ctsio);
11748		ctl_done((union ctl_io *)ctsio);
11749		return (NULL);
11750	}
11751	KASSERT(entry->length > 0,
11752	    ("Not defined length for command 0x%02x/0x%02x",
11753	     ctsio->cdb[0], ctsio->cdb[1]));
11754	for (i = 1; i < entry->length; i++) {
11755		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11756		if (diff == 0)
11757			continue;
11758		ctl_set_invalid_field(ctsio,
11759				      /*sks_valid*/ 1,
11760				      /*command*/ 1,
11761				      /*field*/ i,
11762				      /*bit_valid*/ 1,
11763				      /*bit*/ fls(diff) - 1);
11764		ctl_done((union ctl_io *)ctsio);
11765		return (NULL);
11766	}
11767	return (entry);
11768}
11769
11770static int
11771ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11772{
11773
11774	switch (lun_type) {
11775	case T_PROCESSOR:
11776		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11777		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11778			return (0);
11779		break;
11780	case T_DIRECT:
11781		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11782		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11783			return (0);
11784		break;
11785	default:
11786		return (0);
11787	}
11788	return (1);
11789}
11790
11791static int
11792ctl_scsiio(struct ctl_scsiio *ctsio)
11793{
11794	int retval;
11795	const struct ctl_cmd_entry *entry;
11796
11797	retval = CTL_RETVAL_COMPLETE;
11798
11799	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11800
11801	entry = ctl_get_cmd_entry(ctsio, NULL);
11802
11803	/*
11804	 * If this I/O has been aborted, just send it straight to
11805	 * ctl_done() without executing it.
11806	 */
11807	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11808		ctl_done((union ctl_io *)ctsio);
11809		goto bailout;
11810	}
11811
11812	/*
11813	 * All the checks should have been handled by ctl_scsiio_precheck().
11814	 * We should be clear now to just execute the I/O.
11815	 */
11816	retval = entry->execute(ctsio);
11817
11818bailout:
11819	return (retval);
11820}
11821
11822/*
11823 * Since we only implement one target right now, a bus reset simply resets
11824 * our single target.
11825 */
11826static int
11827ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11828{
11829	return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11830}
11831
11832static int
11833ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11834		 ctl_ua_type ua_type)
11835{
11836	struct ctl_lun *lun;
11837	int retval;
11838
11839	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11840		union ctl_ha_msg msg_info;
11841
11842		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11843		msg_info.hdr.nexus = io->io_hdr.nexus;
11844		if (ua_type==CTL_UA_TARG_RESET)
11845			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11846		else
11847			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11848		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11849		msg_info.hdr.original_sc = NULL;
11850		msg_info.hdr.serializing_sc = NULL;
11851		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11852		    (void *)&msg_info, sizeof(msg_info), 0)) {
11853		}
11854	}
11855	retval = 0;
11856
11857	mtx_lock(&softc->ctl_lock);
11858	STAILQ_FOREACH(lun, &softc->lun_list, links)
11859		retval += ctl_lun_reset(lun, io, ua_type);
11860	mtx_unlock(&softc->ctl_lock);
11861
11862	return (retval);
11863}
11864
11865/*
11866 * The LUN should always be set.  The I/O is optional, and is used to
11867 * distinguish between I/Os sent by this initiator, and by other
11868 * initiators.  We set unit attention for initiators other than this one.
11869 * SAM-3 is vague on this point.  It does say that a unit attention should
11870 * be established for other initiators when a LUN is reset (see section
11871 * 5.7.3), but it doesn't specifically say that the unit attention should
11872 * be established for this particular initiator when a LUN is reset.  Here
11873 * is the relevant text, from SAM-3 rev 8:
11874 *
11875 * 5.7.2 When a SCSI initiator port aborts its own tasks
11876 *
11877 * When a SCSI initiator port causes its own task(s) to be aborted, no
11878 * notification that the task(s) have been aborted shall be returned to
11879 * the SCSI initiator port other than the completion response for the
11880 * command or task management function action that caused the task(s) to
11881 * be aborted and notification(s) associated with related effects of the
11882 * action (e.g., a reset unit attention condition).
11883 *
11884 * XXX KDM for now, we're setting unit attention for all initiators.
11885 */
11886static int
11887ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11888{
11889	union ctl_io *xio;
11890#if 0
11891	uint32_t initidx;
11892#endif
11893#ifdef CTL_WITH_CA
11894	int i;
11895#endif
11896
11897	mtx_lock(&lun->lun_lock);
11898	/*
11899	 * Run through the OOA queue and abort each I/O.
11900	 */
11901#if 0
11902	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11903#endif
11904	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11905	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11906		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11907	}
11908
11909	/*
11910	 * This version sets unit attention for every
11911	 */
11912#if 0
11913	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11914	ctl_est_ua_all(lun, initidx, ua_type);
11915#else
11916	ctl_est_ua_all(lun, -1, ua_type);
11917#endif
11918
11919	/*
11920	 * A reset (any kind, really) clears reservations established with
11921	 * RESERVE/RELEASE.  It does not clear reservations established
11922	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11923	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11924	 * reservations made with the RESERVE/RELEASE commands, because
11925	 * those commands are obsolete in SPC-3.
11926	 */
11927	lun->flags &= ~CTL_LUN_RESERVED;
11928
11929#ifdef CTL_WITH_CA
11930	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11931		ctl_clear_mask(lun->have_ca, i);
11932#endif
11933	mtx_unlock(&lun->lun_lock);
11934
11935	return (0);
11936}
11937
11938static void
11939ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11940    int other_sc)
11941{
11942	union ctl_io *xio;
11943
11944	mtx_assert(&lun->lun_lock, MA_OWNED);
11945
11946	/*
11947	 * Run through the OOA queue and attempt to find the given I/O.
11948	 * The target port, initiator ID, tag type and tag number have to
11949	 * match the values that we got from the initiator.  If we have an
11950	 * untagged command to abort, simply abort the first untagged command
11951	 * we come to.  We only allow one untagged command at a time of course.
11952	 */
11953	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11954	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11955
11956		if ((targ_port == UINT32_MAX ||
11957		     targ_port == xio->io_hdr.nexus.targ_port) &&
11958		    (init_id == UINT32_MAX ||
11959		     init_id == xio->io_hdr.nexus.initid.id)) {
11960			if (targ_port != xio->io_hdr.nexus.targ_port ||
11961			    init_id != xio->io_hdr.nexus.initid.id)
11962				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11963			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11964			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11965				union ctl_ha_msg msg_info;
11966
11967				msg_info.hdr.nexus = xio->io_hdr.nexus;
11968				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11969				msg_info.task.tag_num = xio->scsiio.tag_num;
11970				msg_info.task.tag_type = xio->scsiio.tag_type;
11971				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11972				msg_info.hdr.original_sc = NULL;
11973				msg_info.hdr.serializing_sc = NULL;
11974				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11975				    (void *)&msg_info, sizeof(msg_info), 0);
11976			}
11977		}
11978	}
11979}
11980
11981static int
11982ctl_abort_task_set(union ctl_io *io)
11983{
11984	struct ctl_softc *softc = control_softc;
11985	struct ctl_lun *lun;
11986	uint32_t targ_lun;
11987
11988	/*
11989	 * Look up the LUN.
11990	 */
11991	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11992	mtx_lock(&softc->ctl_lock);
11993	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
11994		lun = softc->ctl_luns[targ_lun];
11995	else {
11996		mtx_unlock(&softc->ctl_lock);
11997		return (1);
11998	}
11999
12000	mtx_lock(&lun->lun_lock);
12001	mtx_unlock(&softc->ctl_lock);
12002	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12003		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12004		    io->io_hdr.nexus.initid.id,
12005		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12006	} else { /* CTL_TASK_CLEAR_TASK_SET */
12007		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12008		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12009	}
12010	mtx_unlock(&lun->lun_lock);
12011	return (0);
12012}
12013
12014static int
12015ctl_i_t_nexus_reset(union ctl_io *io)
12016{
12017	struct ctl_softc *softc = control_softc;
12018	struct ctl_lun *lun;
12019	uint32_t initidx, residx;
12020
12021	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12022	residx = ctl_get_resindex(&io->io_hdr.nexus);
12023	mtx_lock(&softc->ctl_lock);
12024	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12025		mtx_lock(&lun->lun_lock);
12026		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12027		    io->io_hdr.nexus.initid.id,
12028		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12029#ifdef CTL_WITH_CA
12030		ctl_clear_mask(lun->have_ca, initidx);
12031#endif
12032		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
12033			lun->flags &= ~CTL_LUN_RESERVED;
12034		ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12035		mtx_unlock(&lun->lun_lock);
12036	}
12037	mtx_unlock(&softc->ctl_lock);
12038	return (0);
12039}
12040
12041static int
12042ctl_abort_task(union ctl_io *io)
12043{
12044	union ctl_io *xio;
12045	struct ctl_lun *lun;
12046	struct ctl_softc *softc;
12047#if 0
12048	struct sbuf sb;
12049	char printbuf[128];
12050#endif
12051	int found;
12052	uint32_t targ_lun;
12053
12054	softc = control_softc;
12055	found = 0;
12056
12057	/*
12058	 * Look up the LUN.
12059	 */
12060	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12061	mtx_lock(&softc->ctl_lock);
12062	if ((targ_lun < CTL_MAX_LUNS)
12063	 && (softc->ctl_luns[targ_lun] != NULL))
12064		lun = softc->ctl_luns[targ_lun];
12065	else {
12066		mtx_unlock(&softc->ctl_lock);
12067		return (1);
12068	}
12069
12070#if 0
12071	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12072	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12073#endif
12074
12075	mtx_lock(&lun->lun_lock);
12076	mtx_unlock(&softc->ctl_lock);
12077	/*
12078	 * Run through the OOA queue and attempt to find the given I/O.
12079	 * The target port, initiator ID, tag type and tag number have to
12080	 * match the values that we got from the initiator.  If we have an
12081	 * untagged command to abort, simply abort the first untagged command
12082	 * we come to.  We only allow one untagged command at a time of course.
12083	 */
12084#if 0
12085	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12086#endif
12087	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12088	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12089#if 0
12090		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12091
12092		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12093			    lun->lun, xio->scsiio.tag_num,
12094			    xio->scsiio.tag_type,
12095			    (xio->io_hdr.blocked_links.tqe_prev
12096			    == NULL) ? "" : " BLOCKED",
12097			    (xio->io_hdr.flags &
12098			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12099			    (xio->io_hdr.flags &
12100			    CTL_FLAG_ABORT) ? " ABORT" : "",
12101			    (xio->io_hdr.flags &
12102			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12103		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12104		sbuf_finish(&sb);
12105		printf("%s\n", sbuf_data(&sb));
12106#endif
12107
12108		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12109		 && (xio->io_hdr.nexus.initid.id ==
12110		     io->io_hdr.nexus.initid.id)) {
12111			/*
12112			 * If the abort says that the task is untagged, the
12113			 * task in the queue must be untagged.  Otherwise,
12114			 * we just check to see whether the tag numbers
12115			 * match.  This is because the QLogic firmware
12116			 * doesn't pass back the tag type in an abort
12117			 * request.
12118			 */
12119#if 0
12120			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12121			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12122			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12123#endif
12124			/*
12125			 * XXX KDM we've got problems with FC, because it
12126			 * doesn't send down a tag type with aborts.  So we
12127			 * can only really go by the tag number...
12128			 * This may cause problems with parallel SCSI.
12129			 * Need to figure that out!!
12130			 */
12131			if (xio->scsiio.tag_num == io->taskio.tag_num) {
12132				xio->io_hdr.flags |= CTL_FLAG_ABORT;
12133				found = 1;
12134				if ((io->io_hdr.flags &
12135				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
12136				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12137					union ctl_ha_msg msg_info;
12138
12139					io->io_hdr.flags |=
12140					                CTL_FLAG_SENT_2OTHER_SC;
12141					msg_info.hdr.nexus = io->io_hdr.nexus;
12142					msg_info.task.task_action =
12143						CTL_TASK_ABORT_TASK;
12144					msg_info.task.tag_num =
12145						io->taskio.tag_num;
12146					msg_info.task.tag_type =
12147						io->taskio.tag_type;
12148					msg_info.hdr.msg_type =
12149						CTL_MSG_MANAGE_TASKS;
12150					msg_info.hdr.original_sc = NULL;
12151					msg_info.hdr.serializing_sc = NULL;
12152#if 0
12153					printf("Sent Abort to other side\n");
12154#endif
12155					if (CTL_HA_STATUS_SUCCESS !=
12156					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12157		    				(void *)&msg_info,
12158						sizeof(msg_info), 0)) {
12159					}
12160				}
12161#if 0
12162				printf("ctl_abort_task: found I/O to abort\n");
12163#endif
12164				break;
12165			}
12166		}
12167	}
12168	mtx_unlock(&lun->lun_lock);
12169
12170	if (found == 0) {
12171		/*
12172		 * This isn't really an error.  It's entirely possible for
12173		 * the abort and command completion to cross on the wire.
12174		 * This is more of an informative/diagnostic error.
12175		 */
12176#if 0
12177		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12178		       "%d:%d:%d:%d tag %d type %d\n",
12179		       io->io_hdr.nexus.initid.id,
12180		       io->io_hdr.nexus.targ_port,
12181		       io->io_hdr.nexus.targ_target.id,
12182		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12183		       io->taskio.tag_type);
12184#endif
12185	}
12186	return (0);
12187}
12188
12189static void
12190ctl_run_task(union ctl_io *io)
12191{
12192	struct ctl_softc *softc = control_softc;
12193	int retval = 1;
12194	const char *task_desc;
12195
12196	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12197
12198	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12199	    ("ctl_run_task: Unextected io_type %d\n",
12200	     io->io_hdr.io_type));
12201
12202	task_desc = ctl_scsi_task_string(&io->taskio);
12203	if (task_desc != NULL) {
12204#ifdef NEEDTOPORT
12205		csevent_log(CSC_CTL | CSC_SHELF_SW |
12206			    CTL_TASK_REPORT,
12207			    csevent_LogType_Trace,
12208			    csevent_Severity_Information,
12209			    csevent_AlertLevel_Green,
12210			    csevent_FRU_Firmware,
12211			    csevent_FRU_Unknown,
12212			    "CTL: received task: %s",task_desc);
12213#endif
12214	} else {
12215#ifdef NEEDTOPORT
12216		csevent_log(CSC_CTL | CSC_SHELF_SW |
12217			    CTL_TASK_REPORT,
12218			    csevent_LogType_Trace,
12219			    csevent_Severity_Information,
12220			    csevent_AlertLevel_Green,
12221			    csevent_FRU_Firmware,
12222			    csevent_FRU_Unknown,
12223			    "CTL: received unknown task "
12224			    "type: %d (%#x)",
12225			    io->taskio.task_action,
12226			    io->taskio.task_action);
12227#endif
12228	}
12229	switch (io->taskio.task_action) {
12230	case CTL_TASK_ABORT_TASK:
12231		retval = ctl_abort_task(io);
12232		break;
12233	case CTL_TASK_ABORT_TASK_SET:
12234	case CTL_TASK_CLEAR_TASK_SET:
12235		retval = ctl_abort_task_set(io);
12236		break;
12237	case CTL_TASK_CLEAR_ACA:
12238		break;
12239	case CTL_TASK_I_T_NEXUS_RESET:
12240		retval = ctl_i_t_nexus_reset(io);
12241		break;
12242	case CTL_TASK_LUN_RESET: {
12243		struct ctl_lun *lun;
12244		uint32_t targ_lun;
12245
12246		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12247		mtx_lock(&softc->ctl_lock);
12248		if ((targ_lun < CTL_MAX_LUNS)
12249		 && (softc->ctl_luns[targ_lun] != NULL))
12250			lun = softc->ctl_luns[targ_lun];
12251		else {
12252			mtx_unlock(&softc->ctl_lock);
12253			retval = 1;
12254			break;
12255		}
12256
12257		if (!(io->io_hdr.flags &
12258		    CTL_FLAG_FROM_OTHER_SC)) {
12259			union ctl_ha_msg msg_info;
12260
12261			io->io_hdr.flags |=
12262				CTL_FLAG_SENT_2OTHER_SC;
12263			msg_info.hdr.msg_type =
12264				CTL_MSG_MANAGE_TASKS;
12265			msg_info.hdr.nexus = io->io_hdr.nexus;
12266			msg_info.task.task_action =
12267				CTL_TASK_LUN_RESET;
12268			msg_info.hdr.original_sc = NULL;
12269			msg_info.hdr.serializing_sc = NULL;
12270			if (CTL_HA_STATUS_SUCCESS !=
12271			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12272			    (void *)&msg_info,
12273			    sizeof(msg_info), 0)) {
12274			}
12275		}
12276
12277		retval = ctl_lun_reset(lun, io,
12278				       CTL_UA_LUN_RESET);
12279		mtx_unlock(&softc->ctl_lock);
12280		break;
12281	}
12282	case CTL_TASK_TARGET_RESET:
12283		retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12284		break;
12285	case CTL_TASK_BUS_RESET:
12286		retval = ctl_bus_reset(softc, io);
12287		break;
12288	case CTL_TASK_PORT_LOGIN:
12289		break;
12290	case CTL_TASK_PORT_LOGOUT:
12291		break;
12292	default:
12293		printf("ctl_run_task: got unknown task management event %d\n",
12294		       io->taskio.task_action);
12295		break;
12296	}
12297	if (retval == 0)
12298		io->io_hdr.status = CTL_SUCCESS;
12299	else
12300		io->io_hdr.status = CTL_ERROR;
12301	ctl_done(io);
12302}
12303
12304/*
12305 * For HA operation.  Handle commands that come in from the other
12306 * controller.
12307 */
12308static void
12309ctl_handle_isc(union ctl_io *io)
12310{
12311	int free_io;
12312	struct ctl_lun *lun;
12313	struct ctl_softc *softc;
12314	uint32_t targ_lun;
12315
12316	softc = control_softc;
12317
12318	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12319	lun = softc->ctl_luns[targ_lun];
12320
12321	switch (io->io_hdr.msg_type) {
12322	case CTL_MSG_SERIALIZE:
12323		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12324		break;
12325	case CTL_MSG_R2R: {
12326		const struct ctl_cmd_entry *entry;
12327
12328		/*
12329		 * This is only used in SER_ONLY mode.
12330		 */
12331		free_io = 0;
12332		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12333		mtx_lock(&lun->lun_lock);
12334		if (ctl_scsiio_lun_check(lun,
12335		    entry, (struct ctl_scsiio *)io) != 0) {
12336			mtx_unlock(&lun->lun_lock);
12337			ctl_done(io);
12338			break;
12339		}
12340		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12341		mtx_unlock(&lun->lun_lock);
12342		ctl_enqueue_rtr(io);
12343		break;
12344	}
12345	case CTL_MSG_FINISH_IO:
12346		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12347			free_io = 0;
12348			ctl_done(io);
12349		} else {
12350			free_io = 1;
12351			mtx_lock(&lun->lun_lock);
12352			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12353				     ooa_links);
12354			ctl_check_blocked(lun);
12355			mtx_unlock(&lun->lun_lock);
12356		}
12357		break;
12358	case CTL_MSG_PERS_ACTION:
12359		ctl_hndl_per_res_out_on_other_sc(
12360			(union ctl_ha_msg *)&io->presio.pr_msg);
12361		free_io = 1;
12362		break;
12363	case CTL_MSG_BAD_JUJU:
12364		free_io = 0;
12365		ctl_done(io);
12366		break;
12367	case CTL_MSG_DATAMOVE:
12368		/* Only used in XFER mode */
12369		free_io = 0;
12370		ctl_datamove_remote(io);
12371		break;
12372	case CTL_MSG_DATAMOVE_DONE:
12373		/* Only used in XFER mode */
12374		free_io = 0;
12375		io->scsiio.be_move_done(io);
12376		break;
12377	default:
12378		free_io = 1;
12379		printf("%s: Invalid message type %d\n",
12380		       __func__, io->io_hdr.msg_type);
12381		break;
12382	}
12383	if (free_io)
12384		ctl_free_io(io);
12385
12386}
12387
12388
12389/*
12390 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12391 * there is no match.
12392 */
12393static ctl_lun_error_pattern
12394ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12395{
12396	const struct ctl_cmd_entry *entry;
12397	ctl_lun_error_pattern filtered_pattern, pattern;
12398
12399	pattern = desc->error_pattern;
12400
12401	/*
12402	 * XXX KDM we need more data passed into this function to match a
12403	 * custom pattern, and we actually need to implement custom pattern
12404	 * matching.
12405	 */
12406	if (pattern & CTL_LUN_PAT_CMD)
12407		return (CTL_LUN_PAT_CMD);
12408
12409	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12410		return (CTL_LUN_PAT_ANY);
12411
12412	entry = ctl_get_cmd_entry(ctsio, NULL);
12413
12414	filtered_pattern = entry->pattern & pattern;
12415
12416	/*
12417	 * If the user requested specific flags in the pattern (e.g.
12418	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12419	 * flags.
12420	 *
12421	 * If the user did not specify any flags, it doesn't matter whether
12422	 * or not the command supports the flags.
12423	 */
12424	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12425	     (pattern & ~CTL_LUN_PAT_MASK))
12426		return (CTL_LUN_PAT_NONE);
12427
12428	/*
12429	 * If the user asked for a range check, see if the requested LBA
12430	 * range overlaps with this command's LBA range.
12431	 */
12432	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12433		uint64_t lba1;
12434		uint64_t len1;
12435		ctl_action action;
12436		int retval;
12437
12438		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12439		if (retval != 0)
12440			return (CTL_LUN_PAT_NONE);
12441
12442		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12443					      desc->lba_range.len, FALSE);
12444		/*
12445		 * A "pass" means that the LBA ranges don't overlap, so
12446		 * this doesn't match the user's range criteria.
12447		 */
12448		if (action == CTL_ACTION_PASS)
12449			return (CTL_LUN_PAT_NONE);
12450	}
12451
12452	return (filtered_pattern);
12453}
12454
12455static void
12456ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12457{
12458	struct ctl_error_desc *desc, *desc2;
12459
12460	mtx_assert(&lun->lun_lock, MA_OWNED);
12461
12462	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12463		ctl_lun_error_pattern pattern;
12464		/*
12465		 * Check to see whether this particular command matches
12466		 * the pattern in the descriptor.
12467		 */
12468		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12469		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12470			continue;
12471
12472		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12473		case CTL_LUN_INJ_ABORTED:
12474			ctl_set_aborted(&io->scsiio);
12475			break;
12476		case CTL_LUN_INJ_MEDIUM_ERR:
12477			ctl_set_medium_error(&io->scsiio);
12478			break;
12479		case CTL_LUN_INJ_UA:
12480			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12481			 * OCCURRED */
12482			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12483			break;
12484		case CTL_LUN_INJ_CUSTOM:
12485			/*
12486			 * We're assuming the user knows what he is doing.
12487			 * Just copy the sense information without doing
12488			 * checks.
12489			 */
12490			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12491			      MIN(sizeof(desc->custom_sense),
12492				  sizeof(io->scsiio.sense_data)));
12493			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12494			io->scsiio.sense_len = SSD_FULL_SIZE;
12495			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12496			break;
12497		case CTL_LUN_INJ_NONE:
12498		default:
12499			/*
12500			 * If this is an error injection type we don't know
12501			 * about, clear the continuous flag (if it is set)
12502			 * so it will get deleted below.
12503			 */
12504			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12505			break;
12506		}
12507		/*
12508		 * By default, each error injection action is a one-shot
12509		 */
12510		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12511			continue;
12512
12513		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12514
12515		free(desc, M_CTL);
12516	}
12517}
12518
12519#ifdef CTL_IO_DELAY
12520static void
12521ctl_datamove_timer_wakeup(void *arg)
12522{
12523	union ctl_io *io;
12524
12525	io = (union ctl_io *)arg;
12526
12527	ctl_datamove(io);
12528}
12529#endif /* CTL_IO_DELAY */
12530
12531void
12532ctl_datamove(union ctl_io *io)
12533{
12534	void (*fe_datamove)(union ctl_io *io);
12535
12536	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12537
12538	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12539
12540#ifdef CTL_TIME_IO
12541	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12542		char str[256];
12543		char path_str[64];
12544		struct sbuf sb;
12545
12546		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12547		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12548
12549		sbuf_cat(&sb, path_str);
12550		switch (io->io_hdr.io_type) {
12551		case CTL_IO_SCSI:
12552			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12553			sbuf_printf(&sb, "\n");
12554			sbuf_cat(&sb, path_str);
12555			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12556				    io->scsiio.tag_num, io->scsiio.tag_type);
12557			break;
12558		case CTL_IO_TASK:
12559			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12560				    "Tag Type: %d\n", io->taskio.task_action,
12561				    io->taskio.tag_num, io->taskio.tag_type);
12562			break;
12563		default:
12564			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12565			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12566			break;
12567		}
12568		sbuf_cat(&sb, path_str);
12569		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12570			    (intmax_t)time_uptime - io->io_hdr.start_time);
12571		sbuf_finish(&sb);
12572		printf("%s", sbuf_data(&sb));
12573	}
12574#endif /* CTL_TIME_IO */
12575
12576#ifdef CTL_IO_DELAY
12577	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12578		struct ctl_lun *lun;
12579
12580		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12581
12582		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12583	} else {
12584		struct ctl_lun *lun;
12585
12586		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12587		if ((lun != NULL)
12588		 && (lun->delay_info.datamove_delay > 0)) {
12589			struct callout *callout;
12590
12591			callout = (struct callout *)&io->io_hdr.timer_bytes;
12592			callout_init(callout, /*mpsafe*/ 1);
12593			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12594			callout_reset(callout,
12595				      lun->delay_info.datamove_delay * hz,
12596				      ctl_datamove_timer_wakeup, io);
12597			if (lun->delay_info.datamove_type ==
12598			    CTL_DELAY_TYPE_ONESHOT)
12599				lun->delay_info.datamove_delay = 0;
12600			return;
12601		}
12602	}
12603#endif
12604
12605	/*
12606	 * This command has been aborted.  Set the port status, so we fail
12607	 * the data move.
12608	 */
12609	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12610		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12611		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12612		       io->io_hdr.nexus.targ_port,
12613		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12614		       io->io_hdr.nexus.targ_lun);
12615		io->io_hdr.port_status = 31337;
12616		/*
12617		 * Note that the backend, in this case, will get the
12618		 * callback in its context.  In other cases it may get
12619		 * called in the frontend's interrupt thread context.
12620		 */
12621		io->scsiio.be_move_done(io);
12622		return;
12623	}
12624
12625	/* Don't confuse frontend with zero length data move. */
12626	if (io->scsiio.kern_data_len == 0) {
12627		io->scsiio.be_move_done(io);
12628		return;
12629	}
12630
12631	/*
12632	 * If we're in XFER mode and this I/O is from the other shelf
12633	 * controller, we need to send the DMA to the other side to
12634	 * actually transfer the data to/from the host.  In serialize only
12635	 * mode the transfer happens below CTL and ctl_datamove() is only
12636	 * called on the machine that originally received the I/O.
12637	 */
12638	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12639	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12640		union ctl_ha_msg msg;
12641		uint32_t sg_entries_sent;
12642		int do_sg_copy;
12643		int i;
12644
12645		memset(&msg, 0, sizeof(msg));
12646		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12647		msg.hdr.original_sc = io->io_hdr.original_sc;
12648		msg.hdr.serializing_sc = io;
12649		msg.hdr.nexus = io->io_hdr.nexus;
12650		msg.dt.flags = io->io_hdr.flags;
12651		/*
12652		 * We convert everything into a S/G list here.  We can't
12653		 * pass by reference, only by value between controllers.
12654		 * So we can't pass a pointer to the S/G list, only as many
12655		 * S/G entries as we can fit in here.  If it's possible for
12656		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12657		 * then we need to break this up into multiple transfers.
12658		 */
12659		if (io->scsiio.kern_sg_entries == 0) {
12660			msg.dt.kern_sg_entries = 1;
12661			/*
12662			 * If this is in cached memory, flush the cache
12663			 * before we send the DMA request to the other
12664			 * controller.  We want to do this in either the
12665			 * read or the write case.  The read case is
12666			 * straightforward.  In the write case, we want to
12667			 * make sure nothing is in the local cache that
12668			 * could overwrite the DMAed data.
12669			 */
12670			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12671				/*
12672				 * XXX KDM use bus_dmamap_sync() here.
12673				 */
12674			}
12675
12676			/*
12677			 * Convert to a physical address if this is a
12678			 * virtual address.
12679			 */
12680			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12681				msg.dt.sg_list[0].addr =
12682					io->scsiio.kern_data_ptr;
12683			} else {
12684				/*
12685				 * XXX KDM use busdma here!
12686				 */
12687#if 0
12688				msg.dt.sg_list[0].addr = (void *)
12689					vtophys(io->scsiio.kern_data_ptr);
12690#endif
12691			}
12692
12693			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12694			do_sg_copy = 0;
12695		} else {
12696			struct ctl_sg_entry *sgl;
12697
12698			do_sg_copy = 1;
12699			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12700			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12701			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12702				/*
12703				 * XXX KDM use bus_dmamap_sync() here.
12704				 */
12705			}
12706		}
12707
12708		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12709		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12710		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12711		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12712		msg.dt.sg_sequence = 0;
12713
12714		/*
12715		 * Loop until we've sent all of the S/G entries.  On the
12716		 * other end, we'll recompose these S/G entries into one
12717		 * contiguous list before passing it to the
12718		 */
12719		for (sg_entries_sent = 0; sg_entries_sent <
12720		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12721			msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list)/
12722				sizeof(msg.dt.sg_list[0])),
12723				msg.dt.kern_sg_entries - sg_entries_sent);
12724
12725			if (do_sg_copy != 0) {
12726				struct ctl_sg_entry *sgl;
12727				int j;
12728
12729				sgl = (struct ctl_sg_entry *)
12730					io->scsiio.kern_data_ptr;
12731				/*
12732				 * If this is in cached memory, flush the cache
12733				 * before we send the DMA request to the other
12734				 * controller.  We want to do this in either
12735				 * the * read or the write case.  The read
12736				 * case is straightforward.  In the write
12737				 * case, we want to make sure nothing is
12738				 * in the local cache that could overwrite
12739				 * the DMAed data.
12740				 */
12741
12742				for (i = sg_entries_sent, j = 0;
12743				     i < msg.dt.cur_sg_entries; i++, j++) {
12744					if ((io->io_hdr.flags &
12745					     CTL_FLAG_NO_DATASYNC) == 0) {
12746						/*
12747						 * XXX KDM use bus_dmamap_sync()
12748						 */
12749					}
12750					if ((io->io_hdr.flags &
12751					     CTL_FLAG_BUS_ADDR) == 0) {
12752						/*
12753						 * XXX KDM use busdma.
12754						 */
12755#if 0
12756						msg.dt.sg_list[j].addr =(void *)
12757						       vtophys(sgl[i].addr);
12758#endif
12759					} else {
12760						msg.dt.sg_list[j].addr =
12761							sgl[i].addr;
12762					}
12763					msg.dt.sg_list[j].len = sgl[i].len;
12764				}
12765			}
12766
12767			sg_entries_sent += msg.dt.cur_sg_entries;
12768			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12769				msg.dt.sg_last = 1;
12770			else
12771				msg.dt.sg_last = 0;
12772
12773			/*
12774			 * XXX KDM drop and reacquire the lock here?
12775			 */
12776			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12777			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12778				/*
12779				 * XXX do something here.
12780				 */
12781			}
12782
12783			msg.dt.sent_sg_entries = sg_entries_sent;
12784		}
12785		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12786		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12787			ctl_failover_io(io, /*have_lock*/ 0);
12788
12789	} else {
12790
12791		/*
12792		 * Lookup the fe_datamove() function for this particular
12793		 * front end.
12794		 */
12795		fe_datamove =
12796		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12797
12798		fe_datamove(io);
12799	}
12800}
12801
12802static void
12803ctl_send_datamove_done(union ctl_io *io, int have_lock)
12804{
12805	union ctl_ha_msg msg;
12806	int isc_status;
12807
12808	memset(&msg, 0, sizeof(msg));
12809
12810	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12811	msg.hdr.original_sc = io;
12812	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12813	msg.hdr.nexus = io->io_hdr.nexus;
12814	msg.hdr.status = io->io_hdr.status;
12815	msg.scsi.tag_num = io->scsiio.tag_num;
12816	msg.scsi.tag_type = io->scsiio.tag_type;
12817	msg.scsi.scsi_status = io->scsiio.scsi_status;
12818	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12819	       sizeof(io->scsiio.sense_data));
12820	msg.scsi.sense_len = io->scsiio.sense_len;
12821	msg.scsi.sense_residual = io->scsiio.sense_residual;
12822	msg.scsi.fetd_status = io->io_hdr.port_status;
12823	msg.scsi.residual = io->scsiio.residual;
12824	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12825
12826	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12827		ctl_failover_io(io, /*have_lock*/ have_lock);
12828		return;
12829	}
12830
12831	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12832	if (isc_status > CTL_HA_STATUS_SUCCESS) {
12833		/* XXX do something if this fails */
12834	}
12835
12836}
12837
12838/*
12839 * The DMA to the remote side is done, now we need to tell the other side
12840 * we're done so it can continue with its data movement.
12841 */
12842static void
12843ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12844{
12845	union ctl_io *io;
12846
12847	io = rq->context;
12848
12849	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12850		printf("%s: ISC DMA write failed with error %d", __func__,
12851		       rq->ret);
12852		ctl_set_internal_failure(&io->scsiio,
12853					 /*sks_valid*/ 1,
12854					 /*retry_count*/ rq->ret);
12855	}
12856
12857	ctl_dt_req_free(rq);
12858
12859	/*
12860	 * In this case, we had to malloc the memory locally.  Free it.
12861	 */
12862	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12863		int i;
12864		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12865			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12866	}
12867	/*
12868	 * The data is in local and remote memory, so now we need to send
12869	 * status (good or back) back to the other side.
12870	 */
12871	ctl_send_datamove_done(io, /*have_lock*/ 0);
12872}
12873
12874/*
12875 * We've moved the data from the host/controller into local memory.  Now we
12876 * need to push it over to the remote controller's memory.
12877 */
12878static int
12879ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12880{
12881	int retval;
12882
12883	retval = 0;
12884
12885	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12886					  ctl_datamove_remote_write_cb);
12887
12888	return (retval);
12889}
12890
12891static void
12892ctl_datamove_remote_write(union ctl_io *io)
12893{
12894	int retval;
12895	void (*fe_datamove)(union ctl_io *io);
12896
12897	/*
12898	 * - Get the data from the host/HBA into local memory.
12899	 * - DMA memory from the local controller to the remote controller.
12900	 * - Send status back to the remote controller.
12901	 */
12902
12903	retval = ctl_datamove_remote_sgl_setup(io);
12904	if (retval != 0)
12905		return;
12906
12907	/* Switch the pointer over so the FETD knows what to do */
12908	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12909
12910	/*
12911	 * Use a custom move done callback, since we need to send completion
12912	 * back to the other controller, not to the backend on this side.
12913	 */
12914	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12915
12916	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12917
12918	fe_datamove(io);
12919
12920	return;
12921
12922}
12923
12924static int
12925ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12926{
12927#if 0
12928	char str[256];
12929	char path_str[64];
12930	struct sbuf sb;
12931#endif
12932
12933	/*
12934	 * In this case, we had to malloc the memory locally.  Free it.
12935	 */
12936	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12937		int i;
12938		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12939			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12940	}
12941
12942#if 0
12943	scsi_path_string(io, path_str, sizeof(path_str));
12944	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12945	sbuf_cat(&sb, path_str);
12946	scsi_command_string(&io->scsiio, NULL, &sb);
12947	sbuf_printf(&sb, "\n");
12948	sbuf_cat(&sb, path_str);
12949	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12950		    io->scsiio.tag_num, io->scsiio.tag_type);
12951	sbuf_cat(&sb, path_str);
12952	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12953		    io->io_hdr.flags, io->io_hdr.status);
12954	sbuf_finish(&sb);
12955	printk("%s", sbuf_data(&sb));
12956#endif
12957
12958
12959	/*
12960	 * The read is done, now we need to send status (good or bad) back
12961	 * to the other side.
12962	 */
12963	ctl_send_datamove_done(io, /*have_lock*/ 0);
12964
12965	return (0);
12966}
12967
12968static void
12969ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12970{
12971	union ctl_io *io;
12972	void (*fe_datamove)(union ctl_io *io);
12973
12974	io = rq->context;
12975
12976	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12977		printf("%s: ISC DMA read failed with error %d", __func__,
12978		       rq->ret);
12979		ctl_set_internal_failure(&io->scsiio,
12980					 /*sks_valid*/ 1,
12981					 /*retry_count*/ rq->ret);
12982	}
12983
12984	ctl_dt_req_free(rq);
12985
12986	/* Switch the pointer over so the FETD knows what to do */
12987	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12988
12989	/*
12990	 * Use a custom move done callback, since we need to send completion
12991	 * back to the other controller, not to the backend on this side.
12992	 */
12993	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12994
12995	/* XXX KDM add checks like the ones in ctl_datamove? */
12996
12997	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12998
12999	fe_datamove(io);
13000}
13001
13002static int
13003ctl_datamove_remote_sgl_setup(union ctl_io *io)
13004{
13005	struct ctl_sg_entry *local_sglist, *remote_sglist;
13006	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13007	struct ctl_softc *softc;
13008	int retval;
13009	int i;
13010
13011	retval = 0;
13012	softc = control_softc;
13013
13014	local_sglist = io->io_hdr.local_sglist;
13015	local_dma_sglist = io->io_hdr.local_dma_sglist;
13016	remote_sglist = io->io_hdr.remote_sglist;
13017	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13018
13019	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13020		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13021			local_sglist[i].len = remote_sglist[i].len;
13022
13023			/*
13024			 * XXX Detect the situation where the RS-level I/O
13025			 * redirector on the other side has already read the
13026			 * data off of the AOR RS on this side, and
13027			 * transferred it to remote (mirror) memory on the
13028			 * other side.  Since we already have the data in
13029			 * memory here, we just need to use it.
13030			 *
13031			 * XXX KDM this can probably be removed once we
13032			 * get the cache device code in and take the
13033			 * current AOR implementation out.
13034			 */
13035#ifdef NEEDTOPORT
13036			if ((remote_sglist[i].addr >=
13037			     (void *)vtophys(softc->mirr->addr))
13038			 && (remote_sglist[i].addr <
13039			     ((void *)vtophys(softc->mirr->addr) +
13040			     CacheMirrorOffset))) {
13041				local_sglist[i].addr = remote_sglist[i].addr -
13042					CacheMirrorOffset;
13043				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13044				     CTL_FLAG_DATA_IN)
13045					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13046			} else {
13047				local_sglist[i].addr = remote_sglist[i].addr +
13048					CacheMirrorOffset;
13049			}
13050#endif
13051#if 0
13052			printf("%s: local %p, remote %p, len %d\n",
13053			       __func__, local_sglist[i].addr,
13054			       remote_sglist[i].addr, local_sglist[i].len);
13055#endif
13056		}
13057	} else {
13058		uint32_t len_to_go;
13059
13060		/*
13061		 * In this case, we don't have automatically allocated
13062		 * memory for this I/O on this controller.  This typically
13063		 * happens with internal CTL I/O -- e.g. inquiry, mode
13064		 * sense, etc.  Anything coming from RAIDCore will have
13065		 * a mirror area available.
13066		 */
13067		len_to_go = io->scsiio.kern_data_len;
13068
13069		/*
13070		 * Clear the no datasync flag, we have to use malloced
13071		 * buffers.
13072		 */
13073		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13074
13075		/*
13076		 * The difficult thing here is that the size of the various
13077		 * S/G segments may be different than the size from the
13078		 * remote controller.  That'll make it harder when DMAing
13079		 * the data back to the other side.
13080		 */
13081		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13082		     sizeof(io->io_hdr.remote_sglist[0])) &&
13083		     (len_to_go > 0); i++) {
13084			local_sglist[i].len = MIN(len_to_go, 131072);
13085			CTL_SIZE_8B(local_dma_sglist[i].len,
13086				    local_sglist[i].len);
13087			local_sglist[i].addr =
13088				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13089
13090			local_dma_sglist[i].addr = local_sglist[i].addr;
13091
13092			if (local_sglist[i].addr == NULL) {
13093				int j;
13094
13095				printf("malloc failed for %zd bytes!",
13096				       local_dma_sglist[i].len);
13097				for (j = 0; j < i; j++) {
13098					free(local_sglist[j].addr, M_CTL);
13099				}
13100				ctl_set_internal_failure(&io->scsiio,
13101							 /*sks_valid*/ 1,
13102							 /*retry_count*/ 4857);
13103				retval = 1;
13104				goto bailout_error;
13105
13106			}
13107			/* XXX KDM do we need a sync here? */
13108
13109			len_to_go -= local_sglist[i].len;
13110		}
13111		/*
13112		 * Reset the number of S/G entries accordingly.  The
13113		 * original number of S/G entries is available in
13114		 * rem_sg_entries.
13115		 */
13116		io->scsiio.kern_sg_entries = i;
13117
13118#if 0
13119		printf("%s: kern_sg_entries = %d\n", __func__,
13120		       io->scsiio.kern_sg_entries);
13121		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13122			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13123			       local_sglist[i].addr, local_sglist[i].len,
13124			       local_dma_sglist[i].len);
13125#endif
13126	}
13127
13128
13129	return (retval);
13130
13131bailout_error:
13132
13133	ctl_send_datamove_done(io, /*have_lock*/ 0);
13134
13135	return (retval);
13136}
13137
13138static int
13139ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13140			 ctl_ha_dt_cb callback)
13141{
13142	struct ctl_ha_dt_req *rq;
13143	struct ctl_sg_entry *remote_sglist, *local_sglist;
13144	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13145	uint32_t local_used, remote_used, total_used;
13146	int retval;
13147	int i, j;
13148
13149	retval = 0;
13150
13151	rq = ctl_dt_req_alloc();
13152
13153	/*
13154	 * If we failed to allocate the request, and if the DMA didn't fail
13155	 * anyway, set busy status.  This is just a resource allocation
13156	 * failure.
13157	 */
13158	if ((rq == NULL)
13159	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13160		ctl_set_busy(&io->scsiio);
13161
13162	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13163
13164		if (rq != NULL)
13165			ctl_dt_req_free(rq);
13166
13167		/*
13168		 * The data move failed.  We need to return status back
13169		 * to the other controller.  No point in trying to DMA
13170		 * data to the remote controller.
13171		 */
13172
13173		ctl_send_datamove_done(io, /*have_lock*/ 0);
13174
13175		retval = 1;
13176
13177		goto bailout;
13178	}
13179
13180	local_sglist = io->io_hdr.local_sglist;
13181	local_dma_sglist = io->io_hdr.local_dma_sglist;
13182	remote_sglist = io->io_hdr.remote_sglist;
13183	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13184	local_used = 0;
13185	remote_used = 0;
13186	total_used = 0;
13187
13188	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13189		rq->ret = CTL_HA_STATUS_SUCCESS;
13190		rq->context = io;
13191		callback(rq);
13192		goto bailout;
13193	}
13194
13195	/*
13196	 * Pull/push the data over the wire from/to the other controller.
13197	 * This takes into account the possibility that the local and
13198	 * remote sglists may not be identical in terms of the size of
13199	 * the elements and the number of elements.
13200	 *
13201	 * One fundamental assumption here is that the length allocated for
13202	 * both the local and remote sglists is identical.  Otherwise, we've
13203	 * essentially got a coding error of some sort.
13204	 */
13205	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13206		int isc_ret;
13207		uint32_t cur_len, dma_length;
13208		uint8_t *tmp_ptr;
13209
13210		rq->id = CTL_HA_DATA_CTL;
13211		rq->command = command;
13212		rq->context = io;
13213
13214		/*
13215		 * Both pointers should be aligned.  But it is possible
13216		 * that the allocation length is not.  They should both
13217		 * also have enough slack left over at the end, though,
13218		 * to round up to the next 8 byte boundary.
13219		 */
13220		cur_len = MIN(local_sglist[i].len - local_used,
13221			      remote_sglist[j].len - remote_used);
13222
13223		/*
13224		 * In this case, we have a size issue and need to decrease
13225		 * the size, except in the case where we actually have less
13226		 * than 8 bytes left.  In that case, we need to increase
13227		 * the DMA length to get the last bit.
13228		 */
13229		if ((cur_len & 0x7) != 0) {
13230			if (cur_len > 0x7) {
13231				cur_len = cur_len - (cur_len & 0x7);
13232				dma_length = cur_len;
13233			} else {
13234				CTL_SIZE_8B(dma_length, cur_len);
13235			}
13236
13237		} else
13238			dma_length = cur_len;
13239
13240		/*
13241		 * If we had to allocate memory for this I/O, instead of using
13242		 * the non-cached mirror memory, we'll need to flush the cache
13243		 * before trying to DMA to the other controller.
13244		 *
13245		 * We could end up doing this multiple times for the same
13246		 * segment if we have a larger local segment than remote
13247		 * segment.  That shouldn't be an issue.
13248		 */
13249		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13250			/*
13251			 * XXX KDM use bus_dmamap_sync() here.
13252			 */
13253		}
13254
13255		rq->size = dma_length;
13256
13257		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13258		tmp_ptr += local_used;
13259
13260		/* Use physical addresses when talking to ISC hardware */
13261		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13262			/* XXX KDM use busdma */
13263#if 0
13264			rq->local = vtophys(tmp_ptr);
13265#endif
13266		} else
13267			rq->local = tmp_ptr;
13268
13269		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13270		tmp_ptr += remote_used;
13271		rq->remote = tmp_ptr;
13272
13273		rq->callback = NULL;
13274
13275		local_used += cur_len;
13276		if (local_used >= local_sglist[i].len) {
13277			i++;
13278			local_used = 0;
13279		}
13280
13281		remote_used += cur_len;
13282		if (remote_used >= remote_sglist[j].len) {
13283			j++;
13284			remote_used = 0;
13285		}
13286		total_used += cur_len;
13287
13288		if (total_used >= io->scsiio.kern_data_len)
13289			rq->callback = callback;
13290
13291		if ((rq->size & 0x7) != 0) {
13292			printf("%s: warning: size %d is not on 8b boundary\n",
13293			       __func__, rq->size);
13294		}
13295		if (((uintptr_t)rq->local & 0x7) != 0) {
13296			printf("%s: warning: local %p not on 8b boundary\n",
13297			       __func__, rq->local);
13298		}
13299		if (((uintptr_t)rq->remote & 0x7) != 0) {
13300			printf("%s: warning: remote %p not on 8b boundary\n",
13301			       __func__, rq->local);
13302		}
13303#if 0
13304		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13305		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13306		       rq->local, rq->remote, rq->size);
13307#endif
13308
13309		isc_ret = ctl_dt_single(rq);
13310		if (isc_ret == CTL_HA_STATUS_WAIT)
13311			continue;
13312
13313		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13314			rq->ret = CTL_HA_STATUS_SUCCESS;
13315		} else {
13316			rq->ret = isc_ret;
13317		}
13318		callback(rq);
13319		goto bailout;
13320	}
13321
13322bailout:
13323	return (retval);
13324
13325}
13326
13327static void
13328ctl_datamove_remote_read(union ctl_io *io)
13329{
13330	int retval;
13331	int i;
13332
13333	/*
13334	 * This will send an error to the other controller in the case of a
13335	 * failure.
13336	 */
13337	retval = ctl_datamove_remote_sgl_setup(io);
13338	if (retval != 0)
13339		return;
13340
13341	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13342					  ctl_datamove_remote_read_cb);
13343	if ((retval != 0)
13344	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13345		/*
13346		 * Make sure we free memory if there was an error..  The
13347		 * ctl_datamove_remote_xfer() function will send the
13348		 * datamove done message, or call the callback with an
13349		 * error if there is a problem.
13350		 */
13351		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13352			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13353	}
13354
13355	return;
13356}
13357
13358/*
13359 * Process a datamove request from the other controller.  This is used for
13360 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13361 * first.  Once that is complete, the data gets DMAed into the remote
13362 * controller's memory.  For reads, we DMA from the remote controller's
13363 * memory into our memory first, and then move it out to the FETD.
13364 */
13365static void
13366ctl_datamove_remote(union ctl_io *io)
13367{
13368	struct ctl_softc *softc;
13369
13370	softc = control_softc;
13371
13372	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13373
13374	/*
13375	 * Note that we look for an aborted I/O here, but don't do some of
13376	 * the other checks that ctl_datamove() normally does.
13377	 * We don't need to run the datamove delay code, since that should
13378	 * have been done if need be on the other controller.
13379	 */
13380	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13381		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13382		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13383		       io->io_hdr.nexus.targ_port,
13384		       io->io_hdr.nexus.targ_target.id,
13385		       io->io_hdr.nexus.targ_lun);
13386		io->io_hdr.port_status = 31338;
13387		ctl_send_datamove_done(io, /*have_lock*/ 0);
13388		return;
13389	}
13390
13391	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13392		ctl_datamove_remote_write(io);
13393	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13394		ctl_datamove_remote_read(io);
13395	} else {
13396		union ctl_ha_msg msg;
13397		struct scsi_sense_data *sense;
13398		uint8_t sks[3];
13399		int retry_count;
13400
13401		memset(&msg, 0, sizeof(msg));
13402
13403		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13404		msg.hdr.status = CTL_SCSI_ERROR;
13405		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13406
13407		retry_count = 4243;
13408
13409		sense = &msg.scsi.sense_data;
13410		sks[0] = SSD_SCS_VALID;
13411		sks[1] = (retry_count >> 8) & 0xff;
13412		sks[2] = retry_count & 0xff;
13413
13414		/* "Internal target failure" */
13415		scsi_set_sense_data(sense,
13416				    /*sense_format*/ SSD_TYPE_NONE,
13417				    /*current_error*/ 1,
13418				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13419				    /*asc*/ 0x44,
13420				    /*ascq*/ 0x00,
13421				    /*type*/ SSD_ELEM_SKS,
13422				    /*size*/ sizeof(sks),
13423				    /*data*/ sks,
13424				    SSD_ELEM_NONE);
13425
13426		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13427		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13428			ctl_failover_io(io, /*have_lock*/ 1);
13429			return;
13430		}
13431
13432		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13433		    CTL_HA_STATUS_SUCCESS) {
13434			/* XXX KDM what to do if this fails? */
13435		}
13436		return;
13437	}
13438
13439}
13440
13441static int
13442ctl_process_done(union ctl_io *io)
13443{
13444	struct ctl_lun *lun;
13445	struct ctl_softc *softc = control_softc;
13446	void (*fe_done)(union ctl_io *io);
13447	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13448
13449	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13450
13451	fe_done = softc->ctl_ports[targ_port]->fe_done;
13452
13453#ifdef CTL_TIME_IO
13454	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13455		char str[256];
13456		char path_str[64];
13457		struct sbuf sb;
13458
13459		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13460		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13461
13462		sbuf_cat(&sb, path_str);
13463		switch (io->io_hdr.io_type) {
13464		case CTL_IO_SCSI:
13465			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13466			sbuf_printf(&sb, "\n");
13467			sbuf_cat(&sb, path_str);
13468			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13469				    io->scsiio.tag_num, io->scsiio.tag_type);
13470			break;
13471		case CTL_IO_TASK:
13472			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13473				    "Tag Type: %d\n", io->taskio.task_action,
13474				    io->taskio.tag_num, io->taskio.tag_type);
13475			break;
13476		default:
13477			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13478			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13479			break;
13480		}
13481		sbuf_cat(&sb, path_str);
13482		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13483			    (intmax_t)time_uptime - io->io_hdr.start_time);
13484		sbuf_finish(&sb);
13485		printf("%s", sbuf_data(&sb));
13486	}
13487#endif /* CTL_TIME_IO */
13488
13489	switch (io->io_hdr.io_type) {
13490	case CTL_IO_SCSI:
13491		break;
13492	case CTL_IO_TASK:
13493		if (bootverbose || (ctl_debug & CTL_DEBUG_INFO))
13494			ctl_io_error_print(io, NULL);
13495		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13496			ctl_free_io(io);
13497		else
13498			fe_done(io);
13499		return (CTL_RETVAL_COMPLETE);
13500	default:
13501		panic("ctl_process_done: invalid io type %d\n",
13502		      io->io_hdr.io_type);
13503		break; /* NOTREACHED */
13504	}
13505
13506	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13507	if (lun == NULL) {
13508		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13509				 io->io_hdr.nexus.targ_mapped_lun));
13510		goto bailout;
13511	}
13512
13513	mtx_lock(&lun->lun_lock);
13514
13515	/*
13516	 * Check to see if we have any errors to inject here.  We only
13517	 * inject errors for commands that don't already have errors set.
13518	 */
13519	if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
13520	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13521	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13522		ctl_inject_error(lun, io);
13523
13524	/*
13525	 * XXX KDM how do we treat commands that aren't completed
13526	 * successfully?
13527	 *
13528	 * XXX KDM should we also track I/O latency?
13529	 */
13530	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13531	    io->io_hdr.io_type == CTL_IO_SCSI) {
13532#ifdef CTL_TIME_IO
13533		struct bintime cur_bt;
13534#endif
13535		int type;
13536
13537		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13538		    CTL_FLAG_DATA_IN)
13539			type = CTL_STATS_READ;
13540		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13541		    CTL_FLAG_DATA_OUT)
13542			type = CTL_STATS_WRITE;
13543		else
13544			type = CTL_STATS_NO_IO;
13545
13546		lun->stats.ports[targ_port].bytes[type] +=
13547		    io->scsiio.kern_total_len;
13548		lun->stats.ports[targ_port].operations[type]++;
13549#ifdef CTL_TIME_IO
13550		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13551		   &io->io_hdr.dma_bt);
13552		lun->stats.ports[targ_port].num_dmas[type] +=
13553		    io->io_hdr.num_dmas;
13554		getbintime(&cur_bt);
13555		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13556		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13557#endif
13558	}
13559
13560	/*
13561	 * Remove this from the OOA queue.
13562	 */
13563	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13564
13565	/*
13566	 * Run through the blocked queue on this LUN and see if anything
13567	 * has become unblocked, now that this transaction is done.
13568	 */
13569	ctl_check_blocked(lun);
13570
13571	/*
13572	 * If the LUN has been invalidated, free it if there is nothing
13573	 * left on its OOA queue.
13574	 */
13575	if ((lun->flags & CTL_LUN_INVALID)
13576	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13577		mtx_unlock(&lun->lun_lock);
13578		mtx_lock(&softc->ctl_lock);
13579		ctl_free_lun(lun);
13580		mtx_unlock(&softc->ctl_lock);
13581	} else
13582		mtx_unlock(&lun->lun_lock);
13583
13584bailout:
13585
13586	/*
13587	 * If this command has been aborted, make sure we set the status
13588	 * properly.  The FETD is responsible for freeing the I/O and doing
13589	 * whatever it needs to do to clean up its state.
13590	 */
13591	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13592		ctl_set_task_aborted(&io->scsiio);
13593
13594	/*
13595	 * If enabled, print command error status.
13596	 * We don't print UAs unless debugging was enabled explicitly.
13597	 */
13598	do {
13599		if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)
13600			break;
13601		if (!bootverbose && (ctl_debug & CTL_DEBUG_INFO) == 0)
13602			break;
13603		if ((ctl_debug & CTL_DEBUG_INFO) == 0 &&
13604		    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR) &&
13605		     (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13606			int error_code, sense_key, asc, ascq;
13607
13608			scsi_extract_sense_len(&io->scsiio.sense_data,
13609			    io->scsiio.sense_len, &error_code, &sense_key,
13610			    &asc, &ascq, /*show_errors*/ 0);
13611			if (sense_key == SSD_KEY_UNIT_ATTENTION)
13612				break;
13613		}
13614
13615		ctl_io_error_print(io, NULL);
13616	} while (0);
13617
13618	/*
13619	 * Tell the FETD or the other shelf controller we're done with this
13620	 * command.  Note that only SCSI commands get to this point.  Task
13621	 * management commands are completed above.
13622	 *
13623	 * We only send status to the other controller if we're in XFER
13624	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13625	 * received the I/O (from CTL's perspective), and so the status is
13626	 * generated there.
13627	 *
13628	 * XXX KDM if we hold the lock here, we could cause a deadlock
13629	 * if the frontend comes back in in this context to queue
13630	 * something.
13631	 */
13632	if ((softc->ha_mode == CTL_HA_MODE_XFER)
13633	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13634		union ctl_ha_msg msg;
13635
13636		memset(&msg, 0, sizeof(msg));
13637		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13638		msg.hdr.original_sc = io->io_hdr.original_sc;
13639		msg.hdr.nexus = io->io_hdr.nexus;
13640		msg.hdr.status = io->io_hdr.status;
13641		msg.scsi.scsi_status = io->scsiio.scsi_status;
13642		msg.scsi.tag_num = io->scsiio.tag_num;
13643		msg.scsi.tag_type = io->scsiio.tag_type;
13644		msg.scsi.sense_len = io->scsiio.sense_len;
13645		msg.scsi.sense_residual = io->scsiio.sense_residual;
13646		msg.scsi.residual = io->scsiio.residual;
13647		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13648		       sizeof(io->scsiio.sense_data));
13649		/*
13650		 * We copy this whether or not this is an I/O-related
13651		 * command.  Otherwise, we'd have to go and check to see
13652		 * whether it's a read/write command, and it really isn't
13653		 * worth it.
13654		 */
13655		memcpy(&msg.scsi.lbalen,
13656		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13657		       sizeof(msg.scsi.lbalen));
13658
13659		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13660				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13661			/* XXX do something here */
13662		}
13663
13664		ctl_free_io(io);
13665	} else
13666		fe_done(io);
13667
13668	return (CTL_RETVAL_COMPLETE);
13669}
13670
13671#ifdef CTL_WITH_CA
13672/*
13673 * Front end should call this if it doesn't do autosense.  When the request
13674 * sense comes back in from the initiator, we'll dequeue this and send it.
13675 */
13676int
13677ctl_queue_sense(union ctl_io *io)
13678{
13679	struct ctl_lun *lun;
13680	struct ctl_softc *softc;
13681	uint32_t initidx, targ_lun;
13682
13683	softc = control_softc;
13684
13685	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13686
13687	/*
13688	 * LUN lookup will likely move to the ctl_work_thread() once we
13689	 * have our new queueing infrastructure (that doesn't put things on
13690	 * a per-LUN queue initially).  That is so that we can handle
13691	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13692	 * can't deal with that right now.
13693	 */
13694	mtx_lock(&softc->ctl_lock);
13695
13696	/*
13697	 * If we don't have a LUN for this, just toss the sense
13698	 * information.
13699	 */
13700	targ_lun = io->io_hdr.nexus.targ_lun;
13701	targ_lun = ctl_map_lun(softc, io->io_hdr.nexus.targ_port, targ_lun);
13702	if ((targ_lun < CTL_MAX_LUNS)
13703	 && (softc->ctl_luns[targ_lun] != NULL))
13704		lun = softc->ctl_luns[targ_lun];
13705	else
13706		goto bailout;
13707
13708	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13709
13710	mtx_lock(&lun->lun_lock);
13711	/*
13712	 * Already have CA set for this LUN...toss the sense information.
13713	 */
13714	if (ctl_is_set(lun->have_ca, initidx)) {
13715		mtx_unlock(&lun->lun_lock);
13716		goto bailout;
13717	}
13718
13719	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13720	       MIN(sizeof(lun->pending_sense[initidx]),
13721	       sizeof(io->scsiio.sense_data)));
13722	ctl_set_mask(lun->have_ca, initidx);
13723	mtx_unlock(&lun->lun_lock);
13724
13725bailout:
13726	mtx_unlock(&softc->ctl_lock);
13727
13728	ctl_free_io(io);
13729
13730	return (CTL_RETVAL_COMPLETE);
13731}
13732#endif
13733
13734/*
13735 * Primary command inlet from frontend ports.  All SCSI and task I/O
13736 * requests must go through this function.
13737 */
13738int
13739ctl_queue(union ctl_io *io)
13740{
13741
13742	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13743
13744#ifdef CTL_TIME_IO
13745	io->io_hdr.start_time = time_uptime;
13746	getbintime(&io->io_hdr.start_bt);
13747#endif /* CTL_TIME_IO */
13748
13749	/* Map FE-specific LUN ID into global one. */
13750	io->io_hdr.nexus.targ_mapped_lun =
13751	    ctl_map_lun(control_softc, io->io_hdr.nexus.targ_port,
13752	     io->io_hdr.nexus.targ_lun);
13753
13754	switch (io->io_hdr.io_type) {
13755	case CTL_IO_SCSI:
13756	case CTL_IO_TASK:
13757		if (ctl_debug & CTL_DEBUG_CDB)
13758			ctl_io_print(io);
13759		ctl_enqueue_incoming(io);
13760		break;
13761	default:
13762		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13763		return (EINVAL);
13764	}
13765
13766	return (CTL_RETVAL_COMPLETE);
13767}
13768
13769#ifdef CTL_IO_DELAY
13770static void
13771ctl_done_timer_wakeup(void *arg)
13772{
13773	union ctl_io *io;
13774
13775	io = (union ctl_io *)arg;
13776	ctl_done(io);
13777}
13778#endif /* CTL_IO_DELAY */
13779
13780void
13781ctl_done(union ctl_io *io)
13782{
13783
13784	/*
13785	 * Enable this to catch duplicate completion issues.
13786	 */
13787#if 0
13788	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13789		printf("%s: type %d msg %d cdb %x iptl: "
13790		       "%d:%d:%d:%d tag 0x%04x "
13791		       "flag %#x status %x\n",
13792			__func__,
13793			io->io_hdr.io_type,
13794			io->io_hdr.msg_type,
13795			io->scsiio.cdb[0],
13796			io->io_hdr.nexus.initid.id,
13797			io->io_hdr.nexus.targ_port,
13798			io->io_hdr.nexus.targ_target.id,
13799			io->io_hdr.nexus.targ_lun,
13800			(io->io_hdr.io_type ==
13801			CTL_IO_TASK) ?
13802			io->taskio.tag_num :
13803			io->scsiio.tag_num,
13804		        io->io_hdr.flags,
13805			io->io_hdr.status);
13806	} else
13807		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13808#endif
13809
13810	/*
13811	 * This is an internal copy of an I/O, and should not go through
13812	 * the normal done processing logic.
13813	 */
13814	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13815		return;
13816
13817	/*
13818	 * We need to send a msg to the serializing shelf to finish the IO
13819	 * as well.  We don't send a finish message to the other shelf if
13820	 * this is a task management command.  Task management commands
13821	 * aren't serialized in the OOA queue, but rather just executed on
13822	 * both shelf controllers for commands that originated on that
13823	 * controller.
13824	 */
13825	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13826	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
13827		union ctl_ha_msg msg_io;
13828
13829		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13830		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13831		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13832		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13833		}
13834		/* continue on to finish IO */
13835	}
13836#ifdef CTL_IO_DELAY
13837	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13838		struct ctl_lun *lun;
13839
13840		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13841
13842		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13843	} else {
13844		struct ctl_lun *lun;
13845
13846		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13847
13848		if ((lun != NULL)
13849		 && (lun->delay_info.done_delay > 0)) {
13850			struct callout *callout;
13851
13852			callout = (struct callout *)&io->io_hdr.timer_bytes;
13853			callout_init(callout, /*mpsafe*/ 1);
13854			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13855			callout_reset(callout,
13856				      lun->delay_info.done_delay * hz,
13857				      ctl_done_timer_wakeup, io);
13858			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13859				lun->delay_info.done_delay = 0;
13860			return;
13861		}
13862	}
13863#endif /* CTL_IO_DELAY */
13864
13865	ctl_enqueue_done(io);
13866}
13867
13868int
13869ctl_isc(struct ctl_scsiio *ctsio)
13870{
13871	struct ctl_lun *lun;
13872	int retval;
13873
13874	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13875
13876	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13877
13878	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13879
13880	retval = lun->backend->data_submit((union ctl_io *)ctsio);
13881
13882	return (retval);
13883}
13884
13885
13886static void
13887ctl_work_thread(void *arg)
13888{
13889	struct ctl_thread *thr = (struct ctl_thread *)arg;
13890	struct ctl_softc *softc = thr->ctl_softc;
13891	union ctl_io *io;
13892	int retval;
13893
13894	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13895
13896	for (;;) {
13897		retval = 0;
13898
13899		/*
13900		 * We handle the queues in this order:
13901		 * - ISC
13902		 * - done queue (to free up resources, unblock other commands)
13903		 * - RtR queue
13904		 * - incoming queue
13905		 *
13906		 * If those queues are empty, we break out of the loop and
13907		 * go to sleep.
13908		 */
13909		mtx_lock(&thr->queue_lock);
13910		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13911		if (io != NULL) {
13912			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13913			mtx_unlock(&thr->queue_lock);
13914			ctl_handle_isc(io);
13915			continue;
13916		}
13917		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13918		if (io != NULL) {
13919			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13920			/* clear any blocked commands, call fe_done */
13921			mtx_unlock(&thr->queue_lock);
13922			retval = ctl_process_done(io);
13923			continue;
13924		}
13925		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13926		if (io != NULL) {
13927			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13928			mtx_unlock(&thr->queue_lock);
13929			if (io->io_hdr.io_type == CTL_IO_TASK)
13930				ctl_run_task(io);
13931			else
13932				ctl_scsiio_precheck(softc, &io->scsiio);
13933			continue;
13934		}
13935		if (!ctl_pause_rtr) {
13936			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13937			if (io != NULL) {
13938				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13939				mtx_unlock(&thr->queue_lock);
13940				retval = ctl_scsiio(&io->scsiio);
13941				if (retval != CTL_RETVAL_COMPLETE)
13942					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13943				continue;
13944			}
13945		}
13946
13947		/* Sleep until we have something to do. */
13948		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13949	}
13950}
13951
13952static void
13953ctl_lun_thread(void *arg)
13954{
13955	struct ctl_softc *softc = (struct ctl_softc *)arg;
13956	struct ctl_be_lun *be_lun;
13957	int retval;
13958
13959	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13960
13961	for (;;) {
13962		retval = 0;
13963		mtx_lock(&softc->ctl_lock);
13964		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13965		if (be_lun != NULL) {
13966			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13967			mtx_unlock(&softc->ctl_lock);
13968			ctl_create_lun(be_lun);
13969			continue;
13970		}
13971
13972		/* Sleep until we have something to do. */
13973		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13974		    PDROP | PRIBIO, "-", 0);
13975	}
13976}
13977
13978static void
13979ctl_thresh_thread(void *arg)
13980{
13981	struct ctl_softc *softc = (struct ctl_softc *)arg;
13982	struct ctl_lun *lun;
13983	struct ctl_be_lun *be_lun;
13984	struct scsi_da_rw_recovery_page *rwpage;
13985	struct ctl_logical_block_provisioning_page *page;
13986	const char *attr;
13987	uint64_t thres, val;
13988	int i, e;
13989
13990	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13991
13992	for (;;) {
13993		mtx_lock(&softc->ctl_lock);
13994		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13995			be_lun = lun->be_lun;
13996			if ((lun->flags & CTL_LUN_DISABLED) ||
13997			    (lun->flags & CTL_LUN_OFFLINE) ||
13998			    lun->backend->lun_attr == NULL)
13999				continue;
14000			rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
14001			if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
14002				continue;
14003			e = 0;
14004			page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
14005			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
14006				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
14007					continue;
14008				thres = scsi_4btoul(page->descr[i].count);
14009				thres <<= CTL_LBP_EXPONENT;
14010				switch (page->descr[i].resource) {
14011				case 0x01:
14012					attr = "blocksavail";
14013					break;
14014				case 0x02:
14015					attr = "blocksused";
14016					break;
14017				case 0xf1:
14018					attr = "poolblocksavail";
14019					break;
14020				case 0xf2:
14021					attr = "poolblocksused";
14022					break;
14023				default:
14024					continue;
14025				}
14026				mtx_unlock(&softc->ctl_lock); // XXX
14027				val = lun->backend->lun_attr(
14028				    lun->be_lun->be_lun, attr);
14029				mtx_lock(&softc->ctl_lock);
14030				if (val == UINT64_MAX)
14031					continue;
14032				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
14033				    == SLBPPD_ARMING_INC)
14034					e |= (val >= thres);
14035				else
14036					e |= (val <= thres);
14037			}
14038			mtx_lock(&lun->lun_lock);
14039			if (e) {
14040				if (lun->lasttpt == 0 ||
14041				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
14042					lun->lasttpt = time_uptime;
14043					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14044				}
14045			} else {
14046				lun->lasttpt = 0;
14047				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14048			}
14049			mtx_unlock(&lun->lun_lock);
14050		}
14051		mtx_unlock(&softc->ctl_lock);
14052		pause("-", CTL_LBP_PERIOD * hz);
14053	}
14054}
14055
14056static void
14057ctl_enqueue_incoming(union ctl_io *io)
14058{
14059	struct ctl_softc *softc = control_softc;
14060	struct ctl_thread *thr;
14061	u_int idx;
14062
14063	idx = (io->io_hdr.nexus.targ_port * 127 +
14064	       io->io_hdr.nexus.initid.id) % worker_threads;
14065	thr = &softc->threads[idx];
14066	mtx_lock(&thr->queue_lock);
14067	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14068	mtx_unlock(&thr->queue_lock);
14069	wakeup(thr);
14070}
14071
14072static void
14073ctl_enqueue_rtr(union ctl_io *io)
14074{
14075	struct ctl_softc *softc = control_softc;
14076	struct ctl_thread *thr;
14077
14078	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14079	mtx_lock(&thr->queue_lock);
14080	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14081	mtx_unlock(&thr->queue_lock);
14082	wakeup(thr);
14083}
14084
14085static void
14086ctl_enqueue_done(union ctl_io *io)
14087{
14088	struct ctl_softc *softc = control_softc;
14089	struct ctl_thread *thr;
14090
14091	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14092	mtx_lock(&thr->queue_lock);
14093	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14094	mtx_unlock(&thr->queue_lock);
14095	wakeup(thr);
14096}
14097
14098static void
14099ctl_enqueue_isc(union ctl_io *io)
14100{
14101	struct ctl_softc *softc = control_softc;
14102	struct ctl_thread *thr;
14103
14104	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14105	mtx_lock(&thr->queue_lock);
14106	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14107	mtx_unlock(&thr->queue_lock);
14108	wakeup(thr);
14109}
14110
14111/* Initialization and failover */
14112
14113void
14114ctl_init_isc_msg(void)
14115{
14116	printf("CTL: Still calling this thing\n");
14117}
14118
14119/*
14120 * Init component
14121 * 	Initializes component into configuration defined by bootMode
14122 *	(see hasc-sv.c)
14123 *  	returns hasc_Status:
14124 * 		OK
14125 *		ERROR - fatal error
14126 */
14127static ctl_ha_comp_status
14128ctl_isc_init(struct ctl_ha_component *c)
14129{
14130	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14131
14132	c->status = ret;
14133	return ret;
14134}
14135
14136/* Start component
14137 * 	Starts component in state requested. If component starts successfully,
14138 *	it must set its own state to the requestrd state
14139 *	When requested state is HASC_STATE_HA, the component may refine it
14140 * 	by adding _SLAVE or _MASTER flags.
14141 *	Currently allowed state transitions are:
14142 *	UNKNOWN->HA		- initial startup
14143 *	UNKNOWN->SINGLE - initial startup when no parter detected
14144 *	HA->SINGLE		- failover
14145 * returns ctl_ha_comp_status:
14146 * 		OK	- component successfully started in requested state
14147 *		FAILED  - could not start the requested state, failover may
14148 * 			  be possible
14149 *		ERROR	- fatal error detected, no future startup possible
14150 */
14151static ctl_ha_comp_status
14152ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14153{
14154	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14155
14156	printf("%s: go\n", __func__);
14157
14158	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14159	if (c->state == CTL_HA_STATE_UNKNOWN ) {
14160		control_softc->is_single = 0;
14161		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14162		    != CTL_HA_STATUS_SUCCESS) {
14163			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14164			ret = CTL_HA_COMP_STATUS_ERROR;
14165		}
14166	} else if (CTL_HA_STATE_IS_HA(c->state)
14167		&& CTL_HA_STATE_IS_SINGLE(state)){
14168		// HA->SINGLE transition
14169	        ctl_failover();
14170		control_softc->is_single = 1;
14171	} else {
14172		printf("ctl_isc_start:Invalid state transition %X->%X\n",
14173		       c->state, state);
14174		ret = CTL_HA_COMP_STATUS_ERROR;
14175	}
14176	if (CTL_HA_STATE_IS_SINGLE(state))
14177		control_softc->is_single = 1;
14178
14179	c->state = state;
14180	c->status = ret;
14181	return ret;
14182}
14183
14184/*
14185 * Quiesce component
14186 * The component must clear any error conditions (set status to OK) and
14187 * prepare itself to another Start call
14188 * returns ctl_ha_comp_status:
14189 * 	OK
14190 *	ERROR
14191 */
14192static ctl_ha_comp_status
14193ctl_isc_quiesce(struct ctl_ha_component *c)
14194{
14195	int ret = CTL_HA_COMP_STATUS_OK;
14196
14197	ctl_pause_rtr = 1;
14198	c->status = ret;
14199	return ret;
14200}
14201
14202struct ctl_ha_component ctl_ha_component_ctlisc =
14203{
14204	.name = "CTL ISC",
14205	.state = CTL_HA_STATE_UNKNOWN,
14206	.init = ctl_isc_init,
14207	.start = ctl_isc_start,
14208	.quiesce = ctl_isc_quiesce
14209};
14210
14211/*
14212 *  vim: ts=8
14213 */
14214