ctl.c revision 276237
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 276237 2014-12-26 09:44:32Z mav $");
46
47#include <sys/param.h>
48#include <sys/systm.h>
49#include <sys/ctype.h>
50#include <sys/kernel.h>
51#include <sys/types.h>
52#include <sys/kthread.h>
53#include <sys/bio.h>
54#include <sys/fcntl.h>
55#include <sys/lock.h>
56#include <sys/module.h>
57#include <sys/mutex.h>
58#include <sys/condvar.h>
59#include <sys/malloc.h>
60#include <sys/conf.h>
61#include <sys/ioccom.h>
62#include <sys/queue.h>
63#include <sys/sbuf.h>
64#include <sys/smp.h>
65#include <sys/endian.h>
66#include <sys/sysctl.h>
67#include <vm/uma.h>
68
69#include <cam/cam.h>
70#include <cam/scsi/scsi_all.h>
71#include <cam/scsi/scsi_da.h>
72#include <cam/ctl/ctl_io.h>
73#include <cam/ctl/ctl.h>
74#include <cam/ctl/ctl_frontend.h>
75#include <cam/ctl/ctl_frontend_internal.h>
76#include <cam/ctl/ctl_util.h>
77#include <cam/ctl/ctl_backend.h>
78#include <cam/ctl/ctl_ioctl.h>
79#include <cam/ctl/ctl_ha.h>
80#include <cam/ctl/ctl_private.h>
81#include <cam/ctl/ctl_debug.h>
82#include <cam/ctl/ctl_scsi_all.h>
83#include <cam/ctl/ctl_error.h>
84
85struct ctl_softc *control_softc = NULL;
86
87/*
88 * Size and alignment macros needed for Copan-specific HA hardware.  These
89 * can go away when the HA code is re-written, and uses busdma for any
90 * hardware.
91 */
92#define	CTL_ALIGN_8B(target, source, type)				\
93	if (((uint32_t)source & 0x7) != 0)				\
94		target = (type)(source + (0x8 - ((uint32_t)source & 0x7)));\
95	else								\
96		target = (type)source;
97
98#define	CTL_SIZE_8B(target, size)					\
99	if ((size & 0x7) != 0)						\
100		target = size + (0x8 - (size & 0x7));			\
101	else								\
102		target = size;
103
104#define CTL_ALIGN_8B_MARGIN	16
105
106/*
107 * Template mode pages.
108 */
109
110/*
111 * Note that these are default values only.  The actual values will be
112 * filled in when the user does a mode sense.
113 */
114static struct copan_debugconf_subpage debugconf_page_default = {
115	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
116	DBGCNF_SUBPAGE_CODE,		/* subpage */
117	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
118	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
119	DBGCNF_VERSION,			/* page_version */
120	{CTL_TIME_IO_DEFAULT_SECS>>8,
121	 CTL_TIME_IO_DEFAULT_SECS>>0},	/* ctl_time_io_secs */
122};
123
124static struct copan_debugconf_subpage debugconf_page_changeable = {
125	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
126	DBGCNF_SUBPAGE_CODE,		/* subpage */
127	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
128	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
129	0,				/* page_version */
130	{0xff,0xff},			/* ctl_time_io_secs */
131};
132
133static struct scsi_da_rw_recovery_page rw_er_page_default = {
134	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
135	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
136	/*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
137	/*read_retry_count*/0,
138	/*correction_span*/0,
139	/*head_offset_count*/0,
140	/*data_strobe_offset_cnt*/0,
141	/*byte8*/SMS_RWER_LBPERE,
142	/*write_retry_count*/0,
143	/*reserved2*/0,
144	/*recovery_time_limit*/{0, 0},
145};
146
147static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
148	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
149	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
150	/*byte3*/0,
151	/*read_retry_count*/0,
152	/*correction_span*/0,
153	/*head_offset_count*/0,
154	/*data_strobe_offset_cnt*/0,
155	/*byte8*/0,
156	/*write_retry_count*/0,
157	/*reserved2*/0,
158	/*recovery_time_limit*/{0, 0},
159};
160
161static struct scsi_format_page format_page_default = {
162	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
163	/*page_length*/sizeof(struct scsi_format_page) - 2,
164	/*tracks_per_zone*/ {0, 0},
165	/*alt_sectors_per_zone*/ {0, 0},
166	/*alt_tracks_per_zone*/ {0, 0},
167	/*alt_tracks_per_lun*/ {0, 0},
168	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
169			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
170	/*bytes_per_sector*/ {0, 0},
171	/*interleave*/ {0, 0},
172	/*track_skew*/ {0, 0},
173	/*cylinder_skew*/ {0, 0},
174	/*flags*/ SFP_HSEC,
175	/*reserved*/ {0, 0, 0}
176};
177
178static struct scsi_format_page format_page_changeable = {
179	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
180	/*page_length*/sizeof(struct scsi_format_page) - 2,
181	/*tracks_per_zone*/ {0, 0},
182	/*alt_sectors_per_zone*/ {0, 0},
183	/*alt_tracks_per_zone*/ {0, 0},
184	/*alt_tracks_per_lun*/ {0, 0},
185	/*sectors_per_track*/ {0, 0},
186	/*bytes_per_sector*/ {0, 0},
187	/*interleave*/ {0, 0},
188	/*track_skew*/ {0, 0},
189	/*cylinder_skew*/ {0, 0},
190	/*flags*/ 0,
191	/*reserved*/ {0, 0, 0}
192};
193
194static struct scsi_rigid_disk_page rigid_disk_page_default = {
195	/*page_code*/SMS_RIGID_DISK_PAGE,
196	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
197	/*cylinders*/ {0, 0, 0},
198	/*heads*/ CTL_DEFAULT_HEADS,
199	/*start_write_precomp*/ {0, 0, 0},
200	/*start_reduced_current*/ {0, 0, 0},
201	/*step_rate*/ {0, 0},
202	/*landing_zone_cylinder*/ {0, 0, 0},
203	/*rpl*/ SRDP_RPL_DISABLED,
204	/*rotational_offset*/ 0,
205	/*reserved1*/ 0,
206	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
207			   CTL_DEFAULT_ROTATION_RATE & 0xff},
208	/*reserved2*/ {0, 0}
209};
210
211static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
212	/*page_code*/SMS_RIGID_DISK_PAGE,
213	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
214	/*cylinders*/ {0, 0, 0},
215	/*heads*/ 0,
216	/*start_write_precomp*/ {0, 0, 0},
217	/*start_reduced_current*/ {0, 0, 0},
218	/*step_rate*/ {0, 0},
219	/*landing_zone_cylinder*/ {0, 0, 0},
220	/*rpl*/ 0,
221	/*rotational_offset*/ 0,
222	/*reserved1*/ 0,
223	/*rotation_rate*/ {0, 0},
224	/*reserved2*/ {0, 0}
225};
226
227static struct scsi_caching_page caching_page_default = {
228	/*page_code*/SMS_CACHING_PAGE,
229	/*page_length*/sizeof(struct scsi_caching_page) - 2,
230	/*flags1*/ SCP_DISC | SCP_WCE,
231	/*ret_priority*/ 0,
232	/*disable_pf_transfer_len*/ {0xff, 0xff},
233	/*min_prefetch*/ {0, 0},
234	/*max_prefetch*/ {0xff, 0xff},
235	/*max_pf_ceiling*/ {0xff, 0xff},
236	/*flags2*/ 0,
237	/*cache_segments*/ 0,
238	/*cache_seg_size*/ {0, 0},
239	/*reserved*/ 0,
240	/*non_cache_seg_size*/ {0, 0, 0}
241};
242
243static struct scsi_caching_page caching_page_changeable = {
244	/*page_code*/SMS_CACHING_PAGE,
245	/*page_length*/sizeof(struct scsi_caching_page) - 2,
246	/*flags1*/ SCP_WCE | SCP_RCD,
247	/*ret_priority*/ 0,
248	/*disable_pf_transfer_len*/ {0, 0},
249	/*min_prefetch*/ {0, 0},
250	/*max_prefetch*/ {0, 0},
251	/*max_pf_ceiling*/ {0, 0},
252	/*flags2*/ 0,
253	/*cache_segments*/ 0,
254	/*cache_seg_size*/ {0, 0},
255	/*reserved*/ 0,
256	/*non_cache_seg_size*/ {0, 0, 0}
257};
258
259static struct scsi_control_page control_page_default = {
260	/*page_code*/SMS_CONTROL_MODE_PAGE,
261	/*page_length*/sizeof(struct scsi_control_page) - 2,
262	/*rlec*/0,
263	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
264	/*eca_and_aen*/0,
265	/*flags4*/SCP_TAS,
266	/*aen_holdoff_period*/{0, 0},
267	/*busy_timeout_period*/{0, 0},
268	/*extended_selftest_completion_time*/{0, 0}
269};
270
271static struct scsi_control_page control_page_changeable = {
272	/*page_code*/SMS_CONTROL_MODE_PAGE,
273	/*page_length*/sizeof(struct scsi_control_page) - 2,
274	/*rlec*/SCP_DSENSE,
275	/*queue_flags*/SCP_QUEUE_ALG_MASK,
276	/*eca_and_aen*/SCP_SWP,
277	/*flags4*/0,
278	/*aen_holdoff_period*/{0, 0},
279	/*busy_timeout_period*/{0, 0},
280	/*extended_selftest_completion_time*/{0, 0}
281};
282
283static struct scsi_info_exceptions_page ie_page_default = {
284	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
285	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
286	/*info_flags*/SIEP_FLAGS_DEXCPT,
287	/*mrie*/0,
288	/*interval_timer*/{0, 0, 0, 0},
289	/*report_count*/{0, 0, 0, 0}
290};
291
292static struct scsi_info_exceptions_page ie_page_changeable = {
293	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
294	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
295	/*info_flags*/0,
296	/*mrie*/0,
297	/*interval_timer*/{0, 0, 0, 0},
298	/*report_count*/{0, 0, 0, 0}
299};
300
301#define CTL_LBPM_LEN	(sizeof(struct ctl_logical_block_provisioning_page) - 4)
302
303static struct ctl_logical_block_provisioning_page lbp_page_default = {{
304	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
305	/*subpage_code*/0x02,
306	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
307	/*flags*/0,
308	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
309	/*descr*/{}},
310	{{/*flags*/0,
311	  /*resource*/0x01,
312	  /*reserved*/{0, 0},
313	  /*count*/{0, 0, 0, 0}},
314	 {/*flags*/0,
315	  /*resource*/0x02,
316	  /*reserved*/{0, 0},
317	  /*count*/{0, 0, 0, 0}},
318	 {/*flags*/0,
319	  /*resource*/0xf1,
320	  /*reserved*/{0, 0},
321	  /*count*/{0, 0, 0, 0}},
322	 {/*flags*/0,
323	  /*resource*/0xf2,
324	  /*reserved*/{0, 0},
325	  /*count*/{0, 0, 0, 0}}
326	}
327};
328
329static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
330	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
331	/*subpage_code*/0x02,
332	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
333	/*flags*/0,
334	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
335	/*descr*/{}},
336	{{/*flags*/0,
337	  /*resource*/0,
338	  /*reserved*/{0, 0},
339	  /*count*/{0, 0, 0, 0}},
340	 {/*flags*/0,
341	  /*resource*/0,
342	  /*reserved*/{0, 0},
343	  /*count*/{0, 0, 0, 0}},
344	 {/*flags*/0,
345	  /*resource*/0,
346	  /*reserved*/{0, 0},
347	  /*count*/{0, 0, 0, 0}},
348	 {/*flags*/0,
349	  /*resource*/0,
350	  /*reserved*/{0, 0},
351	  /*count*/{0, 0, 0, 0}}
352	}
353};
354
355/*
356 * XXX KDM move these into the softc.
357 */
358static int rcv_sync_msg;
359static uint8_t ctl_pause_rtr;
360
361SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
362static int worker_threads = -1;
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(int port_num, uint32_t lun);
404static uint32_t ctl_map_lun_back(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_softc *ctl_softc,
447				struct ctl_lun *lun,
448				const struct ctl_cmd_entry *entry,
449				struct ctl_scsiio *ctsio);
450//static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
451static void ctl_failover(void);
452static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
453			       struct ctl_scsiio *ctsio);
454static int ctl_scsiio(struct ctl_scsiio *ctsio);
455
456static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
457static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
458			    ctl_ua_type ua_type);
459static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
460			 ctl_ua_type ua_type);
461static int ctl_abort_task(union ctl_io *io);
462static int ctl_abort_task_set(union ctl_io *io);
463static int ctl_i_t_nexus_reset(union ctl_io *io);
464static void ctl_run_task(union ctl_io *io);
465#ifdef CTL_IO_DELAY
466static void ctl_datamove_timer_wakeup(void *arg);
467static void ctl_done_timer_wakeup(void *arg);
468#endif /* CTL_IO_DELAY */
469
470static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
471static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
472static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
473static void ctl_datamove_remote_write(union ctl_io *io);
474static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
475static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
476static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
477static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
478				    ctl_ha_dt_cb callback);
479static void ctl_datamove_remote_read(union ctl_io *io);
480static void ctl_datamove_remote(union ctl_io *io);
481static int ctl_process_done(union ctl_io *io);
482static void ctl_lun_thread(void *arg);
483static void ctl_thresh_thread(void *arg);
484static void ctl_work_thread(void *arg);
485static void ctl_enqueue_incoming(union ctl_io *io);
486static void ctl_enqueue_rtr(union ctl_io *io);
487static void ctl_enqueue_done(union ctl_io *io);
488static void ctl_enqueue_isc(union ctl_io *io);
489static const struct ctl_cmd_entry *
490    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
491static const struct ctl_cmd_entry *
492    ctl_validate_command(struct ctl_scsiio *ctsio);
493static int ctl_cmd_applicable(uint8_t lun_type,
494    const struct ctl_cmd_entry *entry);
495
496/*
497 * Load the serialization table.  This isn't very pretty, but is probably
498 * the easiest way to do it.
499 */
500#include "ctl_ser_table.c"
501
502/*
503 * We only need to define open, close and ioctl routines for this driver.
504 */
505static struct cdevsw ctl_cdevsw = {
506	.d_version =	D_VERSION,
507	.d_flags =	0,
508	.d_open =	ctl_open,
509	.d_close =	ctl_close,
510	.d_ioctl =	ctl_ioctl,
511	.d_name =	"ctl",
512};
513
514
515MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
516MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
517
518static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
519
520static moduledata_t ctl_moduledata = {
521	"ctl",
522	ctl_module_event_handler,
523	NULL
524};
525
526DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
527MODULE_VERSION(ctl, 1);
528
529static struct ctl_frontend ioctl_frontend =
530{
531	.name = "ioctl",
532};
533
534static void
535ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
536			    union ctl_ha_msg *msg_info)
537{
538	struct ctl_scsiio *ctsio;
539
540	if (msg_info->hdr.original_sc == NULL) {
541		printf("%s: original_sc == NULL!\n", __func__);
542		/* XXX KDM now what? */
543		return;
544	}
545
546	ctsio = &msg_info->hdr.original_sc->scsiio;
547	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
548	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
549	ctsio->io_hdr.status = msg_info->hdr.status;
550	ctsio->scsi_status = msg_info->scsi.scsi_status;
551	ctsio->sense_len = msg_info->scsi.sense_len;
552	ctsio->sense_residual = msg_info->scsi.sense_residual;
553	ctsio->residual = msg_info->scsi.residual;
554	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
555	       sizeof(ctsio->sense_data));
556	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
557	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
558	ctl_enqueue_isc((union ctl_io *)ctsio);
559}
560
561static void
562ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
563				union ctl_ha_msg *msg_info)
564{
565	struct ctl_scsiio *ctsio;
566
567	if (msg_info->hdr.serializing_sc == NULL) {
568		printf("%s: serializing_sc == NULL!\n", __func__);
569		/* XXX KDM now what? */
570		return;
571	}
572
573	ctsio = &msg_info->hdr.serializing_sc->scsiio;
574#if 0
575	/*
576	 * Attempt to catch the situation where an I/O has
577	 * been freed, and we're using it again.
578	 */
579	if (ctsio->io_hdr.io_type == 0xff) {
580		union ctl_io *tmp_io;
581		tmp_io = (union ctl_io *)ctsio;
582		printf("%s: %p use after free!\n", __func__,
583		       ctsio);
584		printf("%s: type %d msg %d cdb %x iptl: "
585		       "%d:%d:%d:%d tag 0x%04x "
586		       "flag %#x status %x\n",
587			__func__,
588			tmp_io->io_hdr.io_type,
589			tmp_io->io_hdr.msg_type,
590			tmp_io->scsiio.cdb[0],
591			tmp_io->io_hdr.nexus.initid.id,
592			tmp_io->io_hdr.nexus.targ_port,
593			tmp_io->io_hdr.nexus.targ_target.id,
594			tmp_io->io_hdr.nexus.targ_lun,
595			(tmp_io->io_hdr.io_type ==
596			CTL_IO_TASK) ?
597			tmp_io->taskio.tag_num :
598			tmp_io->scsiio.tag_num,
599		        tmp_io->io_hdr.flags,
600			tmp_io->io_hdr.status);
601	}
602#endif
603	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
604	ctl_enqueue_isc((union ctl_io *)ctsio);
605}
606
607/*
608 * ISC (Inter Shelf Communication) event handler.  Events from the HA
609 * subsystem come in here.
610 */
611static void
612ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
613{
614	struct ctl_softc *ctl_softc;
615	union ctl_io *io;
616	struct ctl_prio *presio;
617	ctl_ha_status isc_status;
618
619	ctl_softc = control_softc;
620	io = NULL;
621
622
623#if 0
624	printf("CTL: Isc Msg event %d\n", event);
625#endif
626	if (event == CTL_HA_EVT_MSG_RECV) {
627		union ctl_ha_msg msg_info;
628
629		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
630					     sizeof(msg_info), /*wait*/ 0);
631#if 0
632		printf("CTL: msg_type %d\n", msg_info.msg_type);
633#endif
634		if (isc_status != 0) {
635			printf("Error receiving message, status = %d\n",
636			       isc_status);
637			return;
638		}
639
640		switch (msg_info.hdr.msg_type) {
641		case CTL_MSG_SERIALIZE:
642#if 0
643			printf("Serialize\n");
644#endif
645			io = ctl_alloc_io_nowait(ctl_softc->othersc_pool);
646			if (io == NULL) {
647				printf("ctl_isc_event_handler: can't allocate "
648				       "ctl_io!\n");
649				/* Bad Juju */
650				/* Need to set busy and send msg back */
651				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
652				msg_info.hdr.status = CTL_SCSI_ERROR;
653				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
654				msg_info.scsi.sense_len = 0;
655			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
656				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
657				}
658				goto bailout;
659			}
660			ctl_zero_io(io);
661			// populate ctsio from msg_info
662			io->io_hdr.io_type = CTL_IO_SCSI;
663			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
664			io->io_hdr.original_sc = msg_info.hdr.original_sc;
665#if 0
666			printf("pOrig %x\n", (int)msg_info.original_sc);
667#endif
668			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
669					    CTL_FLAG_IO_ACTIVE;
670			/*
671			 * If we're in serialization-only mode, we don't
672			 * want to go through full done processing.  Thus
673			 * the COPY flag.
674			 *
675			 * XXX KDM add another flag that is more specific.
676			 */
677			if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
678				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
679			io->io_hdr.nexus = msg_info.hdr.nexus;
680#if 0
681			printf("targ %d, port %d, iid %d, lun %d\n",
682			       io->io_hdr.nexus.targ_target.id,
683			       io->io_hdr.nexus.targ_port,
684			       io->io_hdr.nexus.initid.id,
685			       io->io_hdr.nexus.targ_lun);
686#endif
687			io->scsiio.tag_num = msg_info.scsi.tag_num;
688			io->scsiio.tag_type = msg_info.scsi.tag_type;
689			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
690			       CTL_MAX_CDBLEN);
691			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
692				const struct ctl_cmd_entry *entry;
693
694				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
695				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
696				io->io_hdr.flags |=
697					entry->flags & CTL_FLAG_DATA_MASK;
698			}
699			ctl_enqueue_isc(io);
700			break;
701
702		/* Performed on the Originating SC, XFER mode only */
703		case CTL_MSG_DATAMOVE: {
704			struct ctl_sg_entry *sgl;
705			int i, j;
706
707			io = msg_info.hdr.original_sc;
708			if (io == NULL) {
709				printf("%s: original_sc == NULL!\n", __func__);
710				/* XXX KDM do something here */
711				break;
712			}
713			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
714			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
715			/*
716			 * Keep track of this, we need to send it back over
717			 * when the datamove is complete.
718			 */
719			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
720
721			if (msg_info.dt.sg_sequence == 0) {
722				/*
723				 * XXX KDM we use the preallocated S/G list
724				 * here, but we'll need to change this to
725				 * dynamic allocation if we need larger S/G
726				 * lists.
727				 */
728				if (msg_info.dt.kern_sg_entries >
729				    sizeof(io->io_hdr.remote_sglist) /
730				    sizeof(io->io_hdr.remote_sglist[0])) {
731					printf("%s: number of S/G entries "
732					    "needed %u > allocated num %zd\n",
733					    __func__,
734					    msg_info.dt.kern_sg_entries,
735					    sizeof(io->io_hdr.remote_sglist)/
736					    sizeof(io->io_hdr.remote_sglist[0]));
737
738					/*
739					 * XXX KDM send a message back to
740					 * the other side to shut down the
741					 * DMA.  The error will come back
742					 * through via the normal channel.
743					 */
744					break;
745				}
746				sgl = io->io_hdr.remote_sglist;
747				memset(sgl, 0,
748				       sizeof(io->io_hdr.remote_sglist));
749
750				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
751
752				io->scsiio.kern_sg_entries =
753					msg_info.dt.kern_sg_entries;
754				io->scsiio.rem_sg_entries =
755					msg_info.dt.kern_sg_entries;
756				io->scsiio.kern_data_len =
757					msg_info.dt.kern_data_len;
758				io->scsiio.kern_total_len =
759					msg_info.dt.kern_total_len;
760				io->scsiio.kern_data_resid =
761					msg_info.dt.kern_data_resid;
762				io->scsiio.kern_rel_offset =
763					msg_info.dt.kern_rel_offset;
764				/*
765				 * Clear out per-DMA flags.
766				 */
767				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
768				/*
769				 * Add per-DMA flags that are set for this
770				 * particular DMA request.
771				 */
772				io->io_hdr.flags |= msg_info.dt.flags &
773						    CTL_FLAG_RDMA_MASK;
774			} else
775				sgl = (struct ctl_sg_entry *)
776					io->scsiio.kern_data_ptr;
777
778			for (i = msg_info.dt.sent_sg_entries, j = 0;
779			     i < (msg_info.dt.sent_sg_entries +
780			     msg_info.dt.cur_sg_entries); i++, j++) {
781				sgl[i].addr = msg_info.dt.sg_list[j].addr;
782				sgl[i].len = msg_info.dt.sg_list[j].len;
783
784#if 0
785				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
786				       __func__,
787				       msg_info.dt.sg_list[j].addr,
788				       msg_info.dt.sg_list[j].len,
789				       sgl[i].addr, sgl[i].len, j, i);
790#endif
791			}
792#if 0
793			memcpy(&sgl[msg_info.dt.sent_sg_entries],
794			       msg_info.dt.sg_list,
795			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
796#endif
797
798			/*
799			 * If this is the last piece of the I/O, we've got
800			 * the full S/G list.  Queue processing in the thread.
801			 * Otherwise wait for the next piece.
802			 */
803			if (msg_info.dt.sg_last != 0)
804				ctl_enqueue_isc(io);
805			break;
806		}
807		/* Performed on the Serializing (primary) SC, XFER mode only */
808		case CTL_MSG_DATAMOVE_DONE: {
809			if (msg_info.hdr.serializing_sc == NULL) {
810				printf("%s: serializing_sc == NULL!\n",
811				       __func__);
812				/* XXX KDM now what? */
813				break;
814			}
815			/*
816			 * We grab the sense information here in case
817			 * there was a failure, so we can return status
818			 * back to the initiator.
819			 */
820			io = msg_info.hdr.serializing_sc;
821			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
822			io->io_hdr.status = msg_info.hdr.status;
823			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
824			io->scsiio.sense_len = msg_info.scsi.sense_len;
825			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
826			io->io_hdr.port_status = msg_info.scsi.fetd_status;
827			io->scsiio.residual = msg_info.scsi.residual;
828			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
829			       sizeof(io->scsiio.sense_data));
830			ctl_enqueue_isc(io);
831			break;
832		}
833
834		/* Preformed on Originating SC, SER_ONLY mode */
835		case CTL_MSG_R2R:
836			io = msg_info.hdr.original_sc;
837			if (io == NULL) {
838				printf("%s: Major Bummer\n", __func__);
839				return;
840			} else {
841#if 0
842				printf("pOrig %x\n",(int) ctsio);
843#endif
844			}
845			io->io_hdr.msg_type = CTL_MSG_R2R;
846			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
847			ctl_enqueue_isc(io);
848			break;
849
850		/*
851		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
852		 * mode.
853		 * Performed on the Originating (i.e. secondary) SC in XFER
854		 * mode
855		 */
856		case CTL_MSG_FINISH_IO:
857			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
858				ctl_isc_handler_finish_xfer(ctl_softc,
859							    &msg_info);
860			else
861				ctl_isc_handler_finish_ser_only(ctl_softc,
862								&msg_info);
863			break;
864
865		/* Preformed on Originating SC */
866		case CTL_MSG_BAD_JUJU:
867			io = msg_info.hdr.original_sc;
868			if (io == NULL) {
869				printf("%s: Bad JUJU!, original_sc is NULL!\n",
870				       __func__);
871				break;
872			}
873			ctl_copy_sense_data(&msg_info, io);
874			/*
875			 * IO should have already been cleaned up on other
876			 * SC so clear this flag so we won't send a message
877			 * back to finish the IO there.
878			 */
879			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
880			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
881
882			/* io = msg_info.hdr.serializing_sc; */
883			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
884			ctl_enqueue_isc(io);
885			break;
886
887		/* Handle resets sent from the other side */
888		case CTL_MSG_MANAGE_TASKS: {
889			struct ctl_taskio *taskio;
890			taskio = (struct ctl_taskio *)ctl_alloc_io_nowait(
891			    ctl_softc->othersc_pool);
892			if (taskio == NULL) {
893				printf("ctl_isc_event_handler: can't allocate "
894				       "ctl_io!\n");
895				/* Bad Juju */
896				/* should I just call the proper reset func
897				   here??? */
898				goto bailout;
899			}
900			ctl_zero_io((union ctl_io *)taskio);
901			taskio->io_hdr.io_type = CTL_IO_TASK;
902			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
903			taskio->io_hdr.nexus = msg_info.hdr.nexus;
904			taskio->task_action = msg_info.task.task_action;
905			taskio->tag_num = msg_info.task.tag_num;
906			taskio->tag_type = msg_info.task.tag_type;
907#ifdef CTL_TIME_IO
908			taskio->io_hdr.start_time = time_uptime;
909			getbintime(&taskio->io_hdr.start_bt);
910#if 0
911			cs_prof_gettime(&taskio->io_hdr.start_ticks);
912#endif
913#endif /* CTL_TIME_IO */
914			ctl_run_task((union ctl_io *)taskio);
915			break;
916		}
917		/* Persistent Reserve action which needs attention */
918		case CTL_MSG_PERS_ACTION:
919			presio = (struct ctl_prio *)ctl_alloc_io_nowait(
920			    ctl_softc->othersc_pool);
921			if (presio == NULL) {
922				printf("ctl_isc_event_handler: can't allocate "
923				       "ctl_io!\n");
924				/* Bad Juju */
925				/* Need to set busy and send msg back */
926				goto bailout;
927			}
928			ctl_zero_io((union ctl_io *)presio);
929			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
930			presio->pr_msg = msg_info.pr;
931			ctl_enqueue_isc((union ctl_io *)presio);
932			break;
933		case CTL_MSG_SYNC_FE:
934			rcv_sync_msg = 1;
935			break;
936		default:
937		        printf("How did I get here?\n");
938		}
939	} else if (event == CTL_HA_EVT_MSG_SENT) {
940		if (param != CTL_HA_STATUS_SUCCESS) {
941			printf("Bad status from ctl_ha_msg_send status %d\n",
942			       param);
943		}
944		return;
945	} else if (event == CTL_HA_EVT_DISCONNECT) {
946		printf("CTL: Got a disconnect from Isc\n");
947		return;
948	} else {
949		printf("ctl_isc_event_handler: Unknown event %d\n", event);
950		return;
951	}
952
953bailout:
954	return;
955}
956
957static void
958ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
959{
960	struct scsi_sense_data *sense;
961
962	sense = &dest->scsiio.sense_data;
963	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
964	dest->scsiio.scsi_status = src->scsi.scsi_status;
965	dest->scsiio.sense_len = src->scsi.sense_len;
966	dest->io_hdr.status = src->hdr.status;
967}
968
969static void
970ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
971{
972	ctl_ua_type *pu;
973
974	mtx_assert(&lun->lun_lock, MA_OWNED);
975	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
976	if (pu == NULL)
977		return;
978	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
979}
980
981static void
982ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
983{
984	int i, j;
985
986	mtx_assert(&lun->lun_lock, MA_OWNED);
987	for (i = 0; i < CTL_MAX_PORTS; i++) {
988		if (lun->pending_ua[i] == NULL)
989			continue;
990		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
991			if (i * CTL_MAX_INIT_PER_PORT + j == except)
992				continue;
993			lun->pending_ua[i][j] |= ua;
994		}
995	}
996}
997
998static void
999ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1000{
1001	ctl_ua_type *pu;
1002
1003	mtx_assert(&lun->lun_lock, MA_OWNED);
1004	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1005	if (pu == NULL)
1006		return;
1007	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1008}
1009
1010static void
1011ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1012{
1013	int i, j;
1014
1015	mtx_assert(&lun->lun_lock, MA_OWNED);
1016	for (i = 0; i < CTL_MAX_PORTS; i++) {
1017		if (lun->pending_ua[i] == NULL)
1018			continue;
1019		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1020			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1021				continue;
1022			lun->pending_ua[i][j] &= ~ua;
1023		}
1024	}
1025}
1026
1027static int
1028ctl_ha_state_sysctl(SYSCTL_HANDLER_ARGS)
1029{
1030	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1031	struct ctl_lun *lun;
1032	int error, value;
1033
1034	if (softc->flags & CTL_FLAG_ACTIVE_SHELF)
1035		value = 0;
1036	else
1037		value = 1;
1038
1039	error = sysctl_handle_int(oidp, &value, 0, req);
1040	if ((error != 0) || (req->newptr == NULL))
1041		return (error);
1042
1043	mtx_lock(&softc->ctl_lock);
1044	if (value == 0)
1045		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1046	else
1047		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1048	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1049		mtx_lock(&lun->lun_lock);
1050		ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1051		mtx_unlock(&lun->lun_lock);
1052	}
1053	mtx_unlock(&softc->ctl_lock);
1054	return (0);
1055}
1056
1057static int
1058ctl_init(void)
1059{
1060	struct ctl_softc *softc;
1061	void *other_pool;
1062	struct ctl_port *port;
1063	int i, error, retval;
1064	//int isc_retval;
1065
1066	retval = 0;
1067	ctl_pause_rtr = 0;
1068        rcv_sync_msg = 0;
1069
1070	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1071			       M_WAITOK | M_ZERO);
1072	softc = control_softc;
1073
1074	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1075			      "cam/ctl");
1076
1077	softc->dev->si_drv1 = softc;
1078
1079	/*
1080	 * By default, return a "bad LUN" peripheral qualifier for unknown
1081	 * LUNs.  The user can override this default using the tunable or
1082	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
1083	 */
1084	softc->inquiry_pq_no_lun = 1;
1085	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
1086			  &softc->inquiry_pq_no_lun);
1087	sysctl_ctx_init(&softc->sysctl_ctx);
1088	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1089		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1090		CTLFLAG_RD, 0, "CAM Target Layer");
1091
1092	if (softc->sysctl_tree == NULL) {
1093		printf("%s: unable to allocate sysctl tree\n", __func__);
1094		destroy_dev(softc->dev);
1095		free(control_softc, M_DEVBUF);
1096		control_softc = NULL;
1097		return (ENOMEM);
1098	}
1099
1100	SYSCTL_ADD_INT(&softc->sysctl_ctx,
1101		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1102		       "inquiry_pq_no_lun", CTLFLAG_RW,
1103		       &softc->inquiry_pq_no_lun, 0,
1104		       "Report no lun possible for invalid LUNs");
1105
1106	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1107	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1108	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1109	softc->open_count = 0;
1110
1111	/*
1112	 * Default to actually sending a SYNCHRONIZE CACHE command down to
1113	 * the drive.
1114	 */
1115	softc->flags = CTL_FLAG_REAL_SYNC;
1116
1117	/*
1118	 * In Copan's HA scheme, the "master" and "slave" roles are
1119	 * figured out through the slot the controller is in.  Although it
1120	 * is an active/active system, someone has to be in charge.
1121	 */
1122	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1123	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1124	    "HA head ID (0 - no HA)");
1125	if (softc->ha_id == 0) {
1126		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1127		softc->is_single = 1;
1128		softc->port_offset = 0;
1129	} else
1130		softc->port_offset = (softc->ha_id - 1) * CTL_MAX_PORTS;
1131	softc->persis_offset = softc->port_offset * CTL_MAX_INIT_PER_PORT;
1132
1133	/*
1134	 * XXX KDM need to figure out where we want to get our target ID
1135	 * and WWID.  Is it different on each port?
1136	 */
1137	softc->target.id = 0;
1138	softc->target.wwid[0] = 0x12345678;
1139	softc->target.wwid[1] = 0x87654321;
1140	STAILQ_INIT(&softc->lun_list);
1141	STAILQ_INIT(&softc->pending_lun_queue);
1142	STAILQ_INIT(&softc->fe_list);
1143	STAILQ_INIT(&softc->port_list);
1144	STAILQ_INIT(&softc->be_list);
1145	ctl_tpc_init(softc);
1146
1147	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1148	                    &other_pool) != 0)
1149	{
1150		printf("ctl: can't allocate %d entry other SC pool, "
1151		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1152		return (ENOMEM);
1153	}
1154	softc->othersc_pool = other_pool;
1155
1156	if (worker_threads <= 0)
1157		worker_threads = max(1, mp_ncpus / 4);
1158	if (worker_threads > CTL_MAX_THREADS)
1159		worker_threads = CTL_MAX_THREADS;
1160
1161	for (i = 0; i < worker_threads; i++) {
1162		struct ctl_thread *thr = &softc->threads[i];
1163
1164		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1165		thr->ctl_softc = softc;
1166		STAILQ_INIT(&thr->incoming_queue);
1167		STAILQ_INIT(&thr->rtr_queue);
1168		STAILQ_INIT(&thr->done_queue);
1169		STAILQ_INIT(&thr->isc_queue);
1170
1171		error = kproc_kthread_add(ctl_work_thread, thr,
1172		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1173		if (error != 0) {
1174			printf("error creating CTL work thread!\n");
1175			ctl_pool_free(other_pool);
1176			return (error);
1177		}
1178	}
1179	error = kproc_kthread_add(ctl_lun_thread, softc,
1180	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1181	if (error != 0) {
1182		printf("error creating CTL lun thread!\n");
1183		ctl_pool_free(other_pool);
1184		return (error);
1185	}
1186	error = kproc_kthread_add(ctl_thresh_thread, softc,
1187	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1188	if (error != 0) {
1189		printf("error creating CTL threshold thread!\n");
1190		ctl_pool_free(other_pool);
1191		return (error);
1192	}
1193	if (bootverbose)
1194		printf("ctl: CAM Target Layer loaded\n");
1195
1196	/*
1197	 * Initialize the ioctl front end.
1198	 */
1199	ctl_frontend_register(&ioctl_frontend);
1200	port = &softc->ioctl_info.port;
1201	port->frontend = &ioctl_frontend;
1202	sprintf(softc->ioctl_info.port_name, "ioctl");
1203	port->port_type = CTL_PORT_IOCTL;
1204	port->num_requested_ctl_io = 100;
1205	port->port_name = softc->ioctl_info.port_name;
1206	port->port_online = ctl_ioctl_online;
1207	port->port_offline = ctl_ioctl_offline;
1208	port->onoff_arg = &softc->ioctl_info;
1209	port->lun_enable = ctl_ioctl_lun_enable;
1210	port->lun_disable = ctl_ioctl_lun_disable;
1211	port->targ_lun_arg = &softc->ioctl_info;
1212	port->fe_datamove = ctl_ioctl_datamove;
1213	port->fe_done = ctl_ioctl_done;
1214	port->max_targets = 15;
1215	port->max_target_id = 15;
1216
1217	if (ctl_port_register(&softc->ioctl_info.port) != 0) {
1218		printf("ctl: ioctl front end registration failed, will "
1219		       "continue anyway\n");
1220	}
1221
1222	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1223	    OID_AUTO, "ha_state", CTLTYPE_INT | CTLFLAG_RWTUN,
1224	    softc, 0, ctl_ha_state_sysctl, "I", "HA state for this head");
1225
1226#ifdef CTL_IO_DELAY
1227	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1228		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1229		       sizeof(struct callout), CTL_TIMER_BYTES);
1230		return (EINVAL);
1231	}
1232#endif /* CTL_IO_DELAY */
1233
1234	return (0);
1235}
1236
1237void
1238ctl_shutdown(void)
1239{
1240	struct ctl_softc *softc;
1241	struct ctl_lun *lun, *next_lun;
1242
1243	softc = (struct ctl_softc *)control_softc;
1244
1245	if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1246		printf("ctl: ioctl front end deregistration failed\n");
1247
1248	mtx_lock(&softc->ctl_lock);
1249
1250	/*
1251	 * Free up each LUN.
1252	 */
1253	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1254		next_lun = STAILQ_NEXT(lun, links);
1255		ctl_free_lun(lun);
1256	}
1257
1258	mtx_unlock(&softc->ctl_lock);
1259
1260	ctl_frontend_deregister(&ioctl_frontend);
1261
1262#if 0
1263	ctl_shutdown_thread(softc->work_thread);
1264	mtx_destroy(&softc->queue_lock);
1265#endif
1266
1267	ctl_tpc_shutdown(softc);
1268	uma_zdestroy(softc->io_zone);
1269	mtx_destroy(&softc->ctl_lock);
1270
1271	destroy_dev(softc->dev);
1272
1273	sysctl_ctx_free(&softc->sysctl_ctx);
1274
1275	free(control_softc, M_DEVBUF);
1276	control_softc = NULL;
1277
1278	if (bootverbose)
1279		printf("ctl: CAM Target Layer unloaded\n");
1280}
1281
1282static int
1283ctl_module_event_handler(module_t mod, int what, void *arg)
1284{
1285
1286	switch (what) {
1287	case MOD_LOAD:
1288		return (ctl_init());
1289	case MOD_UNLOAD:
1290		return (EBUSY);
1291	default:
1292		return (EOPNOTSUPP);
1293	}
1294}
1295
1296/*
1297 * XXX KDM should we do some access checks here?  Bump a reference count to
1298 * prevent a CTL module from being unloaded while someone has it open?
1299 */
1300static int
1301ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1302{
1303	return (0);
1304}
1305
1306static int
1307ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1308{
1309	return (0);
1310}
1311
1312int
1313ctl_port_enable(ctl_port_type port_type)
1314{
1315	struct ctl_softc *softc = control_softc;
1316	struct ctl_port *port;
1317
1318	if (softc->is_single == 0) {
1319		union ctl_ha_msg msg_info;
1320		int isc_retval;
1321
1322#if 0
1323		printf("%s: HA mode, synchronizing frontend enable\n",
1324		        __func__);
1325#endif
1326		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1327	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1328		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1329			printf("Sync msg send error retval %d\n", isc_retval);
1330		}
1331		if (!rcv_sync_msg) {
1332			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1333			        sizeof(msg_info), 1);
1334		}
1335#if 0
1336        	printf("CTL:Frontend Enable\n");
1337	} else {
1338		printf("%s: single mode, skipping frontend synchronization\n",
1339		        __func__);
1340#endif
1341	}
1342
1343	STAILQ_FOREACH(port, &softc->port_list, links) {
1344		if (port_type & port->port_type)
1345		{
1346#if 0
1347			printf("port %d\n", port->targ_port);
1348#endif
1349			ctl_port_online(port);
1350		}
1351	}
1352
1353	return (0);
1354}
1355
1356int
1357ctl_port_disable(ctl_port_type port_type)
1358{
1359	struct ctl_softc *softc;
1360	struct ctl_port *port;
1361
1362	softc = control_softc;
1363
1364	STAILQ_FOREACH(port, &softc->port_list, links) {
1365		if (port_type & port->port_type)
1366			ctl_port_offline(port);
1367	}
1368
1369	return (0);
1370}
1371
1372/*
1373 * Returns 0 for success, 1 for failure.
1374 * Currently the only failure mode is if there aren't enough entries
1375 * allocated.  So, in case of a failure, look at num_entries_dropped,
1376 * reallocate and try again.
1377 */
1378int
1379ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1380	      int *num_entries_filled, int *num_entries_dropped,
1381	      ctl_port_type port_type, int no_virtual)
1382{
1383	struct ctl_softc *softc;
1384	struct ctl_port *port;
1385	int entries_dropped, entries_filled;
1386	int retval;
1387	int i;
1388
1389	softc = control_softc;
1390
1391	retval = 0;
1392	entries_filled = 0;
1393	entries_dropped = 0;
1394
1395	i = 0;
1396	mtx_lock(&softc->ctl_lock);
1397	STAILQ_FOREACH(port, &softc->port_list, links) {
1398		struct ctl_port_entry *entry;
1399
1400		if ((port->port_type & port_type) == 0)
1401			continue;
1402
1403		if ((no_virtual != 0)
1404		 && (port->virtual_port != 0))
1405			continue;
1406
1407		if (entries_filled >= num_entries_alloced) {
1408			entries_dropped++;
1409			continue;
1410		}
1411		entry = &entries[i];
1412
1413		entry->port_type = port->port_type;
1414		strlcpy(entry->port_name, port->port_name,
1415			sizeof(entry->port_name));
1416		entry->physical_port = port->physical_port;
1417		entry->virtual_port = port->virtual_port;
1418		entry->wwnn = port->wwnn;
1419		entry->wwpn = port->wwpn;
1420
1421		i++;
1422		entries_filled++;
1423	}
1424
1425	mtx_unlock(&softc->ctl_lock);
1426
1427	if (entries_dropped > 0)
1428		retval = 1;
1429
1430	*num_entries_dropped = entries_dropped;
1431	*num_entries_filled = entries_filled;
1432
1433	return (retval);
1434}
1435
1436static void
1437ctl_ioctl_online(void *arg)
1438{
1439	struct ctl_ioctl_info *ioctl_info;
1440
1441	ioctl_info = (struct ctl_ioctl_info *)arg;
1442
1443	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1444}
1445
1446static void
1447ctl_ioctl_offline(void *arg)
1448{
1449	struct ctl_ioctl_info *ioctl_info;
1450
1451	ioctl_info = (struct ctl_ioctl_info *)arg;
1452
1453	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1454}
1455
1456/*
1457 * Remove an initiator by port number and initiator ID.
1458 * Returns 0 for success, -1 for failure.
1459 */
1460int
1461ctl_remove_initiator(struct ctl_port *port, int iid)
1462{
1463	struct ctl_softc *softc = control_softc;
1464
1465	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1466
1467	if (iid > CTL_MAX_INIT_PER_PORT) {
1468		printf("%s: initiator ID %u > maximun %u!\n",
1469		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1470		return (-1);
1471	}
1472
1473	mtx_lock(&softc->ctl_lock);
1474	port->wwpn_iid[iid].in_use--;
1475	port->wwpn_iid[iid].last_use = time_uptime;
1476	mtx_unlock(&softc->ctl_lock);
1477
1478	return (0);
1479}
1480
1481/*
1482 * Add an initiator to the initiator map.
1483 * Returns iid for success, < 0 for failure.
1484 */
1485int
1486ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1487{
1488	struct ctl_softc *softc = control_softc;
1489	time_t best_time;
1490	int i, best;
1491
1492	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1493
1494	if (iid >= CTL_MAX_INIT_PER_PORT) {
1495		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1496		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1497		free(name, M_CTL);
1498		return (-1);
1499	}
1500
1501	mtx_lock(&softc->ctl_lock);
1502
1503	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1504		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1505			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1506				iid = i;
1507				break;
1508			}
1509			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1510			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1511				iid = i;
1512				break;
1513			}
1514		}
1515	}
1516
1517	if (iid < 0) {
1518		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1519			if (port->wwpn_iid[i].in_use == 0 &&
1520			    port->wwpn_iid[i].wwpn == 0 &&
1521			    port->wwpn_iid[i].name == NULL) {
1522				iid = i;
1523				break;
1524			}
1525		}
1526	}
1527
1528	if (iid < 0) {
1529		best = -1;
1530		best_time = INT32_MAX;
1531		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1532			if (port->wwpn_iid[i].in_use == 0) {
1533				if (port->wwpn_iid[i].last_use < best_time) {
1534					best = i;
1535					best_time = port->wwpn_iid[i].last_use;
1536				}
1537			}
1538		}
1539		iid = best;
1540	}
1541
1542	if (iid < 0) {
1543		mtx_unlock(&softc->ctl_lock);
1544		free(name, M_CTL);
1545		return (-2);
1546	}
1547
1548	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1549		/*
1550		 * This is not an error yet.
1551		 */
1552		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1553#if 0
1554			printf("%s: port %d iid %u WWPN %#jx arrived"
1555			    " again\n", __func__, port->targ_port,
1556			    iid, (uintmax_t)wwpn);
1557#endif
1558			goto take;
1559		}
1560		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1561		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1562#if 0
1563			printf("%s: port %d iid %u name '%s' arrived"
1564			    " again\n", __func__, port->targ_port,
1565			    iid, name);
1566#endif
1567			goto take;
1568		}
1569
1570		/*
1571		 * This is an error, but what do we do about it?  The
1572		 * driver is telling us we have a new WWPN for this
1573		 * initiator ID, so we pretty much need to use it.
1574		 */
1575		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1576		    " but WWPN %#jx '%s' is still at that address\n",
1577		    __func__, port->targ_port, iid, wwpn, name,
1578		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1579		    port->wwpn_iid[iid].name);
1580
1581		/*
1582		 * XXX KDM clear have_ca and ua_pending on each LUN for
1583		 * this initiator.
1584		 */
1585	}
1586take:
1587	free(port->wwpn_iid[iid].name, M_CTL);
1588	port->wwpn_iid[iid].name = name;
1589	port->wwpn_iid[iid].wwpn = wwpn;
1590	port->wwpn_iid[iid].in_use++;
1591	mtx_unlock(&softc->ctl_lock);
1592
1593	return (iid);
1594}
1595
1596static int
1597ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1598{
1599	int len;
1600
1601	switch (port->port_type) {
1602	case CTL_PORT_FC:
1603	{
1604		struct scsi_transportid_fcp *id =
1605		    (struct scsi_transportid_fcp *)buf;
1606		if (port->wwpn_iid[iid].wwpn == 0)
1607			return (0);
1608		memset(id, 0, sizeof(*id));
1609		id->format_protocol = SCSI_PROTO_FC;
1610		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1611		return (sizeof(*id));
1612	}
1613	case CTL_PORT_ISCSI:
1614	{
1615		struct scsi_transportid_iscsi_port *id =
1616		    (struct scsi_transportid_iscsi_port *)buf;
1617		if (port->wwpn_iid[iid].name == NULL)
1618			return (0);
1619		memset(id, 0, 256);
1620		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1621		    SCSI_PROTO_ISCSI;
1622		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1623		len = roundup2(min(len, 252), 4);
1624		scsi_ulto2b(len, id->additional_length);
1625		return (sizeof(*id) + len);
1626	}
1627	case CTL_PORT_SAS:
1628	{
1629		struct scsi_transportid_sas *id =
1630		    (struct scsi_transportid_sas *)buf;
1631		if (port->wwpn_iid[iid].wwpn == 0)
1632			return (0);
1633		memset(id, 0, sizeof(*id));
1634		id->format_protocol = SCSI_PROTO_SAS;
1635		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1636		return (sizeof(*id));
1637	}
1638	default:
1639	{
1640		struct scsi_transportid_spi *id =
1641		    (struct scsi_transportid_spi *)buf;
1642		memset(id, 0, sizeof(*id));
1643		id->format_protocol = SCSI_PROTO_SPI;
1644		scsi_ulto2b(iid, id->scsi_addr);
1645		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1646		return (sizeof(*id));
1647	}
1648	}
1649}
1650
1651static int
1652ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1653{
1654	return (0);
1655}
1656
1657static int
1658ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1659{
1660	return (0);
1661}
1662
1663/*
1664 * Data movement routine for the CTL ioctl frontend port.
1665 */
1666static int
1667ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1668{
1669	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1670	struct ctl_sg_entry ext_entry, kern_entry;
1671	int ext_sglen, ext_sg_entries, kern_sg_entries;
1672	int ext_sg_start, ext_offset;
1673	int len_to_copy, len_copied;
1674	int kern_watermark, ext_watermark;
1675	int ext_sglist_malloced;
1676	int i, j;
1677
1678	ext_sglist_malloced = 0;
1679	ext_sg_start = 0;
1680	ext_offset = 0;
1681
1682	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1683
1684	/*
1685	 * If this flag is set, fake the data transfer.
1686	 */
1687	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1688		ctsio->ext_data_filled = ctsio->ext_data_len;
1689		goto bailout;
1690	}
1691
1692	/*
1693	 * To simplify things here, if we have a single buffer, stick it in
1694	 * a S/G entry and just make it a single entry S/G list.
1695	 */
1696	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1697		int len_seen;
1698
1699		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1700
1701		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1702							   M_WAITOK);
1703		ext_sglist_malloced = 1;
1704		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1705				   ext_sglen) != 0) {
1706			ctl_set_internal_failure(ctsio,
1707						 /*sks_valid*/ 0,
1708						 /*retry_count*/ 0);
1709			goto bailout;
1710		}
1711		ext_sg_entries = ctsio->ext_sg_entries;
1712		len_seen = 0;
1713		for (i = 0; i < ext_sg_entries; i++) {
1714			if ((len_seen + ext_sglist[i].len) >=
1715			     ctsio->ext_data_filled) {
1716				ext_sg_start = i;
1717				ext_offset = ctsio->ext_data_filled - len_seen;
1718				break;
1719			}
1720			len_seen += ext_sglist[i].len;
1721		}
1722	} else {
1723		ext_sglist = &ext_entry;
1724		ext_sglist->addr = ctsio->ext_data_ptr;
1725		ext_sglist->len = ctsio->ext_data_len;
1726		ext_sg_entries = 1;
1727		ext_sg_start = 0;
1728		ext_offset = ctsio->ext_data_filled;
1729	}
1730
1731	if (ctsio->kern_sg_entries > 0) {
1732		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1733		kern_sg_entries = ctsio->kern_sg_entries;
1734	} else {
1735		kern_sglist = &kern_entry;
1736		kern_sglist->addr = ctsio->kern_data_ptr;
1737		kern_sglist->len = ctsio->kern_data_len;
1738		kern_sg_entries = 1;
1739	}
1740
1741
1742	kern_watermark = 0;
1743	ext_watermark = ext_offset;
1744	len_copied = 0;
1745	for (i = ext_sg_start, j = 0;
1746	     i < ext_sg_entries && j < kern_sg_entries;) {
1747		uint8_t *ext_ptr, *kern_ptr;
1748
1749		len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1750				      kern_sglist[j].len - kern_watermark);
1751
1752		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1753		ext_ptr = ext_ptr + ext_watermark;
1754		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1755			/*
1756			 * XXX KDM fix this!
1757			 */
1758			panic("need to implement bus address support");
1759#if 0
1760			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1761#endif
1762		} else
1763			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1764		kern_ptr = kern_ptr + kern_watermark;
1765
1766		kern_watermark += len_to_copy;
1767		ext_watermark += len_to_copy;
1768
1769		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1770		     CTL_FLAG_DATA_IN) {
1771			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1772					 "bytes to user\n", len_to_copy));
1773			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1774					 "to %p\n", kern_ptr, ext_ptr));
1775			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1776				ctl_set_internal_failure(ctsio,
1777							 /*sks_valid*/ 0,
1778							 /*retry_count*/ 0);
1779				goto bailout;
1780			}
1781		} else {
1782			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1783					 "bytes from user\n", len_to_copy));
1784			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1785					 "to %p\n", ext_ptr, kern_ptr));
1786			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1787				ctl_set_internal_failure(ctsio,
1788							 /*sks_valid*/ 0,
1789							 /*retry_count*/0);
1790				goto bailout;
1791			}
1792		}
1793
1794		len_copied += len_to_copy;
1795
1796		if (ext_sglist[i].len == ext_watermark) {
1797			i++;
1798			ext_watermark = 0;
1799		}
1800
1801		if (kern_sglist[j].len == kern_watermark) {
1802			j++;
1803			kern_watermark = 0;
1804		}
1805	}
1806
1807	ctsio->ext_data_filled += len_copied;
1808
1809	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1810			 "kern_sg_entries: %d\n", ext_sg_entries,
1811			 kern_sg_entries));
1812	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1813			 "kern_data_len = %d\n", ctsio->ext_data_len,
1814			 ctsio->kern_data_len));
1815
1816
1817	/* XXX KDM set residual?? */
1818bailout:
1819
1820	if (ext_sglist_malloced != 0)
1821		free(ext_sglist, M_CTL);
1822
1823	return (CTL_RETVAL_COMPLETE);
1824}
1825
1826/*
1827 * Serialize a command that went down the "wrong" side, and so was sent to
1828 * this controller for execution.  The logic is a little different than the
1829 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1830 * sent back to the other side, but in the success case, we execute the
1831 * command on this side (XFER mode) or tell the other side to execute it
1832 * (SER_ONLY mode).
1833 */
1834static int
1835ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1836{
1837	struct ctl_softc *ctl_softc;
1838	union ctl_ha_msg msg_info;
1839	struct ctl_lun *lun;
1840	int retval = 0;
1841	uint32_t targ_lun;
1842
1843	ctl_softc = control_softc;
1844
1845	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1846	lun = ctl_softc->ctl_luns[targ_lun];
1847	if (lun==NULL)
1848	{
1849		/*
1850		 * Why isn't LUN defined? The other side wouldn't
1851		 * send a cmd if the LUN is undefined.
1852		 */
1853		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1854
1855		/* "Logical unit not supported" */
1856		ctl_set_sense_data(&msg_info.scsi.sense_data,
1857				   lun,
1858				   /*sense_format*/SSD_TYPE_NONE,
1859				   /*current_error*/ 1,
1860				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1861				   /*asc*/ 0x25,
1862				   /*ascq*/ 0x00,
1863				   SSD_ELEM_NONE);
1864
1865		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1866		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1867		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1868		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1869		msg_info.hdr.serializing_sc = NULL;
1870		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1871	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1872				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1873		}
1874		return(1);
1875
1876	}
1877
1878	mtx_lock(&lun->lun_lock);
1879    	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1880
1881	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1882		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1883		 ooa_links))) {
1884	case CTL_ACTION_BLOCK:
1885		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1886		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1887				  blocked_links);
1888		break;
1889	case CTL_ACTION_PASS:
1890	case CTL_ACTION_SKIP:
1891		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1892			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1893			ctl_enqueue_rtr((union ctl_io *)ctsio);
1894		} else {
1895
1896			/* send msg back to other side */
1897			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1898			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1899			msg_info.hdr.msg_type = CTL_MSG_R2R;
1900#if 0
1901			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1902#endif
1903		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1904			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1905			}
1906		}
1907		break;
1908	case CTL_ACTION_OVERLAP:
1909		/* OVERLAPPED COMMANDS ATTEMPTED */
1910		ctl_set_sense_data(&msg_info.scsi.sense_data,
1911				   lun,
1912				   /*sense_format*/SSD_TYPE_NONE,
1913				   /*current_error*/ 1,
1914				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1915				   /*asc*/ 0x4E,
1916				   /*ascq*/ 0x00,
1917				   SSD_ELEM_NONE);
1918
1919		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1920		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1921		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1922		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1923		msg_info.hdr.serializing_sc = NULL;
1924		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1925#if 0
1926		printf("BAD JUJU:Major Bummer Overlap\n");
1927#endif
1928		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1929		retval = 1;
1930		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1931		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1932		}
1933		break;
1934	case CTL_ACTION_OVERLAP_TAG:
1935		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1936		ctl_set_sense_data(&msg_info.scsi.sense_data,
1937				   lun,
1938				   /*sense_format*/SSD_TYPE_NONE,
1939				   /*current_error*/ 1,
1940				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1941				   /*asc*/ 0x4D,
1942				   /*ascq*/ ctsio->tag_num & 0xff,
1943				   SSD_ELEM_NONE);
1944
1945		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1946		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1947		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1948		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1949		msg_info.hdr.serializing_sc = NULL;
1950		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1951#if 0
1952		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1953#endif
1954		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1955		retval = 1;
1956		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1957		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1958		}
1959		break;
1960	case CTL_ACTION_ERROR:
1961	default:
1962		/* "Internal target failure" */
1963		ctl_set_sense_data(&msg_info.scsi.sense_data,
1964				   lun,
1965				   /*sense_format*/SSD_TYPE_NONE,
1966				   /*current_error*/ 1,
1967				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1968				   /*asc*/ 0x44,
1969				   /*ascq*/ 0x00,
1970				   SSD_ELEM_NONE);
1971
1972		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1973		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1974		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1975		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1976		msg_info.hdr.serializing_sc = NULL;
1977		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1978#if 0
1979		printf("BAD JUJU:Major Bummer HW Error\n");
1980#endif
1981		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1982		retval = 1;
1983		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1984		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1985		}
1986		break;
1987	}
1988	mtx_unlock(&lun->lun_lock);
1989	return (retval);
1990}
1991
1992static int
1993ctl_ioctl_submit_wait(union ctl_io *io)
1994{
1995	struct ctl_fe_ioctl_params params;
1996	ctl_fe_ioctl_state last_state;
1997	int done, retval;
1998
1999	retval = 0;
2000
2001	bzero(&params, sizeof(params));
2002
2003	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
2004	cv_init(&params.sem, "ctlioccv");
2005	params.state = CTL_IOCTL_INPROG;
2006	last_state = params.state;
2007
2008	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
2009
2010	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
2011
2012	/* This shouldn't happen */
2013	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
2014		return (retval);
2015
2016	done = 0;
2017
2018	do {
2019		mtx_lock(&params.ioctl_mtx);
2020		/*
2021		 * Check the state here, and don't sleep if the state has
2022		 * already changed (i.e. wakeup has already occured, but we
2023		 * weren't waiting yet).
2024		 */
2025		if (params.state == last_state) {
2026			/* XXX KDM cv_wait_sig instead? */
2027			cv_wait(&params.sem, &params.ioctl_mtx);
2028		}
2029		last_state = params.state;
2030
2031		switch (params.state) {
2032		case CTL_IOCTL_INPROG:
2033			/* Why did we wake up? */
2034			/* XXX KDM error here? */
2035			mtx_unlock(&params.ioctl_mtx);
2036			break;
2037		case CTL_IOCTL_DATAMOVE:
2038			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
2039
2040			/*
2041			 * change last_state back to INPROG to avoid
2042			 * deadlock on subsequent data moves.
2043			 */
2044			params.state = last_state = CTL_IOCTL_INPROG;
2045
2046			mtx_unlock(&params.ioctl_mtx);
2047			ctl_ioctl_do_datamove(&io->scsiio);
2048			/*
2049			 * Note that in some cases, most notably writes,
2050			 * this will queue the I/O and call us back later.
2051			 * In other cases, generally reads, this routine
2052			 * will immediately call back and wake us up,
2053			 * probably using our own context.
2054			 */
2055			io->scsiio.be_move_done(io);
2056			break;
2057		case CTL_IOCTL_DONE:
2058			mtx_unlock(&params.ioctl_mtx);
2059			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
2060			done = 1;
2061			break;
2062		default:
2063			mtx_unlock(&params.ioctl_mtx);
2064			/* XXX KDM error here? */
2065			break;
2066		}
2067	} while (done == 0);
2068
2069	mtx_destroy(&params.ioctl_mtx);
2070	cv_destroy(&params.sem);
2071
2072	return (CTL_RETVAL_COMPLETE);
2073}
2074
2075static void
2076ctl_ioctl_datamove(union ctl_io *io)
2077{
2078	struct ctl_fe_ioctl_params *params;
2079
2080	params = (struct ctl_fe_ioctl_params *)
2081		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2082
2083	mtx_lock(&params->ioctl_mtx);
2084	params->state = CTL_IOCTL_DATAMOVE;
2085	cv_broadcast(&params->sem);
2086	mtx_unlock(&params->ioctl_mtx);
2087}
2088
2089static void
2090ctl_ioctl_done(union ctl_io *io)
2091{
2092	struct ctl_fe_ioctl_params *params;
2093
2094	params = (struct ctl_fe_ioctl_params *)
2095		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2096
2097	mtx_lock(&params->ioctl_mtx);
2098	params->state = CTL_IOCTL_DONE;
2099	cv_broadcast(&params->sem);
2100	mtx_unlock(&params->ioctl_mtx);
2101}
2102
2103static void
2104ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2105{
2106	struct ctl_fe_ioctl_startstop_info *sd_info;
2107
2108	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2109
2110	sd_info->hs_info.status = metatask->status;
2111	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2112	sd_info->hs_info.luns_complete =
2113		metatask->taskinfo.startstop.luns_complete;
2114	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2115
2116	cv_broadcast(&sd_info->sem);
2117}
2118
2119static void
2120ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2121{
2122	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2123
2124	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2125
2126	mtx_lock(fe_bbr_info->lock);
2127	fe_bbr_info->bbr_info->status = metatask->status;
2128	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2129	fe_bbr_info->wakeup_done = 1;
2130	mtx_unlock(fe_bbr_info->lock);
2131
2132	cv_broadcast(&fe_bbr_info->sem);
2133}
2134
2135/*
2136 * Returns 0 for success, errno for failure.
2137 */
2138static int
2139ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2140		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2141{
2142	union ctl_io *io;
2143	int retval;
2144
2145	retval = 0;
2146
2147	mtx_lock(&lun->lun_lock);
2148	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2149	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2150	     ooa_links)) {
2151		struct ctl_ooa_entry *entry;
2152
2153		/*
2154		 * If we've got more than we can fit, just count the
2155		 * remaining entries.
2156		 */
2157		if (*cur_fill_num >= ooa_hdr->alloc_num)
2158			continue;
2159
2160		entry = &kern_entries[*cur_fill_num];
2161
2162		entry->tag_num = io->scsiio.tag_num;
2163		entry->lun_num = lun->lun;
2164#ifdef CTL_TIME_IO
2165		entry->start_bt = io->io_hdr.start_bt;
2166#endif
2167		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2168		entry->cdb_len = io->scsiio.cdb_len;
2169		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2170			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2171
2172		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2173			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2174
2175		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2176			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2177
2178		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2179			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2180
2181		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2182			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2183	}
2184	mtx_unlock(&lun->lun_lock);
2185
2186	return (retval);
2187}
2188
2189static void *
2190ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2191		 size_t error_str_len)
2192{
2193	void *kptr;
2194
2195	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2196
2197	if (copyin(user_addr, kptr, len) != 0) {
2198		snprintf(error_str, error_str_len, "Error copying %d bytes "
2199			 "from user address %p to kernel address %p", len,
2200			 user_addr, kptr);
2201		free(kptr, M_CTL);
2202		return (NULL);
2203	}
2204
2205	return (kptr);
2206}
2207
2208static void
2209ctl_free_args(int num_args, struct ctl_be_arg *args)
2210{
2211	int i;
2212
2213	if (args == NULL)
2214		return;
2215
2216	for (i = 0; i < num_args; i++) {
2217		free(args[i].kname, M_CTL);
2218		free(args[i].kvalue, M_CTL);
2219	}
2220
2221	free(args, M_CTL);
2222}
2223
2224static struct ctl_be_arg *
2225ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2226		char *error_str, size_t error_str_len)
2227{
2228	struct ctl_be_arg *args;
2229	int i;
2230
2231	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2232				error_str, error_str_len);
2233
2234	if (args == NULL)
2235		goto bailout;
2236
2237	for (i = 0; i < num_args; i++) {
2238		args[i].kname = NULL;
2239		args[i].kvalue = NULL;
2240	}
2241
2242	for (i = 0; i < num_args; i++) {
2243		uint8_t *tmpptr;
2244
2245		args[i].kname = ctl_copyin_alloc(args[i].name,
2246			args[i].namelen, error_str, error_str_len);
2247		if (args[i].kname == NULL)
2248			goto bailout;
2249
2250		if (args[i].kname[args[i].namelen - 1] != '\0') {
2251			snprintf(error_str, error_str_len, "Argument %d "
2252				 "name is not NUL-terminated", i);
2253			goto bailout;
2254		}
2255
2256		if (args[i].flags & CTL_BEARG_RD) {
2257			tmpptr = ctl_copyin_alloc(args[i].value,
2258				args[i].vallen, error_str, error_str_len);
2259			if (tmpptr == NULL)
2260				goto bailout;
2261			if ((args[i].flags & CTL_BEARG_ASCII)
2262			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2263				snprintf(error_str, error_str_len, "Argument "
2264				    "%d value is not NUL-terminated", i);
2265				goto bailout;
2266			}
2267			args[i].kvalue = tmpptr;
2268		} else {
2269			args[i].kvalue = malloc(args[i].vallen,
2270			    M_CTL, M_WAITOK | M_ZERO);
2271		}
2272	}
2273
2274	return (args);
2275bailout:
2276
2277	ctl_free_args(num_args, args);
2278
2279	return (NULL);
2280}
2281
2282static void
2283ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2284{
2285	int i;
2286
2287	for (i = 0; i < num_args; i++) {
2288		if (args[i].flags & CTL_BEARG_WR)
2289			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2290	}
2291}
2292
2293/*
2294 * Escape characters that are illegal or not recommended in XML.
2295 */
2296int
2297ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2298{
2299	char *end = str + size;
2300	int retval;
2301
2302	retval = 0;
2303
2304	for (; *str && str < end; str++) {
2305		switch (*str) {
2306		case '&':
2307			retval = sbuf_printf(sb, "&amp;");
2308			break;
2309		case '>':
2310			retval = sbuf_printf(sb, "&gt;");
2311			break;
2312		case '<':
2313			retval = sbuf_printf(sb, "&lt;");
2314			break;
2315		default:
2316			retval = sbuf_putc(sb, *str);
2317			break;
2318		}
2319
2320		if (retval != 0)
2321			break;
2322
2323	}
2324
2325	return (retval);
2326}
2327
2328static void
2329ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2330{
2331	struct scsi_vpd_id_descriptor *desc;
2332	int i;
2333
2334	if (id == NULL || id->len < 4)
2335		return;
2336	desc = (struct scsi_vpd_id_descriptor *)id->data;
2337	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2338	case SVPD_ID_TYPE_T10:
2339		sbuf_printf(sb, "t10.");
2340		break;
2341	case SVPD_ID_TYPE_EUI64:
2342		sbuf_printf(sb, "eui.");
2343		break;
2344	case SVPD_ID_TYPE_NAA:
2345		sbuf_printf(sb, "naa.");
2346		break;
2347	case SVPD_ID_TYPE_SCSI_NAME:
2348		break;
2349	}
2350	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2351	case SVPD_ID_CODESET_BINARY:
2352		for (i = 0; i < desc->length; i++)
2353			sbuf_printf(sb, "%02x", desc->identifier[i]);
2354		break;
2355	case SVPD_ID_CODESET_ASCII:
2356		sbuf_printf(sb, "%.*s", (int)desc->length,
2357		    (char *)desc->identifier);
2358		break;
2359	case SVPD_ID_CODESET_UTF8:
2360		sbuf_printf(sb, "%s", (char *)desc->identifier);
2361		break;
2362	}
2363}
2364
2365static int
2366ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2367	  struct thread *td)
2368{
2369	struct ctl_softc *softc;
2370	int retval;
2371
2372	softc = control_softc;
2373
2374	retval = 0;
2375
2376	switch (cmd) {
2377	case CTL_IO: {
2378		union ctl_io *io;
2379		void *pool_tmp;
2380
2381		/*
2382		 * If we haven't been "enabled", don't allow any SCSI I/O
2383		 * to this FETD.
2384		 */
2385		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2386			retval = EPERM;
2387			break;
2388		}
2389
2390		io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2391
2392		/*
2393		 * Need to save the pool reference so it doesn't get
2394		 * spammed by the user's ctl_io.
2395		 */
2396		pool_tmp = io->io_hdr.pool;
2397		memcpy(io, (void *)addr, sizeof(*io));
2398		io->io_hdr.pool = pool_tmp;
2399
2400		/*
2401		 * No status yet, so make sure the status is set properly.
2402		 */
2403		io->io_hdr.status = CTL_STATUS_NONE;
2404
2405		/*
2406		 * The user sets the initiator ID, target and LUN IDs.
2407		 */
2408		io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2409		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2410		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2411		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2412			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2413
2414		retval = ctl_ioctl_submit_wait(io);
2415
2416		if (retval != 0) {
2417			ctl_free_io(io);
2418			break;
2419		}
2420
2421		memcpy((void *)addr, io, sizeof(*io));
2422
2423		/* return this to our pool */
2424		ctl_free_io(io);
2425
2426		break;
2427	}
2428	case CTL_ENABLE_PORT:
2429	case CTL_DISABLE_PORT:
2430	case CTL_SET_PORT_WWNS: {
2431		struct ctl_port *port;
2432		struct ctl_port_entry *entry;
2433
2434		entry = (struct ctl_port_entry *)addr;
2435
2436		mtx_lock(&softc->ctl_lock);
2437		STAILQ_FOREACH(port, &softc->port_list, links) {
2438			int action, done;
2439
2440			action = 0;
2441			done = 0;
2442
2443			if ((entry->port_type == CTL_PORT_NONE)
2444			 && (entry->targ_port == port->targ_port)) {
2445				/*
2446				 * If the user only wants to enable or
2447				 * disable or set WWNs on a specific port,
2448				 * do the operation and we're done.
2449				 */
2450				action = 1;
2451				done = 1;
2452			} else if (entry->port_type & port->port_type) {
2453				/*
2454				 * Compare the user's type mask with the
2455				 * particular frontend type to see if we
2456				 * have a match.
2457				 */
2458				action = 1;
2459				done = 0;
2460
2461				/*
2462				 * Make sure the user isn't trying to set
2463				 * WWNs on multiple ports at the same time.
2464				 */
2465				if (cmd == CTL_SET_PORT_WWNS) {
2466					printf("%s: Can't set WWNs on "
2467					       "multiple ports\n", __func__);
2468					retval = EINVAL;
2469					break;
2470				}
2471			}
2472			if (action != 0) {
2473				/*
2474				 * XXX KDM we have to drop the lock here,
2475				 * because the online/offline operations
2476				 * can potentially block.  We need to
2477				 * reference count the frontends so they
2478				 * can't go away,
2479				 */
2480				mtx_unlock(&softc->ctl_lock);
2481
2482				if (cmd == CTL_ENABLE_PORT) {
2483					struct ctl_lun *lun;
2484
2485					STAILQ_FOREACH(lun, &softc->lun_list,
2486						       links) {
2487						port->lun_enable(port->targ_lun_arg,
2488						    lun->target,
2489						    lun->lun);
2490					}
2491
2492					ctl_port_online(port);
2493				} else if (cmd == CTL_DISABLE_PORT) {
2494					struct ctl_lun *lun;
2495
2496					ctl_port_offline(port);
2497
2498					STAILQ_FOREACH(lun, &softc->lun_list,
2499						       links) {
2500						port->lun_disable(
2501						    port->targ_lun_arg,
2502						    lun->target,
2503						    lun->lun);
2504					}
2505				}
2506
2507				mtx_lock(&softc->ctl_lock);
2508
2509				if (cmd == CTL_SET_PORT_WWNS)
2510					ctl_port_set_wwns(port,
2511					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2512					    1 : 0, entry->wwnn,
2513					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2514					    1 : 0, entry->wwpn);
2515			}
2516			if (done != 0)
2517				break;
2518		}
2519		mtx_unlock(&softc->ctl_lock);
2520		break;
2521	}
2522	case CTL_GET_PORT_LIST: {
2523		struct ctl_port *port;
2524		struct ctl_port_list *list;
2525		int i;
2526
2527		list = (struct ctl_port_list *)addr;
2528
2529		if (list->alloc_len != (list->alloc_num *
2530		    sizeof(struct ctl_port_entry))) {
2531			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2532			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2533			       "%zu\n", __func__, list->alloc_len,
2534			       list->alloc_num, sizeof(struct ctl_port_entry));
2535			retval = EINVAL;
2536			break;
2537		}
2538		list->fill_len = 0;
2539		list->fill_num = 0;
2540		list->dropped_num = 0;
2541		i = 0;
2542		mtx_lock(&softc->ctl_lock);
2543		STAILQ_FOREACH(port, &softc->port_list, links) {
2544			struct ctl_port_entry entry, *list_entry;
2545
2546			if (list->fill_num >= list->alloc_num) {
2547				list->dropped_num++;
2548				continue;
2549			}
2550
2551			entry.port_type = port->port_type;
2552			strlcpy(entry.port_name, port->port_name,
2553				sizeof(entry.port_name));
2554			entry.targ_port = port->targ_port;
2555			entry.physical_port = port->physical_port;
2556			entry.virtual_port = port->virtual_port;
2557			entry.wwnn = port->wwnn;
2558			entry.wwpn = port->wwpn;
2559			if (port->status & CTL_PORT_STATUS_ONLINE)
2560				entry.online = 1;
2561			else
2562				entry.online = 0;
2563
2564			list_entry = &list->entries[i];
2565
2566			retval = copyout(&entry, list_entry, sizeof(entry));
2567			if (retval != 0) {
2568				printf("%s: CTL_GET_PORT_LIST: copyout "
2569				       "returned %d\n", __func__, retval);
2570				break;
2571			}
2572			i++;
2573			list->fill_num++;
2574			list->fill_len += sizeof(entry);
2575		}
2576		mtx_unlock(&softc->ctl_lock);
2577
2578		/*
2579		 * If this is non-zero, we had a copyout fault, so there's
2580		 * probably no point in attempting to set the status inside
2581		 * the structure.
2582		 */
2583		if (retval != 0)
2584			break;
2585
2586		if (list->dropped_num > 0)
2587			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2588		else
2589			list->status = CTL_PORT_LIST_OK;
2590		break;
2591	}
2592	case CTL_DUMP_OOA: {
2593		struct ctl_lun *lun;
2594		union ctl_io *io;
2595		char printbuf[128];
2596		struct sbuf sb;
2597
2598		mtx_lock(&softc->ctl_lock);
2599		printf("Dumping OOA queues:\n");
2600		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2601			mtx_lock(&lun->lun_lock);
2602			for (io = (union ctl_io *)TAILQ_FIRST(
2603			     &lun->ooa_queue); io != NULL;
2604			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2605			     ooa_links)) {
2606				sbuf_new(&sb, printbuf, sizeof(printbuf),
2607					 SBUF_FIXEDLEN);
2608				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2609					    (intmax_t)lun->lun,
2610					    io->scsiio.tag_num,
2611					    (io->io_hdr.flags &
2612					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2613					    (io->io_hdr.flags &
2614					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2615					    (io->io_hdr.flags &
2616					    CTL_FLAG_ABORT) ? " ABORT" : "",
2617			                    (io->io_hdr.flags &
2618		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2619				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2620				sbuf_finish(&sb);
2621				printf("%s\n", sbuf_data(&sb));
2622			}
2623			mtx_unlock(&lun->lun_lock);
2624		}
2625		printf("OOA queues dump done\n");
2626		mtx_unlock(&softc->ctl_lock);
2627		break;
2628	}
2629	case CTL_GET_OOA: {
2630		struct ctl_lun *lun;
2631		struct ctl_ooa *ooa_hdr;
2632		struct ctl_ooa_entry *entries;
2633		uint32_t cur_fill_num;
2634
2635		ooa_hdr = (struct ctl_ooa *)addr;
2636
2637		if ((ooa_hdr->alloc_len == 0)
2638		 || (ooa_hdr->alloc_num == 0)) {
2639			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2640			       "must be non-zero\n", __func__,
2641			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2642			retval = EINVAL;
2643			break;
2644		}
2645
2646		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2647		    sizeof(struct ctl_ooa_entry))) {
2648			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2649			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2650			       __func__, ooa_hdr->alloc_len,
2651			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2652			retval = EINVAL;
2653			break;
2654		}
2655
2656		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2657		if (entries == NULL) {
2658			printf("%s: could not allocate %d bytes for OOA "
2659			       "dump\n", __func__, ooa_hdr->alloc_len);
2660			retval = ENOMEM;
2661			break;
2662		}
2663
2664		mtx_lock(&softc->ctl_lock);
2665		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2666		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2667		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2668			mtx_unlock(&softc->ctl_lock);
2669			free(entries, M_CTL);
2670			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2671			       __func__, (uintmax_t)ooa_hdr->lun_num);
2672			retval = EINVAL;
2673			break;
2674		}
2675
2676		cur_fill_num = 0;
2677
2678		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2679			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2680				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2681					ooa_hdr, entries);
2682				if (retval != 0)
2683					break;
2684			}
2685			if (retval != 0) {
2686				mtx_unlock(&softc->ctl_lock);
2687				free(entries, M_CTL);
2688				break;
2689			}
2690		} else {
2691			lun = softc->ctl_luns[ooa_hdr->lun_num];
2692
2693			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2694						    entries);
2695		}
2696		mtx_unlock(&softc->ctl_lock);
2697
2698		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2699		ooa_hdr->fill_len = ooa_hdr->fill_num *
2700			sizeof(struct ctl_ooa_entry);
2701		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2702		if (retval != 0) {
2703			printf("%s: error copying out %d bytes for OOA dump\n",
2704			       __func__, ooa_hdr->fill_len);
2705		}
2706
2707		getbintime(&ooa_hdr->cur_bt);
2708
2709		if (cur_fill_num > ooa_hdr->alloc_num) {
2710			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2711			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2712		} else {
2713			ooa_hdr->dropped_num = 0;
2714			ooa_hdr->status = CTL_OOA_OK;
2715		}
2716
2717		free(entries, M_CTL);
2718		break;
2719	}
2720	case CTL_CHECK_OOA: {
2721		union ctl_io *io;
2722		struct ctl_lun *lun;
2723		struct ctl_ooa_info *ooa_info;
2724
2725
2726		ooa_info = (struct ctl_ooa_info *)addr;
2727
2728		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2729			ooa_info->status = CTL_OOA_INVALID_LUN;
2730			break;
2731		}
2732		mtx_lock(&softc->ctl_lock);
2733		lun = softc->ctl_luns[ooa_info->lun_id];
2734		if (lun == NULL) {
2735			mtx_unlock(&softc->ctl_lock);
2736			ooa_info->status = CTL_OOA_INVALID_LUN;
2737			break;
2738		}
2739		mtx_lock(&lun->lun_lock);
2740		mtx_unlock(&softc->ctl_lock);
2741		ooa_info->num_entries = 0;
2742		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2743		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2744		     &io->io_hdr, ooa_links)) {
2745			ooa_info->num_entries++;
2746		}
2747		mtx_unlock(&lun->lun_lock);
2748
2749		ooa_info->status = CTL_OOA_SUCCESS;
2750
2751		break;
2752	}
2753	case CTL_HARD_START:
2754	case CTL_HARD_STOP: {
2755		struct ctl_fe_ioctl_startstop_info ss_info;
2756		struct cfi_metatask *metatask;
2757		struct mtx hs_mtx;
2758
2759		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2760
2761		cv_init(&ss_info.sem, "hard start/stop cv" );
2762
2763		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2764		if (metatask == NULL) {
2765			retval = ENOMEM;
2766			mtx_destroy(&hs_mtx);
2767			break;
2768		}
2769
2770		if (cmd == CTL_HARD_START)
2771			metatask->tasktype = CFI_TASK_STARTUP;
2772		else
2773			metatask->tasktype = CFI_TASK_SHUTDOWN;
2774
2775		metatask->callback = ctl_ioctl_hard_startstop_callback;
2776		metatask->callback_arg = &ss_info;
2777
2778		cfi_action(metatask);
2779
2780		/* Wait for the callback */
2781		mtx_lock(&hs_mtx);
2782		cv_wait_sig(&ss_info.sem, &hs_mtx);
2783		mtx_unlock(&hs_mtx);
2784
2785		/*
2786		 * All information has been copied from the metatask by the
2787		 * time cv_broadcast() is called, so we free the metatask here.
2788		 */
2789		cfi_free_metatask(metatask);
2790
2791		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2792
2793		mtx_destroy(&hs_mtx);
2794		break;
2795	}
2796	case CTL_BBRREAD: {
2797		struct ctl_bbrread_info *bbr_info;
2798		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2799		struct mtx bbr_mtx;
2800		struct cfi_metatask *metatask;
2801
2802		bbr_info = (struct ctl_bbrread_info *)addr;
2803
2804		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2805
2806		bzero(&bbr_mtx, sizeof(bbr_mtx));
2807		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2808
2809		fe_bbr_info.bbr_info = bbr_info;
2810		fe_bbr_info.lock = &bbr_mtx;
2811
2812		cv_init(&fe_bbr_info.sem, "BBR read cv");
2813		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2814
2815		if (metatask == NULL) {
2816			mtx_destroy(&bbr_mtx);
2817			cv_destroy(&fe_bbr_info.sem);
2818			retval = ENOMEM;
2819			break;
2820		}
2821		metatask->tasktype = CFI_TASK_BBRREAD;
2822		metatask->callback = ctl_ioctl_bbrread_callback;
2823		metatask->callback_arg = &fe_bbr_info;
2824		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2825		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2826		metatask->taskinfo.bbrread.len = bbr_info->len;
2827
2828		cfi_action(metatask);
2829
2830		mtx_lock(&bbr_mtx);
2831		while (fe_bbr_info.wakeup_done == 0)
2832			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2833		mtx_unlock(&bbr_mtx);
2834
2835		bbr_info->status = metatask->status;
2836		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2837		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2838		memcpy(&bbr_info->sense_data,
2839		       &metatask->taskinfo.bbrread.sense_data,
2840		       ctl_min(sizeof(bbr_info->sense_data),
2841			       sizeof(metatask->taskinfo.bbrread.sense_data)));
2842
2843		cfi_free_metatask(metatask);
2844
2845		mtx_destroy(&bbr_mtx);
2846		cv_destroy(&fe_bbr_info.sem);
2847
2848		break;
2849	}
2850	case CTL_DELAY_IO: {
2851		struct ctl_io_delay_info *delay_info;
2852#ifdef CTL_IO_DELAY
2853		struct ctl_lun *lun;
2854#endif /* CTL_IO_DELAY */
2855
2856		delay_info = (struct ctl_io_delay_info *)addr;
2857
2858#ifdef CTL_IO_DELAY
2859		mtx_lock(&softc->ctl_lock);
2860
2861		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2862		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2863			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2864		} else {
2865			lun = softc->ctl_luns[delay_info->lun_id];
2866			mtx_lock(&lun->lun_lock);
2867
2868			delay_info->status = CTL_DELAY_STATUS_OK;
2869
2870			switch (delay_info->delay_type) {
2871			case CTL_DELAY_TYPE_CONT:
2872				break;
2873			case CTL_DELAY_TYPE_ONESHOT:
2874				break;
2875			default:
2876				delay_info->status =
2877					CTL_DELAY_STATUS_INVALID_TYPE;
2878				break;
2879			}
2880
2881			switch (delay_info->delay_loc) {
2882			case CTL_DELAY_LOC_DATAMOVE:
2883				lun->delay_info.datamove_type =
2884					delay_info->delay_type;
2885				lun->delay_info.datamove_delay =
2886					delay_info->delay_secs;
2887				break;
2888			case CTL_DELAY_LOC_DONE:
2889				lun->delay_info.done_type =
2890					delay_info->delay_type;
2891				lun->delay_info.done_delay =
2892					delay_info->delay_secs;
2893				break;
2894			default:
2895				delay_info->status =
2896					CTL_DELAY_STATUS_INVALID_LOC;
2897				break;
2898			}
2899			mtx_unlock(&lun->lun_lock);
2900		}
2901
2902		mtx_unlock(&softc->ctl_lock);
2903#else
2904		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2905#endif /* CTL_IO_DELAY */
2906		break;
2907	}
2908	case CTL_REALSYNC_SET: {
2909		int *syncstate;
2910
2911		syncstate = (int *)addr;
2912
2913		mtx_lock(&softc->ctl_lock);
2914		switch (*syncstate) {
2915		case 0:
2916			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2917			break;
2918		case 1:
2919			softc->flags |= CTL_FLAG_REAL_SYNC;
2920			break;
2921		default:
2922			retval = EINVAL;
2923			break;
2924		}
2925		mtx_unlock(&softc->ctl_lock);
2926		break;
2927	}
2928	case CTL_REALSYNC_GET: {
2929		int *syncstate;
2930
2931		syncstate = (int*)addr;
2932
2933		mtx_lock(&softc->ctl_lock);
2934		if (softc->flags & CTL_FLAG_REAL_SYNC)
2935			*syncstate = 1;
2936		else
2937			*syncstate = 0;
2938		mtx_unlock(&softc->ctl_lock);
2939
2940		break;
2941	}
2942	case CTL_SETSYNC:
2943	case CTL_GETSYNC: {
2944		struct ctl_sync_info *sync_info;
2945		struct ctl_lun *lun;
2946
2947		sync_info = (struct ctl_sync_info *)addr;
2948
2949		mtx_lock(&softc->ctl_lock);
2950		lun = softc->ctl_luns[sync_info->lun_id];
2951		if (lun == NULL) {
2952			mtx_unlock(&softc->ctl_lock);
2953			sync_info->status = CTL_GS_SYNC_NO_LUN;
2954		}
2955		/*
2956		 * Get or set the sync interval.  We're not bounds checking
2957		 * in the set case, hopefully the user won't do something
2958		 * silly.
2959		 */
2960		mtx_lock(&lun->lun_lock);
2961		mtx_unlock(&softc->ctl_lock);
2962		if (cmd == CTL_GETSYNC)
2963			sync_info->sync_interval = lun->sync_interval;
2964		else
2965			lun->sync_interval = sync_info->sync_interval;
2966		mtx_unlock(&lun->lun_lock);
2967
2968		sync_info->status = CTL_GS_SYNC_OK;
2969
2970		break;
2971	}
2972	case CTL_GETSTATS: {
2973		struct ctl_stats *stats;
2974		struct ctl_lun *lun;
2975		int i;
2976
2977		stats = (struct ctl_stats *)addr;
2978
2979		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2980		     stats->alloc_len) {
2981			stats->status = CTL_SS_NEED_MORE_SPACE;
2982			stats->num_luns = softc->num_luns;
2983			break;
2984		}
2985		/*
2986		 * XXX KDM no locking here.  If the LUN list changes,
2987		 * things can blow up.
2988		 */
2989		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2990		     i++, lun = STAILQ_NEXT(lun, links)) {
2991			retval = copyout(&lun->stats, &stats->lun_stats[i],
2992					 sizeof(lun->stats));
2993			if (retval != 0)
2994				break;
2995		}
2996		stats->num_luns = softc->num_luns;
2997		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2998				 softc->num_luns;
2999		stats->status = CTL_SS_OK;
3000#ifdef CTL_TIME_IO
3001		stats->flags = CTL_STATS_FLAG_TIME_VALID;
3002#else
3003		stats->flags = CTL_STATS_FLAG_NONE;
3004#endif
3005		getnanouptime(&stats->timestamp);
3006		break;
3007	}
3008	case CTL_ERROR_INJECT: {
3009		struct ctl_error_desc *err_desc, *new_err_desc;
3010		struct ctl_lun *lun;
3011
3012		err_desc = (struct ctl_error_desc *)addr;
3013
3014		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
3015				      M_WAITOK | M_ZERO);
3016		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
3017
3018		mtx_lock(&softc->ctl_lock);
3019		lun = softc->ctl_luns[err_desc->lun_id];
3020		if (lun == NULL) {
3021			mtx_unlock(&softc->ctl_lock);
3022			free(new_err_desc, M_CTL);
3023			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
3024			       __func__, (uintmax_t)err_desc->lun_id);
3025			retval = EINVAL;
3026			break;
3027		}
3028		mtx_lock(&lun->lun_lock);
3029		mtx_unlock(&softc->ctl_lock);
3030
3031		/*
3032		 * We could do some checking here to verify the validity
3033		 * of the request, but given the complexity of error
3034		 * injection requests, the checking logic would be fairly
3035		 * complex.
3036		 *
3037		 * For now, if the request is invalid, it just won't get
3038		 * executed and might get deleted.
3039		 */
3040		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
3041
3042		/*
3043		 * XXX KDM check to make sure the serial number is unique,
3044		 * in case we somehow manage to wrap.  That shouldn't
3045		 * happen for a very long time, but it's the right thing to
3046		 * do.
3047		 */
3048		new_err_desc->serial = lun->error_serial;
3049		err_desc->serial = lun->error_serial;
3050		lun->error_serial++;
3051
3052		mtx_unlock(&lun->lun_lock);
3053		break;
3054	}
3055	case CTL_ERROR_INJECT_DELETE: {
3056		struct ctl_error_desc *delete_desc, *desc, *desc2;
3057		struct ctl_lun *lun;
3058		int delete_done;
3059
3060		delete_desc = (struct ctl_error_desc *)addr;
3061		delete_done = 0;
3062
3063		mtx_lock(&softc->ctl_lock);
3064		lun = softc->ctl_luns[delete_desc->lun_id];
3065		if (lun == NULL) {
3066			mtx_unlock(&softc->ctl_lock);
3067			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
3068			       __func__, (uintmax_t)delete_desc->lun_id);
3069			retval = EINVAL;
3070			break;
3071		}
3072		mtx_lock(&lun->lun_lock);
3073		mtx_unlock(&softc->ctl_lock);
3074		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
3075			if (desc->serial != delete_desc->serial)
3076				continue;
3077
3078			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
3079				      links);
3080			free(desc, M_CTL);
3081			delete_done = 1;
3082		}
3083		mtx_unlock(&lun->lun_lock);
3084		if (delete_done == 0) {
3085			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
3086			       "error serial %ju on LUN %u\n", __func__,
3087			       delete_desc->serial, delete_desc->lun_id);
3088			retval = EINVAL;
3089			break;
3090		}
3091		break;
3092	}
3093	case CTL_DUMP_STRUCTS: {
3094		int i, j, k;
3095		struct ctl_port *port;
3096		struct ctl_frontend *fe;
3097
3098		mtx_lock(&softc->ctl_lock);
3099		printf("CTL Persistent Reservation information start:\n");
3100		for (i = 0; i < CTL_MAX_LUNS; i++) {
3101			struct ctl_lun *lun;
3102
3103			lun = softc->ctl_luns[i];
3104
3105			if ((lun == NULL)
3106			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
3107				continue;
3108
3109			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
3110				if (lun->pr_keys[j] == NULL)
3111					continue;
3112				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
3113					if (lun->pr_keys[j][k] == 0)
3114						continue;
3115					printf("  LUN %d port %d iid %d key "
3116					       "%#jx\n", i, j, k,
3117					       (uintmax_t)lun->pr_keys[j][k]);
3118				}
3119			}
3120		}
3121		printf("CTL Persistent Reservation information end\n");
3122		printf("CTL Ports:\n");
3123		STAILQ_FOREACH(port, &softc->port_list, links) {
3124			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3125			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3126			       port->frontend->name, port->port_type,
3127			       port->physical_port, port->virtual_port,
3128			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3129			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3130				if (port->wwpn_iid[j].in_use == 0 &&
3131				    port->wwpn_iid[j].wwpn == 0 &&
3132				    port->wwpn_iid[j].name == NULL)
3133					continue;
3134
3135				printf("    iid %u use %d WWPN %#jx '%s'\n",
3136				    j, port->wwpn_iid[j].in_use,
3137				    (uintmax_t)port->wwpn_iid[j].wwpn,
3138				    port->wwpn_iid[j].name);
3139			}
3140		}
3141		printf("CTL Port information end\n");
3142		mtx_unlock(&softc->ctl_lock);
3143		/*
3144		 * XXX KDM calling this without a lock.  We'd likely want
3145		 * to drop the lock before calling the frontend's dump
3146		 * routine anyway.
3147		 */
3148		printf("CTL Frontends:\n");
3149		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3150			printf("  Frontend '%s'\n", fe->name);
3151			if (fe->fe_dump != NULL)
3152				fe->fe_dump();
3153		}
3154		printf("CTL Frontend information end\n");
3155		break;
3156	}
3157	case CTL_LUN_REQ: {
3158		struct ctl_lun_req *lun_req;
3159		struct ctl_backend_driver *backend;
3160
3161		lun_req = (struct ctl_lun_req *)addr;
3162
3163		backend = ctl_backend_find(lun_req->backend);
3164		if (backend == NULL) {
3165			lun_req->status = CTL_LUN_ERROR;
3166			snprintf(lun_req->error_str,
3167				 sizeof(lun_req->error_str),
3168				 "Backend \"%s\" not found.",
3169				 lun_req->backend);
3170			break;
3171		}
3172		if (lun_req->num_be_args > 0) {
3173			lun_req->kern_be_args = ctl_copyin_args(
3174				lun_req->num_be_args,
3175				lun_req->be_args,
3176				lun_req->error_str,
3177				sizeof(lun_req->error_str));
3178			if (lun_req->kern_be_args == NULL) {
3179				lun_req->status = CTL_LUN_ERROR;
3180				break;
3181			}
3182		}
3183
3184		retval = backend->ioctl(dev, cmd, addr, flag, td);
3185
3186		if (lun_req->num_be_args > 0) {
3187			ctl_copyout_args(lun_req->num_be_args,
3188				      lun_req->kern_be_args);
3189			ctl_free_args(lun_req->num_be_args,
3190				      lun_req->kern_be_args);
3191		}
3192		break;
3193	}
3194	case CTL_LUN_LIST: {
3195		struct sbuf *sb;
3196		struct ctl_lun *lun;
3197		struct ctl_lun_list *list;
3198		struct ctl_option *opt;
3199
3200		list = (struct ctl_lun_list *)addr;
3201
3202		/*
3203		 * Allocate a fixed length sbuf here, based on the length
3204		 * of the user's buffer.  We could allocate an auto-extending
3205		 * buffer, and then tell the user how much larger our
3206		 * amount of data is than his buffer, but that presents
3207		 * some problems:
3208		 *
3209		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3210		 *     we can't hold a lock while calling them with an
3211		 *     auto-extending buffer.
3212 		 *
3213		 * 2.  There is not currently a LUN reference counting
3214		 *     mechanism, outside of outstanding transactions on
3215		 *     the LUN's OOA queue.  So a LUN could go away on us
3216		 *     while we're getting the LUN number, backend-specific
3217		 *     information, etc.  Thus, given the way things
3218		 *     currently work, we need to hold the CTL lock while
3219		 *     grabbing LUN information.
3220		 *
3221		 * So, from the user's standpoint, the best thing to do is
3222		 * allocate what he thinks is a reasonable buffer length,
3223		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3224		 * double the buffer length and try again.  (And repeat
3225		 * that until he succeeds.)
3226		 */
3227		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3228		if (sb == NULL) {
3229			list->status = CTL_LUN_LIST_ERROR;
3230			snprintf(list->error_str, sizeof(list->error_str),
3231				 "Unable to allocate %d bytes for LUN list",
3232				 list->alloc_len);
3233			break;
3234		}
3235
3236		sbuf_printf(sb, "<ctllunlist>\n");
3237
3238		mtx_lock(&softc->ctl_lock);
3239		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3240			mtx_lock(&lun->lun_lock);
3241			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3242					     (uintmax_t)lun->lun);
3243
3244			/*
3245			 * Bail out as soon as we see that we've overfilled
3246			 * the buffer.
3247			 */
3248			if (retval != 0)
3249				break;
3250
3251			retval = sbuf_printf(sb, "\t<backend_type>%s"
3252					     "</backend_type>\n",
3253					     (lun->backend == NULL) ?  "none" :
3254					     lun->backend->name);
3255
3256			if (retval != 0)
3257				break;
3258
3259			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3260					     lun->be_lun->lun_type);
3261
3262			if (retval != 0)
3263				break;
3264
3265			if (lun->backend == NULL) {
3266				retval = sbuf_printf(sb, "</lun>\n");
3267				if (retval != 0)
3268					break;
3269				continue;
3270			}
3271
3272			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3273					     (lun->be_lun->maxlba > 0) ?
3274					     lun->be_lun->maxlba + 1 : 0);
3275
3276			if (retval != 0)
3277				break;
3278
3279			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3280					     lun->be_lun->blocksize);
3281
3282			if (retval != 0)
3283				break;
3284
3285			retval = sbuf_printf(sb, "\t<serial_number>");
3286
3287			if (retval != 0)
3288				break;
3289
3290			retval = ctl_sbuf_printf_esc(sb,
3291			    lun->be_lun->serial_num,
3292			    sizeof(lun->be_lun->serial_num));
3293
3294			if (retval != 0)
3295				break;
3296
3297			retval = sbuf_printf(sb, "</serial_number>\n");
3298
3299			if (retval != 0)
3300				break;
3301
3302			retval = sbuf_printf(sb, "\t<device_id>");
3303
3304			if (retval != 0)
3305				break;
3306
3307			retval = ctl_sbuf_printf_esc(sb,
3308			    lun->be_lun->device_id,
3309			    sizeof(lun->be_lun->device_id));
3310
3311			if (retval != 0)
3312				break;
3313
3314			retval = sbuf_printf(sb, "</device_id>\n");
3315
3316			if (retval != 0)
3317				break;
3318
3319			if (lun->backend->lun_info != NULL) {
3320				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3321				if (retval != 0)
3322					break;
3323			}
3324			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3325				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3326				    opt->name, opt->value, opt->name);
3327				if (retval != 0)
3328					break;
3329			}
3330
3331			retval = sbuf_printf(sb, "</lun>\n");
3332
3333			if (retval != 0)
3334				break;
3335			mtx_unlock(&lun->lun_lock);
3336		}
3337		if (lun != NULL)
3338			mtx_unlock(&lun->lun_lock);
3339		mtx_unlock(&softc->ctl_lock);
3340
3341		if ((retval != 0)
3342		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3343			retval = 0;
3344			sbuf_delete(sb);
3345			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3346			snprintf(list->error_str, sizeof(list->error_str),
3347				 "Out of space, %d bytes is too small",
3348				 list->alloc_len);
3349			break;
3350		}
3351
3352		sbuf_finish(sb);
3353
3354		retval = copyout(sbuf_data(sb), list->lun_xml,
3355				 sbuf_len(sb) + 1);
3356
3357		list->fill_len = sbuf_len(sb) + 1;
3358		list->status = CTL_LUN_LIST_OK;
3359		sbuf_delete(sb);
3360		break;
3361	}
3362	case CTL_ISCSI: {
3363		struct ctl_iscsi *ci;
3364		struct ctl_frontend *fe;
3365
3366		ci = (struct ctl_iscsi *)addr;
3367
3368		fe = ctl_frontend_find("iscsi");
3369		if (fe == NULL) {
3370			ci->status = CTL_ISCSI_ERROR;
3371			snprintf(ci->error_str, sizeof(ci->error_str),
3372			    "Frontend \"iscsi\" not found.");
3373			break;
3374		}
3375
3376		retval = fe->ioctl(dev, cmd, addr, flag, td);
3377		break;
3378	}
3379	case CTL_PORT_REQ: {
3380		struct ctl_req *req;
3381		struct ctl_frontend *fe;
3382
3383		req = (struct ctl_req *)addr;
3384
3385		fe = ctl_frontend_find(req->driver);
3386		if (fe == NULL) {
3387			req->status = CTL_LUN_ERROR;
3388			snprintf(req->error_str, sizeof(req->error_str),
3389			    "Frontend \"%s\" not found.", req->driver);
3390			break;
3391		}
3392		if (req->num_args > 0) {
3393			req->kern_args = ctl_copyin_args(req->num_args,
3394			    req->args, req->error_str, sizeof(req->error_str));
3395			if (req->kern_args == NULL) {
3396				req->status = CTL_LUN_ERROR;
3397				break;
3398			}
3399		}
3400
3401		retval = fe->ioctl(dev, cmd, addr, flag, td);
3402
3403		if (req->num_args > 0) {
3404			ctl_copyout_args(req->num_args, req->kern_args);
3405			ctl_free_args(req->num_args, req->kern_args);
3406		}
3407		break;
3408	}
3409	case CTL_PORT_LIST: {
3410		struct sbuf *sb;
3411		struct ctl_port *port;
3412		struct ctl_lun_list *list;
3413		struct ctl_option *opt;
3414		int j;
3415
3416		list = (struct ctl_lun_list *)addr;
3417
3418		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3419		if (sb == NULL) {
3420			list->status = CTL_LUN_LIST_ERROR;
3421			snprintf(list->error_str, sizeof(list->error_str),
3422				 "Unable to allocate %d bytes for LUN list",
3423				 list->alloc_len);
3424			break;
3425		}
3426
3427		sbuf_printf(sb, "<ctlportlist>\n");
3428
3429		mtx_lock(&softc->ctl_lock);
3430		STAILQ_FOREACH(port, &softc->port_list, links) {
3431			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3432					     (uintmax_t)port->targ_port);
3433
3434			/*
3435			 * Bail out as soon as we see that we've overfilled
3436			 * the buffer.
3437			 */
3438			if (retval != 0)
3439				break;
3440
3441			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3442			    "</frontend_type>\n", port->frontend->name);
3443			if (retval != 0)
3444				break;
3445
3446			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3447					     port->port_type);
3448			if (retval != 0)
3449				break;
3450
3451			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3452			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3453			if (retval != 0)
3454				break;
3455
3456			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3457			    port->port_name);
3458			if (retval != 0)
3459				break;
3460
3461			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3462			    port->physical_port);
3463			if (retval != 0)
3464				break;
3465
3466			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3467			    port->virtual_port);
3468			if (retval != 0)
3469				break;
3470
3471			if (port->target_devid != NULL) {
3472				sbuf_printf(sb, "\t<target>");
3473				ctl_id_sbuf(port->target_devid, sb);
3474				sbuf_printf(sb, "</target>\n");
3475			}
3476
3477			if (port->port_devid != NULL) {
3478				sbuf_printf(sb, "\t<port>");
3479				ctl_id_sbuf(port->port_devid, sb);
3480				sbuf_printf(sb, "</port>\n");
3481			}
3482
3483			if (port->port_info != NULL) {
3484				retval = port->port_info(port->onoff_arg, sb);
3485				if (retval != 0)
3486					break;
3487			}
3488			STAILQ_FOREACH(opt, &port->options, links) {
3489				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3490				    opt->name, opt->value, opt->name);
3491				if (retval != 0)
3492					break;
3493			}
3494
3495			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3496				if (port->wwpn_iid[j].in_use == 0 ||
3497				    (port->wwpn_iid[j].wwpn == 0 &&
3498				     port->wwpn_iid[j].name == NULL))
3499					continue;
3500
3501				if (port->wwpn_iid[j].name != NULL)
3502					retval = sbuf_printf(sb,
3503					    "\t<initiator id=\"%u\">%s</initiator>\n",
3504					    j, port->wwpn_iid[j].name);
3505				else
3506					retval = sbuf_printf(sb,
3507					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3508					    j, port->wwpn_iid[j].wwpn);
3509				if (retval != 0)
3510					break;
3511			}
3512			if (retval != 0)
3513				break;
3514
3515			retval = sbuf_printf(sb, "</targ_port>\n");
3516			if (retval != 0)
3517				break;
3518		}
3519		mtx_unlock(&softc->ctl_lock);
3520
3521		if ((retval != 0)
3522		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3523			retval = 0;
3524			sbuf_delete(sb);
3525			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3526			snprintf(list->error_str, sizeof(list->error_str),
3527				 "Out of space, %d bytes is too small",
3528				 list->alloc_len);
3529			break;
3530		}
3531
3532		sbuf_finish(sb);
3533
3534		retval = copyout(sbuf_data(sb), list->lun_xml,
3535				 sbuf_len(sb) + 1);
3536
3537		list->fill_len = sbuf_len(sb) + 1;
3538		list->status = CTL_LUN_LIST_OK;
3539		sbuf_delete(sb);
3540		break;
3541	}
3542	default: {
3543		/* XXX KDM should we fix this? */
3544#if 0
3545		struct ctl_backend_driver *backend;
3546		unsigned int type;
3547		int found;
3548
3549		found = 0;
3550
3551		/*
3552		 * We encode the backend type as the ioctl type for backend
3553		 * ioctls.  So parse it out here, and then search for a
3554		 * backend of this type.
3555		 */
3556		type = _IOC_TYPE(cmd);
3557
3558		STAILQ_FOREACH(backend, &softc->be_list, links) {
3559			if (backend->type == type) {
3560				found = 1;
3561				break;
3562			}
3563		}
3564		if (found == 0) {
3565			printf("ctl: unknown ioctl command %#lx or backend "
3566			       "%d\n", cmd, type);
3567			retval = EINVAL;
3568			break;
3569		}
3570		retval = backend->ioctl(dev, cmd, addr, flag, td);
3571#endif
3572		retval = ENOTTY;
3573		break;
3574	}
3575	}
3576	return (retval);
3577}
3578
3579uint32_t
3580ctl_get_initindex(struct ctl_nexus *nexus)
3581{
3582	if (nexus->targ_port < CTL_MAX_PORTS)
3583		return (nexus->initid.id +
3584			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3585	else
3586		return (nexus->initid.id +
3587		       ((nexus->targ_port - CTL_MAX_PORTS) *
3588			CTL_MAX_INIT_PER_PORT));
3589}
3590
3591uint32_t
3592ctl_get_resindex(struct ctl_nexus *nexus)
3593{
3594	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3595}
3596
3597uint32_t
3598ctl_port_idx(int port_num)
3599{
3600	if (port_num < CTL_MAX_PORTS)
3601		return(port_num);
3602	else
3603		return(port_num - CTL_MAX_PORTS);
3604}
3605
3606static uint32_t
3607ctl_map_lun(int port_num, uint32_t lun_id)
3608{
3609	struct ctl_port *port;
3610
3611	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3612	if (port == NULL)
3613		return (UINT32_MAX);
3614	if (port->lun_map == NULL)
3615		return (lun_id);
3616	return (port->lun_map(port->targ_lun_arg, lun_id));
3617}
3618
3619static uint32_t
3620ctl_map_lun_back(int port_num, uint32_t lun_id)
3621{
3622	struct ctl_port *port;
3623	uint32_t i;
3624
3625	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3626	if (port->lun_map == NULL)
3627		return (lun_id);
3628	for (i = 0; i < CTL_MAX_LUNS; i++) {
3629		if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3630			return (i);
3631	}
3632	return (UINT32_MAX);
3633}
3634
3635/*
3636 * Note:  This only works for bitmask sizes that are at least 32 bits, and
3637 * that are a power of 2.
3638 */
3639int
3640ctl_ffz(uint32_t *mask, uint32_t size)
3641{
3642	uint32_t num_chunks, num_pieces;
3643	int i, j;
3644
3645	num_chunks = (size >> 5);
3646	if (num_chunks == 0)
3647		num_chunks++;
3648	num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3649
3650	for (i = 0; i < num_chunks; i++) {
3651		for (j = 0; j < num_pieces; j++) {
3652			if ((mask[i] & (1 << j)) == 0)
3653				return ((i << 5) + j);
3654		}
3655	}
3656
3657	return (-1);
3658}
3659
3660int
3661ctl_set_mask(uint32_t *mask, uint32_t bit)
3662{
3663	uint32_t chunk, piece;
3664
3665	chunk = bit >> 5;
3666	piece = bit % (sizeof(uint32_t) * 8);
3667
3668	if ((mask[chunk] & (1 << piece)) != 0)
3669		return (-1);
3670	else
3671		mask[chunk] |= (1 << piece);
3672
3673	return (0);
3674}
3675
3676int
3677ctl_clear_mask(uint32_t *mask, uint32_t bit)
3678{
3679	uint32_t chunk, piece;
3680
3681	chunk = bit >> 5;
3682	piece = bit % (sizeof(uint32_t) * 8);
3683
3684	if ((mask[chunk] & (1 << piece)) == 0)
3685		return (-1);
3686	else
3687		mask[chunk] &= ~(1 << piece);
3688
3689	return (0);
3690}
3691
3692int
3693ctl_is_set(uint32_t *mask, uint32_t bit)
3694{
3695	uint32_t chunk, piece;
3696
3697	chunk = bit >> 5;
3698	piece = bit % (sizeof(uint32_t) * 8);
3699
3700	if ((mask[chunk] & (1 << piece)) == 0)
3701		return (0);
3702	else
3703		return (1);
3704}
3705
3706static uint64_t
3707ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3708{
3709	uint64_t *t;
3710
3711	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3712	if (t == NULL)
3713		return (0);
3714	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3715}
3716
3717static void
3718ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3719{
3720	uint64_t *t;
3721
3722	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3723	if (t == NULL)
3724		return;
3725	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3726}
3727
3728static void
3729ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3730{
3731	uint64_t *p;
3732	u_int i;
3733
3734	i = residx/CTL_MAX_INIT_PER_PORT;
3735	if (lun->pr_keys[i] != NULL)
3736		return;
3737	mtx_unlock(&lun->lun_lock);
3738	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3739	    M_WAITOK | M_ZERO);
3740	mtx_lock(&lun->lun_lock);
3741	if (lun->pr_keys[i] == NULL)
3742		lun->pr_keys[i] = p;
3743	else
3744		free(p, M_CTL);
3745}
3746
3747static void
3748ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3749{
3750	uint64_t *t;
3751
3752	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3753	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3754	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3755}
3756
3757/*
3758 * ctl_softc, pool_name, total_ctl_io are passed in.
3759 * npool is passed out.
3760 */
3761int
3762ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3763		uint32_t total_ctl_io, void **npool)
3764{
3765#ifdef IO_POOLS
3766	struct ctl_io_pool *pool;
3767
3768	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3769					    M_NOWAIT | M_ZERO);
3770	if (pool == NULL)
3771		return (ENOMEM);
3772
3773	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3774	pool->ctl_softc = ctl_softc;
3775	pool->zone = uma_zsecond_create(pool->name, NULL,
3776	    NULL, NULL, NULL, ctl_softc->io_zone);
3777	/* uma_prealloc(pool->zone, total_ctl_io); */
3778
3779	*npool = pool;
3780#else
3781	*npool = ctl_softc->io_zone;
3782#endif
3783	return (0);
3784}
3785
3786void
3787ctl_pool_free(struct ctl_io_pool *pool)
3788{
3789
3790	if (pool == NULL)
3791		return;
3792
3793#ifdef IO_POOLS
3794	uma_zdestroy(pool->zone);
3795	free(pool, M_CTL);
3796#endif
3797}
3798
3799union ctl_io *
3800ctl_alloc_io(void *pool_ref)
3801{
3802	union ctl_io *io;
3803#ifdef IO_POOLS
3804	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3805
3806	io = uma_zalloc(pool->zone, M_WAITOK);
3807#else
3808	io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3809#endif
3810	if (io != NULL)
3811		io->io_hdr.pool = pool_ref;
3812	return (io);
3813}
3814
3815union ctl_io *
3816ctl_alloc_io_nowait(void *pool_ref)
3817{
3818	union ctl_io *io;
3819#ifdef IO_POOLS
3820	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3821
3822	io = uma_zalloc(pool->zone, M_NOWAIT);
3823#else
3824	io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3825#endif
3826	if (io != NULL)
3827		io->io_hdr.pool = pool_ref;
3828	return (io);
3829}
3830
3831void
3832ctl_free_io(union ctl_io *io)
3833{
3834#ifdef IO_POOLS
3835	struct ctl_io_pool *pool;
3836#endif
3837
3838	if (io == NULL)
3839		return;
3840
3841#ifdef IO_POOLS
3842	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3843	uma_zfree(pool->zone, io);
3844#else
3845	uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3846#endif
3847}
3848
3849void
3850ctl_zero_io(union ctl_io *io)
3851{
3852	void *pool_ref;
3853
3854	if (io == NULL)
3855		return;
3856
3857	/*
3858	 * May need to preserve linked list pointers at some point too.
3859	 */
3860	pool_ref = io->io_hdr.pool;
3861	memset(io, 0, sizeof(*io));
3862	io->io_hdr.pool = pool_ref;
3863}
3864
3865/*
3866 * This routine is currently used for internal copies of ctl_ios that need
3867 * to persist for some reason after we've already returned status to the
3868 * FETD.  (Thus the flag set.)
3869 *
3870 * XXX XXX
3871 * Note that this makes a blind copy of all fields in the ctl_io, except
3872 * for the pool reference.  This includes any memory that has been
3873 * allocated!  That memory will no longer be valid after done has been
3874 * called, so this would be VERY DANGEROUS for command that actually does
3875 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3876 * start and stop commands, which don't transfer any data, so this is not a
3877 * problem.  If it is used for anything else, the caller would also need to
3878 * allocate data buffer space and this routine would need to be modified to
3879 * copy the data buffer(s) as well.
3880 */
3881void
3882ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3883{
3884	void *pool_ref;
3885
3886	if ((src == NULL)
3887	 || (dest == NULL))
3888		return;
3889
3890	/*
3891	 * May need to preserve linked list pointers at some point too.
3892	 */
3893	pool_ref = dest->io_hdr.pool;
3894
3895	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3896
3897	dest->io_hdr.pool = pool_ref;
3898	/*
3899	 * We need to know that this is an internal copy, and doesn't need
3900	 * to get passed back to the FETD that allocated it.
3901	 */
3902	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3903}
3904
3905int
3906ctl_expand_number(const char *buf, uint64_t *num)
3907{
3908	char *endptr;
3909	uint64_t number;
3910	unsigned shift;
3911
3912	number = strtoq(buf, &endptr, 0);
3913
3914	switch (tolower((unsigned char)*endptr)) {
3915	case 'e':
3916		shift = 60;
3917		break;
3918	case 'p':
3919		shift = 50;
3920		break;
3921	case 't':
3922		shift = 40;
3923		break;
3924	case 'g':
3925		shift = 30;
3926		break;
3927	case 'm':
3928		shift = 20;
3929		break;
3930	case 'k':
3931		shift = 10;
3932		break;
3933	case 'b':
3934	case '\0': /* No unit. */
3935		*num = number;
3936		return (0);
3937	default:
3938		/* Unrecognized unit. */
3939		return (-1);
3940	}
3941
3942	if ((number << shift) >> shift != number) {
3943		/* Overflow */
3944		return (-1);
3945	}
3946	*num = number << shift;
3947	return (0);
3948}
3949
3950
3951/*
3952 * This routine could be used in the future to load default and/or saved
3953 * mode page parameters for a particuar lun.
3954 */
3955static int
3956ctl_init_page_index(struct ctl_lun *lun)
3957{
3958	int i;
3959	struct ctl_page_index *page_index;
3960	const char *value;
3961	uint64_t ival;
3962
3963	memcpy(&lun->mode_pages.index, page_index_template,
3964	       sizeof(page_index_template));
3965
3966	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3967
3968		page_index = &lun->mode_pages.index[i];
3969		/*
3970		 * If this is a disk-only mode page, there's no point in
3971		 * setting it up.  For some pages, we have to have some
3972		 * basic information about the disk in order to calculate the
3973		 * mode page data.
3974		 */
3975		if ((lun->be_lun->lun_type != T_DIRECT)
3976		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3977			continue;
3978
3979		switch (page_index->page_code & SMPH_PC_MASK) {
3980		case SMS_RW_ERROR_RECOVERY_PAGE: {
3981			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3982				panic("subpage is incorrect!");
3983			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3984			       &rw_er_page_default,
3985			       sizeof(rw_er_page_default));
3986			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3987			       &rw_er_page_changeable,
3988			       sizeof(rw_er_page_changeable));
3989			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3990			       &rw_er_page_default,
3991			       sizeof(rw_er_page_default));
3992			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3993			       &rw_er_page_default,
3994			       sizeof(rw_er_page_default));
3995			page_index->page_data =
3996				(uint8_t *)lun->mode_pages.rw_er_page;
3997			break;
3998		}
3999		case SMS_FORMAT_DEVICE_PAGE: {
4000			struct scsi_format_page *format_page;
4001
4002			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4003				panic("subpage is incorrect!");
4004
4005			/*
4006			 * Sectors per track are set above.  Bytes per
4007			 * sector need to be set here on a per-LUN basis.
4008			 */
4009			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4010			       &format_page_default,
4011			       sizeof(format_page_default));
4012			memcpy(&lun->mode_pages.format_page[
4013			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4014			       sizeof(format_page_changeable));
4015			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4016			       &format_page_default,
4017			       sizeof(format_page_default));
4018			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4019			       &format_page_default,
4020			       sizeof(format_page_default));
4021
4022			format_page = &lun->mode_pages.format_page[
4023				CTL_PAGE_CURRENT];
4024			scsi_ulto2b(lun->be_lun->blocksize,
4025				    format_page->bytes_per_sector);
4026
4027			format_page = &lun->mode_pages.format_page[
4028				CTL_PAGE_DEFAULT];
4029			scsi_ulto2b(lun->be_lun->blocksize,
4030				    format_page->bytes_per_sector);
4031
4032			format_page = &lun->mode_pages.format_page[
4033				CTL_PAGE_SAVED];
4034			scsi_ulto2b(lun->be_lun->blocksize,
4035				    format_page->bytes_per_sector);
4036
4037			page_index->page_data =
4038				(uint8_t *)lun->mode_pages.format_page;
4039			break;
4040		}
4041		case SMS_RIGID_DISK_PAGE: {
4042			struct scsi_rigid_disk_page *rigid_disk_page;
4043			uint32_t sectors_per_cylinder;
4044			uint64_t cylinders;
4045#ifndef	__XSCALE__
4046			int shift;
4047#endif /* !__XSCALE__ */
4048
4049			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4050				panic("invalid subpage value %d",
4051				      page_index->subpage);
4052
4053			/*
4054			 * Rotation rate and sectors per track are set
4055			 * above.  We calculate the cylinders here based on
4056			 * capacity.  Due to the number of heads and
4057			 * sectors per track we're using, smaller arrays
4058			 * may turn out to have 0 cylinders.  Linux and
4059			 * FreeBSD don't pay attention to these mode pages
4060			 * to figure out capacity, but Solaris does.  It
4061			 * seems to deal with 0 cylinders just fine, and
4062			 * works out a fake geometry based on the capacity.
4063			 */
4064			memcpy(&lun->mode_pages.rigid_disk_page[
4065			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4066			       sizeof(rigid_disk_page_default));
4067			memcpy(&lun->mode_pages.rigid_disk_page[
4068			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4069			       sizeof(rigid_disk_page_changeable));
4070
4071			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4072				CTL_DEFAULT_HEADS;
4073
4074			/*
4075			 * The divide method here will be more accurate,
4076			 * probably, but results in floating point being
4077			 * used in the kernel on i386 (__udivdi3()).  On the
4078			 * XScale, though, __udivdi3() is implemented in
4079			 * software.
4080			 *
4081			 * The shift method for cylinder calculation is
4082			 * accurate if sectors_per_cylinder is a power of
4083			 * 2.  Otherwise it might be slightly off -- you
4084			 * might have a bit of a truncation problem.
4085			 */
4086#ifdef	__XSCALE__
4087			cylinders = (lun->be_lun->maxlba + 1) /
4088				sectors_per_cylinder;
4089#else
4090			for (shift = 31; shift > 0; shift--) {
4091				if (sectors_per_cylinder & (1 << shift))
4092					break;
4093			}
4094			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4095#endif
4096
4097			/*
4098			 * We've basically got 3 bytes, or 24 bits for the
4099			 * cylinder size in the mode page.  If we're over,
4100			 * just round down to 2^24.
4101			 */
4102			if (cylinders > 0xffffff)
4103				cylinders = 0xffffff;
4104
4105			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4106				CTL_PAGE_DEFAULT];
4107			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4108
4109			if ((value = ctl_get_opt(&lun->be_lun->options,
4110			    "rpm")) != NULL) {
4111				scsi_ulto2b(strtol(value, NULL, 0),
4112				     rigid_disk_page->rotation_rate);
4113			}
4114
4115			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4116			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4117			       sizeof(rigid_disk_page_default));
4118			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4119			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4120			       sizeof(rigid_disk_page_default));
4121
4122			page_index->page_data =
4123				(uint8_t *)lun->mode_pages.rigid_disk_page;
4124			break;
4125		}
4126		case SMS_CACHING_PAGE: {
4127			struct scsi_caching_page *caching_page;
4128
4129			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4130				panic("invalid subpage value %d",
4131				      page_index->subpage);
4132			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4133			       &caching_page_default,
4134			       sizeof(caching_page_default));
4135			memcpy(&lun->mode_pages.caching_page[
4136			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4137			       sizeof(caching_page_changeable));
4138			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4139			       &caching_page_default,
4140			       sizeof(caching_page_default));
4141			caching_page = &lun->mode_pages.caching_page[
4142			    CTL_PAGE_SAVED];
4143			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4144			if (value != NULL && strcmp(value, "off") == 0)
4145				caching_page->flags1 &= ~SCP_WCE;
4146			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4147			if (value != NULL && strcmp(value, "off") == 0)
4148				caching_page->flags1 |= SCP_RCD;
4149			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4150			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4151			       sizeof(caching_page_default));
4152			page_index->page_data =
4153				(uint8_t *)lun->mode_pages.caching_page;
4154			break;
4155		}
4156		case SMS_CONTROL_MODE_PAGE: {
4157			struct scsi_control_page *control_page;
4158
4159			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4160				panic("invalid subpage value %d",
4161				      page_index->subpage);
4162
4163			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4164			       &control_page_default,
4165			       sizeof(control_page_default));
4166			memcpy(&lun->mode_pages.control_page[
4167			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4168			       sizeof(control_page_changeable));
4169			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4170			       &control_page_default,
4171			       sizeof(control_page_default));
4172			control_page = &lun->mode_pages.control_page[
4173			    CTL_PAGE_SAVED];
4174			value = ctl_get_opt(&lun->be_lun->options, "reordering");
4175			if (value != NULL && strcmp(value, "unrestricted") == 0) {
4176				control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4177				control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4178			}
4179			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4180			       &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4181			       sizeof(control_page_default));
4182			page_index->page_data =
4183				(uint8_t *)lun->mode_pages.control_page;
4184			break;
4185
4186		}
4187		case SMS_INFO_EXCEPTIONS_PAGE: {
4188			switch (page_index->subpage) {
4189			case SMS_SUBPAGE_PAGE_0:
4190				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4191				       &ie_page_default,
4192				       sizeof(ie_page_default));
4193				memcpy(&lun->mode_pages.ie_page[
4194				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4195				       sizeof(ie_page_changeable));
4196				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4197				       &ie_page_default,
4198				       sizeof(ie_page_default));
4199				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4200				       &ie_page_default,
4201				       sizeof(ie_page_default));
4202				page_index->page_data =
4203					(uint8_t *)lun->mode_pages.ie_page;
4204				break;
4205			case 0x02: {
4206				struct ctl_logical_block_provisioning_page *page;
4207
4208				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4209				       &lbp_page_default,
4210				       sizeof(lbp_page_default));
4211				memcpy(&lun->mode_pages.lbp_page[
4212				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4213				       sizeof(lbp_page_changeable));
4214				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4215				       &lbp_page_default,
4216				       sizeof(lbp_page_default));
4217				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4218				value = ctl_get_opt(&lun->be_lun->options,
4219				    "avail-threshold");
4220				if (value != NULL &&
4221				    ctl_expand_number(value, &ival) == 0) {
4222					page->descr[0].flags |= SLBPPD_ENABLED |
4223					    SLBPPD_ARMING_DEC;
4224					if (lun->be_lun->blocksize)
4225						ival /= lun->be_lun->blocksize;
4226					else
4227						ival /= 512;
4228					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4229					    page->descr[0].count);
4230				}
4231				value = ctl_get_opt(&lun->be_lun->options,
4232				    "used-threshold");
4233				if (value != NULL &&
4234				    ctl_expand_number(value, &ival) == 0) {
4235					page->descr[1].flags |= SLBPPD_ENABLED |
4236					    SLBPPD_ARMING_INC;
4237					if (lun->be_lun->blocksize)
4238						ival /= lun->be_lun->blocksize;
4239					else
4240						ival /= 512;
4241					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4242					    page->descr[1].count);
4243				}
4244				value = ctl_get_opt(&lun->be_lun->options,
4245				    "pool-avail-threshold");
4246				if (value != NULL &&
4247				    ctl_expand_number(value, &ival) == 0) {
4248					page->descr[2].flags |= SLBPPD_ENABLED |
4249					    SLBPPD_ARMING_DEC;
4250					if (lun->be_lun->blocksize)
4251						ival /= lun->be_lun->blocksize;
4252					else
4253						ival /= 512;
4254					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4255					    page->descr[2].count);
4256				}
4257				value = ctl_get_opt(&lun->be_lun->options,
4258				    "pool-used-threshold");
4259				if (value != NULL &&
4260				    ctl_expand_number(value, &ival) == 0) {
4261					page->descr[3].flags |= SLBPPD_ENABLED |
4262					    SLBPPD_ARMING_INC;
4263					if (lun->be_lun->blocksize)
4264						ival /= lun->be_lun->blocksize;
4265					else
4266						ival /= 512;
4267					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4268					    page->descr[3].count);
4269				}
4270				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4271				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4272				       sizeof(lbp_page_default));
4273				page_index->page_data =
4274					(uint8_t *)lun->mode_pages.lbp_page;
4275			}}
4276			break;
4277		}
4278		case SMS_VENDOR_SPECIFIC_PAGE:{
4279			switch (page_index->subpage) {
4280			case DBGCNF_SUBPAGE_CODE: {
4281				struct copan_debugconf_subpage *current_page,
4282							       *saved_page;
4283
4284				memcpy(&lun->mode_pages.debugconf_subpage[
4285				       CTL_PAGE_CURRENT],
4286				       &debugconf_page_default,
4287				       sizeof(debugconf_page_default));
4288				memcpy(&lun->mode_pages.debugconf_subpage[
4289				       CTL_PAGE_CHANGEABLE],
4290				       &debugconf_page_changeable,
4291				       sizeof(debugconf_page_changeable));
4292				memcpy(&lun->mode_pages.debugconf_subpage[
4293				       CTL_PAGE_DEFAULT],
4294				       &debugconf_page_default,
4295				       sizeof(debugconf_page_default));
4296				memcpy(&lun->mode_pages.debugconf_subpage[
4297				       CTL_PAGE_SAVED],
4298				       &debugconf_page_default,
4299				       sizeof(debugconf_page_default));
4300				page_index->page_data =
4301					(uint8_t *)lun->mode_pages.debugconf_subpage;
4302
4303				current_page = (struct copan_debugconf_subpage *)
4304					(page_index->page_data +
4305					 (page_index->page_len *
4306					  CTL_PAGE_CURRENT));
4307				saved_page = (struct copan_debugconf_subpage *)
4308					(page_index->page_data +
4309					 (page_index->page_len *
4310					  CTL_PAGE_SAVED));
4311				break;
4312			}
4313			default:
4314				panic("invalid subpage value %d",
4315				      page_index->subpage);
4316				break;
4317			}
4318   			break;
4319		}
4320		default:
4321			panic("invalid page value %d",
4322			      page_index->page_code & SMPH_PC_MASK);
4323			break;
4324    	}
4325	}
4326
4327	return (CTL_RETVAL_COMPLETE);
4328}
4329
4330static int
4331ctl_init_log_page_index(struct ctl_lun *lun)
4332{
4333	struct ctl_page_index *page_index;
4334	int i, j, k, prev;
4335
4336	memcpy(&lun->log_pages.index, log_page_index_template,
4337	       sizeof(log_page_index_template));
4338
4339	prev = -1;
4340	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4341
4342		page_index = &lun->log_pages.index[i];
4343		/*
4344		 * If this is a disk-only mode page, there's no point in
4345		 * setting it up.  For some pages, we have to have some
4346		 * basic information about the disk in order to calculate the
4347		 * mode page data.
4348		 */
4349		if ((lun->be_lun->lun_type != T_DIRECT)
4350		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4351			continue;
4352
4353		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4354		     lun->backend->lun_attr == NULL)
4355			continue;
4356
4357		if (page_index->page_code != prev) {
4358			lun->log_pages.pages_page[j] = page_index->page_code;
4359			prev = page_index->page_code;
4360			j++;
4361		}
4362		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4363		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4364		k++;
4365	}
4366	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4367	lun->log_pages.index[0].page_len = j;
4368	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4369	lun->log_pages.index[1].page_len = k * 2;
4370	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4371	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4372
4373	return (CTL_RETVAL_COMPLETE);
4374}
4375
4376static int
4377hex2bin(const char *str, uint8_t *buf, int buf_size)
4378{
4379	int i;
4380	u_char c;
4381
4382	memset(buf, 0, buf_size);
4383	while (isspace(str[0]))
4384		str++;
4385	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4386		str += 2;
4387	buf_size *= 2;
4388	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4389		c = str[i];
4390		if (isdigit(c))
4391			c -= '0';
4392		else if (isalpha(c))
4393			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4394		else
4395			break;
4396		if (c >= 16)
4397			break;
4398		if ((i & 1) == 0)
4399			buf[i / 2] |= (c << 4);
4400		else
4401			buf[i / 2] |= c;
4402	}
4403	return ((i + 1) / 2);
4404}
4405
4406/*
4407 * LUN allocation.
4408 *
4409 * Requirements:
4410 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4411 *   wants us to allocate the LUN and he can block.
4412 * - ctl_softc is always set
4413 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4414 *
4415 * Returns 0 for success, non-zero (errno) for failure.
4416 */
4417static int
4418ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4419	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4420{
4421	struct ctl_lun *nlun, *lun;
4422	struct ctl_port *port;
4423	struct scsi_vpd_id_descriptor *desc;
4424	struct scsi_vpd_id_t10 *t10id;
4425	const char *eui, *naa, *scsiname, *vendor, *value;
4426	int lun_number, i, lun_malloced;
4427	int devidlen, idlen1, idlen2 = 0, len;
4428
4429	if (be_lun == NULL)
4430		return (EINVAL);
4431
4432	/*
4433	 * We currently only support Direct Access or Processor LUN types.
4434	 */
4435	switch (be_lun->lun_type) {
4436	case T_DIRECT:
4437		break;
4438	case T_PROCESSOR:
4439		break;
4440	case T_SEQUENTIAL:
4441	case T_CHANGER:
4442	default:
4443		be_lun->lun_config_status(be_lun->be_lun,
4444					  CTL_LUN_CONFIG_FAILURE);
4445		break;
4446	}
4447	if (ctl_lun == NULL) {
4448		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4449		lun_malloced = 1;
4450	} else {
4451		lun_malloced = 0;
4452		lun = ctl_lun;
4453	}
4454
4455	memset(lun, 0, sizeof(*lun));
4456	if (lun_malloced)
4457		lun->flags = CTL_LUN_MALLOCED;
4458
4459	/* Generate LUN ID. */
4460	devidlen = max(CTL_DEVID_MIN_LEN,
4461	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4462	idlen1 = sizeof(*t10id) + devidlen;
4463	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4464	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4465	if (scsiname != NULL) {
4466		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4467		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4468	}
4469	eui = ctl_get_opt(&be_lun->options, "eui");
4470	if (eui != NULL) {
4471		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4472	}
4473	naa = ctl_get_opt(&be_lun->options, "naa");
4474	if (naa != NULL) {
4475		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4476	}
4477	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4478	    M_CTL, M_WAITOK | M_ZERO);
4479	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4480	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4481	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4482	desc->length = idlen1;
4483	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4484	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4485	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4486		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4487	} else {
4488		strncpy(t10id->vendor, vendor,
4489		    min(sizeof(t10id->vendor), strlen(vendor)));
4490	}
4491	strncpy((char *)t10id->vendor_spec_id,
4492	    (char *)be_lun->device_id, devidlen);
4493	if (scsiname != NULL) {
4494		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4495		    desc->length);
4496		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4497		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4498		    SVPD_ID_TYPE_SCSI_NAME;
4499		desc->length = idlen2;
4500		strlcpy(desc->identifier, scsiname, idlen2);
4501	}
4502	if (eui != NULL) {
4503		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4504		    desc->length);
4505		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4506		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4507		    SVPD_ID_TYPE_EUI64;
4508		desc->length = hex2bin(eui, desc->identifier, 16);
4509		desc->length = desc->length > 12 ? 16 :
4510		    (desc->length > 8 ? 12 : 8);
4511		len -= 16 - desc->length;
4512	}
4513	if (naa != NULL) {
4514		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4515		    desc->length);
4516		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4517		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4518		    SVPD_ID_TYPE_NAA;
4519		desc->length = hex2bin(naa, desc->identifier, 16);
4520		desc->length = desc->length > 8 ? 16 : 8;
4521		len -= 16 - desc->length;
4522	}
4523	lun->lun_devid->len = len;
4524
4525	mtx_lock(&ctl_softc->ctl_lock);
4526	/*
4527	 * See if the caller requested a particular LUN number.  If so, see
4528	 * if it is available.  Otherwise, allocate the first available LUN.
4529	 */
4530	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4531		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4532		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4533			mtx_unlock(&ctl_softc->ctl_lock);
4534			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4535				printf("ctl: requested LUN ID %d is higher "
4536				       "than CTL_MAX_LUNS - 1 (%d)\n",
4537				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4538			} else {
4539				/*
4540				 * XXX KDM return an error, or just assign
4541				 * another LUN ID in this case??
4542				 */
4543				printf("ctl: requested LUN ID %d is already "
4544				       "in use\n", be_lun->req_lun_id);
4545			}
4546			if (lun->flags & CTL_LUN_MALLOCED)
4547				free(lun, M_CTL);
4548			be_lun->lun_config_status(be_lun->be_lun,
4549						  CTL_LUN_CONFIG_FAILURE);
4550			return (ENOSPC);
4551		}
4552		lun_number = be_lun->req_lun_id;
4553	} else {
4554		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4555		if (lun_number == -1) {
4556			mtx_unlock(&ctl_softc->ctl_lock);
4557			printf("ctl: can't allocate LUN on target %ju, out of "
4558			       "LUNs\n", (uintmax_t)target_id.id);
4559			if (lun->flags & CTL_LUN_MALLOCED)
4560				free(lun, M_CTL);
4561			be_lun->lun_config_status(be_lun->be_lun,
4562						  CTL_LUN_CONFIG_FAILURE);
4563			return (ENOSPC);
4564		}
4565	}
4566	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4567
4568	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4569	lun->target = target_id;
4570	lun->lun = lun_number;
4571	lun->be_lun = be_lun;
4572	/*
4573	 * The processor LUN is always enabled.  Disk LUNs come on line
4574	 * disabled, and must be enabled by the backend.
4575	 */
4576	lun->flags |= CTL_LUN_DISABLED;
4577	lun->backend = be_lun->be;
4578	be_lun->ctl_lun = lun;
4579	be_lun->lun_id = lun_number;
4580	atomic_add_int(&be_lun->be->num_luns, 1);
4581	if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4582		lun->flags |= CTL_LUN_OFFLINE;
4583
4584	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4585		lun->flags |= CTL_LUN_STOPPED;
4586
4587	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4588		lun->flags |= CTL_LUN_INOPERABLE;
4589
4590	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4591		lun->flags |= CTL_LUN_PRIMARY_SC;
4592
4593	value = ctl_get_opt(&be_lun->options, "readonly");
4594	if (value != NULL && strcmp(value, "on") == 0)
4595		lun->flags |= CTL_LUN_READONLY;
4596
4597	lun->serseq = CTL_LUN_SERSEQ_OFF;
4598	if (be_lun->flags & CTL_LUN_FLAG_SERSEQ_READ)
4599		lun->serseq = CTL_LUN_SERSEQ_READ;
4600	value = ctl_get_opt(&be_lun->options, "serseq");
4601	if (value != NULL && strcmp(value, "on") == 0)
4602		lun->serseq = CTL_LUN_SERSEQ_ON;
4603	else if (value != NULL && strcmp(value, "read") == 0)
4604		lun->serseq = CTL_LUN_SERSEQ_READ;
4605	else if (value != NULL && strcmp(value, "off") == 0)
4606		lun->serseq = CTL_LUN_SERSEQ_OFF;
4607
4608	lun->ctl_softc = ctl_softc;
4609	TAILQ_INIT(&lun->ooa_queue);
4610	TAILQ_INIT(&lun->blocked_queue);
4611	STAILQ_INIT(&lun->error_list);
4612	ctl_tpc_lun_init(lun);
4613
4614	/*
4615	 * Initialize the mode and log page index.
4616	 */
4617	ctl_init_page_index(lun);
4618	ctl_init_log_page_index(lun);
4619
4620	/*
4621	 * Now, before we insert this lun on the lun list, set the lun
4622	 * inventory changed UA for all other luns.
4623	 */
4624	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4625		mtx_lock(&nlun->lun_lock);
4626		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4627		mtx_unlock(&nlun->lun_lock);
4628	}
4629
4630	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4631
4632	ctl_softc->ctl_luns[lun_number] = lun;
4633
4634	ctl_softc->num_luns++;
4635
4636	/* Setup statistics gathering */
4637	lun->stats.device_type = be_lun->lun_type;
4638	lun->stats.lun_number = lun_number;
4639	if (lun->stats.device_type == T_DIRECT)
4640		lun->stats.blocksize = be_lun->blocksize;
4641	else
4642		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4643	for (i = 0;i < CTL_MAX_PORTS;i++)
4644		lun->stats.ports[i].targ_port = i;
4645
4646	mtx_unlock(&ctl_softc->ctl_lock);
4647
4648	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4649
4650	/*
4651	 * Run through each registered FETD and bring it online if it isn't
4652	 * already.  Enable the target ID if it hasn't been enabled, and
4653	 * enable this particular LUN.
4654	 */
4655	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4656		int retval;
4657
4658		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4659		if (retval != 0) {
4660			printf("ctl_alloc_lun: FETD %s port %d returned error "
4661			       "%d for lun_enable on target %ju lun %d\n",
4662			       port->port_name, port->targ_port, retval,
4663			       (uintmax_t)target_id.id, lun_number);
4664		} else
4665			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4666	}
4667	return (0);
4668}
4669
4670/*
4671 * Delete a LUN.
4672 * Assumptions:
4673 * - LUN has already been marked invalid and any pending I/O has been taken
4674 *   care of.
4675 */
4676static int
4677ctl_free_lun(struct ctl_lun *lun)
4678{
4679	struct ctl_softc *softc;
4680#if 0
4681	struct ctl_port *port;
4682#endif
4683	struct ctl_lun *nlun;
4684	int i;
4685
4686	softc = lun->ctl_softc;
4687
4688	mtx_assert(&softc->ctl_lock, MA_OWNED);
4689
4690	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4691
4692	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4693
4694	softc->ctl_luns[lun->lun] = NULL;
4695
4696	if (!TAILQ_EMPTY(&lun->ooa_queue))
4697		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4698
4699	softc->num_luns--;
4700
4701	/*
4702	 * XXX KDM this scheme only works for a single target/multiple LUN
4703	 * setup.  It needs to be revamped for a multiple target scheme.
4704	 *
4705	 * XXX KDM this results in port->lun_disable() getting called twice,
4706	 * once when ctl_disable_lun() is called, and a second time here.
4707	 * We really need to re-think the LUN disable semantics.  There
4708	 * should probably be several steps/levels to LUN removal:
4709	 *  - disable
4710	 *  - invalidate
4711	 *  - free
4712 	 *
4713	 * Right now we only have a disable method when communicating to
4714	 * the front end ports, at least for individual LUNs.
4715	 */
4716#if 0
4717	STAILQ_FOREACH(port, &softc->port_list, links) {
4718		int retval;
4719
4720		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4721					 lun->lun);
4722		if (retval != 0) {
4723			printf("ctl_free_lun: FETD %s port %d returned error "
4724			       "%d for lun_disable on target %ju lun %jd\n",
4725			       port->port_name, port->targ_port, retval,
4726			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4727		}
4728
4729		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4730			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4731
4732			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4733			if (retval != 0) {
4734				printf("ctl_free_lun: FETD %s port %d "
4735				       "returned error %d for targ_disable on "
4736				       "target %ju\n", port->port_name,
4737				       port->targ_port, retval,
4738				       (uintmax_t)lun->target.id);
4739			} else
4740				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4741
4742			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4743				continue;
4744
4745#if 0
4746			port->port_offline(port->onoff_arg);
4747			port->status &= ~CTL_PORT_STATUS_ONLINE;
4748#endif
4749		}
4750	}
4751#endif
4752
4753	/*
4754	 * Tell the backend to free resources, if this LUN has a backend.
4755	 */
4756	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4757	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4758
4759	ctl_tpc_lun_shutdown(lun);
4760	mtx_destroy(&lun->lun_lock);
4761	free(lun->lun_devid, M_CTL);
4762	for (i = 0; i < CTL_MAX_PORTS; i++)
4763		free(lun->pending_ua[i], M_CTL);
4764	for (i = 0; i < 2 * CTL_MAX_PORTS; i++)
4765		free(lun->pr_keys[i], M_CTL);
4766	free(lun->write_buffer, M_CTL);
4767	if (lun->flags & CTL_LUN_MALLOCED)
4768		free(lun, M_CTL);
4769
4770	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4771		mtx_lock(&nlun->lun_lock);
4772		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4773		mtx_unlock(&nlun->lun_lock);
4774	}
4775
4776	return (0);
4777}
4778
4779static void
4780ctl_create_lun(struct ctl_be_lun *be_lun)
4781{
4782	struct ctl_softc *ctl_softc;
4783
4784	ctl_softc = control_softc;
4785
4786	/*
4787	 * ctl_alloc_lun() should handle all potential failure cases.
4788	 */
4789	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4790}
4791
4792int
4793ctl_add_lun(struct ctl_be_lun *be_lun)
4794{
4795	struct ctl_softc *ctl_softc = control_softc;
4796
4797	mtx_lock(&ctl_softc->ctl_lock);
4798	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4799	mtx_unlock(&ctl_softc->ctl_lock);
4800	wakeup(&ctl_softc->pending_lun_queue);
4801
4802	return (0);
4803}
4804
4805int
4806ctl_enable_lun(struct ctl_be_lun *be_lun)
4807{
4808	struct ctl_softc *ctl_softc;
4809	struct ctl_port *port, *nport;
4810	struct ctl_lun *lun;
4811	int retval;
4812
4813	ctl_softc = control_softc;
4814
4815	lun = (struct ctl_lun *)be_lun->ctl_lun;
4816
4817	mtx_lock(&ctl_softc->ctl_lock);
4818	mtx_lock(&lun->lun_lock);
4819	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4820		/*
4821		 * eh?  Why did we get called if the LUN is already
4822		 * enabled?
4823		 */
4824		mtx_unlock(&lun->lun_lock);
4825		mtx_unlock(&ctl_softc->ctl_lock);
4826		return (0);
4827	}
4828	lun->flags &= ~CTL_LUN_DISABLED;
4829	mtx_unlock(&lun->lun_lock);
4830
4831	for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4832		nport = STAILQ_NEXT(port, links);
4833
4834		/*
4835		 * Drop the lock while we call the FETD's enable routine.
4836		 * This can lead to a callback into CTL (at least in the
4837		 * case of the internal initiator frontend.
4838		 */
4839		mtx_unlock(&ctl_softc->ctl_lock);
4840		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4841		mtx_lock(&ctl_softc->ctl_lock);
4842		if (retval != 0) {
4843			printf("%s: FETD %s port %d returned error "
4844			       "%d for lun_enable on target %ju lun %jd\n",
4845			       __func__, port->port_name, port->targ_port, retval,
4846			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4847		}
4848#if 0
4849		 else {
4850            /* NOTE:  TODO:  why does lun enable affect port status? */
4851			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4852		}
4853#endif
4854	}
4855
4856	mtx_unlock(&ctl_softc->ctl_lock);
4857
4858	return (0);
4859}
4860
4861int
4862ctl_disable_lun(struct ctl_be_lun *be_lun)
4863{
4864	struct ctl_softc *ctl_softc;
4865	struct ctl_port *port;
4866	struct ctl_lun *lun;
4867	int retval;
4868
4869	ctl_softc = control_softc;
4870
4871	lun = (struct ctl_lun *)be_lun->ctl_lun;
4872
4873	mtx_lock(&ctl_softc->ctl_lock);
4874	mtx_lock(&lun->lun_lock);
4875	if (lun->flags & CTL_LUN_DISABLED) {
4876		mtx_unlock(&lun->lun_lock);
4877		mtx_unlock(&ctl_softc->ctl_lock);
4878		return (0);
4879	}
4880	lun->flags |= CTL_LUN_DISABLED;
4881	mtx_unlock(&lun->lun_lock);
4882
4883	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4884		mtx_unlock(&ctl_softc->ctl_lock);
4885		/*
4886		 * Drop the lock before we call the frontend's disable
4887		 * routine, to avoid lock order reversals.
4888		 *
4889		 * XXX KDM what happens if the frontend list changes while
4890		 * we're traversing it?  It's unlikely, but should be handled.
4891		 */
4892		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4893					 lun->lun);
4894		mtx_lock(&ctl_softc->ctl_lock);
4895		if (retval != 0) {
4896			printf("ctl_alloc_lun: FETD %s port %d returned error "
4897			       "%d for lun_disable on target %ju lun %jd\n",
4898			       port->port_name, port->targ_port, retval,
4899			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4900		}
4901	}
4902
4903	mtx_unlock(&ctl_softc->ctl_lock);
4904
4905	return (0);
4906}
4907
4908int
4909ctl_start_lun(struct ctl_be_lun *be_lun)
4910{
4911	struct ctl_softc *ctl_softc;
4912	struct ctl_lun *lun;
4913
4914	ctl_softc = control_softc;
4915
4916	lun = (struct ctl_lun *)be_lun->ctl_lun;
4917
4918	mtx_lock(&lun->lun_lock);
4919	lun->flags &= ~CTL_LUN_STOPPED;
4920	mtx_unlock(&lun->lun_lock);
4921
4922	return (0);
4923}
4924
4925int
4926ctl_stop_lun(struct ctl_be_lun *be_lun)
4927{
4928	struct ctl_softc *ctl_softc;
4929	struct ctl_lun *lun;
4930
4931	ctl_softc = control_softc;
4932
4933	lun = (struct ctl_lun *)be_lun->ctl_lun;
4934
4935	mtx_lock(&lun->lun_lock);
4936	lun->flags |= CTL_LUN_STOPPED;
4937	mtx_unlock(&lun->lun_lock);
4938
4939	return (0);
4940}
4941
4942int
4943ctl_lun_offline(struct ctl_be_lun *be_lun)
4944{
4945	struct ctl_softc *ctl_softc;
4946	struct ctl_lun *lun;
4947
4948	ctl_softc = control_softc;
4949
4950	lun = (struct ctl_lun *)be_lun->ctl_lun;
4951
4952	mtx_lock(&lun->lun_lock);
4953	lun->flags |= CTL_LUN_OFFLINE;
4954	mtx_unlock(&lun->lun_lock);
4955
4956	return (0);
4957}
4958
4959int
4960ctl_lun_online(struct ctl_be_lun *be_lun)
4961{
4962	struct ctl_softc *ctl_softc;
4963	struct ctl_lun *lun;
4964
4965	ctl_softc = control_softc;
4966
4967	lun = (struct ctl_lun *)be_lun->ctl_lun;
4968
4969	mtx_lock(&lun->lun_lock);
4970	lun->flags &= ~CTL_LUN_OFFLINE;
4971	mtx_unlock(&lun->lun_lock);
4972
4973	return (0);
4974}
4975
4976int
4977ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4978{
4979	struct ctl_softc *ctl_softc;
4980	struct ctl_lun *lun;
4981
4982	ctl_softc = control_softc;
4983
4984	lun = (struct ctl_lun *)be_lun->ctl_lun;
4985
4986	mtx_lock(&lun->lun_lock);
4987
4988	/*
4989	 * The LUN needs to be disabled before it can be marked invalid.
4990	 */
4991	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4992		mtx_unlock(&lun->lun_lock);
4993		return (-1);
4994	}
4995	/*
4996	 * Mark the LUN invalid.
4997	 */
4998	lun->flags |= CTL_LUN_INVALID;
4999
5000	/*
5001	 * If there is nothing in the OOA queue, go ahead and free the LUN.
5002	 * If we have something in the OOA queue, we'll free it when the
5003	 * last I/O completes.
5004	 */
5005	if (TAILQ_EMPTY(&lun->ooa_queue)) {
5006		mtx_unlock(&lun->lun_lock);
5007		mtx_lock(&ctl_softc->ctl_lock);
5008		ctl_free_lun(lun);
5009		mtx_unlock(&ctl_softc->ctl_lock);
5010	} else
5011		mtx_unlock(&lun->lun_lock);
5012
5013	return (0);
5014}
5015
5016int
5017ctl_lun_inoperable(struct ctl_be_lun *be_lun)
5018{
5019	struct ctl_softc *ctl_softc;
5020	struct ctl_lun *lun;
5021
5022	ctl_softc = control_softc;
5023	lun = (struct ctl_lun *)be_lun->ctl_lun;
5024
5025	mtx_lock(&lun->lun_lock);
5026	lun->flags |= CTL_LUN_INOPERABLE;
5027	mtx_unlock(&lun->lun_lock);
5028
5029	return (0);
5030}
5031
5032int
5033ctl_lun_operable(struct ctl_be_lun *be_lun)
5034{
5035	struct ctl_softc *ctl_softc;
5036	struct ctl_lun *lun;
5037
5038	ctl_softc = control_softc;
5039	lun = (struct ctl_lun *)be_lun->ctl_lun;
5040
5041	mtx_lock(&lun->lun_lock);
5042	lun->flags &= ~CTL_LUN_INOPERABLE;
5043	mtx_unlock(&lun->lun_lock);
5044
5045	return (0);
5046}
5047
5048void
5049ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5050{
5051	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5052
5053	mtx_lock(&lun->lun_lock);
5054	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGED);
5055	mtx_unlock(&lun->lun_lock);
5056}
5057
5058/*
5059 * Backend "memory move is complete" callback for requests that never
5060 * make it down to say RAIDCore's configuration code.
5061 */
5062int
5063ctl_config_move_done(union ctl_io *io)
5064{
5065	int retval;
5066
5067	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5068	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5069	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5070
5071	if ((io->io_hdr.port_status != 0) &&
5072	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5073	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5074		/*
5075		 * For hardware error sense keys, the sense key
5076		 * specific value is defined to be a retry count,
5077		 * but we use it to pass back an internal FETD
5078		 * error code.  XXX KDM  Hopefully the FETD is only
5079		 * using 16 bits for an error code, since that's
5080		 * all the space we have in the sks field.
5081		 */
5082		ctl_set_internal_failure(&io->scsiio,
5083					 /*sks_valid*/ 1,
5084					 /*retry_count*/
5085					 io->io_hdr.port_status);
5086	}
5087
5088	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5089	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5090	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5091	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5092		/*
5093		 * XXX KDM just assuming a single pointer here, and not a
5094		 * S/G list.  If we start using S/G lists for config data,
5095		 * we'll need to know how to clean them up here as well.
5096		 */
5097		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5098			free(io->scsiio.kern_data_ptr, M_CTL);
5099		ctl_done(io);
5100		retval = CTL_RETVAL_COMPLETE;
5101	} else {
5102		/*
5103		 * XXX KDM now we need to continue data movement.  Some
5104		 * options:
5105		 * - call ctl_scsiio() again?  We don't do this for data
5106		 *   writes, because for those at least we know ahead of
5107		 *   time where the write will go and how long it is.  For
5108		 *   config writes, though, that information is largely
5109		 *   contained within the write itself, thus we need to
5110		 *   parse out the data again.
5111		 *
5112		 * - Call some other function once the data is in?
5113		 */
5114		if (ctl_debug & CTL_DEBUG_CDB_DATA)
5115			ctl_data_print(io);
5116
5117		/*
5118		 * XXX KDM call ctl_scsiio() again for now, and check flag
5119		 * bits to see whether we're allocated or not.
5120		 */
5121		retval = ctl_scsiio(&io->scsiio);
5122	}
5123	return (retval);
5124}
5125
5126/*
5127 * This gets called by a backend driver when it is done with a
5128 * data_submit method.
5129 */
5130void
5131ctl_data_submit_done(union ctl_io *io)
5132{
5133	/*
5134	 * If the IO_CONT flag is set, we need to call the supplied
5135	 * function to continue processing the I/O, instead of completing
5136	 * the I/O just yet.
5137	 *
5138	 * If there is an error, though, we don't want to keep processing.
5139	 * Instead, just send status back to the initiator.
5140	 */
5141	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5142	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5143	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5144	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5145		io->scsiio.io_cont(io);
5146		return;
5147	}
5148	ctl_done(io);
5149}
5150
5151/*
5152 * This gets called by a backend driver when it is done with a
5153 * configuration write.
5154 */
5155void
5156ctl_config_write_done(union ctl_io *io)
5157{
5158	uint8_t *buf;
5159
5160	/*
5161	 * If the IO_CONT flag is set, we need to call the supplied
5162	 * function to continue processing the I/O, instead of completing
5163	 * the I/O just yet.
5164	 *
5165	 * If there is an error, though, we don't want to keep processing.
5166	 * Instead, just send status back to the initiator.
5167	 */
5168	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5169	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5170	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5171	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5172		io->scsiio.io_cont(io);
5173		return;
5174	}
5175	/*
5176	 * Since a configuration write can be done for commands that actually
5177	 * have data allocated, like write buffer, and commands that have
5178	 * no data, like start/stop unit, we need to check here.
5179	 */
5180	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5181		buf = io->scsiio.kern_data_ptr;
5182	else
5183		buf = NULL;
5184	ctl_done(io);
5185	if (buf)
5186		free(buf, M_CTL);
5187}
5188
5189void
5190ctl_config_read_done(union ctl_io *io)
5191{
5192	uint8_t *buf;
5193
5194	/*
5195	 * If there is some error -- we are done, skip data transfer.
5196	 */
5197	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5198	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5199	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5200		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5201			buf = io->scsiio.kern_data_ptr;
5202		else
5203			buf = NULL;
5204		ctl_done(io);
5205		if (buf)
5206			free(buf, M_CTL);
5207		return;
5208	}
5209
5210	/*
5211	 * If the IO_CONT flag is set, we need to call the supplied
5212	 * function to continue processing the I/O, instead of completing
5213	 * the I/O just yet.
5214	 */
5215	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5216		io->scsiio.io_cont(io);
5217		return;
5218	}
5219
5220	ctl_datamove(io);
5221}
5222
5223/*
5224 * SCSI release command.
5225 */
5226int
5227ctl_scsi_release(struct ctl_scsiio *ctsio)
5228{
5229	int length, longid, thirdparty_id, resv_id;
5230	struct ctl_softc *ctl_softc;
5231	struct ctl_lun *lun;
5232	uint32_t residx;
5233
5234	length = 0;
5235	resv_id = 0;
5236
5237	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5238
5239	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5240	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5241	ctl_softc = control_softc;
5242
5243	switch (ctsio->cdb[0]) {
5244	case RELEASE_10: {
5245		struct scsi_release_10 *cdb;
5246
5247		cdb = (struct scsi_release_10 *)ctsio->cdb;
5248
5249		if (cdb->byte2 & SR10_LONGID)
5250			longid = 1;
5251		else
5252			thirdparty_id = cdb->thirdparty_id;
5253
5254		resv_id = cdb->resv_id;
5255		length = scsi_2btoul(cdb->length);
5256		break;
5257	}
5258	}
5259
5260
5261	/*
5262	 * XXX KDM right now, we only support LUN reservation.  We don't
5263	 * support 3rd party reservations, or extent reservations, which
5264	 * might actually need the parameter list.  If we've gotten this
5265	 * far, we've got a LUN reservation.  Anything else got kicked out
5266	 * above.  So, according to SPC, ignore the length.
5267	 */
5268	length = 0;
5269
5270	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5271	 && (length > 0)) {
5272		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5273		ctsio->kern_data_len = length;
5274		ctsio->kern_total_len = length;
5275		ctsio->kern_data_resid = 0;
5276		ctsio->kern_rel_offset = 0;
5277		ctsio->kern_sg_entries = 0;
5278		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5279		ctsio->be_move_done = ctl_config_move_done;
5280		ctl_datamove((union ctl_io *)ctsio);
5281
5282		return (CTL_RETVAL_COMPLETE);
5283	}
5284
5285	if (length > 0)
5286		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5287
5288	mtx_lock(&lun->lun_lock);
5289
5290	/*
5291	 * According to SPC, it is not an error for an intiator to attempt
5292	 * to release a reservation on a LUN that isn't reserved, or that
5293	 * is reserved by another initiator.  The reservation can only be
5294	 * released, though, by the initiator who made it or by one of
5295	 * several reset type events.
5296	 */
5297	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5298			lun->flags &= ~CTL_LUN_RESERVED;
5299
5300	mtx_unlock(&lun->lun_lock);
5301
5302	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5303		free(ctsio->kern_data_ptr, M_CTL);
5304		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5305	}
5306
5307	ctl_set_success(ctsio);
5308	ctl_done((union ctl_io *)ctsio);
5309	return (CTL_RETVAL_COMPLETE);
5310}
5311
5312int
5313ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5314{
5315	int extent, thirdparty, longid;
5316	int resv_id, length;
5317	uint64_t thirdparty_id;
5318	struct ctl_softc *ctl_softc;
5319	struct ctl_lun *lun;
5320	uint32_t residx;
5321
5322	extent = 0;
5323	thirdparty = 0;
5324	longid = 0;
5325	resv_id = 0;
5326	length = 0;
5327	thirdparty_id = 0;
5328
5329	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5330
5331	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5332	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5333	ctl_softc = control_softc;
5334
5335	switch (ctsio->cdb[0]) {
5336	case RESERVE_10: {
5337		struct scsi_reserve_10 *cdb;
5338
5339		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5340
5341		if (cdb->byte2 & SR10_LONGID)
5342			longid = 1;
5343		else
5344			thirdparty_id = cdb->thirdparty_id;
5345
5346		resv_id = cdb->resv_id;
5347		length = scsi_2btoul(cdb->length);
5348		break;
5349	}
5350	}
5351
5352	/*
5353	 * XXX KDM right now, we only support LUN reservation.  We don't
5354	 * support 3rd party reservations, or extent reservations, which
5355	 * might actually need the parameter list.  If we've gotten this
5356	 * far, we've got a LUN reservation.  Anything else got kicked out
5357	 * above.  So, according to SPC, ignore the length.
5358	 */
5359	length = 0;
5360
5361	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5362	 && (length > 0)) {
5363		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5364		ctsio->kern_data_len = length;
5365		ctsio->kern_total_len = length;
5366		ctsio->kern_data_resid = 0;
5367		ctsio->kern_rel_offset = 0;
5368		ctsio->kern_sg_entries = 0;
5369		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5370		ctsio->be_move_done = ctl_config_move_done;
5371		ctl_datamove((union ctl_io *)ctsio);
5372
5373		return (CTL_RETVAL_COMPLETE);
5374	}
5375
5376	if (length > 0)
5377		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5378
5379	mtx_lock(&lun->lun_lock);
5380	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5381		ctl_set_reservation_conflict(ctsio);
5382		goto bailout;
5383	}
5384
5385	lun->flags |= CTL_LUN_RESERVED;
5386	lun->res_idx = residx;
5387
5388	ctl_set_success(ctsio);
5389
5390bailout:
5391	mtx_unlock(&lun->lun_lock);
5392
5393	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5394		free(ctsio->kern_data_ptr, M_CTL);
5395		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5396	}
5397
5398	ctl_done((union ctl_io *)ctsio);
5399	return (CTL_RETVAL_COMPLETE);
5400}
5401
5402int
5403ctl_start_stop(struct ctl_scsiio *ctsio)
5404{
5405	struct scsi_start_stop_unit *cdb;
5406	struct ctl_lun *lun;
5407	struct ctl_softc *ctl_softc;
5408	int retval;
5409
5410	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5411
5412	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5413	ctl_softc = control_softc;
5414	retval = 0;
5415
5416	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5417
5418	/*
5419	 * XXX KDM
5420	 * We don't support the immediate bit on a stop unit.  In order to
5421	 * do that, we would need to code up a way to know that a stop is
5422	 * pending, and hold off any new commands until it completes, one
5423	 * way or another.  Then we could accept or reject those commands
5424	 * depending on its status.  We would almost need to do the reverse
5425	 * of what we do below for an immediate start -- return the copy of
5426	 * the ctl_io to the FETD with status to send to the host (and to
5427	 * free the copy!) and then free the original I/O once the stop
5428	 * actually completes.  That way, the OOA queue mechanism can work
5429	 * to block commands that shouldn't proceed.  Another alternative
5430	 * would be to put the copy in the queue in place of the original,
5431	 * and return the original back to the caller.  That could be
5432	 * slightly safer..
5433	 */
5434	if ((cdb->byte2 & SSS_IMMED)
5435	 && ((cdb->how & SSS_START) == 0)) {
5436		ctl_set_invalid_field(ctsio,
5437				      /*sks_valid*/ 1,
5438				      /*command*/ 1,
5439				      /*field*/ 1,
5440				      /*bit_valid*/ 1,
5441				      /*bit*/ 0);
5442		ctl_done((union ctl_io *)ctsio);
5443		return (CTL_RETVAL_COMPLETE);
5444	}
5445
5446	if ((lun->flags & CTL_LUN_PR_RESERVED)
5447	 && ((cdb->how & SSS_START)==0)) {
5448		uint32_t residx;
5449
5450		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5451		if (ctl_get_prkey(lun, residx) == 0
5452		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5453
5454			ctl_set_reservation_conflict(ctsio);
5455			ctl_done((union ctl_io *)ctsio);
5456			return (CTL_RETVAL_COMPLETE);
5457		}
5458	}
5459
5460	/*
5461	 * If there is no backend on this device, we can't start or stop
5462	 * it.  In theory we shouldn't get any start/stop commands in the
5463	 * first place at this level if the LUN doesn't have a backend.
5464	 * That should get stopped by the command decode code.
5465	 */
5466	if (lun->backend == NULL) {
5467		ctl_set_invalid_opcode(ctsio);
5468		ctl_done((union ctl_io *)ctsio);
5469		return (CTL_RETVAL_COMPLETE);
5470	}
5471
5472	/*
5473	 * XXX KDM Copan-specific offline behavior.
5474	 * Figure out a reasonable way to port this?
5475	 */
5476#ifdef NEEDTOPORT
5477	mtx_lock(&lun->lun_lock);
5478
5479	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5480	 && (lun->flags & CTL_LUN_OFFLINE)) {
5481		/*
5482		 * If the LUN is offline, and the on/offline bit isn't set,
5483		 * reject the start or stop.  Otherwise, let it through.
5484		 */
5485		mtx_unlock(&lun->lun_lock);
5486		ctl_set_lun_not_ready(ctsio);
5487		ctl_done((union ctl_io *)ctsio);
5488	} else {
5489		mtx_unlock(&lun->lun_lock);
5490#endif /* NEEDTOPORT */
5491		/*
5492		 * This could be a start or a stop when we're online,
5493		 * or a stop/offline or start/online.  A start or stop when
5494		 * we're offline is covered in the case above.
5495		 */
5496		/*
5497		 * In the non-immediate case, we send the request to
5498		 * the backend and return status to the user when
5499		 * it is done.
5500		 *
5501		 * In the immediate case, we allocate a new ctl_io
5502		 * to hold a copy of the request, and send that to
5503		 * the backend.  We then set good status on the
5504		 * user's request and return it immediately.
5505		 */
5506		if (cdb->byte2 & SSS_IMMED) {
5507			union ctl_io *new_io;
5508
5509			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5510			ctl_copy_io((union ctl_io *)ctsio, new_io);
5511			retval = lun->backend->config_write(new_io);
5512			ctl_set_success(ctsio);
5513			ctl_done((union ctl_io *)ctsio);
5514		} else {
5515			retval = lun->backend->config_write(
5516				(union ctl_io *)ctsio);
5517		}
5518#ifdef NEEDTOPORT
5519	}
5520#endif
5521	return (retval);
5522}
5523
5524/*
5525 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5526 * we don't really do anything with the LBA and length fields if the user
5527 * passes them in.  Instead we'll just flush out the cache for the entire
5528 * LUN.
5529 */
5530int
5531ctl_sync_cache(struct ctl_scsiio *ctsio)
5532{
5533	struct ctl_lun *lun;
5534	struct ctl_softc *ctl_softc;
5535	uint64_t starting_lba;
5536	uint32_t block_count;
5537	int retval;
5538
5539	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5540
5541	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5542	ctl_softc = control_softc;
5543	retval = 0;
5544
5545	switch (ctsio->cdb[0]) {
5546	case SYNCHRONIZE_CACHE: {
5547		struct scsi_sync_cache *cdb;
5548		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5549
5550		starting_lba = scsi_4btoul(cdb->begin_lba);
5551		block_count = scsi_2btoul(cdb->lb_count);
5552		break;
5553	}
5554	case SYNCHRONIZE_CACHE_16: {
5555		struct scsi_sync_cache_16 *cdb;
5556		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5557
5558		starting_lba = scsi_8btou64(cdb->begin_lba);
5559		block_count = scsi_4btoul(cdb->lb_count);
5560		break;
5561	}
5562	default:
5563		ctl_set_invalid_opcode(ctsio);
5564		ctl_done((union ctl_io *)ctsio);
5565		goto bailout;
5566		break; /* NOTREACHED */
5567	}
5568
5569	/*
5570	 * We check the LBA and length, but don't do anything with them.
5571	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5572	 * get flushed.  This check will just help satisfy anyone who wants
5573	 * to see an error for an out of range LBA.
5574	 */
5575	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5576		ctl_set_lba_out_of_range(ctsio);
5577		ctl_done((union ctl_io *)ctsio);
5578		goto bailout;
5579	}
5580
5581	/*
5582	 * If this LUN has no backend, we can't flush the cache anyway.
5583	 */
5584	if (lun->backend == NULL) {
5585		ctl_set_invalid_opcode(ctsio);
5586		ctl_done((union ctl_io *)ctsio);
5587		goto bailout;
5588	}
5589
5590	/*
5591	 * Check to see whether we're configured to send the SYNCHRONIZE
5592	 * CACHE command directly to the back end.
5593	 */
5594	mtx_lock(&lun->lun_lock);
5595	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5596	 && (++(lun->sync_count) >= lun->sync_interval)) {
5597		lun->sync_count = 0;
5598		mtx_unlock(&lun->lun_lock);
5599		retval = lun->backend->config_write((union ctl_io *)ctsio);
5600	} else {
5601		mtx_unlock(&lun->lun_lock);
5602		ctl_set_success(ctsio);
5603		ctl_done((union ctl_io *)ctsio);
5604	}
5605
5606bailout:
5607
5608	return (retval);
5609}
5610
5611int
5612ctl_format(struct ctl_scsiio *ctsio)
5613{
5614	struct scsi_format *cdb;
5615	struct ctl_lun *lun;
5616	struct ctl_softc *ctl_softc;
5617	int length, defect_list_len;
5618
5619	CTL_DEBUG_PRINT(("ctl_format\n"));
5620
5621	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5622	ctl_softc = control_softc;
5623
5624	cdb = (struct scsi_format *)ctsio->cdb;
5625
5626	length = 0;
5627	if (cdb->byte2 & SF_FMTDATA) {
5628		if (cdb->byte2 & SF_LONGLIST)
5629			length = sizeof(struct scsi_format_header_long);
5630		else
5631			length = sizeof(struct scsi_format_header_short);
5632	}
5633
5634	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5635	 && (length > 0)) {
5636		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5637		ctsio->kern_data_len = length;
5638		ctsio->kern_total_len = length;
5639		ctsio->kern_data_resid = 0;
5640		ctsio->kern_rel_offset = 0;
5641		ctsio->kern_sg_entries = 0;
5642		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5643		ctsio->be_move_done = ctl_config_move_done;
5644		ctl_datamove((union ctl_io *)ctsio);
5645
5646		return (CTL_RETVAL_COMPLETE);
5647	}
5648
5649	defect_list_len = 0;
5650
5651	if (cdb->byte2 & SF_FMTDATA) {
5652		if (cdb->byte2 & SF_LONGLIST) {
5653			struct scsi_format_header_long *header;
5654
5655			header = (struct scsi_format_header_long *)
5656				ctsio->kern_data_ptr;
5657
5658			defect_list_len = scsi_4btoul(header->defect_list_len);
5659			if (defect_list_len != 0) {
5660				ctl_set_invalid_field(ctsio,
5661						      /*sks_valid*/ 1,
5662						      /*command*/ 0,
5663						      /*field*/ 2,
5664						      /*bit_valid*/ 0,
5665						      /*bit*/ 0);
5666				goto bailout;
5667			}
5668		} else {
5669			struct scsi_format_header_short *header;
5670
5671			header = (struct scsi_format_header_short *)
5672				ctsio->kern_data_ptr;
5673
5674			defect_list_len = scsi_2btoul(header->defect_list_len);
5675			if (defect_list_len != 0) {
5676				ctl_set_invalid_field(ctsio,
5677						      /*sks_valid*/ 1,
5678						      /*command*/ 0,
5679						      /*field*/ 2,
5680						      /*bit_valid*/ 0,
5681						      /*bit*/ 0);
5682				goto bailout;
5683			}
5684		}
5685	}
5686
5687	/*
5688	 * The format command will clear out the "Medium format corrupted"
5689	 * status if set by the configuration code.  That status is really
5690	 * just a way to notify the host that we have lost the media, and
5691	 * get them to issue a command that will basically make them think
5692	 * they're blowing away the media.
5693	 */
5694	mtx_lock(&lun->lun_lock);
5695	lun->flags &= ~CTL_LUN_INOPERABLE;
5696	mtx_unlock(&lun->lun_lock);
5697
5698	ctl_set_success(ctsio);
5699bailout:
5700
5701	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5702		free(ctsio->kern_data_ptr, M_CTL);
5703		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5704	}
5705
5706	ctl_done((union ctl_io *)ctsio);
5707	return (CTL_RETVAL_COMPLETE);
5708}
5709
5710int
5711ctl_read_buffer(struct ctl_scsiio *ctsio)
5712{
5713	struct scsi_read_buffer *cdb;
5714	struct ctl_lun *lun;
5715	int buffer_offset, len;
5716	static uint8_t descr[4];
5717	static uint8_t echo_descr[4] = { 0 };
5718
5719	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5720
5721	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5722	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5723
5724	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5725	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5726	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5727		ctl_set_invalid_field(ctsio,
5728				      /*sks_valid*/ 1,
5729				      /*command*/ 1,
5730				      /*field*/ 1,
5731				      /*bit_valid*/ 1,
5732				      /*bit*/ 4);
5733		ctl_done((union ctl_io *)ctsio);
5734		return (CTL_RETVAL_COMPLETE);
5735	}
5736
5737	len = scsi_3btoul(cdb->length);
5738	buffer_offset = scsi_3btoul(cdb->offset);
5739
5740	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5741		ctl_set_invalid_field(ctsio,
5742				      /*sks_valid*/ 1,
5743				      /*command*/ 1,
5744				      /*field*/ 6,
5745				      /*bit_valid*/ 0,
5746				      /*bit*/ 0);
5747		ctl_done((union ctl_io *)ctsio);
5748		return (CTL_RETVAL_COMPLETE);
5749	}
5750
5751	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5752		descr[0] = 0;
5753		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5754		ctsio->kern_data_ptr = descr;
5755		len = min(len, sizeof(descr));
5756	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5757		ctsio->kern_data_ptr = echo_descr;
5758		len = min(len, sizeof(echo_descr));
5759	} else {
5760		if (lun->write_buffer == NULL) {
5761			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5762			    M_CTL, M_WAITOK);
5763		}
5764		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5765	}
5766	ctsio->kern_data_len = len;
5767	ctsio->kern_total_len = len;
5768	ctsio->kern_data_resid = 0;
5769	ctsio->kern_rel_offset = 0;
5770	ctsio->kern_sg_entries = 0;
5771	ctl_set_success(ctsio);
5772	ctsio->be_move_done = ctl_config_move_done;
5773	ctl_datamove((union ctl_io *)ctsio);
5774	return (CTL_RETVAL_COMPLETE);
5775}
5776
5777int
5778ctl_write_buffer(struct ctl_scsiio *ctsio)
5779{
5780	struct scsi_write_buffer *cdb;
5781	struct ctl_lun *lun;
5782	int buffer_offset, len;
5783
5784	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5785
5786	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5787	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5788
5789	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5790		ctl_set_invalid_field(ctsio,
5791				      /*sks_valid*/ 1,
5792				      /*command*/ 1,
5793				      /*field*/ 1,
5794				      /*bit_valid*/ 1,
5795				      /*bit*/ 4);
5796		ctl_done((union ctl_io *)ctsio);
5797		return (CTL_RETVAL_COMPLETE);
5798	}
5799
5800	len = scsi_3btoul(cdb->length);
5801	buffer_offset = scsi_3btoul(cdb->offset);
5802
5803	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5804		ctl_set_invalid_field(ctsio,
5805				      /*sks_valid*/ 1,
5806				      /*command*/ 1,
5807				      /*field*/ 6,
5808				      /*bit_valid*/ 0,
5809				      /*bit*/ 0);
5810		ctl_done((union ctl_io *)ctsio);
5811		return (CTL_RETVAL_COMPLETE);
5812	}
5813
5814	/*
5815	 * If we've got a kernel request that hasn't been malloced yet,
5816	 * malloc it and tell the caller the data buffer is here.
5817	 */
5818	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5819		if (lun->write_buffer == NULL) {
5820			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5821			    M_CTL, M_WAITOK);
5822		}
5823		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5824		ctsio->kern_data_len = len;
5825		ctsio->kern_total_len = len;
5826		ctsio->kern_data_resid = 0;
5827		ctsio->kern_rel_offset = 0;
5828		ctsio->kern_sg_entries = 0;
5829		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5830		ctsio->be_move_done = ctl_config_move_done;
5831		ctl_datamove((union ctl_io *)ctsio);
5832
5833		return (CTL_RETVAL_COMPLETE);
5834	}
5835
5836	ctl_set_success(ctsio);
5837	ctl_done((union ctl_io *)ctsio);
5838	return (CTL_RETVAL_COMPLETE);
5839}
5840
5841int
5842ctl_write_same(struct ctl_scsiio *ctsio)
5843{
5844	struct ctl_lun *lun;
5845	struct ctl_lba_len_flags *lbalen;
5846	uint64_t lba;
5847	uint32_t num_blocks;
5848	int len, retval;
5849	uint8_t byte2;
5850
5851	retval = CTL_RETVAL_COMPLETE;
5852
5853	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5854
5855	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5856
5857	switch (ctsio->cdb[0]) {
5858	case WRITE_SAME_10: {
5859		struct scsi_write_same_10 *cdb;
5860
5861		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5862
5863		lba = scsi_4btoul(cdb->addr);
5864		num_blocks = scsi_2btoul(cdb->length);
5865		byte2 = cdb->byte2;
5866		break;
5867	}
5868	case WRITE_SAME_16: {
5869		struct scsi_write_same_16 *cdb;
5870
5871		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5872
5873		lba = scsi_8btou64(cdb->addr);
5874		num_blocks = scsi_4btoul(cdb->length);
5875		byte2 = cdb->byte2;
5876		break;
5877	}
5878	default:
5879		/*
5880		 * We got a command we don't support.  This shouldn't
5881		 * happen, commands should be filtered out above us.
5882		 */
5883		ctl_set_invalid_opcode(ctsio);
5884		ctl_done((union ctl_io *)ctsio);
5885
5886		return (CTL_RETVAL_COMPLETE);
5887		break; /* NOTREACHED */
5888	}
5889
5890	/* NDOB and ANCHOR flags can be used only together with UNMAP */
5891	if ((byte2 & SWS_UNMAP) == 0 &&
5892	    (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5893		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5894		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5895		ctl_done((union ctl_io *)ctsio);
5896		return (CTL_RETVAL_COMPLETE);
5897	}
5898
5899	/*
5900	 * The first check is to make sure we're in bounds, the second
5901	 * check is to catch wrap-around problems.  If the lba + num blocks
5902	 * is less than the lba, then we've wrapped around and the block
5903	 * range is invalid anyway.
5904	 */
5905	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5906	 || ((lba + num_blocks) < lba)) {
5907		ctl_set_lba_out_of_range(ctsio);
5908		ctl_done((union ctl_io *)ctsio);
5909		return (CTL_RETVAL_COMPLETE);
5910	}
5911
5912	/* Zero number of blocks means "to the last logical block" */
5913	if (num_blocks == 0) {
5914		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5915			ctl_set_invalid_field(ctsio,
5916					      /*sks_valid*/ 0,
5917					      /*command*/ 1,
5918					      /*field*/ 0,
5919					      /*bit_valid*/ 0,
5920					      /*bit*/ 0);
5921			ctl_done((union ctl_io *)ctsio);
5922			return (CTL_RETVAL_COMPLETE);
5923		}
5924		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5925	}
5926
5927	len = lun->be_lun->blocksize;
5928
5929	/*
5930	 * If we've got a kernel request that hasn't been malloced yet,
5931	 * malloc it and tell the caller the data buffer is here.
5932	 */
5933	if ((byte2 & SWS_NDOB) == 0 &&
5934	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5935		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5936		ctsio->kern_data_len = len;
5937		ctsio->kern_total_len = len;
5938		ctsio->kern_data_resid = 0;
5939		ctsio->kern_rel_offset = 0;
5940		ctsio->kern_sg_entries = 0;
5941		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5942		ctsio->be_move_done = ctl_config_move_done;
5943		ctl_datamove((union ctl_io *)ctsio);
5944
5945		return (CTL_RETVAL_COMPLETE);
5946	}
5947
5948	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5949	lbalen->lba = lba;
5950	lbalen->len = num_blocks;
5951	lbalen->flags = byte2;
5952	retval = lun->backend->config_write((union ctl_io *)ctsio);
5953
5954	return (retval);
5955}
5956
5957int
5958ctl_unmap(struct ctl_scsiio *ctsio)
5959{
5960	struct ctl_lun *lun;
5961	struct scsi_unmap *cdb;
5962	struct ctl_ptr_len_flags *ptrlen;
5963	struct scsi_unmap_header *hdr;
5964	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5965	uint64_t lba;
5966	uint32_t num_blocks;
5967	int len, retval;
5968	uint8_t byte2;
5969
5970	retval = CTL_RETVAL_COMPLETE;
5971
5972	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5973
5974	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5975	cdb = (struct scsi_unmap *)ctsio->cdb;
5976
5977	len = scsi_2btoul(cdb->length);
5978	byte2 = cdb->byte2;
5979
5980	/*
5981	 * If we've got a kernel request that hasn't been malloced yet,
5982	 * malloc it and tell the caller the data buffer is here.
5983	 */
5984	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5985		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5986		ctsio->kern_data_len = len;
5987		ctsio->kern_total_len = len;
5988		ctsio->kern_data_resid = 0;
5989		ctsio->kern_rel_offset = 0;
5990		ctsio->kern_sg_entries = 0;
5991		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5992		ctsio->be_move_done = ctl_config_move_done;
5993		ctl_datamove((union ctl_io *)ctsio);
5994
5995		return (CTL_RETVAL_COMPLETE);
5996	}
5997
5998	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5999	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
6000	if (len < sizeof (*hdr) ||
6001	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
6002	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
6003	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
6004		ctl_set_invalid_field(ctsio,
6005				      /*sks_valid*/ 0,
6006				      /*command*/ 0,
6007				      /*field*/ 0,
6008				      /*bit_valid*/ 0,
6009				      /*bit*/ 0);
6010		goto done;
6011	}
6012	len = scsi_2btoul(hdr->desc_length);
6013	buf = (struct scsi_unmap_desc *)(hdr + 1);
6014	end = buf + len / sizeof(*buf);
6015
6016	endnz = buf;
6017	for (range = buf; range < end; range++) {
6018		lba = scsi_8btou64(range->lba);
6019		num_blocks = scsi_4btoul(range->length);
6020		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6021		 || ((lba + num_blocks) < lba)) {
6022			ctl_set_lba_out_of_range(ctsio);
6023			ctl_done((union ctl_io *)ctsio);
6024			return (CTL_RETVAL_COMPLETE);
6025		}
6026		if (num_blocks != 0)
6027			endnz = range + 1;
6028	}
6029
6030	/*
6031	 * Block backend can not handle zero last range.
6032	 * Filter it out and return if there is nothing left.
6033	 */
6034	len = (uint8_t *)endnz - (uint8_t *)buf;
6035	if (len == 0) {
6036		ctl_set_success(ctsio);
6037		goto done;
6038	}
6039
6040	mtx_lock(&lun->lun_lock);
6041	ptrlen = (struct ctl_ptr_len_flags *)
6042	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6043	ptrlen->ptr = (void *)buf;
6044	ptrlen->len = len;
6045	ptrlen->flags = byte2;
6046	ctl_check_blocked(lun);
6047	mtx_unlock(&lun->lun_lock);
6048
6049	retval = lun->backend->config_write((union ctl_io *)ctsio);
6050	return (retval);
6051
6052done:
6053	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
6054		free(ctsio->kern_data_ptr, M_CTL);
6055		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
6056	}
6057	ctl_done((union ctl_io *)ctsio);
6058	return (CTL_RETVAL_COMPLETE);
6059}
6060
6061/*
6062 * Note that this function currently doesn't actually do anything inside
6063 * CTL to enforce things if the DQue bit is turned on.
6064 *
6065 * Also note that this function can't be used in the default case, because
6066 * the DQue bit isn't set in the changeable mask for the control mode page
6067 * anyway.  This is just here as an example for how to implement a page
6068 * handler, and a placeholder in case we want to allow the user to turn
6069 * tagged queueing on and off.
6070 *
6071 * The D_SENSE bit handling is functional, however, and will turn
6072 * descriptor sense on and off for a given LUN.
6073 */
6074int
6075ctl_control_page_handler(struct ctl_scsiio *ctsio,
6076			 struct ctl_page_index *page_index, uint8_t *page_ptr)
6077{
6078	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6079	struct ctl_lun *lun;
6080	struct ctl_softc *softc;
6081	int set_ua;
6082	uint32_t initidx;
6083
6084	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6085	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6086	set_ua = 0;
6087
6088	user_cp = (struct scsi_control_page *)page_ptr;
6089	current_cp = (struct scsi_control_page *)
6090		(page_index->page_data + (page_index->page_len *
6091		CTL_PAGE_CURRENT));
6092	saved_cp = (struct scsi_control_page *)
6093		(page_index->page_data + (page_index->page_len *
6094		CTL_PAGE_SAVED));
6095
6096	softc = control_softc;
6097
6098	mtx_lock(&lun->lun_lock);
6099	if (((current_cp->rlec & SCP_DSENSE) == 0)
6100	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6101		/*
6102		 * Descriptor sense is currently turned off and the user
6103		 * wants to turn it on.
6104		 */
6105		current_cp->rlec |= SCP_DSENSE;
6106		saved_cp->rlec |= SCP_DSENSE;
6107		lun->flags |= CTL_LUN_SENSE_DESC;
6108		set_ua = 1;
6109	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6110		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6111		/*
6112		 * Descriptor sense is currently turned on, and the user
6113		 * wants to turn it off.
6114		 */
6115		current_cp->rlec &= ~SCP_DSENSE;
6116		saved_cp->rlec &= ~SCP_DSENSE;
6117		lun->flags &= ~CTL_LUN_SENSE_DESC;
6118		set_ua = 1;
6119	}
6120	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6121	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6122		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6123		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6124		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6125		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6126		set_ua = 1;
6127	}
6128	if ((current_cp->eca_and_aen & SCP_SWP) !=
6129	    (user_cp->eca_and_aen & SCP_SWP)) {
6130		current_cp->eca_and_aen &= ~SCP_SWP;
6131		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6132		saved_cp->eca_and_aen &= ~SCP_SWP;
6133		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6134		set_ua = 1;
6135	}
6136	if (set_ua != 0)
6137		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6138	mtx_unlock(&lun->lun_lock);
6139
6140	return (0);
6141}
6142
6143int
6144ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6145		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6146{
6147	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6148	struct ctl_lun *lun;
6149	int set_ua;
6150	uint32_t initidx;
6151
6152	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6153	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6154	set_ua = 0;
6155
6156	user_cp = (struct scsi_caching_page *)page_ptr;
6157	current_cp = (struct scsi_caching_page *)
6158		(page_index->page_data + (page_index->page_len *
6159		CTL_PAGE_CURRENT));
6160	saved_cp = (struct scsi_caching_page *)
6161		(page_index->page_data + (page_index->page_len *
6162		CTL_PAGE_SAVED));
6163
6164	mtx_lock(&lun->lun_lock);
6165	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6166	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6167		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6168		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6169		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6170		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6171		set_ua = 1;
6172	}
6173	if (set_ua != 0)
6174		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6175	mtx_unlock(&lun->lun_lock);
6176
6177	return (0);
6178}
6179
6180int
6181ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6182				struct ctl_page_index *page_index,
6183				uint8_t *page_ptr)
6184{
6185	uint8_t *c;
6186	int i;
6187
6188	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6189	ctl_time_io_secs =
6190		(c[0] << 8) |
6191		(c[1] << 0) |
6192		0;
6193	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6194	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6195	printf("page data:");
6196	for (i=0; i<8; i++)
6197		printf(" %.2x",page_ptr[i]);
6198	printf("\n");
6199	return (0);
6200}
6201
6202int
6203ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6204			       struct ctl_page_index *page_index,
6205			       int pc)
6206{
6207	struct copan_debugconf_subpage *page;
6208
6209	page = (struct copan_debugconf_subpage *)page_index->page_data +
6210		(page_index->page_len * pc);
6211
6212	switch (pc) {
6213	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6214	case SMS_PAGE_CTRL_DEFAULT >> 6:
6215	case SMS_PAGE_CTRL_SAVED >> 6:
6216		/*
6217		 * We don't update the changable or default bits for this page.
6218		 */
6219		break;
6220	case SMS_PAGE_CTRL_CURRENT >> 6:
6221		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6222		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6223		break;
6224	default:
6225#ifdef NEEDTOPORT
6226		EPRINT(0, "Invalid PC %d!!", pc);
6227#endif /* NEEDTOPORT */
6228		break;
6229	}
6230	return (0);
6231}
6232
6233
6234static int
6235ctl_do_mode_select(union ctl_io *io)
6236{
6237	struct scsi_mode_page_header *page_header;
6238	struct ctl_page_index *page_index;
6239	struct ctl_scsiio *ctsio;
6240	int control_dev, page_len;
6241	int page_len_offset, page_len_size;
6242	union ctl_modepage_info *modepage_info;
6243	struct ctl_lun *lun;
6244	int *len_left, *len_used;
6245	int retval, i;
6246
6247	ctsio = &io->scsiio;
6248	page_index = NULL;
6249	page_len = 0;
6250	retval = CTL_RETVAL_COMPLETE;
6251
6252	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6253
6254	if (lun->be_lun->lun_type != T_DIRECT)
6255		control_dev = 1;
6256	else
6257		control_dev = 0;
6258
6259	modepage_info = (union ctl_modepage_info *)
6260		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6261	len_left = &modepage_info->header.len_left;
6262	len_used = &modepage_info->header.len_used;
6263
6264do_next_page:
6265
6266	page_header = (struct scsi_mode_page_header *)
6267		(ctsio->kern_data_ptr + *len_used);
6268
6269	if (*len_left == 0) {
6270		free(ctsio->kern_data_ptr, M_CTL);
6271		ctl_set_success(ctsio);
6272		ctl_done((union ctl_io *)ctsio);
6273		return (CTL_RETVAL_COMPLETE);
6274	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6275
6276		free(ctsio->kern_data_ptr, M_CTL);
6277		ctl_set_param_len_error(ctsio);
6278		ctl_done((union ctl_io *)ctsio);
6279		return (CTL_RETVAL_COMPLETE);
6280
6281	} else if ((page_header->page_code & SMPH_SPF)
6282		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6283
6284		free(ctsio->kern_data_ptr, M_CTL);
6285		ctl_set_param_len_error(ctsio);
6286		ctl_done((union ctl_io *)ctsio);
6287		return (CTL_RETVAL_COMPLETE);
6288	}
6289
6290
6291	/*
6292	 * XXX KDM should we do something with the block descriptor?
6293	 */
6294	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6295
6296		if ((control_dev != 0)
6297		 && (lun->mode_pages.index[i].page_flags &
6298		     CTL_PAGE_FLAG_DISK_ONLY))
6299			continue;
6300
6301		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6302		    (page_header->page_code & SMPH_PC_MASK))
6303			continue;
6304
6305		/*
6306		 * If neither page has a subpage code, then we've got a
6307		 * match.
6308		 */
6309		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6310		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6311			page_index = &lun->mode_pages.index[i];
6312			page_len = page_header->page_length;
6313			break;
6314		}
6315
6316		/*
6317		 * If both pages have subpages, then the subpage numbers
6318		 * have to match.
6319		 */
6320		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6321		  && (page_header->page_code & SMPH_SPF)) {
6322			struct scsi_mode_page_header_sp *sph;
6323
6324			sph = (struct scsi_mode_page_header_sp *)page_header;
6325
6326			if (lun->mode_pages.index[i].subpage ==
6327			    sph->subpage) {
6328				page_index = &lun->mode_pages.index[i];
6329				page_len = scsi_2btoul(sph->page_length);
6330				break;
6331			}
6332		}
6333	}
6334
6335	/*
6336	 * If we couldn't find the page, or if we don't have a mode select
6337	 * handler for it, send back an error to the user.
6338	 */
6339	if ((page_index == NULL)
6340	 || (page_index->select_handler == NULL)) {
6341		ctl_set_invalid_field(ctsio,
6342				      /*sks_valid*/ 1,
6343				      /*command*/ 0,
6344				      /*field*/ *len_used,
6345				      /*bit_valid*/ 0,
6346				      /*bit*/ 0);
6347		free(ctsio->kern_data_ptr, M_CTL);
6348		ctl_done((union ctl_io *)ctsio);
6349		return (CTL_RETVAL_COMPLETE);
6350	}
6351
6352	if (page_index->page_code & SMPH_SPF) {
6353		page_len_offset = 2;
6354		page_len_size = 2;
6355	} else {
6356		page_len_size = 1;
6357		page_len_offset = 1;
6358	}
6359
6360	/*
6361	 * If the length the initiator gives us isn't the one we specify in
6362	 * the mode page header, or if they didn't specify enough data in
6363	 * the CDB to avoid truncating this page, kick out the request.
6364	 */
6365	if ((page_len != (page_index->page_len - page_len_offset -
6366			  page_len_size))
6367	 || (*len_left < page_index->page_len)) {
6368
6369
6370		ctl_set_invalid_field(ctsio,
6371				      /*sks_valid*/ 1,
6372				      /*command*/ 0,
6373				      /*field*/ *len_used + page_len_offset,
6374				      /*bit_valid*/ 0,
6375				      /*bit*/ 0);
6376		free(ctsio->kern_data_ptr, M_CTL);
6377		ctl_done((union ctl_io *)ctsio);
6378		return (CTL_RETVAL_COMPLETE);
6379	}
6380
6381	/*
6382	 * Run through the mode page, checking to make sure that the bits
6383	 * the user changed are actually legal for him to change.
6384	 */
6385	for (i = 0; i < page_index->page_len; i++) {
6386		uint8_t *user_byte, *change_mask, *current_byte;
6387		int bad_bit;
6388		int j;
6389
6390		user_byte = (uint8_t *)page_header + i;
6391		change_mask = page_index->page_data +
6392			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6393		current_byte = page_index->page_data +
6394			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6395
6396		/*
6397		 * Check to see whether the user set any bits in this byte
6398		 * that he is not allowed to set.
6399		 */
6400		if ((*user_byte & ~(*change_mask)) ==
6401		    (*current_byte & ~(*change_mask)))
6402			continue;
6403
6404		/*
6405		 * Go through bit by bit to determine which one is illegal.
6406		 */
6407		bad_bit = 0;
6408		for (j = 7; j >= 0; j--) {
6409			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6410			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6411				bad_bit = i;
6412				break;
6413			}
6414		}
6415		ctl_set_invalid_field(ctsio,
6416				      /*sks_valid*/ 1,
6417				      /*command*/ 0,
6418				      /*field*/ *len_used + i,
6419				      /*bit_valid*/ 1,
6420				      /*bit*/ bad_bit);
6421		free(ctsio->kern_data_ptr, M_CTL);
6422		ctl_done((union ctl_io *)ctsio);
6423		return (CTL_RETVAL_COMPLETE);
6424	}
6425
6426	/*
6427	 * Decrement these before we call the page handler, since we may
6428	 * end up getting called back one way or another before the handler
6429	 * returns to this context.
6430	 */
6431	*len_left -= page_index->page_len;
6432	*len_used += page_index->page_len;
6433
6434	retval = page_index->select_handler(ctsio, page_index,
6435					    (uint8_t *)page_header);
6436
6437	/*
6438	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6439	 * wait until this queued command completes to finish processing
6440	 * the mode page.  If it returns anything other than
6441	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6442	 * already set the sense information, freed the data pointer, and
6443	 * completed the io for us.
6444	 */
6445	if (retval != CTL_RETVAL_COMPLETE)
6446		goto bailout_no_done;
6447
6448	/*
6449	 * If the initiator sent us more than one page, parse the next one.
6450	 */
6451	if (*len_left > 0)
6452		goto do_next_page;
6453
6454	ctl_set_success(ctsio);
6455	free(ctsio->kern_data_ptr, M_CTL);
6456	ctl_done((union ctl_io *)ctsio);
6457
6458bailout_no_done:
6459
6460	return (CTL_RETVAL_COMPLETE);
6461
6462}
6463
6464int
6465ctl_mode_select(struct ctl_scsiio *ctsio)
6466{
6467	int param_len, pf, sp;
6468	int header_size, bd_len;
6469	int len_left, len_used;
6470	struct ctl_page_index *page_index;
6471	struct ctl_lun *lun;
6472	int control_dev, page_len;
6473	union ctl_modepage_info *modepage_info;
6474	int retval;
6475
6476	pf = 0;
6477	sp = 0;
6478	page_len = 0;
6479	len_used = 0;
6480	len_left = 0;
6481	retval = 0;
6482	bd_len = 0;
6483	page_index = NULL;
6484
6485	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6486
6487	if (lun->be_lun->lun_type != T_DIRECT)
6488		control_dev = 1;
6489	else
6490		control_dev = 0;
6491
6492	switch (ctsio->cdb[0]) {
6493	case MODE_SELECT_6: {
6494		struct scsi_mode_select_6 *cdb;
6495
6496		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6497
6498		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6499		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6500
6501		param_len = cdb->length;
6502		header_size = sizeof(struct scsi_mode_header_6);
6503		break;
6504	}
6505	case MODE_SELECT_10: {
6506		struct scsi_mode_select_10 *cdb;
6507
6508		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6509
6510		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6511		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6512
6513		param_len = scsi_2btoul(cdb->length);
6514		header_size = sizeof(struct scsi_mode_header_10);
6515		break;
6516	}
6517	default:
6518		ctl_set_invalid_opcode(ctsio);
6519		ctl_done((union ctl_io *)ctsio);
6520		return (CTL_RETVAL_COMPLETE);
6521		break; /* NOTREACHED */
6522	}
6523
6524	/*
6525	 * From SPC-3:
6526	 * "A parameter list length of zero indicates that the Data-Out Buffer
6527	 * shall be empty. This condition shall not be considered as an error."
6528	 */
6529	if (param_len == 0) {
6530		ctl_set_success(ctsio);
6531		ctl_done((union ctl_io *)ctsio);
6532		return (CTL_RETVAL_COMPLETE);
6533	}
6534
6535	/*
6536	 * Since we'll hit this the first time through, prior to
6537	 * allocation, we don't need to free a data buffer here.
6538	 */
6539	if (param_len < header_size) {
6540		ctl_set_param_len_error(ctsio);
6541		ctl_done((union ctl_io *)ctsio);
6542		return (CTL_RETVAL_COMPLETE);
6543	}
6544
6545	/*
6546	 * Allocate the data buffer and grab the user's data.  In theory,
6547	 * we shouldn't have to sanity check the parameter list length here
6548	 * because the maximum size is 64K.  We should be able to malloc
6549	 * that much without too many problems.
6550	 */
6551	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6552		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6553		ctsio->kern_data_len = param_len;
6554		ctsio->kern_total_len = param_len;
6555		ctsio->kern_data_resid = 0;
6556		ctsio->kern_rel_offset = 0;
6557		ctsio->kern_sg_entries = 0;
6558		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6559		ctsio->be_move_done = ctl_config_move_done;
6560		ctl_datamove((union ctl_io *)ctsio);
6561
6562		return (CTL_RETVAL_COMPLETE);
6563	}
6564
6565	switch (ctsio->cdb[0]) {
6566	case MODE_SELECT_6: {
6567		struct scsi_mode_header_6 *mh6;
6568
6569		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6570		bd_len = mh6->blk_desc_len;
6571		break;
6572	}
6573	case MODE_SELECT_10: {
6574		struct scsi_mode_header_10 *mh10;
6575
6576		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6577		bd_len = scsi_2btoul(mh10->blk_desc_len);
6578		break;
6579	}
6580	default:
6581		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6582		break;
6583	}
6584
6585	if (param_len < (header_size + bd_len)) {
6586		free(ctsio->kern_data_ptr, M_CTL);
6587		ctl_set_param_len_error(ctsio);
6588		ctl_done((union ctl_io *)ctsio);
6589		return (CTL_RETVAL_COMPLETE);
6590	}
6591
6592	/*
6593	 * Set the IO_CONT flag, so that if this I/O gets passed to
6594	 * ctl_config_write_done(), it'll get passed back to
6595	 * ctl_do_mode_select() for further processing, or completion if
6596	 * we're all done.
6597	 */
6598	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6599	ctsio->io_cont = ctl_do_mode_select;
6600
6601	modepage_info = (union ctl_modepage_info *)
6602		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6603
6604	memset(modepage_info, 0, sizeof(*modepage_info));
6605
6606	len_left = param_len - header_size - bd_len;
6607	len_used = header_size + bd_len;
6608
6609	modepage_info->header.len_left = len_left;
6610	modepage_info->header.len_used = len_used;
6611
6612	return (ctl_do_mode_select((union ctl_io *)ctsio));
6613}
6614
6615int
6616ctl_mode_sense(struct ctl_scsiio *ctsio)
6617{
6618	struct ctl_lun *lun;
6619	int pc, page_code, dbd, llba, subpage;
6620	int alloc_len, page_len, header_len, total_len;
6621	struct scsi_mode_block_descr *block_desc;
6622	struct ctl_page_index *page_index;
6623	int control_dev;
6624
6625	dbd = 0;
6626	llba = 0;
6627	block_desc = NULL;
6628	page_index = NULL;
6629
6630	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6631
6632	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6633
6634	if (lun->be_lun->lun_type != T_DIRECT)
6635		control_dev = 1;
6636	else
6637		control_dev = 0;
6638
6639	switch (ctsio->cdb[0]) {
6640	case MODE_SENSE_6: {
6641		struct scsi_mode_sense_6 *cdb;
6642
6643		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6644
6645		header_len = sizeof(struct scsi_mode_hdr_6);
6646		if (cdb->byte2 & SMS_DBD)
6647			dbd = 1;
6648		else
6649			header_len += sizeof(struct scsi_mode_block_descr);
6650
6651		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6652		page_code = cdb->page & SMS_PAGE_CODE;
6653		subpage = cdb->subpage;
6654		alloc_len = cdb->length;
6655		break;
6656	}
6657	case MODE_SENSE_10: {
6658		struct scsi_mode_sense_10 *cdb;
6659
6660		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6661
6662		header_len = sizeof(struct scsi_mode_hdr_10);
6663
6664		if (cdb->byte2 & SMS_DBD)
6665			dbd = 1;
6666		else
6667			header_len += sizeof(struct scsi_mode_block_descr);
6668		if (cdb->byte2 & SMS10_LLBAA)
6669			llba = 1;
6670		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6671		page_code = cdb->page & SMS_PAGE_CODE;
6672		subpage = cdb->subpage;
6673		alloc_len = scsi_2btoul(cdb->length);
6674		break;
6675	}
6676	default:
6677		ctl_set_invalid_opcode(ctsio);
6678		ctl_done((union ctl_io *)ctsio);
6679		return (CTL_RETVAL_COMPLETE);
6680		break; /* NOTREACHED */
6681	}
6682
6683	/*
6684	 * We have to make a first pass through to calculate the size of
6685	 * the pages that match the user's query.  Then we allocate enough
6686	 * memory to hold it, and actually copy the data into the buffer.
6687	 */
6688	switch (page_code) {
6689	case SMS_ALL_PAGES_PAGE: {
6690		int i;
6691
6692		page_len = 0;
6693
6694		/*
6695		 * At the moment, values other than 0 and 0xff here are
6696		 * reserved according to SPC-3.
6697		 */
6698		if ((subpage != SMS_SUBPAGE_PAGE_0)
6699		 && (subpage != SMS_SUBPAGE_ALL)) {
6700			ctl_set_invalid_field(ctsio,
6701					      /*sks_valid*/ 1,
6702					      /*command*/ 1,
6703					      /*field*/ 3,
6704					      /*bit_valid*/ 0,
6705					      /*bit*/ 0);
6706			ctl_done((union ctl_io *)ctsio);
6707			return (CTL_RETVAL_COMPLETE);
6708		}
6709
6710		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6711			if ((control_dev != 0)
6712			 && (lun->mode_pages.index[i].page_flags &
6713			     CTL_PAGE_FLAG_DISK_ONLY))
6714				continue;
6715
6716			/*
6717			 * We don't use this subpage if the user didn't
6718			 * request all subpages.
6719			 */
6720			if ((lun->mode_pages.index[i].subpage != 0)
6721			 && (subpage == SMS_SUBPAGE_PAGE_0))
6722				continue;
6723
6724#if 0
6725			printf("found page %#x len %d\n",
6726			       lun->mode_pages.index[i].page_code &
6727			       SMPH_PC_MASK,
6728			       lun->mode_pages.index[i].page_len);
6729#endif
6730			page_len += lun->mode_pages.index[i].page_len;
6731		}
6732		break;
6733	}
6734	default: {
6735		int i;
6736
6737		page_len = 0;
6738
6739		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6740			/* Look for the right page code */
6741			if ((lun->mode_pages.index[i].page_code &
6742			     SMPH_PC_MASK) != page_code)
6743				continue;
6744
6745			/* Look for the right subpage or the subpage wildcard*/
6746			if ((lun->mode_pages.index[i].subpage != subpage)
6747			 && (subpage != SMS_SUBPAGE_ALL))
6748				continue;
6749
6750			/* Make sure the page is supported for this dev type */
6751			if ((control_dev != 0)
6752			 && (lun->mode_pages.index[i].page_flags &
6753			     CTL_PAGE_FLAG_DISK_ONLY))
6754				continue;
6755
6756#if 0
6757			printf("found page %#x len %d\n",
6758			       lun->mode_pages.index[i].page_code &
6759			       SMPH_PC_MASK,
6760			       lun->mode_pages.index[i].page_len);
6761#endif
6762
6763			page_len += lun->mode_pages.index[i].page_len;
6764		}
6765
6766		if (page_len == 0) {
6767			ctl_set_invalid_field(ctsio,
6768					      /*sks_valid*/ 1,
6769					      /*command*/ 1,
6770					      /*field*/ 2,
6771					      /*bit_valid*/ 1,
6772					      /*bit*/ 5);
6773			ctl_done((union ctl_io *)ctsio);
6774			return (CTL_RETVAL_COMPLETE);
6775		}
6776		break;
6777	}
6778	}
6779
6780	total_len = header_len + page_len;
6781#if 0
6782	printf("header_len = %d, page_len = %d, total_len = %d\n",
6783	       header_len, page_len, total_len);
6784#endif
6785
6786	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6787	ctsio->kern_sg_entries = 0;
6788	ctsio->kern_data_resid = 0;
6789	ctsio->kern_rel_offset = 0;
6790	if (total_len < alloc_len) {
6791		ctsio->residual = alloc_len - total_len;
6792		ctsio->kern_data_len = total_len;
6793		ctsio->kern_total_len = total_len;
6794	} else {
6795		ctsio->residual = 0;
6796		ctsio->kern_data_len = alloc_len;
6797		ctsio->kern_total_len = alloc_len;
6798	}
6799
6800	switch (ctsio->cdb[0]) {
6801	case MODE_SENSE_6: {
6802		struct scsi_mode_hdr_6 *header;
6803
6804		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6805
6806		header->datalen = ctl_min(total_len - 1, 254);
6807		if (control_dev == 0) {
6808			header->dev_specific = 0x10; /* DPOFUA */
6809			if ((lun->flags & CTL_LUN_READONLY) ||
6810			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6811			    .eca_and_aen & SCP_SWP) != 0)
6812				    header->dev_specific |= 0x80; /* WP */
6813		}
6814		if (dbd)
6815			header->block_descr_len = 0;
6816		else
6817			header->block_descr_len =
6818				sizeof(struct scsi_mode_block_descr);
6819		block_desc = (struct scsi_mode_block_descr *)&header[1];
6820		break;
6821	}
6822	case MODE_SENSE_10: {
6823		struct scsi_mode_hdr_10 *header;
6824		int datalen;
6825
6826		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6827
6828		datalen = ctl_min(total_len - 2, 65533);
6829		scsi_ulto2b(datalen, header->datalen);
6830		if (control_dev == 0) {
6831			header->dev_specific = 0x10; /* DPOFUA */
6832			if ((lun->flags & CTL_LUN_READONLY) ||
6833			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6834			    .eca_and_aen & SCP_SWP) != 0)
6835				    header->dev_specific |= 0x80; /* WP */
6836		}
6837		if (dbd)
6838			scsi_ulto2b(0, header->block_descr_len);
6839		else
6840			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6841				    header->block_descr_len);
6842		block_desc = (struct scsi_mode_block_descr *)&header[1];
6843		break;
6844	}
6845	default:
6846		panic("invalid CDB type %#x", ctsio->cdb[0]);
6847		break; /* NOTREACHED */
6848	}
6849
6850	/*
6851	 * If we've got a disk, use its blocksize in the block
6852	 * descriptor.  Otherwise, just set it to 0.
6853	 */
6854	if (dbd == 0) {
6855		if (control_dev == 0)
6856			scsi_ulto3b(lun->be_lun->blocksize,
6857				    block_desc->block_len);
6858		else
6859			scsi_ulto3b(0, block_desc->block_len);
6860	}
6861
6862	switch (page_code) {
6863	case SMS_ALL_PAGES_PAGE: {
6864		int i, data_used;
6865
6866		data_used = header_len;
6867		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6868			struct ctl_page_index *page_index;
6869
6870			page_index = &lun->mode_pages.index[i];
6871
6872			if ((control_dev != 0)
6873			 && (page_index->page_flags &
6874			    CTL_PAGE_FLAG_DISK_ONLY))
6875				continue;
6876
6877			/*
6878			 * We don't use this subpage if the user didn't
6879			 * request all subpages.  We already checked (above)
6880			 * to make sure the user only specified a subpage
6881			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6882			 */
6883			if ((page_index->subpage != 0)
6884			 && (subpage == SMS_SUBPAGE_PAGE_0))
6885				continue;
6886
6887			/*
6888			 * Call the handler, if it exists, to update the
6889			 * page to the latest values.
6890			 */
6891			if (page_index->sense_handler != NULL)
6892				page_index->sense_handler(ctsio, page_index,pc);
6893
6894			memcpy(ctsio->kern_data_ptr + data_used,
6895			       page_index->page_data +
6896			       (page_index->page_len * pc),
6897			       page_index->page_len);
6898			data_used += page_index->page_len;
6899		}
6900		break;
6901	}
6902	default: {
6903		int i, data_used;
6904
6905		data_used = header_len;
6906
6907		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6908			struct ctl_page_index *page_index;
6909
6910			page_index = &lun->mode_pages.index[i];
6911
6912			/* Look for the right page code */
6913			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6914				continue;
6915
6916			/* Look for the right subpage or the subpage wildcard*/
6917			if ((page_index->subpage != subpage)
6918			 && (subpage != SMS_SUBPAGE_ALL))
6919				continue;
6920
6921			/* Make sure the page is supported for this dev type */
6922			if ((control_dev != 0)
6923			 && (page_index->page_flags &
6924			     CTL_PAGE_FLAG_DISK_ONLY))
6925				continue;
6926
6927			/*
6928			 * Call the handler, if it exists, to update the
6929			 * page to the latest values.
6930			 */
6931			if (page_index->sense_handler != NULL)
6932				page_index->sense_handler(ctsio, page_index,pc);
6933
6934			memcpy(ctsio->kern_data_ptr + data_used,
6935			       page_index->page_data +
6936			       (page_index->page_len * pc),
6937			       page_index->page_len);
6938			data_used += page_index->page_len;
6939		}
6940		break;
6941	}
6942	}
6943
6944	ctl_set_success(ctsio);
6945	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6946	ctsio->be_move_done = ctl_config_move_done;
6947	ctl_datamove((union ctl_io *)ctsio);
6948	return (CTL_RETVAL_COMPLETE);
6949}
6950
6951int
6952ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6953			       struct ctl_page_index *page_index,
6954			       int pc)
6955{
6956	struct ctl_lun *lun;
6957	struct scsi_log_param_header *phdr;
6958	uint8_t *data;
6959	uint64_t val;
6960
6961	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6962	data = page_index->page_data;
6963
6964	if (lun->backend->lun_attr != NULL &&
6965	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6966	     != UINT64_MAX) {
6967		phdr = (struct scsi_log_param_header *)data;
6968		scsi_ulto2b(0x0001, phdr->param_code);
6969		phdr->param_control = SLP_LBIN | SLP_LP;
6970		phdr->param_len = 8;
6971		data = (uint8_t *)(phdr + 1);
6972		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6973		data[4] = 0x02; /* per-pool */
6974		data += phdr->param_len;
6975	}
6976
6977	if (lun->backend->lun_attr != NULL &&
6978	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6979	     != UINT64_MAX) {
6980		phdr = (struct scsi_log_param_header *)data;
6981		scsi_ulto2b(0x0002, phdr->param_code);
6982		phdr->param_control = SLP_LBIN | SLP_LP;
6983		phdr->param_len = 8;
6984		data = (uint8_t *)(phdr + 1);
6985		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6986		data[4] = 0x01; /* per-LUN */
6987		data += phdr->param_len;
6988	}
6989
6990	if (lun->backend->lun_attr != NULL &&
6991	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6992	     != UINT64_MAX) {
6993		phdr = (struct scsi_log_param_header *)data;
6994		scsi_ulto2b(0x00f1, phdr->param_code);
6995		phdr->param_control = SLP_LBIN | SLP_LP;
6996		phdr->param_len = 8;
6997		data = (uint8_t *)(phdr + 1);
6998		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6999		data[4] = 0x02; /* per-pool */
7000		data += phdr->param_len;
7001	}
7002
7003	if (lun->backend->lun_attr != NULL &&
7004	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
7005	     != UINT64_MAX) {
7006		phdr = (struct scsi_log_param_header *)data;
7007		scsi_ulto2b(0x00f2, phdr->param_code);
7008		phdr->param_control = SLP_LBIN | SLP_LP;
7009		phdr->param_len = 8;
7010		data = (uint8_t *)(phdr + 1);
7011		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
7012		data[4] = 0x02; /* per-pool */
7013		data += phdr->param_len;
7014	}
7015
7016	page_index->page_len = data - page_index->page_data;
7017	return (0);
7018}
7019
7020int
7021ctl_log_sense(struct ctl_scsiio *ctsio)
7022{
7023	struct ctl_lun *lun;
7024	int i, pc, page_code, subpage;
7025	int alloc_len, total_len;
7026	struct ctl_page_index *page_index;
7027	struct scsi_log_sense *cdb;
7028	struct scsi_log_header *header;
7029
7030	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
7031
7032	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7033	cdb = (struct scsi_log_sense *)ctsio->cdb;
7034	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
7035	page_code = cdb->page & SLS_PAGE_CODE;
7036	subpage = cdb->subpage;
7037	alloc_len = scsi_2btoul(cdb->length);
7038
7039	page_index = NULL;
7040	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
7041		page_index = &lun->log_pages.index[i];
7042
7043		/* Look for the right page code */
7044		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
7045			continue;
7046
7047		/* Look for the right subpage or the subpage wildcard*/
7048		if (page_index->subpage != subpage)
7049			continue;
7050
7051		break;
7052	}
7053	if (i >= CTL_NUM_LOG_PAGES) {
7054		ctl_set_invalid_field(ctsio,
7055				      /*sks_valid*/ 1,
7056				      /*command*/ 1,
7057				      /*field*/ 2,
7058				      /*bit_valid*/ 0,
7059				      /*bit*/ 0);
7060		ctl_done((union ctl_io *)ctsio);
7061		return (CTL_RETVAL_COMPLETE);
7062	}
7063
7064	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
7065
7066	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7067	ctsio->kern_sg_entries = 0;
7068	ctsio->kern_data_resid = 0;
7069	ctsio->kern_rel_offset = 0;
7070	if (total_len < alloc_len) {
7071		ctsio->residual = alloc_len - total_len;
7072		ctsio->kern_data_len = total_len;
7073		ctsio->kern_total_len = total_len;
7074	} else {
7075		ctsio->residual = 0;
7076		ctsio->kern_data_len = alloc_len;
7077		ctsio->kern_total_len = alloc_len;
7078	}
7079
7080	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7081	header->page = page_index->page_code;
7082	if (page_index->subpage) {
7083		header->page |= SL_SPF;
7084		header->subpage = page_index->subpage;
7085	}
7086	scsi_ulto2b(page_index->page_len, header->datalen);
7087
7088	/*
7089	 * Call the handler, if it exists, to update the
7090	 * page to the latest values.
7091	 */
7092	if (page_index->sense_handler != NULL)
7093		page_index->sense_handler(ctsio, page_index, pc);
7094
7095	memcpy(header + 1, page_index->page_data, page_index->page_len);
7096
7097	ctl_set_success(ctsio);
7098	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7099	ctsio->be_move_done = ctl_config_move_done;
7100	ctl_datamove((union ctl_io *)ctsio);
7101	return (CTL_RETVAL_COMPLETE);
7102}
7103
7104int
7105ctl_read_capacity(struct ctl_scsiio *ctsio)
7106{
7107	struct scsi_read_capacity *cdb;
7108	struct scsi_read_capacity_data *data;
7109	struct ctl_lun *lun;
7110	uint32_t lba;
7111
7112	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7113
7114	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7115
7116	lba = scsi_4btoul(cdb->addr);
7117	if (((cdb->pmi & SRC_PMI) == 0)
7118	 && (lba != 0)) {
7119		ctl_set_invalid_field(/*ctsio*/ ctsio,
7120				      /*sks_valid*/ 1,
7121				      /*command*/ 1,
7122				      /*field*/ 2,
7123				      /*bit_valid*/ 0,
7124				      /*bit*/ 0);
7125		ctl_done((union ctl_io *)ctsio);
7126		return (CTL_RETVAL_COMPLETE);
7127	}
7128
7129	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7130
7131	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7132	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7133	ctsio->residual = 0;
7134	ctsio->kern_data_len = sizeof(*data);
7135	ctsio->kern_total_len = sizeof(*data);
7136	ctsio->kern_data_resid = 0;
7137	ctsio->kern_rel_offset = 0;
7138	ctsio->kern_sg_entries = 0;
7139
7140	/*
7141	 * If the maximum LBA is greater than 0xfffffffe, the user must
7142	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7143	 * serivce action set.
7144	 */
7145	if (lun->be_lun->maxlba > 0xfffffffe)
7146		scsi_ulto4b(0xffffffff, data->addr);
7147	else
7148		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7149
7150	/*
7151	 * XXX KDM this may not be 512 bytes...
7152	 */
7153	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7154
7155	ctl_set_success(ctsio);
7156	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7157	ctsio->be_move_done = ctl_config_move_done;
7158	ctl_datamove((union ctl_io *)ctsio);
7159	return (CTL_RETVAL_COMPLETE);
7160}
7161
7162int
7163ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7164{
7165	struct scsi_read_capacity_16 *cdb;
7166	struct scsi_read_capacity_data_long *data;
7167	struct ctl_lun *lun;
7168	uint64_t lba;
7169	uint32_t alloc_len;
7170
7171	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7172
7173	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7174
7175	alloc_len = scsi_4btoul(cdb->alloc_len);
7176	lba = scsi_8btou64(cdb->addr);
7177
7178	if ((cdb->reladr & SRC16_PMI)
7179	 && (lba != 0)) {
7180		ctl_set_invalid_field(/*ctsio*/ ctsio,
7181				      /*sks_valid*/ 1,
7182				      /*command*/ 1,
7183				      /*field*/ 2,
7184				      /*bit_valid*/ 0,
7185				      /*bit*/ 0);
7186		ctl_done((union ctl_io *)ctsio);
7187		return (CTL_RETVAL_COMPLETE);
7188	}
7189
7190	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7191
7192	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7193	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7194
7195	if (sizeof(*data) < alloc_len) {
7196		ctsio->residual = alloc_len - sizeof(*data);
7197		ctsio->kern_data_len = sizeof(*data);
7198		ctsio->kern_total_len = sizeof(*data);
7199	} else {
7200		ctsio->residual = 0;
7201		ctsio->kern_data_len = alloc_len;
7202		ctsio->kern_total_len = alloc_len;
7203	}
7204	ctsio->kern_data_resid = 0;
7205	ctsio->kern_rel_offset = 0;
7206	ctsio->kern_sg_entries = 0;
7207
7208	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7209	/* XXX KDM this may not be 512 bytes... */
7210	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7211	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7212	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7213	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7214		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7215
7216	ctl_set_success(ctsio);
7217	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7218	ctsio->be_move_done = ctl_config_move_done;
7219	ctl_datamove((union ctl_io *)ctsio);
7220	return (CTL_RETVAL_COMPLETE);
7221}
7222
7223int
7224ctl_get_lba_status(struct ctl_scsiio *ctsio)
7225{
7226	struct scsi_get_lba_status *cdb;
7227	struct scsi_get_lba_status_data *data;
7228	struct ctl_lun *lun;
7229	struct ctl_lba_len_flags *lbalen;
7230	uint64_t lba;
7231	uint32_t alloc_len, total_len;
7232	int retval;
7233
7234	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7235
7236	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7237	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7238	lba = scsi_8btou64(cdb->addr);
7239	alloc_len = scsi_4btoul(cdb->alloc_len);
7240
7241	if (lba > lun->be_lun->maxlba) {
7242		ctl_set_lba_out_of_range(ctsio);
7243		ctl_done((union ctl_io *)ctsio);
7244		return (CTL_RETVAL_COMPLETE);
7245	}
7246
7247	total_len = sizeof(*data) + sizeof(data->descr[0]);
7248	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7249	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7250
7251	if (total_len < alloc_len) {
7252		ctsio->residual = alloc_len - total_len;
7253		ctsio->kern_data_len = total_len;
7254		ctsio->kern_total_len = total_len;
7255	} else {
7256		ctsio->residual = 0;
7257		ctsio->kern_data_len = alloc_len;
7258		ctsio->kern_total_len = alloc_len;
7259	}
7260	ctsio->kern_data_resid = 0;
7261	ctsio->kern_rel_offset = 0;
7262	ctsio->kern_sg_entries = 0;
7263
7264	/* Fill dummy data in case backend can't tell anything. */
7265	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7266	scsi_u64to8b(lba, data->descr[0].addr);
7267	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7268	    data->descr[0].length);
7269	data->descr[0].status = 0; /* Mapped or unknown. */
7270
7271	ctl_set_success(ctsio);
7272	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7273	ctsio->be_move_done = ctl_config_move_done;
7274
7275	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7276	lbalen->lba = lba;
7277	lbalen->len = total_len;
7278	lbalen->flags = 0;
7279	retval = lun->backend->config_read((union ctl_io *)ctsio);
7280	return (CTL_RETVAL_COMPLETE);
7281}
7282
7283int
7284ctl_read_defect(struct ctl_scsiio *ctsio)
7285{
7286	struct scsi_read_defect_data_10 *ccb10;
7287	struct scsi_read_defect_data_12 *ccb12;
7288	struct scsi_read_defect_data_hdr_10 *data10;
7289	struct scsi_read_defect_data_hdr_12 *data12;
7290	uint32_t alloc_len, data_len;
7291	uint8_t format;
7292
7293	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7294
7295	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7296		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7297		format = ccb10->format;
7298		alloc_len = scsi_2btoul(ccb10->alloc_length);
7299		data_len = sizeof(*data10);
7300	} else {
7301		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7302		format = ccb12->format;
7303		alloc_len = scsi_4btoul(ccb12->alloc_length);
7304		data_len = sizeof(*data12);
7305	}
7306	if (alloc_len == 0) {
7307		ctl_set_success(ctsio);
7308		ctl_done((union ctl_io *)ctsio);
7309		return (CTL_RETVAL_COMPLETE);
7310	}
7311
7312	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7313	if (data_len < alloc_len) {
7314		ctsio->residual = alloc_len - data_len;
7315		ctsio->kern_data_len = data_len;
7316		ctsio->kern_total_len = data_len;
7317	} else {
7318		ctsio->residual = 0;
7319		ctsio->kern_data_len = alloc_len;
7320		ctsio->kern_total_len = alloc_len;
7321	}
7322	ctsio->kern_data_resid = 0;
7323	ctsio->kern_rel_offset = 0;
7324	ctsio->kern_sg_entries = 0;
7325
7326	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7327		data10 = (struct scsi_read_defect_data_hdr_10 *)
7328		    ctsio->kern_data_ptr;
7329		data10->format = format;
7330		scsi_ulto2b(0, data10->length);
7331	} else {
7332		data12 = (struct scsi_read_defect_data_hdr_12 *)
7333		    ctsio->kern_data_ptr;
7334		data12->format = format;
7335		scsi_ulto2b(0, data12->generation);
7336		scsi_ulto4b(0, data12->length);
7337	}
7338
7339	ctl_set_success(ctsio);
7340	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7341	ctsio->be_move_done = ctl_config_move_done;
7342	ctl_datamove((union ctl_io *)ctsio);
7343	return (CTL_RETVAL_COMPLETE);
7344}
7345
7346int
7347ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7348{
7349	struct scsi_maintenance_in *cdb;
7350	int retval;
7351	int alloc_len, ext, total_len = 0, g, p, pc, pg, gs, os;
7352	int num_target_port_groups, num_target_ports;
7353	struct ctl_lun *lun;
7354	struct ctl_softc *softc;
7355	struct ctl_port *port;
7356	struct scsi_target_group_data *rtg_ptr;
7357	struct scsi_target_group_data_extended *rtg_ext_ptr;
7358	struct scsi_target_port_group_descriptor *tpg_desc;
7359
7360	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7361
7362	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7363	softc = control_softc;
7364	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7365
7366	retval = CTL_RETVAL_COMPLETE;
7367
7368	switch (cdb->byte2 & STG_PDF_MASK) {
7369	case STG_PDF_LENGTH:
7370		ext = 0;
7371		break;
7372	case STG_PDF_EXTENDED:
7373		ext = 1;
7374		break;
7375	default:
7376		ctl_set_invalid_field(/*ctsio*/ ctsio,
7377				      /*sks_valid*/ 1,
7378				      /*command*/ 1,
7379				      /*field*/ 2,
7380				      /*bit_valid*/ 1,
7381				      /*bit*/ 5);
7382		ctl_done((union ctl_io *)ctsio);
7383		return(retval);
7384	}
7385
7386	if (softc->is_single)
7387		num_target_port_groups = 1;
7388	else
7389		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7390	num_target_ports = 0;
7391	mtx_lock(&softc->ctl_lock);
7392	STAILQ_FOREACH(port, &softc->port_list, links) {
7393		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7394			continue;
7395		if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7396			continue;
7397		num_target_ports++;
7398	}
7399	mtx_unlock(&softc->ctl_lock);
7400
7401	if (ext)
7402		total_len = sizeof(struct scsi_target_group_data_extended);
7403	else
7404		total_len = sizeof(struct scsi_target_group_data);
7405	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7406		num_target_port_groups +
7407	    sizeof(struct scsi_target_port_descriptor) *
7408		num_target_ports * num_target_port_groups;
7409
7410	alloc_len = scsi_4btoul(cdb->length);
7411
7412	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7413
7414	ctsio->kern_sg_entries = 0;
7415
7416	if (total_len < alloc_len) {
7417		ctsio->residual = alloc_len - total_len;
7418		ctsio->kern_data_len = total_len;
7419		ctsio->kern_total_len = total_len;
7420	} else {
7421		ctsio->residual = 0;
7422		ctsio->kern_data_len = alloc_len;
7423		ctsio->kern_total_len = alloc_len;
7424	}
7425	ctsio->kern_data_resid = 0;
7426	ctsio->kern_rel_offset = 0;
7427
7428	if (ext) {
7429		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7430		    ctsio->kern_data_ptr;
7431		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7432		rtg_ext_ptr->format_type = 0x10;
7433		rtg_ext_ptr->implicit_transition_time = 0;
7434		tpg_desc = &rtg_ext_ptr->groups[0];
7435	} else {
7436		rtg_ptr = (struct scsi_target_group_data *)
7437		    ctsio->kern_data_ptr;
7438		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7439		tpg_desc = &rtg_ptr->groups[0];
7440	}
7441
7442	mtx_lock(&softc->ctl_lock);
7443	pg = softc->port_offset / CTL_MAX_PORTS;
7444	if (softc->flags & CTL_FLAG_ACTIVE_SHELF) {
7445		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY) {
7446			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7447			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7448		} else if (lun->flags & CTL_LUN_PRIMARY_SC) {
7449			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7450			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7451		} else {
7452			gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7453			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7454		}
7455	} else {
7456		gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7457		os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7458	}
7459	for (g = 0; g < num_target_port_groups; g++) {
7460		tpg_desc->pref_state = (g == pg) ? gs : os;
7461		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP;
7462		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7463		tpg_desc->status = TPG_IMPLICIT;
7464		pc = 0;
7465		STAILQ_FOREACH(port, &softc->port_list, links) {
7466			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7467				continue;
7468			if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7469			    CTL_MAX_LUNS)
7470				continue;
7471			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7472			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7473			    relative_target_port_identifier);
7474			pc++;
7475		}
7476		tpg_desc->target_port_count = pc;
7477		tpg_desc = (struct scsi_target_port_group_descriptor *)
7478		    &tpg_desc->descriptors[pc];
7479	}
7480	mtx_unlock(&softc->ctl_lock);
7481
7482	ctl_set_success(ctsio);
7483	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7484	ctsio->be_move_done = ctl_config_move_done;
7485	ctl_datamove((union ctl_io *)ctsio);
7486	return(retval);
7487}
7488
7489int
7490ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7491{
7492	struct ctl_lun *lun;
7493	struct scsi_report_supported_opcodes *cdb;
7494	const struct ctl_cmd_entry *entry, *sentry;
7495	struct scsi_report_supported_opcodes_all *all;
7496	struct scsi_report_supported_opcodes_descr *descr;
7497	struct scsi_report_supported_opcodes_one *one;
7498	int retval;
7499	int alloc_len, total_len;
7500	int opcode, service_action, i, j, num;
7501
7502	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7503
7504	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7505	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7506
7507	retval = CTL_RETVAL_COMPLETE;
7508
7509	opcode = cdb->requested_opcode;
7510	service_action = scsi_2btoul(cdb->requested_service_action);
7511	switch (cdb->options & RSO_OPTIONS_MASK) {
7512	case RSO_OPTIONS_ALL:
7513		num = 0;
7514		for (i = 0; i < 256; i++) {
7515			entry = &ctl_cmd_table[i];
7516			if (entry->flags & CTL_CMD_FLAG_SA5) {
7517				for (j = 0; j < 32; j++) {
7518					sentry = &((const struct ctl_cmd_entry *)
7519					    entry->execute)[j];
7520					if (ctl_cmd_applicable(
7521					    lun->be_lun->lun_type, sentry))
7522						num++;
7523				}
7524			} else {
7525				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7526				    entry))
7527					num++;
7528			}
7529		}
7530		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7531		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7532		break;
7533	case RSO_OPTIONS_OC:
7534		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7535			ctl_set_invalid_field(/*ctsio*/ ctsio,
7536					      /*sks_valid*/ 1,
7537					      /*command*/ 1,
7538					      /*field*/ 2,
7539					      /*bit_valid*/ 1,
7540					      /*bit*/ 2);
7541			ctl_done((union ctl_io *)ctsio);
7542			return (CTL_RETVAL_COMPLETE);
7543		}
7544		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7545		break;
7546	case RSO_OPTIONS_OC_SA:
7547		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7548		    service_action >= 32) {
7549			ctl_set_invalid_field(/*ctsio*/ ctsio,
7550					      /*sks_valid*/ 1,
7551					      /*command*/ 1,
7552					      /*field*/ 2,
7553					      /*bit_valid*/ 1,
7554					      /*bit*/ 2);
7555			ctl_done((union ctl_io *)ctsio);
7556			return (CTL_RETVAL_COMPLETE);
7557		}
7558		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7559		break;
7560	default:
7561		ctl_set_invalid_field(/*ctsio*/ ctsio,
7562				      /*sks_valid*/ 1,
7563				      /*command*/ 1,
7564				      /*field*/ 2,
7565				      /*bit_valid*/ 1,
7566				      /*bit*/ 2);
7567		ctl_done((union ctl_io *)ctsio);
7568		return (CTL_RETVAL_COMPLETE);
7569	}
7570
7571	alloc_len = scsi_4btoul(cdb->length);
7572
7573	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7574
7575	ctsio->kern_sg_entries = 0;
7576
7577	if (total_len < alloc_len) {
7578		ctsio->residual = alloc_len - total_len;
7579		ctsio->kern_data_len = total_len;
7580		ctsio->kern_total_len = total_len;
7581	} else {
7582		ctsio->residual = 0;
7583		ctsio->kern_data_len = alloc_len;
7584		ctsio->kern_total_len = alloc_len;
7585	}
7586	ctsio->kern_data_resid = 0;
7587	ctsio->kern_rel_offset = 0;
7588
7589	switch (cdb->options & RSO_OPTIONS_MASK) {
7590	case RSO_OPTIONS_ALL:
7591		all = (struct scsi_report_supported_opcodes_all *)
7592		    ctsio->kern_data_ptr;
7593		num = 0;
7594		for (i = 0; i < 256; i++) {
7595			entry = &ctl_cmd_table[i];
7596			if (entry->flags & CTL_CMD_FLAG_SA5) {
7597				for (j = 0; j < 32; j++) {
7598					sentry = &((const struct ctl_cmd_entry *)
7599					    entry->execute)[j];
7600					if (!ctl_cmd_applicable(
7601					    lun->be_lun->lun_type, sentry))
7602						continue;
7603					descr = &all->descr[num++];
7604					descr->opcode = i;
7605					scsi_ulto2b(j, descr->service_action);
7606					descr->flags = RSO_SERVACTV;
7607					scsi_ulto2b(sentry->length,
7608					    descr->cdb_length);
7609				}
7610			} else {
7611				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7612				    entry))
7613					continue;
7614				descr = &all->descr[num++];
7615				descr->opcode = i;
7616				scsi_ulto2b(0, descr->service_action);
7617				descr->flags = 0;
7618				scsi_ulto2b(entry->length, descr->cdb_length);
7619			}
7620		}
7621		scsi_ulto4b(
7622		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7623		    all->length);
7624		break;
7625	case RSO_OPTIONS_OC:
7626		one = (struct scsi_report_supported_opcodes_one *)
7627		    ctsio->kern_data_ptr;
7628		entry = &ctl_cmd_table[opcode];
7629		goto fill_one;
7630	case RSO_OPTIONS_OC_SA:
7631		one = (struct scsi_report_supported_opcodes_one *)
7632		    ctsio->kern_data_ptr;
7633		entry = &ctl_cmd_table[opcode];
7634		entry = &((const struct ctl_cmd_entry *)
7635		    entry->execute)[service_action];
7636fill_one:
7637		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7638			one->support = 3;
7639			scsi_ulto2b(entry->length, one->cdb_length);
7640			one->cdb_usage[0] = opcode;
7641			memcpy(&one->cdb_usage[1], entry->usage,
7642			    entry->length - 1);
7643		} else
7644			one->support = 1;
7645		break;
7646	}
7647
7648	ctl_set_success(ctsio);
7649	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7650	ctsio->be_move_done = ctl_config_move_done;
7651	ctl_datamove((union ctl_io *)ctsio);
7652	return(retval);
7653}
7654
7655int
7656ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7657{
7658	struct scsi_report_supported_tmf *cdb;
7659	struct scsi_report_supported_tmf_data *data;
7660	int retval;
7661	int alloc_len, total_len;
7662
7663	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7664
7665	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7666
7667	retval = CTL_RETVAL_COMPLETE;
7668
7669	total_len = sizeof(struct scsi_report_supported_tmf_data);
7670	alloc_len = scsi_4btoul(cdb->length);
7671
7672	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7673
7674	ctsio->kern_sg_entries = 0;
7675
7676	if (total_len < alloc_len) {
7677		ctsio->residual = alloc_len - total_len;
7678		ctsio->kern_data_len = total_len;
7679		ctsio->kern_total_len = total_len;
7680	} else {
7681		ctsio->residual = 0;
7682		ctsio->kern_data_len = alloc_len;
7683		ctsio->kern_total_len = alloc_len;
7684	}
7685	ctsio->kern_data_resid = 0;
7686	ctsio->kern_rel_offset = 0;
7687
7688	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7689	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7690	data->byte2 |= RST_ITNRS;
7691
7692	ctl_set_success(ctsio);
7693	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7694	ctsio->be_move_done = ctl_config_move_done;
7695	ctl_datamove((union ctl_io *)ctsio);
7696	return (retval);
7697}
7698
7699int
7700ctl_report_timestamp(struct ctl_scsiio *ctsio)
7701{
7702	struct scsi_report_timestamp *cdb;
7703	struct scsi_report_timestamp_data *data;
7704	struct timeval tv;
7705	int64_t timestamp;
7706	int retval;
7707	int alloc_len, total_len;
7708
7709	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7710
7711	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7712
7713	retval = CTL_RETVAL_COMPLETE;
7714
7715	total_len = sizeof(struct scsi_report_timestamp_data);
7716	alloc_len = scsi_4btoul(cdb->length);
7717
7718	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7719
7720	ctsio->kern_sg_entries = 0;
7721
7722	if (total_len < alloc_len) {
7723		ctsio->residual = alloc_len - total_len;
7724		ctsio->kern_data_len = total_len;
7725		ctsio->kern_total_len = total_len;
7726	} else {
7727		ctsio->residual = 0;
7728		ctsio->kern_data_len = alloc_len;
7729		ctsio->kern_total_len = alloc_len;
7730	}
7731	ctsio->kern_data_resid = 0;
7732	ctsio->kern_rel_offset = 0;
7733
7734	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7735	scsi_ulto2b(sizeof(*data) - 2, data->length);
7736	data->origin = RTS_ORIG_OUTSIDE;
7737	getmicrotime(&tv);
7738	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7739	scsi_ulto4b(timestamp >> 16, data->timestamp);
7740	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7741
7742	ctl_set_success(ctsio);
7743	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7744	ctsio->be_move_done = ctl_config_move_done;
7745	ctl_datamove((union ctl_io *)ctsio);
7746	return (retval);
7747}
7748
7749int
7750ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7751{
7752	struct scsi_per_res_in *cdb;
7753	int alloc_len, total_len = 0;
7754	/* struct scsi_per_res_in_rsrv in_data; */
7755	struct ctl_lun *lun;
7756	struct ctl_softc *softc;
7757	uint64_t key;
7758
7759	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7760
7761	softc = control_softc;
7762
7763	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7764
7765	alloc_len = scsi_2btoul(cdb->length);
7766
7767	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7768
7769retry:
7770	mtx_lock(&lun->lun_lock);
7771	switch (cdb->action) {
7772	case SPRI_RK: /* read keys */
7773		total_len = sizeof(struct scsi_per_res_in_keys) +
7774			lun->pr_key_count *
7775			sizeof(struct scsi_per_res_key);
7776		break;
7777	case SPRI_RR: /* read reservation */
7778		if (lun->flags & CTL_LUN_PR_RESERVED)
7779			total_len = sizeof(struct scsi_per_res_in_rsrv);
7780		else
7781			total_len = sizeof(struct scsi_per_res_in_header);
7782		break;
7783	case SPRI_RC: /* report capabilities */
7784		total_len = sizeof(struct scsi_per_res_cap);
7785		break;
7786	case SPRI_RS: /* read full status */
7787		total_len = sizeof(struct scsi_per_res_in_header) +
7788		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7789		    lun->pr_key_count;
7790		break;
7791	default:
7792		panic("Invalid PR type %x", cdb->action);
7793	}
7794	mtx_unlock(&lun->lun_lock);
7795
7796	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7797
7798	if (total_len < alloc_len) {
7799		ctsio->residual = alloc_len - total_len;
7800		ctsio->kern_data_len = total_len;
7801		ctsio->kern_total_len = total_len;
7802	} else {
7803		ctsio->residual = 0;
7804		ctsio->kern_data_len = alloc_len;
7805		ctsio->kern_total_len = alloc_len;
7806	}
7807
7808	ctsio->kern_data_resid = 0;
7809	ctsio->kern_rel_offset = 0;
7810	ctsio->kern_sg_entries = 0;
7811
7812	mtx_lock(&lun->lun_lock);
7813	switch (cdb->action) {
7814	case SPRI_RK: { // read keys
7815        struct scsi_per_res_in_keys *res_keys;
7816		int i, key_count;
7817
7818		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7819
7820		/*
7821		 * We had to drop the lock to allocate our buffer, which
7822		 * leaves time for someone to come in with another
7823		 * persistent reservation.  (That is unlikely, though,
7824		 * since this should be the only persistent reservation
7825		 * command active right now.)
7826		 */
7827		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7828		    (lun->pr_key_count *
7829		     sizeof(struct scsi_per_res_key)))){
7830			mtx_unlock(&lun->lun_lock);
7831			free(ctsio->kern_data_ptr, M_CTL);
7832			printf("%s: reservation length changed, retrying\n",
7833			       __func__);
7834			goto retry;
7835		}
7836
7837		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7838
7839		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7840			     lun->pr_key_count, res_keys->header.length);
7841
7842		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7843			if ((key = ctl_get_prkey(lun, i)) == 0)
7844				continue;
7845
7846			/*
7847			 * We used lun->pr_key_count to calculate the
7848			 * size to allocate.  If it turns out the number of
7849			 * initiators with the registered flag set is
7850			 * larger than that (i.e. they haven't been kept in
7851			 * sync), we've got a problem.
7852			 */
7853			if (key_count >= lun->pr_key_count) {
7854#ifdef NEEDTOPORT
7855				csevent_log(CSC_CTL | CSC_SHELF_SW |
7856					    CTL_PR_ERROR,
7857					    csevent_LogType_Fault,
7858					    csevent_AlertLevel_Yellow,
7859					    csevent_FRU_ShelfController,
7860					    csevent_FRU_Firmware,
7861				        csevent_FRU_Unknown,
7862					    "registered keys %d >= key "
7863					    "count %d", key_count,
7864					    lun->pr_key_count);
7865#endif
7866				key_count++;
7867				continue;
7868			}
7869			scsi_u64to8b(key, res_keys->keys[key_count].key);
7870			key_count++;
7871		}
7872		break;
7873	}
7874	case SPRI_RR: { // read reservation
7875		struct scsi_per_res_in_rsrv *res;
7876		int tmp_len, header_only;
7877
7878		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7879
7880		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7881
7882		if (lun->flags & CTL_LUN_PR_RESERVED)
7883		{
7884			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7885			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7886				    res->header.length);
7887			header_only = 0;
7888		} else {
7889			tmp_len = sizeof(struct scsi_per_res_in_header);
7890			scsi_ulto4b(0, res->header.length);
7891			header_only = 1;
7892		}
7893
7894		/*
7895		 * We had to drop the lock to allocate our buffer, which
7896		 * leaves time for someone to come in with another
7897		 * persistent reservation.  (That is unlikely, though,
7898		 * since this should be the only persistent reservation
7899		 * command active right now.)
7900		 */
7901		if (tmp_len != total_len) {
7902			mtx_unlock(&lun->lun_lock);
7903			free(ctsio->kern_data_ptr, M_CTL);
7904			printf("%s: reservation status changed, retrying\n",
7905			       __func__);
7906			goto retry;
7907		}
7908
7909		/*
7910		 * No reservation held, so we're done.
7911		 */
7912		if (header_only != 0)
7913			break;
7914
7915		/*
7916		 * If the registration is an All Registrants type, the key
7917		 * is 0, since it doesn't really matter.
7918		 */
7919		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7920			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7921			    res->data.reservation);
7922		}
7923		res->data.scopetype = lun->res_type;
7924		break;
7925	}
7926	case SPRI_RC:     //report capabilities
7927	{
7928		struct scsi_per_res_cap *res_cap;
7929		uint16_t type_mask;
7930
7931		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7932		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7933		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7934		type_mask = SPRI_TM_WR_EX_AR |
7935			    SPRI_TM_EX_AC_RO |
7936			    SPRI_TM_WR_EX_RO |
7937			    SPRI_TM_EX_AC |
7938			    SPRI_TM_WR_EX |
7939			    SPRI_TM_EX_AC_AR;
7940		scsi_ulto2b(type_mask, res_cap->type_mask);
7941		break;
7942	}
7943	case SPRI_RS: { // read full status
7944		struct scsi_per_res_in_full *res_status;
7945		struct scsi_per_res_in_full_desc *res_desc;
7946		struct ctl_port *port;
7947		int i, len;
7948
7949		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7950
7951		/*
7952		 * We had to drop the lock to allocate our buffer, which
7953		 * leaves time for someone to come in with another
7954		 * persistent reservation.  (That is unlikely, though,
7955		 * since this should be the only persistent reservation
7956		 * command active right now.)
7957		 */
7958		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7959		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7960		     lun->pr_key_count)){
7961			mtx_unlock(&lun->lun_lock);
7962			free(ctsio->kern_data_ptr, M_CTL);
7963			printf("%s: reservation length changed, retrying\n",
7964			       __func__);
7965			goto retry;
7966		}
7967
7968		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7969
7970		res_desc = &res_status->desc[0];
7971		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7972			if ((key = ctl_get_prkey(lun, i)) == 0)
7973				continue;
7974
7975			scsi_u64to8b(key, res_desc->res_key.key);
7976			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7977			    (lun->pr_res_idx == i ||
7978			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7979				res_desc->flags = SPRI_FULL_R_HOLDER;
7980				res_desc->scopetype = lun->res_type;
7981			}
7982			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7983			    res_desc->rel_trgt_port_id);
7984			len = 0;
7985			port = softc->ctl_ports[
7986			    ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
7987			if (port != NULL)
7988				len = ctl_create_iid(port,
7989				    i % CTL_MAX_INIT_PER_PORT,
7990				    res_desc->transport_id);
7991			scsi_ulto4b(len, res_desc->additional_length);
7992			res_desc = (struct scsi_per_res_in_full_desc *)
7993			    &res_desc->transport_id[len];
7994		}
7995		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7996		    res_status->header.length);
7997		break;
7998	}
7999	default:
8000		/*
8001		 * This is a bug, because we just checked for this above,
8002		 * and should have returned an error.
8003		 */
8004		panic("Invalid PR type %x", cdb->action);
8005		break; /* NOTREACHED */
8006	}
8007	mtx_unlock(&lun->lun_lock);
8008
8009	ctl_set_success(ctsio);
8010	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8011	ctsio->be_move_done = ctl_config_move_done;
8012	ctl_datamove((union ctl_io *)ctsio);
8013	return (CTL_RETVAL_COMPLETE);
8014}
8015
8016static void
8017ctl_est_res_ua(struct ctl_lun *lun, uint32_t residx, ctl_ua_type ua)
8018{
8019	int off = lun->ctl_softc->persis_offset;
8020
8021	if (residx >= off && residx < off + CTL_MAX_INITIATORS)
8022		ctl_est_ua(lun, residx - off, ua);
8023}
8024
8025/*
8026 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
8027 * it should return.
8028 */
8029static int
8030ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
8031		uint64_t sa_res_key, uint8_t type, uint32_t residx,
8032		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
8033		struct scsi_per_res_out_parms* param)
8034{
8035	union ctl_ha_msg persis_io;
8036	int retval, i;
8037	int isc_retval;
8038
8039	retval = 0;
8040
8041	mtx_lock(&lun->lun_lock);
8042	if (sa_res_key == 0) {
8043		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8044			/* validate scope and type */
8045			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8046			     SPR_LU_SCOPE) {
8047				mtx_unlock(&lun->lun_lock);
8048				ctl_set_invalid_field(/*ctsio*/ ctsio,
8049						      /*sks_valid*/ 1,
8050						      /*command*/ 1,
8051						      /*field*/ 2,
8052						      /*bit_valid*/ 1,
8053						      /*bit*/ 4);
8054				ctl_done((union ctl_io *)ctsio);
8055				return (1);
8056			}
8057
8058		        if (type>8 || type==2 || type==4 || type==0) {
8059				mtx_unlock(&lun->lun_lock);
8060				ctl_set_invalid_field(/*ctsio*/ ctsio,
8061       	           				      /*sks_valid*/ 1,
8062						      /*command*/ 1,
8063						      /*field*/ 2,
8064						      /*bit_valid*/ 1,
8065						      /*bit*/ 0);
8066				ctl_done((union ctl_io *)ctsio);
8067				return (1);
8068		        }
8069
8070			/*
8071			 * Unregister everybody else and build UA for
8072			 * them
8073			 */
8074			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8075				if (i == residx || ctl_get_prkey(lun, i) == 0)
8076					continue;
8077
8078				ctl_clr_prkey(lun, i);
8079				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8080			}
8081			lun->pr_key_count = 1;
8082			lun->res_type = type;
8083			if (lun->res_type != SPR_TYPE_WR_EX_AR
8084			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8085				lun->pr_res_idx = residx;
8086
8087			/* send msg to other side */
8088			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8089			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8090			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8091			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8092			persis_io.pr.pr_info.res_type = type;
8093			memcpy(persis_io.pr.pr_info.sa_res_key,
8094			       param->serv_act_res_key,
8095			       sizeof(param->serv_act_res_key));
8096			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8097			     &persis_io, sizeof(persis_io), 0)) >
8098			     CTL_HA_STATUS_SUCCESS) {
8099				printf("CTL:Persis Out error returned "
8100				       "from ctl_ha_msg_send %d\n",
8101				       isc_retval);
8102			}
8103		} else {
8104			/* not all registrants */
8105			mtx_unlock(&lun->lun_lock);
8106			free(ctsio->kern_data_ptr, M_CTL);
8107			ctl_set_invalid_field(ctsio,
8108					      /*sks_valid*/ 1,
8109					      /*command*/ 0,
8110					      /*field*/ 8,
8111					      /*bit_valid*/ 0,
8112					      /*bit*/ 0);
8113			ctl_done((union ctl_io *)ctsio);
8114			return (1);
8115		}
8116	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8117		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8118		int found = 0;
8119
8120		if (res_key == sa_res_key) {
8121			/* special case */
8122			/*
8123			 * The spec implies this is not good but doesn't
8124			 * say what to do. There are two choices either
8125			 * generate a res conflict or check condition
8126			 * with illegal field in parameter data. Since
8127			 * that is what is done when the sa_res_key is
8128			 * zero I'll take that approach since this has
8129			 * to do with the sa_res_key.
8130			 */
8131			mtx_unlock(&lun->lun_lock);
8132			free(ctsio->kern_data_ptr, M_CTL);
8133			ctl_set_invalid_field(ctsio,
8134					      /*sks_valid*/ 1,
8135					      /*command*/ 0,
8136					      /*field*/ 8,
8137					      /*bit_valid*/ 0,
8138					      /*bit*/ 0);
8139			ctl_done((union ctl_io *)ctsio);
8140			return (1);
8141		}
8142
8143		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8144			if (ctl_get_prkey(lun, i) != sa_res_key)
8145				continue;
8146
8147			found = 1;
8148			ctl_clr_prkey(lun, i);
8149			lun->pr_key_count--;
8150			ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8151		}
8152		if (!found) {
8153			mtx_unlock(&lun->lun_lock);
8154			free(ctsio->kern_data_ptr, M_CTL);
8155			ctl_set_reservation_conflict(ctsio);
8156			ctl_done((union ctl_io *)ctsio);
8157			return (CTL_RETVAL_COMPLETE);
8158		}
8159		/* send msg to other side */
8160		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8161		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8162		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8163		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8164		persis_io.pr.pr_info.res_type = type;
8165		memcpy(persis_io.pr.pr_info.sa_res_key,
8166		       param->serv_act_res_key,
8167		       sizeof(param->serv_act_res_key));
8168		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8169		     &persis_io, sizeof(persis_io), 0)) >
8170		     CTL_HA_STATUS_SUCCESS) {
8171			printf("CTL:Persis Out error returned from "
8172			       "ctl_ha_msg_send %d\n", isc_retval);
8173		}
8174	} else {
8175		/* Reserved but not all registrants */
8176		/* sa_res_key is res holder */
8177		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
8178			/* validate scope and type */
8179			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8180			     SPR_LU_SCOPE) {
8181				mtx_unlock(&lun->lun_lock);
8182				ctl_set_invalid_field(/*ctsio*/ ctsio,
8183						      /*sks_valid*/ 1,
8184						      /*command*/ 1,
8185						      /*field*/ 2,
8186						      /*bit_valid*/ 1,
8187						      /*bit*/ 4);
8188				ctl_done((union ctl_io *)ctsio);
8189				return (1);
8190			}
8191
8192			if (type>8 || type==2 || type==4 || type==0) {
8193				mtx_unlock(&lun->lun_lock);
8194				ctl_set_invalid_field(/*ctsio*/ ctsio,
8195						      /*sks_valid*/ 1,
8196						      /*command*/ 1,
8197						      /*field*/ 2,
8198						      /*bit_valid*/ 1,
8199						      /*bit*/ 0);
8200				ctl_done((union ctl_io *)ctsio);
8201				return (1);
8202			}
8203
8204			/*
8205			 * Do the following:
8206			 * if sa_res_key != res_key remove all
8207			 * registrants w/sa_res_key and generate UA
8208			 * for these registrants(Registrations
8209			 * Preempted) if it wasn't an exclusive
8210			 * reservation generate UA(Reservations
8211			 * Preempted) for all other registered nexuses
8212			 * if the type has changed. Establish the new
8213			 * reservation and holder. If res_key and
8214			 * sa_res_key are the same do the above
8215			 * except don't unregister the res holder.
8216			 */
8217
8218			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8219				if (i == residx || ctl_get_prkey(lun, i) == 0)
8220					continue;
8221
8222				if (sa_res_key == ctl_get_prkey(lun, i)) {
8223					ctl_clr_prkey(lun, i);
8224					lun->pr_key_count--;
8225					ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8226				} else if (type != lun->res_type
8227					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8228					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8229					ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
8230				}
8231			}
8232			lun->res_type = type;
8233			if (lun->res_type != SPR_TYPE_WR_EX_AR
8234			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8235				lun->pr_res_idx = residx;
8236			else
8237				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8238
8239			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8240			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8241			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8242			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8243			persis_io.pr.pr_info.res_type = type;
8244			memcpy(persis_io.pr.pr_info.sa_res_key,
8245			       param->serv_act_res_key,
8246			       sizeof(param->serv_act_res_key));
8247			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8248			     &persis_io, sizeof(persis_io), 0)) >
8249			     CTL_HA_STATUS_SUCCESS) {
8250				printf("CTL:Persis Out error returned "
8251				       "from ctl_ha_msg_send %d\n",
8252				       isc_retval);
8253			}
8254		} else {
8255			/*
8256			 * sa_res_key is not the res holder just
8257			 * remove registrants
8258			 */
8259			int found=0;
8260
8261			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8262				if (sa_res_key != ctl_get_prkey(lun, i))
8263					continue;
8264
8265				found = 1;
8266				ctl_clr_prkey(lun, i);
8267				lun->pr_key_count--;
8268				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8269			}
8270
8271			if (!found) {
8272				mtx_unlock(&lun->lun_lock);
8273				free(ctsio->kern_data_ptr, M_CTL);
8274				ctl_set_reservation_conflict(ctsio);
8275				ctl_done((union ctl_io *)ctsio);
8276		        	return (1);
8277			}
8278			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8279			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8280			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8281			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8282			persis_io.pr.pr_info.res_type = type;
8283			memcpy(persis_io.pr.pr_info.sa_res_key,
8284			       param->serv_act_res_key,
8285			       sizeof(param->serv_act_res_key));
8286			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8287			     &persis_io, sizeof(persis_io), 0)) >
8288			     CTL_HA_STATUS_SUCCESS) {
8289				printf("CTL:Persis Out error returned "
8290				       "from ctl_ha_msg_send %d\n",
8291				isc_retval);
8292			}
8293		}
8294	}
8295
8296	lun->PRGeneration++;
8297	mtx_unlock(&lun->lun_lock);
8298
8299	return (retval);
8300}
8301
8302static void
8303ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8304{
8305	uint64_t sa_res_key;
8306	int i;
8307
8308	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8309
8310	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8311	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8312	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8313		if (sa_res_key == 0) {
8314			/*
8315			 * Unregister everybody else and build UA for
8316			 * them
8317			 */
8318			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8319				if (i == msg->pr.pr_info.residx ||
8320				    ctl_get_prkey(lun, i) == 0)
8321					continue;
8322
8323				ctl_clr_prkey(lun, i);
8324				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8325			}
8326
8327			lun->pr_key_count = 1;
8328			lun->res_type = msg->pr.pr_info.res_type;
8329			if (lun->res_type != SPR_TYPE_WR_EX_AR
8330			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8331				lun->pr_res_idx = msg->pr.pr_info.residx;
8332		} else {
8333		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8334				if (sa_res_key == ctl_get_prkey(lun, i))
8335					continue;
8336
8337				ctl_clr_prkey(lun, i);
8338				lun->pr_key_count--;
8339				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8340			}
8341		}
8342	} else {
8343		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8344			if (i == msg->pr.pr_info.residx ||
8345			    ctl_get_prkey(lun, i) == 0)
8346				continue;
8347
8348			if (sa_res_key == ctl_get_prkey(lun, i)) {
8349				ctl_clr_prkey(lun, i);
8350				lun->pr_key_count--;
8351				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8352			} else if (msg->pr.pr_info.res_type != lun->res_type
8353				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8354				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8355				ctl_est_res_ua(lun, i, CTL_UA_RES_RELEASE);
8356			}
8357		}
8358		lun->res_type = msg->pr.pr_info.res_type;
8359		if (lun->res_type != SPR_TYPE_WR_EX_AR
8360		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8361			lun->pr_res_idx = msg->pr.pr_info.residx;
8362		else
8363			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8364	}
8365	lun->PRGeneration++;
8366
8367}
8368
8369
8370int
8371ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8372{
8373	int retval;
8374	int isc_retval;
8375	u_int32_t param_len;
8376	struct scsi_per_res_out *cdb;
8377	struct ctl_lun *lun;
8378	struct scsi_per_res_out_parms* param;
8379	struct ctl_softc *softc;
8380	uint32_t residx;
8381	uint64_t res_key, sa_res_key, key;
8382	uint8_t type;
8383	union ctl_ha_msg persis_io;
8384	int    i;
8385
8386	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8387
8388	retval = CTL_RETVAL_COMPLETE;
8389
8390	softc = control_softc;
8391
8392	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8393	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8394
8395	/*
8396	 * We only support whole-LUN scope.  The scope & type are ignored for
8397	 * register, register and ignore existing key and clear.
8398	 * We sometimes ignore scope and type on preempts too!!
8399	 * Verify reservation type here as well.
8400	 */
8401	type = cdb->scope_type & SPR_TYPE_MASK;
8402	if ((cdb->action == SPRO_RESERVE)
8403	 || (cdb->action == SPRO_RELEASE)) {
8404		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8405			ctl_set_invalid_field(/*ctsio*/ ctsio,
8406					      /*sks_valid*/ 1,
8407					      /*command*/ 1,
8408					      /*field*/ 2,
8409					      /*bit_valid*/ 1,
8410					      /*bit*/ 4);
8411			ctl_done((union ctl_io *)ctsio);
8412			return (CTL_RETVAL_COMPLETE);
8413		}
8414
8415		if (type>8 || type==2 || type==4 || type==0) {
8416			ctl_set_invalid_field(/*ctsio*/ ctsio,
8417					      /*sks_valid*/ 1,
8418					      /*command*/ 1,
8419					      /*field*/ 2,
8420					      /*bit_valid*/ 1,
8421					      /*bit*/ 0);
8422			ctl_done((union ctl_io *)ctsio);
8423			return (CTL_RETVAL_COMPLETE);
8424		}
8425	}
8426
8427	param_len = scsi_4btoul(cdb->length);
8428
8429	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8430		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8431		ctsio->kern_data_len = param_len;
8432		ctsio->kern_total_len = param_len;
8433		ctsio->kern_data_resid = 0;
8434		ctsio->kern_rel_offset = 0;
8435		ctsio->kern_sg_entries = 0;
8436		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8437		ctsio->be_move_done = ctl_config_move_done;
8438		ctl_datamove((union ctl_io *)ctsio);
8439
8440		return (CTL_RETVAL_COMPLETE);
8441	}
8442
8443	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8444
8445	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8446	res_key = scsi_8btou64(param->res_key.key);
8447	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8448
8449	/*
8450	 * Validate the reservation key here except for SPRO_REG_IGNO
8451	 * This must be done for all other service actions
8452	 */
8453	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8454		mtx_lock(&lun->lun_lock);
8455		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8456			if (res_key != key) {
8457				/*
8458				 * The current key passed in doesn't match
8459				 * the one the initiator previously
8460				 * registered.
8461				 */
8462				mtx_unlock(&lun->lun_lock);
8463				free(ctsio->kern_data_ptr, M_CTL);
8464				ctl_set_reservation_conflict(ctsio);
8465				ctl_done((union ctl_io *)ctsio);
8466				return (CTL_RETVAL_COMPLETE);
8467			}
8468		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8469			/*
8470			 * We are not registered
8471			 */
8472			mtx_unlock(&lun->lun_lock);
8473			free(ctsio->kern_data_ptr, M_CTL);
8474			ctl_set_reservation_conflict(ctsio);
8475			ctl_done((union ctl_io *)ctsio);
8476			return (CTL_RETVAL_COMPLETE);
8477		} else if (res_key != 0) {
8478			/*
8479			 * We are not registered and trying to register but
8480			 * the register key isn't zero.
8481			 */
8482			mtx_unlock(&lun->lun_lock);
8483			free(ctsio->kern_data_ptr, M_CTL);
8484			ctl_set_reservation_conflict(ctsio);
8485			ctl_done((union ctl_io *)ctsio);
8486			return (CTL_RETVAL_COMPLETE);
8487		}
8488		mtx_unlock(&lun->lun_lock);
8489	}
8490
8491	switch (cdb->action & SPRO_ACTION_MASK) {
8492	case SPRO_REGISTER:
8493	case SPRO_REG_IGNO: {
8494
8495#if 0
8496		printf("Registration received\n");
8497#endif
8498
8499		/*
8500		 * We don't support any of these options, as we report in
8501		 * the read capabilities request (see
8502		 * ctl_persistent_reserve_in(), above).
8503		 */
8504		if ((param->flags & SPR_SPEC_I_PT)
8505		 || (param->flags & SPR_ALL_TG_PT)
8506		 || (param->flags & SPR_APTPL)) {
8507			int bit_ptr;
8508
8509			if (param->flags & SPR_APTPL)
8510				bit_ptr = 0;
8511			else if (param->flags & SPR_ALL_TG_PT)
8512				bit_ptr = 2;
8513			else /* SPR_SPEC_I_PT */
8514				bit_ptr = 3;
8515
8516			free(ctsio->kern_data_ptr, M_CTL);
8517			ctl_set_invalid_field(ctsio,
8518					      /*sks_valid*/ 1,
8519					      /*command*/ 0,
8520					      /*field*/ 20,
8521					      /*bit_valid*/ 1,
8522					      /*bit*/ bit_ptr);
8523			ctl_done((union ctl_io *)ctsio);
8524			return (CTL_RETVAL_COMPLETE);
8525		}
8526
8527		mtx_lock(&lun->lun_lock);
8528
8529		/*
8530		 * The initiator wants to clear the
8531		 * key/unregister.
8532		 */
8533		if (sa_res_key == 0) {
8534			if ((res_key == 0
8535			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8536			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8537			  && ctl_get_prkey(lun, residx) == 0)) {
8538				mtx_unlock(&lun->lun_lock);
8539				goto done;
8540			}
8541
8542			ctl_clr_prkey(lun, residx);
8543			lun->pr_key_count--;
8544
8545			if (residx == lun->pr_res_idx) {
8546				lun->flags &= ~CTL_LUN_PR_RESERVED;
8547				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8548
8549				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8550				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8551				 && lun->pr_key_count) {
8552					/*
8553					 * If the reservation is a registrants
8554					 * only type we need to generate a UA
8555					 * for other registered inits.  The
8556					 * sense code should be RESERVATIONS
8557					 * RELEASED
8558					 */
8559
8560					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8561						if (ctl_get_prkey(lun, i +
8562						    softc->persis_offset) == 0)
8563							continue;
8564						ctl_est_ua(lun, i,
8565						    CTL_UA_RES_RELEASE);
8566					}
8567				}
8568				lun->res_type = 0;
8569			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8570				if (lun->pr_key_count==0) {
8571					lun->flags &= ~CTL_LUN_PR_RESERVED;
8572					lun->res_type = 0;
8573					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8574				}
8575			}
8576			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8577			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8578			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8579			persis_io.pr.pr_info.residx = residx;
8580			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8581			     &persis_io, sizeof(persis_io), 0 )) >
8582			     CTL_HA_STATUS_SUCCESS) {
8583				printf("CTL:Persis Out error returned from "
8584				       "ctl_ha_msg_send %d\n", isc_retval);
8585			}
8586		} else /* sa_res_key != 0 */ {
8587
8588			/*
8589			 * If we aren't registered currently then increment
8590			 * the key count and set the registered flag.
8591			 */
8592			ctl_alloc_prkey(lun, residx);
8593			if (ctl_get_prkey(lun, residx) == 0)
8594				lun->pr_key_count++;
8595			ctl_set_prkey(lun, residx, sa_res_key);
8596
8597			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8598			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8599			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8600			persis_io.pr.pr_info.residx = residx;
8601			memcpy(persis_io.pr.pr_info.sa_res_key,
8602			       param->serv_act_res_key,
8603			       sizeof(param->serv_act_res_key));
8604			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8605			     &persis_io, sizeof(persis_io), 0)) >
8606			     CTL_HA_STATUS_SUCCESS) {
8607				printf("CTL:Persis Out error returned from "
8608				       "ctl_ha_msg_send %d\n", isc_retval);
8609			}
8610		}
8611		lun->PRGeneration++;
8612		mtx_unlock(&lun->lun_lock);
8613
8614		break;
8615	}
8616	case SPRO_RESERVE:
8617#if 0
8618                printf("Reserve executed type %d\n", type);
8619#endif
8620		mtx_lock(&lun->lun_lock);
8621		if (lun->flags & CTL_LUN_PR_RESERVED) {
8622			/*
8623			 * if this isn't the reservation holder and it's
8624			 * not a "all registrants" type or if the type is
8625			 * different then we have a conflict
8626			 */
8627			if ((lun->pr_res_idx != residx
8628			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8629			 || lun->res_type != type) {
8630				mtx_unlock(&lun->lun_lock);
8631				free(ctsio->kern_data_ptr, M_CTL);
8632				ctl_set_reservation_conflict(ctsio);
8633				ctl_done((union ctl_io *)ctsio);
8634				return (CTL_RETVAL_COMPLETE);
8635			}
8636			mtx_unlock(&lun->lun_lock);
8637		} else /* create a reservation */ {
8638			/*
8639			 * If it's not an "all registrants" type record
8640			 * reservation holder
8641			 */
8642			if (type != SPR_TYPE_WR_EX_AR
8643			 && type != SPR_TYPE_EX_AC_AR)
8644				lun->pr_res_idx = residx; /* Res holder */
8645			else
8646				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8647
8648			lun->flags |= CTL_LUN_PR_RESERVED;
8649			lun->res_type = type;
8650
8651			mtx_unlock(&lun->lun_lock);
8652
8653			/* send msg to other side */
8654			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8655			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8656			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8657			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8658			persis_io.pr.pr_info.res_type = type;
8659			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8660			     &persis_io, sizeof(persis_io), 0)) >
8661			     CTL_HA_STATUS_SUCCESS) {
8662				printf("CTL:Persis Out error returned from "
8663				       "ctl_ha_msg_send %d\n", isc_retval);
8664			}
8665		}
8666		break;
8667
8668	case SPRO_RELEASE:
8669		mtx_lock(&lun->lun_lock);
8670		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8671			/* No reservation exists return good status */
8672			mtx_unlock(&lun->lun_lock);
8673			goto done;
8674		}
8675		/*
8676		 * Is this nexus a reservation holder?
8677		 */
8678		if (lun->pr_res_idx != residx
8679		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8680			/*
8681			 * not a res holder return good status but
8682			 * do nothing
8683			 */
8684			mtx_unlock(&lun->lun_lock);
8685			goto done;
8686		}
8687
8688		if (lun->res_type != type) {
8689			mtx_unlock(&lun->lun_lock);
8690			free(ctsio->kern_data_ptr, M_CTL);
8691			ctl_set_illegal_pr_release(ctsio);
8692			ctl_done((union ctl_io *)ctsio);
8693			return (CTL_RETVAL_COMPLETE);
8694		}
8695
8696		/* okay to release */
8697		lun->flags &= ~CTL_LUN_PR_RESERVED;
8698		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8699		lun->res_type = 0;
8700
8701		/*
8702		 * if this isn't an exclusive access
8703		 * res generate UA for all other
8704		 * registrants.
8705		 */
8706		if (type != SPR_TYPE_EX_AC
8707		 && type != SPR_TYPE_WR_EX) {
8708			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8709				if (i == residx ||
8710				    ctl_get_prkey(lun,
8711				     i + softc->persis_offset) == 0)
8712					continue;
8713				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8714			}
8715		}
8716		mtx_unlock(&lun->lun_lock);
8717		/* Send msg to other side */
8718		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8719		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8720		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8721		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8722		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8723			printf("CTL:Persis Out error returned from "
8724			       "ctl_ha_msg_send %d\n", isc_retval);
8725		}
8726		break;
8727
8728	case SPRO_CLEAR:
8729		/* send msg to other side */
8730
8731		mtx_lock(&lun->lun_lock);
8732		lun->flags &= ~CTL_LUN_PR_RESERVED;
8733		lun->res_type = 0;
8734		lun->pr_key_count = 0;
8735		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8736
8737		ctl_clr_prkey(lun, residx);
8738		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8739			if (ctl_get_prkey(lun, i) != 0) {
8740				ctl_clr_prkey(lun, i);
8741				ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8742			}
8743		lun->PRGeneration++;
8744		mtx_unlock(&lun->lun_lock);
8745		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8746		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8747		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8748		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8749		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8750			printf("CTL:Persis Out error returned from "
8751			       "ctl_ha_msg_send %d\n", isc_retval);
8752		}
8753		break;
8754
8755	case SPRO_PREEMPT:
8756	case SPRO_PRE_ABO: {
8757		int nretval;
8758
8759		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8760					  residx, ctsio, cdb, param);
8761		if (nretval != 0)
8762			return (CTL_RETVAL_COMPLETE);
8763		break;
8764	}
8765	default:
8766		panic("Invalid PR type %x", cdb->action);
8767	}
8768
8769done:
8770	free(ctsio->kern_data_ptr, M_CTL);
8771	ctl_set_success(ctsio);
8772	ctl_done((union ctl_io *)ctsio);
8773
8774	return (retval);
8775}
8776
8777/*
8778 * This routine is for handling a message from the other SC pertaining to
8779 * persistent reserve out. All the error checking will have been done
8780 * so only perorming the action need be done here to keep the two
8781 * in sync.
8782 */
8783static void
8784ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8785{
8786	struct ctl_lun *lun;
8787	struct ctl_softc *softc;
8788	int i;
8789	uint32_t targ_lun;
8790
8791	softc = control_softc;
8792
8793	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8794	lun = softc->ctl_luns[targ_lun];
8795	mtx_lock(&lun->lun_lock);
8796	switch(msg->pr.pr_info.action) {
8797	case CTL_PR_REG_KEY:
8798		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8799		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8800			lun->pr_key_count++;
8801		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8802		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8803		lun->PRGeneration++;
8804		break;
8805
8806	case CTL_PR_UNREG_KEY:
8807		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8808		lun->pr_key_count--;
8809
8810		/* XXX Need to see if the reservation has been released */
8811		/* if so do we need to generate UA? */
8812		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8813			lun->flags &= ~CTL_LUN_PR_RESERVED;
8814			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8815
8816			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8817			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8818			 && lun->pr_key_count) {
8819				/*
8820				 * If the reservation is a registrants
8821				 * only type we need to generate a UA
8822				 * for other registered inits.  The
8823				 * sense code should be RESERVATIONS
8824				 * RELEASED
8825				 */
8826
8827				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8828					if (ctl_get_prkey(lun, i +
8829					    softc->persis_offset) == 0)
8830						continue;
8831
8832					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8833				}
8834			}
8835			lun->res_type = 0;
8836		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8837			if (lun->pr_key_count==0) {
8838				lun->flags &= ~CTL_LUN_PR_RESERVED;
8839				lun->res_type = 0;
8840				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8841			}
8842		}
8843		lun->PRGeneration++;
8844		break;
8845
8846	case CTL_PR_RESERVE:
8847		lun->flags |= CTL_LUN_PR_RESERVED;
8848		lun->res_type = msg->pr.pr_info.res_type;
8849		lun->pr_res_idx = msg->pr.pr_info.residx;
8850
8851		break;
8852
8853	case CTL_PR_RELEASE:
8854		/*
8855		 * if this isn't an exclusive access res generate UA for all
8856		 * other registrants.
8857		 */
8858		if (lun->res_type != SPR_TYPE_EX_AC
8859		 && lun->res_type != SPR_TYPE_WR_EX) {
8860			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8861				if (ctl_get_prkey(lun, i + softc->persis_offset) != 0)
8862					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8863		}
8864
8865		lun->flags &= ~CTL_LUN_PR_RESERVED;
8866		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8867		lun->res_type = 0;
8868		break;
8869
8870	case CTL_PR_PREEMPT:
8871		ctl_pro_preempt_other(lun, msg);
8872		break;
8873	case CTL_PR_CLEAR:
8874		lun->flags &= ~CTL_LUN_PR_RESERVED;
8875		lun->res_type = 0;
8876		lun->pr_key_count = 0;
8877		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8878
8879		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8880			if (ctl_get_prkey(lun, i) == 0)
8881				continue;
8882			ctl_clr_prkey(lun, i);
8883			ctl_est_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8884		}
8885		lun->PRGeneration++;
8886		break;
8887	}
8888
8889	mtx_unlock(&lun->lun_lock);
8890}
8891
8892int
8893ctl_read_write(struct ctl_scsiio *ctsio)
8894{
8895	struct ctl_lun *lun;
8896	struct ctl_lba_len_flags *lbalen;
8897	uint64_t lba;
8898	uint32_t num_blocks;
8899	int flags, retval;
8900	int isread;
8901
8902	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8903
8904	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8905
8906	flags = 0;
8907	retval = CTL_RETVAL_COMPLETE;
8908
8909	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8910	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8911	switch (ctsio->cdb[0]) {
8912	case READ_6:
8913	case WRITE_6: {
8914		struct scsi_rw_6 *cdb;
8915
8916		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8917
8918		lba = scsi_3btoul(cdb->addr);
8919		/* only 5 bits are valid in the most significant address byte */
8920		lba &= 0x1fffff;
8921		num_blocks = cdb->length;
8922		/*
8923		 * This is correct according to SBC-2.
8924		 */
8925		if (num_blocks == 0)
8926			num_blocks = 256;
8927		break;
8928	}
8929	case READ_10:
8930	case WRITE_10: {
8931		struct scsi_rw_10 *cdb;
8932
8933		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8934		if (cdb->byte2 & SRW10_FUA)
8935			flags |= CTL_LLF_FUA;
8936		if (cdb->byte2 & SRW10_DPO)
8937			flags |= CTL_LLF_DPO;
8938		lba = scsi_4btoul(cdb->addr);
8939		num_blocks = scsi_2btoul(cdb->length);
8940		break;
8941	}
8942	case WRITE_VERIFY_10: {
8943		struct scsi_write_verify_10 *cdb;
8944
8945		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8946		flags |= CTL_LLF_FUA;
8947		if (cdb->byte2 & SWV_DPO)
8948			flags |= CTL_LLF_DPO;
8949		lba = scsi_4btoul(cdb->addr);
8950		num_blocks = scsi_2btoul(cdb->length);
8951		break;
8952	}
8953	case READ_12:
8954	case WRITE_12: {
8955		struct scsi_rw_12 *cdb;
8956
8957		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8958		if (cdb->byte2 & SRW12_FUA)
8959			flags |= CTL_LLF_FUA;
8960		if (cdb->byte2 & SRW12_DPO)
8961			flags |= CTL_LLF_DPO;
8962		lba = scsi_4btoul(cdb->addr);
8963		num_blocks = scsi_4btoul(cdb->length);
8964		break;
8965	}
8966	case WRITE_VERIFY_12: {
8967		struct scsi_write_verify_12 *cdb;
8968
8969		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8970		flags |= CTL_LLF_FUA;
8971		if (cdb->byte2 & SWV_DPO)
8972			flags |= CTL_LLF_DPO;
8973		lba = scsi_4btoul(cdb->addr);
8974		num_blocks = scsi_4btoul(cdb->length);
8975		break;
8976	}
8977	case READ_16:
8978	case WRITE_16: {
8979		struct scsi_rw_16 *cdb;
8980
8981		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8982		if (cdb->byte2 & SRW12_FUA)
8983			flags |= CTL_LLF_FUA;
8984		if (cdb->byte2 & SRW12_DPO)
8985			flags |= CTL_LLF_DPO;
8986		lba = scsi_8btou64(cdb->addr);
8987		num_blocks = scsi_4btoul(cdb->length);
8988		break;
8989	}
8990	case WRITE_ATOMIC_16: {
8991		struct scsi_rw_16 *cdb;
8992
8993		if (lun->be_lun->atomicblock == 0) {
8994			ctl_set_invalid_opcode(ctsio);
8995			ctl_done((union ctl_io *)ctsio);
8996			return (CTL_RETVAL_COMPLETE);
8997		}
8998
8999		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9000		if (cdb->byte2 & SRW12_FUA)
9001			flags |= CTL_LLF_FUA;
9002		if (cdb->byte2 & SRW12_DPO)
9003			flags |= CTL_LLF_DPO;
9004		lba = scsi_8btou64(cdb->addr);
9005		num_blocks = scsi_4btoul(cdb->length);
9006		if (num_blocks > lun->be_lun->atomicblock) {
9007			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
9008			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
9009			    /*bit*/ 0);
9010			ctl_done((union ctl_io *)ctsio);
9011			return (CTL_RETVAL_COMPLETE);
9012		}
9013		break;
9014	}
9015	case WRITE_VERIFY_16: {
9016		struct scsi_write_verify_16 *cdb;
9017
9018		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9019		flags |= CTL_LLF_FUA;
9020		if (cdb->byte2 & SWV_DPO)
9021			flags |= CTL_LLF_DPO;
9022		lba = scsi_8btou64(cdb->addr);
9023		num_blocks = scsi_4btoul(cdb->length);
9024		break;
9025	}
9026	default:
9027		/*
9028		 * We got a command we don't support.  This shouldn't
9029		 * happen, commands should be filtered out above us.
9030		 */
9031		ctl_set_invalid_opcode(ctsio);
9032		ctl_done((union ctl_io *)ctsio);
9033
9034		return (CTL_RETVAL_COMPLETE);
9035		break; /* NOTREACHED */
9036	}
9037
9038	/*
9039	 * The first check is to make sure we're in bounds, the second
9040	 * check is to catch wrap-around problems.  If the lba + num blocks
9041	 * is less than the lba, then we've wrapped around and the block
9042	 * range is invalid anyway.
9043	 */
9044	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9045	 || ((lba + num_blocks) < lba)) {
9046		ctl_set_lba_out_of_range(ctsio);
9047		ctl_done((union ctl_io *)ctsio);
9048		return (CTL_RETVAL_COMPLETE);
9049	}
9050
9051	/*
9052	 * According to SBC-3, a transfer length of 0 is not an error.
9053	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
9054	 * translates to 256 blocks for those commands.
9055	 */
9056	if (num_blocks == 0) {
9057		ctl_set_success(ctsio);
9058		ctl_done((union ctl_io *)ctsio);
9059		return (CTL_RETVAL_COMPLETE);
9060	}
9061
9062	/* Set FUA and/or DPO if caches are disabled. */
9063	if (isread) {
9064		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9065		    SCP_RCD) != 0)
9066			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9067	} else {
9068		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9069		    SCP_WCE) == 0)
9070			flags |= CTL_LLF_FUA;
9071	}
9072
9073	lbalen = (struct ctl_lba_len_flags *)
9074	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9075	lbalen->lba = lba;
9076	lbalen->len = num_blocks;
9077	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9078
9079	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9080	ctsio->kern_rel_offset = 0;
9081
9082	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9083
9084	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9085
9086	return (retval);
9087}
9088
9089static int
9090ctl_cnw_cont(union ctl_io *io)
9091{
9092	struct ctl_scsiio *ctsio;
9093	struct ctl_lun *lun;
9094	struct ctl_lba_len_flags *lbalen;
9095	int retval;
9096
9097	ctsio = &io->scsiio;
9098	ctsio->io_hdr.status = CTL_STATUS_NONE;
9099	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9100	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9101	lbalen = (struct ctl_lba_len_flags *)
9102	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9103	lbalen->flags &= ~CTL_LLF_COMPARE;
9104	lbalen->flags |= CTL_LLF_WRITE;
9105
9106	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9107	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9108	return (retval);
9109}
9110
9111int
9112ctl_cnw(struct ctl_scsiio *ctsio)
9113{
9114	struct ctl_lun *lun;
9115	struct ctl_lba_len_flags *lbalen;
9116	uint64_t lba;
9117	uint32_t num_blocks;
9118	int flags, retval;
9119
9120	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9121
9122	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9123
9124	flags = 0;
9125	retval = CTL_RETVAL_COMPLETE;
9126
9127	switch (ctsio->cdb[0]) {
9128	case COMPARE_AND_WRITE: {
9129		struct scsi_compare_and_write *cdb;
9130
9131		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9132		if (cdb->byte2 & SRW10_FUA)
9133			flags |= CTL_LLF_FUA;
9134		if (cdb->byte2 & SRW10_DPO)
9135			flags |= CTL_LLF_DPO;
9136		lba = scsi_8btou64(cdb->addr);
9137		num_blocks = cdb->length;
9138		break;
9139	}
9140	default:
9141		/*
9142		 * We got a command we don't support.  This shouldn't
9143		 * happen, commands should be filtered out above us.
9144		 */
9145		ctl_set_invalid_opcode(ctsio);
9146		ctl_done((union ctl_io *)ctsio);
9147
9148		return (CTL_RETVAL_COMPLETE);
9149		break; /* NOTREACHED */
9150	}
9151
9152	/*
9153	 * The first check is to make sure we're in bounds, the second
9154	 * check is to catch wrap-around problems.  If the lba + num blocks
9155	 * is less than the lba, then we've wrapped around and the block
9156	 * range is invalid anyway.
9157	 */
9158	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9159	 || ((lba + num_blocks) < lba)) {
9160		ctl_set_lba_out_of_range(ctsio);
9161		ctl_done((union ctl_io *)ctsio);
9162		return (CTL_RETVAL_COMPLETE);
9163	}
9164
9165	/*
9166	 * According to SBC-3, a transfer length of 0 is not an error.
9167	 */
9168	if (num_blocks == 0) {
9169		ctl_set_success(ctsio);
9170		ctl_done((union ctl_io *)ctsio);
9171		return (CTL_RETVAL_COMPLETE);
9172	}
9173
9174	/* Set FUA if write cache is disabled. */
9175	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9176	    SCP_WCE) == 0)
9177		flags |= CTL_LLF_FUA;
9178
9179	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9180	ctsio->kern_rel_offset = 0;
9181
9182	/*
9183	 * Set the IO_CONT flag, so that if this I/O gets passed to
9184	 * ctl_data_submit_done(), it'll get passed back to
9185	 * ctl_ctl_cnw_cont() for further processing.
9186	 */
9187	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9188	ctsio->io_cont = ctl_cnw_cont;
9189
9190	lbalen = (struct ctl_lba_len_flags *)
9191	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9192	lbalen->lba = lba;
9193	lbalen->len = num_blocks;
9194	lbalen->flags = CTL_LLF_COMPARE | flags;
9195
9196	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9197	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9198	return (retval);
9199}
9200
9201int
9202ctl_verify(struct ctl_scsiio *ctsio)
9203{
9204	struct ctl_lun *lun;
9205	struct ctl_lba_len_flags *lbalen;
9206	uint64_t lba;
9207	uint32_t num_blocks;
9208	int bytchk, flags;
9209	int retval;
9210
9211	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9212
9213	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9214
9215	bytchk = 0;
9216	flags = CTL_LLF_FUA;
9217	retval = CTL_RETVAL_COMPLETE;
9218
9219	switch (ctsio->cdb[0]) {
9220	case VERIFY_10: {
9221		struct scsi_verify_10 *cdb;
9222
9223		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9224		if (cdb->byte2 & SVFY_BYTCHK)
9225			bytchk = 1;
9226		if (cdb->byte2 & SVFY_DPO)
9227			flags |= CTL_LLF_DPO;
9228		lba = scsi_4btoul(cdb->addr);
9229		num_blocks = scsi_2btoul(cdb->length);
9230		break;
9231	}
9232	case VERIFY_12: {
9233		struct scsi_verify_12 *cdb;
9234
9235		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9236		if (cdb->byte2 & SVFY_BYTCHK)
9237			bytchk = 1;
9238		if (cdb->byte2 & SVFY_DPO)
9239			flags |= CTL_LLF_DPO;
9240		lba = scsi_4btoul(cdb->addr);
9241		num_blocks = scsi_4btoul(cdb->length);
9242		break;
9243	}
9244	case VERIFY_16: {
9245		struct scsi_rw_16 *cdb;
9246
9247		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9248		if (cdb->byte2 & SVFY_BYTCHK)
9249			bytchk = 1;
9250		if (cdb->byte2 & SVFY_DPO)
9251			flags |= CTL_LLF_DPO;
9252		lba = scsi_8btou64(cdb->addr);
9253		num_blocks = scsi_4btoul(cdb->length);
9254		break;
9255	}
9256	default:
9257		/*
9258		 * We got a command we don't support.  This shouldn't
9259		 * happen, commands should be filtered out above us.
9260		 */
9261		ctl_set_invalid_opcode(ctsio);
9262		ctl_done((union ctl_io *)ctsio);
9263		return (CTL_RETVAL_COMPLETE);
9264	}
9265
9266	/*
9267	 * The first check is to make sure we're in bounds, the second
9268	 * check is to catch wrap-around problems.  If the lba + num blocks
9269	 * is less than the lba, then we've wrapped around and the block
9270	 * range is invalid anyway.
9271	 */
9272	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9273	 || ((lba + num_blocks) < lba)) {
9274		ctl_set_lba_out_of_range(ctsio);
9275		ctl_done((union ctl_io *)ctsio);
9276		return (CTL_RETVAL_COMPLETE);
9277	}
9278
9279	/*
9280	 * According to SBC-3, a transfer length of 0 is not an error.
9281	 */
9282	if (num_blocks == 0) {
9283		ctl_set_success(ctsio);
9284		ctl_done((union ctl_io *)ctsio);
9285		return (CTL_RETVAL_COMPLETE);
9286	}
9287
9288	lbalen = (struct ctl_lba_len_flags *)
9289	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9290	lbalen->lba = lba;
9291	lbalen->len = num_blocks;
9292	if (bytchk) {
9293		lbalen->flags = CTL_LLF_COMPARE | flags;
9294		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9295	} else {
9296		lbalen->flags = CTL_LLF_VERIFY | flags;
9297		ctsio->kern_total_len = 0;
9298	}
9299	ctsio->kern_rel_offset = 0;
9300
9301	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9302	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9303	return (retval);
9304}
9305
9306int
9307ctl_report_luns(struct ctl_scsiio *ctsio)
9308{
9309	struct scsi_report_luns *cdb;
9310	struct scsi_report_luns_data *lun_data;
9311	struct ctl_lun *lun, *request_lun;
9312	int num_luns, retval;
9313	uint32_t alloc_len, lun_datalen;
9314	int num_filled, well_known;
9315	uint32_t initidx, targ_lun_id, lun_id;
9316
9317	retval = CTL_RETVAL_COMPLETE;
9318	well_known = 0;
9319
9320	cdb = (struct scsi_report_luns *)ctsio->cdb;
9321
9322	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9323
9324	mtx_lock(&control_softc->ctl_lock);
9325	num_luns = control_softc->num_luns;
9326	mtx_unlock(&control_softc->ctl_lock);
9327
9328	switch (cdb->select_report) {
9329	case RPL_REPORT_DEFAULT:
9330	case RPL_REPORT_ALL:
9331		break;
9332	case RPL_REPORT_WELLKNOWN:
9333		well_known = 1;
9334		num_luns = 0;
9335		break;
9336	default:
9337		ctl_set_invalid_field(ctsio,
9338				      /*sks_valid*/ 1,
9339				      /*command*/ 1,
9340				      /*field*/ 2,
9341				      /*bit_valid*/ 0,
9342				      /*bit*/ 0);
9343		ctl_done((union ctl_io *)ctsio);
9344		return (retval);
9345		break; /* NOTREACHED */
9346	}
9347
9348	alloc_len = scsi_4btoul(cdb->length);
9349	/*
9350	 * The initiator has to allocate at least 16 bytes for this request,
9351	 * so he can at least get the header and the first LUN.  Otherwise
9352	 * we reject the request (per SPC-3 rev 14, section 6.21).
9353	 */
9354	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9355	    sizeof(struct scsi_report_luns_lundata))) {
9356		ctl_set_invalid_field(ctsio,
9357				      /*sks_valid*/ 1,
9358				      /*command*/ 1,
9359				      /*field*/ 6,
9360				      /*bit_valid*/ 0,
9361				      /*bit*/ 0);
9362		ctl_done((union ctl_io *)ctsio);
9363		return (retval);
9364	}
9365
9366	request_lun = (struct ctl_lun *)
9367		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9368
9369	lun_datalen = sizeof(*lun_data) +
9370		(num_luns * sizeof(struct scsi_report_luns_lundata));
9371
9372	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9373	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9374	ctsio->kern_sg_entries = 0;
9375
9376	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9377
9378	mtx_lock(&control_softc->ctl_lock);
9379	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9380		lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9381		if (lun_id >= CTL_MAX_LUNS)
9382			continue;
9383		lun = control_softc->ctl_luns[lun_id];
9384		if (lun == NULL)
9385			continue;
9386
9387		if (targ_lun_id <= 0xff) {
9388			/*
9389			 * Peripheral addressing method, bus number 0.
9390			 */
9391			lun_data->luns[num_filled].lundata[0] =
9392				RPL_LUNDATA_ATYP_PERIPH;
9393			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9394			num_filled++;
9395		} else if (targ_lun_id <= 0x3fff) {
9396			/*
9397			 * Flat addressing method.
9398			 */
9399			lun_data->luns[num_filled].lundata[0] =
9400				RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9401			lun_data->luns[num_filled].lundata[1] =
9402				(targ_lun_id & 0xff);
9403			num_filled++;
9404		} else if (targ_lun_id <= 0xffffff) {
9405			/*
9406			 * Extended flat addressing method.
9407			 */
9408			lun_data->luns[num_filled].lundata[0] =
9409			    RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9410			scsi_ulto3b(targ_lun_id,
9411			    &lun_data->luns[num_filled].lundata[1]);
9412			num_filled++;
9413		} else {
9414			printf("ctl_report_luns: bogus LUN number %jd, "
9415			       "skipping\n", (intmax_t)targ_lun_id);
9416		}
9417		/*
9418		 * According to SPC-3, rev 14 section 6.21:
9419		 *
9420		 * "The execution of a REPORT LUNS command to any valid and
9421		 * installed logical unit shall clear the REPORTED LUNS DATA
9422		 * HAS CHANGED unit attention condition for all logical
9423		 * units of that target with respect to the requesting
9424		 * initiator. A valid and installed logical unit is one
9425		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9426		 * INQUIRY data (see 6.4.2)."
9427		 *
9428		 * If request_lun is NULL, the LUN this report luns command
9429		 * was issued to is either disabled or doesn't exist. In that
9430		 * case, we shouldn't clear any pending lun change unit
9431		 * attention.
9432		 */
9433		if (request_lun != NULL) {
9434			mtx_lock(&lun->lun_lock);
9435			ctl_clr_ua(lun, initidx, CTL_UA_RES_RELEASE);
9436			mtx_unlock(&lun->lun_lock);
9437		}
9438	}
9439	mtx_unlock(&control_softc->ctl_lock);
9440
9441	/*
9442	 * It's quite possible that we've returned fewer LUNs than we allocated
9443	 * space for.  Trim it.
9444	 */
9445	lun_datalen = sizeof(*lun_data) +
9446		(num_filled * sizeof(struct scsi_report_luns_lundata));
9447
9448	if (lun_datalen < alloc_len) {
9449		ctsio->residual = alloc_len - lun_datalen;
9450		ctsio->kern_data_len = lun_datalen;
9451		ctsio->kern_total_len = lun_datalen;
9452	} else {
9453		ctsio->residual = 0;
9454		ctsio->kern_data_len = alloc_len;
9455		ctsio->kern_total_len = alloc_len;
9456	}
9457	ctsio->kern_data_resid = 0;
9458	ctsio->kern_rel_offset = 0;
9459	ctsio->kern_sg_entries = 0;
9460
9461	/*
9462	 * We set this to the actual data length, regardless of how much
9463	 * space we actually have to return results.  If the user looks at
9464	 * this value, he'll know whether or not he allocated enough space
9465	 * and reissue the command if necessary.  We don't support well
9466	 * known logical units, so if the user asks for that, return none.
9467	 */
9468	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9469
9470	/*
9471	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9472	 * this request.
9473	 */
9474	ctl_set_success(ctsio);
9475	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9476	ctsio->be_move_done = ctl_config_move_done;
9477	ctl_datamove((union ctl_io *)ctsio);
9478	return (retval);
9479}
9480
9481int
9482ctl_request_sense(struct ctl_scsiio *ctsio)
9483{
9484	struct scsi_request_sense *cdb;
9485	struct scsi_sense_data *sense_ptr;
9486	struct ctl_lun *lun;
9487	uint32_t initidx;
9488	int have_error;
9489	scsi_sense_data_type sense_format;
9490	ctl_ua_type ua_type;
9491
9492	cdb = (struct scsi_request_sense *)ctsio->cdb;
9493
9494	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9495
9496	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9497
9498	/*
9499	 * Determine which sense format the user wants.
9500	 */
9501	if (cdb->byte2 & SRS_DESC)
9502		sense_format = SSD_TYPE_DESC;
9503	else
9504		sense_format = SSD_TYPE_FIXED;
9505
9506	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9507	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9508	ctsio->kern_sg_entries = 0;
9509
9510	/*
9511	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9512	 * larger than the largest allowed value for the length field in the
9513	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9514	 */
9515	ctsio->residual = 0;
9516	ctsio->kern_data_len = cdb->length;
9517	ctsio->kern_total_len = cdb->length;
9518
9519	ctsio->kern_data_resid = 0;
9520	ctsio->kern_rel_offset = 0;
9521	ctsio->kern_sg_entries = 0;
9522
9523	/*
9524	 * If we don't have a LUN, we don't have any pending sense.
9525	 */
9526	if (lun == NULL)
9527		goto no_sense;
9528
9529	have_error = 0;
9530	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9531	/*
9532	 * Check for pending sense, and then for pending unit attentions.
9533	 * Pending sense gets returned first, then pending unit attentions.
9534	 */
9535	mtx_lock(&lun->lun_lock);
9536#ifdef CTL_WITH_CA
9537	if (ctl_is_set(lun->have_ca, initidx)) {
9538		scsi_sense_data_type stored_format;
9539
9540		/*
9541		 * Check to see which sense format was used for the stored
9542		 * sense data.
9543		 */
9544		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9545
9546		/*
9547		 * If the user requested a different sense format than the
9548		 * one we stored, then we need to convert it to the other
9549		 * format.  If we're going from descriptor to fixed format
9550		 * sense data, we may lose things in translation, depending
9551		 * on what options were used.
9552		 *
9553		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9554		 * for some reason we'll just copy it out as-is.
9555		 */
9556		if ((stored_format == SSD_TYPE_FIXED)
9557		 && (sense_format == SSD_TYPE_DESC))
9558			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9559			    &lun->pending_sense[initidx],
9560			    (struct scsi_sense_data_desc *)sense_ptr);
9561		else if ((stored_format == SSD_TYPE_DESC)
9562		      && (sense_format == SSD_TYPE_FIXED))
9563			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9564			    &lun->pending_sense[initidx],
9565			    (struct scsi_sense_data_fixed *)sense_ptr);
9566		else
9567			memcpy(sense_ptr, &lun->pending_sense[initidx],
9568			       ctl_min(sizeof(*sense_ptr),
9569			       sizeof(lun->pending_sense[initidx])));
9570
9571		ctl_clear_mask(lun->have_ca, initidx);
9572		have_error = 1;
9573	} else
9574#endif
9575	{
9576		ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9577		if (ua_type != CTL_UA_NONE)
9578			have_error = 1;
9579	}
9580	mtx_unlock(&lun->lun_lock);
9581
9582	/*
9583	 * We already have a pending error, return it.
9584	 */
9585	if (have_error != 0) {
9586		/*
9587		 * We report the SCSI status as OK, since the status of the
9588		 * request sense command itself is OK.
9589		 * We report 0 for the sense length, because we aren't doing
9590		 * autosense in this case.  We're reporting sense as
9591		 * parameter data.
9592		 */
9593		ctl_set_success(ctsio);
9594		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9595		ctsio->be_move_done = ctl_config_move_done;
9596		ctl_datamove((union ctl_io *)ctsio);
9597		return (CTL_RETVAL_COMPLETE);
9598	}
9599
9600no_sense:
9601
9602	/*
9603	 * No sense information to report, so we report that everything is
9604	 * okay.
9605	 */
9606	ctl_set_sense_data(sense_ptr,
9607			   lun,
9608			   sense_format,
9609			   /*current_error*/ 1,
9610			   /*sense_key*/ SSD_KEY_NO_SENSE,
9611			   /*asc*/ 0x00,
9612			   /*ascq*/ 0x00,
9613			   SSD_ELEM_NONE);
9614
9615	/*
9616	 * We report 0 for the sense length, because we aren't doing
9617	 * autosense in this case.  We're reporting sense as parameter data.
9618	 */
9619	ctl_set_success(ctsio);
9620	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9621	ctsio->be_move_done = ctl_config_move_done;
9622	ctl_datamove((union ctl_io *)ctsio);
9623	return (CTL_RETVAL_COMPLETE);
9624}
9625
9626int
9627ctl_tur(struct ctl_scsiio *ctsio)
9628{
9629
9630	CTL_DEBUG_PRINT(("ctl_tur\n"));
9631
9632	ctl_set_success(ctsio);
9633	ctl_done((union ctl_io *)ctsio);
9634
9635	return (CTL_RETVAL_COMPLETE);
9636}
9637
9638#ifdef notyet
9639static int
9640ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9641{
9642
9643}
9644#endif
9645
9646static int
9647ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9648{
9649	struct scsi_vpd_supported_pages *pages;
9650	int sup_page_size;
9651	struct ctl_lun *lun;
9652
9653	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9654
9655	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9656	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9657	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9658	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9659	ctsio->kern_sg_entries = 0;
9660
9661	if (sup_page_size < alloc_len) {
9662		ctsio->residual = alloc_len - sup_page_size;
9663		ctsio->kern_data_len = sup_page_size;
9664		ctsio->kern_total_len = sup_page_size;
9665	} else {
9666		ctsio->residual = 0;
9667		ctsio->kern_data_len = alloc_len;
9668		ctsio->kern_total_len = alloc_len;
9669	}
9670	ctsio->kern_data_resid = 0;
9671	ctsio->kern_rel_offset = 0;
9672	ctsio->kern_sg_entries = 0;
9673
9674	/*
9675	 * The control device is always connected.  The disk device, on the
9676	 * other hand, may not be online all the time.  Need to change this
9677	 * to figure out whether the disk device is actually online or not.
9678	 */
9679	if (lun != NULL)
9680		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9681				lun->be_lun->lun_type;
9682	else
9683		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9684
9685	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9686	/* Supported VPD pages */
9687	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9688	/* Serial Number */
9689	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9690	/* Device Identification */
9691	pages->page_list[2] = SVPD_DEVICE_ID;
9692	/* Extended INQUIRY Data */
9693	pages->page_list[3] = SVPD_EXTENDED_INQUIRY_DATA;
9694	/* Mode Page Policy */
9695	pages->page_list[4] = SVPD_MODE_PAGE_POLICY;
9696	/* SCSI Ports */
9697	pages->page_list[5] = SVPD_SCSI_PORTS;
9698	/* Third-party Copy */
9699	pages->page_list[6] = SVPD_SCSI_TPC;
9700	/* Block limits */
9701	pages->page_list[7] = SVPD_BLOCK_LIMITS;
9702	/* Block Device Characteristics */
9703	pages->page_list[8] = SVPD_BDC;
9704	/* Logical Block Provisioning */
9705	pages->page_list[9] = SVPD_LBP;
9706
9707	ctl_set_success(ctsio);
9708	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9709	ctsio->be_move_done = ctl_config_move_done;
9710	ctl_datamove((union ctl_io *)ctsio);
9711	return (CTL_RETVAL_COMPLETE);
9712}
9713
9714static int
9715ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9716{
9717	struct scsi_vpd_unit_serial_number *sn_ptr;
9718	struct ctl_lun *lun;
9719	int data_len;
9720
9721	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9722
9723	data_len = 4 + CTL_SN_LEN;
9724	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9725	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9726	if (data_len < alloc_len) {
9727		ctsio->residual = alloc_len - data_len;
9728		ctsio->kern_data_len = data_len;
9729		ctsio->kern_total_len = data_len;
9730	} else {
9731		ctsio->residual = 0;
9732		ctsio->kern_data_len = alloc_len;
9733		ctsio->kern_total_len = alloc_len;
9734	}
9735	ctsio->kern_data_resid = 0;
9736	ctsio->kern_rel_offset = 0;
9737	ctsio->kern_sg_entries = 0;
9738
9739	/*
9740	 * The control device is always connected.  The disk device, on the
9741	 * other hand, may not be online all the time.  Need to change this
9742	 * to figure out whether the disk device is actually online or not.
9743	 */
9744	if (lun != NULL)
9745		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9746				  lun->be_lun->lun_type;
9747	else
9748		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9749
9750	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9751	sn_ptr->length = CTL_SN_LEN;
9752	/*
9753	 * If we don't have a LUN, we just leave the serial number as
9754	 * all spaces.
9755	 */
9756	if (lun != NULL) {
9757		strncpy((char *)sn_ptr->serial_num,
9758			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9759	} else
9760		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9761
9762	ctl_set_success(ctsio);
9763	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9764	ctsio->be_move_done = ctl_config_move_done;
9765	ctl_datamove((union ctl_io *)ctsio);
9766	return (CTL_RETVAL_COMPLETE);
9767}
9768
9769
9770static int
9771ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9772{
9773	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9774	struct ctl_lun *lun;
9775	int data_len;
9776
9777	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9778
9779	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9780	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9781	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9782	ctsio->kern_sg_entries = 0;
9783
9784	if (data_len < alloc_len) {
9785		ctsio->residual = alloc_len - data_len;
9786		ctsio->kern_data_len = data_len;
9787		ctsio->kern_total_len = data_len;
9788	} else {
9789		ctsio->residual = 0;
9790		ctsio->kern_data_len = alloc_len;
9791		ctsio->kern_total_len = alloc_len;
9792	}
9793	ctsio->kern_data_resid = 0;
9794	ctsio->kern_rel_offset = 0;
9795	ctsio->kern_sg_entries = 0;
9796
9797	/*
9798	 * The control device is always connected.  The disk device, on the
9799	 * other hand, may not be online all the time.
9800	 */
9801	if (lun != NULL)
9802		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9803				     lun->be_lun->lun_type;
9804	else
9805		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9806	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9807	eid_ptr->page_length = data_len - 4;
9808	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9809	eid_ptr->flags3 = SVPD_EID_V_SUP;
9810
9811	ctl_set_success(ctsio);
9812	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9813	ctsio->be_move_done = ctl_config_move_done;
9814	ctl_datamove((union ctl_io *)ctsio);
9815	return (CTL_RETVAL_COMPLETE);
9816}
9817
9818static int
9819ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9820{
9821	struct scsi_vpd_mode_page_policy *mpp_ptr;
9822	struct ctl_lun *lun;
9823	int data_len;
9824
9825	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9826
9827	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9828	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9829
9830	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9831	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9832	ctsio->kern_sg_entries = 0;
9833
9834	if (data_len < alloc_len) {
9835		ctsio->residual = alloc_len - data_len;
9836		ctsio->kern_data_len = data_len;
9837		ctsio->kern_total_len = data_len;
9838	} else {
9839		ctsio->residual = 0;
9840		ctsio->kern_data_len = alloc_len;
9841		ctsio->kern_total_len = alloc_len;
9842	}
9843	ctsio->kern_data_resid = 0;
9844	ctsio->kern_rel_offset = 0;
9845	ctsio->kern_sg_entries = 0;
9846
9847	/*
9848	 * The control device is always connected.  The disk device, on the
9849	 * other hand, may not be online all the time.
9850	 */
9851	if (lun != NULL)
9852		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9853				     lun->be_lun->lun_type;
9854	else
9855		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9856	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9857	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9858	mpp_ptr->descr[0].page_code = 0x3f;
9859	mpp_ptr->descr[0].subpage_code = 0xff;
9860	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9861
9862	ctl_set_success(ctsio);
9863	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9864	ctsio->be_move_done = ctl_config_move_done;
9865	ctl_datamove((union ctl_io *)ctsio);
9866	return (CTL_RETVAL_COMPLETE);
9867}
9868
9869static int
9870ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9871{
9872	struct scsi_vpd_device_id *devid_ptr;
9873	struct scsi_vpd_id_descriptor *desc;
9874	struct ctl_softc *ctl_softc;
9875	struct ctl_lun *lun;
9876	struct ctl_port *port;
9877	int data_len;
9878	uint8_t proto;
9879
9880	ctl_softc = control_softc;
9881
9882	port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9883	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9884
9885	data_len = sizeof(struct scsi_vpd_device_id) +
9886	    sizeof(struct scsi_vpd_id_descriptor) +
9887		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9888	    sizeof(struct scsi_vpd_id_descriptor) +
9889		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9890	if (lun && lun->lun_devid)
9891		data_len += lun->lun_devid->len;
9892	if (port->port_devid)
9893		data_len += port->port_devid->len;
9894	if (port->target_devid)
9895		data_len += port->target_devid->len;
9896
9897	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9898	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9899	ctsio->kern_sg_entries = 0;
9900
9901	if (data_len < alloc_len) {
9902		ctsio->residual = alloc_len - data_len;
9903		ctsio->kern_data_len = data_len;
9904		ctsio->kern_total_len = data_len;
9905	} else {
9906		ctsio->residual = 0;
9907		ctsio->kern_data_len = alloc_len;
9908		ctsio->kern_total_len = alloc_len;
9909	}
9910	ctsio->kern_data_resid = 0;
9911	ctsio->kern_rel_offset = 0;
9912	ctsio->kern_sg_entries = 0;
9913
9914	/*
9915	 * The control device is always connected.  The disk device, on the
9916	 * other hand, may not be online all the time.
9917	 */
9918	if (lun != NULL)
9919		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9920				     lun->be_lun->lun_type;
9921	else
9922		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9923	devid_ptr->page_code = SVPD_DEVICE_ID;
9924	scsi_ulto2b(data_len - 4, devid_ptr->length);
9925
9926	if (port->port_type == CTL_PORT_FC)
9927		proto = SCSI_PROTO_FC << 4;
9928	else if (port->port_type == CTL_PORT_ISCSI)
9929		proto = SCSI_PROTO_ISCSI << 4;
9930	else
9931		proto = SCSI_PROTO_SPI << 4;
9932	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9933
9934	/*
9935	 * We're using a LUN association here.  i.e., this device ID is a
9936	 * per-LUN identifier.
9937	 */
9938	if (lun && lun->lun_devid) {
9939		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9940		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9941		    lun->lun_devid->len);
9942	}
9943
9944	/*
9945	 * This is for the WWPN which is a port association.
9946	 */
9947	if (port->port_devid) {
9948		memcpy(desc, port->port_devid->data, port->port_devid->len);
9949		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9950		    port->port_devid->len);
9951	}
9952
9953	/*
9954	 * This is for the Relative Target Port(type 4h) identifier
9955	 */
9956	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9957	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9958	    SVPD_ID_TYPE_RELTARG;
9959	desc->length = 4;
9960	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9961	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9962	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9963
9964	/*
9965	 * This is for the Target Port Group(type 5h) identifier
9966	 */
9967	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9968	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9969	    SVPD_ID_TYPE_TPORTGRP;
9970	desc->length = 4;
9971	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
9972	    &desc->identifier[2]);
9973	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9974	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9975
9976	/*
9977	 * This is for the Target identifier
9978	 */
9979	if (port->target_devid) {
9980		memcpy(desc, port->target_devid->data, port->target_devid->len);
9981	}
9982
9983	ctl_set_success(ctsio);
9984	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9985	ctsio->be_move_done = ctl_config_move_done;
9986	ctl_datamove((union ctl_io *)ctsio);
9987	return (CTL_RETVAL_COMPLETE);
9988}
9989
9990static int
9991ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9992{
9993	struct ctl_softc *softc = control_softc;
9994	struct scsi_vpd_scsi_ports *sp;
9995	struct scsi_vpd_port_designation *pd;
9996	struct scsi_vpd_port_designation_cont *pdc;
9997	struct ctl_lun *lun;
9998	struct ctl_port *port;
9999	int data_len, num_target_ports, iid_len, id_len, g, pg, p;
10000	int num_target_port_groups;
10001
10002	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10003
10004	if (softc->is_single)
10005		num_target_port_groups = 1;
10006	else
10007		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10008	num_target_ports = 0;
10009	iid_len = 0;
10010	id_len = 0;
10011	mtx_lock(&softc->ctl_lock);
10012	STAILQ_FOREACH(port, &softc->port_list, links) {
10013		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10014			continue;
10015		if (lun != NULL &&
10016		    ctl_map_lun_back(port->targ_port, lun->lun) >=
10017		    CTL_MAX_LUNS)
10018			continue;
10019		num_target_ports++;
10020		if (port->init_devid)
10021			iid_len += port->init_devid->len;
10022		if (port->port_devid)
10023			id_len += port->port_devid->len;
10024	}
10025	mtx_unlock(&softc->ctl_lock);
10026
10027	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10028	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10029	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10030	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10031	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10032	ctsio->kern_sg_entries = 0;
10033
10034	if (data_len < alloc_len) {
10035		ctsio->residual = alloc_len - data_len;
10036		ctsio->kern_data_len = data_len;
10037		ctsio->kern_total_len = data_len;
10038	} else {
10039		ctsio->residual = 0;
10040		ctsio->kern_data_len = alloc_len;
10041		ctsio->kern_total_len = alloc_len;
10042	}
10043	ctsio->kern_data_resid = 0;
10044	ctsio->kern_rel_offset = 0;
10045	ctsio->kern_sg_entries = 0;
10046
10047	/*
10048	 * The control device is always connected.  The disk device, on the
10049	 * other hand, may not be online all the time.  Need to change this
10050	 * to figure out whether the disk device is actually online or not.
10051	 */
10052	if (lun != NULL)
10053		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10054				  lun->be_lun->lun_type;
10055	else
10056		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10057
10058	sp->page_code = SVPD_SCSI_PORTS;
10059	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10060	    sp->page_length);
10061	pd = &sp->design[0];
10062
10063	mtx_lock(&softc->ctl_lock);
10064	pg = softc->port_offset / CTL_MAX_PORTS;
10065	for (g = 0; g < num_target_port_groups; g++) {
10066		STAILQ_FOREACH(port, &softc->port_list, links) {
10067			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10068				continue;
10069			if (lun != NULL &&
10070			    ctl_map_lun_back(port->targ_port, lun->lun) >=
10071			    CTL_MAX_LUNS)
10072				continue;
10073			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10074			scsi_ulto2b(p, pd->relative_port_id);
10075			if (port->init_devid && g == pg) {
10076				iid_len = port->init_devid->len;
10077				memcpy(pd->initiator_transportid,
10078				    port->init_devid->data, port->init_devid->len);
10079			} else
10080				iid_len = 0;
10081			scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10082			pdc = (struct scsi_vpd_port_designation_cont *)
10083			    (&pd->initiator_transportid[iid_len]);
10084			if (port->port_devid && g == pg) {
10085				id_len = port->port_devid->len;
10086				memcpy(pdc->target_port_descriptors,
10087				    port->port_devid->data, port->port_devid->len);
10088			} else
10089				id_len = 0;
10090			scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10091			pd = (struct scsi_vpd_port_designation *)
10092			    ((uint8_t *)pdc->target_port_descriptors + id_len);
10093		}
10094	}
10095	mtx_unlock(&softc->ctl_lock);
10096
10097	ctl_set_success(ctsio);
10098	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10099	ctsio->be_move_done = ctl_config_move_done;
10100	ctl_datamove((union ctl_io *)ctsio);
10101	return (CTL_RETVAL_COMPLETE);
10102}
10103
10104static int
10105ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10106{
10107	struct scsi_vpd_block_limits *bl_ptr;
10108	struct ctl_lun *lun;
10109	int bs;
10110
10111	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10112
10113	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10114	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10115	ctsio->kern_sg_entries = 0;
10116
10117	if (sizeof(*bl_ptr) < alloc_len) {
10118		ctsio->residual = alloc_len - sizeof(*bl_ptr);
10119		ctsio->kern_data_len = sizeof(*bl_ptr);
10120		ctsio->kern_total_len = sizeof(*bl_ptr);
10121	} else {
10122		ctsio->residual = 0;
10123		ctsio->kern_data_len = alloc_len;
10124		ctsio->kern_total_len = alloc_len;
10125	}
10126	ctsio->kern_data_resid = 0;
10127	ctsio->kern_rel_offset = 0;
10128	ctsio->kern_sg_entries = 0;
10129
10130	/*
10131	 * The control device is always connected.  The disk device, on the
10132	 * other hand, may not be online all the time.  Need to change this
10133	 * to figure out whether the disk device is actually online or not.
10134	 */
10135	if (lun != NULL)
10136		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10137				  lun->be_lun->lun_type;
10138	else
10139		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10140
10141	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10142	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10143	bl_ptr->max_cmp_write_len = 0xff;
10144	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10145	if (lun != NULL) {
10146		bs = lun->be_lun->blocksize;
10147		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
10148		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10149			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10150			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10151			if (lun->be_lun->ublockexp != 0) {
10152				scsi_ulto4b((1 << lun->be_lun->ublockexp),
10153				    bl_ptr->opt_unmap_grain);
10154				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
10155				    bl_ptr->unmap_grain_align);
10156			}
10157		}
10158		scsi_ulto4b(lun->be_lun->atomicblock,
10159		    bl_ptr->max_atomic_transfer_length);
10160		scsi_ulto4b(0, bl_ptr->atomic_alignment);
10161		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10162	}
10163	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10164
10165	ctl_set_success(ctsio);
10166	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10167	ctsio->be_move_done = ctl_config_move_done;
10168	ctl_datamove((union ctl_io *)ctsio);
10169	return (CTL_RETVAL_COMPLETE);
10170}
10171
10172static int
10173ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10174{
10175	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10176	struct ctl_lun *lun;
10177	const char *value;
10178	u_int i;
10179
10180	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10181
10182	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10183	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10184	ctsio->kern_sg_entries = 0;
10185
10186	if (sizeof(*bdc_ptr) < alloc_len) {
10187		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10188		ctsio->kern_data_len = sizeof(*bdc_ptr);
10189		ctsio->kern_total_len = sizeof(*bdc_ptr);
10190	} else {
10191		ctsio->residual = 0;
10192		ctsio->kern_data_len = alloc_len;
10193		ctsio->kern_total_len = alloc_len;
10194	}
10195	ctsio->kern_data_resid = 0;
10196	ctsio->kern_rel_offset = 0;
10197	ctsio->kern_sg_entries = 0;
10198
10199	/*
10200	 * The control device is always connected.  The disk device, on the
10201	 * other hand, may not be online all the time.  Need to change this
10202	 * to figure out whether the disk device is actually online or not.
10203	 */
10204	if (lun != NULL)
10205		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10206				  lun->be_lun->lun_type;
10207	else
10208		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10209	bdc_ptr->page_code = SVPD_BDC;
10210	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10211	if (lun != NULL &&
10212	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10213		i = strtol(value, NULL, 0);
10214	else
10215		i = CTL_DEFAULT_ROTATION_RATE;
10216	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10217	if (lun != NULL &&
10218	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10219		i = strtol(value, NULL, 0);
10220	else
10221		i = 0;
10222	bdc_ptr->wab_wac_ff = (i & 0x0f);
10223	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10224
10225	ctl_set_success(ctsio);
10226	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10227	ctsio->be_move_done = ctl_config_move_done;
10228	ctl_datamove((union ctl_io *)ctsio);
10229	return (CTL_RETVAL_COMPLETE);
10230}
10231
10232static int
10233ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10234{
10235	struct scsi_vpd_logical_block_prov *lbp_ptr;
10236	struct ctl_lun *lun;
10237
10238	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10239
10240	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10241	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10242	ctsio->kern_sg_entries = 0;
10243
10244	if (sizeof(*lbp_ptr) < alloc_len) {
10245		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10246		ctsio->kern_data_len = sizeof(*lbp_ptr);
10247		ctsio->kern_total_len = sizeof(*lbp_ptr);
10248	} else {
10249		ctsio->residual = 0;
10250		ctsio->kern_data_len = alloc_len;
10251		ctsio->kern_total_len = alloc_len;
10252	}
10253	ctsio->kern_data_resid = 0;
10254	ctsio->kern_rel_offset = 0;
10255	ctsio->kern_sg_entries = 0;
10256
10257	/*
10258	 * The control device is always connected.  The disk device, on the
10259	 * other hand, may not be online all the time.  Need to change this
10260	 * to figure out whether the disk device is actually online or not.
10261	 */
10262	if (lun != NULL)
10263		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10264				  lun->be_lun->lun_type;
10265	else
10266		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10267
10268	lbp_ptr->page_code = SVPD_LBP;
10269	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10270	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10271	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10272		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10273		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10274		lbp_ptr->prov_type = SVPD_LBP_THIN;
10275	}
10276
10277	ctl_set_success(ctsio);
10278	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10279	ctsio->be_move_done = ctl_config_move_done;
10280	ctl_datamove((union ctl_io *)ctsio);
10281	return (CTL_RETVAL_COMPLETE);
10282}
10283
10284static int
10285ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10286{
10287	struct scsi_inquiry *cdb;
10288	int alloc_len, retval;
10289
10290	cdb = (struct scsi_inquiry *)ctsio->cdb;
10291
10292	retval = CTL_RETVAL_COMPLETE;
10293
10294	alloc_len = scsi_2btoul(cdb->length);
10295
10296	switch (cdb->page_code) {
10297	case SVPD_SUPPORTED_PAGES:
10298		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10299		break;
10300	case SVPD_UNIT_SERIAL_NUMBER:
10301		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10302		break;
10303	case SVPD_DEVICE_ID:
10304		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10305		break;
10306	case SVPD_EXTENDED_INQUIRY_DATA:
10307		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10308		break;
10309	case SVPD_MODE_PAGE_POLICY:
10310		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10311		break;
10312	case SVPD_SCSI_PORTS:
10313		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10314		break;
10315	case SVPD_SCSI_TPC:
10316		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10317		break;
10318	case SVPD_BLOCK_LIMITS:
10319		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10320		break;
10321	case SVPD_BDC:
10322		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10323		break;
10324	case SVPD_LBP:
10325		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10326		break;
10327	default:
10328		ctl_set_invalid_field(ctsio,
10329				      /*sks_valid*/ 1,
10330				      /*command*/ 1,
10331				      /*field*/ 2,
10332				      /*bit_valid*/ 0,
10333				      /*bit*/ 0);
10334		ctl_done((union ctl_io *)ctsio);
10335		retval = CTL_RETVAL_COMPLETE;
10336		break;
10337	}
10338
10339	return (retval);
10340}
10341
10342static int
10343ctl_inquiry_std(struct ctl_scsiio *ctsio)
10344{
10345	struct scsi_inquiry_data *inq_ptr;
10346	struct scsi_inquiry *cdb;
10347	struct ctl_softc *ctl_softc;
10348	struct ctl_lun *lun;
10349	char *val;
10350	uint32_t alloc_len, data_len;
10351	ctl_port_type port_type;
10352
10353	ctl_softc = control_softc;
10354
10355	/*
10356	 * Figure out whether we're talking to a Fibre Channel port or not.
10357	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10358	 * SCSI front ends.
10359	 */
10360	port_type = ctl_softc->ctl_ports[
10361	    ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10362	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10363		port_type = CTL_PORT_SCSI;
10364
10365	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10366	cdb = (struct scsi_inquiry *)ctsio->cdb;
10367	alloc_len = scsi_2btoul(cdb->length);
10368
10369	/*
10370	 * We malloc the full inquiry data size here and fill it
10371	 * in.  If the user only asks for less, we'll give him
10372	 * that much.
10373	 */
10374	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10375	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10376	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10377	ctsio->kern_sg_entries = 0;
10378	ctsio->kern_data_resid = 0;
10379	ctsio->kern_rel_offset = 0;
10380
10381	if (data_len < alloc_len) {
10382		ctsio->residual = alloc_len - data_len;
10383		ctsio->kern_data_len = data_len;
10384		ctsio->kern_total_len = data_len;
10385	} else {
10386		ctsio->residual = 0;
10387		ctsio->kern_data_len = alloc_len;
10388		ctsio->kern_total_len = alloc_len;
10389	}
10390
10391	/*
10392	 * If we have a LUN configured, report it as connected.  Otherwise,
10393	 * report that it is offline or no device is supported, depending
10394	 * on the value of inquiry_pq_no_lun.
10395	 *
10396	 * According to the spec (SPC-4 r34), the peripheral qualifier
10397	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10398	 *
10399	 * "A peripheral device having the specified peripheral device type
10400	 * is not connected to this logical unit. However, the device
10401	 * server is capable of supporting the specified peripheral device
10402	 * type on this logical unit."
10403	 *
10404	 * According to the same spec, the peripheral qualifier
10405	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10406	 *
10407	 * "The device server is not capable of supporting a peripheral
10408	 * device on this logical unit. For this peripheral qualifier the
10409	 * peripheral device type shall be set to 1Fh. All other peripheral
10410	 * device type values are reserved for this peripheral qualifier."
10411	 *
10412	 * Given the text, it would seem that we probably want to report that
10413	 * the LUN is offline here.  There is no LUN connected, but we can
10414	 * support a LUN at the given LUN number.
10415	 *
10416	 * In the real world, though, it sounds like things are a little
10417	 * different:
10418	 *
10419	 * - Linux, when presented with a LUN with the offline peripheral
10420	 *   qualifier, will create an sg driver instance for it.  So when
10421	 *   you attach it to CTL, you wind up with a ton of sg driver
10422	 *   instances.  (One for every LUN that Linux bothered to probe.)
10423	 *   Linux does this despite the fact that it issues a REPORT LUNs
10424	 *   to LUN 0 to get the inventory of supported LUNs.
10425	 *
10426	 * - There is other anecdotal evidence (from Emulex folks) about
10427	 *   arrays that use the offline peripheral qualifier for LUNs that
10428	 *   are on the "passive" path in an active/passive array.
10429	 *
10430	 * So the solution is provide a hopefully reasonable default
10431	 * (return bad/no LUN) and allow the user to change the behavior
10432	 * with a tunable/sysctl variable.
10433	 */
10434	if (lun != NULL)
10435		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10436				  lun->be_lun->lun_type;
10437	else if (ctl_softc->inquiry_pq_no_lun == 0)
10438		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10439	else
10440		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10441
10442	/* RMB in byte 2 is 0 */
10443	inq_ptr->version = SCSI_REV_SPC4;
10444
10445	/*
10446	 * According to SAM-3, even if a device only supports a single
10447	 * level of LUN addressing, it should still set the HISUP bit:
10448	 *
10449	 * 4.9.1 Logical unit numbers overview
10450	 *
10451	 * All logical unit number formats described in this standard are
10452	 * hierarchical in structure even when only a single level in that
10453	 * hierarchy is used. The HISUP bit shall be set to one in the
10454	 * standard INQUIRY data (see SPC-2) when any logical unit number
10455	 * format described in this standard is used.  Non-hierarchical
10456	 * formats are outside the scope of this standard.
10457	 *
10458	 * Therefore we set the HiSup bit here.
10459	 *
10460	 * The reponse format is 2, per SPC-3.
10461	 */
10462	inq_ptr->response_format = SID_HiSup | 2;
10463
10464	inq_ptr->additional_length = data_len -
10465	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10466	CTL_DEBUG_PRINT(("additional_length = %d\n",
10467			 inq_ptr->additional_length));
10468
10469	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10470	/* 16 bit addressing */
10471	if (port_type == CTL_PORT_SCSI)
10472		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10473	/* XXX set the SID_MultiP bit here if we're actually going to
10474	   respond on multiple ports */
10475	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10476
10477	/* 16 bit data bus, synchronous transfers */
10478	if (port_type == CTL_PORT_SCSI)
10479		inq_ptr->flags = SID_WBus16 | SID_Sync;
10480	/*
10481	 * XXX KDM do we want to support tagged queueing on the control
10482	 * device at all?
10483	 */
10484	if ((lun == NULL)
10485	 || (lun->be_lun->lun_type != T_PROCESSOR))
10486		inq_ptr->flags |= SID_CmdQue;
10487	/*
10488	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10489	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10490	 * name and 4 bytes for the revision.
10491	 */
10492	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10493	    "vendor")) == NULL) {
10494		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10495	} else {
10496		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10497		strncpy(inq_ptr->vendor, val,
10498		    min(sizeof(inq_ptr->vendor), strlen(val)));
10499	}
10500	if (lun == NULL) {
10501		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10502		    sizeof(inq_ptr->product));
10503	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10504		switch (lun->be_lun->lun_type) {
10505		case T_DIRECT:
10506			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10507			    sizeof(inq_ptr->product));
10508			break;
10509		case T_PROCESSOR:
10510			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10511			    sizeof(inq_ptr->product));
10512			break;
10513		default:
10514			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10515			    sizeof(inq_ptr->product));
10516			break;
10517		}
10518	} else {
10519		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10520		strncpy(inq_ptr->product, val,
10521		    min(sizeof(inq_ptr->product), strlen(val)));
10522	}
10523
10524	/*
10525	 * XXX make this a macro somewhere so it automatically gets
10526	 * incremented when we make changes.
10527	 */
10528	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10529	    "revision")) == NULL) {
10530		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10531	} else {
10532		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10533		strncpy(inq_ptr->revision, val,
10534		    min(sizeof(inq_ptr->revision), strlen(val)));
10535	}
10536
10537	/*
10538	 * For parallel SCSI, we support double transition and single
10539	 * transition clocking.  We also support QAS (Quick Arbitration
10540	 * and Selection) and Information Unit transfers on both the
10541	 * control and array devices.
10542	 */
10543	if (port_type == CTL_PORT_SCSI)
10544		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10545				    SID_SPI_IUS;
10546
10547	/* SAM-5 (no version claimed) */
10548	scsi_ulto2b(0x00A0, inq_ptr->version1);
10549	/* SPC-4 (no version claimed) */
10550	scsi_ulto2b(0x0460, inq_ptr->version2);
10551	if (port_type == CTL_PORT_FC) {
10552		/* FCP-2 ANSI INCITS.350:2003 */
10553		scsi_ulto2b(0x0917, inq_ptr->version3);
10554	} else if (port_type == CTL_PORT_SCSI) {
10555		/* SPI-4 ANSI INCITS.362:200x */
10556		scsi_ulto2b(0x0B56, inq_ptr->version3);
10557	} else if (port_type == CTL_PORT_ISCSI) {
10558		/* iSCSI (no version claimed) */
10559		scsi_ulto2b(0x0960, inq_ptr->version3);
10560	} else if (port_type == CTL_PORT_SAS) {
10561		/* SAS (no version claimed) */
10562		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10563	}
10564
10565	if (lun == NULL) {
10566		/* SBC-4 (no version claimed) */
10567		scsi_ulto2b(0x0600, inq_ptr->version4);
10568	} else {
10569		switch (lun->be_lun->lun_type) {
10570		case T_DIRECT:
10571			/* SBC-4 (no version claimed) */
10572			scsi_ulto2b(0x0600, inq_ptr->version4);
10573			break;
10574		case T_PROCESSOR:
10575		default:
10576			break;
10577		}
10578	}
10579
10580	ctl_set_success(ctsio);
10581	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10582	ctsio->be_move_done = ctl_config_move_done;
10583	ctl_datamove((union ctl_io *)ctsio);
10584	return (CTL_RETVAL_COMPLETE);
10585}
10586
10587int
10588ctl_inquiry(struct ctl_scsiio *ctsio)
10589{
10590	struct scsi_inquiry *cdb;
10591	int retval;
10592
10593	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10594
10595	cdb = (struct scsi_inquiry *)ctsio->cdb;
10596	if (cdb->byte2 & SI_EVPD)
10597		retval = ctl_inquiry_evpd(ctsio);
10598	else if (cdb->page_code == 0)
10599		retval = ctl_inquiry_std(ctsio);
10600	else {
10601		ctl_set_invalid_field(ctsio,
10602				      /*sks_valid*/ 1,
10603				      /*command*/ 1,
10604				      /*field*/ 2,
10605				      /*bit_valid*/ 0,
10606				      /*bit*/ 0);
10607		ctl_done((union ctl_io *)ctsio);
10608		return (CTL_RETVAL_COMPLETE);
10609	}
10610
10611	return (retval);
10612}
10613
10614/*
10615 * For known CDB types, parse the LBA and length.
10616 */
10617static int
10618ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10619{
10620	if (io->io_hdr.io_type != CTL_IO_SCSI)
10621		return (1);
10622
10623	switch (io->scsiio.cdb[0]) {
10624	case COMPARE_AND_WRITE: {
10625		struct scsi_compare_and_write *cdb;
10626
10627		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10628
10629		*lba = scsi_8btou64(cdb->addr);
10630		*len = cdb->length;
10631		break;
10632	}
10633	case READ_6:
10634	case WRITE_6: {
10635		struct scsi_rw_6 *cdb;
10636
10637		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10638
10639		*lba = scsi_3btoul(cdb->addr);
10640		/* only 5 bits are valid in the most significant address byte */
10641		*lba &= 0x1fffff;
10642		*len = cdb->length;
10643		break;
10644	}
10645	case READ_10:
10646	case WRITE_10: {
10647		struct scsi_rw_10 *cdb;
10648
10649		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10650
10651		*lba = scsi_4btoul(cdb->addr);
10652		*len = scsi_2btoul(cdb->length);
10653		break;
10654	}
10655	case WRITE_VERIFY_10: {
10656		struct scsi_write_verify_10 *cdb;
10657
10658		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10659
10660		*lba = scsi_4btoul(cdb->addr);
10661		*len = scsi_2btoul(cdb->length);
10662		break;
10663	}
10664	case READ_12:
10665	case WRITE_12: {
10666		struct scsi_rw_12 *cdb;
10667
10668		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10669
10670		*lba = scsi_4btoul(cdb->addr);
10671		*len = scsi_4btoul(cdb->length);
10672		break;
10673	}
10674	case WRITE_VERIFY_12: {
10675		struct scsi_write_verify_12 *cdb;
10676
10677		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10678
10679		*lba = scsi_4btoul(cdb->addr);
10680		*len = scsi_4btoul(cdb->length);
10681		break;
10682	}
10683	case READ_16:
10684	case WRITE_16:
10685	case WRITE_ATOMIC_16: {
10686		struct scsi_rw_16 *cdb;
10687
10688		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10689
10690		*lba = scsi_8btou64(cdb->addr);
10691		*len = scsi_4btoul(cdb->length);
10692		break;
10693	}
10694	case WRITE_VERIFY_16: {
10695		struct scsi_write_verify_16 *cdb;
10696
10697		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10698
10699		*lba = scsi_8btou64(cdb->addr);
10700		*len = scsi_4btoul(cdb->length);
10701		break;
10702	}
10703	case WRITE_SAME_10: {
10704		struct scsi_write_same_10 *cdb;
10705
10706		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10707
10708		*lba = scsi_4btoul(cdb->addr);
10709		*len = scsi_2btoul(cdb->length);
10710		break;
10711	}
10712	case WRITE_SAME_16: {
10713		struct scsi_write_same_16 *cdb;
10714
10715		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10716
10717		*lba = scsi_8btou64(cdb->addr);
10718		*len = scsi_4btoul(cdb->length);
10719		break;
10720	}
10721	case VERIFY_10: {
10722		struct scsi_verify_10 *cdb;
10723
10724		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10725
10726		*lba = scsi_4btoul(cdb->addr);
10727		*len = scsi_2btoul(cdb->length);
10728		break;
10729	}
10730	case VERIFY_12: {
10731		struct scsi_verify_12 *cdb;
10732
10733		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10734
10735		*lba = scsi_4btoul(cdb->addr);
10736		*len = scsi_4btoul(cdb->length);
10737		break;
10738	}
10739	case VERIFY_16: {
10740		struct scsi_verify_16 *cdb;
10741
10742		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10743
10744		*lba = scsi_8btou64(cdb->addr);
10745		*len = scsi_4btoul(cdb->length);
10746		break;
10747	}
10748	case UNMAP: {
10749		*lba = 0;
10750		*len = UINT64_MAX;
10751		break;
10752	}
10753	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10754		struct scsi_get_lba_status *cdb;
10755
10756		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10757		*lba = scsi_8btou64(cdb->addr);
10758		*len = UINT32_MAX;
10759		break;
10760	}
10761	default:
10762		return (1);
10763		break; /* NOTREACHED */
10764	}
10765
10766	return (0);
10767}
10768
10769static ctl_action
10770ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10771    bool seq)
10772{
10773	uint64_t endlba1, endlba2;
10774
10775	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10776	endlba2 = lba2 + len2 - 1;
10777
10778	if ((endlba1 < lba2) || (endlba2 < lba1))
10779		return (CTL_ACTION_PASS);
10780	else
10781		return (CTL_ACTION_BLOCK);
10782}
10783
10784static int
10785ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10786{
10787	struct ctl_ptr_len_flags *ptrlen;
10788	struct scsi_unmap_desc *buf, *end, *range;
10789	uint64_t lba;
10790	uint32_t len;
10791
10792	/* If not UNMAP -- go other way. */
10793	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10794	    io->scsiio.cdb[0] != UNMAP)
10795		return (CTL_ACTION_ERROR);
10796
10797	/* If UNMAP without data -- block and wait for data. */
10798	ptrlen = (struct ctl_ptr_len_flags *)
10799	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10800	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10801	    ptrlen->ptr == NULL)
10802		return (CTL_ACTION_BLOCK);
10803
10804	/* UNMAP with data -- check for collision. */
10805	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10806	end = buf + ptrlen->len / sizeof(*buf);
10807	for (range = buf; range < end; range++) {
10808		lba = scsi_8btou64(range->lba);
10809		len = scsi_4btoul(range->length);
10810		if ((lba < lba2 + len2) && (lba + len > lba2))
10811			return (CTL_ACTION_BLOCK);
10812	}
10813	return (CTL_ACTION_PASS);
10814}
10815
10816static ctl_action
10817ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10818{
10819	uint64_t lba1, lba2;
10820	uint64_t len1, len2;
10821	int retval;
10822
10823	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10824		return (CTL_ACTION_ERROR);
10825
10826	retval = ctl_extent_check_unmap(io1, lba2, len2);
10827	if (retval != CTL_ACTION_ERROR)
10828		return (retval);
10829
10830	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10831		return (CTL_ACTION_ERROR);
10832
10833	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10834}
10835
10836static ctl_action
10837ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10838{
10839	uint64_t lba1, lba2;
10840	uint64_t len1, len2;
10841
10842	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10843		return (CTL_ACTION_ERROR);
10844	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10845		return (CTL_ACTION_ERROR);
10846
10847	if (lba1 + len1 == lba2)
10848		return (CTL_ACTION_BLOCK);
10849	return (CTL_ACTION_PASS);
10850}
10851
10852static ctl_action
10853ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10854    union ctl_io *ooa_io)
10855{
10856	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10857	ctl_serialize_action *serialize_row;
10858
10859	/*
10860	 * The initiator attempted multiple untagged commands at the same
10861	 * time.  Can't do that.
10862	 */
10863	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10864	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10865	 && ((pending_io->io_hdr.nexus.targ_port ==
10866	      ooa_io->io_hdr.nexus.targ_port)
10867	  && (pending_io->io_hdr.nexus.initid.id ==
10868	      ooa_io->io_hdr.nexus.initid.id))
10869	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10870		return (CTL_ACTION_OVERLAP);
10871
10872	/*
10873	 * The initiator attempted to send multiple tagged commands with
10874	 * the same ID.  (It's fine if different initiators have the same
10875	 * tag ID.)
10876	 *
10877	 * Even if all of those conditions are true, we don't kill the I/O
10878	 * if the command ahead of us has been aborted.  We won't end up
10879	 * sending it to the FETD, and it's perfectly legal to resend a
10880	 * command with the same tag number as long as the previous
10881	 * instance of this tag number has been aborted somehow.
10882	 */
10883	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10884	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10885	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10886	 && ((pending_io->io_hdr.nexus.targ_port ==
10887	      ooa_io->io_hdr.nexus.targ_port)
10888	  && (pending_io->io_hdr.nexus.initid.id ==
10889	      ooa_io->io_hdr.nexus.initid.id))
10890	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10891		return (CTL_ACTION_OVERLAP_TAG);
10892
10893	/*
10894	 * If we get a head of queue tag, SAM-3 says that we should
10895	 * immediately execute it.
10896	 *
10897	 * What happens if this command would normally block for some other
10898	 * reason?  e.g. a request sense with a head of queue tag
10899	 * immediately after a write.  Normally that would block, but this
10900	 * will result in its getting executed immediately...
10901	 *
10902	 * We currently return "pass" instead of "skip", so we'll end up
10903	 * going through the rest of the queue to check for overlapped tags.
10904	 *
10905	 * XXX KDM check for other types of blockage first??
10906	 */
10907	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10908		return (CTL_ACTION_PASS);
10909
10910	/*
10911	 * Ordered tags have to block until all items ahead of them
10912	 * have completed.  If we get called with an ordered tag, we always
10913	 * block, if something else is ahead of us in the queue.
10914	 */
10915	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10916		return (CTL_ACTION_BLOCK);
10917
10918	/*
10919	 * Simple tags get blocked until all head of queue and ordered tags
10920	 * ahead of them have completed.  I'm lumping untagged commands in
10921	 * with simple tags here.  XXX KDM is that the right thing to do?
10922	 */
10923	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10924	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10925	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10926	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10927		return (CTL_ACTION_BLOCK);
10928
10929	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10930	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10931
10932	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10933
10934	switch (serialize_row[pending_entry->seridx]) {
10935	case CTL_SER_BLOCK:
10936		return (CTL_ACTION_BLOCK);
10937	case CTL_SER_EXTENT:
10938		return (ctl_extent_check(ooa_io, pending_io,
10939		    (lun->serseq == CTL_LUN_SERSEQ_ON)));
10940	case CTL_SER_EXTENTOPT:
10941		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10942		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10943			return (ctl_extent_check(ooa_io, pending_io,
10944			    (lun->serseq == CTL_LUN_SERSEQ_ON)));
10945		return (CTL_ACTION_PASS);
10946	case CTL_SER_EXTENTSEQ:
10947		if (lun->serseq != CTL_LUN_SERSEQ_OFF)
10948			return (ctl_extent_check_seq(ooa_io, pending_io));
10949		return (CTL_ACTION_PASS);
10950	case CTL_SER_PASS:
10951		return (CTL_ACTION_PASS);
10952	case CTL_SER_BLOCKOPT:
10953		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10954		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10955			return (CTL_ACTION_BLOCK);
10956		return (CTL_ACTION_PASS);
10957	case CTL_SER_SKIP:
10958		return (CTL_ACTION_SKIP);
10959	default:
10960		panic("invalid serialization value %d",
10961		      serialize_row[pending_entry->seridx]);
10962	}
10963
10964	return (CTL_ACTION_ERROR);
10965}
10966
10967/*
10968 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10969 * Assumptions:
10970 * - pending_io is generally either incoming, or on the blocked queue
10971 * - starting I/O is the I/O we want to start the check with.
10972 */
10973static ctl_action
10974ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10975	      union ctl_io *starting_io)
10976{
10977	union ctl_io *ooa_io;
10978	ctl_action action;
10979
10980	mtx_assert(&lun->lun_lock, MA_OWNED);
10981
10982	/*
10983	 * Run back along the OOA queue, starting with the current
10984	 * blocked I/O and going through every I/O before it on the
10985	 * queue.  If starting_io is NULL, we'll just end up returning
10986	 * CTL_ACTION_PASS.
10987	 */
10988	for (ooa_io = starting_io; ooa_io != NULL;
10989	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10990	     ooa_links)){
10991
10992		/*
10993		 * This routine just checks to see whether
10994		 * cur_blocked is blocked by ooa_io, which is ahead
10995		 * of it in the queue.  It doesn't queue/dequeue
10996		 * cur_blocked.
10997		 */
10998		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10999		switch (action) {
11000		case CTL_ACTION_BLOCK:
11001		case CTL_ACTION_OVERLAP:
11002		case CTL_ACTION_OVERLAP_TAG:
11003		case CTL_ACTION_SKIP:
11004		case CTL_ACTION_ERROR:
11005			return (action);
11006			break; /* NOTREACHED */
11007		case CTL_ACTION_PASS:
11008			break;
11009		default:
11010			panic("invalid action %d", action);
11011			break;  /* NOTREACHED */
11012		}
11013	}
11014
11015	return (CTL_ACTION_PASS);
11016}
11017
11018/*
11019 * Assumptions:
11020 * - An I/O has just completed, and has been removed from the per-LUN OOA
11021 *   queue, so some items on the blocked queue may now be unblocked.
11022 */
11023static int
11024ctl_check_blocked(struct ctl_lun *lun)
11025{
11026	union ctl_io *cur_blocked, *next_blocked;
11027
11028	mtx_assert(&lun->lun_lock, MA_OWNED);
11029
11030	/*
11031	 * Run forward from the head of the blocked queue, checking each
11032	 * entry against the I/Os prior to it on the OOA queue to see if
11033	 * there is still any blockage.
11034	 *
11035	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11036	 * with our removing a variable on it while it is traversing the
11037	 * list.
11038	 */
11039	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11040	     cur_blocked != NULL; cur_blocked = next_blocked) {
11041		union ctl_io *prev_ooa;
11042		ctl_action action;
11043
11044		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11045							  blocked_links);
11046
11047		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11048						      ctl_ooaq, ooa_links);
11049
11050		/*
11051		 * If cur_blocked happens to be the first item in the OOA
11052		 * queue now, prev_ooa will be NULL, and the action
11053		 * returned will just be CTL_ACTION_PASS.
11054		 */
11055		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11056
11057		switch (action) {
11058		case CTL_ACTION_BLOCK:
11059			/* Nothing to do here, still blocked */
11060			break;
11061		case CTL_ACTION_OVERLAP:
11062		case CTL_ACTION_OVERLAP_TAG:
11063			/*
11064			 * This shouldn't happen!  In theory we've already
11065			 * checked this command for overlap...
11066			 */
11067			break;
11068		case CTL_ACTION_PASS:
11069		case CTL_ACTION_SKIP: {
11070			struct ctl_softc *softc;
11071			const struct ctl_cmd_entry *entry;
11072			int isc_retval;
11073
11074			/*
11075			 * The skip case shouldn't happen, this transaction
11076			 * should have never made it onto the blocked queue.
11077			 */
11078			/*
11079			 * This I/O is no longer blocked, we can remove it
11080			 * from the blocked queue.  Since this is a TAILQ
11081			 * (doubly linked list), we can do O(1) removals
11082			 * from any place on the list.
11083			 */
11084			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11085				     blocked_links);
11086			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11087
11088			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11089				/*
11090				 * Need to send IO back to original side to
11091				 * run
11092				 */
11093				union ctl_ha_msg msg_info;
11094
11095				msg_info.hdr.original_sc =
11096					cur_blocked->io_hdr.original_sc;
11097				msg_info.hdr.serializing_sc = cur_blocked;
11098				msg_info.hdr.msg_type = CTL_MSG_R2R;
11099				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11100				     &msg_info, sizeof(msg_info), 0)) >
11101				     CTL_HA_STATUS_SUCCESS) {
11102					printf("CTL:Check Blocked error from "
11103					       "ctl_ha_msg_send %d\n",
11104					       isc_retval);
11105				}
11106				break;
11107			}
11108			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11109			softc = control_softc;
11110
11111			/*
11112			 * Check this I/O for LUN state changes that may
11113			 * have happened while this command was blocked.
11114			 * The LUN state may have been changed by a command
11115			 * ahead of us in the queue, so we need to re-check
11116			 * for any states that can be caused by SCSI
11117			 * commands.
11118			 */
11119			if (ctl_scsiio_lun_check(softc, lun, entry,
11120						 &cur_blocked->scsiio) == 0) {
11121				cur_blocked->io_hdr.flags |=
11122				                      CTL_FLAG_IS_WAS_ON_RTR;
11123				ctl_enqueue_rtr(cur_blocked);
11124			} else
11125				ctl_done(cur_blocked);
11126			break;
11127		}
11128		default:
11129			/*
11130			 * This probably shouldn't happen -- we shouldn't
11131			 * get CTL_ACTION_ERROR, or anything else.
11132			 */
11133			break;
11134		}
11135	}
11136
11137	return (CTL_RETVAL_COMPLETE);
11138}
11139
11140/*
11141 * This routine (with one exception) checks LUN flags that can be set by
11142 * commands ahead of us in the OOA queue.  These flags have to be checked
11143 * when a command initially comes in, and when we pull a command off the
11144 * blocked queue and are preparing to execute it.  The reason we have to
11145 * check these flags for commands on the blocked queue is that the LUN
11146 * state may have been changed by a command ahead of us while we're on the
11147 * blocked queue.
11148 *
11149 * Ordering is somewhat important with these checks, so please pay
11150 * careful attention to the placement of any new checks.
11151 */
11152static int
11153ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11154    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11155{
11156	int retval;
11157	uint32_t residx;
11158
11159	retval = 0;
11160
11161	mtx_assert(&lun->lun_lock, MA_OWNED);
11162
11163	/*
11164	 * If this shelf is a secondary shelf controller, we have to reject
11165	 * any media access commands.
11166	 */
11167	if ((ctl_softc->flags & CTL_FLAG_ACTIVE_SHELF) == 0 &&
11168	    (entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0) {
11169		ctl_set_lun_standby(ctsio);
11170		retval = 1;
11171		goto bailout;
11172	}
11173
11174	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11175		if (lun->flags & CTL_LUN_READONLY) {
11176			ctl_set_sense(ctsio, /*current_error*/ 1,
11177			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11178			    /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11179			retval = 1;
11180			goto bailout;
11181		}
11182		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11183		    .eca_and_aen & SCP_SWP) != 0) {
11184			ctl_set_sense(ctsio, /*current_error*/ 1,
11185			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11186			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11187			retval = 1;
11188			goto bailout;
11189		}
11190	}
11191
11192	/*
11193	 * Check for a reservation conflict.  If this command isn't allowed
11194	 * even on reserved LUNs, and if this initiator isn't the one who
11195	 * reserved us, reject the command with a reservation conflict.
11196	 */
11197	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11198	if ((lun->flags & CTL_LUN_RESERVED)
11199	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11200		if (lun->res_idx != residx) {
11201			ctl_set_reservation_conflict(ctsio);
11202			retval = 1;
11203			goto bailout;
11204		}
11205	}
11206
11207	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11208	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11209		/* No reservation or command is allowed. */;
11210	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11211	    (lun->res_type == SPR_TYPE_WR_EX ||
11212	     lun->res_type == SPR_TYPE_WR_EX_RO ||
11213	     lun->res_type == SPR_TYPE_WR_EX_AR)) {
11214		/* The command is allowed for Write Exclusive resv. */;
11215	} else {
11216		/*
11217		 * if we aren't registered or it's a res holder type
11218		 * reservation and this isn't the res holder then set a
11219		 * conflict.
11220		 */
11221		if (ctl_get_prkey(lun, residx) == 0
11222		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11223			ctl_set_reservation_conflict(ctsio);
11224			retval = 1;
11225			goto bailout;
11226		}
11227
11228	}
11229
11230	if ((lun->flags & CTL_LUN_OFFLINE)
11231	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11232		ctl_set_lun_not_ready(ctsio);
11233		retval = 1;
11234		goto bailout;
11235	}
11236
11237	/*
11238	 * If the LUN is stopped, see if this particular command is allowed
11239	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11240	 */
11241	if ((lun->flags & CTL_LUN_STOPPED)
11242	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11243		/* "Logical unit not ready, initializing cmd. required" */
11244		ctl_set_lun_stopped(ctsio);
11245		retval = 1;
11246		goto bailout;
11247	}
11248
11249	if ((lun->flags & CTL_LUN_INOPERABLE)
11250	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11251		/* "Medium format corrupted" */
11252		ctl_set_medium_format_corrupted(ctsio);
11253		retval = 1;
11254		goto bailout;
11255	}
11256
11257bailout:
11258	return (retval);
11259
11260}
11261
11262static void
11263ctl_failover_io(union ctl_io *io, int have_lock)
11264{
11265	ctl_set_busy(&io->scsiio);
11266	ctl_done(io);
11267}
11268
11269static void
11270ctl_failover(void)
11271{
11272	struct ctl_lun *lun;
11273	struct ctl_softc *ctl_softc;
11274	union ctl_io *next_io, *pending_io;
11275	union ctl_io *io;
11276	int lun_idx;
11277
11278	ctl_softc = control_softc;
11279
11280	mtx_lock(&ctl_softc->ctl_lock);
11281	/*
11282	 * Remove any cmds from the other SC from the rtr queue.  These
11283	 * will obviously only be for LUNs for which we're the primary.
11284	 * We can't send status or get/send data for these commands.
11285	 * Since they haven't been executed yet, we can just remove them.
11286	 * We'll either abort them or delete them below, depending on
11287	 * which HA mode we're in.
11288	 */
11289#ifdef notyet
11290	mtx_lock(&ctl_softc->queue_lock);
11291	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11292	     io != NULL; io = next_io) {
11293		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11294		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11295			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11296				      ctl_io_hdr, links);
11297	}
11298	mtx_unlock(&ctl_softc->queue_lock);
11299#endif
11300
11301	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11302		lun = ctl_softc->ctl_luns[lun_idx];
11303		if (lun==NULL)
11304			continue;
11305
11306		/*
11307		 * Processor LUNs are primary on both sides.
11308		 * XXX will this always be true?
11309		 */
11310		if (lun->be_lun->lun_type == T_PROCESSOR)
11311			continue;
11312
11313		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11314		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11315			printf("FAILOVER: primary lun %d\n", lun_idx);
11316		        /*
11317			 * Remove all commands from the other SC. First from the
11318			 * blocked queue then from the ooa queue. Once we have
11319			 * removed them. Call ctl_check_blocked to see if there
11320			 * is anything that can run.
11321			 */
11322			for (io = (union ctl_io *)TAILQ_FIRST(
11323			     &lun->blocked_queue); io != NULL; io = next_io) {
11324
11325		        	next_io = (union ctl_io *)TAILQ_NEXT(
11326				    &io->io_hdr, blocked_links);
11327
11328				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11329					TAILQ_REMOVE(&lun->blocked_queue,
11330						     &io->io_hdr,blocked_links);
11331					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11332					TAILQ_REMOVE(&lun->ooa_queue,
11333						     &io->io_hdr, ooa_links);
11334
11335					ctl_free_io(io);
11336				}
11337			}
11338
11339			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11340	     		     io != NULL; io = next_io) {
11341
11342		        	next_io = (union ctl_io *)TAILQ_NEXT(
11343				    &io->io_hdr, ooa_links);
11344
11345				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11346
11347					TAILQ_REMOVE(&lun->ooa_queue,
11348						&io->io_hdr,
11349					     	ooa_links);
11350
11351					ctl_free_io(io);
11352				}
11353			}
11354			ctl_check_blocked(lun);
11355		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11356			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11357
11358			printf("FAILOVER: primary lun %d\n", lun_idx);
11359			/*
11360			 * Abort all commands from the other SC.  We can't
11361			 * send status back for them now.  These should get
11362			 * cleaned up when they are completed or come out
11363			 * for a datamove operation.
11364			 */
11365			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11366	     		     io != NULL; io = next_io) {
11367		        	next_io = (union ctl_io *)TAILQ_NEXT(
11368					&io->io_hdr, ooa_links);
11369
11370				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11371					io->io_hdr.flags |= CTL_FLAG_ABORT;
11372			}
11373		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11374			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11375
11376			printf("FAILOVER: secondary lun %d\n", lun_idx);
11377
11378			lun->flags |= CTL_LUN_PRIMARY_SC;
11379
11380			/*
11381			 * We send all I/O that was sent to this controller
11382			 * and redirected to the other side back with
11383			 * busy status, and have the initiator retry it.
11384			 * Figuring out how much data has been transferred,
11385			 * etc. and picking up where we left off would be
11386			 * very tricky.
11387			 *
11388			 * XXX KDM need to remove I/O from the blocked
11389			 * queue as well!
11390			 */
11391			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11392			     &lun->ooa_queue); pending_io != NULL;
11393			     pending_io = next_io) {
11394
11395				next_io =  (union ctl_io *)TAILQ_NEXT(
11396					&pending_io->io_hdr, ooa_links);
11397
11398				pending_io->io_hdr.flags &=
11399					~CTL_FLAG_SENT_2OTHER_SC;
11400
11401				if (pending_io->io_hdr.flags &
11402				    CTL_FLAG_IO_ACTIVE) {
11403					pending_io->io_hdr.flags |=
11404						CTL_FLAG_FAILOVER;
11405				} else {
11406					ctl_set_busy(&pending_io->scsiio);
11407					ctl_done(pending_io);
11408				}
11409			}
11410
11411			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11412		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11413			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11414			printf("FAILOVER: secondary lun %d\n", lun_idx);
11415			/*
11416			 * if the first io on the OOA is not on the RtR queue
11417			 * add it.
11418			 */
11419			lun->flags |= CTL_LUN_PRIMARY_SC;
11420
11421			pending_io = (union ctl_io *)TAILQ_FIRST(
11422			    &lun->ooa_queue);
11423			if (pending_io==NULL) {
11424				printf("Nothing on OOA queue\n");
11425				continue;
11426			}
11427
11428			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11429			if ((pending_io->io_hdr.flags &
11430			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11431				pending_io->io_hdr.flags |=
11432				    CTL_FLAG_IS_WAS_ON_RTR;
11433				ctl_enqueue_rtr(pending_io);
11434			}
11435#if 0
11436			else
11437			{
11438				printf("Tag 0x%04x is running\n",
11439				      pending_io->scsiio.tag_num);
11440			}
11441#endif
11442
11443			next_io = (union ctl_io *)TAILQ_NEXT(
11444			    &pending_io->io_hdr, ooa_links);
11445			for (pending_io=next_io; pending_io != NULL;
11446			     pending_io = next_io) {
11447				pending_io->io_hdr.flags &=
11448				    ~CTL_FLAG_SENT_2OTHER_SC;
11449				next_io = (union ctl_io *)TAILQ_NEXT(
11450					&pending_io->io_hdr, ooa_links);
11451				if (pending_io->io_hdr.flags &
11452				    CTL_FLAG_IS_WAS_ON_RTR) {
11453#if 0
11454				        printf("Tag 0x%04x is running\n",
11455				      		pending_io->scsiio.tag_num);
11456#endif
11457					continue;
11458				}
11459
11460				switch (ctl_check_ooa(lun, pending_io,
11461			            (union ctl_io *)TAILQ_PREV(
11462				    &pending_io->io_hdr, ctl_ooaq,
11463				    ooa_links))) {
11464
11465				case CTL_ACTION_BLOCK:
11466					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11467							  &pending_io->io_hdr,
11468							  blocked_links);
11469					pending_io->io_hdr.flags |=
11470					    CTL_FLAG_BLOCKED;
11471					break;
11472				case CTL_ACTION_PASS:
11473				case CTL_ACTION_SKIP:
11474					pending_io->io_hdr.flags |=
11475					    CTL_FLAG_IS_WAS_ON_RTR;
11476					ctl_enqueue_rtr(pending_io);
11477					break;
11478				case CTL_ACTION_OVERLAP:
11479					ctl_set_overlapped_cmd(
11480					    (struct ctl_scsiio *)pending_io);
11481					ctl_done(pending_io);
11482					break;
11483				case CTL_ACTION_OVERLAP_TAG:
11484					ctl_set_overlapped_tag(
11485					    (struct ctl_scsiio *)pending_io,
11486					    pending_io->scsiio.tag_num & 0xff);
11487					ctl_done(pending_io);
11488					break;
11489				case CTL_ACTION_ERROR:
11490				default:
11491					ctl_set_internal_failure(
11492						(struct ctl_scsiio *)pending_io,
11493						0,  // sks_valid
11494						0); //retry count
11495					ctl_done(pending_io);
11496					break;
11497				}
11498			}
11499
11500			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
11501		} else {
11502			panic("Unhandled HA mode failover, LUN flags = %#x, "
11503			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11504		}
11505	}
11506	ctl_pause_rtr = 0;
11507	mtx_unlock(&ctl_softc->ctl_lock);
11508}
11509
11510static int
11511ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11512{
11513	struct ctl_lun *lun;
11514	const struct ctl_cmd_entry *entry;
11515	uint32_t initidx, targ_lun;
11516	int retval;
11517
11518	retval = 0;
11519
11520	lun = NULL;
11521
11522	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11523	if ((targ_lun < CTL_MAX_LUNS)
11524	 && ((lun = ctl_softc->ctl_luns[targ_lun]) != NULL)) {
11525		/*
11526		 * If the LUN is invalid, pretend that it doesn't exist.
11527		 * It will go away as soon as all pending I/O has been
11528		 * completed.
11529		 */
11530		mtx_lock(&lun->lun_lock);
11531		if (lun->flags & CTL_LUN_DISABLED) {
11532			mtx_unlock(&lun->lun_lock);
11533			lun = NULL;
11534			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11535			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11536		} else {
11537			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11538			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11539				lun->be_lun;
11540			if (lun->be_lun->lun_type == T_PROCESSOR) {
11541				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11542			}
11543
11544			/*
11545			 * Every I/O goes into the OOA queue for a
11546			 * particular LUN, and stays there until completion.
11547			 */
11548			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11549			    ooa_links);
11550		}
11551	} else {
11552		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11553		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11554	}
11555
11556	/* Get command entry and return error if it is unsuppotyed. */
11557	entry = ctl_validate_command(ctsio);
11558	if (entry == NULL) {
11559		if (lun)
11560			mtx_unlock(&lun->lun_lock);
11561		return (retval);
11562	}
11563
11564	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11565	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11566
11567	/*
11568	 * Check to see whether we can send this command to LUNs that don't
11569	 * exist.  This should pretty much only be the case for inquiry
11570	 * and request sense.  Further checks, below, really require having
11571	 * a LUN, so we can't really check the command anymore.  Just put
11572	 * it on the rtr queue.
11573	 */
11574	if (lun == NULL) {
11575		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11576			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11577			ctl_enqueue_rtr((union ctl_io *)ctsio);
11578			return (retval);
11579		}
11580
11581		ctl_set_unsupported_lun(ctsio);
11582		ctl_done((union ctl_io *)ctsio);
11583		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11584		return (retval);
11585	} else {
11586		/*
11587		 * Make sure we support this particular command on this LUN.
11588		 * e.g., we don't support writes to the control LUN.
11589		 */
11590		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11591			mtx_unlock(&lun->lun_lock);
11592			ctl_set_invalid_opcode(ctsio);
11593			ctl_done((union ctl_io *)ctsio);
11594			return (retval);
11595		}
11596	}
11597
11598	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11599
11600#ifdef CTL_WITH_CA
11601	/*
11602	 * If we've got a request sense, it'll clear the contingent
11603	 * allegiance condition.  Otherwise, if we have a CA condition for
11604	 * this initiator, clear it, because it sent down a command other
11605	 * than request sense.
11606	 */
11607	if ((ctsio->cdb[0] != REQUEST_SENSE)
11608	 && (ctl_is_set(lun->have_ca, initidx)))
11609		ctl_clear_mask(lun->have_ca, initidx);
11610#endif
11611
11612	/*
11613	 * If the command has this flag set, it handles its own unit
11614	 * attention reporting, we shouldn't do anything.  Otherwise we
11615	 * check for any pending unit attentions, and send them back to the
11616	 * initiator.  We only do this when a command initially comes in,
11617	 * not when we pull it off the blocked queue.
11618	 *
11619	 * According to SAM-3, section 5.3.2, the order that things get
11620	 * presented back to the host is basically unit attentions caused
11621	 * by some sort of reset event, busy status, reservation conflicts
11622	 * or task set full, and finally any other status.
11623	 *
11624	 * One issue here is that some of the unit attentions we report
11625	 * don't fall into the "reset" category (e.g. "reported luns data
11626	 * has changed").  So reporting it here, before the reservation
11627	 * check, may be technically wrong.  I guess the only thing to do
11628	 * would be to check for and report the reset events here, and then
11629	 * check for the other unit attention types after we check for a
11630	 * reservation conflict.
11631	 *
11632	 * XXX KDM need to fix this
11633	 */
11634	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11635		ctl_ua_type ua_type;
11636		scsi_sense_data_type sense_format;
11637
11638		if (lun->flags & CTL_LUN_SENSE_DESC)
11639			sense_format = SSD_TYPE_DESC;
11640		else
11641			sense_format = SSD_TYPE_FIXED;
11642
11643		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11644		    sense_format);
11645		if (ua_type != CTL_UA_NONE) {
11646			mtx_unlock(&lun->lun_lock);
11647			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11648			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11649			ctsio->sense_len = SSD_FULL_SIZE;
11650			ctl_done((union ctl_io *)ctsio);
11651			return (retval);
11652		}
11653	}
11654
11655
11656	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11657		mtx_unlock(&lun->lun_lock);
11658		ctl_done((union ctl_io *)ctsio);
11659		return (retval);
11660	}
11661
11662	/*
11663	 * XXX CHD this is where we want to send IO to other side if
11664	 * this LUN is secondary on this SC. We will need to make a copy
11665	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11666	 * the copy we send as FROM_OTHER.
11667	 * We also need to stuff the address of the original IO so we can
11668	 * find it easily. Something similar will need be done on the other
11669	 * side so when we are done we can find the copy.
11670	 */
11671	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11672		union ctl_ha_msg msg_info;
11673		int isc_retval;
11674
11675		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11676
11677		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11678		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11679#if 0
11680		printf("1. ctsio %p\n", ctsio);
11681#endif
11682		msg_info.hdr.serializing_sc = NULL;
11683		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11684		msg_info.scsi.tag_num = ctsio->tag_num;
11685		msg_info.scsi.tag_type = ctsio->tag_type;
11686		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11687
11688		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11689
11690		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11691		    (void *)&msg_info, sizeof(msg_info), 0)) >
11692		    CTL_HA_STATUS_SUCCESS) {
11693			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11694			       isc_retval);
11695			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11696		} else {
11697#if 0
11698			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11699#endif
11700		}
11701
11702		/*
11703		 * XXX KDM this I/O is off the incoming queue, but hasn't
11704		 * been inserted on any other queue.  We may need to come
11705		 * up with a holding queue while we wait for serialization
11706		 * so that we have an idea of what we're waiting for from
11707		 * the other side.
11708		 */
11709		mtx_unlock(&lun->lun_lock);
11710		return (retval);
11711	}
11712
11713	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11714			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11715			      ctl_ooaq, ooa_links))) {
11716	case CTL_ACTION_BLOCK:
11717		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11718		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11719				  blocked_links);
11720		mtx_unlock(&lun->lun_lock);
11721		return (retval);
11722	case CTL_ACTION_PASS:
11723	case CTL_ACTION_SKIP:
11724		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11725		mtx_unlock(&lun->lun_lock);
11726		ctl_enqueue_rtr((union ctl_io *)ctsio);
11727		break;
11728	case CTL_ACTION_OVERLAP:
11729		mtx_unlock(&lun->lun_lock);
11730		ctl_set_overlapped_cmd(ctsio);
11731		ctl_done((union ctl_io *)ctsio);
11732		break;
11733	case CTL_ACTION_OVERLAP_TAG:
11734		mtx_unlock(&lun->lun_lock);
11735		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11736		ctl_done((union ctl_io *)ctsio);
11737		break;
11738	case CTL_ACTION_ERROR:
11739	default:
11740		mtx_unlock(&lun->lun_lock);
11741		ctl_set_internal_failure(ctsio,
11742					 /*sks_valid*/ 0,
11743					 /*retry_count*/ 0);
11744		ctl_done((union ctl_io *)ctsio);
11745		break;
11746	}
11747	return (retval);
11748}
11749
11750const struct ctl_cmd_entry *
11751ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11752{
11753	const struct ctl_cmd_entry *entry;
11754	int service_action;
11755
11756	entry = &ctl_cmd_table[ctsio->cdb[0]];
11757	if (sa)
11758		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11759	if (entry->flags & CTL_CMD_FLAG_SA5) {
11760		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11761		entry = &((const struct ctl_cmd_entry *)
11762		    entry->execute)[service_action];
11763	}
11764	return (entry);
11765}
11766
11767const struct ctl_cmd_entry *
11768ctl_validate_command(struct ctl_scsiio *ctsio)
11769{
11770	const struct ctl_cmd_entry *entry;
11771	int i, sa;
11772	uint8_t diff;
11773
11774	entry = ctl_get_cmd_entry(ctsio, &sa);
11775	if (entry->execute == NULL) {
11776		if (sa)
11777			ctl_set_invalid_field(ctsio,
11778					      /*sks_valid*/ 1,
11779					      /*command*/ 1,
11780					      /*field*/ 1,
11781					      /*bit_valid*/ 1,
11782					      /*bit*/ 4);
11783		else
11784			ctl_set_invalid_opcode(ctsio);
11785		ctl_done((union ctl_io *)ctsio);
11786		return (NULL);
11787	}
11788	KASSERT(entry->length > 0,
11789	    ("Not defined length for command 0x%02x/0x%02x",
11790	     ctsio->cdb[0], ctsio->cdb[1]));
11791	for (i = 1; i < entry->length; i++) {
11792		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11793		if (diff == 0)
11794			continue;
11795		ctl_set_invalid_field(ctsio,
11796				      /*sks_valid*/ 1,
11797				      /*command*/ 1,
11798				      /*field*/ i,
11799				      /*bit_valid*/ 1,
11800				      /*bit*/ fls(diff) - 1);
11801		ctl_done((union ctl_io *)ctsio);
11802		return (NULL);
11803	}
11804	return (entry);
11805}
11806
11807static int
11808ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11809{
11810
11811	switch (lun_type) {
11812	case T_PROCESSOR:
11813		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11814		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11815			return (0);
11816		break;
11817	case T_DIRECT:
11818		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11819		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11820			return (0);
11821		break;
11822	default:
11823		return (0);
11824	}
11825	return (1);
11826}
11827
11828static int
11829ctl_scsiio(struct ctl_scsiio *ctsio)
11830{
11831	int retval;
11832	const struct ctl_cmd_entry *entry;
11833
11834	retval = CTL_RETVAL_COMPLETE;
11835
11836	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11837
11838	entry = ctl_get_cmd_entry(ctsio, NULL);
11839
11840	/*
11841	 * If this I/O has been aborted, just send it straight to
11842	 * ctl_done() without executing it.
11843	 */
11844	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11845		ctl_done((union ctl_io *)ctsio);
11846		goto bailout;
11847	}
11848
11849	/*
11850	 * All the checks should have been handled by ctl_scsiio_precheck().
11851	 * We should be clear now to just execute the I/O.
11852	 */
11853	retval = entry->execute(ctsio);
11854
11855bailout:
11856	return (retval);
11857}
11858
11859/*
11860 * Since we only implement one target right now, a bus reset simply resets
11861 * our single target.
11862 */
11863static int
11864ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11865{
11866	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11867}
11868
11869static int
11870ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11871		 ctl_ua_type ua_type)
11872{
11873	struct ctl_lun *lun;
11874	int retval;
11875
11876	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11877		union ctl_ha_msg msg_info;
11878
11879		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11880		msg_info.hdr.nexus = io->io_hdr.nexus;
11881		if (ua_type==CTL_UA_TARG_RESET)
11882			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11883		else
11884			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11885		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11886		msg_info.hdr.original_sc = NULL;
11887		msg_info.hdr.serializing_sc = NULL;
11888		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11889		    (void *)&msg_info, sizeof(msg_info), 0)) {
11890		}
11891	}
11892	retval = 0;
11893
11894	mtx_lock(&ctl_softc->ctl_lock);
11895	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11896		retval += ctl_lun_reset(lun, io, ua_type);
11897	mtx_unlock(&ctl_softc->ctl_lock);
11898
11899	return (retval);
11900}
11901
11902/*
11903 * The LUN should always be set.  The I/O is optional, and is used to
11904 * distinguish between I/Os sent by this initiator, and by other
11905 * initiators.  We set unit attention for initiators other than this one.
11906 * SAM-3 is vague on this point.  It does say that a unit attention should
11907 * be established for other initiators when a LUN is reset (see section
11908 * 5.7.3), but it doesn't specifically say that the unit attention should
11909 * be established for this particular initiator when a LUN is reset.  Here
11910 * is the relevant text, from SAM-3 rev 8:
11911 *
11912 * 5.7.2 When a SCSI initiator port aborts its own tasks
11913 *
11914 * When a SCSI initiator port causes its own task(s) to be aborted, no
11915 * notification that the task(s) have been aborted shall be returned to
11916 * the SCSI initiator port other than the completion response for the
11917 * command or task management function action that caused the task(s) to
11918 * be aborted and notification(s) associated with related effects of the
11919 * action (e.g., a reset unit attention condition).
11920 *
11921 * XXX KDM for now, we're setting unit attention for all initiators.
11922 */
11923static int
11924ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11925{
11926	union ctl_io *xio;
11927#if 0
11928	uint32_t initidx;
11929#endif
11930#ifdef CTL_WITH_CA
11931	int i;
11932#endif
11933
11934	mtx_lock(&lun->lun_lock);
11935	/*
11936	 * Run through the OOA queue and abort each I/O.
11937	 */
11938#if 0
11939	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11940#endif
11941	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11942	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11943		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11944	}
11945
11946	/*
11947	 * This version sets unit attention for every
11948	 */
11949#if 0
11950	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11951	ctl_est_ua_all(lun, initidx, ua_type);
11952#else
11953	ctl_est_ua_all(lun, -1, ua_type);
11954#endif
11955
11956	/*
11957	 * A reset (any kind, really) clears reservations established with
11958	 * RESERVE/RELEASE.  It does not clear reservations established
11959	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11960	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11961	 * reservations made with the RESERVE/RELEASE commands, because
11962	 * those commands are obsolete in SPC-3.
11963	 */
11964	lun->flags &= ~CTL_LUN_RESERVED;
11965
11966#ifdef CTL_WITH_CA
11967	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11968		ctl_clear_mask(lun->have_ca, i);
11969#endif
11970	mtx_unlock(&lun->lun_lock);
11971
11972	return (0);
11973}
11974
11975static void
11976ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11977    int other_sc)
11978{
11979	union ctl_io *xio;
11980
11981	mtx_assert(&lun->lun_lock, MA_OWNED);
11982
11983	/*
11984	 * Run through the OOA queue and attempt to find the given I/O.
11985	 * The target port, initiator ID, tag type and tag number have to
11986	 * match the values that we got from the initiator.  If we have an
11987	 * untagged command to abort, simply abort the first untagged command
11988	 * we come to.  We only allow one untagged command at a time of course.
11989	 */
11990	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11991	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11992
11993		if ((targ_port == UINT32_MAX ||
11994		     targ_port == xio->io_hdr.nexus.targ_port) &&
11995		    (init_id == UINT32_MAX ||
11996		     init_id == xio->io_hdr.nexus.initid.id)) {
11997			if (targ_port != xio->io_hdr.nexus.targ_port ||
11998			    init_id != xio->io_hdr.nexus.initid.id)
11999				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12000			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12001			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12002				union ctl_ha_msg msg_info;
12003
12004				msg_info.hdr.nexus = xio->io_hdr.nexus;
12005				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12006				msg_info.task.tag_num = xio->scsiio.tag_num;
12007				msg_info.task.tag_type = xio->scsiio.tag_type;
12008				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12009				msg_info.hdr.original_sc = NULL;
12010				msg_info.hdr.serializing_sc = NULL;
12011				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12012				    (void *)&msg_info, sizeof(msg_info), 0);
12013			}
12014		}
12015	}
12016}
12017
12018static int
12019ctl_abort_task_set(union ctl_io *io)
12020{
12021	struct ctl_softc *softc = control_softc;
12022	struct ctl_lun *lun;
12023	uint32_t targ_lun;
12024
12025	/*
12026	 * Look up the LUN.
12027	 */
12028	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12029	mtx_lock(&softc->ctl_lock);
12030	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
12031		lun = softc->ctl_luns[targ_lun];
12032	else {
12033		mtx_unlock(&softc->ctl_lock);
12034		return (1);
12035	}
12036
12037	mtx_lock(&lun->lun_lock);
12038	mtx_unlock(&softc->ctl_lock);
12039	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12040		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12041		    io->io_hdr.nexus.initid.id,
12042		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12043	} else { /* CTL_TASK_CLEAR_TASK_SET */
12044		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12045		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12046	}
12047	mtx_unlock(&lun->lun_lock);
12048	return (0);
12049}
12050
12051static int
12052ctl_i_t_nexus_reset(union ctl_io *io)
12053{
12054	struct ctl_softc *softc = control_softc;
12055	struct ctl_lun *lun;
12056	uint32_t initidx, residx;
12057
12058	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12059	residx = ctl_get_resindex(&io->io_hdr.nexus);
12060	mtx_lock(&softc->ctl_lock);
12061	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12062		mtx_lock(&lun->lun_lock);
12063		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12064		    io->io_hdr.nexus.initid.id,
12065		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12066#ifdef CTL_WITH_CA
12067		ctl_clear_mask(lun->have_ca, initidx);
12068#endif
12069		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
12070			lun->flags &= ~CTL_LUN_RESERVED;
12071		ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12072		mtx_unlock(&lun->lun_lock);
12073	}
12074	mtx_unlock(&softc->ctl_lock);
12075	return (0);
12076}
12077
12078static int
12079ctl_abort_task(union ctl_io *io)
12080{
12081	union ctl_io *xio;
12082	struct ctl_lun *lun;
12083	struct ctl_softc *ctl_softc;
12084#if 0
12085	struct sbuf sb;
12086	char printbuf[128];
12087#endif
12088	int found;
12089	uint32_t targ_lun;
12090
12091	ctl_softc = control_softc;
12092	found = 0;
12093
12094	/*
12095	 * Look up the LUN.
12096	 */
12097	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12098	mtx_lock(&ctl_softc->ctl_lock);
12099	if ((targ_lun < CTL_MAX_LUNS)
12100	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12101		lun = ctl_softc->ctl_luns[targ_lun];
12102	else {
12103		mtx_unlock(&ctl_softc->ctl_lock);
12104		return (1);
12105	}
12106
12107#if 0
12108	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12109	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12110#endif
12111
12112	mtx_lock(&lun->lun_lock);
12113	mtx_unlock(&ctl_softc->ctl_lock);
12114	/*
12115	 * Run through the OOA queue and attempt to find the given I/O.
12116	 * The target port, initiator ID, tag type and tag number have to
12117	 * match the values that we got from the initiator.  If we have an
12118	 * untagged command to abort, simply abort the first untagged command
12119	 * we come to.  We only allow one untagged command at a time of course.
12120	 */
12121#if 0
12122	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12123#endif
12124	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12125	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12126#if 0
12127		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12128
12129		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12130			    lun->lun, xio->scsiio.tag_num,
12131			    xio->scsiio.tag_type,
12132			    (xio->io_hdr.blocked_links.tqe_prev
12133			    == NULL) ? "" : " BLOCKED",
12134			    (xio->io_hdr.flags &
12135			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12136			    (xio->io_hdr.flags &
12137			    CTL_FLAG_ABORT) ? " ABORT" : "",
12138			    (xio->io_hdr.flags &
12139			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12140		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12141		sbuf_finish(&sb);
12142		printf("%s\n", sbuf_data(&sb));
12143#endif
12144
12145		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12146		 && (xio->io_hdr.nexus.initid.id ==
12147		     io->io_hdr.nexus.initid.id)) {
12148			/*
12149			 * If the abort says that the task is untagged, the
12150			 * task in the queue must be untagged.  Otherwise,
12151			 * we just check to see whether the tag numbers
12152			 * match.  This is because the QLogic firmware
12153			 * doesn't pass back the tag type in an abort
12154			 * request.
12155			 */
12156#if 0
12157			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12158			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12159			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12160#endif
12161			/*
12162			 * XXX KDM we've got problems with FC, because it
12163			 * doesn't send down a tag type with aborts.  So we
12164			 * can only really go by the tag number...
12165			 * This may cause problems with parallel SCSI.
12166			 * Need to figure that out!!
12167			 */
12168			if (xio->scsiio.tag_num == io->taskio.tag_num) {
12169				xio->io_hdr.flags |= CTL_FLAG_ABORT;
12170				found = 1;
12171				if ((io->io_hdr.flags &
12172				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
12173				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12174					union ctl_ha_msg msg_info;
12175
12176					io->io_hdr.flags |=
12177					                CTL_FLAG_SENT_2OTHER_SC;
12178					msg_info.hdr.nexus = io->io_hdr.nexus;
12179					msg_info.task.task_action =
12180						CTL_TASK_ABORT_TASK;
12181					msg_info.task.tag_num =
12182						io->taskio.tag_num;
12183					msg_info.task.tag_type =
12184						io->taskio.tag_type;
12185					msg_info.hdr.msg_type =
12186						CTL_MSG_MANAGE_TASKS;
12187					msg_info.hdr.original_sc = NULL;
12188					msg_info.hdr.serializing_sc = NULL;
12189#if 0
12190					printf("Sent Abort to other side\n");
12191#endif
12192					if (CTL_HA_STATUS_SUCCESS !=
12193					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12194		    				(void *)&msg_info,
12195						sizeof(msg_info), 0)) {
12196					}
12197				}
12198#if 0
12199				printf("ctl_abort_task: found I/O to abort\n");
12200#endif
12201				break;
12202			}
12203		}
12204	}
12205	mtx_unlock(&lun->lun_lock);
12206
12207	if (found == 0) {
12208		/*
12209		 * This isn't really an error.  It's entirely possible for
12210		 * the abort and command completion to cross on the wire.
12211		 * This is more of an informative/diagnostic error.
12212		 */
12213#if 0
12214		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12215		       "%d:%d:%d:%d tag %d type %d\n",
12216		       io->io_hdr.nexus.initid.id,
12217		       io->io_hdr.nexus.targ_port,
12218		       io->io_hdr.nexus.targ_target.id,
12219		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12220		       io->taskio.tag_type);
12221#endif
12222	}
12223	return (0);
12224}
12225
12226static void
12227ctl_run_task(union ctl_io *io)
12228{
12229	struct ctl_softc *ctl_softc = control_softc;
12230	int retval = 1;
12231	const char *task_desc;
12232
12233	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12234
12235	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12236	    ("ctl_run_task: Unextected io_type %d\n",
12237	     io->io_hdr.io_type));
12238
12239	task_desc = ctl_scsi_task_string(&io->taskio);
12240	if (task_desc != NULL) {
12241#ifdef NEEDTOPORT
12242		csevent_log(CSC_CTL | CSC_SHELF_SW |
12243			    CTL_TASK_REPORT,
12244			    csevent_LogType_Trace,
12245			    csevent_Severity_Information,
12246			    csevent_AlertLevel_Green,
12247			    csevent_FRU_Firmware,
12248			    csevent_FRU_Unknown,
12249			    "CTL: received task: %s",task_desc);
12250#endif
12251	} else {
12252#ifdef NEEDTOPORT
12253		csevent_log(CSC_CTL | CSC_SHELF_SW |
12254			    CTL_TASK_REPORT,
12255			    csevent_LogType_Trace,
12256			    csevent_Severity_Information,
12257			    csevent_AlertLevel_Green,
12258			    csevent_FRU_Firmware,
12259			    csevent_FRU_Unknown,
12260			    "CTL: received unknown task "
12261			    "type: %d (%#x)",
12262			    io->taskio.task_action,
12263			    io->taskio.task_action);
12264#endif
12265	}
12266	switch (io->taskio.task_action) {
12267	case CTL_TASK_ABORT_TASK:
12268		retval = ctl_abort_task(io);
12269		break;
12270	case CTL_TASK_ABORT_TASK_SET:
12271	case CTL_TASK_CLEAR_TASK_SET:
12272		retval = ctl_abort_task_set(io);
12273		break;
12274	case CTL_TASK_CLEAR_ACA:
12275		break;
12276	case CTL_TASK_I_T_NEXUS_RESET:
12277		retval = ctl_i_t_nexus_reset(io);
12278		break;
12279	case CTL_TASK_LUN_RESET: {
12280		struct ctl_lun *lun;
12281		uint32_t targ_lun;
12282
12283		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12284		mtx_lock(&ctl_softc->ctl_lock);
12285		if ((targ_lun < CTL_MAX_LUNS)
12286		 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12287			lun = ctl_softc->ctl_luns[targ_lun];
12288		else {
12289			mtx_unlock(&ctl_softc->ctl_lock);
12290			retval = 1;
12291			break;
12292		}
12293
12294		if (!(io->io_hdr.flags &
12295		    CTL_FLAG_FROM_OTHER_SC)) {
12296			union ctl_ha_msg msg_info;
12297
12298			io->io_hdr.flags |=
12299				CTL_FLAG_SENT_2OTHER_SC;
12300			msg_info.hdr.msg_type =
12301				CTL_MSG_MANAGE_TASKS;
12302			msg_info.hdr.nexus = io->io_hdr.nexus;
12303			msg_info.task.task_action =
12304				CTL_TASK_LUN_RESET;
12305			msg_info.hdr.original_sc = NULL;
12306			msg_info.hdr.serializing_sc = NULL;
12307			if (CTL_HA_STATUS_SUCCESS !=
12308			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12309			    (void *)&msg_info,
12310			    sizeof(msg_info), 0)) {
12311			}
12312		}
12313
12314		retval = ctl_lun_reset(lun, io,
12315				       CTL_UA_LUN_RESET);
12316		mtx_unlock(&ctl_softc->ctl_lock);
12317		break;
12318	}
12319	case CTL_TASK_TARGET_RESET:
12320		retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12321		break;
12322	case CTL_TASK_BUS_RESET:
12323		retval = ctl_bus_reset(ctl_softc, io);
12324		break;
12325	case CTL_TASK_PORT_LOGIN:
12326		break;
12327	case CTL_TASK_PORT_LOGOUT:
12328		break;
12329	default:
12330		printf("ctl_run_task: got unknown task management event %d\n",
12331		       io->taskio.task_action);
12332		break;
12333	}
12334	if (retval == 0)
12335		io->io_hdr.status = CTL_SUCCESS;
12336	else
12337		io->io_hdr.status = CTL_ERROR;
12338	ctl_done(io);
12339}
12340
12341/*
12342 * For HA operation.  Handle commands that come in from the other
12343 * controller.
12344 */
12345static void
12346ctl_handle_isc(union ctl_io *io)
12347{
12348	int free_io;
12349	struct ctl_lun *lun;
12350	struct ctl_softc *ctl_softc;
12351	uint32_t targ_lun;
12352
12353	ctl_softc = control_softc;
12354
12355	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12356	lun = ctl_softc->ctl_luns[targ_lun];
12357
12358	switch (io->io_hdr.msg_type) {
12359	case CTL_MSG_SERIALIZE:
12360		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12361		break;
12362	case CTL_MSG_R2R: {
12363		const struct ctl_cmd_entry *entry;
12364
12365		/*
12366		 * This is only used in SER_ONLY mode.
12367		 */
12368		free_io = 0;
12369		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12370		mtx_lock(&lun->lun_lock);
12371		if (ctl_scsiio_lun_check(ctl_softc, lun,
12372		    entry, (struct ctl_scsiio *)io) != 0) {
12373			mtx_unlock(&lun->lun_lock);
12374			ctl_done(io);
12375			break;
12376		}
12377		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12378		mtx_unlock(&lun->lun_lock);
12379		ctl_enqueue_rtr(io);
12380		break;
12381	}
12382	case CTL_MSG_FINISH_IO:
12383		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12384			free_io = 0;
12385			ctl_done(io);
12386		} else {
12387			free_io = 1;
12388			mtx_lock(&lun->lun_lock);
12389			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12390				     ooa_links);
12391			ctl_check_blocked(lun);
12392			mtx_unlock(&lun->lun_lock);
12393		}
12394		break;
12395	case CTL_MSG_PERS_ACTION:
12396		ctl_hndl_per_res_out_on_other_sc(
12397			(union ctl_ha_msg *)&io->presio.pr_msg);
12398		free_io = 1;
12399		break;
12400	case CTL_MSG_BAD_JUJU:
12401		free_io = 0;
12402		ctl_done(io);
12403		break;
12404	case CTL_MSG_DATAMOVE:
12405		/* Only used in XFER mode */
12406		free_io = 0;
12407		ctl_datamove_remote(io);
12408		break;
12409	case CTL_MSG_DATAMOVE_DONE:
12410		/* Only used in XFER mode */
12411		free_io = 0;
12412		io->scsiio.be_move_done(io);
12413		break;
12414	default:
12415		free_io = 1;
12416		printf("%s: Invalid message type %d\n",
12417		       __func__, io->io_hdr.msg_type);
12418		break;
12419	}
12420	if (free_io)
12421		ctl_free_io(io);
12422
12423}
12424
12425
12426/*
12427 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12428 * there is no match.
12429 */
12430static ctl_lun_error_pattern
12431ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12432{
12433	const struct ctl_cmd_entry *entry;
12434	ctl_lun_error_pattern filtered_pattern, pattern;
12435
12436	pattern = desc->error_pattern;
12437
12438	/*
12439	 * XXX KDM we need more data passed into this function to match a
12440	 * custom pattern, and we actually need to implement custom pattern
12441	 * matching.
12442	 */
12443	if (pattern & CTL_LUN_PAT_CMD)
12444		return (CTL_LUN_PAT_CMD);
12445
12446	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12447		return (CTL_LUN_PAT_ANY);
12448
12449	entry = ctl_get_cmd_entry(ctsio, NULL);
12450
12451	filtered_pattern = entry->pattern & pattern;
12452
12453	/*
12454	 * If the user requested specific flags in the pattern (e.g.
12455	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12456	 * flags.
12457	 *
12458	 * If the user did not specify any flags, it doesn't matter whether
12459	 * or not the command supports the flags.
12460	 */
12461	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12462	     (pattern & ~CTL_LUN_PAT_MASK))
12463		return (CTL_LUN_PAT_NONE);
12464
12465	/*
12466	 * If the user asked for a range check, see if the requested LBA
12467	 * range overlaps with this command's LBA range.
12468	 */
12469	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12470		uint64_t lba1;
12471		uint64_t len1;
12472		ctl_action action;
12473		int retval;
12474
12475		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12476		if (retval != 0)
12477			return (CTL_LUN_PAT_NONE);
12478
12479		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12480					      desc->lba_range.len, FALSE);
12481		/*
12482		 * A "pass" means that the LBA ranges don't overlap, so
12483		 * this doesn't match the user's range criteria.
12484		 */
12485		if (action == CTL_ACTION_PASS)
12486			return (CTL_LUN_PAT_NONE);
12487	}
12488
12489	return (filtered_pattern);
12490}
12491
12492static void
12493ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12494{
12495	struct ctl_error_desc *desc, *desc2;
12496
12497	mtx_assert(&lun->lun_lock, MA_OWNED);
12498
12499	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12500		ctl_lun_error_pattern pattern;
12501		/*
12502		 * Check to see whether this particular command matches
12503		 * the pattern in the descriptor.
12504		 */
12505		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12506		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12507			continue;
12508
12509		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12510		case CTL_LUN_INJ_ABORTED:
12511			ctl_set_aborted(&io->scsiio);
12512			break;
12513		case CTL_LUN_INJ_MEDIUM_ERR:
12514			ctl_set_medium_error(&io->scsiio);
12515			break;
12516		case CTL_LUN_INJ_UA:
12517			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12518			 * OCCURRED */
12519			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12520			break;
12521		case CTL_LUN_INJ_CUSTOM:
12522			/*
12523			 * We're assuming the user knows what he is doing.
12524			 * Just copy the sense information without doing
12525			 * checks.
12526			 */
12527			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12528			      ctl_min(sizeof(desc->custom_sense),
12529				      sizeof(io->scsiio.sense_data)));
12530			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12531			io->scsiio.sense_len = SSD_FULL_SIZE;
12532			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12533			break;
12534		case CTL_LUN_INJ_NONE:
12535		default:
12536			/*
12537			 * If this is an error injection type we don't know
12538			 * about, clear the continuous flag (if it is set)
12539			 * so it will get deleted below.
12540			 */
12541			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12542			break;
12543		}
12544		/*
12545		 * By default, each error injection action is a one-shot
12546		 */
12547		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12548			continue;
12549
12550		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12551
12552		free(desc, M_CTL);
12553	}
12554}
12555
12556#ifdef CTL_IO_DELAY
12557static void
12558ctl_datamove_timer_wakeup(void *arg)
12559{
12560	union ctl_io *io;
12561
12562	io = (union ctl_io *)arg;
12563
12564	ctl_datamove(io);
12565}
12566#endif /* CTL_IO_DELAY */
12567
12568void
12569ctl_datamove(union ctl_io *io)
12570{
12571	void (*fe_datamove)(union ctl_io *io);
12572
12573	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12574
12575	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12576
12577#ifdef CTL_TIME_IO
12578	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12579		char str[256];
12580		char path_str[64];
12581		struct sbuf sb;
12582
12583		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12584		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12585
12586		sbuf_cat(&sb, path_str);
12587		switch (io->io_hdr.io_type) {
12588		case CTL_IO_SCSI:
12589			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12590			sbuf_printf(&sb, "\n");
12591			sbuf_cat(&sb, path_str);
12592			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12593				    io->scsiio.tag_num, io->scsiio.tag_type);
12594			break;
12595		case CTL_IO_TASK:
12596			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12597				    "Tag Type: %d\n", io->taskio.task_action,
12598				    io->taskio.tag_num, io->taskio.tag_type);
12599			break;
12600		default:
12601			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12602			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12603			break;
12604		}
12605		sbuf_cat(&sb, path_str);
12606		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12607			    (intmax_t)time_uptime - io->io_hdr.start_time);
12608		sbuf_finish(&sb);
12609		printf("%s", sbuf_data(&sb));
12610	}
12611#endif /* CTL_TIME_IO */
12612
12613#ifdef CTL_IO_DELAY
12614	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12615		struct ctl_lun *lun;
12616
12617		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12618
12619		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12620	} else {
12621		struct ctl_lun *lun;
12622
12623		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12624		if ((lun != NULL)
12625		 && (lun->delay_info.datamove_delay > 0)) {
12626			struct callout *callout;
12627
12628			callout = (struct callout *)&io->io_hdr.timer_bytes;
12629			callout_init(callout, /*mpsafe*/ 1);
12630			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12631			callout_reset(callout,
12632				      lun->delay_info.datamove_delay * hz,
12633				      ctl_datamove_timer_wakeup, io);
12634			if (lun->delay_info.datamove_type ==
12635			    CTL_DELAY_TYPE_ONESHOT)
12636				lun->delay_info.datamove_delay = 0;
12637			return;
12638		}
12639	}
12640#endif
12641
12642	/*
12643	 * This command has been aborted.  Set the port status, so we fail
12644	 * the data move.
12645	 */
12646	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12647		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12648		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12649		       io->io_hdr.nexus.targ_port,
12650		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12651		       io->io_hdr.nexus.targ_lun);
12652		io->io_hdr.port_status = 31337;
12653		/*
12654		 * Note that the backend, in this case, will get the
12655		 * callback in its context.  In other cases it may get
12656		 * called in the frontend's interrupt thread context.
12657		 */
12658		io->scsiio.be_move_done(io);
12659		return;
12660	}
12661
12662	/* Don't confuse frontend with zero length data move. */
12663	if (io->scsiio.kern_data_len == 0) {
12664		io->scsiio.be_move_done(io);
12665		return;
12666	}
12667
12668	/*
12669	 * If we're in XFER mode and this I/O is from the other shelf
12670	 * controller, we need to send the DMA to the other side to
12671	 * actually transfer the data to/from the host.  In serialize only
12672	 * mode the transfer happens below CTL and ctl_datamove() is only
12673	 * called on the machine that originally received the I/O.
12674	 */
12675	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12676	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12677		union ctl_ha_msg msg;
12678		uint32_t sg_entries_sent;
12679		int do_sg_copy;
12680		int i;
12681
12682		memset(&msg, 0, sizeof(msg));
12683		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12684		msg.hdr.original_sc = io->io_hdr.original_sc;
12685		msg.hdr.serializing_sc = io;
12686		msg.hdr.nexus = io->io_hdr.nexus;
12687		msg.dt.flags = io->io_hdr.flags;
12688		/*
12689		 * We convert everything into a S/G list here.  We can't
12690		 * pass by reference, only by value between controllers.
12691		 * So we can't pass a pointer to the S/G list, only as many
12692		 * S/G entries as we can fit in here.  If it's possible for
12693		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12694		 * then we need to break this up into multiple transfers.
12695		 */
12696		if (io->scsiio.kern_sg_entries == 0) {
12697			msg.dt.kern_sg_entries = 1;
12698			/*
12699			 * If this is in cached memory, flush the cache
12700			 * before we send the DMA request to the other
12701			 * controller.  We want to do this in either the
12702			 * read or the write case.  The read case is
12703			 * straightforward.  In the write case, we want to
12704			 * make sure nothing is in the local cache that
12705			 * could overwrite the DMAed data.
12706			 */
12707			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12708				/*
12709				 * XXX KDM use bus_dmamap_sync() here.
12710				 */
12711			}
12712
12713			/*
12714			 * Convert to a physical address if this is a
12715			 * virtual address.
12716			 */
12717			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12718				msg.dt.sg_list[0].addr =
12719					io->scsiio.kern_data_ptr;
12720			} else {
12721				/*
12722				 * XXX KDM use busdma here!
12723				 */
12724#if 0
12725				msg.dt.sg_list[0].addr = (void *)
12726					vtophys(io->scsiio.kern_data_ptr);
12727#endif
12728			}
12729
12730			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12731			do_sg_copy = 0;
12732		} else {
12733			struct ctl_sg_entry *sgl;
12734
12735			do_sg_copy = 1;
12736			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12737			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12738			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12739				/*
12740				 * XXX KDM use bus_dmamap_sync() here.
12741				 */
12742			}
12743		}
12744
12745		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12746		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12747		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12748		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12749		msg.dt.sg_sequence = 0;
12750
12751		/*
12752		 * Loop until we've sent all of the S/G entries.  On the
12753		 * other end, we'll recompose these S/G entries into one
12754		 * contiguous list before passing it to the
12755		 */
12756		for (sg_entries_sent = 0; sg_entries_sent <
12757		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12758			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12759				sizeof(msg.dt.sg_list[0])),
12760				msg.dt.kern_sg_entries - sg_entries_sent);
12761
12762			if (do_sg_copy != 0) {
12763				struct ctl_sg_entry *sgl;
12764				int j;
12765
12766				sgl = (struct ctl_sg_entry *)
12767					io->scsiio.kern_data_ptr;
12768				/*
12769				 * If this is in cached memory, flush the cache
12770				 * before we send the DMA request to the other
12771				 * controller.  We want to do this in either
12772				 * the * read or the write case.  The read
12773				 * case is straightforward.  In the write
12774				 * case, we want to make sure nothing is
12775				 * in the local cache that could overwrite
12776				 * the DMAed data.
12777				 */
12778
12779				for (i = sg_entries_sent, j = 0;
12780				     i < msg.dt.cur_sg_entries; i++, j++) {
12781					if ((io->io_hdr.flags &
12782					     CTL_FLAG_NO_DATASYNC) == 0) {
12783						/*
12784						 * XXX KDM use bus_dmamap_sync()
12785						 */
12786					}
12787					if ((io->io_hdr.flags &
12788					     CTL_FLAG_BUS_ADDR) == 0) {
12789						/*
12790						 * XXX KDM use busdma.
12791						 */
12792#if 0
12793						msg.dt.sg_list[j].addr =(void *)
12794						       vtophys(sgl[i].addr);
12795#endif
12796					} else {
12797						msg.dt.sg_list[j].addr =
12798							sgl[i].addr;
12799					}
12800					msg.dt.sg_list[j].len = sgl[i].len;
12801				}
12802			}
12803
12804			sg_entries_sent += msg.dt.cur_sg_entries;
12805			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12806				msg.dt.sg_last = 1;
12807			else
12808				msg.dt.sg_last = 0;
12809
12810			/*
12811			 * XXX KDM drop and reacquire the lock here?
12812			 */
12813			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12814			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12815				/*
12816				 * XXX do something here.
12817				 */
12818			}
12819
12820			msg.dt.sent_sg_entries = sg_entries_sent;
12821		}
12822		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12823		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12824			ctl_failover_io(io, /*have_lock*/ 0);
12825
12826	} else {
12827
12828		/*
12829		 * Lookup the fe_datamove() function for this particular
12830		 * front end.
12831		 */
12832		fe_datamove =
12833		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12834
12835		fe_datamove(io);
12836	}
12837}
12838
12839static void
12840ctl_send_datamove_done(union ctl_io *io, int have_lock)
12841{
12842	union ctl_ha_msg msg;
12843	int isc_status;
12844
12845	memset(&msg, 0, sizeof(msg));
12846
12847	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12848	msg.hdr.original_sc = io;
12849	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12850	msg.hdr.nexus = io->io_hdr.nexus;
12851	msg.hdr.status = io->io_hdr.status;
12852	msg.scsi.tag_num = io->scsiio.tag_num;
12853	msg.scsi.tag_type = io->scsiio.tag_type;
12854	msg.scsi.scsi_status = io->scsiio.scsi_status;
12855	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12856	       sizeof(io->scsiio.sense_data));
12857	msg.scsi.sense_len = io->scsiio.sense_len;
12858	msg.scsi.sense_residual = io->scsiio.sense_residual;
12859	msg.scsi.fetd_status = io->io_hdr.port_status;
12860	msg.scsi.residual = io->scsiio.residual;
12861	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12862
12863	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12864		ctl_failover_io(io, /*have_lock*/ have_lock);
12865		return;
12866	}
12867
12868	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12869	if (isc_status > CTL_HA_STATUS_SUCCESS) {
12870		/* XXX do something if this fails */
12871	}
12872
12873}
12874
12875/*
12876 * The DMA to the remote side is done, now we need to tell the other side
12877 * we're done so it can continue with its data movement.
12878 */
12879static void
12880ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12881{
12882	union ctl_io *io;
12883
12884	io = rq->context;
12885
12886	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12887		printf("%s: ISC DMA write failed with error %d", __func__,
12888		       rq->ret);
12889		ctl_set_internal_failure(&io->scsiio,
12890					 /*sks_valid*/ 1,
12891					 /*retry_count*/ rq->ret);
12892	}
12893
12894	ctl_dt_req_free(rq);
12895
12896	/*
12897	 * In this case, we had to malloc the memory locally.  Free it.
12898	 */
12899	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12900		int i;
12901		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12902			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12903	}
12904	/*
12905	 * The data is in local and remote memory, so now we need to send
12906	 * status (good or back) back to the other side.
12907	 */
12908	ctl_send_datamove_done(io, /*have_lock*/ 0);
12909}
12910
12911/*
12912 * We've moved the data from the host/controller into local memory.  Now we
12913 * need to push it over to the remote controller's memory.
12914 */
12915static int
12916ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12917{
12918	int retval;
12919
12920	retval = 0;
12921
12922	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12923					  ctl_datamove_remote_write_cb);
12924
12925	return (retval);
12926}
12927
12928static void
12929ctl_datamove_remote_write(union ctl_io *io)
12930{
12931	int retval;
12932	void (*fe_datamove)(union ctl_io *io);
12933
12934	/*
12935	 * - Get the data from the host/HBA into local memory.
12936	 * - DMA memory from the local controller to the remote controller.
12937	 * - Send status back to the remote controller.
12938	 */
12939
12940	retval = ctl_datamove_remote_sgl_setup(io);
12941	if (retval != 0)
12942		return;
12943
12944	/* Switch the pointer over so the FETD knows what to do */
12945	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12946
12947	/*
12948	 * Use a custom move done callback, since we need to send completion
12949	 * back to the other controller, not to the backend on this side.
12950	 */
12951	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12952
12953	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12954
12955	fe_datamove(io);
12956
12957	return;
12958
12959}
12960
12961static int
12962ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12963{
12964#if 0
12965	char str[256];
12966	char path_str[64];
12967	struct sbuf sb;
12968#endif
12969
12970	/*
12971	 * In this case, we had to malloc the memory locally.  Free it.
12972	 */
12973	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12974		int i;
12975		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12976			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12977	}
12978
12979#if 0
12980	scsi_path_string(io, path_str, sizeof(path_str));
12981	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12982	sbuf_cat(&sb, path_str);
12983	scsi_command_string(&io->scsiio, NULL, &sb);
12984	sbuf_printf(&sb, "\n");
12985	sbuf_cat(&sb, path_str);
12986	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12987		    io->scsiio.tag_num, io->scsiio.tag_type);
12988	sbuf_cat(&sb, path_str);
12989	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12990		    io->io_hdr.flags, io->io_hdr.status);
12991	sbuf_finish(&sb);
12992	printk("%s", sbuf_data(&sb));
12993#endif
12994
12995
12996	/*
12997	 * The read is done, now we need to send status (good or bad) back
12998	 * to the other side.
12999	 */
13000	ctl_send_datamove_done(io, /*have_lock*/ 0);
13001
13002	return (0);
13003}
13004
13005static void
13006ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
13007{
13008	union ctl_io *io;
13009	void (*fe_datamove)(union ctl_io *io);
13010
13011	io = rq->context;
13012
13013	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13014		printf("%s: ISC DMA read failed with error %d", __func__,
13015		       rq->ret);
13016		ctl_set_internal_failure(&io->scsiio,
13017					 /*sks_valid*/ 1,
13018					 /*retry_count*/ rq->ret);
13019	}
13020
13021	ctl_dt_req_free(rq);
13022
13023	/* Switch the pointer over so the FETD knows what to do */
13024	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13025
13026	/*
13027	 * Use a custom move done callback, since we need to send completion
13028	 * back to the other controller, not to the backend on this side.
13029	 */
13030	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
13031
13032	/* XXX KDM add checks like the ones in ctl_datamove? */
13033
13034	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13035
13036	fe_datamove(io);
13037}
13038
13039static int
13040ctl_datamove_remote_sgl_setup(union ctl_io *io)
13041{
13042	struct ctl_sg_entry *local_sglist, *remote_sglist;
13043	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13044	struct ctl_softc *softc;
13045	int retval;
13046	int i;
13047
13048	retval = 0;
13049	softc = control_softc;
13050
13051	local_sglist = io->io_hdr.local_sglist;
13052	local_dma_sglist = io->io_hdr.local_dma_sglist;
13053	remote_sglist = io->io_hdr.remote_sglist;
13054	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13055
13056	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13057		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13058			local_sglist[i].len = remote_sglist[i].len;
13059
13060			/*
13061			 * XXX Detect the situation where the RS-level I/O
13062			 * redirector on the other side has already read the
13063			 * data off of the AOR RS on this side, and
13064			 * transferred it to remote (mirror) memory on the
13065			 * other side.  Since we already have the data in
13066			 * memory here, we just need to use it.
13067			 *
13068			 * XXX KDM this can probably be removed once we
13069			 * get the cache device code in and take the
13070			 * current AOR implementation out.
13071			 */
13072#ifdef NEEDTOPORT
13073			if ((remote_sglist[i].addr >=
13074			     (void *)vtophys(softc->mirr->addr))
13075			 && (remote_sglist[i].addr <
13076			     ((void *)vtophys(softc->mirr->addr) +
13077			     CacheMirrorOffset))) {
13078				local_sglist[i].addr = remote_sglist[i].addr -
13079					CacheMirrorOffset;
13080				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13081				     CTL_FLAG_DATA_IN)
13082					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13083			} else {
13084				local_sglist[i].addr = remote_sglist[i].addr +
13085					CacheMirrorOffset;
13086			}
13087#endif
13088#if 0
13089			printf("%s: local %p, remote %p, len %d\n",
13090			       __func__, local_sglist[i].addr,
13091			       remote_sglist[i].addr, local_sglist[i].len);
13092#endif
13093		}
13094	} else {
13095		uint32_t len_to_go;
13096
13097		/*
13098		 * In this case, we don't have automatically allocated
13099		 * memory for this I/O on this controller.  This typically
13100		 * happens with internal CTL I/O -- e.g. inquiry, mode
13101		 * sense, etc.  Anything coming from RAIDCore will have
13102		 * a mirror area available.
13103		 */
13104		len_to_go = io->scsiio.kern_data_len;
13105
13106		/*
13107		 * Clear the no datasync flag, we have to use malloced
13108		 * buffers.
13109		 */
13110		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13111
13112		/*
13113		 * The difficult thing here is that the size of the various
13114		 * S/G segments may be different than the size from the
13115		 * remote controller.  That'll make it harder when DMAing
13116		 * the data back to the other side.
13117		 */
13118		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13119		     sizeof(io->io_hdr.remote_sglist[0])) &&
13120		     (len_to_go > 0); i++) {
13121			local_sglist[i].len = ctl_min(len_to_go, 131072);
13122			CTL_SIZE_8B(local_dma_sglist[i].len,
13123				    local_sglist[i].len);
13124			local_sglist[i].addr =
13125				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13126
13127			local_dma_sglist[i].addr = local_sglist[i].addr;
13128
13129			if (local_sglist[i].addr == NULL) {
13130				int j;
13131
13132				printf("malloc failed for %zd bytes!",
13133				       local_dma_sglist[i].len);
13134				for (j = 0; j < i; j++) {
13135					free(local_sglist[j].addr, M_CTL);
13136				}
13137				ctl_set_internal_failure(&io->scsiio,
13138							 /*sks_valid*/ 1,
13139							 /*retry_count*/ 4857);
13140				retval = 1;
13141				goto bailout_error;
13142
13143			}
13144			/* XXX KDM do we need a sync here? */
13145
13146			len_to_go -= local_sglist[i].len;
13147		}
13148		/*
13149		 * Reset the number of S/G entries accordingly.  The
13150		 * original number of S/G entries is available in
13151		 * rem_sg_entries.
13152		 */
13153		io->scsiio.kern_sg_entries = i;
13154
13155#if 0
13156		printf("%s: kern_sg_entries = %d\n", __func__,
13157		       io->scsiio.kern_sg_entries);
13158		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13159			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13160			       local_sglist[i].addr, local_sglist[i].len,
13161			       local_dma_sglist[i].len);
13162#endif
13163	}
13164
13165
13166	return (retval);
13167
13168bailout_error:
13169
13170	ctl_send_datamove_done(io, /*have_lock*/ 0);
13171
13172	return (retval);
13173}
13174
13175static int
13176ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13177			 ctl_ha_dt_cb callback)
13178{
13179	struct ctl_ha_dt_req *rq;
13180	struct ctl_sg_entry *remote_sglist, *local_sglist;
13181	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13182	uint32_t local_used, remote_used, total_used;
13183	int retval;
13184	int i, j;
13185
13186	retval = 0;
13187
13188	rq = ctl_dt_req_alloc();
13189
13190	/*
13191	 * If we failed to allocate the request, and if the DMA didn't fail
13192	 * anyway, set busy status.  This is just a resource allocation
13193	 * failure.
13194	 */
13195	if ((rq == NULL)
13196	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13197		ctl_set_busy(&io->scsiio);
13198
13199	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13200
13201		if (rq != NULL)
13202			ctl_dt_req_free(rq);
13203
13204		/*
13205		 * The data move failed.  We need to return status back
13206		 * to the other controller.  No point in trying to DMA
13207		 * data to the remote controller.
13208		 */
13209
13210		ctl_send_datamove_done(io, /*have_lock*/ 0);
13211
13212		retval = 1;
13213
13214		goto bailout;
13215	}
13216
13217	local_sglist = io->io_hdr.local_sglist;
13218	local_dma_sglist = io->io_hdr.local_dma_sglist;
13219	remote_sglist = io->io_hdr.remote_sglist;
13220	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13221	local_used = 0;
13222	remote_used = 0;
13223	total_used = 0;
13224
13225	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13226		rq->ret = CTL_HA_STATUS_SUCCESS;
13227		rq->context = io;
13228		callback(rq);
13229		goto bailout;
13230	}
13231
13232	/*
13233	 * Pull/push the data over the wire from/to the other controller.
13234	 * This takes into account the possibility that the local and
13235	 * remote sglists may not be identical in terms of the size of
13236	 * the elements and the number of elements.
13237	 *
13238	 * One fundamental assumption here is that the length allocated for
13239	 * both the local and remote sglists is identical.  Otherwise, we've
13240	 * essentially got a coding error of some sort.
13241	 */
13242	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13243		int isc_ret;
13244		uint32_t cur_len, dma_length;
13245		uint8_t *tmp_ptr;
13246
13247		rq->id = CTL_HA_DATA_CTL;
13248		rq->command = command;
13249		rq->context = io;
13250
13251		/*
13252		 * Both pointers should be aligned.  But it is possible
13253		 * that the allocation length is not.  They should both
13254		 * also have enough slack left over at the end, though,
13255		 * to round up to the next 8 byte boundary.
13256		 */
13257		cur_len = ctl_min(local_sglist[i].len - local_used,
13258				  remote_sglist[j].len - remote_used);
13259
13260		/*
13261		 * In this case, we have a size issue and need to decrease
13262		 * the size, except in the case where we actually have less
13263		 * than 8 bytes left.  In that case, we need to increase
13264		 * the DMA length to get the last bit.
13265		 */
13266		if ((cur_len & 0x7) != 0) {
13267			if (cur_len > 0x7) {
13268				cur_len = cur_len - (cur_len & 0x7);
13269				dma_length = cur_len;
13270			} else {
13271				CTL_SIZE_8B(dma_length, cur_len);
13272			}
13273
13274		} else
13275			dma_length = cur_len;
13276
13277		/*
13278		 * If we had to allocate memory for this I/O, instead of using
13279		 * the non-cached mirror memory, we'll need to flush the cache
13280		 * before trying to DMA to the other controller.
13281		 *
13282		 * We could end up doing this multiple times for the same
13283		 * segment if we have a larger local segment than remote
13284		 * segment.  That shouldn't be an issue.
13285		 */
13286		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13287			/*
13288			 * XXX KDM use bus_dmamap_sync() here.
13289			 */
13290		}
13291
13292		rq->size = dma_length;
13293
13294		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13295		tmp_ptr += local_used;
13296
13297		/* Use physical addresses when talking to ISC hardware */
13298		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13299			/* XXX KDM use busdma */
13300#if 0
13301			rq->local = vtophys(tmp_ptr);
13302#endif
13303		} else
13304			rq->local = tmp_ptr;
13305
13306		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13307		tmp_ptr += remote_used;
13308		rq->remote = tmp_ptr;
13309
13310		rq->callback = NULL;
13311
13312		local_used += cur_len;
13313		if (local_used >= local_sglist[i].len) {
13314			i++;
13315			local_used = 0;
13316		}
13317
13318		remote_used += cur_len;
13319		if (remote_used >= remote_sglist[j].len) {
13320			j++;
13321			remote_used = 0;
13322		}
13323		total_used += cur_len;
13324
13325		if (total_used >= io->scsiio.kern_data_len)
13326			rq->callback = callback;
13327
13328		if ((rq->size & 0x7) != 0) {
13329			printf("%s: warning: size %d is not on 8b boundary\n",
13330			       __func__, rq->size);
13331		}
13332		if (((uintptr_t)rq->local & 0x7) != 0) {
13333			printf("%s: warning: local %p not on 8b boundary\n",
13334			       __func__, rq->local);
13335		}
13336		if (((uintptr_t)rq->remote & 0x7) != 0) {
13337			printf("%s: warning: remote %p not on 8b boundary\n",
13338			       __func__, rq->local);
13339		}
13340#if 0
13341		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13342		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13343		       rq->local, rq->remote, rq->size);
13344#endif
13345
13346		isc_ret = ctl_dt_single(rq);
13347		if (isc_ret == CTL_HA_STATUS_WAIT)
13348			continue;
13349
13350		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13351			rq->ret = CTL_HA_STATUS_SUCCESS;
13352		} else {
13353			rq->ret = isc_ret;
13354		}
13355		callback(rq);
13356		goto bailout;
13357	}
13358
13359bailout:
13360	return (retval);
13361
13362}
13363
13364static void
13365ctl_datamove_remote_read(union ctl_io *io)
13366{
13367	int retval;
13368	int i;
13369
13370	/*
13371	 * This will send an error to the other controller in the case of a
13372	 * failure.
13373	 */
13374	retval = ctl_datamove_remote_sgl_setup(io);
13375	if (retval != 0)
13376		return;
13377
13378	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13379					  ctl_datamove_remote_read_cb);
13380	if ((retval != 0)
13381	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13382		/*
13383		 * Make sure we free memory if there was an error..  The
13384		 * ctl_datamove_remote_xfer() function will send the
13385		 * datamove done message, or call the callback with an
13386		 * error if there is a problem.
13387		 */
13388		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13389			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13390	}
13391
13392	return;
13393}
13394
13395/*
13396 * Process a datamove request from the other controller.  This is used for
13397 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13398 * first.  Once that is complete, the data gets DMAed into the remote
13399 * controller's memory.  For reads, we DMA from the remote controller's
13400 * memory into our memory first, and then move it out to the FETD.
13401 */
13402static void
13403ctl_datamove_remote(union ctl_io *io)
13404{
13405	struct ctl_softc *softc;
13406
13407	softc = control_softc;
13408
13409	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13410
13411	/*
13412	 * Note that we look for an aborted I/O here, but don't do some of
13413	 * the other checks that ctl_datamove() normally does.
13414	 * We don't need to run the datamove delay code, since that should
13415	 * have been done if need be on the other controller.
13416	 */
13417	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13418		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13419		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13420		       io->io_hdr.nexus.targ_port,
13421		       io->io_hdr.nexus.targ_target.id,
13422		       io->io_hdr.nexus.targ_lun);
13423		io->io_hdr.port_status = 31338;
13424		ctl_send_datamove_done(io, /*have_lock*/ 0);
13425		return;
13426	}
13427
13428	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13429		ctl_datamove_remote_write(io);
13430	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13431		ctl_datamove_remote_read(io);
13432	} else {
13433		union ctl_ha_msg msg;
13434		struct scsi_sense_data *sense;
13435		uint8_t sks[3];
13436		int retry_count;
13437
13438		memset(&msg, 0, sizeof(msg));
13439
13440		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13441		msg.hdr.status = CTL_SCSI_ERROR;
13442		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13443
13444		retry_count = 4243;
13445
13446		sense = &msg.scsi.sense_data;
13447		sks[0] = SSD_SCS_VALID;
13448		sks[1] = (retry_count >> 8) & 0xff;
13449		sks[2] = retry_count & 0xff;
13450
13451		/* "Internal target failure" */
13452		scsi_set_sense_data(sense,
13453				    /*sense_format*/ SSD_TYPE_NONE,
13454				    /*current_error*/ 1,
13455				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13456				    /*asc*/ 0x44,
13457				    /*ascq*/ 0x00,
13458				    /*type*/ SSD_ELEM_SKS,
13459				    /*size*/ sizeof(sks),
13460				    /*data*/ sks,
13461				    SSD_ELEM_NONE);
13462
13463		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13464		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13465			ctl_failover_io(io, /*have_lock*/ 1);
13466			return;
13467		}
13468
13469		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13470		    CTL_HA_STATUS_SUCCESS) {
13471			/* XXX KDM what to do if this fails? */
13472		}
13473		return;
13474	}
13475
13476}
13477
13478static int
13479ctl_process_done(union ctl_io *io)
13480{
13481	struct ctl_lun *lun;
13482	struct ctl_softc *ctl_softc = control_softc;
13483	void (*fe_done)(union ctl_io *io);
13484	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13485
13486	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13487
13488	fe_done =
13489	    control_softc->ctl_ports[targ_port]->fe_done;
13490
13491#ifdef CTL_TIME_IO
13492	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13493		char str[256];
13494		char path_str[64];
13495		struct sbuf sb;
13496
13497		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13498		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13499
13500		sbuf_cat(&sb, path_str);
13501		switch (io->io_hdr.io_type) {
13502		case CTL_IO_SCSI:
13503			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13504			sbuf_printf(&sb, "\n");
13505			sbuf_cat(&sb, path_str);
13506			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13507				    io->scsiio.tag_num, io->scsiio.tag_type);
13508			break;
13509		case CTL_IO_TASK:
13510			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13511				    "Tag Type: %d\n", io->taskio.task_action,
13512				    io->taskio.tag_num, io->taskio.tag_type);
13513			break;
13514		default:
13515			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13516			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13517			break;
13518		}
13519		sbuf_cat(&sb, path_str);
13520		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13521			    (intmax_t)time_uptime - io->io_hdr.start_time);
13522		sbuf_finish(&sb);
13523		printf("%s", sbuf_data(&sb));
13524	}
13525#endif /* CTL_TIME_IO */
13526
13527	switch (io->io_hdr.io_type) {
13528	case CTL_IO_SCSI:
13529		break;
13530	case CTL_IO_TASK:
13531		if (bootverbose || (ctl_debug & CTL_DEBUG_INFO))
13532			ctl_io_error_print(io, NULL);
13533		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13534			ctl_free_io(io);
13535		else
13536			fe_done(io);
13537		return (CTL_RETVAL_COMPLETE);
13538	default:
13539		panic("ctl_process_done: invalid io type %d\n",
13540		      io->io_hdr.io_type);
13541		break; /* NOTREACHED */
13542	}
13543
13544	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13545	if (lun == NULL) {
13546		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13547				 io->io_hdr.nexus.targ_mapped_lun));
13548		goto bailout;
13549	}
13550
13551	mtx_lock(&lun->lun_lock);
13552
13553	/*
13554	 * Check to see if we have any errors to inject here.  We only
13555	 * inject errors for commands that don't already have errors set.
13556	 */
13557	if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
13558	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13559	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13560		ctl_inject_error(lun, io);
13561
13562	/*
13563	 * XXX KDM how do we treat commands that aren't completed
13564	 * successfully?
13565	 *
13566	 * XXX KDM should we also track I/O latency?
13567	 */
13568	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13569	    io->io_hdr.io_type == CTL_IO_SCSI) {
13570#ifdef CTL_TIME_IO
13571		struct bintime cur_bt;
13572#endif
13573		int type;
13574
13575		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13576		    CTL_FLAG_DATA_IN)
13577			type = CTL_STATS_READ;
13578		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13579		    CTL_FLAG_DATA_OUT)
13580			type = CTL_STATS_WRITE;
13581		else
13582			type = CTL_STATS_NO_IO;
13583
13584		lun->stats.ports[targ_port].bytes[type] +=
13585		    io->scsiio.kern_total_len;
13586		lun->stats.ports[targ_port].operations[type]++;
13587#ifdef CTL_TIME_IO
13588		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13589		   &io->io_hdr.dma_bt);
13590		lun->stats.ports[targ_port].num_dmas[type] +=
13591		    io->io_hdr.num_dmas;
13592		getbintime(&cur_bt);
13593		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13594		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13595#endif
13596	}
13597
13598	/*
13599	 * Remove this from the OOA queue.
13600	 */
13601	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13602
13603	/*
13604	 * Run through the blocked queue on this LUN and see if anything
13605	 * has become unblocked, now that this transaction is done.
13606	 */
13607	ctl_check_blocked(lun);
13608
13609	/*
13610	 * If the LUN has been invalidated, free it if there is nothing
13611	 * left on its OOA queue.
13612	 */
13613	if ((lun->flags & CTL_LUN_INVALID)
13614	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13615		mtx_unlock(&lun->lun_lock);
13616		mtx_lock(&ctl_softc->ctl_lock);
13617		ctl_free_lun(lun);
13618		mtx_unlock(&ctl_softc->ctl_lock);
13619	} else
13620		mtx_unlock(&lun->lun_lock);
13621
13622bailout:
13623
13624	/*
13625	 * If this command has been aborted, make sure we set the status
13626	 * properly.  The FETD is responsible for freeing the I/O and doing
13627	 * whatever it needs to do to clean up its state.
13628	 */
13629	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13630		ctl_set_task_aborted(&io->scsiio);
13631
13632	/*
13633	 * If enabled, print command error status.
13634	 * We don't print UAs unless debugging was enabled explicitly.
13635	 */
13636	do {
13637		if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)
13638			break;
13639		if (!bootverbose && (ctl_debug & CTL_DEBUG_INFO) == 0)
13640			break;
13641		if ((ctl_debug & CTL_DEBUG_INFO) == 0 &&
13642		    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR) &&
13643		     (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13644			int error_code, sense_key, asc, ascq;
13645
13646			scsi_extract_sense_len(&io->scsiio.sense_data,
13647			    io->scsiio.sense_len, &error_code, &sense_key,
13648			    &asc, &ascq, /*show_errors*/ 0);
13649			if (sense_key == SSD_KEY_UNIT_ATTENTION)
13650				break;
13651		}
13652
13653		ctl_io_error_print(io, NULL);
13654	} while (0);
13655
13656	/*
13657	 * Tell the FETD or the other shelf controller we're done with this
13658	 * command.  Note that only SCSI commands get to this point.  Task
13659	 * management commands are completed above.
13660	 *
13661	 * We only send status to the other controller if we're in XFER
13662	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13663	 * received the I/O (from CTL's perspective), and so the status is
13664	 * generated there.
13665	 *
13666	 * XXX KDM if we hold the lock here, we could cause a deadlock
13667	 * if the frontend comes back in in this context to queue
13668	 * something.
13669	 */
13670	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13671	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13672		union ctl_ha_msg msg;
13673
13674		memset(&msg, 0, sizeof(msg));
13675		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13676		msg.hdr.original_sc = io->io_hdr.original_sc;
13677		msg.hdr.nexus = io->io_hdr.nexus;
13678		msg.hdr.status = io->io_hdr.status;
13679		msg.scsi.scsi_status = io->scsiio.scsi_status;
13680		msg.scsi.tag_num = io->scsiio.tag_num;
13681		msg.scsi.tag_type = io->scsiio.tag_type;
13682		msg.scsi.sense_len = io->scsiio.sense_len;
13683		msg.scsi.sense_residual = io->scsiio.sense_residual;
13684		msg.scsi.residual = io->scsiio.residual;
13685		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13686		       sizeof(io->scsiio.sense_data));
13687		/*
13688		 * We copy this whether or not this is an I/O-related
13689		 * command.  Otherwise, we'd have to go and check to see
13690		 * whether it's a read/write command, and it really isn't
13691		 * worth it.
13692		 */
13693		memcpy(&msg.scsi.lbalen,
13694		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13695		       sizeof(msg.scsi.lbalen));
13696
13697		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13698				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13699			/* XXX do something here */
13700		}
13701
13702		ctl_free_io(io);
13703	} else
13704		fe_done(io);
13705
13706	return (CTL_RETVAL_COMPLETE);
13707}
13708
13709#ifdef CTL_WITH_CA
13710/*
13711 * Front end should call this if it doesn't do autosense.  When the request
13712 * sense comes back in from the initiator, we'll dequeue this and send it.
13713 */
13714int
13715ctl_queue_sense(union ctl_io *io)
13716{
13717	struct ctl_lun *lun;
13718	struct ctl_softc *ctl_softc;
13719	uint32_t initidx, targ_lun;
13720
13721	ctl_softc = control_softc;
13722
13723	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13724
13725	/*
13726	 * LUN lookup will likely move to the ctl_work_thread() once we
13727	 * have our new queueing infrastructure (that doesn't put things on
13728	 * a per-LUN queue initially).  That is so that we can handle
13729	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13730	 * can't deal with that right now.
13731	 */
13732	mtx_lock(&ctl_softc->ctl_lock);
13733
13734	/*
13735	 * If we don't have a LUN for this, just toss the sense
13736	 * information.
13737	 */
13738	targ_lun = io->io_hdr.nexus.targ_lun;
13739	targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13740	if ((targ_lun < CTL_MAX_LUNS)
13741	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
13742		lun = ctl_softc->ctl_luns[targ_lun];
13743	else
13744		goto bailout;
13745
13746	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13747
13748	mtx_lock(&lun->lun_lock);
13749	/*
13750	 * Already have CA set for this LUN...toss the sense information.
13751	 */
13752	if (ctl_is_set(lun->have_ca, initidx)) {
13753		mtx_unlock(&lun->lun_lock);
13754		goto bailout;
13755	}
13756
13757	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13758	       ctl_min(sizeof(lun->pending_sense[initidx]),
13759	       sizeof(io->scsiio.sense_data)));
13760	ctl_set_mask(lun->have_ca, initidx);
13761	mtx_unlock(&lun->lun_lock);
13762
13763bailout:
13764	mtx_unlock(&ctl_softc->ctl_lock);
13765
13766	ctl_free_io(io);
13767
13768	return (CTL_RETVAL_COMPLETE);
13769}
13770#endif
13771
13772/*
13773 * Primary command inlet from frontend ports.  All SCSI and task I/O
13774 * requests must go through this function.
13775 */
13776int
13777ctl_queue(union ctl_io *io)
13778{
13779	struct ctl_softc *ctl_softc;
13780
13781	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13782
13783	ctl_softc = control_softc;
13784
13785#ifdef CTL_TIME_IO
13786	io->io_hdr.start_time = time_uptime;
13787	getbintime(&io->io_hdr.start_bt);
13788#endif /* CTL_TIME_IO */
13789
13790	/* Map FE-specific LUN ID into global one. */
13791	io->io_hdr.nexus.targ_mapped_lun =
13792	    ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13793
13794	switch (io->io_hdr.io_type) {
13795	case CTL_IO_SCSI:
13796	case CTL_IO_TASK:
13797		if (ctl_debug & CTL_DEBUG_CDB)
13798			ctl_io_print(io);
13799		ctl_enqueue_incoming(io);
13800		break;
13801	default:
13802		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13803		return (EINVAL);
13804	}
13805
13806	return (CTL_RETVAL_COMPLETE);
13807}
13808
13809#ifdef CTL_IO_DELAY
13810static void
13811ctl_done_timer_wakeup(void *arg)
13812{
13813	union ctl_io *io;
13814
13815	io = (union ctl_io *)arg;
13816	ctl_done(io);
13817}
13818#endif /* CTL_IO_DELAY */
13819
13820void
13821ctl_done(union ctl_io *io)
13822{
13823	struct ctl_softc *ctl_softc;
13824
13825	ctl_softc = control_softc;
13826
13827	/*
13828	 * Enable this to catch duplicate completion issues.
13829	 */
13830#if 0
13831	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13832		printf("%s: type %d msg %d cdb %x iptl: "
13833		       "%d:%d:%d:%d tag 0x%04x "
13834		       "flag %#x status %x\n",
13835			__func__,
13836			io->io_hdr.io_type,
13837			io->io_hdr.msg_type,
13838			io->scsiio.cdb[0],
13839			io->io_hdr.nexus.initid.id,
13840			io->io_hdr.nexus.targ_port,
13841			io->io_hdr.nexus.targ_target.id,
13842			io->io_hdr.nexus.targ_lun,
13843			(io->io_hdr.io_type ==
13844			CTL_IO_TASK) ?
13845			io->taskio.tag_num :
13846			io->scsiio.tag_num,
13847		        io->io_hdr.flags,
13848			io->io_hdr.status);
13849	} else
13850		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13851#endif
13852
13853	/*
13854	 * This is an internal copy of an I/O, and should not go through
13855	 * the normal done processing logic.
13856	 */
13857	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13858		return;
13859
13860	/*
13861	 * We need to send a msg to the serializing shelf to finish the IO
13862	 * as well.  We don't send a finish message to the other shelf if
13863	 * this is a task management command.  Task management commands
13864	 * aren't serialized in the OOA queue, but rather just executed on
13865	 * both shelf controllers for commands that originated on that
13866	 * controller.
13867	 */
13868	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13869	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
13870		union ctl_ha_msg msg_io;
13871
13872		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13873		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13874		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13875		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13876		}
13877		/* continue on to finish IO */
13878	}
13879#ifdef CTL_IO_DELAY
13880	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13881		struct ctl_lun *lun;
13882
13883		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13884
13885		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13886	} else {
13887		struct ctl_lun *lun;
13888
13889		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13890
13891		if ((lun != NULL)
13892		 && (lun->delay_info.done_delay > 0)) {
13893			struct callout *callout;
13894
13895			callout = (struct callout *)&io->io_hdr.timer_bytes;
13896			callout_init(callout, /*mpsafe*/ 1);
13897			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13898			callout_reset(callout,
13899				      lun->delay_info.done_delay * hz,
13900				      ctl_done_timer_wakeup, io);
13901			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13902				lun->delay_info.done_delay = 0;
13903			return;
13904		}
13905	}
13906#endif /* CTL_IO_DELAY */
13907
13908	ctl_enqueue_done(io);
13909}
13910
13911int
13912ctl_isc(struct ctl_scsiio *ctsio)
13913{
13914	struct ctl_lun *lun;
13915	int retval;
13916
13917	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13918
13919	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13920
13921	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13922
13923	retval = lun->backend->data_submit((union ctl_io *)ctsio);
13924
13925	return (retval);
13926}
13927
13928
13929static void
13930ctl_work_thread(void *arg)
13931{
13932	struct ctl_thread *thr = (struct ctl_thread *)arg;
13933	struct ctl_softc *softc = thr->ctl_softc;
13934	union ctl_io *io;
13935	int retval;
13936
13937	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13938
13939	for (;;) {
13940		retval = 0;
13941
13942		/*
13943		 * We handle the queues in this order:
13944		 * - ISC
13945		 * - done queue (to free up resources, unblock other commands)
13946		 * - RtR queue
13947		 * - incoming queue
13948		 *
13949		 * If those queues are empty, we break out of the loop and
13950		 * go to sleep.
13951		 */
13952		mtx_lock(&thr->queue_lock);
13953		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13954		if (io != NULL) {
13955			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13956			mtx_unlock(&thr->queue_lock);
13957			ctl_handle_isc(io);
13958			continue;
13959		}
13960		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13961		if (io != NULL) {
13962			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13963			/* clear any blocked commands, call fe_done */
13964			mtx_unlock(&thr->queue_lock);
13965			retval = ctl_process_done(io);
13966			continue;
13967		}
13968		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13969		if (io != NULL) {
13970			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13971			mtx_unlock(&thr->queue_lock);
13972			if (io->io_hdr.io_type == CTL_IO_TASK)
13973				ctl_run_task(io);
13974			else
13975				ctl_scsiio_precheck(softc, &io->scsiio);
13976			continue;
13977		}
13978		if (!ctl_pause_rtr) {
13979			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13980			if (io != NULL) {
13981				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13982				mtx_unlock(&thr->queue_lock);
13983				retval = ctl_scsiio(&io->scsiio);
13984				if (retval != CTL_RETVAL_COMPLETE)
13985					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13986				continue;
13987			}
13988		}
13989
13990		/* Sleep until we have something to do. */
13991		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13992	}
13993}
13994
13995static void
13996ctl_lun_thread(void *arg)
13997{
13998	struct ctl_softc *softc = (struct ctl_softc *)arg;
13999	struct ctl_be_lun *be_lun;
14000	int retval;
14001
14002	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
14003
14004	for (;;) {
14005		retval = 0;
14006		mtx_lock(&softc->ctl_lock);
14007		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
14008		if (be_lun != NULL) {
14009			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
14010			mtx_unlock(&softc->ctl_lock);
14011			ctl_create_lun(be_lun);
14012			continue;
14013		}
14014
14015		/* Sleep until we have something to do. */
14016		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
14017		    PDROP | PRIBIO, "-", 0);
14018	}
14019}
14020
14021static void
14022ctl_thresh_thread(void *arg)
14023{
14024	struct ctl_softc *softc = (struct ctl_softc *)arg;
14025	struct ctl_lun *lun;
14026	struct ctl_be_lun *be_lun;
14027	struct scsi_da_rw_recovery_page *rwpage;
14028	struct ctl_logical_block_provisioning_page *page;
14029	const char *attr;
14030	uint64_t thres, val;
14031	int i, e;
14032
14033	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
14034
14035	for (;;) {
14036		mtx_lock(&softc->ctl_lock);
14037		STAILQ_FOREACH(lun, &softc->lun_list, links) {
14038			be_lun = lun->be_lun;
14039			if ((lun->flags & CTL_LUN_DISABLED) ||
14040			    (lun->flags & CTL_LUN_OFFLINE) ||
14041			    lun->backend->lun_attr == NULL)
14042				continue;
14043			rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
14044			if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
14045				continue;
14046			e = 0;
14047			page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
14048			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
14049				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
14050					continue;
14051				thres = scsi_4btoul(page->descr[i].count);
14052				thres <<= CTL_LBP_EXPONENT;
14053				switch (page->descr[i].resource) {
14054				case 0x01:
14055					attr = "blocksavail";
14056					break;
14057				case 0x02:
14058					attr = "blocksused";
14059					break;
14060				case 0xf1:
14061					attr = "poolblocksavail";
14062					break;
14063				case 0xf2:
14064					attr = "poolblocksused";
14065					break;
14066				default:
14067					continue;
14068				}
14069				mtx_unlock(&softc->ctl_lock); // XXX
14070				val = lun->backend->lun_attr(
14071				    lun->be_lun->be_lun, attr);
14072				mtx_lock(&softc->ctl_lock);
14073				if (val == UINT64_MAX)
14074					continue;
14075				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
14076				    == SLBPPD_ARMING_INC)
14077					e |= (val >= thres);
14078				else
14079					e |= (val <= thres);
14080			}
14081			mtx_lock(&lun->lun_lock);
14082			if (e) {
14083				if (lun->lasttpt == 0 ||
14084				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
14085					lun->lasttpt = time_uptime;
14086					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14087				}
14088			} else {
14089				lun->lasttpt = 0;
14090				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
14091			}
14092			mtx_unlock(&lun->lun_lock);
14093		}
14094		mtx_unlock(&softc->ctl_lock);
14095		pause("-", CTL_LBP_PERIOD * hz);
14096	}
14097}
14098
14099static void
14100ctl_enqueue_incoming(union ctl_io *io)
14101{
14102	struct ctl_softc *softc = control_softc;
14103	struct ctl_thread *thr;
14104	u_int idx;
14105
14106	idx = (io->io_hdr.nexus.targ_port * 127 +
14107	       io->io_hdr.nexus.initid.id) % worker_threads;
14108	thr = &softc->threads[idx];
14109	mtx_lock(&thr->queue_lock);
14110	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14111	mtx_unlock(&thr->queue_lock);
14112	wakeup(thr);
14113}
14114
14115static void
14116ctl_enqueue_rtr(union ctl_io *io)
14117{
14118	struct ctl_softc *softc = control_softc;
14119	struct ctl_thread *thr;
14120
14121	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14122	mtx_lock(&thr->queue_lock);
14123	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14124	mtx_unlock(&thr->queue_lock);
14125	wakeup(thr);
14126}
14127
14128static void
14129ctl_enqueue_done(union ctl_io *io)
14130{
14131	struct ctl_softc *softc = control_softc;
14132	struct ctl_thread *thr;
14133
14134	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14135	mtx_lock(&thr->queue_lock);
14136	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14137	mtx_unlock(&thr->queue_lock);
14138	wakeup(thr);
14139}
14140
14141static void
14142ctl_enqueue_isc(union ctl_io *io)
14143{
14144	struct ctl_softc *softc = control_softc;
14145	struct ctl_thread *thr;
14146
14147	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14148	mtx_lock(&thr->queue_lock);
14149	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14150	mtx_unlock(&thr->queue_lock);
14151	wakeup(thr);
14152}
14153
14154/* Initialization and failover */
14155
14156void
14157ctl_init_isc_msg(void)
14158{
14159	printf("CTL: Still calling this thing\n");
14160}
14161
14162/*
14163 * Init component
14164 * 	Initializes component into configuration defined by bootMode
14165 *	(see hasc-sv.c)
14166 *  	returns hasc_Status:
14167 * 		OK
14168 *		ERROR - fatal error
14169 */
14170static ctl_ha_comp_status
14171ctl_isc_init(struct ctl_ha_component *c)
14172{
14173	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14174
14175	c->status = ret;
14176	return ret;
14177}
14178
14179/* Start component
14180 * 	Starts component in state requested. If component starts successfully,
14181 *	it must set its own state to the requestrd state
14182 *	When requested state is HASC_STATE_HA, the component may refine it
14183 * 	by adding _SLAVE or _MASTER flags.
14184 *	Currently allowed state transitions are:
14185 *	UNKNOWN->HA		- initial startup
14186 *	UNKNOWN->SINGLE - initial startup when no parter detected
14187 *	HA->SINGLE		- failover
14188 * returns ctl_ha_comp_status:
14189 * 		OK	- component successfully started in requested state
14190 *		FAILED  - could not start the requested state, failover may
14191 * 			  be possible
14192 *		ERROR	- fatal error detected, no future startup possible
14193 */
14194static ctl_ha_comp_status
14195ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14196{
14197	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14198
14199	printf("%s: go\n", __func__);
14200
14201	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14202	if (c->state == CTL_HA_STATE_UNKNOWN ) {
14203		control_softc->is_single = 0;
14204		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14205		    != CTL_HA_STATUS_SUCCESS) {
14206			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14207			ret = CTL_HA_COMP_STATUS_ERROR;
14208		}
14209	} else if (CTL_HA_STATE_IS_HA(c->state)
14210		&& CTL_HA_STATE_IS_SINGLE(state)){
14211		// HA->SINGLE transition
14212	        ctl_failover();
14213		control_softc->is_single = 1;
14214	} else {
14215		printf("ctl_isc_start:Invalid state transition %X->%X\n",
14216		       c->state, state);
14217		ret = CTL_HA_COMP_STATUS_ERROR;
14218	}
14219	if (CTL_HA_STATE_IS_SINGLE(state))
14220		control_softc->is_single = 1;
14221
14222	c->state = state;
14223	c->status = ret;
14224	return ret;
14225}
14226
14227/*
14228 * Quiesce component
14229 * The component must clear any error conditions (set status to OK) and
14230 * prepare itself to another Start call
14231 * returns ctl_ha_comp_status:
14232 * 	OK
14233 *	ERROR
14234 */
14235static ctl_ha_comp_status
14236ctl_isc_quiesce(struct ctl_ha_component *c)
14237{
14238	int ret = CTL_HA_COMP_STATUS_OK;
14239
14240	ctl_pause_rtr = 1;
14241	c->status = ret;
14242	return ret;
14243}
14244
14245struct ctl_ha_component ctl_ha_component_ctlisc =
14246{
14247	.name = "CTL ISC",
14248	.state = CTL_HA_STATE_UNKNOWN,
14249	.init = ctl_isc_init,
14250	.start = ctl_isc_start,
14251	.quiesce = ctl_isc_quiesce
14252};
14253
14254/*
14255 *  vim: ts=8
14256 */
14257