ctl.c revision 288795
1/*-
2 * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3 * Copyright (c) 2012 The FreeBSD Foundation
4 * Copyright (c) 2015 Alexander Motin <mav@FreeBSD.org>
5 * All rights reserved.
6 *
7 * Portions of this software were developed by Edward Tomasz Napierala
8 * under sponsorship from the FreeBSD Foundation.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions, and the following disclaimer,
15 *    without modification.
16 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
17 *    substantially similar to the "NO WARRANTY" disclaimer below
18 *    ("Disclaimer") and any redistribution must be conditioned upon
19 *    including a substantially similar Disclaimer requirement for further
20 *    binary redistribution.
21 *
22 * NO WARRANTY
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
26 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
31 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
32 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33 * POSSIBILITY OF SUCH DAMAGES.
34 *
35 * $Id$
36 */
37/*
38 * CAM Target Layer, a SCSI device emulation subsystem.
39 *
40 * Author: Ken Merry <ken@FreeBSD.org>
41 */
42
43#define _CTL_C
44
45#include <sys/cdefs.h>
46__FBSDID("$FreeBSD: stable/10/sys/cam/ctl/ctl.c 288795 2015-10-05 10:58:41Z mav $");
47
48#include <sys/param.h>
49#include <sys/systm.h>
50#include <sys/ctype.h>
51#include <sys/kernel.h>
52#include <sys/types.h>
53#include <sys/kthread.h>
54#include <sys/bio.h>
55#include <sys/fcntl.h>
56#include <sys/lock.h>
57#include <sys/module.h>
58#include <sys/mutex.h>
59#include <sys/condvar.h>
60#include <sys/malloc.h>
61#include <sys/conf.h>
62#include <sys/ioccom.h>
63#include <sys/queue.h>
64#include <sys/sbuf.h>
65#include <sys/smp.h>
66#include <sys/endian.h>
67#include <sys/sysctl.h>
68#include <vm/uma.h>
69
70#include <cam/cam.h>
71#include <cam/scsi/scsi_all.h>
72#include <cam/scsi/scsi_da.h>
73#include <cam/ctl/ctl_io.h>
74#include <cam/ctl/ctl.h>
75#include <cam/ctl/ctl_frontend.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 * Template mode pages.
89 */
90
91/*
92 * Note that these are default values only.  The actual values will be
93 * filled in when the user does a mode sense.
94 */
95const static struct copan_debugconf_subpage debugconf_page_default = {
96	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
97	DBGCNF_SUBPAGE_CODE,		/* subpage */
98	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
99	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
100	DBGCNF_VERSION,			/* page_version */
101	{CTL_TIME_IO_DEFAULT_SECS>>8,
102	 CTL_TIME_IO_DEFAULT_SECS>>0},	/* ctl_time_io_secs */
103};
104
105const static struct copan_debugconf_subpage debugconf_page_changeable = {
106	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
107	DBGCNF_SUBPAGE_CODE,		/* subpage */
108	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
109	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
110	0,				/* page_version */
111	{0xff,0xff},			/* ctl_time_io_secs */
112};
113
114const static struct scsi_da_rw_recovery_page rw_er_page_default = {
115	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
116	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
117	/*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
118	/*read_retry_count*/0,
119	/*correction_span*/0,
120	/*head_offset_count*/0,
121	/*data_strobe_offset_cnt*/0,
122	/*byte8*/SMS_RWER_LBPERE,
123	/*write_retry_count*/0,
124	/*reserved2*/0,
125	/*recovery_time_limit*/{0, 0},
126};
127
128const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
129	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
130	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
131	/*byte3*/0,
132	/*read_retry_count*/0,
133	/*correction_span*/0,
134	/*head_offset_count*/0,
135	/*data_strobe_offset_cnt*/0,
136	/*byte8*/0,
137	/*write_retry_count*/0,
138	/*reserved2*/0,
139	/*recovery_time_limit*/{0, 0},
140};
141
142const static struct scsi_format_page format_page_default = {
143	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
144	/*page_length*/sizeof(struct scsi_format_page) - 2,
145	/*tracks_per_zone*/ {0, 0},
146	/*alt_sectors_per_zone*/ {0, 0},
147	/*alt_tracks_per_zone*/ {0, 0},
148	/*alt_tracks_per_lun*/ {0, 0},
149	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
150			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
151	/*bytes_per_sector*/ {0, 0},
152	/*interleave*/ {0, 0},
153	/*track_skew*/ {0, 0},
154	/*cylinder_skew*/ {0, 0},
155	/*flags*/ SFP_HSEC,
156	/*reserved*/ {0, 0, 0}
157};
158
159const static struct scsi_format_page format_page_changeable = {
160	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
161	/*page_length*/sizeof(struct scsi_format_page) - 2,
162	/*tracks_per_zone*/ {0, 0},
163	/*alt_sectors_per_zone*/ {0, 0},
164	/*alt_tracks_per_zone*/ {0, 0},
165	/*alt_tracks_per_lun*/ {0, 0},
166	/*sectors_per_track*/ {0, 0},
167	/*bytes_per_sector*/ {0, 0},
168	/*interleave*/ {0, 0},
169	/*track_skew*/ {0, 0},
170	/*cylinder_skew*/ {0, 0},
171	/*flags*/ 0,
172	/*reserved*/ {0, 0, 0}
173};
174
175const static struct scsi_rigid_disk_page rigid_disk_page_default = {
176	/*page_code*/SMS_RIGID_DISK_PAGE,
177	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
178	/*cylinders*/ {0, 0, 0},
179	/*heads*/ CTL_DEFAULT_HEADS,
180	/*start_write_precomp*/ {0, 0, 0},
181	/*start_reduced_current*/ {0, 0, 0},
182	/*step_rate*/ {0, 0},
183	/*landing_zone_cylinder*/ {0, 0, 0},
184	/*rpl*/ SRDP_RPL_DISABLED,
185	/*rotational_offset*/ 0,
186	/*reserved1*/ 0,
187	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
188			   CTL_DEFAULT_ROTATION_RATE & 0xff},
189	/*reserved2*/ {0, 0}
190};
191
192const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
193	/*page_code*/SMS_RIGID_DISK_PAGE,
194	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
195	/*cylinders*/ {0, 0, 0},
196	/*heads*/ 0,
197	/*start_write_precomp*/ {0, 0, 0},
198	/*start_reduced_current*/ {0, 0, 0},
199	/*step_rate*/ {0, 0},
200	/*landing_zone_cylinder*/ {0, 0, 0},
201	/*rpl*/ 0,
202	/*rotational_offset*/ 0,
203	/*reserved1*/ 0,
204	/*rotation_rate*/ {0, 0},
205	/*reserved2*/ {0, 0}
206};
207
208const static struct scsi_caching_page caching_page_default = {
209	/*page_code*/SMS_CACHING_PAGE,
210	/*page_length*/sizeof(struct scsi_caching_page) - 2,
211	/*flags1*/ SCP_DISC | SCP_WCE,
212	/*ret_priority*/ 0,
213	/*disable_pf_transfer_len*/ {0xff, 0xff},
214	/*min_prefetch*/ {0, 0},
215	/*max_prefetch*/ {0xff, 0xff},
216	/*max_pf_ceiling*/ {0xff, 0xff},
217	/*flags2*/ 0,
218	/*cache_segments*/ 0,
219	/*cache_seg_size*/ {0, 0},
220	/*reserved*/ 0,
221	/*non_cache_seg_size*/ {0, 0, 0}
222};
223
224const static struct scsi_caching_page caching_page_changeable = {
225	/*page_code*/SMS_CACHING_PAGE,
226	/*page_length*/sizeof(struct scsi_caching_page) - 2,
227	/*flags1*/ SCP_WCE | SCP_RCD,
228	/*ret_priority*/ 0,
229	/*disable_pf_transfer_len*/ {0, 0},
230	/*min_prefetch*/ {0, 0},
231	/*max_prefetch*/ {0, 0},
232	/*max_pf_ceiling*/ {0, 0},
233	/*flags2*/ 0,
234	/*cache_segments*/ 0,
235	/*cache_seg_size*/ {0, 0},
236	/*reserved*/ 0,
237	/*non_cache_seg_size*/ {0, 0, 0}
238};
239
240const static struct scsi_control_page control_page_default = {
241	/*page_code*/SMS_CONTROL_MODE_PAGE,
242	/*page_length*/sizeof(struct scsi_control_page) - 2,
243	/*rlec*/0,
244	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
245	/*eca_and_aen*/0,
246	/*flags4*/SCP_TAS,
247	/*aen_holdoff_period*/{0, 0},
248	/*busy_timeout_period*/{0, 0},
249	/*extended_selftest_completion_time*/{0, 0}
250};
251
252const static struct scsi_control_page control_page_changeable = {
253	/*page_code*/SMS_CONTROL_MODE_PAGE,
254	/*page_length*/sizeof(struct scsi_control_page) - 2,
255	/*rlec*/SCP_DSENSE,
256	/*queue_flags*/SCP_QUEUE_ALG_MASK,
257	/*eca_and_aen*/SCP_SWP,
258	/*flags4*/0,
259	/*aen_holdoff_period*/{0, 0},
260	/*busy_timeout_period*/{0, 0},
261	/*extended_selftest_completion_time*/{0, 0}
262};
263
264#define CTL_CEM_LEN	(sizeof(struct scsi_control_ext_page) - 4)
265
266const static struct scsi_control_ext_page control_ext_page_default = {
267	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
268	/*subpage_code*/0x01,
269	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
270	/*flags*/0,
271	/*prio*/0,
272	/*max_sense*/0
273};
274
275const static struct scsi_control_ext_page control_ext_page_changeable = {
276	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
277	/*subpage_code*/0x01,
278	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
279	/*flags*/0,
280	/*prio*/0,
281	/*max_sense*/0
282};
283
284const static struct scsi_info_exceptions_page ie_page_default = {
285	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
286	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
287	/*info_flags*/SIEP_FLAGS_DEXCPT,
288	/*mrie*/0,
289	/*interval_timer*/{0, 0, 0, 0},
290	/*report_count*/{0, 0, 0, 0}
291};
292
293const static struct scsi_info_exceptions_page ie_page_changeable = {
294	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
295	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
296	/*info_flags*/0,
297	/*mrie*/0,
298	/*interval_timer*/{0, 0, 0, 0},
299	/*report_count*/{0, 0, 0, 0}
300};
301
302#define CTL_LBPM_LEN	(sizeof(struct ctl_logical_block_provisioning_page) - 4)
303
304const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
305	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
306	/*subpage_code*/0x02,
307	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
308	/*flags*/0,
309	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
310	/*descr*/{}},
311	{{/*flags*/0,
312	  /*resource*/0x01,
313	  /*reserved*/{0, 0},
314	  /*count*/{0, 0, 0, 0}},
315	 {/*flags*/0,
316	  /*resource*/0x02,
317	  /*reserved*/{0, 0},
318	  /*count*/{0, 0, 0, 0}},
319	 {/*flags*/0,
320	  /*resource*/0xf1,
321	  /*reserved*/{0, 0},
322	  /*count*/{0, 0, 0, 0}},
323	 {/*flags*/0,
324	  /*resource*/0xf2,
325	  /*reserved*/{0, 0},
326	  /*count*/{0, 0, 0, 0}}
327	}
328};
329
330const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
331	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
332	/*subpage_code*/0x02,
333	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
334	/*flags*/0,
335	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
336	/*descr*/{}},
337	{{/*flags*/0,
338	  /*resource*/0,
339	  /*reserved*/{0, 0},
340	  /*count*/{0, 0, 0, 0}},
341	 {/*flags*/0,
342	  /*resource*/0,
343	  /*reserved*/{0, 0},
344	  /*count*/{0, 0, 0, 0}},
345	 {/*flags*/0,
346	  /*resource*/0,
347	  /*reserved*/{0, 0},
348	  /*count*/{0, 0, 0, 0}},
349	 {/*flags*/0,
350	  /*resource*/0,
351	  /*reserved*/{0, 0},
352	  /*count*/{0, 0, 0, 0}}
353	}
354};
355
356SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
357static int worker_threads = -1;
358TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
359SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
360    &worker_threads, 1, "Number of worker threads");
361static int ctl_debug = CTL_DEBUG_NONE;
362TUNABLE_INT("kern.cam.ctl.debug", &ctl_debug);
363SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
364    &ctl_debug, 0, "Enabled debug flags");
365
366/*
367 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
368 * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
369 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
370 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
371 */
372#define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
373
374static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
375				  int param);
376static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
377static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
378static int ctl_init(void);
379void ctl_shutdown(void);
380static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
381static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
382static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
383static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
384			      struct ctl_ooa *ooa_hdr,
385			      struct ctl_ooa_entry *kern_entries);
386static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
387		     struct thread *td);
388static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
389			 struct ctl_be_lun *be_lun);
390static int ctl_free_lun(struct ctl_lun *lun);
391static void ctl_create_lun(struct ctl_be_lun *be_lun);
392static struct ctl_port * ctl_io_port(struct ctl_io_hdr *io_hdr);
393
394static int ctl_do_mode_select(union ctl_io *io);
395static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
396			   uint64_t res_key, uint64_t sa_res_key,
397			   uint8_t type, uint32_t residx,
398			   struct ctl_scsiio *ctsio,
399			   struct scsi_per_res_out *cdb,
400			   struct scsi_per_res_out_parms* param);
401static void ctl_pro_preempt_other(struct ctl_lun *lun,
402				  union ctl_ha_msg *msg);
403static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
404static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
405static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
406static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
407static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
408static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
409static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
410					 int alloc_len);
411static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
412					 int alloc_len);
413static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
414static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
415static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
416static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
417static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
418static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
419    bool seq);
420static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
421static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
422    union ctl_io *pending_io, union ctl_io *ooa_io);
423static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
424				union ctl_io *starting_io);
425static int ctl_check_blocked(struct ctl_lun *lun);
426static int ctl_scsiio_lun_check(struct ctl_lun *lun,
427				const struct ctl_cmd_entry *entry,
428				struct ctl_scsiio *ctsio);
429static void ctl_failover_lun(struct ctl_lun *lun);
430static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
431			       struct ctl_scsiio *ctsio);
432static int ctl_scsiio(struct ctl_scsiio *ctsio);
433
434static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
435static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
436			    ctl_ua_type ua_type);
437static int ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io,
438			 ctl_ua_type ua_type);
439static int ctl_lun_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
440static int ctl_abort_task(union ctl_io *io);
441static int ctl_abort_task_set(union ctl_io *io);
442static int ctl_query_task(union ctl_io *io, int task_set);
443static int ctl_i_t_nexus_reset(union ctl_io *io);
444static int ctl_query_async_event(union ctl_io *io);
445static void ctl_run_task(union ctl_io *io);
446#ifdef CTL_IO_DELAY
447static void ctl_datamove_timer_wakeup(void *arg);
448static void ctl_done_timer_wakeup(void *arg);
449#endif /* CTL_IO_DELAY */
450
451static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
452static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
453static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
454static void ctl_datamove_remote_write(union ctl_io *io);
455static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
456static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
457static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
458static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
459				    ctl_ha_dt_cb callback);
460static void ctl_datamove_remote_read(union ctl_io *io);
461static void ctl_datamove_remote(union ctl_io *io);
462static int ctl_process_done(union ctl_io *io);
463static void ctl_lun_thread(void *arg);
464static void ctl_thresh_thread(void *arg);
465static void ctl_work_thread(void *arg);
466static void ctl_enqueue_incoming(union ctl_io *io);
467static void ctl_enqueue_rtr(union ctl_io *io);
468static void ctl_enqueue_done(union ctl_io *io);
469static void ctl_enqueue_isc(union ctl_io *io);
470static const struct ctl_cmd_entry *
471    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
472static const struct ctl_cmd_entry *
473    ctl_validate_command(struct ctl_scsiio *ctsio);
474static int ctl_cmd_applicable(uint8_t lun_type,
475    const struct ctl_cmd_entry *entry);
476
477static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
478static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
479static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
480static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
481
482/*
483 * Load the serialization table.  This isn't very pretty, but is probably
484 * the easiest way to do it.
485 */
486#include "ctl_ser_table.c"
487
488/*
489 * We only need to define open, close and ioctl routines for this driver.
490 */
491static struct cdevsw ctl_cdevsw = {
492	.d_version =	D_VERSION,
493	.d_flags =	0,
494	.d_open =	ctl_open,
495	.d_close =	ctl_close,
496	.d_ioctl =	ctl_ioctl,
497	.d_name =	"ctl",
498};
499
500
501MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
502
503static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
504
505static moduledata_t ctl_moduledata = {
506	"ctl",
507	ctl_module_event_handler,
508	NULL
509};
510
511DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
512MODULE_VERSION(ctl, 1);
513
514static struct ctl_frontend ha_frontend =
515{
516	.name = "ha",
517};
518
519static void
520ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
521			    union ctl_ha_msg *msg_info)
522{
523	struct ctl_scsiio *ctsio;
524
525	if (msg_info->hdr.original_sc == NULL) {
526		printf("%s: original_sc == NULL!\n", __func__);
527		/* XXX KDM now what? */
528		return;
529	}
530
531	ctsio = &msg_info->hdr.original_sc->scsiio;
532	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
533	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
534	ctsio->io_hdr.status = msg_info->hdr.status;
535	ctsio->scsi_status = msg_info->scsi.scsi_status;
536	ctsio->sense_len = msg_info->scsi.sense_len;
537	ctsio->sense_residual = msg_info->scsi.sense_residual;
538	ctsio->residual = msg_info->scsi.residual;
539	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
540	       msg_info->scsi.sense_len);
541	ctl_enqueue_isc((union ctl_io *)ctsio);
542}
543
544static void
545ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
546				union ctl_ha_msg *msg_info)
547{
548	struct ctl_scsiio *ctsio;
549
550	if (msg_info->hdr.serializing_sc == NULL) {
551		printf("%s: serializing_sc == NULL!\n", __func__);
552		/* XXX KDM now what? */
553		return;
554	}
555
556	ctsio = &msg_info->hdr.serializing_sc->scsiio;
557	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
558	ctl_enqueue_isc((union ctl_io *)ctsio);
559}
560
561void
562ctl_isc_announce_lun(struct ctl_lun *lun)
563{
564	struct ctl_softc *softc = lun->ctl_softc;
565	union ctl_ha_msg *msg;
566	struct ctl_ha_msg_lun_pr_key pr_key;
567	int i, k;
568
569	if (softc->ha_link != CTL_HA_LINK_ONLINE)
570		return;
571	mtx_lock(&lun->lun_lock);
572	i = sizeof(msg->lun);
573	if (lun->lun_devid)
574		i += lun->lun_devid->len;
575	i += sizeof(pr_key) * lun->pr_key_count;
576alloc:
577	mtx_unlock(&lun->lun_lock);
578	msg = malloc(i, M_CTL, M_WAITOK);
579	mtx_lock(&lun->lun_lock);
580	k = sizeof(msg->lun);
581	if (lun->lun_devid)
582		k += lun->lun_devid->len;
583	k += sizeof(pr_key) * lun->pr_key_count;
584	if (i < k) {
585		free(msg, M_CTL);
586		i = k;
587		goto alloc;
588	}
589	bzero(&msg->lun, sizeof(msg->lun));
590	msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
591	msg->hdr.nexus.targ_lun = lun->lun;
592	msg->hdr.nexus.targ_mapped_lun = lun->lun;
593	msg->lun.flags = lun->flags;
594	msg->lun.pr_generation = lun->PRGeneration;
595	msg->lun.pr_res_idx = lun->pr_res_idx;
596	msg->lun.pr_res_type = lun->res_type;
597	msg->lun.pr_key_count = lun->pr_key_count;
598	i = 0;
599	if (lun->lun_devid) {
600		msg->lun.lun_devid_len = lun->lun_devid->len;
601		memcpy(&msg->lun.data[i], lun->lun_devid->data,
602		    msg->lun.lun_devid_len);
603		i += msg->lun.lun_devid_len;
604	}
605	for (k = 0; k < CTL_MAX_INITIATORS; k++) {
606		if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
607			continue;
608		pr_key.pr_iid = k;
609		memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
610		i += sizeof(pr_key);
611	}
612	mtx_unlock(&lun->lun_lock);
613	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
614	    M_WAITOK);
615	free(msg, M_CTL);
616
617	if (lun->flags & CTL_LUN_PRIMARY_SC) {
618		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
619			ctl_isc_announce_mode(lun, -1,
620			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
621			    lun->mode_pages.index[i].subpage);
622		}
623	}
624}
625
626void
627ctl_isc_announce_port(struct ctl_port *port)
628{
629	struct ctl_softc *softc = port->ctl_softc;
630	union ctl_ha_msg *msg;
631	int i;
632
633	if (port->targ_port < softc->port_min ||
634	    port->targ_port >= softc->port_max ||
635	    softc->ha_link != CTL_HA_LINK_ONLINE)
636		return;
637	i = sizeof(msg->port) + strlen(port->port_name) + 1;
638	if (port->lun_map)
639		i += sizeof(uint32_t) * CTL_MAX_LUNS;
640	if (port->port_devid)
641		i += port->port_devid->len;
642	if (port->target_devid)
643		i += port->target_devid->len;
644	if (port->init_devid)
645		i += port->init_devid->len;
646	msg = malloc(i, M_CTL, M_WAITOK);
647	bzero(&msg->port, sizeof(msg->port));
648	msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
649	msg->hdr.nexus.targ_port = port->targ_port;
650	msg->port.port_type = port->port_type;
651	msg->port.physical_port = port->physical_port;
652	msg->port.virtual_port = port->virtual_port;
653	msg->port.status = port->status;
654	i = 0;
655	msg->port.name_len = sprintf(&msg->port.data[i],
656	    "%d:%s", softc->ha_id, port->port_name) + 1;
657	i += msg->port.name_len;
658	if (port->lun_map) {
659		msg->port.lun_map_len = sizeof(uint32_t) * CTL_MAX_LUNS;
660		memcpy(&msg->port.data[i], port->lun_map,
661		    msg->port.lun_map_len);
662		i += msg->port.lun_map_len;
663	}
664	if (port->port_devid) {
665		msg->port.port_devid_len = port->port_devid->len;
666		memcpy(&msg->port.data[i], port->port_devid->data,
667		    msg->port.port_devid_len);
668		i += msg->port.port_devid_len;
669	}
670	if (port->target_devid) {
671		msg->port.target_devid_len = port->target_devid->len;
672		memcpy(&msg->port.data[i], port->target_devid->data,
673		    msg->port.target_devid_len);
674		i += msg->port.target_devid_len;
675	}
676	if (port->init_devid) {
677		msg->port.init_devid_len = port->init_devid->len;
678		memcpy(&msg->port.data[i], port->init_devid->data,
679		    msg->port.init_devid_len);
680		i += msg->port.init_devid_len;
681	}
682	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
683	    M_WAITOK);
684	free(msg, M_CTL);
685}
686
687void
688ctl_isc_announce_iid(struct ctl_port *port, int iid)
689{
690	struct ctl_softc *softc = port->ctl_softc;
691	union ctl_ha_msg *msg;
692	int i, l;
693
694	if (port->targ_port < softc->port_min ||
695	    port->targ_port >= softc->port_max ||
696	    softc->ha_link != CTL_HA_LINK_ONLINE)
697		return;
698	mtx_lock(&softc->ctl_lock);
699	i = sizeof(msg->iid);
700	l = 0;
701	if (port->wwpn_iid[iid].name)
702		l = strlen(port->wwpn_iid[iid].name) + 1;
703	i += l;
704	msg = malloc(i, M_CTL, M_NOWAIT);
705	if (msg == NULL) {
706		mtx_unlock(&softc->ctl_lock);
707		return;
708	}
709	bzero(&msg->iid, sizeof(msg->iid));
710	msg->hdr.msg_type = CTL_MSG_IID_SYNC;
711	msg->hdr.nexus.targ_port = port->targ_port;
712	msg->hdr.nexus.initid = iid;
713	msg->iid.in_use = port->wwpn_iid[iid].in_use;
714	msg->iid.name_len = l;
715	msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
716	if (port->wwpn_iid[iid].name)
717		strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
718	mtx_unlock(&softc->ctl_lock);
719	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
720	free(msg, M_CTL);
721}
722
723void
724ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
725    uint8_t page, uint8_t subpage)
726{
727	struct ctl_softc *softc = lun->ctl_softc;
728	union ctl_ha_msg msg;
729	int i;
730
731	if (softc->ha_link != CTL_HA_LINK_ONLINE)
732		return;
733	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
734		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
735		    page && lun->mode_pages.index[i].subpage == subpage)
736			break;
737	}
738	if (i == CTL_NUM_MODE_PAGES)
739		return;
740	bzero(&msg.mode, sizeof(msg.mode));
741	msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
742	msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
743	msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
744	msg.hdr.nexus.targ_lun = lun->lun;
745	msg.hdr.nexus.targ_mapped_lun = lun->lun;
746	msg.mode.page_code = page;
747	msg.mode.subpage = subpage;
748	msg.mode.page_len = lun->mode_pages.index[i].page_len;
749	memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
750	    msg.mode.page_len);
751	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
752	    M_WAITOK);
753}
754
755static void
756ctl_isc_ha_link_up(struct ctl_softc *softc)
757{
758	struct ctl_port *port;
759	struct ctl_lun *lun;
760	union ctl_ha_msg msg;
761	int i;
762
763	/* Announce this node parameters to peer for validation. */
764	msg.login.msg_type = CTL_MSG_LOGIN;
765	msg.login.version = CTL_HA_VERSION;
766	msg.login.ha_mode = softc->ha_mode;
767	msg.login.ha_id = softc->ha_id;
768	msg.login.max_luns = CTL_MAX_LUNS;
769	msg.login.max_ports = CTL_MAX_PORTS;
770	msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
771	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
772	    M_WAITOK);
773
774	STAILQ_FOREACH(port, &softc->port_list, links) {
775		ctl_isc_announce_port(port);
776		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
777			if (port->wwpn_iid[i].in_use)
778				ctl_isc_announce_iid(port, i);
779		}
780	}
781	STAILQ_FOREACH(lun, &softc->lun_list, links)
782		ctl_isc_announce_lun(lun);
783}
784
785static void
786ctl_isc_ha_link_down(struct ctl_softc *softc)
787{
788	struct ctl_port *port;
789	struct ctl_lun *lun;
790	union ctl_io *io;
791	int i;
792
793	mtx_lock(&softc->ctl_lock);
794	STAILQ_FOREACH(lun, &softc->lun_list, links) {
795		mtx_lock(&lun->lun_lock);
796		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
797			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
798			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
799		}
800		mtx_unlock(&lun->lun_lock);
801
802		mtx_unlock(&softc->ctl_lock);
803		io = ctl_alloc_io(softc->othersc_pool);
804		mtx_lock(&softc->ctl_lock);
805		ctl_zero_io(io);
806		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
807		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
808		ctl_enqueue_isc(io);
809	}
810
811	STAILQ_FOREACH(port, &softc->port_list, links) {
812		if (port->targ_port >= softc->port_min &&
813		    port->targ_port < softc->port_max)
814			continue;
815		port->status &= ~CTL_PORT_STATUS_ONLINE;
816		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
817			port->wwpn_iid[i].in_use = 0;
818			free(port->wwpn_iid[i].name, M_CTL);
819			port->wwpn_iid[i].name = NULL;
820		}
821	}
822	mtx_unlock(&softc->ctl_lock);
823}
824
825static void
826ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
827{
828	struct ctl_lun *lun;
829	uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
830
831	mtx_lock(&softc->ctl_lock);
832	if (msg->hdr.nexus.targ_lun < CTL_MAX_LUNS &&
833	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) != NULL) {
834		mtx_lock(&lun->lun_lock);
835		mtx_unlock(&softc->ctl_lock);
836		if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES &&
837		    msg->ua.ua_set)
838			memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
839		if (msg->ua.ua_all) {
840			if (msg->ua.ua_set)
841				ctl_est_ua_all(lun, iid, msg->ua.ua_type);
842			else
843				ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
844		} else {
845			if (msg->ua.ua_set)
846				ctl_est_ua(lun, iid, msg->ua.ua_type);
847			else
848				ctl_clr_ua(lun, iid, msg->ua.ua_type);
849		}
850		mtx_unlock(&lun->lun_lock);
851	} else
852		mtx_unlock(&softc->ctl_lock);
853}
854
855static void
856ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
857{
858	struct ctl_lun *lun;
859	struct ctl_ha_msg_lun_pr_key pr_key;
860	int i, k;
861	ctl_lun_flags oflags;
862	uint32_t targ_lun;
863
864	targ_lun = msg->hdr.nexus.targ_mapped_lun;
865	mtx_lock(&softc->ctl_lock);
866	if ((targ_lun >= CTL_MAX_LUNS) ||
867	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
868		mtx_unlock(&softc->ctl_lock);
869		return;
870	}
871	mtx_lock(&lun->lun_lock);
872	mtx_unlock(&softc->ctl_lock);
873	if (lun->flags & CTL_LUN_DISABLED) {
874		mtx_unlock(&lun->lun_lock);
875		return;
876	}
877	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
878	if (msg->lun.lun_devid_len != i || (i > 0 &&
879	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
880		mtx_unlock(&lun->lun_lock);
881		printf("%s: Received conflicting HA LUN %d\n",
882		    __func__, msg->hdr.nexus.targ_lun);
883		return;
884	} else {
885		/* Record whether peer is primary. */
886		oflags = lun->flags;
887		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
888		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
889			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
890		else
891			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
892		if (oflags != lun->flags)
893			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
894
895		/* If peer is primary and we are not -- use data */
896		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
897		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
898			lun->PRGeneration = msg->lun.pr_generation;
899			lun->pr_res_idx = msg->lun.pr_res_idx;
900			lun->res_type = msg->lun.pr_res_type;
901			lun->pr_key_count = msg->lun.pr_key_count;
902			for (k = 0; k < CTL_MAX_INITIATORS; k++)
903				ctl_clr_prkey(lun, k);
904			for (k = 0; k < msg->lun.pr_key_count; k++) {
905				memcpy(&pr_key, &msg->lun.data[i],
906				    sizeof(pr_key));
907				ctl_alloc_prkey(lun, pr_key.pr_iid);
908				ctl_set_prkey(lun, pr_key.pr_iid,
909				    pr_key.pr_key);
910				i += sizeof(pr_key);
911			}
912		}
913
914		mtx_unlock(&lun->lun_lock);
915		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
916		    __func__, msg->hdr.nexus.targ_lun,
917		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
918		    "primary" : "secondary"));
919
920		/* If we are primary but peer doesn't know -- notify */
921		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
922		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
923			ctl_isc_announce_lun(lun);
924	}
925}
926
927static void
928ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
929{
930	struct ctl_port *port;
931	struct ctl_lun *lun;
932	int i, new;
933
934	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
935	if (port == NULL) {
936		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
937		    msg->hdr.nexus.targ_port));
938		new = 1;
939		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
940		port->frontend = &ha_frontend;
941		port->targ_port = msg->hdr.nexus.targ_port;
942	} else if (port->frontend == &ha_frontend) {
943		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
944		    msg->hdr.nexus.targ_port));
945		new = 0;
946	} else {
947		printf("%s: Received conflicting HA port %d\n",
948		    __func__, msg->hdr.nexus.targ_port);
949		return;
950	}
951	port->port_type = msg->port.port_type;
952	port->physical_port = msg->port.physical_port;
953	port->virtual_port = msg->port.virtual_port;
954	port->status = msg->port.status;
955	i = 0;
956	free(port->port_name, M_CTL);
957	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
958	    M_CTL);
959	i += msg->port.name_len;
960	if (msg->port.lun_map_len != 0) {
961		if (port->lun_map == NULL)
962			port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
963			    M_CTL, M_WAITOK);
964		memcpy(port->lun_map, &msg->port.data[i],
965		    sizeof(uint32_t) * CTL_MAX_LUNS);
966		i += msg->port.lun_map_len;
967	} else {
968		free(port->lun_map, M_CTL);
969		port->lun_map = NULL;
970	}
971	if (msg->port.port_devid_len != 0) {
972		if (port->port_devid == NULL ||
973		    port->port_devid->len != msg->port.port_devid_len) {
974			free(port->port_devid, M_CTL);
975			port->port_devid = malloc(sizeof(struct ctl_devid) +
976			    msg->port.port_devid_len, M_CTL, M_WAITOK);
977		}
978		memcpy(port->port_devid->data, &msg->port.data[i],
979		    msg->port.port_devid_len);
980		port->port_devid->len = msg->port.port_devid_len;
981		i += msg->port.port_devid_len;
982	} else {
983		free(port->port_devid, M_CTL);
984		port->port_devid = NULL;
985	}
986	if (msg->port.target_devid_len != 0) {
987		if (port->target_devid == NULL ||
988		    port->target_devid->len != msg->port.target_devid_len) {
989			free(port->target_devid, M_CTL);
990			port->target_devid = malloc(sizeof(struct ctl_devid) +
991			    msg->port.target_devid_len, M_CTL, M_WAITOK);
992		}
993		memcpy(port->target_devid->data, &msg->port.data[i],
994		    msg->port.target_devid_len);
995		port->target_devid->len = msg->port.target_devid_len;
996		i += msg->port.target_devid_len;
997	} else {
998		free(port->target_devid, M_CTL);
999		port->target_devid = NULL;
1000	}
1001	if (msg->port.init_devid_len != 0) {
1002		if (port->init_devid == NULL ||
1003		    port->init_devid->len != msg->port.init_devid_len) {
1004			free(port->init_devid, M_CTL);
1005			port->init_devid = malloc(sizeof(struct ctl_devid) +
1006			    msg->port.init_devid_len, M_CTL, M_WAITOK);
1007		}
1008		memcpy(port->init_devid->data, &msg->port.data[i],
1009		    msg->port.init_devid_len);
1010		port->init_devid->len = msg->port.init_devid_len;
1011		i += msg->port.init_devid_len;
1012	} else {
1013		free(port->init_devid, M_CTL);
1014		port->init_devid = NULL;
1015	}
1016	if (new) {
1017		if (ctl_port_register(port) != 0) {
1018			printf("%s: ctl_port_register() failed with error\n",
1019			    __func__);
1020		}
1021	}
1022	mtx_lock(&softc->ctl_lock);
1023	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1024		if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
1025			continue;
1026		mtx_lock(&lun->lun_lock);
1027		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1028		mtx_unlock(&lun->lun_lock);
1029	}
1030	mtx_unlock(&softc->ctl_lock);
1031}
1032
1033static void
1034ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1035{
1036	struct ctl_port *port;
1037	int iid;
1038
1039	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1040	if (port == NULL) {
1041		printf("%s: Received IID for unknown port %d\n",
1042		    __func__, msg->hdr.nexus.targ_port);
1043		return;
1044	}
1045	iid = msg->hdr.nexus.initid;
1046	port->wwpn_iid[iid].in_use = msg->iid.in_use;
1047	port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1048	free(port->wwpn_iid[iid].name, M_CTL);
1049	if (msg->iid.name_len) {
1050		port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1051		    msg->iid.name_len, M_CTL);
1052	} else
1053		port->wwpn_iid[iid].name = NULL;
1054}
1055
1056static void
1057ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1058{
1059
1060	if (msg->login.version != CTL_HA_VERSION) {
1061		printf("CTL HA peers have different versions %d != %d\n",
1062		    msg->login.version, CTL_HA_VERSION);
1063		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1064		return;
1065	}
1066	if (msg->login.ha_mode != softc->ha_mode) {
1067		printf("CTL HA peers have different ha_mode %d != %d\n",
1068		    msg->login.ha_mode, softc->ha_mode);
1069		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1070		return;
1071	}
1072	if (msg->login.ha_id == softc->ha_id) {
1073		printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1074		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1075		return;
1076	}
1077	if (msg->login.max_luns != CTL_MAX_LUNS ||
1078	    msg->login.max_ports != CTL_MAX_PORTS ||
1079	    msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1080		printf("CTL HA peers have different limits\n");
1081		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1082		return;
1083	}
1084}
1085
1086static void
1087ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1088{
1089	struct ctl_lun *lun;
1090	int i;
1091	uint32_t initidx, targ_lun;
1092
1093	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1094	mtx_lock(&softc->ctl_lock);
1095	if ((targ_lun >= CTL_MAX_LUNS) ||
1096	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
1097		mtx_unlock(&softc->ctl_lock);
1098		return;
1099	}
1100	mtx_lock(&lun->lun_lock);
1101	mtx_unlock(&softc->ctl_lock);
1102	if (lun->flags & CTL_LUN_DISABLED) {
1103		mtx_unlock(&lun->lun_lock);
1104		return;
1105	}
1106	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1107		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1108		    msg->mode.page_code &&
1109		    lun->mode_pages.index[i].subpage == msg->mode.subpage)
1110			break;
1111	}
1112	if (i == CTL_NUM_MODE_PAGES) {
1113		mtx_unlock(&lun->lun_lock);
1114		return;
1115	}
1116	memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1117	    lun->mode_pages.index[i].page_len);
1118	initidx = ctl_get_initindex(&msg->hdr.nexus);
1119	if (initidx != -1)
1120		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1121	mtx_unlock(&lun->lun_lock);
1122}
1123
1124/*
1125 * ISC (Inter Shelf Communication) event handler.  Events from the HA
1126 * subsystem come in here.
1127 */
1128static void
1129ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1130{
1131	struct ctl_softc *softc = control_softc;
1132	union ctl_io *io;
1133	struct ctl_prio *presio;
1134	ctl_ha_status isc_status;
1135
1136	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1137	if (event == CTL_HA_EVT_MSG_RECV) {
1138		union ctl_ha_msg *msg, msgbuf;
1139
1140		if (param > sizeof(msgbuf))
1141			msg = malloc(param, M_CTL, M_WAITOK);
1142		else
1143			msg = &msgbuf;
1144		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1145		    M_WAITOK);
1146		if (isc_status != CTL_HA_STATUS_SUCCESS) {
1147			printf("%s: Error receiving message: %d\n",
1148			    __func__, isc_status);
1149			if (msg != &msgbuf)
1150				free(msg, M_CTL);
1151			return;
1152		}
1153
1154		CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1155		switch (msg->hdr.msg_type) {
1156		case CTL_MSG_SERIALIZE:
1157			io = ctl_alloc_io(softc->othersc_pool);
1158			ctl_zero_io(io);
1159			// populate ctsio from msg
1160			io->io_hdr.io_type = CTL_IO_SCSI;
1161			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1162			io->io_hdr.original_sc = msg->hdr.original_sc;
1163			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1164					    CTL_FLAG_IO_ACTIVE;
1165			/*
1166			 * If we're in serialization-only mode, we don't
1167			 * want to go through full done processing.  Thus
1168			 * the COPY flag.
1169			 *
1170			 * XXX KDM add another flag that is more specific.
1171			 */
1172			if (softc->ha_mode != CTL_HA_MODE_XFER)
1173				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1174			io->io_hdr.nexus = msg->hdr.nexus;
1175#if 0
1176			printf("port %u, iid %u, lun %u\n",
1177			       io->io_hdr.nexus.targ_port,
1178			       io->io_hdr.nexus.initid,
1179			       io->io_hdr.nexus.targ_lun);
1180#endif
1181			io->scsiio.tag_num = msg->scsi.tag_num;
1182			io->scsiio.tag_type = msg->scsi.tag_type;
1183#ifdef CTL_TIME_IO
1184			io->io_hdr.start_time = time_uptime;
1185			getbintime(&io->io_hdr.start_bt);
1186#endif /* CTL_TIME_IO */
1187			io->scsiio.cdb_len = msg->scsi.cdb_len;
1188			memcpy(io->scsiio.cdb, msg->scsi.cdb,
1189			       CTL_MAX_CDBLEN);
1190			if (softc->ha_mode == CTL_HA_MODE_XFER) {
1191				const struct ctl_cmd_entry *entry;
1192
1193				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1194				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1195				io->io_hdr.flags |=
1196					entry->flags & CTL_FLAG_DATA_MASK;
1197			}
1198			ctl_enqueue_isc(io);
1199			break;
1200
1201		/* Performed on the Originating SC, XFER mode only */
1202		case CTL_MSG_DATAMOVE: {
1203			struct ctl_sg_entry *sgl;
1204			int i, j;
1205
1206			io = msg->hdr.original_sc;
1207			if (io == NULL) {
1208				printf("%s: original_sc == NULL!\n", __func__);
1209				/* XXX KDM do something here */
1210				break;
1211			}
1212			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1213			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1214			/*
1215			 * Keep track of this, we need to send it back over
1216			 * when the datamove is complete.
1217			 */
1218			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1219			if (msg->hdr.status == CTL_SUCCESS)
1220				io->io_hdr.status = msg->hdr.status;
1221
1222			if (msg->dt.sg_sequence == 0) {
1223				i = msg->dt.kern_sg_entries +
1224				    msg->dt.kern_data_len /
1225				    CTL_HA_DATAMOVE_SEGMENT + 1;
1226				sgl = malloc(sizeof(*sgl) * i, M_CTL,
1227				    M_WAITOK | M_ZERO);
1228				io->io_hdr.remote_sglist = sgl;
1229				io->io_hdr.local_sglist =
1230				    &sgl[msg->dt.kern_sg_entries];
1231
1232				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1233
1234				io->scsiio.kern_sg_entries =
1235					msg->dt.kern_sg_entries;
1236				io->scsiio.rem_sg_entries =
1237					msg->dt.kern_sg_entries;
1238				io->scsiio.kern_data_len =
1239					msg->dt.kern_data_len;
1240				io->scsiio.kern_total_len =
1241					msg->dt.kern_total_len;
1242				io->scsiio.kern_data_resid =
1243					msg->dt.kern_data_resid;
1244				io->scsiio.kern_rel_offset =
1245					msg->dt.kern_rel_offset;
1246				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1247				io->io_hdr.flags |= msg->dt.flags &
1248				    CTL_FLAG_BUS_ADDR;
1249			} else
1250				sgl = (struct ctl_sg_entry *)
1251					io->scsiio.kern_data_ptr;
1252
1253			for (i = msg->dt.sent_sg_entries, j = 0;
1254			     i < (msg->dt.sent_sg_entries +
1255			     msg->dt.cur_sg_entries); i++, j++) {
1256				sgl[i].addr = msg->dt.sg_list[j].addr;
1257				sgl[i].len = msg->dt.sg_list[j].len;
1258
1259#if 0
1260				printf("%s: DATAMOVE: %p,%lu j=%d, i=%d\n",
1261				    __func__, sgl[i].addr, sgl[i].len, j, i);
1262#endif
1263			}
1264
1265			/*
1266			 * If this is the last piece of the I/O, we've got
1267			 * the full S/G list.  Queue processing in the thread.
1268			 * Otherwise wait for the next piece.
1269			 */
1270			if (msg->dt.sg_last != 0)
1271				ctl_enqueue_isc(io);
1272			break;
1273		}
1274		/* Performed on the Serializing (primary) SC, XFER mode only */
1275		case CTL_MSG_DATAMOVE_DONE: {
1276			if (msg->hdr.serializing_sc == NULL) {
1277				printf("%s: serializing_sc == NULL!\n",
1278				       __func__);
1279				/* XXX KDM now what? */
1280				break;
1281			}
1282			/*
1283			 * We grab the sense information here in case
1284			 * there was a failure, so we can return status
1285			 * back to the initiator.
1286			 */
1287			io = msg->hdr.serializing_sc;
1288			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1289			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1290			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1291			io->io_hdr.port_status = msg->scsi.fetd_status;
1292			io->scsiio.residual = msg->scsi.residual;
1293			if (msg->hdr.status != CTL_STATUS_NONE) {
1294				io->io_hdr.status = msg->hdr.status;
1295				io->scsiio.scsi_status = msg->scsi.scsi_status;
1296				io->scsiio.sense_len = msg->scsi.sense_len;
1297				io->scsiio.sense_residual =msg->scsi.sense_residual;
1298				memcpy(&io->scsiio.sense_data,
1299				    &msg->scsi.sense_data,
1300				    msg->scsi.sense_len);
1301				if (msg->hdr.status == CTL_SUCCESS)
1302					io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1303			}
1304			ctl_enqueue_isc(io);
1305			break;
1306		}
1307
1308		/* Preformed on Originating SC, SER_ONLY mode */
1309		case CTL_MSG_R2R:
1310			io = msg->hdr.original_sc;
1311			if (io == NULL) {
1312				printf("%s: original_sc == NULL!\n",
1313				    __func__);
1314				break;
1315			}
1316			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1317			io->io_hdr.msg_type = CTL_MSG_R2R;
1318			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1319			ctl_enqueue_isc(io);
1320			break;
1321
1322		/*
1323		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1324		 * mode.
1325		 * Performed on the Originating (i.e. secondary) SC in XFER
1326		 * mode
1327		 */
1328		case CTL_MSG_FINISH_IO:
1329			if (softc->ha_mode == CTL_HA_MODE_XFER)
1330				ctl_isc_handler_finish_xfer(softc, msg);
1331			else
1332				ctl_isc_handler_finish_ser_only(softc, msg);
1333			break;
1334
1335		/* Preformed on Originating SC */
1336		case CTL_MSG_BAD_JUJU:
1337			io = msg->hdr.original_sc;
1338			if (io == NULL) {
1339				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1340				       __func__);
1341				break;
1342			}
1343			ctl_copy_sense_data(msg, io);
1344			/*
1345			 * IO should have already been cleaned up on other
1346			 * SC so clear this flag so we won't send a message
1347			 * back to finish the IO there.
1348			 */
1349			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1350			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1351
1352			/* io = msg->hdr.serializing_sc; */
1353			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1354			ctl_enqueue_isc(io);
1355			break;
1356
1357		/* Handle resets sent from the other side */
1358		case CTL_MSG_MANAGE_TASKS: {
1359			struct ctl_taskio *taskio;
1360			taskio = (struct ctl_taskio *)ctl_alloc_io(
1361			    softc->othersc_pool);
1362			ctl_zero_io((union ctl_io *)taskio);
1363			taskio->io_hdr.io_type = CTL_IO_TASK;
1364			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1365			taskio->io_hdr.nexus = msg->hdr.nexus;
1366			taskio->task_action = msg->task.task_action;
1367			taskio->tag_num = msg->task.tag_num;
1368			taskio->tag_type = msg->task.tag_type;
1369#ifdef CTL_TIME_IO
1370			taskio->io_hdr.start_time = time_uptime;
1371			getbintime(&taskio->io_hdr.start_bt);
1372#endif /* CTL_TIME_IO */
1373			ctl_run_task((union ctl_io *)taskio);
1374			break;
1375		}
1376		/* Persistent Reserve action which needs attention */
1377		case CTL_MSG_PERS_ACTION:
1378			presio = (struct ctl_prio *)ctl_alloc_io(
1379			    softc->othersc_pool);
1380			ctl_zero_io((union ctl_io *)presio);
1381			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1382			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1383			presio->io_hdr.nexus = msg->hdr.nexus;
1384			presio->pr_msg = msg->pr;
1385			ctl_enqueue_isc((union ctl_io *)presio);
1386			break;
1387		case CTL_MSG_UA:
1388			ctl_isc_ua(softc, msg, param);
1389			break;
1390		case CTL_MSG_PORT_SYNC:
1391			ctl_isc_port_sync(softc, msg, param);
1392			break;
1393		case CTL_MSG_LUN_SYNC:
1394			ctl_isc_lun_sync(softc, msg, param);
1395			break;
1396		case CTL_MSG_IID_SYNC:
1397			ctl_isc_iid_sync(softc, msg, param);
1398			break;
1399		case CTL_MSG_LOGIN:
1400			ctl_isc_login(softc, msg, param);
1401			break;
1402		case CTL_MSG_MODE_SYNC:
1403			ctl_isc_mode_sync(softc, msg, param);
1404			break;
1405		default:
1406			printf("Received HA message of unknown type %d\n",
1407			    msg->hdr.msg_type);
1408			ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1409			break;
1410		}
1411		if (msg != &msgbuf)
1412			free(msg, M_CTL);
1413	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1414		printf("CTL: HA link status changed from %d to %d\n",
1415		    softc->ha_link, param);
1416		if (param == softc->ha_link)
1417			return;
1418		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1419			softc->ha_link = param;
1420			ctl_isc_ha_link_down(softc);
1421		} else {
1422			softc->ha_link = param;
1423			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1424				ctl_isc_ha_link_up(softc);
1425		}
1426		return;
1427	} else {
1428		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1429		return;
1430	}
1431}
1432
1433static void
1434ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1435{
1436
1437	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1438	    src->scsi.sense_len);
1439	dest->scsiio.scsi_status = src->scsi.scsi_status;
1440	dest->scsiio.sense_len = src->scsi.sense_len;
1441	dest->io_hdr.status = src->hdr.status;
1442}
1443
1444static void
1445ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1446{
1447
1448	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1449	    src->scsiio.sense_len);
1450	dest->scsi.scsi_status = src->scsiio.scsi_status;
1451	dest->scsi.sense_len = src->scsiio.sense_len;
1452	dest->hdr.status = src->io_hdr.status;
1453}
1454
1455void
1456ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1457{
1458	struct ctl_softc *softc = lun->ctl_softc;
1459	ctl_ua_type *pu;
1460
1461	if (initidx < softc->init_min || initidx >= softc->init_max)
1462		return;
1463	mtx_assert(&lun->lun_lock, MA_OWNED);
1464	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1465	if (pu == NULL)
1466		return;
1467	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1468}
1469
1470void
1471ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1472{
1473	int i;
1474
1475	mtx_assert(&lun->lun_lock, MA_OWNED);
1476	if (lun->pending_ua[port] == NULL)
1477		return;
1478	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1479		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1480			continue;
1481		lun->pending_ua[port][i] |= ua;
1482	}
1483}
1484
1485void
1486ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1487{
1488	struct ctl_softc *softc = lun->ctl_softc;
1489	int i;
1490
1491	mtx_assert(&lun->lun_lock, MA_OWNED);
1492	for (i = softc->port_min; i < softc->port_max; i++)
1493		ctl_est_ua_port(lun, i, except, ua);
1494}
1495
1496void
1497ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1498{
1499	struct ctl_softc *softc = lun->ctl_softc;
1500	ctl_ua_type *pu;
1501
1502	if (initidx < softc->init_min || initidx >= softc->init_max)
1503		return;
1504	mtx_assert(&lun->lun_lock, MA_OWNED);
1505	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1506	if (pu == NULL)
1507		return;
1508	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1509}
1510
1511void
1512ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1513{
1514	struct ctl_softc *softc = lun->ctl_softc;
1515	int i, j;
1516
1517	mtx_assert(&lun->lun_lock, MA_OWNED);
1518	for (i = softc->port_min; i < softc->port_max; i++) {
1519		if (lun->pending_ua[i] == NULL)
1520			continue;
1521		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1522			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1523				continue;
1524			lun->pending_ua[i][j] &= ~ua;
1525		}
1526	}
1527}
1528
1529void
1530ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1531    ctl_ua_type ua_type)
1532{
1533	struct ctl_lun *lun;
1534
1535	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1536	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1537		mtx_lock(&lun->lun_lock);
1538		ctl_clr_ua(lun, initidx, ua_type);
1539		mtx_unlock(&lun->lun_lock);
1540	}
1541}
1542
1543static int
1544ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1545{
1546	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1547	struct ctl_lun *lun;
1548	struct ctl_lun_req ireq;
1549	int error, value;
1550
1551	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1552	error = sysctl_handle_int(oidp, &value, 0, req);
1553	if ((error != 0) || (req->newptr == NULL))
1554		return (error);
1555
1556	mtx_lock(&softc->ctl_lock);
1557	if (value == 0)
1558		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1559	else
1560		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1561	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1562		mtx_unlock(&softc->ctl_lock);
1563		bzero(&ireq, sizeof(ireq));
1564		ireq.reqtype = CTL_LUNREQ_MODIFY;
1565		ireq.reqdata.modify.lun_id = lun->lun;
1566		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1567		    curthread);
1568		if (ireq.status != CTL_LUN_OK) {
1569			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1570			    __func__, ireq.status, ireq.error_str);
1571		}
1572		mtx_lock(&softc->ctl_lock);
1573	}
1574	mtx_unlock(&softc->ctl_lock);
1575	return (0);
1576}
1577
1578static int
1579ctl_init(void)
1580{
1581	struct ctl_softc *softc;
1582	void *other_pool;
1583	int i, error, retval;
1584
1585	retval = 0;
1586	softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1587			       M_WAITOK | M_ZERO);
1588
1589	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1590			      "cam/ctl");
1591	softc->dev->si_drv1 = softc;
1592
1593	sysctl_ctx_init(&softc->sysctl_ctx);
1594	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1595		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1596		CTLFLAG_RD, 0, "CAM Target Layer");
1597
1598	if (softc->sysctl_tree == NULL) {
1599		printf("%s: unable to allocate sysctl tree\n", __func__);
1600		destroy_dev(softc->dev);
1601		free(control_softc, M_DEVBUF);
1602		control_softc = NULL;
1603		return (ENOMEM);
1604	}
1605
1606	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1607	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1608	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1609	softc->open_count = 0;
1610
1611	/*
1612	 * Default to actually sending a SYNCHRONIZE CACHE command down to
1613	 * the drive.
1614	 */
1615	softc->flags = CTL_FLAG_REAL_SYNC;
1616
1617	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1618	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1619	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1620
1621	/*
1622	 * In Copan's HA scheme, the "master" and "slave" roles are
1623	 * figured out through the slot the controller is in.  Although it
1624	 * is an active/active system, someone has to be in charge.
1625	 */
1626	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1627	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1628	    "HA head ID (0 - no HA)");
1629	if (softc->ha_id == 0 || softc->ha_id > NUM_TARGET_PORT_GROUPS) {
1630		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1631		softc->is_single = 1;
1632		softc->port_cnt = CTL_MAX_PORTS;
1633		softc->port_min = 0;
1634	} else {
1635		softc->port_cnt = CTL_MAX_PORTS / NUM_TARGET_PORT_GROUPS;
1636		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1637	}
1638	softc->port_max = softc->port_min + softc->port_cnt;
1639	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1640	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1641
1642	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1643	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1644	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
1645
1646	STAILQ_INIT(&softc->lun_list);
1647	STAILQ_INIT(&softc->pending_lun_queue);
1648	STAILQ_INIT(&softc->fe_list);
1649	STAILQ_INIT(&softc->port_list);
1650	STAILQ_INIT(&softc->be_list);
1651	ctl_tpc_init(softc);
1652
1653	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1654	                    &other_pool) != 0)
1655	{
1656		printf("ctl: can't allocate %d entry other SC pool, "
1657		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1658		return (ENOMEM);
1659	}
1660	softc->othersc_pool = other_pool;
1661
1662	if (worker_threads <= 0)
1663		worker_threads = max(1, mp_ncpus / 4);
1664	if (worker_threads > CTL_MAX_THREADS)
1665		worker_threads = CTL_MAX_THREADS;
1666
1667	for (i = 0; i < worker_threads; i++) {
1668		struct ctl_thread *thr = &softc->threads[i];
1669
1670		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1671		thr->ctl_softc = softc;
1672		STAILQ_INIT(&thr->incoming_queue);
1673		STAILQ_INIT(&thr->rtr_queue);
1674		STAILQ_INIT(&thr->done_queue);
1675		STAILQ_INIT(&thr->isc_queue);
1676
1677		error = kproc_kthread_add(ctl_work_thread, thr,
1678		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1679		if (error != 0) {
1680			printf("error creating CTL work thread!\n");
1681			ctl_pool_free(other_pool);
1682			return (error);
1683		}
1684	}
1685	error = kproc_kthread_add(ctl_lun_thread, softc,
1686	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1687	if (error != 0) {
1688		printf("error creating CTL lun thread!\n");
1689		ctl_pool_free(other_pool);
1690		return (error);
1691	}
1692	error = kproc_kthread_add(ctl_thresh_thread, softc,
1693	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1694	if (error != 0) {
1695		printf("error creating CTL threshold thread!\n");
1696		ctl_pool_free(other_pool);
1697		return (error);
1698	}
1699
1700	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1701	    OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1702	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1703
1704	if (softc->is_single == 0) {
1705		ctl_frontend_register(&ha_frontend);
1706		if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
1707			printf("ctl_init: ctl_ha_msg_init failed.\n");
1708			softc->is_single = 1;
1709		} else
1710		if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
1711		    != CTL_HA_STATUS_SUCCESS) {
1712			printf("ctl_init: ctl_ha_msg_register failed.\n");
1713			softc->is_single = 1;
1714		}
1715	}
1716	return (0);
1717}
1718
1719void
1720ctl_shutdown(void)
1721{
1722	struct ctl_softc *softc = control_softc;
1723	struct ctl_lun *lun, *next_lun;
1724
1725	if (softc->is_single == 0) {
1726		ctl_ha_msg_shutdown(softc);
1727		if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL)
1728		    != CTL_HA_STATUS_SUCCESS)
1729			printf("%s: ctl_ha_msg_deregister failed.\n", __func__);
1730		if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
1731			printf("%s: ctl_ha_msg_destroy failed.\n", __func__);
1732		ctl_frontend_deregister(&ha_frontend);
1733	}
1734
1735	mtx_lock(&softc->ctl_lock);
1736
1737	/*
1738	 * Free up each LUN.
1739	 */
1740	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1741		next_lun = STAILQ_NEXT(lun, links);
1742		ctl_free_lun(lun);
1743	}
1744
1745	mtx_unlock(&softc->ctl_lock);
1746
1747#if 0
1748	ctl_shutdown_thread(softc->work_thread);
1749	mtx_destroy(&softc->queue_lock);
1750#endif
1751
1752	ctl_tpc_shutdown(softc);
1753	uma_zdestroy(softc->io_zone);
1754	mtx_destroy(&softc->ctl_lock);
1755
1756	destroy_dev(softc->dev);
1757
1758	sysctl_ctx_free(&softc->sysctl_ctx);
1759
1760	free(control_softc, M_DEVBUF);
1761	control_softc = NULL;
1762}
1763
1764static int
1765ctl_module_event_handler(module_t mod, int what, void *arg)
1766{
1767
1768	switch (what) {
1769	case MOD_LOAD:
1770		return (ctl_init());
1771	case MOD_UNLOAD:
1772		return (EBUSY);
1773	default:
1774		return (EOPNOTSUPP);
1775	}
1776}
1777
1778/*
1779 * XXX KDM should we do some access checks here?  Bump a reference count to
1780 * prevent a CTL module from being unloaded while someone has it open?
1781 */
1782static int
1783ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1784{
1785	return (0);
1786}
1787
1788static int
1789ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1790{
1791	return (0);
1792}
1793
1794/*
1795 * Remove an initiator by port number and initiator ID.
1796 * Returns 0 for success, -1 for failure.
1797 */
1798int
1799ctl_remove_initiator(struct ctl_port *port, int iid)
1800{
1801	struct ctl_softc *softc = port->ctl_softc;
1802
1803	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1804
1805	if (iid > CTL_MAX_INIT_PER_PORT) {
1806		printf("%s: initiator ID %u > maximun %u!\n",
1807		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1808		return (-1);
1809	}
1810
1811	mtx_lock(&softc->ctl_lock);
1812	port->wwpn_iid[iid].in_use--;
1813	port->wwpn_iid[iid].last_use = time_uptime;
1814	mtx_unlock(&softc->ctl_lock);
1815	ctl_isc_announce_iid(port, iid);
1816
1817	return (0);
1818}
1819
1820/*
1821 * Add an initiator to the initiator map.
1822 * Returns iid for success, < 0 for failure.
1823 */
1824int
1825ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1826{
1827	struct ctl_softc *softc = port->ctl_softc;
1828	time_t best_time;
1829	int i, best;
1830
1831	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1832
1833	if (iid >= CTL_MAX_INIT_PER_PORT) {
1834		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1835		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1836		free(name, M_CTL);
1837		return (-1);
1838	}
1839
1840	mtx_lock(&softc->ctl_lock);
1841
1842	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1843		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1844			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1845				iid = i;
1846				break;
1847			}
1848			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1849			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1850				iid = i;
1851				break;
1852			}
1853		}
1854	}
1855
1856	if (iid < 0) {
1857		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1858			if (port->wwpn_iid[i].in_use == 0 &&
1859			    port->wwpn_iid[i].wwpn == 0 &&
1860			    port->wwpn_iid[i].name == NULL) {
1861				iid = i;
1862				break;
1863			}
1864		}
1865	}
1866
1867	if (iid < 0) {
1868		best = -1;
1869		best_time = INT32_MAX;
1870		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1871			if (port->wwpn_iid[i].in_use == 0) {
1872				if (port->wwpn_iid[i].last_use < best_time) {
1873					best = i;
1874					best_time = port->wwpn_iid[i].last_use;
1875				}
1876			}
1877		}
1878		iid = best;
1879	}
1880
1881	if (iid < 0) {
1882		mtx_unlock(&softc->ctl_lock);
1883		free(name, M_CTL);
1884		return (-2);
1885	}
1886
1887	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1888		/*
1889		 * This is not an error yet.
1890		 */
1891		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1892#if 0
1893			printf("%s: port %d iid %u WWPN %#jx arrived"
1894			    " again\n", __func__, port->targ_port,
1895			    iid, (uintmax_t)wwpn);
1896#endif
1897			goto take;
1898		}
1899		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1900		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1901#if 0
1902			printf("%s: port %d iid %u name '%s' arrived"
1903			    " again\n", __func__, port->targ_port,
1904			    iid, name);
1905#endif
1906			goto take;
1907		}
1908
1909		/*
1910		 * This is an error, but what do we do about it?  The
1911		 * driver is telling us we have a new WWPN for this
1912		 * initiator ID, so we pretty much need to use it.
1913		 */
1914		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1915		    " but WWPN %#jx '%s' is still at that address\n",
1916		    __func__, port->targ_port, iid, wwpn, name,
1917		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1918		    port->wwpn_iid[iid].name);
1919
1920		/*
1921		 * XXX KDM clear have_ca and ua_pending on each LUN for
1922		 * this initiator.
1923		 */
1924	}
1925take:
1926	free(port->wwpn_iid[iid].name, M_CTL);
1927	port->wwpn_iid[iid].name = name;
1928	port->wwpn_iid[iid].wwpn = wwpn;
1929	port->wwpn_iid[iid].in_use++;
1930	mtx_unlock(&softc->ctl_lock);
1931	ctl_isc_announce_iid(port, iid);
1932
1933	return (iid);
1934}
1935
1936static int
1937ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1938{
1939	int len;
1940
1941	switch (port->port_type) {
1942	case CTL_PORT_FC:
1943	{
1944		struct scsi_transportid_fcp *id =
1945		    (struct scsi_transportid_fcp *)buf;
1946		if (port->wwpn_iid[iid].wwpn == 0)
1947			return (0);
1948		memset(id, 0, sizeof(*id));
1949		id->format_protocol = SCSI_PROTO_FC;
1950		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1951		return (sizeof(*id));
1952	}
1953	case CTL_PORT_ISCSI:
1954	{
1955		struct scsi_transportid_iscsi_port *id =
1956		    (struct scsi_transportid_iscsi_port *)buf;
1957		if (port->wwpn_iid[iid].name == NULL)
1958			return (0);
1959		memset(id, 0, 256);
1960		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1961		    SCSI_PROTO_ISCSI;
1962		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1963		len = roundup2(min(len, 252), 4);
1964		scsi_ulto2b(len, id->additional_length);
1965		return (sizeof(*id) + len);
1966	}
1967	case CTL_PORT_SAS:
1968	{
1969		struct scsi_transportid_sas *id =
1970		    (struct scsi_transportid_sas *)buf;
1971		if (port->wwpn_iid[iid].wwpn == 0)
1972			return (0);
1973		memset(id, 0, sizeof(*id));
1974		id->format_protocol = SCSI_PROTO_SAS;
1975		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1976		return (sizeof(*id));
1977	}
1978	default:
1979	{
1980		struct scsi_transportid_spi *id =
1981		    (struct scsi_transportid_spi *)buf;
1982		memset(id, 0, sizeof(*id));
1983		id->format_protocol = SCSI_PROTO_SPI;
1984		scsi_ulto2b(iid, id->scsi_addr);
1985		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1986		return (sizeof(*id));
1987	}
1988	}
1989}
1990
1991/*
1992 * Serialize a command that went down the "wrong" side, and so was sent to
1993 * this controller for execution.  The logic is a little different than the
1994 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1995 * sent back to the other side, but in the success case, we execute the
1996 * command on this side (XFER mode) or tell the other side to execute it
1997 * (SER_ONLY mode).
1998 */
1999static int
2000ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2001{
2002	struct ctl_softc *softc = control_softc;
2003	union ctl_ha_msg msg_info;
2004	struct ctl_lun *lun;
2005	const struct ctl_cmd_entry *entry;
2006	int retval = 0;
2007	uint32_t targ_lun;
2008
2009	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2010	mtx_lock(&softc->ctl_lock);
2011	if ((targ_lun < CTL_MAX_LUNS) &&
2012	    ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
2013		mtx_lock(&lun->lun_lock);
2014		mtx_unlock(&softc->ctl_lock);
2015		/*
2016		 * If the LUN is invalid, pretend that it doesn't exist.
2017		 * It will go away as soon as all pending I/O has been
2018		 * completed.
2019		 */
2020		if (lun->flags & CTL_LUN_DISABLED) {
2021			mtx_unlock(&lun->lun_lock);
2022			lun = NULL;
2023		}
2024	} else {
2025		mtx_unlock(&softc->ctl_lock);
2026		lun = NULL;
2027	}
2028	if (lun == NULL) {
2029		/*
2030		 * The other node would not send this request to us unless
2031		 * received announce that we are primary node for this LUN.
2032		 * If this LUN does not exist now, it is probably result of
2033		 * a race, so respond to initiator in the most opaque way.
2034		 */
2035		ctl_set_busy(ctsio);
2036		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2037		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2038		msg_info.hdr.serializing_sc = NULL;
2039		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2040		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2041		    sizeof(msg_info.scsi), M_WAITOK);
2042		return(1);
2043	}
2044
2045	entry = ctl_get_cmd_entry(ctsio, NULL);
2046	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2047		mtx_unlock(&lun->lun_lock);
2048		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2049		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2050		msg_info.hdr.serializing_sc = NULL;
2051		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2052		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2053		    sizeof(msg_info.scsi), M_WAITOK);
2054		return(1);
2055	}
2056
2057	ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
2058	ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = lun->be_lun;
2059
2060	/*
2061	 * Every I/O goes into the OOA queue for a
2062	 * particular LUN, and stays there until completion.
2063	 */
2064#ifdef CTL_TIME_IO
2065	if (TAILQ_EMPTY(&lun->ooa_queue))
2066		lun->idle_time += getsbinuptime() - lun->last_busy;
2067#endif
2068	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2069
2070	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2071		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2072		 ooa_links))) {
2073	case CTL_ACTION_BLOCK:
2074		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2075		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2076				  blocked_links);
2077		mtx_unlock(&lun->lun_lock);
2078		break;
2079	case CTL_ACTION_PASS:
2080	case CTL_ACTION_SKIP:
2081		if (softc->ha_mode == CTL_HA_MODE_XFER) {
2082			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2083			ctl_enqueue_rtr((union ctl_io *)ctsio);
2084			mtx_unlock(&lun->lun_lock);
2085		} else {
2086			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2087			mtx_unlock(&lun->lun_lock);
2088
2089			/* send msg back to other side */
2090			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2091			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2092			msg_info.hdr.msg_type = CTL_MSG_R2R;
2093			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2094			    sizeof(msg_info.hdr), M_WAITOK);
2095		}
2096		break;
2097	case CTL_ACTION_OVERLAP:
2098		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2099		mtx_unlock(&lun->lun_lock);
2100		retval = 1;
2101
2102		ctl_set_overlapped_cmd(ctsio);
2103		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2104		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2105		msg_info.hdr.serializing_sc = NULL;
2106		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2107		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2108		    sizeof(msg_info.scsi), M_WAITOK);
2109		break;
2110	case CTL_ACTION_OVERLAP_TAG:
2111		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2112		mtx_unlock(&lun->lun_lock);
2113		retval = 1;
2114		ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2115		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2116		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2117		msg_info.hdr.serializing_sc = NULL;
2118		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2119		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2120		    sizeof(msg_info.scsi), M_WAITOK);
2121		break;
2122	case CTL_ACTION_ERROR:
2123	default:
2124		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2125		mtx_unlock(&lun->lun_lock);
2126		retval = 1;
2127
2128		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2129					 /*retry_count*/ 0);
2130		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2131		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2132		msg_info.hdr.serializing_sc = NULL;
2133		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2134		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2135		    sizeof(msg_info.scsi), M_WAITOK);
2136		break;
2137	}
2138	return (retval);
2139}
2140
2141/*
2142 * Returns 0 for success, errno for failure.
2143 */
2144static int
2145ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2146		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2147{
2148	union ctl_io *io;
2149	int retval;
2150
2151	retval = 0;
2152
2153	mtx_lock(&lun->lun_lock);
2154	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2155	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2156	     ooa_links)) {
2157		struct ctl_ooa_entry *entry;
2158
2159		/*
2160		 * If we've got more than we can fit, just count the
2161		 * remaining entries.
2162		 */
2163		if (*cur_fill_num >= ooa_hdr->alloc_num)
2164			continue;
2165
2166		entry = &kern_entries[*cur_fill_num];
2167
2168		entry->tag_num = io->scsiio.tag_num;
2169		entry->lun_num = lun->lun;
2170#ifdef CTL_TIME_IO
2171		entry->start_bt = io->io_hdr.start_bt;
2172#endif
2173		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2174		entry->cdb_len = io->scsiio.cdb_len;
2175		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2176			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2177
2178		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2179			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2180
2181		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2182			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2183
2184		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2185			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2186
2187		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2188			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2189	}
2190	mtx_unlock(&lun->lun_lock);
2191
2192	return (retval);
2193}
2194
2195static void *
2196ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2197		 size_t error_str_len)
2198{
2199	void *kptr;
2200
2201	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2202
2203	if (copyin(user_addr, kptr, len) != 0) {
2204		snprintf(error_str, error_str_len, "Error copying %d bytes "
2205			 "from user address %p to kernel address %p", len,
2206			 user_addr, kptr);
2207		free(kptr, M_CTL);
2208		return (NULL);
2209	}
2210
2211	return (kptr);
2212}
2213
2214static void
2215ctl_free_args(int num_args, struct ctl_be_arg *args)
2216{
2217	int i;
2218
2219	if (args == NULL)
2220		return;
2221
2222	for (i = 0; i < num_args; i++) {
2223		free(args[i].kname, M_CTL);
2224		free(args[i].kvalue, M_CTL);
2225	}
2226
2227	free(args, M_CTL);
2228}
2229
2230static struct ctl_be_arg *
2231ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2232		char *error_str, size_t error_str_len)
2233{
2234	struct ctl_be_arg *args;
2235	int i;
2236
2237	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2238				error_str, error_str_len);
2239
2240	if (args == NULL)
2241		goto bailout;
2242
2243	for (i = 0; i < num_args; i++) {
2244		args[i].kname = NULL;
2245		args[i].kvalue = NULL;
2246	}
2247
2248	for (i = 0; i < num_args; i++) {
2249		uint8_t *tmpptr;
2250
2251		args[i].kname = ctl_copyin_alloc(args[i].name,
2252			args[i].namelen, error_str, error_str_len);
2253		if (args[i].kname == NULL)
2254			goto bailout;
2255
2256		if (args[i].kname[args[i].namelen - 1] != '\0') {
2257			snprintf(error_str, error_str_len, "Argument %d "
2258				 "name is not NUL-terminated", i);
2259			goto bailout;
2260		}
2261
2262		if (args[i].flags & CTL_BEARG_RD) {
2263			tmpptr = ctl_copyin_alloc(args[i].value,
2264				args[i].vallen, error_str, error_str_len);
2265			if (tmpptr == NULL)
2266				goto bailout;
2267			if ((args[i].flags & CTL_BEARG_ASCII)
2268			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2269				snprintf(error_str, error_str_len, "Argument "
2270				    "%d value is not NUL-terminated", i);
2271				goto bailout;
2272			}
2273			args[i].kvalue = tmpptr;
2274		} else {
2275			args[i].kvalue = malloc(args[i].vallen,
2276			    M_CTL, M_WAITOK | M_ZERO);
2277		}
2278	}
2279
2280	return (args);
2281bailout:
2282
2283	ctl_free_args(num_args, args);
2284
2285	return (NULL);
2286}
2287
2288static void
2289ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2290{
2291	int i;
2292
2293	for (i = 0; i < num_args; i++) {
2294		if (args[i].flags & CTL_BEARG_WR)
2295			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2296	}
2297}
2298
2299/*
2300 * Escape characters that are illegal or not recommended in XML.
2301 */
2302int
2303ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2304{
2305	char *end = str + size;
2306	int retval;
2307
2308	retval = 0;
2309
2310	for (; *str && str < end; str++) {
2311		switch (*str) {
2312		case '&':
2313			retval = sbuf_printf(sb, "&amp;");
2314			break;
2315		case '>':
2316			retval = sbuf_printf(sb, "&gt;");
2317			break;
2318		case '<':
2319			retval = sbuf_printf(sb, "&lt;");
2320			break;
2321		default:
2322			retval = sbuf_putc(sb, *str);
2323			break;
2324		}
2325
2326		if (retval != 0)
2327			break;
2328
2329	}
2330
2331	return (retval);
2332}
2333
2334static void
2335ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2336{
2337	struct scsi_vpd_id_descriptor *desc;
2338	int i;
2339
2340	if (id == NULL || id->len < 4)
2341		return;
2342	desc = (struct scsi_vpd_id_descriptor *)id->data;
2343	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2344	case SVPD_ID_TYPE_T10:
2345		sbuf_printf(sb, "t10.");
2346		break;
2347	case SVPD_ID_TYPE_EUI64:
2348		sbuf_printf(sb, "eui.");
2349		break;
2350	case SVPD_ID_TYPE_NAA:
2351		sbuf_printf(sb, "naa.");
2352		break;
2353	case SVPD_ID_TYPE_SCSI_NAME:
2354		break;
2355	}
2356	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2357	case SVPD_ID_CODESET_BINARY:
2358		for (i = 0; i < desc->length; i++)
2359			sbuf_printf(sb, "%02x", desc->identifier[i]);
2360		break;
2361	case SVPD_ID_CODESET_ASCII:
2362		sbuf_printf(sb, "%.*s", (int)desc->length,
2363		    (char *)desc->identifier);
2364		break;
2365	case SVPD_ID_CODESET_UTF8:
2366		sbuf_printf(sb, "%s", (char *)desc->identifier);
2367		break;
2368	}
2369}
2370
2371static int
2372ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2373	  struct thread *td)
2374{
2375	struct ctl_softc *softc = dev->si_drv1;
2376	struct ctl_lun *lun;
2377	int retval;
2378
2379	retval = 0;
2380
2381	switch (cmd) {
2382	case CTL_IO:
2383		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2384		break;
2385	case CTL_ENABLE_PORT:
2386	case CTL_DISABLE_PORT:
2387	case CTL_SET_PORT_WWNS: {
2388		struct ctl_port *port;
2389		struct ctl_port_entry *entry;
2390
2391		entry = (struct ctl_port_entry *)addr;
2392
2393		mtx_lock(&softc->ctl_lock);
2394		STAILQ_FOREACH(port, &softc->port_list, links) {
2395			int action, done;
2396
2397			if (port->targ_port < softc->port_min ||
2398			    port->targ_port >= softc->port_max)
2399				continue;
2400
2401			action = 0;
2402			done = 0;
2403			if ((entry->port_type == CTL_PORT_NONE)
2404			 && (entry->targ_port == port->targ_port)) {
2405				/*
2406				 * If the user only wants to enable or
2407				 * disable or set WWNs on a specific port,
2408				 * do the operation and we're done.
2409				 */
2410				action = 1;
2411				done = 1;
2412			} else if (entry->port_type & port->port_type) {
2413				/*
2414				 * Compare the user's type mask with the
2415				 * particular frontend type to see if we
2416				 * have a match.
2417				 */
2418				action = 1;
2419				done = 0;
2420
2421				/*
2422				 * Make sure the user isn't trying to set
2423				 * WWNs on multiple ports at the same time.
2424				 */
2425				if (cmd == CTL_SET_PORT_WWNS) {
2426					printf("%s: Can't set WWNs on "
2427					       "multiple ports\n", __func__);
2428					retval = EINVAL;
2429					break;
2430				}
2431			}
2432			if (action == 0)
2433				continue;
2434
2435			/*
2436			 * XXX KDM we have to drop the lock here, because
2437			 * the online/offline operations can potentially
2438			 * block.  We need to reference count the frontends
2439			 * so they can't go away,
2440			 */
2441			if (cmd == CTL_ENABLE_PORT) {
2442				mtx_unlock(&softc->ctl_lock);
2443				ctl_port_online(port);
2444				mtx_lock(&softc->ctl_lock);
2445			} else if (cmd == CTL_DISABLE_PORT) {
2446				mtx_unlock(&softc->ctl_lock);
2447				ctl_port_offline(port);
2448				mtx_lock(&softc->ctl_lock);
2449			} else if (cmd == CTL_SET_PORT_WWNS) {
2450				ctl_port_set_wwns(port,
2451				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2452				    1 : 0, entry->wwnn,
2453				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2454				    1 : 0, entry->wwpn);
2455			}
2456			if (done != 0)
2457				break;
2458		}
2459		mtx_unlock(&softc->ctl_lock);
2460		break;
2461	}
2462	case CTL_GET_PORT_LIST: {
2463		struct ctl_port *port;
2464		struct ctl_port_list *list;
2465		int i;
2466
2467		list = (struct ctl_port_list *)addr;
2468
2469		if (list->alloc_len != (list->alloc_num *
2470		    sizeof(struct ctl_port_entry))) {
2471			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2472			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2473			       "%zu\n", __func__, list->alloc_len,
2474			       list->alloc_num, sizeof(struct ctl_port_entry));
2475			retval = EINVAL;
2476			break;
2477		}
2478		list->fill_len = 0;
2479		list->fill_num = 0;
2480		list->dropped_num = 0;
2481		i = 0;
2482		mtx_lock(&softc->ctl_lock);
2483		STAILQ_FOREACH(port, &softc->port_list, links) {
2484			struct ctl_port_entry entry, *list_entry;
2485
2486			if (list->fill_num >= list->alloc_num) {
2487				list->dropped_num++;
2488				continue;
2489			}
2490
2491			entry.port_type = port->port_type;
2492			strlcpy(entry.port_name, port->port_name,
2493				sizeof(entry.port_name));
2494			entry.targ_port = port->targ_port;
2495			entry.physical_port = port->physical_port;
2496			entry.virtual_port = port->virtual_port;
2497			entry.wwnn = port->wwnn;
2498			entry.wwpn = port->wwpn;
2499			if (port->status & CTL_PORT_STATUS_ONLINE)
2500				entry.online = 1;
2501			else
2502				entry.online = 0;
2503
2504			list_entry = &list->entries[i];
2505
2506			retval = copyout(&entry, list_entry, sizeof(entry));
2507			if (retval != 0) {
2508				printf("%s: CTL_GET_PORT_LIST: copyout "
2509				       "returned %d\n", __func__, retval);
2510				break;
2511			}
2512			i++;
2513			list->fill_num++;
2514			list->fill_len += sizeof(entry);
2515		}
2516		mtx_unlock(&softc->ctl_lock);
2517
2518		/*
2519		 * If this is non-zero, we had a copyout fault, so there's
2520		 * probably no point in attempting to set the status inside
2521		 * the structure.
2522		 */
2523		if (retval != 0)
2524			break;
2525
2526		if (list->dropped_num > 0)
2527			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2528		else
2529			list->status = CTL_PORT_LIST_OK;
2530		break;
2531	}
2532	case CTL_DUMP_OOA: {
2533		union ctl_io *io;
2534		char printbuf[128];
2535		struct sbuf sb;
2536
2537		mtx_lock(&softc->ctl_lock);
2538		printf("Dumping OOA queues:\n");
2539		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2540			mtx_lock(&lun->lun_lock);
2541			for (io = (union ctl_io *)TAILQ_FIRST(
2542			     &lun->ooa_queue); io != NULL;
2543			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2544			     ooa_links)) {
2545				sbuf_new(&sb, printbuf, sizeof(printbuf),
2546					 SBUF_FIXEDLEN);
2547				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2548					    (intmax_t)lun->lun,
2549					    io->scsiio.tag_num,
2550					    (io->io_hdr.flags &
2551					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2552					    (io->io_hdr.flags &
2553					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2554					    (io->io_hdr.flags &
2555					    CTL_FLAG_ABORT) ? " ABORT" : "",
2556			                    (io->io_hdr.flags &
2557		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2558				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2559				sbuf_finish(&sb);
2560				printf("%s\n", sbuf_data(&sb));
2561			}
2562			mtx_unlock(&lun->lun_lock);
2563		}
2564		printf("OOA queues dump done\n");
2565		mtx_unlock(&softc->ctl_lock);
2566		break;
2567	}
2568	case CTL_GET_OOA: {
2569		struct ctl_ooa *ooa_hdr;
2570		struct ctl_ooa_entry *entries;
2571		uint32_t cur_fill_num;
2572
2573		ooa_hdr = (struct ctl_ooa *)addr;
2574
2575		if ((ooa_hdr->alloc_len == 0)
2576		 || (ooa_hdr->alloc_num == 0)) {
2577			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2578			       "must be non-zero\n", __func__,
2579			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2580			retval = EINVAL;
2581			break;
2582		}
2583
2584		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2585		    sizeof(struct ctl_ooa_entry))) {
2586			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2587			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2588			       __func__, ooa_hdr->alloc_len,
2589			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2590			retval = EINVAL;
2591			break;
2592		}
2593
2594		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2595		if (entries == NULL) {
2596			printf("%s: could not allocate %d bytes for OOA "
2597			       "dump\n", __func__, ooa_hdr->alloc_len);
2598			retval = ENOMEM;
2599			break;
2600		}
2601
2602		mtx_lock(&softc->ctl_lock);
2603		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2604		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2605		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2606			mtx_unlock(&softc->ctl_lock);
2607			free(entries, M_CTL);
2608			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2609			       __func__, (uintmax_t)ooa_hdr->lun_num);
2610			retval = EINVAL;
2611			break;
2612		}
2613
2614		cur_fill_num = 0;
2615
2616		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2617			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2618				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2619					ooa_hdr, entries);
2620				if (retval != 0)
2621					break;
2622			}
2623			if (retval != 0) {
2624				mtx_unlock(&softc->ctl_lock);
2625				free(entries, M_CTL);
2626				break;
2627			}
2628		} else {
2629			lun = softc->ctl_luns[ooa_hdr->lun_num];
2630
2631			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2632						    entries);
2633		}
2634		mtx_unlock(&softc->ctl_lock);
2635
2636		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2637		ooa_hdr->fill_len = ooa_hdr->fill_num *
2638			sizeof(struct ctl_ooa_entry);
2639		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2640		if (retval != 0) {
2641			printf("%s: error copying out %d bytes for OOA dump\n",
2642			       __func__, ooa_hdr->fill_len);
2643		}
2644
2645		getbintime(&ooa_hdr->cur_bt);
2646
2647		if (cur_fill_num > ooa_hdr->alloc_num) {
2648			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2649			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2650		} else {
2651			ooa_hdr->dropped_num = 0;
2652			ooa_hdr->status = CTL_OOA_OK;
2653		}
2654
2655		free(entries, M_CTL);
2656		break;
2657	}
2658	case CTL_CHECK_OOA: {
2659		union ctl_io *io;
2660		struct ctl_ooa_info *ooa_info;
2661
2662
2663		ooa_info = (struct ctl_ooa_info *)addr;
2664
2665		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2666			ooa_info->status = CTL_OOA_INVALID_LUN;
2667			break;
2668		}
2669		mtx_lock(&softc->ctl_lock);
2670		lun = softc->ctl_luns[ooa_info->lun_id];
2671		if (lun == NULL) {
2672			mtx_unlock(&softc->ctl_lock);
2673			ooa_info->status = CTL_OOA_INVALID_LUN;
2674			break;
2675		}
2676		mtx_lock(&lun->lun_lock);
2677		mtx_unlock(&softc->ctl_lock);
2678		ooa_info->num_entries = 0;
2679		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2680		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2681		     &io->io_hdr, ooa_links)) {
2682			ooa_info->num_entries++;
2683		}
2684		mtx_unlock(&lun->lun_lock);
2685
2686		ooa_info->status = CTL_OOA_SUCCESS;
2687
2688		break;
2689	}
2690	case CTL_DELAY_IO: {
2691		struct ctl_io_delay_info *delay_info;
2692
2693		delay_info = (struct ctl_io_delay_info *)addr;
2694
2695#ifdef CTL_IO_DELAY
2696		mtx_lock(&softc->ctl_lock);
2697
2698		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2699		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2700			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2701		} else {
2702			lun = softc->ctl_luns[delay_info->lun_id];
2703			mtx_lock(&lun->lun_lock);
2704
2705			delay_info->status = CTL_DELAY_STATUS_OK;
2706
2707			switch (delay_info->delay_type) {
2708			case CTL_DELAY_TYPE_CONT:
2709				break;
2710			case CTL_DELAY_TYPE_ONESHOT:
2711				break;
2712			default:
2713				delay_info->status =
2714					CTL_DELAY_STATUS_INVALID_TYPE;
2715				break;
2716			}
2717
2718			switch (delay_info->delay_loc) {
2719			case CTL_DELAY_LOC_DATAMOVE:
2720				lun->delay_info.datamove_type =
2721					delay_info->delay_type;
2722				lun->delay_info.datamove_delay =
2723					delay_info->delay_secs;
2724				break;
2725			case CTL_DELAY_LOC_DONE:
2726				lun->delay_info.done_type =
2727					delay_info->delay_type;
2728				lun->delay_info.done_delay =
2729					delay_info->delay_secs;
2730				break;
2731			default:
2732				delay_info->status =
2733					CTL_DELAY_STATUS_INVALID_LOC;
2734				break;
2735			}
2736			mtx_unlock(&lun->lun_lock);
2737		}
2738
2739		mtx_unlock(&softc->ctl_lock);
2740#else
2741		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2742#endif /* CTL_IO_DELAY */
2743		break;
2744	}
2745	case CTL_REALSYNC_SET: {
2746		int *syncstate;
2747
2748		syncstate = (int *)addr;
2749
2750		mtx_lock(&softc->ctl_lock);
2751		switch (*syncstate) {
2752		case 0:
2753			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2754			break;
2755		case 1:
2756			softc->flags |= CTL_FLAG_REAL_SYNC;
2757			break;
2758		default:
2759			retval = EINVAL;
2760			break;
2761		}
2762		mtx_unlock(&softc->ctl_lock);
2763		break;
2764	}
2765	case CTL_REALSYNC_GET: {
2766		int *syncstate;
2767
2768		syncstate = (int*)addr;
2769
2770		mtx_lock(&softc->ctl_lock);
2771		if (softc->flags & CTL_FLAG_REAL_SYNC)
2772			*syncstate = 1;
2773		else
2774			*syncstate = 0;
2775		mtx_unlock(&softc->ctl_lock);
2776
2777		break;
2778	}
2779	case CTL_SETSYNC:
2780	case CTL_GETSYNC: {
2781		struct ctl_sync_info *sync_info;
2782
2783		sync_info = (struct ctl_sync_info *)addr;
2784
2785		mtx_lock(&softc->ctl_lock);
2786		lun = softc->ctl_luns[sync_info->lun_id];
2787		if (lun == NULL) {
2788			mtx_unlock(&softc->ctl_lock);
2789			sync_info->status = CTL_GS_SYNC_NO_LUN;
2790			break;
2791		}
2792		/*
2793		 * Get or set the sync interval.  We're not bounds checking
2794		 * in the set case, hopefully the user won't do something
2795		 * silly.
2796		 */
2797		mtx_lock(&lun->lun_lock);
2798		mtx_unlock(&softc->ctl_lock);
2799		if (cmd == CTL_GETSYNC)
2800			sync_info->sync_interval = lun->sync_interval;
2801		else
2802			lun->sync_interval = sync_info->sync_interval;
2803		mtx_unlock(&lun->lun_lock);
2804
2805		sync_info->status = CTL_GS_SYNC_OK;
2806
2807		break;
2808	}
2809	case CTL_GETSTATS: {
2810		struct ctl_stats *stats;
2811		int i;
2812
2813		stats = (struct ctl_stats *)addr;
2814
2815		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2816		     stats->alloc_len) {
2817			stats->status = CTL_SS_NEED_MORE_SPACE;
2818			stats->num_luns = softc->num_luns;
2819			break;
2820		}
2821		/*
2822		 * XXX KDM no locking here.  If the LUN list changes,
2823		 * things can blow up.
2824		 */
2825		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2826		     i++, lun = STAILQ_NEXT(lun, links)) {
2827			retval = copyout(&lun->stats, &stats->lun_stats[i],
2828					 sizeof(lun->stats));
2829			if (retval != 0)
2830				break;
2831		}
2832		stats->num_luns = softc->num_luns;
2833		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2834				 softc->num_luns;
2835		stats->status = CTL_SS_OK;
2836#ifdef CTL_TIME_IO
2837		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2838#else
2839		stats->flags = CTL_STATS_FLAG_NONE;
2840#endif
2841		getnanouptime(&stats->timestamp);
2842		break;
2843	}
2844	case CTL_ERROR_INJECT: {
2845		struct ctl_error_desc *err_desc, *new_err_desc;
2846
2847		err_desc = (struct ctl_error_desc *)addr;
2848
2849		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2850				      M_WAITOK | M_ZERO);
2851		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2852
2853		mtx_lock(&softc->ctl_lock);
2854		lun = softc->ctl_luns[err_desc->lun_id];
2855		if (lun == NULL) {
2856			mtx_unlock(&softc->ctl_lock);
2857			free(new_err_desc, M_CTL);
2858			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2859			       __func__, (uintmax_t)err_desc->lun_id);
2860			retval = EINVAL;
2861			break;
2862		}
2863		mtx_lock(&lun->lun_lock);
2864		mtx_unlock(&softc->ctl_lock);
2865
2866		/*
2867		 * We could do some checking here to verify the validity
2868		 * of the request, but given the complexity of error
2869		 * injection requests, the checking logic would be fairly
2870		 * complex.
2871		 *
2872		 * For now, if the request is invalid, it just won't get
2873		 * executed and might get deleted.
2874		 */
2875		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2876
2877		/*
2878		 * XXX KDM check to make sure the serial number is unique,
2879		 * in case we somehow manage to wrap.  That shouldn't
2880		 * happen for a very long time, but it's the right thing to
2881		 * do.
2882		 */
2883		new_err_desc->serial = lun->error_serial;
2884		err_desc->serial = lun->error_serial;
2885		lun->error_serial++;
2886
2887		mtx_unlock(&lun->lun_lock);
2888		break;
2889	}
2890	case CTL_ERROR_INJECT_DELETE: {
2891		struct ctl_error_desc *delete_desc, *desc, *desc2;
2892		int delete_done;
2893
2894		delete_desc = (struct ctl_error_desc *)addr;
2895		delete_done = 0;
2896
2897		mtx_lock(&softc->ctl_lock);
2898		lun = softc->ctl_luns[delete_desc->lun_id];
2899		if (lun == NULL) {
2900			mtx_unlock(&softc->ctl_lock);
2901			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2902			       __func__, (uintmax_t)delete_desc->lun_id);
2903			retval = EINVAL;
2904			break;
2905		}
2906		mtx_lock(&lun->lun_lock);
2907		mtx_unlock(&softc->ctl_lock);
2908		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2909			if (desc->serial != delete_desc->serial)
2910				continue;
2911
2912			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2913				      links);
2914			free(desc, M_CTL);
2915			delete_done = 1;
2916		}
2917		mtx_unlock(&lun->lun_lock);
2918		if (delete_done == 0) {
2919			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2920			       "error serial %ju on LUN %u\n", __func__,
2921			       delete_desc->serial, delete_desc->lun_id);
2922			retval = EINVAL;
2923			break;
2924		}
2925		break;
2926	}
2927	case CTL_DUMP_STRUCTS: {
2928		int i, j, k;
2929		struct ctl_port *port;
2930		struct ctl_frontend *fe;
2931
2932		mtx_lock(&softc->ctl_lock);
2933		printf("CTL Persistent Reservation information start:\n");
2934		for (i = 0; i < CTL_MAX_LUNS; i++) {
2935			lun = softc->ctl_luns[i];
2936
2937			if ((lun == NULL)
2938			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
2939				continue;
2940
2941			for (j = 0; j < CTL_MAX_PORTS; j++) {
2942				if (lun->pr_keys[j] == NULL)
2943					continue;
2944				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2945					if (lun->pr_keys[j][k] == 0)
2946						continue;
2947					printf("  LUN %d port %d iid %d key "
2948					       "%#jx\n", i, j, k,
2949					       (uintmax_t)lun->pr_keys[j][k]);
2950				}
2951			}
2952		}
2953		printf("CTL Persistent Reservation information end\n");
2954		printf("CTL Ports:\n");
2955		STAILQ_FOREACH(port, &softc->port_list, links) {
2956			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2957			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2958			       port->frontend->name, port->port_type,
2959			       port->physical_port, port->virtual_port,
2960			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2961			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2962				if (port->wwpn_iid[j].in_use == 0 &&
2963				    port->wwpn_iid[j].wwpn == 0 &&
2964				    port->wwpn_iid[j].name == NULL)
2965					continue;
2966
2967				printf("    iid %u use %d WWPN %#jx '%s'\n",
2968				    j, port->wwpn_iid[j].in_use,
2969				    (uintmax_t)port->wwpn_iid[j].wwpn,
2970				    port->wwpn_iid[j].name);
2971			}
2972		}
2973		printf("CTL Port information end\n");
2974		mtx_unlock(&softc->ctl_lock);
2975		/*
2976		 * XXX KDM calling this without a lock.  We'd likely want
2977		 * to drop the lock before calling the frontend's dump
2978		 * routine anyway.
2979		 */
2980		printf("CTL Frontends:\n");
2981		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2982			printf("  Frontend '%s'\n", fe->name);
2983			if (fe->fe_dump != NULL)
2984				fe->fe_dump();
2985		}
2986		printf("CTL Frontend information end\n");
2987		break;
2988	}
2989	case CTL_LUN_REQ: {
2990		struct ctl_lun_req *lun_req;
2991		struct ctl_backend_driver *backend;
2992
2993		lun_req = (struct ctl_lun_req *)addr;
2994
2995		backend = ctl_backend_find(lun_req->backend);
2996		if (backend == NULL) {
2997			lun_req->status = CTL_LUN_ERROR;
2998			snprintf(lun_req->error_str,
2999				 sizeof(lun_req->error_str),
3000				 "Backend \"%s\" not found.",
3001				 lun_req->backend);
3002			break;
3003		}
3004		if (lun_req->num_be_args > 0) {
3005			lun_req->kern_be_args = ctl_copyin_args(
3006				lun_req->num_be_args,
3007				lun_req->be_args,
3008				lun_req->error_str,
3009				sizeof(lun_req->error_str));
3010			if (lun_req->kern_be_args == NULL) {
3011				lun_req->status = CTL_LUN_ERROR;
3012				break;
3013			}
3014		}
3015
3016		retval = backend->ioctl(dev, cmd, addr, flag, td);
3017
3018		if (lun_req->num_be_args > 0) {
3019			ctl_copyout_args(lun_req->num_be_args,
3020				      lun_req->kern_be_args);
3021			ctl_free_args(lun_req->num_be_args,
3022				      lun_req->kern_be_args);
3023		}
3024		break;
3025	}
3026	case CTL_LUN_LIST: {
3027		struct sbuf *sb;
3028		struct ctl_lun_list *list;
3029		struct ctl_option *opt;
3030
3031		list = (struct ctl_lun_list *)addr;
3032
3033		/*
3034		 * Allocate a fixed length sbuf here, based on the length
3035		 * of the user's buffer.  We could allocate an auto-extending
3036		 * buffer, and then tell the user how much larger our
3037		 * amount of data is than his buffer, but that presents
3038		 * some problems:
3039		 *
3040		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3041		 *     we can't hold a lock while calling them with an
3042		 *     auto-extending buffer.
3043 		 *
3044		 * 2.  There is not currently a LUN reference counting
3045		 *     mechanism, outside of outstanding transactions on
3046		 *     the LUN's OOA queue.  So a LUN could go away on us
3047		 *     while we're getting the LUN number, backend-specific
3048		 *     information, etc.  Thus, given the way things
3049		 *     currently work, we need to hold the CTL lock while
3050		 *     grabbing LUN information.
3051		 *
3052		 * So, from the user's standpoint, the best thing to do is
3053		 * allocate what he thinks is a reasonable buffer length,
3054		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3055		 * double the buffer length and try again.  (And repeat
3056		 * that until he succeeds.)
3057		 */
3058		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3059		if (sb == NULL) {
3060			list->status = CTL_LUN_LIST_ERROR;
3061			snprintf(list->error_str, sizeof(list->error_str),
3062				 "Unable to allocate %d bytes for LUN list",
3063				 list->alloc_len);
3064			break;
3065		}
3066
3067		sbuf_printf(sb, "<ctllunlist>\n");
3068
3069		mtx_lock(&softc->ctl_lock);
3070		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3071			mtx_lock(&lun->lun_lock);
3072			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3073					     (uintmax_t)lun->lun);
3074
3075			/*
3076			 * Bail out as soon as we see that we've overfilled
3077			 * the buffer.
3078			 */
3079			if (retval != 0)
3080				break;
3081
3082			retval = sbuf_printf(sb, "\t<backend_type>%s"
3083					     "</backend_type>\n",
3084					     (lun->backend == NULL) ?  "none" :
3085					     lun->backend->name);
3086
3087			if (retval != 0)
3088				break;
3089
3090			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3091					     lun->be_lun->lun_type);
3092
3093			if (retval != 0)
3094				break;
3095
3096			if (lun->backend == NULL) {
3097				retval = sbuf_printf(sb, "</lun>\n");
3098				if (retval != 0)
3099					break;
3100				continue;
3101			}
3102
3103			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3104					     (lun->be_lun->maxlba > 0) ?
3105					     lun->be_lun->maxlba + 1 : 0);
3106
3107			if (retval != 0)
3108				break;
3109
3110			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3111					     lun->be_lun->blocksize);
3112
3113			if (retval != 0)
3114				break;
3115
3116			retval = sbuf_printf(sb, "\t<serial_number>");
3117
3118			if (retval != 0)
3119				break;
3120
3121			retval = ctl_sbuf_printf_esc(sb,
3122			    lun->be_lun->serial_num,
3123			    sizeof(lun->be_lun->serial_num));
3124
3125			if (retval != 0)
3126				break;
3127
3128			retval = sbuf_printf(sb, "</serial_number>\n");
3129
3130			if (retval != 0)
3131				break;
3132
3133			retval = sbuf_printf(sb, "\t<device_id>");
3134
3135			if (retval != 0)
3136				break;
3137
3138			retval = ctl_sbuf_printf_esc(sb,
3139			    lun->be_lun->device_id,
3140			    sizeof(lun->be_lun->device_id));
3141
3142			if (retval != 0)
3143				break;
3144
3145			retval = sbuf_printf(sb, "</device_id>\n");
3146
3147			if (retval != 0)
3148				break;
3149
3150			if (lun->backend->lun_info != NULL) {
3151				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3152				if (retval != 0)
3153					break;
3154			}
3155			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3156				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3157				    opt->name, opt->value, opt->name);
3158				if (retval != 0)
3159					break;
3160			}
3161
3162			retval = sbuf_printf(sb, "</lun>\n");
3163
3164			if (retval != 0)
3165				break;
3166			mtx_unlock(&lun->lun_lock);
3167		}
3168		if (lun != NULL)
3169			mtx_unlock(&lun->lun_lock);
3170		mtx_unlock(&softc->ctl_lock);
3171
3172		if ((retval != 0)
3173		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3174			retval = 0;
3175			sbuf_delete(sb);
3176			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3177			snprintf(list->error_str, sizeof(list->error_str),
3178				 "Out of space, %d bytes is too small",
3179				 list->alloc_len);
3180			break;
3181		}
3182
3183		sbuf_finish(sb);
3184
3185		retval = copyout(sbuf_data(sb), list->lun_xml,
3186				 sbuf_len(sb) + 1);
3187
3188		list->fill_len = sbuf_len(sb) + 1;
3189		list->status = CTL_LUN_LIST_OK;
3190		sbuf_delete(sb);
3191		break;
3192	}
3193	case CTL_ISCSI: {
3194		struct ctl_iscsi *ci;
3195		struct ctl_frontend *fe;
3196
3197		ci = (struct ctl_iscsi *)addr;
3198
3199		fe = ctl_frontend_find("iscsi");
3200		if (fe == NULL) {
3201			ci->status = CTL_ISCSI_ERROR;
3202			snprintf(ci->error_str, sizeof(ci->error_str),
3203			    "Frontend \"iscsi\" not found.");
3204			break;
3205		}
3206
3207		retval = fe->ioctl(dev, cmd, addr, flag, td);
3208		break;
3209	}
3210	case CTL_PORT_REQ: {
3211		struct ctl_req *req;
3212		struct ctl_frontend *fe;
3213
3214		req = (struct ctl_req *)addr;
3215
3216		fe = ctl_frontend_find(req->driver);
3217		if (fe == NULL) {
3218			req->status = CTL_LUN_ERROR;
3219			snprintf(req->error_str, sizeof(req->error_str),
3220			    "Frontend \"%s\" not found.", req->driver);
3221			break;
3222		}
3223		if (req->num_args > 0) {
3224			req->kern_args = ctl_copyin_args(req->num_args,
3225			    req->args, req->error_str, sizeof(req->error_str));
3226			if (req->kern_args == NULL) {
3227				req->status = CTL_LUN_ERROR;
3228				break;
3229			}
3230		}
3231
3232		if (fe->ioctl)
3233			retval = fe->ioctl(dev, cmd, addr, flag, td);
3234		else
3235			retval = ENODEV;
3236
3237		if (req->num_args > 0) {
3238			ctl_copyout_args(req->num_args, req->kern_args);
3239			ctl_free_args(req->num_args, req->kern_args);
3240		}
3241		break;
3242	}
3243	case CTL_PORT_LIST: {
3244		struct sbuf *sb;
3245		struct ctl_port *port;
3246		struct ctl_lun_list *list;
3247		struct ctl_option *opt;
3248		int j;
3249		uint32_t plun;
3250
3251		list = (struct ctl_lun_list *)addr;
3252
3253		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3254		if (sb == NULL) {
3255			list->status = CTL_LUN_LIST_ERROR;
3256			snprintf(list->error_str, sizeof(list->error_str),
3257				 "Unable to allocate %d bytes for LUN list",
3258				 list->alloc_len);
3259			break;
3260		}
3261
3262		sbuf_printf(sb, "<ctlportlist>\n");
3263
3264		mtx_lock(&softc->ctl_lock);
3265		STAILQ_FOREACH(port, &softc->port_list, links) {
3266			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3267					     (uintmax_t)port->targ_port);
3268
3269			/*
3270			 * Bail out as soon as we see that we've overfilled
3271			 * the buffer.
3272			 */
3273			if (retval != 0)
3274				break;
3275
3276			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3277			    "</frontend_type>\n", port->frontend->name);
3278			if (retval != 0)
3279				break;
3280
3281			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3282					     port->port_type);
3283			if (retval != 0)
3284				break;
3285
3286			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3287			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3288			if (retval != 0)
3289				break;
3290
3291			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3292			    port->port_name);
3293			if (retval != 0)
3294				break;
3295
3296			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3297			    port->physical_port);
3298			if (retval != 0)
3299				break;
3300
3301			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3302			    port->virtual_port);
3303			if (retval != 0)
3304				break;
3305
3306			if (port->target_devid != NULL) {
3307				sbuf_printf(sb, "\t<target>");
3308				ctl_id_sbuf(port->target_devid, sb);
3309				sbuf_printf(sb, "</target>\n");
3310			}
3311
3312			if (port->port_devid != NULL) {
3313				sbuf_printf(sb, "\t<port>");
3314				ctl_id_sbuf(port->port_devid, sb);
3315				sbuf_printf(sb, "</port>\n");
3316			}
3317
3318			if (port->port_info != NULL) {
3319				retval = port->port_info(port->onoff_arg, sb);
3320				if (retval != 0)
3321					break;
3322			}
3323			STAILQ_FOREACH(opt, &port->options, links) {
3324				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3325				    opt->name, opt->value, opt->name);
3326				if (retval != 0)
3327					break;
3328			}
3329
3330			if (port->lun_map != NULL) {
3331				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3332				for (j = 0; j < CTL_MAX_LUNS; j++) {
3333					plun = ctl_lun_map_from_port(port, j);
3334					if (plun >= CTL_MAX_LUNS)
3335						continue;
3336					sbuf_printf(sb,
3337					    "\t<lun id=\"%u\">%u</lun>\n",
3338					    j, plun);
3339				}
3340			}
3341
3342			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3343				if (port->wwpn_iid[j].in_use == 0 ||
3344				    (port->wwpn_iid[j].wwpn == 0 &&
3345				     port->wwpn_iid[j].name == NULL))
3346					continue;
3347
3348				if (port->wwpn_iid[j].name != NULL)
3349					retval = sbuf_printf(sb,
3350					    "\t<initiator id=\"%u\">%s</initiator>\n",
3351					    j, port->wwpn_iid[j].name);
3352				else
3353					retval = sbuf_printf(sb,
3354					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3355					    j, port->wwpn_iid[j].wwpn);
3356				if (retval != 0)
3357					break;
3358			}
3359			if (retval != 0)
3360				break;
3361
3362			retval = sbuf_printf(sb, "</targ_port>\n");
3363			if (retval != 0)
3364				break;
3365		}
3366		mtx_unlock(&softc->ctl_lock);
3367
3368		if ((retval != 0)
3369		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3370			retval = 0;
3371			sbuf_delete(sb);
3372			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3373			snprintf(list->error_str, sizeof(list->error_str),
3374				 "Out of space, %d bytes is too small",
3375				 list->alloc_len);
3376			break;
3377		}
3378
3379		sbuf_finish(sb);
3380
3381		retval = copyout(sbuf_data(sb), list->lun_xml,
3382				 sbuf_len(sb) + 1);
3383
3384		list->fill_len = sbuf_len(sb) + 1;
3385		list->status = CTL_LUN_LIST_OK;
3386		sbuf_delete(sb);
3387		break;
3388	}
3389	case CTL_LUN_MAP: {
3390		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3391		struct ctl_port *port;
3392
3393		mtx_lock(&softc->ctl_lock);
3394		if (lm->port < softc->port_min ||
3395		    lm->port >= softc->port_max ||
3396		    (port = softc->ctl_ports[lm->port]) == NULL) {
3397			mtx_unlock(&softc->ctl_lock);
3398			return (ENXIO);
3399		}
3400		if (port->status & CTL_PORT_STATUS_ONLINE) {
3401			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3402				if (ctl_lun_map_to_port(port, lun->lun) >=
3403				    CTL_MAX_LUNS)
3404					continue;
3405				mtx_lock(&lun->lun_lock);
3406				ctl_est_ua_port(lun, lm->port, -1,
3407				    CTL_UA_LUN_CHANGE);
3408				mtx_unlock(&lun->lun_lock);
3409			}
3410		}
3411		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3412		if (lm->plun < CTL_MAX_LUNS) {
3413			if (lm->lun == UINT32_MAX)
3414				retval = ctl_lun_map_unset(port, lm->plun);
3415			else if (lm->lun < CTL_MAX_LUNS &&
3416			    softc->ctl_luns[lm->lun] != NULL)
3417				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3418			else
3419				return (ENXIO);
3420		} else if (lm->plun == UINT32_MAX) {
3421			if (lm->lun == UINT32_MAX)
3422				retval = ctl_lun_map_deinit(port);
3423			else
3424				retval = ctl_lun_map_init(port);
3425		} else
3426			return (ENXIO);
3427		if (port->status & CTL_PORT_STATUS_ONLINE)
3428			ctl_isc_announce_port(port);
3429		break;
3430	}
3431	default: {
3432		/* XXX KDM should we fix this? */
3433#if 0
3434		struct ctl_backend_driver *backend;
3435		unsigned int type;
3436		int found;
3437
3438		found = 0;
3439
3440		/*
3441		 * We encode the backend type as the ioctl type for backend
3442		 * ioctls.  So parse it out here, and then search for a
3443		 * backend of this type.
3444		 */
3445		type = _IOC_TYPE(cmd);
3446
3447		STAILQ_FOREACH(backend, &softc->be_list, links) {
3448			if (backend->type == type) {
3449				found = 1;
3450				break;
3451			}
3452		}
3453		if (found == 0) {
3454			printf("ctl: unknown ioctl command %#lx or backend "
3455			       "%d\n", cmd, type);
3456			retval = EINVAL;
3457			break;
3458		}
3459		retval = backend->ioctl(dev, cmd, addr, flag, td);
3460#endif
3461		retval = ENOTTY;
3462		break;
3463	}
3464	}
3465	return (retval);
3466}
3467
3468uint32_t
3469ctl_get_initindex(struct ctl_nexus *nexus)
3470{
3471	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3472}
3473
3474int
3475ctl_lun_map_init(struct ctl_port *port)
3476{
3477	struct ctl_softc *softc = port->ctl_softc;
3478	struct ctl_lun *lun;
3479	uint32_t i;
3480
3481	if (port->lun_map == NULL)
3482		port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3483		    M_CTL, M_NOWAIT);
3484	if (port->lun_map == NULL)
3485		return (ENOMEM);
3486	for (i = 0; i < CTL_MAX_LUNS; i++)
3487		port->lun_map[i] = UINT32_MAX;
3488	if (port->status & CTL_PORT_STATUS_ONLINE) {
3489		if (port->lun_disable != NULL) {
3490			STAILQ_FOREACH(lun, &softc->lun_list, links)
3491				port->lun_disable(port->targ_lun_arg, lun->lun);
3492		}
3493		ctl_isc_announce_port(port);
3494	}
3495	return (0);
3496}
3497
3498int
3499ctl_lun_map_deinit(struct ctl_port *port)
3500{
3501	struct ctl_softc *softc = port->ctl_softc;
3502	struct ctl_lun *lun;
3503
3504	if (port->lun_map == NULL)
3505		return (0);
3506	free(port->lun_map, M_CTL);
3507	port->lun_map = NULL;
3508	if (port->status & CTL_PORT_STATUS_ONLINE) {
3509		if (port->lun_enable != NULL) {
3510			STAILQ_FOREACH(lun, &softc->lun_list, links)
3511				port->lun_enable(port->targ_lun_arg, lun->lun);
3512		}
3513		ctl_isc_announce_port(port);
3514	}
3515	return (0);
3516}
3517
3518int
3519ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3520{
3521	int status;
3522	uint32_t old;
3523
3524	if (port->lun_map == NULL) {
3525		status = ctl_lun_map_init(port);
3526		if (status != 0)
3527			return (status);
3528	}
3529	old = port->lun_map[plun];
3530	port->lun_map[plun] = glun;
3531	if ((port->status & CTL_PORT_STATUS_ONLINE) && old >= CTL_MAX_LUNS) {
3532		if (port->lun_enable != NULL)
3533			port->lun_enable(port->targ_lun_arg, plun);
3534		ctl_isc_announce_port(port);
3535	}
3536	return (0);
3537}
3538
3539int
3540ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3541{
3542	uint32_t old;
3543
3544	if (port->lun_map == NULL)
3545		return (0);
3546	old = port->lun_map[plun];
3547	port->lun_map[plun] = UINT32_MAX;
3548	if ((port->status & CTL_PORT_STATUS_ONLINE) && old < CTL_MAX_LUNS) {
3549		if (port->lun_disable != NULL)
3550			port->lun_disable(port->targ_lun_arg, plun);
3551		ctl_isc_announce_port(port);
3552	}
3553	return (0);
3554}
3555
3556uint32_t
3557ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3558{
3559
3560	if (port == NULL)
3561		return (UINT32_MAX);
3562	if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3563		return (lun_id);
3564	return (port->lun_map[lun_id]);
3565}
3566
3567uint32_t
3568ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3569{
3570	uint32_t i;
3571
3572	if (port == NULL)
3573		return (UINT32_MAX);
3574	if (port->lun_map == NULL)
3575		return (lun_id);
3576	for (i = 0; i < CTL_MAX_LUNS; i++) {
3577		if (port->lun_map[i] == lun_id)
3578			return (i);
3579	}
3580	return (UINT32_MAX);
3581}
3582
3583static struct ctl_port *
3584ctl_io_port(struct ctl_io_hdr *io_hdr)
3585{
3586
3587	return (control_softc->ctl_ports[io_hdr->nexus.targ_port]);
3588}
3589
3590int
3591ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3592{
3593	int i;
3594
3595	for (i = first; i < last; i++) {
3596		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3597			return (i);
3598	}
3599	return (-1);
3600}
3601
3602int
3603ctl_set_mask(uint32_t *mask, uint32_t bit)
3604{
3605	uint32_t chunk, piece;
3606
3607	chunk = bit >> 5;
3608	piece = bit % (sizeof(uint32_t) * 8);
3609
3610	if ((mask[chunk] & (1 << piece)) != 0)
3611		return (-1);
3612	else
3613		mask[chunk] |= (1 << piece);
3614
3615	return (0);
3616}
3617
3618int
3619ctl_clear_mask(uint32_t *mask, uint32_t bit)
3620{
3621	uint32_t chunk, piece;
3622
3623	chunk = bit >> 5;
3624	piece = bit % (sizeof(uint32_t) * 8);
3625
3626	if ((mask[chunk] & (1 << piece)) == 0)
3627		return (-1);
3628	else
3629		mask[chunk] &= ~(1 << piece);
3630
3631	return (0);
3632}
3633
3634int
3635ctl_is_set(uint32_t *mask, uint32_t bit)
3636{
3637	uint32_t chunk, piece;
3638
3639	chunk = bit >> 5;
3640	piece = bit % (sizeof(uint32_t) * 8);
3641
3642	if ((mask[chunk] & (1 << piece)) == 0)
3643		return (0);
3644	else
3645		return (1);
3646}
3647
3648static uint64_t
3649ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3650{
3651	uint64_t *t;
3652
3653	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3654	if (t == NULL)
3655		return (0);
3656	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3657}
3658
3659static void
3660ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3661{
3662	uint64_t *t;
3663
3664	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3665	if (t == NULL)
3666		return;
3667	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3668}
3669
3670static void
3671ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3672{
3673	uint64_t *p;
3674	u_int i;
3675
3676	i = residx/CTL_MAX_INIT_PER_PORT;
3677	if (lun->pr_keys[i] != NULL)
3678		return;
3679	mtx_unlock(&lun->lun_lock);
3680	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3681	    M_WAITOK | M_ZERO);
3682	mtx_lock(&lun->lun_lock);
3683	if (lun->pr_keys[i] == NULL)
3684		lun->pr_keys[i] = p;
3685	else
3686		free(p, M_CTL);
3687}
3688
3689static void
3690ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3691{
3692	uint64_t *t;
3693
3694	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3695	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3696	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3697}
3698
3699/*
3700 * ctl_softc, pool_name, total_ctl_io are passed in.
3701 * npool is passed out.
3702 */
3703int
3704ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3705		uint32_t total_ctl_io, void **npool)
3706{
3707#ifdef IO_POOLS
3708	struct ctl_io_pool *pool;
3709
3710	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3711					    M_NOWAIT | M_ZERO);
3712	if (pool == NULL)
3713		return (ENOMEM);
3714
3715	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3716	pool->ctl_softc = ctl_softc;
3717	pool->zone = uma_zsecond_create(pool->name, NULL,
3718	    NULL, NULL, NULL, ctl_softc->io_zone);
3719	/* uma_prealloc(pool->zone, total_ctl_io); */
3720
3721	*npool = pool;
3722#else
3723	*npool = ctl_softc->io_zone;
3724#endif
3725	return (0);
3726}
3727
3728void
3729ctl_pool_free(struct ctl_io_pool *pool)
3730{
3731
3732	if (pool == NULL)
3733		return;
3734
3735#ifdef IO_POOLS
3736	uma_zdestroy(pool->zone);
3737	free(pool, M_CTL);
3738#endif
3739}
3740
3741union ctl_io *
3742ctl_alloc_io(void *pool_ref)
3743{
3744	union ctl_io *io;
3745#ifdef IO_POOLS
3746	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3747
3748	io = uma_zalloc(pool->zone, M_WAITOK);
3749#else
3750	io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3751#endif
3752	if (io != NULL)
3753		io->io_hdr.pool = pool_ref;
3754	return (io);
3755}
3756
3757union ctl_io *
3758ctl_alloc_io_nowait(void *pool_ref)
3759{
3760	union ctl_io *io;
3761#ifdef IO_POOLS
3762	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3763
3764	io = uma_zalloc(pool->zone, M_NOWAIT);
3765#else
3766	io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3767#endif
3768	if (io != NULL)
3769		io->io_hdr.pool = pool_ref;
3770	return (io);
3771}
3772
3773void
3774ctl_free_io(union ctl_io *io)
3775{
3776#ifdef IO_POOLS
3777	struct ctl_io_pool *pool;
3778#endif
3779
3780	if (io == NULL)
3781		return;
3782
3783#ifdef IO_POOLS
3784	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3785	uma_zfree(pool->zone, io);
3786#else
3787	uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3788#endif
3789}
3790
3791void
3792ctl_zero_io(union ctl_io *io)
3793{
3794	void *pool_ref;
3795
3796	if (io == NULL)
3797		return;
3798
3799	/*
3800	 * May need to preserve linked list pointers at some point too.
3801	 */
3802	pool_ref = io->io_hdr.pool;
3803	memset(io, 0, sizeof(*io));
3804	io->io_hdr.pool = pool_ref;
3805}
3806
3807/*
3808 * This routine is currently used for internal copies of ctl_ios that need
3809 * to persist for some reason after we've already returned status to the
3810 * FETD.  (Thus the flag set.)
3811 *
3812 * XXX XXX
3813 * Note that this makes a blind copy of all fields in the ctl_io, except
3814 * for the pool reference.  This includes any memory that has been
3815 * allocated!  That memory will no longer be valid after done has been
3816 * called, so this would be VERY DANGEROUS for command that actually does
3817 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3818 * start and stop commands, which don't transfer any data, so this is not a
3819 * problem.  If it is used for anything else, the caller would also need to
3820 * allocate data buffer space and this routine would need to be modified to
3821 * copy the data buffer(s) as well.
3822 */
3823void
3824ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3825{
3826	void *pool_ref;
3827
3828	if ((src == NULL)
3829	 || (dest == NULL))
3830		return;
3831
3832	/*
3833	 * May need to preserve linked list pointers at some point too.
3834	 */
3835	pool_ref = dest->io_hdr.pool;
3836
3837	memcpy(dest, src, MIN(sizeof(*src), sizeof(*dest)));
3838
3839	dest->io_hdr.pool = pool_ref;
3840	/*
3841	 * We need to know that this is an internal copy, and doesn't need
3842	 * to get passed back to the FETD that allocated it.
3843	 */
3844	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3845}
3846
3847int
3848ctl_expand_number(const char *buf, uint64_t *num)
3849{
3850	char *endptr;
3851	uint64_t number;
3852	unsigned shift;
3853
3854	number = strtoq(buf, &endptr, 0);
3855
3856	switch (tolower((unsigned char)*endptr)) {
3857	case 'e':
3858		shift = 60;
3859		break;
3860	case 'p':
3861		shift = 50;
3862		break;
3863	case 't':
3864		shift = 40;
3865		break;
3866	case 'g':
3867		shift = 30;
3868		break;
3869	case 'm':
3870		shift = 20;
3871		break;
3872	case 'k':
3873		shift = 10;
3874		break;
3875	case 'b':
3876	case '\0': /* No unit. */
3877		*num = number;
3878		return (0);
3879	default:
3880		/* Unrecognized unit. */
3881		return (-1);
3882	}
3883
3884	if ((number << shift) >> shift != number) {
3885		/* Overflow */
3886		return (-1);
3887	}
3888	*num = number << shift;
3889	return (0);
3890}
3891
3892
3893/*
3894 * This routine could be used in the future to load default and/or saved
3895 * mode page parameters for a particuar lun.
3896 */
3897static int
3898ctl_init_page_index(struct ctl_lun *lun)
3899{
3900	int i;
3901	struct ctl_page_index *page_index;
3902	const char *value;
3903	uint64_t ival;
3904
3905	memcpy(&lun->mode_pages.index, page_index_template,
3906	       sizeof(page_index_template));
3907
3908	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3909
3910		page_index = &lun->mode_pages.index[i];
3911		/*
3912		 * If this is a disk-only mode page, there's no point in
3913		 * setting it up.  For some pages, we have to have some
3914		 * basic information about the disk in order to calculate the
3915		 * mode page data.
3916		 */
3917		if ((lun->be_lun->lun_type != T_DIRECT)
3918		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3919			continue;
3920
3921		switch (page_index->page_code & SMPH_PC_MASK) {
3922		case SMS_RW_ERROR_RECOVERY_PAGE: {
3923			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3924				panic("subpage is incorrect!");
3925			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3926			       &rw_er_page_default,
3927			       sizeof(rw_er_page_default));
3928			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3929			       &rw_er_page_changeable,
3930			       sizeof(rw_er_page_changeable));
3931			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3932			       &rw_er_page_default,
3933			       sizeof(rw_er_page_default));
3934			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3935			       &rw_er_page_default,
3936			       sizeof(rw_er_page_default));
3937			page_index->page_data =
3938				(uint8_t *)lun->mode_pages.rw_er_page;
3939			break;
3940		}
3941		case SMS_FORMAT_DEVICE_PAGE: {
3942			struct scsi_format_page *format_page;
3943
3944			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3945				panic("subpage is incorrect!");
3946
3947			/*
3948			 * Sectors per track are set above.  Bytes per
3949			 * sector need to be set here on a per-LUN basis.
3950			 */
3951			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3952			       &format_page_default,
3953			       sizeof(format_page_default));
3954			memcpy(&lun->mode_pages.format_page[
3955			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
3956			       sizeof(format_page_changeable));
3957			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3958			       &format_page_default,
3959			       sizeof(format_page_default));
3960			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3961			       &format_page_default,
3962			       sizeof(format_page_default));
3963
3964			format_page = &lun->mode_pages.format_page[
3965				CTL_PAGE_CURRENT];
3966			scsi_ulto2b(lun->be_lun->blocksize,
3967				    format_page->bytes_per_sector);
3968
3969			format_page = &lun->mode_pages.format_page[
3970				CTL_PAGE_DEFAULT];
3971			scsi_ulto2b(lun->be_lun->blocksize,
3972				    format_page->bytes_per_sector);
3973
3974			format_page = &lun->mode_pages.format_page[
3975				CTL_PAGE_SAVED];
3976			scsi_ulto2b(lun->be_lun->blocksize,
3977				    format_page->bytes_per_sector);
3978
3979			page_index->page_data =
3980				(uint8_t *)lun->mode_pages.format_page;
3981			break;
3982		}
3983		case SMS_RIGID_DISK_PAGE: {
3984			struct scsi_rigid_disk_page *rigid_disk_page;
3985			uint32_t sectors_per_cylinder;
3986			uint64_t cylinders;
3987#ifndef	__XSCALE__
3988			int shift;
3989#endif /* !__XSCALE__ */
3990
3991			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3992				panic("invalid subpage value %d",
3993				      page_index->subpage);
3994
3995			/*
3996			 * Rotation rate and sectors per track are set
3997			 * above.  We calculate the cylinders here based on
3998			 * capacity.  Due to the number of heads and
3999			 * sectors per track we're using, smaller arrays
4000			 * may turn out to have 0 cylinders.  Linux and
4001			 * FreeBSD don't pay attention to these mode pages
4002			 * to figure out capacity, but Solaris does.  It
4003			 * seems to deal with 0 cylinders just fine, and
4004			 * works out a fake geometry based on the capacity.
4005			 */
4006			memcpy(&lun->mode_pages.rigid_disk_page[
4007			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4008			       sizeof(rigid_disk_page_default));
4009			memcpy(&lun->mode_pages.rigid_disk_page[
4010			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4011			       sizeof(rigid_disk_page_changeable));
4012
4013			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4014				CTL_DEFAULT_HEADS;
4015
4016			/*
4017			 * The divide method here will be more accurate,
4018			 * probably, but results in floating point being
4019			 * used in the kernel on i386 (__udivdi3()).  On the
4020			 * XScale, though, __udivdi3() is implemented in
4021			 * software.
4022			 *
4023			 * The shift method for cylinder calculation is
4024			 * accurate if sectors_per_cylinder is a power of
4025			 * 2.  Otherwise it might be slightly off -- you
4026			 * might have a bit of a truncation problem.
4027			 */
4028#ifdef	__XSCALE__
4029			cylinders = (lun->be_lun->maxlba + 1) /
4030				sectors_per_cylinder;
4031#else
4032			for (shift = 31; shift > 0; shift--) {
4033				if (sectors_per_cylinder & (1 << shift))
4034					break;
4035			}
4036			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4037#endif
4038
4039			/*
4040			 * We've basically got 3 bytes, or 24 bits for the
4041			 * cylinder size in the mode page.  If we're over,
4042			 * just round down to 2^24.
4043			 */
4044			if (cylinders > 0xffffff)
4045				cylinders = 0xffffff;
4046
4047			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4048				CTL_PAGE_DEFAULT];
4049			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4050
4051			if ((value = ctl_get_opt(&lun->be_lun->options,
4052			    "rpm")) != NULL) {
4053				scsi_ulto2b(strtol(value, NULL, 0),
4054				     rigid_disk_page->rotation_rate);
4055			}
4056
4057			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4058			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4059			       sizeof(rigid_disk_page_default));
4060			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4061			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4062			       sizeof(rigid_disk_page_default));
4063
4064			page_index->page_data =
4065				(uint8_t *)lun->mode_pages.rigid_disk_page;
4066			break;
4067		}
4068		case SMS_CACHING_PAGE: {
4069			struct scsi_caching_page *caching_page;
4070
4071			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4072				panic("invalid subpage value %d",
4073				      page_index->subpage);
4074			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4075			       &caching_page_default,
4076			       sizeof(caching_page_default));
4077			memcpy(&lun->mode_pages.caching_page[
4078			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4079			       sizeof(caching_page_changeable));
4080			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4081			       &caching_page_default,
4082			       sizeof(caching_page_default));
4083			caching_page = &lun->mode_pages.caching_page[
4084			    CTL_PAGE_SAVED];
4085			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4086			if (value != NULL && strcmp(value, "off") == 0)
4087				caching_page->flags1 &= ~SCP_WCE;
4088			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4089			if (value != NULL && strcmp(value, "off") == 0)
4090				caching_page->flags1 |= SCP_RCD;
4091			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4092			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4093			       sizeof(caching_page_default));
4094			page_index->page_data =
4095				(uint8_t *)lun->mode_pages.caching_page;
4096			break;
4097		}
4098		case SMS_CONTROL_MODE_PAGE: {
4099			switch (page_index->subpage) {
4100			case SMS_SUBPAGE_PAGE_0: {
4101				struct scsi_control_page *control_page;
4102
4103				memcpy(&lun->mode_pages.control_page[
4104				    CTL_PAGE_DEFAULT],
4105				       &control_page_default,
4106				       sizeof(control_page_default));
4107				memcpy(&lun->mode_pages.control_page[
4108				    CTL_PAGE_CHANGEABLE],
4109				       &control_page_changeable,
4110				       sizeof(control_page_changeable));
4111				memcpy(&lun->mode_pages.control_page[
4112				    CTL_PAGE_SAVED],
4113				       &control_page_default,
4114				       sizeof(control_page_default));
4115				control_page = &lun->mode_pages.control_page[
4116				    CTL_PAGE_SAVED];
4117				value = ctl_get_opt(&lun->be_lun->options,
4118				    "reordering");
4119				if (value != NULL &&
4120				    strcmp(value, "unrestricted") == 0) {
4121					control_page->queue_flags &=
4122					    ~SCP_QUEUE_ALG_MASK;
4123					control_page->queue_flags |=
4124					    SCP_QUEUE_ALG_UNRESTRICTED;
4125				}
4126				memcpy(&lun->mode_pages.control_page[
4127				    CTL_PAGE_CURRENT],
4128				       &lun->mode_pages.control_page[
4129				    CTL_PAGE_SAVED],
4130				       sizeof(control_page_default));
4131				page_index->page_data =
4132				    (uint8_t *)lun->mode_pages.control_page;
4133				break;
4134			}
4135			case 0x01:
4136				memcpy(&lun->mode_pages.control_ext_page[
4137				    CTL_PAGE_DEFAULT],
4138				       &control_ext_page_default,
4139				       sizeof(control_ext_page_default));
4140				memcpy(&lun->mode_pages.control_ext_page[
4141				    CTL_PAGE_CHANGEABLE],
4142				       &control_ext_page_changeable,
4143				       sizeof(control_ext_page_changeable));
4144				memcpy(&lun->mode_pages.control_ext_page[
4145				    CTL_PAGE_SAVED],
4146				       &control_ext_page_default,
4147				       sizeof(control_ext_page_default));
4148				memcpy(&lun->mode_pages.control_ext_page[
4149				    CTL_PAGE_CURRENT],
4150				       &lun->mode_pages.control_ext_page[
4151				    CTL_PAGE_SAVED],
4152				       sizeof(control_ext_page_default));
4153				page_index->page_data =
4154				    (uint8_t *)lun->mode_pages.control_ext_page;
4155				break;
4156			}
4157			break;
4158		}
4159		case SMS_INFO_EXCEPTIONS_PAGE: {
4160			switch (page_index->subpage) {
4161			case SMS_SUBPAGE_PAGE_0:
4162				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4163				       &ie_page_default,
4164				       sizeof(ie_page_default));
4165				memcpy(&lun->mode_pages.ie_page[
4166				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4167				       sizeof(ie_page_changeable));
4168				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4169				       &ie_page_default,
4170				       sizeof(ie_page_default));
4171				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4172				       &ie_page_default,
4173				       sizeof(ie_page_default));
4174				page_index->page_data =
4175					(uint8_t *)lun->mode_pages.ie_page;
4176				break;
4177			case 0x02: {
4178				struct ctl_logical_block_provisioning_page *page;
4179
4180				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4181				       &lbp_page_default,
4182				       sizeof(lbp_page_default));
4183				memcpy(&lun->mode_pages.lbp_page[
4184				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4185				       sizeof(lbp_page_changeable));
4186				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4187				       &lbp_page_default,
4188				       sizeof(lbp_page_default));
4189				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4190				value = ctl_get_opt(&lun->be_lun->options,
4191				    "avail-threshold");
4192				if (value != NULL &&
4193				    ctl_expand_number(value, &ival) == 0) {
4194					page->descr[0].flags |= SLBPPD_ENABLED |
4195					    SLBPPD_ARMING_DEC;
4196					if (lun->be_lun->blocksize)
4197						ival /= lun->be_lun->blocksize;
4198					else
4199						ival /= 512;
4200					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4201					    page->descr[0].count);
4202				}
4203				value = ctl_get_opt(&lun->be_lun->options,
4204				    "used-threshold");
4205				if (value != NULL &&
4206				    ctl_expand_number(value, &ival) == 0) {
4207					page->descr[1].flags |= SLBPPD_ENABLED |
4208					    SLBPPD_ARMING_INC;
4209					if (lun->be_lun->blocksize)
4210						ival /= lun->be_lun->blocksize;
4211					else
4212						ival /= 512;
4213					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4214					    page->descr[1].count);
4215				}
4216				value = ctl_get_opt(&lun->be_lun->options,
4217				    "pool-avail-threshold");
4218				if (value != NULL &&
4219				    ctl_expand_number(value, &ival) == 0) {
4220					page->descr[2].flags |= SLBPPD_ENABLED |
4221					    SLBPPD_ARMING_DEC;
4222					if (lun->be_lun->blocksize)
4223						ival /= lun->be_lun->blocksize;
4224					else
4225						ival /= 512;
4226					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4227					    page->descr[2].count);
4228				}
4229				value = ctl_get_opt(&lun->be_lun->options,
4230				    "pool-used-threshold");
4231				if (value != NULL &&
4232				    ctl_expand_number(value, &ival) == 0) {
4233					page->descr[3].flags |= SLBPPD_ENABLED |
4234					    SLBPPD_ARMING_INC;
4235					if (lun->be_lun->blocksize)
4236						ival /= lun->be_lun->blocksize;
4237					else
4238						ival /= 512;
4239					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4240					    page->descr[3].count);
4241				}
4242				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4243				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4244				       sizeof(lbp_page_default));
4245				page_index->page_data =
4246					(uint8_t *)lun->mode_pages.lbp_page;
4247			}}
4248			break;
4249		}
4250		case SMS_VENDOR_SPECIFIC_PAGE:{
4251			switch (page_index->subpage) {
4252			case DBGCNF_SUBPAGE_CODE: {
4253				struct copan_debugconf_subpage *current_page,
4254							       *saved_page;
4255
4256				memcpy(&lun->mode_pages.debugconf_subpage[
4257				       CTL_PAGE_CURRENT],
4258				       &debugconf_page_default,
4259				       sizeof(debugconf_page_default));
4260				memcpy(&lun->mode_pages.debugconf_subpage[
4261				       CTL_PAGE_CHANGEABLE],
4262				       &debugconf_page_changeable,
4263				       sizeof(debugconf_page_changeable));
4264				memcpy(&lun->mode_pages.debugconf_subpage[
4265				       CTL_PAGE_DEFAULT],
4266				       &debugconf_page_default,
4267				       sizeof(debugconf_page_default));
4268				memcpy(&lun->mode_pages.debugconf_subpage[
4269				       CTL_PAGE_SAVED],
4270				       &debugconf_page_default,
4271				       sizeof(debugconf_page_default));
4272				page_index->page_data =
4273					(uint8_t *)lun->mode_pages.debugconf_subpage;
4274
4275				current_page = (struct copan_debugconf_subpage *)
4276					(page_index->page_data +
4277					 (page_index->page_len *
4278					  CTL_PAGE_CURRENT));
4279				saved_page = (struct copan_debugconf_subpage *)
4280					(page_index->page_data +
4281					 (page_index->page_len *
4282					  CTL_PAGE_SAVED));
4283				break;
4284			}
4285			default:
4286				panic("invalid subpage value %d",
4287				      page_index->subpage);
4288				break;
4289			}
4290   			break;
4291		}
4292		default:
4293			panic("invalid page value %d",
4294			      page_index->page_code & SMPH_PC_MASK);
4295			break;
4296    	}
4297	}
4298
4299	return (CTL_RETVAL_COMPLETE);
4300}
4301
4302static int
4303ctl_init_log_page_index(struct ctl_lun *lun)
4304{
4305	struct ctl_page_index *page_index;
4306	int i, j, k, prev;
4307
4308	memcpy(&lun->log_pages.index, log_page_index_template,
4309	       sizeof(log_page_index_template));
4310
4311	prev = -1;
4312	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4313
4314		page_index = &lun->log_pages.index[i];
4315		/*
4316		 * If this is a disk-only mode page, there's no point in
4317		 * setting it up.  For some pages, we have to have some
4318		 * basic information about the disk in order to calculate the
4319		 * mode page data.
4320		 */
4321		if ((lun->be_lun->lun_type != T_DIRECT)
4322		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4323			continue;
4324
4325		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4326		     lun->backend->lun_attr == NULL)
4327			continue;
4328
4329		if (page_index->page_code != prev) {
4330			lun->log_pages.pages_page[j] = page_index->page_code;
4331			prev = page_index->page_code;
4332			j++;
4333		}
4334		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4335		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4336		k++;
4337	}
4338	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4339	lun->log_pages.index[0].page_len = j;
4340	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4341	lun->log_pages.index[1].page_len = k * 2;
4342	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4343	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4344	lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4345	lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4346
4347	return (CTL_RETVAL_COMPLETE);
4348}
4349
4350static int
4351hex2bin(const char *str, uint8_t *buf, int buf_size)
4352{
4353	int i;
4354	u_char c;
4355
4356	memset(buf, 0, buf_size);
4357	while (isspace(str[0]))
4358		str++;
4359	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4360		str += 2;
4361	buf_size *= 2;
4362	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4363		c = str[i];
4364		if (isdigit(c))
4365			c -= '0';
4366		else if (isalpha(c))
4367			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4368		else
4369			break;
4370		if (c >= 16)
4371			break;
4372		if ((i & 1) == 0)
4373			buf[i / 2] |= (c << 4);
4374		else
4375			buf[i / 2] |= c;
4376	}
4377	return ((i + 1) / 2);
4378}
4379
4380/*
4381 * LUN allocation.
4382 *
4383 * Requirements:
4384 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4385 *   wants us to allocate the LUN and he can block.
4386 * - ctl_softc is always set
4387 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4388 *
4389 * Returns 0 for success, non-zero (errno) for failure.
4390 */
4391static int
4392ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4393	      struct ctl_be_lun *const be_lun)
4394{
4395	struct ctl_lun *nlun, *lun;
4396	struct scsi_vpd_id_descriptor *desc;
4397	struct scsi_vpd_id_t10 *t10id;
4398	const char *eui, *naa, *scsiname, *vendor;
4399	int lun_number, i, lun_malloced;
4400	int devidlen, idlen1, idlen2 = 0, len;
4401
4402	if (be_lun == NULL)
4403		return (EINVAL);
4404
4405	/*
4406	 * We currently only support Direct Access or Processor LUN types.
4407	 */
4408	switch (be_lun->lun_type) {
4409	case T_DIRECT:
4410		break;
4411	case T_PROCESSOR:
4412		break;
4413	case T_SEQUENTIAL:
4414	case T_CHANGER:
4415	default:
4416		be_lun->lun_config_status(be_lun->be_lun,
4417					  CTL_LUN_CONFIG_FAILURE);
4418		break;
4419	}
4420	if (ctl_lun == NULL) {
4421		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4422		lun_malloced = 1;
4423	} else {
4424		lun_malloced = 0;
4425		lun = ctl_lun;
4426	}
4427
4428	memset(lun, 0, sizeof(*lun));
4429	if (lun_malloced)
4430		lun->flags = CTL_LUN_MALLOCED;
4431
4432	/* Generate LUN ID. */
4433	devidlen = max(CTL_DEVID_MIN_LEN,
4434	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4435	idlen1 = sizeof(*t10id) + devidlen;
4436	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4437	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4438	if (scsiname != NULL) {
4439		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4440		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4441	}
4442	eui = ctl_get_opt(&be_lun->options, "eui");
4443	if (eui != NULL) {
4444		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4445	}
4446	naa = ctl_get_opt(&be_lun->options, "naa");
4447	if (naa != NULL) {
4448		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4449	}
4450	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4451	    M_CTL, M_WAITOK | M_ZERO);
4452	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4453	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4454	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4455	desc->length = idlen1;
4456	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4457	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4458	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4459		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4460	} else {
4461		strncpy(t10id->vendor, vendor,
4462		    min(sizeof(t10id->vendor), strlen(vendor)));
4463	}
4464	strncpy((char *)t10id->vendor_spec_id,
4465	    (char *)be_lun->device_id, devidlen);
4466	if (scsiname != NULL) {
4467		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4468		    desc->length);
4469		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4470		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4471		    SVPD_ID_TYPE_SCSI_NAME;
4472		desc->length = idlen2;
4473		strlcpy(desc->identifier, scsiname, idlen2);
4474	}
4475	if (eui != NULL) {
4476		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4477		    desc->length);
4478		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4479		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4480		    SVPD_ID_TYPE_EUI64;
4481		desc->length = hex2bin(eui, desc->identifier, 16);
4482		desc->length = desc->length > 12 ? 16 :
4483		    (desc->length > 8 ? 12 : 8);
4484		len -= 16 - desc->length;
4485	}
4486	if (naa != NULL) {
4487		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4488		    desc->length);
4489		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4490		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4491		    SVPD_ID_TYPE_NAA;
4492		desc->length = hex2bin(naa, desc->identifier, 16);
4493		desc->length = desc->length > 8 ? 16 : 8;
4494		len -= 16 - desc->length;
4495	}
4496	lun->lun_devid->len = len;
4497
4498	mtx_lock(&ctl_softc->ctl_lock);
4499	/*
4500	 * See if the caller requested a particular LUN number.  If so, see
4501	 * if it is available.  Otherwise, allocate the first available LUN.
4502	 */
4503	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4504		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4505		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4506			mtx_unlock(&ctl_softc->ctl_lock);
4507			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4508				printf("ctl: requested LUN ID %d is higher "
4509				       "than CTL_MAX_LUNS - 1 (%d)\n",
4510				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4511			} else {
4512				/*
4513				 * XXX KDM return an error, or just assign
4514				 * another LUN ID in this case??
4515				 */
4516				printf("ctl: requested LUN ID %d is already "
4517				       "in use\n", be_lun->req_lun_id);
4518			}
4519			if (lun->flags & CTL_LUN_MALLOCED)
4520				free(lun, M_CTL);
4521			be_lun->lun_config_status(be_lun->be_lun,
4522						  CTL_LUN_CONFIG_FAILURE);
4523			return (ENOSPC);
4524		}
4525		lun_number = be_lun->req_lun_id;
4526	} else {
4527		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4528		if (lun_number == -1) {
4529			mtx_unlock(&ctl_softc->ctl_lock);
4530			printf("ctl: can't allocate LUN, out of LUNs\n");
4531			if (lun->flags & CTL_LUN_MALLOCED)
4532				free(lun, M_CTL);
4533			be_lun->lun_config_status(be_lun->be_lun,
4534						  CTL_LUN_CONFIG_FAILURE);
4535			return (ENOSPC);
4536		}
4537	}
4538	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4539
4540	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4541	lun->lun = lun_number;
4542	lun->be_lun = be_lun;
4543	/*
4544	 * The processor LUN is always enabled.  Disk LUNs come on line
4545	 * disabled, and must be enabled by the backend.
4546	 */
4547	lun->flags |= CTL_LUN_DISABLED;
4548	lun->backend = be_lun->be;
4549	be_lun->ctl_lun = lun;
4550	be_lun->lun_id = lun_number;
4551	atomic_add_int(&be_lun->be->num_luns, 1);
4552	if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4553		lun->flags |= CTL_LUN_OFFLINE;
4554
4555	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4556		lun->flags |= CTL_LUN_STOPPED;
4557
4558	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4559		lun->flags |= CTL_LUN_INOPERABLE;
4560
4561	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4562		lun->flags |= CTL_LUN_PRIMARY_SC;
4563
4564	lun->ctl_softc = ctl_softc;
4565#ifdef CTL_TIME_IO
4566	lun->last_busy = getsbinuptime();
4567#endif
4568	TAILQ_INIT(&lun->ooa_queue);
4569	TAILQ_INIT(&lun->blocked_queue);
4570	STAILQ_INIT(&lun->error_list);
4571	ctl_tpc_lun_init(lun);
4572
4573	/*
4574	 * Initialize the mode and log page index.
4575	 */
4576	ctl_init_page_index(lun);
4577	ctl_init_log_page_index(lun);
4578
4579	/*
4580	 * Now, before we insert this lun on the lun list, set the lun
4581	 * inventory changed UA for all other luns.
4582	 */
4583	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4584		mtx_lock(&nlun->lun_lock);
4585		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4586		mtx_unlock(&nlun->lun_lock);
4587	}
4588
4589	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4590
4591	ctl_softc->ctl_luns[lun_number] = lun;
4592
4593	ctl_softc->num_luns++;
4594
4595	/* Setup statistics gathering */
4596	lun->stats.device_type = be_lun->lun_type;
4597	lun->stats.lun_number = lun_number;
4598	if (lun->stats.device_type == T_DIRECT)
4599		lun->stats.blocksize = be_lun->blocksize;
4600	else
4601		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4602	for (i = 0;i < CTL_MAX_PORTS;i++)
4603		lun->stats.ports[i].targ_port = i;
4604
4605	mtx_unlock(&ctl_softc->ctl_lock);
4606
4607	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4608	return (0);
4609}
4610
4611/*
4612 * Delete a LUN.
4613 * Assumptions:
4614 * - LUN has already been marked invalid and any pending I/O has been taken
4615 *   care of.
4616 */
4617static int
4618ctl_free_lun(struct ctl_lun *lun)
4619{
4620	struct ctl_softc *softc;
4621	struct ctl_lun *nlun;
4622	int i;
4623
4624	softc = lun->ctl_softc;
4625
4626	mtx_assert(&softc->ctl_lock, MA_OWNED);
4627
4628	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4629
4630	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4631
4632	softc->ctl_luns[lun->lun] = NULL;
4633
4634	if (!TAILQ_EMPTY(&lun->ooa_queue))
4635		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4636
4637	softc->num_luns--;
4638
4639	/*
4640	 * Tell the backend to free resources, if this LUN has a backend.
4641	 */
4642	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4643	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4644
4645	ctl_tpc_lun_shutdown(lun);
4646	mtx_destroy(&lun->lun_lock);
4647	free(lun->lun_devid, M_CTL);
4648	for (i = 0; i < CTL_MAX_PORTS; i++)
4649		free(lun->pending_ua[i], M_CTL);
4650	for (i = 0; i < CTL_MAX_PORTS; i++)
4651		free(lun->pr_keys[i], M_CTL);
4652	free(lun->write_buffer, M_CTL);
4653	if (lun->flags & CTL_LUN_MALLOCED)
4654		free(lun, M_CTL);
4655
4656	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4657		mtx_lock(&nlun->lun_lock);
4658		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4659		mtx_unlock(&nlun->lun_lock);
4660	}
4661
4662	return (0);
4663}
4664
4665static void
4666ctl_create_lun(struct ctl_be_lun *be_lun)
4667{
4668
4669	/*
4670	 * ctl_alloc_lun() should handle all potential failure cases.
4671	 */
4672	ctl_alloc_lun(control_softc, NULL, be_lun);
4673}
4674
4675int
4676ctl_add_lun(struct ctl_be_lun *be_lun)
4677{
4678	struct ctl_softc *softc = control_softc;
4679
4680	mtx_lock(&softc->ctl_lock);
4681	STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4682	mtx_unlock(&softc->ctl_lock);
4683	wakeup(&softc->pending_lun_queue);
4684
4685	return (0);
4686}
4687
4688int
4689ctl_enable_lun(struct ctl_be_lun *be_lun)
4690{
4691	struct ctl_softc *softc;
4692	struct ctl_port *port, *nport;
4693	struct ctl_lun *lun;
4694	int retval;
4695
4696	lun = (struct ctl_lun *)be_lun->ctl_lun;
4697	softc = lun->ctl_softc;
4698
4699	mtx_lock(&softc->ctl_lock);
4700	mtx_lock(&lun->lun_lock);
4701	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4702		/*
4703		 * eh?  Why did we get called if the LUN is already
4704		 * enabled?
4705		 */
4706		mtx_unlock(&lun->lun_lock);
4707		mtx_unlock(&softc->ctl_lock);
4708		return (0);
4709	}
4710	lun->flags &= ~CTL_LUN_DISABLED;
4711	mtx_unlock(&lun->lun_lock);
4712
4713	for (port = STAILQ_FIRST(&softc->port_list); port != NULL; port = nport) {
4714		nport = STAILQ_NEXT(port, links);
4715		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4716		    port->lun_map != NULL || port->lun_enable == NULL)
4717			continue;
4718
4719		/*
4720		 * Drop the lock while we call the FETD's enable routine.
4721		 * This can lead to a callback into CTL (at least in the
4722		 * case of the internal initiator frontend.
4723		 */
4724		mtx_unlock(&softc->ctl_lock);
4725		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4726		mtx_lock(&softc->ctl_lock);
4727		if (retval != 0) {
4728			printf("%s: FETD %s port %d returned error "
4729			       "%d for lun_enable on lun %jd\n",
4730			       __func__, port->port_name, port->targ_port,
4731			       retval, (intmax_t)lun->lun);
4732		}
4733	}
4734
4735	mtx_unlock(&softc->ctl_lock);
4736	ctl_isc_announce_lun(lun);
4737
4738	return (0);
4739}
4740
4741int
4742ctl_disable_lun(struct ctl_be_lun *be_lun)
4743{
4744	struct ctl_softc *softc;
4745	struct ctl_port *port;
4746	struct ctl_lun *lun;
4747	int retval;
4748
4749	lun = (struct ctl_lun *)be_lun->ctl_lun;
4750	softc = lun->ctl_softc;
4751
4752	mtx_lock(&softc->ctl_lock);
4753	mtx_lock(&lun->lun_lock);
4754	if (lun->flags & CTL_LUN_DISABLED) {
4755		mtx_unlock(&lun->lun_lock);
4756		mtx_unlock(&softc->ctl_lock);
4757		return (0);
4758	}
4759	lun->flags |= CTL_LUN_DISABLED;
4760	mtx_unlock(&lun->lun_lock);
4761
4762	STAILQ_FOREACH(port, &softc->port_list, links) {
4763		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4764		    port->lun_map != NULL || port->lun_disable == NULL)
4765			continue;
4766
4767		/*
4768		 * Drop the lock before we call the frontend's disable
4769		 * routine, to avoid lock order reversals.
4770		 *
4771		 * XXX KDM what happens if the frontend list changes while
4772		 * we're traversing it?  It's unlikely, but should be handled.
4773		 */
4774		mtx_unlock(&softc->ctl_lock);
4775		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4776		mtx_lock(&softc->ctl_lock);
4777		if (retval != 0) {
4778			printf("%s: FETD %s port %d returned error "
4779			       "%d for lun_disable on lun %jd\n",
4780			       __func__, port->port_name, port->targ_port,
4781			       retval, (intmax_t)lun->lun);
4782		}
4783	}
4784
4785	mtx_unlock(&softc->ctl_lock);
4786	ctl_isc_announce_lun(lun);
4787
4788	return (0);
4789}
4790
4791int
4792ctl_start_lun(struct ctl_be_lun *be_lun)
4793{
4794	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4795
4796	mtx_lock(&lun->lun_lock);
4797	lun->flags &= ~CTL_LUN_STOPPED;
4798	mtx_unlock(&lun->lun_lock);
4799	return (0);
4800}
4801
4802int
4803ctl_stop_lun(struct ctl_be_lun *be_lun)
4804{
4805	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4806
4807	mtx_lock(&lun->lun_lock);
4808	lun->flags |= CTL_LUN_STOPPED;
4809	mtx_unlock(&lun->lun_lock);
4810	return (0);
4811}
4812
4813int
4814ctl_lun_offline(struct ctl_be_lun *be_lun)
4815{
4816	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4817
4818	mtx_lock(&lun->lun_lock);
4819	lun->flags |= CTL_LUN_OFFLINE;
4820	mtx_unlock(&lun->lun_lock);
4821	return (0);
4822}
4823
4824int
4825ctl_lun_online(struct ctl_be_lun *be_lun)
4826{
4827	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4828
4829	mtx_lock(&lun->lun_lock);
4830	lun->flags &= ~CTL_LUN_OFFLINE;
4831	mtx_unlock(&lun->lun_lock);
4832	return (0);
4833}
4834
4835int
4836ctl_lun_primary(struct ctl_be_lun *be_lun)
4837{
4838	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4839
4840	mtx_lock(&lun->lun_lock);
4841	lun->flags |= CTL_LUN_PRIMARY_SC;
4842	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4843	mtx_unlock(&lun->lun_lock);
4844	ctl_isc_announce_lun(lun);
4845	return (0);
4846}
4847
4848int
4849ctl_lun_secondary(struct ctl_be_lun *be_lun)
4850{
4851	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4852
4853	mtx_lock(&lun->lun_lock);
4854	lun->flags &= ~CTL_LUN_PRIMARY_SC;
4855	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4856	mtx_unlock(&lun->lun_lock);
4857	ctl_isc_announce_lun(lun);
4858	return (0);
4859}
4860
4861int
4862ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4863{
4864	struct ctl_softc *softc;
4865	struct ctl_lun *lun;
4866
4867	lun = (struct ctl_lun *)be_lun->ctl_lun;
4868	softc = lun->ctl_softc;
4869
4870	mtx_lock(&lun->lun_lock);
4871
4872	/*
4873	 * The LUN needs to be disabled before it can be marked invalid.
4874	 */
4875	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4876		mtx_unlock(&lun->lun_lock);
4877		return (-1);
4878	}
4879	/*
4880	 * Mark the LUN invalid.
4881	 */
4882	lun->flags |= CTL_LUN_INVALID;
4883
4884	/*
4885	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4886	 * If we have something in the OOA queue, we'll free it when the
4887	 * last I/O completes.
4888	 */
4889	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4890		mtx_unlock(&lun->lun_lock);
4891		mtx_lock(&softc->ctl_lock);
4892		ctl_free_lun(lun);
4893		mtx_unlock(&softc->ctl_lock);
4894	} else
4895		mtx_unlock(&lun->lun_lock);
4896
4897	return (0);
4898}
4899
4900int
4901ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4902{
4903	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4904
4905	mtx_lock(&lun->lun_lock);
4906	lun->flags |= CTL_LUN_INOPERABLE;
4907	mtx_unlock(&lun->lun_lock);
4908	return (0);
4909}
4910
4911int
4912ctl_lun_operable(struct ctl_be_lun *be_lun)
4913{
4914	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4915
4916	mtx_lock(&lun->lun_lock);
4917	lun->flags &= ~CTL_LUN_INOPERABLE;
4918	mtx_unlock(&lun->lun_lock);
4919	return (0);
4920}
4921
4922void
4923ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4924{
4925	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4926	union ctl_ha_msg msg;
4927
4928	mtx_lock(&lun->lun_lock);
4929	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGED);
4930	mtx_unlock(&lun->lun_lock);
4931	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4932		/* Send msg to other side. */
4933		bzero(&msg.ua, sizeof(msg.ua));
4934		msg.hdr.msg_type = CTL_MSG_UA;
4935		msg.hdr.nexus.initid = -1;
4936		msg.hdr.nexus.targ_port = -1;
4937		msg.hdr.nexus.targ_lun = lun->lun;
4938		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4939		msg.ua.ua_all = 1;
4940		msg.ua.ua_set = 1;
4941		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGED;
4942		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4943		    M_WAITOK);
4944	}
4945}
4946
4947/*
4948 * Backend "memory move is complete" callback for requests that never
4949 * make it down to say RAIDCore's configuration code.
4950 */
4951int
4952ctl_config_move_done(union ctl_io *io)
4953{
4954	int retval;
4955
4956	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4957	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4958	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
4959
4960	if ((io->io_hdr.port_status != 0) &&
4961	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4962	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4963		/*
4964		 * For hardware error sense keys, the sense key
4965		 * specific value is defined to be a retry count,
4966		 * but we use it to pass back an internal FETD
4967		 * error code.  XXX KDM  Hopefully the FETD is only
4968		 * using 16 bits for an error code, since that's
4969		 * all the space we have in the sks field.
4970		 */
4971		ctl_set_internal_failure(&io->scsiio,
4972					 /*sks_valid*/ 1,
4973					 /*retry_count*/
4974					 io->io_hdr.port_status);
4975	}
4976
4977	if (ctl_debug & CTL_DEBUG_CDB_DATA)
4978		ctl_data_print(io);
4979	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
4980	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4981	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
4982	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
4983		/*
4984		 * XXX KDM just assuming a single pointer here, and not a
4985		 * S/G list.  If we start using S/G lists for config data,
4986		 * we'll need to know how to clean them up here as well.
4987		 */
4988		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4989			free(io->scsiio.kern_data_ptr, M_CTL);
4990		ctl_done(io);
4991		retval = CTL_RETVAL_COMPLETE;
4992	} else {
4993		/*
4994		 * XXX KDM now we need to continue data movement.  Some
4995		 * options:
4996		 * - call ctl_scsiio() again?  We don't do this for data
4997		 *   writes, because for those at least we know ahead of
4998		 *   time where the write will go and how long it is.  For
4999		 *   config writes, though, that information is largely
5000		 *   contained within the write itself, thus we need to
5001		 *   parse out the data again.
5002		 *
5003		 * - Call some other function once the data is in?
5004		 */
5005
5006		/*
5007		 * XXX KDM call ctl_scsiio() again for now, and check flag
5008		 * bits to see whether we're allocated or not.
5009		 */
5010		retval = ctl_scsiio(&io->scsiio);
5011	}
5012	return (retval);
5013}
5014
5015/*
5016 * This gets called by a backend driver when it is done with a
5017 * data_submit method.
5018 */
5019void
5020ctl_data_submit_done(union ctl_io *io)
5021{
5022	/*
5023	 * If the IO_CONT flag is set, we need to call the supplied
5024	 * function to continue processing the I/O, instead of completing
5025	 * the I/O just yet.
5026	 *
5027	 * If there is an error, though, we don't want to keep processing.
5028	 * Instead, just send status back to the initiator.
5029	 */
5030	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5031	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5032	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5033	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5034		io->scsiio.io_cont(io);
5035		return;
5036	}
5037	ctl_done(io);
5038}
5039
5040/*
5041 * This gets called by a backend driver when it is done with a
5042 * configuration write.
5043 */
5044void
5045ctl_config_write_done(union ctl_io *io)
5046{
5047	uint8_t *buf;
5048
5049	/*
5050	 * If the IO_CONT flag is set, we need to call the supplied
5051	 * function to continue processing the I/O, instead of completing
5052	 * the I/O just yet.
5053	 *
5054	 * If there is an error, though, we don't want to keep processing.
5055	 * Instead, just send status back to the initiator.
5056	 */
5057	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5058	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5059	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5060	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5061		io->scsiio.io_cont(io);
5062		return;
5063	}
5064	/*
5065	 * Since a configuration write can be done for commands that actually
5066	 * have data allocated, like write buffer, and commands that have
5067	 * no data, like start/stop unit, we need to check here.
5068	 */
5069	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5070		buf = io->scsiio.kern_data_ptr;
5071	else
5072		buf = NULL;
5073	ctl_done(io);
5074	if (buf)
5075		free(buf, M_CTL);
5076}
5077
5078void
5079ctl_config_read_done(union ctl_io *io)
5080{
5081	uint8_t *buf;
5082
5083	/*
5084	 * If there is some error -- we are done, skip data transfer.
5085	 */
5086	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5087	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5088	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5089		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5090			buf = io->scsiio.kern_data_ptr;
5091		else
5092			buf = NULL;
5093		ctl_done(io);
5094		if (buf)
5095			free(buf, M_CTL);
5096		return;
5097	}
5098
5099	/*
5100	 * If the IO_CONT flag is set, we need to call the supplied
5101	 * function to continue processing the I/O, instead of completing
5102	 * the I/O just yet.
5103	 */
5104	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5105		io->scsiio.io_cont(io);
5106		return;
5107	}
5108
5109	ctl_datamove(io);
5110}
5111
5112/*
5113 * SCSI release command.
5114 */
5115int
5116ctl_scsi_release(struct ctl_scsiio *ctsio)
5117{
5118	int length, longid, thirdparty_id, resv_id;
5119	struct ctl_lun *lun;
5120	uint32_t residx;
5121
5122	length = 0;
5123	resv_id = 0;
5124
5125	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5126
5127	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5128	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5129
5130	switch (ctsio->cdb[0]) {
5131	case RELEASE_10: {
5132		struct scsi_release_10 *cdb;
5133
5134		cdb = (struct scsi_release_10 *)ctsio->cdb;
5135
5136		if (cdb->byte2 & SR10_LONGID)
5137			longid = 1;
5138		else
5139			thirdparty_id = cdb->thirdparty_id;
5140
5141		resv_id = cdb->resv_id;
5142		length = scsi_2btoul(cdb->length);
5143		break;
5144	}
5145	}
5146
5147
5148	/*
5149	 * XXX KDM right now, we only support LUN reservation.  We don't
5150	 * support 3rd party reservations, or extent reservations, which
5151	 * might actually need the parameter list.  If we've gotten this
5152	 * far, we've got a LUN reservation.  Anything else got kicked out
5153	 * above.  So, according to SPC, ignore the length.
5154	 */
5155	length = 0;
5156
5157	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5158	 && (length > 0)) {
5159		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5160		ctsio->kern_data_len = length;
5161		ctsio->kern_total_len = length;
5162		ctsio->kern_data_resid = 0;
5163		ctsio->kern_rel_offset = 0;
5164		ctsio->kern_sg_entries = 0;
5165		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5166		ctsio->be_move_done = ctl_config_move_done;
5167		ctl_datamove((union ctl_io *)ctsio);
5168
5169		return (CTL_RETVAL_COMPLETE);
5170	}
5171
5172	if (length > 0)
5173		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5174
5175	mtx_lock(&lun->lun_lock);
5176
5177	/*
5178	 * According to SPC, it is not an error for an intiator to attempt
5179	 * to release a reservation on a LUN that isn't reserved, or that
5180	 * is reserved by another initiator.  The reservation can only be
5181	 * released, though, by the initiator who made it or by one of
5182	 * several reset type events.
5183	 */
5184	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5185			lun->flags &= ~CTL_LUN_RESERVED;
5186
5187	mtx_unlock(&lun->lun_lock);
5188
5189	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5190		free(ctsio->kern_data_ptr, M_CTL);
5191		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5192	}
5193
5194	ctl_set_success(ctsio);
5195	ctl_done((union ctl_io *)ctsio);
5196	return (CTL_RETVAL_COMPLETE);
5197}
5198
5199int
5200ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5201{
5202	int extent, thirdparty, longid;
5203	int resv_id, length;
5204	uint64_t thirdparty_id;
5205	struct ctl_lun *lun;
5206	uint32_t residx;
5207
5208	extent = 0;
5209	thirdparty = 0;
5210	longid = 0;
5211	resv_id = 0;
5212	length = 0;
5213	thirdparty_id = 0;
5214
5215	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5216
5217	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5218	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5219
5220	switch (ctsio->cdb[0]) {
5221	case RESERVE_10: {
5222		struct scsi_reserve_10 *cdb;
5223
5224		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5225
5226		if (cdb->byte2 & SR10_LONGID)
5227			longid = 1;
5228		else
5229			thirdparty_id = cdb->thirdparty_id;
5230
5231		resv_id = cdb->resv_id;
5232		length = scsi_2btoul(cdb->length);
5233		break;
5234	}
5235	}
5236
5237	/*
5238	 * XXX KDM right now, we only support LUN reservation.  We don't
5239	 * support 3rd party reservations, or extent reservations, which
5240	 * might actually need the parameter list.  If we've gotten this
5241	 * far, we've got a LUN reservation.  Anything else got kicked out
5242	 * above.  So, according to SPC, ignore the length.
5243	 */
5244	length = 0;
5245
5246	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5247	 && (length > 0)) {
5248		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5249		ctsio->kern_data_len = length;
5250		ctsio->kern_total_len = length;
5251		ctsio->kern_data_resid = 0;
5252		ctsio->kern_rel_offset = 0;
5253		ctsio->kern_sg_entries = 0;
5254		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5255		ctsio->be_move_done = ctl_config_move_done;
5256		ctl_datamove((union ctl_io *)ctsio);
5257
5258		return (CTL_RETVAL_COMPLETE);
5259	}
5260
5261	if (length > 0)
5262		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5263
5264	mtx_lock(&lun->lun_lock);
5265	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5266		ctl_set_reservation_conflict(ctsio);
5267		goto bailout;
5268	}
5269
5270	lun->flags |= CTL_LUN_RESERVED;
5271	lun->res_idx = residx;
5272
5273	ctl_set_success(ctsio);
5274
5275bailout:
5276	mtx_unlock(&lun->lun_lock);
5277
5278	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5279		free(ctsio->kern_data_ptr, M_CTL);
5280		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5281	}
5282
5283	ctl_done((union ctl_io *)ctsio);
5284	return (CTL_RETVAL_COMPLETE);
5285}
5286
5287int
5288ctl_start_stop(struct ctl_scsiio *ctsio)
5289{
5290	struct scsi_start_stop_unit *cdb;
5291	struct ctl_lun *lun;
5292	int retval;
5293
5294	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5295
5296	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5297	retval = 0;
5298
5299	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5300
5301	/*
5302	 * XXX KDM
5303	 * We don't support the immediate bit on a stop unit.  In order to
5304	 * do that, we would need to code up a way to know that a stop is
5305	 * pending, and hold off any new commands until it completes, one
5306	 * way or another.  Then we could accept or reject those commands
5307	 * depending on its status.  We would almost need to do the reverse
5308	 * of what we do below for an immediate start -- return the copy of
5309	 * the ctl_io to the FETD with status to send to the host (and to
5310	 * free the copy!) and then free the original I/O once the stop
5311	 * actually completes.  That way, the OOA queue mechanism can work
5312	 * to block commands that shouldn't proceed.  Another alternative
5313	 * would be to put the copy in the queue in place of the original,
5314	 * and return the original back to the caller.  That could be
5315	 * slightly safer..
5316	 */
5317	if ((cdb->byte2 & SSS_IMMED)
5318	 && ((cdb->how & SSS_START) == 0)) {
5319		ctl_set_invalid_field(ctsio,
5320				      /*sks_valid*/ 1,
5321				      /*command*/ 1,
5322				      /*field*/ 1,
5323				      /*bit_valid*/ 1,
5324				      /*bit*/ 0);
5325		ctl_done((union ctl_io *)ctsio);
5326		return (CTL_RETVAL_COMPLETE);
5327	}
5328
5329	if ((lun->flags & CTL_LUN_PR_RESERVED)
5330	 && ((cdb->how & SSS_START)==0)) {
5331		uint32_t residx;
5332
5333		residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5334		if (ctl_get_prkey(lun, residx) == 0
5335		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5336
5337			ctl_set_reservation_conflict(ctsio);
5338			ctl_done((union ctl_io *)ctsio);
5339			return (CTL_RETVAL_COMPLETE);
5340		}
5341	}
5342
5343	/*
5344	 * If there is no backend on this device, we can't start or stop
5345	 * it.  In theory we shouldn't get any start/stop commands in the
5346	 * first place at this level if the LUN doesn't have a backend.
5347	 * That should get stopped by the command decode code.
5348	 */
5349	if (lun->backend == NULL) {
5350		ctl_set_invalid_opcode(ctsio);
5351		ctl_done((union ctl_io *)ctsio);
5352		return (CTL_RETVAL_COMPLETE);
5353	}
5354
5355	/*
5356	 * XXX KDM Copan-specific offline behavior.
5357	 * Figure out a reasonable way to port this?
5358	 */
5359#ifdef NEEDTOPORT
5360	mtx_lock(&lun->lun_lock);
5361
5362	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5363	 && (lun->flags & CTL_LUN_OFFLINE)) {
5364		/*
5365		 * If the LUN is offline, and the on/offline bit isn't set,
5366		 * reject the start or stop.  Otherwise, let it through.
5367		 */
5368		mtx_unlock(&lun->lun_lock);
5369		ctl_set_lun_not_ready(ctsio);
5370		ctl_done((union ctl_io *)ctsio);
5371	} else {
5372		mtx_unlock(&lun->lun_lock);
5373#endif /* NEEDTOPORT */
5374		/*
5375		 * This could be a start or a stop when we're online,
5376		 * or a stop/offline or start/online.  A start or stop when
5377		 * we're offline is covered in the case above.
5378		 */
5379		/*
5380		 * In the non-immediate case, we send the request to
5381		 * the backend and return status to the user when
5382		 * it is done.
5383		 *
5384		 * In the immediate case, we allocate a new ctl_io
5385		 * to hold a copy of the request, and send that to
5386		 * the backend.  We then set good status on the
5387		 * user's request and return it immediately.
5388		 */
5389		if (cdb->byte2 & SSS_IMMED) {
5390			union ctl_io *new_io;
5391
5392			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5393			ctl_copy_io((union ctl_io *)ctsio, new_io);
5394			retval = lun->backend->config_write(new_io);
5395			ctl_set_success(ctsio);
5396			ctl_done((union ctl_io *)ctsio);
5397		} else {
5398			retval = lun->backend->config_write(
5399				(union ctl_io *)ctsio);
5400		}
5401#ifdef NEEDTOPORT
5402	}
5403#endif
5404	return (retval);
5405}
5406
5407/*
5408 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5409 * we don't really do anything with the LBA and length fields if the user
5410 * passes them in.  Instead we'll just flush out the cache for the entire
5411 * LUN.
5412 */
5413int
5414ctl_sync_cache(struct ctl_scsiio *ctsio)
5415{
5416	struct ctl_lun *lun;
5417	struct ctl_softc *softc;
5418	struct ctl_lba_len_flags *lbalen;
5419	uint64_t starting_lba;
5420	uint32_t block_count;
5421	int retval;
5422	uint8_t byte2;
5423
5424	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5425
5426	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5427	softc = lun->ctl_softc;
5428	retval = 0;
5429
5430	switch (ctsio->cdb[0]) {
5431	case SYNCHRONIZE_CACHE: {
5432		struct scsi_sync_cache *cdb;
5433		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5434
5435		starting_lba = scsi_4btoul(cdb->begin_lba);
5436		block_count = scsi_2btoul(cdb->lb_count);
5437		byte2 = cdb->byte2;
5438		break;
5439	}
5440	case SYNCHRONIZE_CACHE_16: {
5441		struct scsi_sync_cache_16 *cdb;
5442		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5443
5444		starting_lba = scsi_8btou64(cdb->begin_lba);
5445		block_count = scsi_4btoul(cdb->lb_count);
5446		byte2 = cdb->byte2;
5447		break;
5448	}
5449	default:
5450		ctl_set_invalid_opcode(ctsio);
5451		ctl_done((union ctl_io *)ctsio);
5452		goto bailout;
5453		break; /* NOTREACHED */
5454	}
5455
5456	/*
5457	 * We check the LBA and length, but don't do anything with them.
5458	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5459	 * get flushed.  This check will just help satisfy anyone who wants
5460	 * to see an error for an out of range LBA.
5461	 */
5462	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5463		ctl_set_lba_out_of_range(ctsio);
5464		ctl_done((union ctl_io *)ctsio);
5465		goto bailout;
5466	}
5467
5468	/*
5469	 * If this LUN has no backend, we can't flush the cache anyway.
5470	 */
5471	if (lun->backend == NULL) {
5472		ctl_set_invalid_opcode(ctsio);
5473		ctl_done((union ctl_io *)ctsio);
5474		goto bailout;
5475	}
5476
5477	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5478	lbalen->lba = starting_lba;
5479	lbalen->len = block_count;
5480	lbalen->flags = byte2;
5481
5482	/*
5483	 * Check to see whether we're configured to send the SYNCHRONIZE
5484	 * CACHE command directly to the back end.
5485	 */
5486	mtx_lock(&lun->lun_lock);
5487	if ((softc->flags & CTL_FLAG_REAL_SYNC)
5488	 && (++(lun->sync_count) >= lun->sync_interval)) {
5489		lun->sync_count = 0;
5490		mtx_unlock(&lun->lun_lock);
5491		retval = lun->backend->config_write((union ctl_io *)ctsio);
5492	} else {
5493		mtx_unlock(&lun->lun_lock);
5494		ctl_set_success(ctsio);
5495		ctl_done((union ctl_io *)ctsio);
5496	}
5497
5498bailout:
5499
5500	return (retval);
5501}
5502
5503int
5504ctl_format(struct ctl_scsiio *ctsio)
5505{
5506	struct scsi_format *cdb;
5507	struct ctl_lun *lun;
5508	int length, defect_list_len;
5509
5510	CTL_DEBUG_PRINT(("ctl_format\n"));
5511
5512	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5513
5514	cdb = (struct scsi_format *)ctsio->cdb;
5515
5516	length = 0;
5517	if (cdb->byte2 & SF_FMTDATA) {
5518		if (cdb->byte2 & SF_LONGLIST)
5519			length = sizeof(struct scsi_format_header_long);
5520		else
5521			length = sizeof(struct scsi_format_header_short);
5522	}
5523
5524	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5525	 && (length > 0)) {
5526		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5527		ctsio->kern_data_len = length;
5528		ctsio->kern_total_len = length;
5529		ctsio->kern_data_resid = 0;
5530		ctsio->kern_rel_offset = 0;
5531		ctsio->kern_sg_entries = 0;
5532		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5533		ctsio->be_move_done = ctl_config_move_done;
5534		ctl_datamove((union ctl_io *)ctsio);
5535
5536		return (CTL_RETVAL_COMPLETE);
5537	}
5538
5539	defect_list_len = 0;
5540
5541	if (cdb->byte2 & SF_FMTDATA) {
5542		if (cdb->byte2 & SF_LONGLIST) {
5543			struct scsi_format_header_long *header;
5544
5545			header = (struct scsi_format_header_long *)
5546				ctsio->kern_data_ptr;
5547
5548			defect_list_len = scsi_4btoul(header->defect_list_len);
5549			if (defect_list_len != 0) {
5550				ctl_set_invalid_field(ctsio,
5551						      /*sks_valid*/ 1,
5552						      /*command*/ 0,
5553						      /*field*/ 2,
5554						      /*bit_valid*/ 0,
5555						      /*bit*/ 0);
5556				goto bailout;
5557			}
5558		} else {
5559			struct scsi_format_header_short *header;
5560
5561			header = (struct scsi_format_header_short *)
5562				ctsio->kern_data_ptr;
5563
5564			defect_list_len = scsi_2btoul(header->defect_list_len);
5565			if (defect_list_len != 0) {
5566				ctl_set_invalid_field(ctsio,
5567						      /*sks_valid*/ 1,
5568						      /*command*/ 0,
5569						      /*field*/ 2,
5570						      /*bit_valid*/ 0,
5571						      /*bit*/ 0);
5572				goto bailout;
5573			}
5574		}
5575	}
5576
5577	/*
5578	 * The format command will clear out the "Medium format corrupted"
5579	 * status if set by the configuration code.  That status is really
5580	 * just a way to notify the host that we have lost the media, and
5581	 * get them to issue a command that will basically make them think
5582	 * they're blowing away the media.
5583	 */
5584	mtx_lock(&lun->lun_lock);
5585	lun->flags &= ~CTL_LUN_INOPERABLE;
5586	mtx_unlock(&lun->lun_lock);
5587
5588	ctl_set_success(ctsio);
5589bailout:
5590
5591	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5592		free(ctsio->kern_data_ptr, M_CTL);
5593		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5594	}
5595
5596	ctl_done((union ctl_io *)ctsio);
5597	return (CTL_RETVAL_COMPLETE);
5598}
5599
5600int
5601ctl_read_buffer(struct ctl_scsiio *ctsio)
5602{
5603	struct ctl_lun *lun;
5604	uint64_t buffer_offset;
5605	uint32_t len;
5606	uint8_t byte2;
5607	static uint8_t descr[4];
5608	static uint8_t echo_descr[4] = { 0 };
5609
5610	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5611	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5612	switch (ctsio->cdb[0]) {
5613	case READ_BUFFER: {
5614		struct scsi_read_buffer *cdb;
5615
5616		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5617		buffer_offset = scsi_3btoul(cdb->offset);
5618		len = scsi_3btoul(cdb->length);
5619		byte2 = cdb->byte2;
5620		break;
5621	}
5622	case READ_BUFFER_16: {
5623		struct scsi_read_buffer_16 *cdb;
5624
5625		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5626		buffer_offset = scsi_8btou64(cdb->offset);
5627		len = scsi_4btoul(cdb->length);
5628		byte2 = cdb->byte2;
5629		break;
5630	}
5631	default: /* This shouldn't happen. */
5632		ctl_set_invalid_opcode(ctsio);
5633		ctl_done((union ctl_io *)ctsio);
5634		return (CTL_RETVAL_COMPLETE);
5635	}
5636
5637	if ((byte2 & RWB_MODE) != RWB_MODE_DATA &&
5638	    (byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5639	    (byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5640		ctl_set_invalid_field(ctsio,
5641				      /*sks_valid*/ 1,
5642				      /*command*/ 1,
5643				      /*field*/ 1,
5644				      /*bit_valid*/ 1,
5645				      /*bit*/ 4);
5646		ctl_done((union ctl_io *)ctsio);
5647		return (CTL_RETVAL_COMPLETE);
5648	}
5649
5650	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5651	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5652		ctl_set_invalid_field(ctsio,
5653				      /*sks_valid*/ 1,
5654				      /*command*/ 1,
5655				      /*field*/ 6,
5656				      /*bit_valid*/ 0,
5657				      /*bit*/ 0);
5658		ctl_done((union ctl_io *)ctsio);
5659		return (CTL_RETVAL_COMPLETE);
5660	}
5661
5662	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5663		descr[0] = 0;
5664		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5665		ctsio->kern_data_ptr = descr;
5666		len = min(len, sizeof(descr));
5667	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5668		ctsio->kern_data_ptr = echo_descr;
5669		len = min(len, sizeof(echo_descr));
5670	} else {
5671		if (lun->write_buffer == NULL) {
5672			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5673			    M_CTL, M_WAITOK);
5674		}
5675		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5676	}
5677	ctsio->kern_data_len = len;
5678	ctsio->kern_total_len = len;
5679	ctsio->kern_data_resid = 0;
5680	ctsio->kern_rel_offset = 0;
5681	ctsio->kern_sg_entries = 0;
5682	ctl_set_success(ctsio);
5683	ctsio->be_move_done = ctl_config_move_done;
5684	ctl_datamove((union ctl_io *)ctsio);
5685	return (CTL_RETVAL_COMPLETE);
5686}
5687
5688int
5689ctl_write_buffer(struct ctl_scsiio *ctsio)
5690{
5691	struct scsi_write_buffer *cdb;
5692	struct ctl_lun *lun;
5693	int buffer_offset, len;
5694
5695	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5696
5697	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5698	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5699
5700	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5701		ctl_set_invalid_field(ctsio,
5702				      /*sks_valid*/ 1,
5703				      /*command*/ 1,
5704				      /*field*/ 1,
5705				      /*bit_valid*/ 1,
5706				      /*bit*/ 4);
5707		ctl_done((union ctl_io *)ctsio);
5708		return (CTL_RETVAL_COMPLETE);
5709	}
5710
5711	len = scsi_3btoul(cdb->length);
5712	buffer_offset = scsi_3btoul(cdb->offset);
5713
5714	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5715		ctl_set_invalid_field(ctsio,
5716				      /*sks_valid*/ 1,
5717				      /*command*/ 1,
5718				      /*field*/ 6,
5719				      /*bit_valid*/ 0,
5720				      /*bit*/ 0);
5721		ctl_done((union ctl_io *)ctsio);
5722		return (CTL_RETVAL_COMPLETE);
5723	}
5724
5725	/*
5726	 * If we've got a kernel request that hasn't been malloced yet,
5727	 * malloc it and tell the caller the data buffer is here.
5728	 */
5729	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5730		if (lun->write_buffer == NULL) {
5731			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5732			    M_CTL, M_WAITOK);
5733		}
5734		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5735		ctsio->kern_data_len = len;
5736		ctsio->kern_total_len = len;
5737		ctsio->kern_data_resid = 0;
5738		ctsio->kern_rel_offset = 0;
5739		ctsio->kern_sg_entries = 0;
5740		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5741		ctsio->be_move_done = ctl_config_move_done;
5742		ctl_datamove((union ctl_io *)ctsio);
5743
5744		return (CTL_RETVAL_COMPLETE);
5745	}
5746
5747	ctl_set_success(ctsio);
5748	ctl_done((union ctl_io *)ctsio);
5749	return (CTL_RETVAL_COMPLETE);
5750}
5751
5752int
5753ctl_write_same(struct ctl_scsiio *ctsio)
5754{
5755	struct ctl_lun *lun;
5756	struct ctl_lba_len_flags *lbalen;
5757	uint64_t lba;
5758	uint32_t num_blocks;
5759	int len, retval;
5760	uint8_t byte2;
5761
5762	retval = CTL_RETVAL_COMPLETE;
5763
5764	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5765
5766	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5767
5768	switch (ctsio->cdb[0]) {
5769	case WRITE_SAME_10: {
5770		struct scsi_write_same_10 *cdb;
5771
5772		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5773
5774		lba = scsi_4btoul(cdb->addr);
5775		num_blocks = scsi_2btoul(cdb->length);
5776		byte2 = cdb->byte2;
5777		break;
5778	}
5779	case WRITE_SAME_16: {
5780		struct scsi_write_same_16 *cdb;
5781
5782		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5783
5784		lba = scsi_8btou64(cdb->addr);
5785		num_blocks = scsi_4btoul(cdb->length);
5786		byte2 = cdb->byte2;
5787		break;
5788	}
5789	default:
5790		/*
5791		 * We got a command we don't support.  This shouldn't
5792		 * happen, commands should be filtered out above us.
5793		 */
5794		ctl_set_invalid_opcode(ctsio);
5795		ctl_done((union ctl_io *)ctsio);
5796
5797		return (CTL_RETVAL_COMPLETE);
5798		break; /* NOTREACHED */
5799	}
5800
5801	/* ANCHOR flag can be used only together with UNMAP */
5802	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5803		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5804		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5805		ctl_done((union ctl_io *)ctsio);
5806		return (CTL_RETVAL_COMPLETE);
5807	}
5808
5809	/*
5810	 * The first check is to make sure we're in bounds, the second
5811	 * check is to catch wrap-around problems.  If the lba + num blocks
5812	 * is less than the lba, then we've wrapped around and the block
5813	 * range is invalid anyway.
5814	 */
5815	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5816	 || ((lba + num_blocks) < lba)) {
5817		ctl_set_lba_out_of_range(ctsio);
5818		ctl_done((union ctl_io *)ctsio);
5819		return (CTL_RETVAL_COMPLETE);
5820	}
5821
5822	/* Zero number of blocks means "to the last logical block" */
5823	if (num_blocks == 0) {
5824		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5825			ctl_set_invalid_field(ctsio,
5826					      /*sks_valid*/ 0,
5827					      /*command*/ 1,
5828					      /*field*/ 0,
5829					      /*bit_valid*/ 0,
5830					      /*bit*/ 0);
5831			ctl_done((union ctl_io *)ctsio);
5832			return (CTL_RETVAL_COMPLETE);
5833		}
5834		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5835	}
5836
5837	len = lun->be_lun->blocksize;
5838
5839	/*
5840	 * If we've got a kernel request that hasn't been malloced yet,
5841	 * malloc it and tell the caller the data buffer is here.
5842	 */
5843	if ((byte2 & SWS_NDOB) == 0 &&
5844	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5845		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5846		ctsio->kern_data_len = len;
5847		ctsio->kern_total_len = len;
5848		ctsio->kern_data_resid = 0;
5849		ctsio->kern_rel_offset = 0;
5850		ctsio->kern_sg_entries = 0;
5851		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5852		ctsio->be_move_done = ctl_config_move_done;
5853		ctl_datamove((union ctl_io *)ctsio);
5854
5855		return (CTL_RETVAL_COMPLETE);
5856	}
5857
5858	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5859	lbalen->lba = lba;
5860	lbalen->len = num_blocks;
5861	lbalen->flags = byte2;
5862	retval = lun->backend->config_write((union ctl_io *)ctsio);
5863
5864	return (retval);
5865}
5866
5867int
5868ctl_unmap(struct ctl_scsiio *ctsio)
5869{
5870	struct ctl_lun *lun;
5871	struct scsi_unmap *cdb;
5872	struct ctl_ptr_len_flags *ptrlen;
5873	struct scsi_unmap_header *hdr;
5874	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5875	uint64_t lba;
5876	uint32_t num_blocks;
5877	int len, retval;
5878	uint8_t byte2;
5879
5880	retval = CTL_RETVAL_COMPLETE;
5881
5882	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5883
5884	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5885	cdb = (struct scsi_unmap *)ctsio->cdb;
5886
5887	len = scsi_2btoul(cdb->length);
5888	byte2 = cdb->byte2;
5889
5890	/*
5891	 * If we've got a kernel request that hasn't been malloced yet,
5892	 * malloc it and tell the caller the data buffer is here.
5893	 */
5894	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5895		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5896		ctsio->kern_data_len = len;
5897		ctsio->kern_total_len = len;
5898		ctsio->kern_data_resid = 0;
5899		ctsio->kern_rel_offset = 0;
5900		ctsio->kern_sg_entries = 0;
5901		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5902		ctsio->be_move_done = ctl_config_move_done;
5903		ctl_datamove((union ctl_io *)ctsio);
5904
5905		return (CTL_RETVAL_COMPLETE);
5906	}
5907
5908	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5909	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5910	if (len < sizeof (*hdr) ||
5911	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5912	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5913	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5914		ctl_set_invalid_field(ctsio,
5915				      /*sks_valid*/ 0,
5916				      /*command*/ 0,
5917				      /*field*/ 0,
5918				      /*bit_valid*/ 0,
5919				      /*bit*/ 0);
5920		goto done;
5921	}
5922	len = scsi_2btoul(hdr->desc_length);
5923	buf = (struct scsi_unmap_desc *)(hdr + 1);
5924	end = buf + len / sizeof(*buf);
5925
5926	endnz = buf;
5927	for (range = buf; range < end; range++) {
5928		lba = scsi_8btou64(range->lba);
5929		num_blocks = scsi_4btoul(range->length);
5930		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5931		 || ((lba + num_blocks) < lba)) {
5932			ctl_set_lba_out_of_range(ctsio);
5933			ctl_done((union ctl_io *)ctsio);
5934			return (CTL_RETVAL_COMPLETE);
5935		}
5936		if (num_blocks != 0)
5937			endnz = range + 1;
5938	}
5939
5940	/*
5941	 * Block backend can not handle zero last range.
5942	 * Filter it out and return if there is nothing left.
5943	 */
5944	len = (uint8_t *)endnz - (uint8_t *)buf;
5945	if (len == 0) {
5946		ctl_set_success(ctsio);
5947		goto done;
5948	}
5949
5950	mtx_lock(&lun->lun_lock);
5951	ptrlen = (struct ctl_ptr_len_flags *)
5952	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5953	ptrlen->ptr = (void *)buf;
5954	ptrlen->len = len;
5955	ptrlen->flags = byte2;
5956	ctl_check_blocked(lun);
5957	mtx_unlock(&lun->lun_lock);
5958
5959	retval = lun->backend->config_write((union ctl_io *)ctsio);
5960	return (retval);
5961
5962done:
5963	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5964		free(ctsio->kern_data_ptr, M_CTL);
5965		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5966	}
5967	ctl_done((union ctl_io *)ctsio);
5968	return (CTL_RETVAL_COMPLETE);
5969}
5970
5971/*
5972 * Note that this function currently doesn't actually do anything inside
5973 * CTL to enforce things if the DQue bit is turned on.
5974 *
5975 * Also note that this function can't be used in the default case, because
5976 * the DQue bit isn't set in the changeable mask for the control mode page
5977 * anyway.  This is just here as an example for how to implement a page
5978 * handler, and a placeholder in case we want to allow the user to turn
5979 * tagged queueing on and off.
5980 *
5981 * The D_SENSE bit handling is functional, however, and will turn
5982 * descriptor sense on and off for a given LUN.
5983 */
5984int
5985ctl_control_page_handler(struct ctl_scsiio *ctsio,
5986			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5987{
5988	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5989	struct ctl_lun *lun;
5990	int set_ua;
5991	uint32_t initidx;
5992
5993	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5994	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5995	set_ua = 0;
5996
5997	user_cp = (struct scsi_control_page *)page_ptr;
5998	current_cp = (struct scsi_control_page *)
5999		(page_index->page_data + (page_index->page_len *
6000		CTL_PAGE_CURRENT));
6001	saved_cp = (struct scsi_control_page *)
6002		(page_index->page_data + (page_index->page_len *
6003		CTL_PAGE_SAVED));
6004
6005	mtx_lock(&lun->lun_lock);
6006	if (((current_cp->rlec & SCP_DSENSE) == 0)
6007	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6008		/*
6009		 * Descriptor sense is currently turned off and the user
6010		 * wants to turn it on.
6011		 */
6012		current_cp->rlec |= SCP_DSENSE;
6013		saved_cp->rlec |= SCP_DSENSE;
6014		lun->flags |= CTL_LUN_SENSE_DESC;
6015		set_ua = 1;
6016	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6017		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6018		/*
6019		 * Descriptor sense is currently turned on, and the user
6020		 * wants to turn it off.
6021		 */
6022		current_cp->rlec &= ~SCP_DSENSE;
6023		saved_cp->rlec &= ~SCP_DSENSE;
6024		lun->flags &= ~CTL_LUN_SENSE_DESC;
6025		set_ua = 1;
6026	}
6027	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6028	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6029		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6030		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6031		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6032		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6033		set_ua = 1;
6034	}
6035	if ((current_cp->eca_and_aen & SCP_SWP) !=
6036	    (user_cp->eca_and_aen & SCP_SWP)) {
6037		current_cp->eca_and_aen &= ~SCP_SWP;
6038		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6039		saved_cp->eca_and_aen &= ~SCP_SWP;
6040		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6041		set_ua = 1;
6042	}
6043	if (set_ua != 0)
6044		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6045	mtx_unlock(&lun->lun_lock);
6046	if (set_ua) {
6047		ctl_isc_announce_mode(lun,
6048		    ctl_get_initindex(&ctsio->io_hdr.nexus),
6049		    page_index->page_code, page_index->subpage);
6050	}
6051	return (0);
6052}
6053
6054int
6055ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6056		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6057{
6058	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6059	struct ctl_lun *lun;
6060	int set_ua;
6061	uint32_t initidx;
6062
6063	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6064	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6065	set_ua = 0;
6066
6067	user_cp = (struct scsi_caching_page *)page_ptr;
6068	current_cp = (struct scsi_caching_page *)
6069		(page_index->page_data + (page_index->page_len *
6070		CTL_PAGE_CURRENT));
6071	saved_cp = (struct scsi_caching_page *)
6072		(page_index->page_data + (page_index->page_len *
6073		CTL_PAGE_SAVED));
6074
6075	mtx_lock(&lun->lun_lock);
6076	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6077	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6078		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6079		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6080		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6081		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6082		set_ua = 1;
6083	}
6084	if (set_ua != 0)
6085		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6086	mtx_unlock(&lun->lun_lock);
6087	if (set_ua) {
6088		ctl_isc_announce_mode(lun,
6089		    ctl_get_initindex(&ctsio->io_hdr.nexus),
6090		    page_index->page_code, page_index->subpage);
6091	}
6092	return (0);
6093}
6094
6095int
6096ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6097				struct ctl_page_index *page_index,
6098				uint8_t *page_ptr)
6099{
6100	uint8_t *c;
6101	int i;
6102
6103	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6104	ctl_time_io_secs =
6105		(c[0] << 8) |
6106		(c[1] << 0) |
6107		0;
6108	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6109	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6110	printf("page data:");
6111	for (i=0; i<8; i++)
6112		printf(" %.2x",page_ptr[i]);
6113	printf("\n");
6114	return (0);
6115}
6116
6117int
6118ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6119			       struct ctl_page_index *page_index,
6120			       int pc)
6121{
6122	struct copan_debugconf_subpage *page;
6123
6124	page = (struct copan_debugconf_subpage *)page_index->page_data +
6125		(page_index->page_len * pc);
6126
6127	switch (pc) {
6128	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6129	case SMS_PAGE_CTRL_DEFAULT >> 6:
6130	case SMS_PAGE_CTRL_SAVED >> 6:
6131		/*
6132		 * We don't update the changable or default bits for this page.
6133		 */
6134		break;
6135	case SMS_PAGE_CTRL_CURRENT >> 6:
6136		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6137		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6138		break;
6139	default:
6140#ifdef NEEDTOPORT
6141		EPRINT(0, "Invalid PC %d!!", pc);
6142#endif /* NEEDTOPORT */
6143		break;
6144	}
6145	return (0);
6146}
6147
6148
6149static int
6150ctl_do_mode_select(union ctl_io *io)
6151{
6152	struct scsi_mode_page_header *page_header;
6153	struct ctl_page_index *page_index;
6154	struct ctl_scsiio *ctsio;
6155	int control_dev, page_len;
6156	int page_len_offset, page_len_size;
6157	union ctl_modepage_info *modepage_info;
6158	struct ctl_lun *lun;
6159	int *len_left, *len_used;
6160	int retval, i;
6161
6162	ctsio = &io->scsiio;
6163	page_index = NULL;
6164	page_len = 0;
6165	retval = CTL_RETVAL_COMPLETE;
6166
6167	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6168
6169	if (lun->be_lun->lun_type != T_DIRECT)
6170		control_dev = 1;
6171	else
6172		control_dev = 0;
6173
6174	modepage_info = (union ctl_modepage_info *)
6175		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6176	len_left = &modepage_info->header.len_left;
6177	len_used = &modepage_info->header.len_used;
6178
6179do_next_page:
6180
6181	page_header = (struct scsi_mode_page_header *)
6182		(ctsio->kern_data_ptr + *len_used);
6183
6184	if (*len_left == 0) {
6185		free(ctsio->kern_data_ptr, M_CTL);
6186		ctl_set_success(ctsio);
6187		ctl_done((union ctl_io *)ctsio);
6188		return (CTL_RETVAL_COMPLETE);
6189	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6190
6191		free(ctsio->kern_data_ptr, M_CTL);
6192		ctl_set_param_len_error(ctsio);
6193		ctl_done((union ctl_io *)ctsio);
6194		return (CTL_RETVAL_COMPLETE);
6195
6196	} else if ((page_header->page_code & SMPH_SPF)
6197		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6198
6199		free(ctsio->kern_data_ptr, M_CTL);
6200		ctl_set_param_len_error(ctsio);
6201		ctl_done((union ctl_io *)ctsio);
6202		return (CTL_RETVAL_COMPLETE);
6203	}
6204
6205
6206	/*
6207	 * XXX KDM should we do something with the block descriptor?
6208	 */
6209	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6210
6211		if ((control_dev != 0)
6212		 && (lun->mode_pages.index[i].page_flags &
6213		     CTL_PAGE_FLAG_DISK_ONLY))
6214			continue;
6215
6216		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6217		    (page_header->page_code & SMPH_PC_MASK))
6218			continue;
6219
6220		/*
6221		 * If neither page has a subpage code, then we've got a
6222		 * match.
6223		 */
6224		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6225		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6226			page_index = &lun->mode_pages.index[i];
6227			page_len = page_header->page_length;
6228			break;
6229		}
6230
6231		/*
6232		 * If both pages have subpages, then the subpage numbers
6233		 * have to match.
6234		 */
6235		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6236		  && (page_header->page_code & SMPH_SPF)) {
6237			struct scsi_mode_page_header_sp *sph;
6238
6239			sph = (struct scsi_mode_page_header_sp *)page_header;
6240
6241			if (lun->mode_pages.index[i].subpage ==
6242			    sph->subpage) {
6243				page_index = &lun->mode_pages.index[i];
6244				page_len = scsi_2btoul(sph->page_length);
6245				break;
6246			}
6247		}
6248	}
6249
6250	/*
6251	 * If we couldn't find the page, or if we don't have a mode select
6252	 * handler for it, send back an error to the user.
6253	 */
6254	if ((page_index == NULL)
6255	 || (page_index->select_handler == NULL)) {
6256		ctl_set_invalid_field(ctsio,
6257				      /*sks_valid*/ 1,
6258				      /*command*/ 0,
6259				      /*field*/ *len_used,
6260				      /*bit_valid*/ 0,
6261				      /*bit*/ 0);
6262		free(ctsio->kern_data_ptr, M_CTL);
6263		ctl_done((union ctl_io *)ctsio);
6264		return (CTL_RETVAL_COMPLETE);
6265	}
6266
6267	if (page_index->page_code & SMPH_SPF) {
6268		page_len_offset = 2;
6269		page_len_size = 2;
6270	} else {
6271		page_len_size = 1;
6272		page_len_offset = 1;
6273	}
6274
6275	/*
6276	 * If the length the initiator gives us isn't the one we specify in
6277	 * the mode page header, or if they didn't specify enough data in
6278	 * the CDB to avoid truncating this page, kick out the request.
6279	 */
6280	if ((page_len != (page_index->page_len - page_len_offset -
6281			  page_len_size))
6282	 || (*len_left < page_index->page_len)) {
6283
6284
6285		ctl_set_invalid_field(ctsio,
6286				      /*sks_valid*/ 1,
6287				      /*command*/ 0,
6288				      /*field*/ *len_used + page_len_offset,
6289				      /*bit_valid*/ 0,
6290				      /*bit*/ 0);
6291		free(ctsio->kern_data_ptr, M_CTL);
6292		ctl_done((union ctl_io *)ctsio);
6293		return (CTL_RETVAL_COMPLETE);
6294	}
6295
6296	/*
6297	 * Run through the mode page, checking to make sure that the bits
6298	 * the user changed are actually legal for him to change.
6299	 */
6300	for (i = 0; i < page_index->page_len; i++) {
6301		uint8_t *user_byte, *change_mask, *current_byte;
6302		int bad_bit;
6303		int j;
6304
6305		user_byte = (uint8_t *)page_header + i;
6306		change_mask = page_index->page_data +
6307			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6308		current_byte = page_index->page_data +
6309			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6310
6311		/*
6312		 * Check to see whether the user set any bits in this byte
6313		 * that he is not allowed to set.
6314		 */
6315		if ((*user_byte & ~(*change_mask)) ==
6316		    (*current_byte & ~(*change_mask)))
6317			continue;
6318
6319		/*
6320		 * Go through bit by bit to determine which one is illegal.
6321		 */
6322		bad_bit = 0;
6323		for (j = 7; j >= 0; j--) {
6324			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6325			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6326				bad_bit = i;
6327				break;
6328			}
6329		}
6330		ctl_set_invalid_field(ctsio,
6331				      /*sks_valid*/ 1,
6332				      /*command*/ 0,
6333				      /*field*/ *len_used + i,
6334				      /*bit_valid*/ 1,
6335				      /*bit*/ bad_bit);
6336		free(ctsio->kern_data_ptr, M_CTL);
6337		ctl_done((union ctl_io *)ctsio);
6338		return (CTL_RETVAL_COMPLETE);
6339	}
6340
6341	/*
6342	 * Decrement these before we call the page handler, since we may
6343	 * end up getting called back one way or another before the handler
6344	 * returns to this context.
6345	 */
6346	*len_left -= page_index->page_len;
6347	*len_used += page_index->page_len;
6348
6349	retval = page_index->select_handler(ctsio, page_index,
6350					    (uint8_t *)page_header);
6351
6352	/*
6353	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6354	 * wait until this queued command completes to finish processing
6355	 * the mode page.  If it returns anything other than
6356	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6357	 * already set the sense information, freed the data pointer, and
6358	 * completed the io for us.
6359	 */
6360	if (retval != CTL_RETVAL_COMPLETE)
6361		goto bailout_no_done;
6362
6363	/*
6364	 * If the initiator sent us more than one page, parse the next one.
6365	 */
6366	if (*len_left > 0)
6367		goto do_next_page;
6368
6369	ctl_set_success(ctsio);
6370	free(ctsio->kern_data_ptr, M_CTL);
6371	ctl_done((union ctl_io *)ctsio);
6372
6373bailout_no_done:
6374
6375	return (CTL_RETVAL_COMPLETE);
6376
6377}
6378
6379int
6380ctl_mode_select(struct ctl_scsiio *ctsio)
6381{
6382	int param_len, pf, sp;
6383	int header_size, bd_len;
6384	int len_left, len_used;
6385	struct ctl_page_index *page_index;
6386	struct ctl_lun *lun;
6387	int control_dev, page_len;
6388	union ctl_modepage_info *modepage_info;
6389	int retval;
6390
6391	pf = 0;
6392	sp = 0;
6393	page_len = 0;
6394	len_used = 0;
6395	len_left = 0;
6396	retval = 0;
6397	bd_len = 0;
6398	page_index = NULL;
6399
6400	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6401
6402	if (lun->be_lun->lun_type != T_DIRECT)
6403		control_dev = 1;
6404	else
6405		control_dev = 0;
6406
6407	switch (ctsio->cdb[0]) {
6408	case MODE_SELECT_6: {
6409		struct scsi_mode_select_6 *cdb;
6410
6411		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6412
6413		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6414		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6415
6416		param_len = cdb->length;
6417		header_size = sizeof(struct scsi_mode_header_6);
6418		break;
6419	}
6420	case MODE_SELECT_10: {
6421		struct scsi_mode_select_10 *cdb;
6422
6423		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6424
6425		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6426		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6427
6428		param_len = scsi_2btoul(cdb->length);
6429		header_size = sizeof(struct scsi_mode_header_10);
6430		break;
6431	}
6432	default:
6433		ctl_set_invalid_opcode(ctsio);
6434		ctl_done((union ctl_io *)ctsio);
6435		return (CTL_RETVAL_COMPLETE);
6436		break; /* NOTREACHED */
6437	}
6438
6439	/*
6440	 * From SPC-3:
6441	 * "A parameter list length of zero indicates that the Data-Out Buffer
6442	 * shall be empty. This condition shall not be considered as an error."
6443	 */
6444	if (param_len == 0) {
6445		ctl_set_success(ctsio);
6446		ctl_done((union ctl_io *)ctsio);
6447		return (CTL_RETVAL_COMPLETE);
6448	}
6449
6450	/*
6451	 * Since we'll hit this the first time through, prior to
6452	 * allocation, we don't need to free a data buffer here.
6453	 */
6454	if (param_len < header_size) {
6455		ctl_set_param_len_error(ctsio);
6456		ctl_done((union ctl_io *)ctsio);
6457		return (CTL_RETVAL_COMPLETE);
6458	}
6459
6460	/*
6461	 * Allocate the data buffer and grab the user's data.  In theory,
6462	 * we shouldn't have to sanity check the parameter list length here
6463	 * because the maximum size is 64K.  We should be able to malloc
6464	 * that much without too many problems.
6465	 */
6466	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6467		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6468		ctsio->kern_data_len = param_len;
6469		ctsio->kern_total_len = param_len;
6470		ctsio->kern_data_resid = 0;
6471		ctsio->kern_rel_offset = 0;
6472		ctsio->kern_sg_entries = 0;
6473		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6474		ctsio->be_move_done = ctl_config_move_done;
6475		ctl_datamove((union ctl_io *)ctsio);
6476
6477		return (CTL_RETVAL_COMPLETE);
6478	}
6479
6480	switch (ctsio->cdb[0]) {
6481	case MODE_SELECT_6: {
6482		struct scsi_mode_header_6 *mh6;
6483
6484		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6485		bd_len = mh6->blk_desc_len;
6486		break;
6487	}
6488	case MODE_SELECT_10: {
6489		struct scsi_mode_header_10 *mh10;
6490
6491		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6492		bd_len = scsi_2btoul(mh10->blk_desc_len);
6493		break;
6494	}
6495	default:
6496		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6497		break;
6498	}
6499
6500	if (param_len < (header_size + bd_len)) {
6501		free(ctsio->kern_data_ptr, M_CTL);
6502		ctl_set_param_len_error(ctsio);
6503		ctl_done((union ctl_io *)ctsio);
6504		return (CTL_RETVAL_COMPLETE);
6505	}
6506
6507	/*
6508	 * Set the IO_CONT flag, so that if this I/O gets passed to
6509	 * ctl_config_write_done(), it'll get passed back to
6510	 * ctl_do_mode_select() for further processing, or completion if
6511	 * we're all done.
6512	 */
6513	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6514	ctsio->io_cont = ctl_do_mode_select;
6515
6516	modepage_info = (union ctl_modepage_info *)
6517		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6518
6519	memset(modepage_info, 0, sizeof(*modepage_info));
6520
6521	len_left = param_len - header_size - bd_len;
6522	len_used = header_size + bd_len;
6523
6524	modepage_info->header.len_left = len_left;
6525	modepage_info->header.len_used = len_used;
6526
6527	return (ctl_do_mode_select((union ctl_io *)ctsio));
6528}
6529
6530int
6531ctl_mode_sense(struct ctl_scsiio *ctsio)
6532{
6533	struct ctl_lun *lun;
6534	int pc, page_code, dbd, llba, subpage;
6535	int alloc_len, page_len, header_len, total_len;
6536	struct scsi_mode_block_descr *block_desc;
6537	struct ctl_page_index *page_index;
6538	int control_dev;
6539
6540	dbd = 0;
6541	llba = 0;
6542	block_desc = NULL;
6543	page_index = NULL;
6544
6545	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6546
6547	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6548
6549	if (lun->be_lun->lun_type != T_DIRECT)
6550		control_dev = 1;
6551	else
6552		control_dev = 0;
6553
6554	switch (ctsio->cdb[0]) {
6555	case MODE_SENSE_6: {
6556		struct scsi_mode_sense_6 *cdb;
6557
6558		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6559
6560		header_len = sizeof(struct scsi_mode_hdr_6);
6561		if (cdb->byte2 & SMS_DBD)
6562			dbd = 1;
6563		else
6564			header_len += sizeof(struct scsi_mode_block_descr);
6565
6566		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6567		page_code = cdb->page & SMS_PAGE_CODE;
6568		subpage = cdb->subpage;
6569		alloc_len = cdb->length;
6570		break;
6571	}
6572	case MODE_SENSE_10: {
6573		struct scsi_mode_sense_10 *cdb;
6574
6575		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6576
6577		header_len = sizeof(struct scsi_mode_hdr_10);
6578
6579		if (cdb->byte2 & SMS_DBD)
6580			dbd = 1;
6581		else
6582			header_len += sizeof(struct scsi_mode_block_descr);
6583		if (cdb->byte2 & SMS10_LLBAA)
6584			llba = 1;
6585		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6586		page_code = cdb->page & SMS_PAGE_CODE;
6587		subpage = cdb->subpage;
6588		alloc_len = scsi_2btoul(cdb->length);
6589		break;
6590	}
6591	default:
6592		ctl_set_invalid_opcode(ctsio);
6593		ctl_done((union ctl_io *)ctsio);
6594		return (CTL_RETVAL_COMPLETE);
6595		break; /* NOTREACHED */
6596	}
6597
6598	/*
6599	 * We have to make a first pass through to calculate the size of
6600	 * the pages that match the user's query.  Then we allocate enough
6601	 * memory to hold it, and actually copy the data into the buffer.
6602	 */
6603	switch (page_code) {
6604	case SMS_ALL_PAGES_PAGE: {
6605		int i;
6606
6607		page_len = 0;
6608
6609		/*
6610		 * At the moment, values other than 0 and 0xff here are
6611		 * reserved according to SPC-3.
6612		 */
6613		if ((subpage != SMS_SUBPAGE_PAGE_0)
6614		 && (subpage != SMS_SUBPAGE_ALL)) {
6615			ctl_set_invalid_field(ctsio,
6616					      /*sks_valid*/ 1,
6617					      /*command*/ 1,
6618					      /*field*/ 3,
6619					      /*bit_valid*/ 0,
6620					      /*bit*/ 0);
6621			ctl_done((union ctl_io *)ctsio);
6622			return (CTL_RETVAL_COMPLETE);
6623		}
6624
6625		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6626			if ((control_dev != 0)
6627			 && (lun->mode_pages.index[i].page_flags &
6628			     CTL_PAGE_FLAG_DISK_ONLY))
6629				continue;
6630
6631			/*
6632			 * We don't use this subpage if the user didn't
6633			 * request all subpages.
6634			 */
6635			if ((lun->mode_pages.index[i].subpage != 0)
6636			 && (subpage == SMS_SUBPAGE_PAGE_0))
6637				continue;
6638
6639#if 0
6640			printf("found page %#x len %d\n",
6641			       lun->mode_pages.index[i].page_code &
6642			       SMPH_PC_MASK,
6643			       lun->mode_pages.index[i].page_len);
6644#endif
6645			page_len += lun->mode_pages.index[i].page_len;
6646		}
6647		break;
6648	}
6649	default: {
6650		int i;
6651
6652		page_len = 0;
6653
6654		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6655			/* Look for the right page code */
6656			if ((lun->mode_pages.index[i].page_code &
6657			     SMPH_PC_MASK) != page_code)
6658				continue;
6659
6660			/* Look for the right subpage or the subpage wildcard*/
6661			if ((lun->mode_pages.index[i].subpage != subpage)
6662			 && (subpage != SMS_SUBPAGE_ALL))
6663				continue;
6664
6665			/* Make sure the page is supported for this dev type */
6666			if ((control_dev != 0)
6667			 && (lun->mode_pages.index[i].page_flags &
6668			     CTL_PAGE_FLAG_DISK_ONLY))
6669				continue;
6670
6671#if 0
6672			printf("found page %#x len %d\n",
6673			       lun->mode_pages.index[i].page_code &
6674			       SMPH_PC_MASK,
6675			       lun->mode_pages.index[i].page_len);
6676#endif
6677
6678			page_len += lun->mode_pages.index[i].page_len;
6679		}
6680
6681		if (page_len == 0) {
6682			ctl_set_invalid_field(ctsio,
6683					      /*sks_valid*/ 1,
6684					      /*command*/ 1,
6685					      /*field*/ 2,
6686					      /*bit_valid*/ 1,
6687					      /*bit*/ 5);
6688			ctl_done((union ctl_io *)ctsio);
6689			return (CTL_RETVAL_COMPLETE);
6690		}
6691		break;
6692	}
6693	}
6694
6695	total_len = header_len + page_len;
6696#if 0
6697	printf("header_len = %d, page_len = %d, total_len = %d\n",
6698	       header_len, page_len, total_len);
6699#endif
6700
6701	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6702	ctsio->kern_sg_entries = 0;
6703	ctsio->kern_data_resid = 0;
6704	ctsio->kern_rel_offset = 0;
6705	if (total_len < alloc_len) {
6706		ctsio->residual = alloc_len - total_len;
6707		ctsio->kern_data_len = total_len;
6708		ctsio->kern_total_len = total_len;
6709	} else {
6710		ctsio->residual = 0;
6711		ctsio->kern_data_len = alloc_len;
6712		ctsio->kern_total_len = alloc_len;
6713	}
6714
6715	switch (ctsio->cdb[0]) {
6716	case MODE_SENSE_6: {
6717		struct scsi_mode_hdr_6 *header;
6718
6719		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6720
6721		header->datalen = MIN(total_len - 1, 254);
6722		if (control_dev == 0) {
6723			header->dev_specific = 0x10; /* DPOFUA */
6724			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6725			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6726			    .eca_and_aen & SCP_SWP) != 0)
6727				    header->dev_specific |= 0x80; /* WP */
6728		}
6729		if (dbd)
6730			header->block_descr_len = 0;
6731		else
6732			header->block_descr_len =
6733				sizeof(struct scsi_mode_block_descr);
6734		block_desc = (struct scsi_mode_block_descr *)&header[1];
6735		break;
6736	}
6737	case MODE_SENSE_10: {
6738		struct scsi_mode_hdr_10 *header;
6739		int datalen;
6740
6741		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6742
6743		datalen = MIN(total_len - 2, 65533);
6744		scsi_ulto2b(datalen, header->datalen);
6745		if (control_dev == 0) {
6746			header->dev_specific = 0x10; /* DPOFUA */
6747			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6748			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6749			    .eca_and_aen & SCP_SWP) != 0)
6750				    header->dev_specific |= 0x80; /* WP */
6751		}
6752		if (dbd)
6753			scsi_ulto2b(0, header->block_descr_len);
6754		else
6755			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6756				    header->block_descr_len);
6757		block_desc = (struct scsi_mode_block_descr *)&header[1];
6758		break;
6759	}
6760	default:
6761		panic("invalid CDB type %#x", ctsio->cdb[0]);
6762		break; /* NOTREACHED */
6763	}
6764
6765	/*
6766	 * If we've got a disk, use its blocksize in the block
6767	 * descriptor.  Otherwise, just set it to 0.
6768	 */
6769	if (dbd == 0) {
6770		if (control_dev == 0)
6771			scsi_ulto3b(lun->be_lun->blocksize,
6772				    block_desc->block_len);
6773		else
6774			scsi_ulto3b(0, block_desc->block_len);
6775	}
6776
6777	switch (page_code) {
6778	case SMS_ALL_PAGES_PAGE: {
6779		int i, data_used;
6780
6781		data_used = header_len;
6782		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6783			struct ctl_page_index *page_index;
6784
6785			page_index = &lun->mode_pages.index[i];
6786
6787			if ((control_dev != 0)
6788			 && (page_index->page_flags &
6789			    CTL_PAGE_FLAG_DISK_ONLY))
6790				continue;
6791
6792			/*
6793			 * We don't use this subpage if the user didn't
6794			 * request all subpages.  We already checked (above)
6795			 * to make sure the user only specified a subpage
6796			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6797			 */
6798			if ((page_index->subpage != 0)
6799			 && (subpage == SMS_SUBPAGE_PAGE_0))
6800				continue;
6801
6802			/*
6803			 * Call the handler, if it exists, to update the
6804			 * page to the latest values.
6805			 */
6806			if (page_index->sense_handler != NULL)
6807				page_index->sense_handler(ctsio, page_index,pc);
6808
6809			memcpy(ctsio->kern_data_ptr + data_used,
6810			       page_index->page_data +
6811			       (page_index->page_len * pc),
6812			       page_index->page_len);
6813			data_used += page_index->page_len;
6814		}
6815		break;
6816	}
6817	default: {
6818		int i, data_used;
6819
6820		data_used = header_len;
6821
6822		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6823			struct ctl_page_index *page_index;
6824
6825			page_index = &lun->mode_pages.index[i];
6826
6827			/* Look for the right page code */
6828			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6829				continue;
6830
6831			/* Look for the right subpage or the subpage wildcard*/
6832			if ((page_index->subpage != subpage)
6833			 && (subpage != SMS_SUBPAGE_ALL))
6834				continue;
6835
6836			/* Make sure the page is supported for this dev type */
6837			if ((control_dev != 0)
6838			 && (page_index->page_flags &
6839			     CTL_PAGE_FLAG_DISK_ONLY))
6840				continue;
6841
6842			/*
6843			 * Call the handler, if it exists, to update the
6844			 * page to the latest values.
6845			 */
6846			if (page_index->sense_handler != NULL)
6847				page_index->sense_handler(ctsio, page_index,pc);
6848
6849			memcpy(ctsio->kern_data_ptr + data_used,
6850			       page_index->page_data +
6851			       (page_index->page_len * pc),
6852			       page_index->page_len);
6853			data_used += page_index->page_len;
6854		}
6855		break;
6856	}
6857	}
6858
6859	ctl_set_success(ctsio);
6860	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6861	ctsio->be_move_done = ctl_config_move_done;
6862	ctl_datamove((union ctl_io *)ctsio);
6863	return (CTL_RETVAL_COMPLETE);
6864}
6865
6866int
6867ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6868			       struct ctl_page_index *page_index,
6869			       int pc)
6870{
6871	struct ctl_lun *lun;
6872	struct scsi_log_param_header *phdr;
6873	uint8_t *data;
6874	uint64_t val;
6875
6876	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6877	data = page_index->page_data;
6878
6879	if (lun->backend->lun_attr != NULL &&
6880	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6881	     != UINT64_MAX) {
6882		phdr = (struct scsi_log_param_header *)data;
6883		scsi_ulto2b(0x0001, phdr->param_code);
6884		phdr->param_control = SLP_LBIN | SLP_LP;
6885		phdr->param_len = 8;
6886		data = (uint8_t *)(phdr + 1);
6887		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6888		data[4] = 0x02; /* per-pool */
6889		data += phdr->param_len;
6890	}
6891
6892	if (lun->backend->lun_attr != NULL &&
6893	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6894	     != UINT64_MAX) {
6895		phdr = (struct scsi_log_param_header *)data;
6896		scsi_ulto2b(0x0002, phdr->param_code);
6897		phdr->param_control = SLP_LBIN | SLP_LP;
6898		phdr->param_len = 8;
6899		data = (uint8_t *)(phdr + 1);
6900		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6901		data[4] = 0x01; /* per-LUN */
6902		data += phdr->param_len;
6903	}
6904
6905	if (lun->backend->lun_attr != NULL &&
6906	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6907	     != UINT64_MAX) {
6908		phdr = (struct scsi_log_param_header *)data;
6909		scsi_ulto2b(0x00f1, phdr->param_code);
6910		phdr->param_control = SLP_LBIN | SLP_LP;
6911		phdr->param_len = 8;
6912		data = (uint8_t *)(phdr + 1);
6913		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6914		data[4] = 0x02; /* per-pool */
6915		data += phdr->param_len;
6916	}
6917
6918	if (lun->backend->lun_attr != NULL &&
6919	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6920	     != UINT64_MAX) {
6921		phdr = (struct scsi_log_param_header *)data;
6922		scsi_ulto2b(0x00f2, phdr->param_code);
6923		phdr->param_control = SLP_LBIN | SLP_LP;
6924		phdr->param_len = 8;
6925		data = (uint8_t *)(phdr + 1);
6926		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6927		data[4] = 0x02; /* per-pool */
6928		data += phdr->param_len;
6929	}
6930
6931	page_index->page_len = data - page_index->page_data;
6932	return (0);
6933}
6934
6935int
6936ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6937			       struct ctl_page_index *page_index,
6938			       int pc)
6939{
6940	struct ctl_lun *lun;
6941	struct stat_page *data;
6942	uint64_t rn, wn, rb, wb;
6943	struct bintime rt, wt;
6944	int i;
6945
6946	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6947	data = (struct stat_page *)page_index->page_data;
6948
6949	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6950	data->sap.hdr.param_control = SLP_LBIN;
6951	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6952	    sizeof(struct scsi_log_param_header);
6953	rn = wn = rb = wb = 0;
6954	bintime_clear(&rt);
6955	bintime_clear(&wt);
6956	for (i = 0; i < CTL_MAX_PORTS; i++) {
6957		rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6958		wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6959		rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6960		wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6961		bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6962		bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6963	}
6964	scsi_u64to8b(rn, data->sap.read_num);
6965	scsi_u64to8b(wn, data->sap.write_num);
6966	if (lun->stats.blocksize > 0) {
6967		scsi_u64to8b(wb / lun->stats.blocksize,
6968		    data->sap.recvieved_lba);
6969		scsi_u64to8b(rb / lun->stats.blocksize,
6970		    data->sap.transmitted_lba);
6971	}
6972	scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6973	    data->sap.read_int);
6974	scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6975	    data->sap.write_int);
6976	scsi_u64to8b(0, data->sap.weighted_num);
6977	scsi_u64to8b(0, data->sap.weighted_int);
6978	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6979	data->it.hdr.param_control = SLP_LBIN;
6980	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6981	    sizeof(struct scsi_log_param_header);
6982#ifdef CTL_TIME_IO
6983	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6984#endif
6985	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6986	data->it.hdr.param_control = SLP_LBIN;
6987	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6988	    sizeof(struct scsi_log_param_header);
6989	scsi_ulto4b(3, data->ti.exponent);
6990	scsi_ulto4b(1, data->ti.integer);
6991
6992	page_index->page_len = sizeof(*data);
6993	return (0);
6994}
6995
6996int
6997ctl_log_sense(struct ctl_scsiio *ctsio)
6998{
6999	struct ctl_lun *lun;
7000	int i, pc, page_code, subpage;
7001	int alloc_len, total_len;
7002	struct ctl_page_index *page_index;
7003	struct scsi_log_sense *cdb;
7004	struct scsi_log_header *header;
7005
7006	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
7007
7008	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7009	cdb = (struct scsi_log_sense *)ctsio->cdb;
7010	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
7011	page_code = cdb->page & SLS_PAGE_CODE;
7012	subpage = cdb->subpage;
7013	alloc_len = scsi_2btoul(cdb->length);
7014
7015	page_index = NULL;
7016	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
7017		page_index = &lun->log_pages.index[i];
7018
7019		/* Look for the right page code */
7020		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
7021			continue;
7022
7023		/* Look for the right subpage or the subpage wildcard*/
7024		if (page_index->subpage != subpage)
7025			continue;
7026
7027		break;
7028	}
7029	if (i >= CTL_NUM_LOG_PAGES) {
7030		ctl_set_invalid_field(ctsio,
7031				      /*sks_valid*/ 1,
7032				      /*command*/ 1,
7033				      /*field*/ 2,
7034				      /*bit_valid*/ 0,
7035				      /*bit*/ 0);
7036		ctl_done((union ctl_io *)ctsio);
7037		return (CTL_RETVAL_COMPLETE);
7038	}
7039
7040	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
7041
7042	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7043	ctsio->kern_sg_entries = 0;
7044	ctsio->kern_data_resid = 0;
7045	ctsio->kern_rel_offset = 0;
7046	if (total_len < alloc_len) {
7047		ctsio->residual = alloc_len - total_len;
7048		ctsio->kern_data_len = total_len;
7049		ctsio->kern_total_len = total_len;
7050	} else {
7051		ctsio->residual = 0;
7052		ctsio->kern_data_len = alloc_len;
7053		ctsio->kern_total_len = alloc_len;
7054	}
7055
7056	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7057	header->page = page_index->page_code;
7058	if (page_index->subpage) {
7059		header->page |= SL_SPF;
7060		header->subpage = page_index->subpage;
7061	}
7062	scsi_ulto2b(page_index->page_len, header->datalen);
7063
7064	/*
7065	 * Call the handler, if it exists, to update the
7066	 * page to the latest values.
7067	 */
7068	if (page_index->sense_handler != NULL)
7069		page_index->sense_handler(ctsio, page_index, pc);
7070
7071	memcpy(header + 1, page_index->page_data, page_index->page_len);
7072
7073	ctl_set_success(ctsio);
7074	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7075	ctsio->be_move_done = ctl_config_move_done;
7076	ctl_datamove((union ctl_io *)ctsio);
7077	return (CTL_RETVAL_COMPLETE);
7078}
7079
7080int
7081ctl_read_capacity(struct ctl_scsiio *ctsio)
7082{
7083	struct scsi_read_capacity *cdb;
7084	struct scsi_read_capacity_data *data;
7085	struct ctl_lun *lun;
7086	uint32_t lba;
7087
7088	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7089
7090	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7091
7092	lba = scsi_4btoul(cdb->addr);
7093	if (((cdb->pmi & SRC_PMI) == 0)
7094	 && (lba != 0)) {
7095		ctl_set_invalid_field(/*ctsio*/ ctsio,
7096				      /*sks_valid*/ 1,
7097				      /*command*/ 1,
7098				      /*field*/ 2,
7099				      /*bit_valid*/ 0,
7100				      /*bit*/ 0);
7101		ctl_done((union ctl_io *)ctsio);
7102		return (CTL_RETVAL_COMPLETE);
7103	}
7104
7105	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7106
7107	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7108	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7109	ctsio->residual = 0;
7110	ctsio->kern_data_len = sizeof(*data);
7111	ctsio->kern_total_len = sizeof(*data);
7112	ctsio->kern_data_resid = 0;
7113	ctsio->kern_rel_offset = 0;
7114	ctsio->kern_sg_entries = 0;
7115
7116	/*
7117	 * If the maximum LBA is greater than 0xfffffffe, the user must
7118	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7119	 * serivce action set.
7120	 */
7121	if (lun->be_lun->maxlba > 0xfffffffe)
7122		scsi_ulto4b(0xffffffff, data->addr);
7123	else
7124		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7125
7126	/*
7127	 * XXX KDM this may not be 512 bytes...
7128	 */
7129	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7130
7131	ctl_set_success(ctsio);
7132	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7133	ctsio->be_move_done = ctl_config_move_done;
7134	ctl_datamove((union ctl_io *)ctsio);
7135	return (CTL_RETVAL_COMPLETE);
7136}
7137
7138int
7139ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7140{
7141	struct scsi_read_capacity_16 *cdb;
7142	struct scsi_read_capacity_data_long *data;
7143	struct ctl_lun *lun;
7144	uint64_t lba;
7145	uint32_t alloc_len;
7146
7147	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7148
7149	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7150
7151	alloc_len = scsi_4btoul(cdb->alloc_len);
7152	lba = scsi_8btou64(cdb->addr);
7153
7154	if ((cdb->reladr & SRC16_PMI)
7155	 && (lba != 0)) {
7156		ctl_set_invalid_field(/*ctsio*/ ctsio,
7157				      /*sks_valid*/ 1,
7158				      /*command*/ 1,
7159				      /*field*/ 2,
7160				      /*bit_valid*/ 0,
7161				      /*bit*/ 0);
7162		ctl_done((union ctl_io *)ctsio);
7163		return (CTL_RETVAL_COMPLETE);
7164	}
7165
7166	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7167
7168	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7169	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7170
7171	if (sizeof(*data) < alloc_len) {
7172		ctsio->residual = alloc_len - sizeof(*data);
7173		ctsio->kern_data_len = sizeof(*data);
7174		ctsio->kern_total_len = sizeof(*data);
7175	} else {
7176		ctsio->residual = 0;
7177		ctsio->kern_data_len = alloc_len;
7178		ctsio->kern_total_len = alloc_len;
7179	}
7180	ctsio->kern_data_resid = 0;
7181	ctsio->kern_rel_offset = 0;
7182	ctsio->kern_sg_entries = 0;
7183
7184	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7185	/* XXX KDM this may not be 512 bytes... */
7186	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7187	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7188	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7189	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7190		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7191
7192	ctl_set_success(ctsio);
7193	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7194	ctsio->be_move_done = ctl_config_move_done;
7195	ctl_datamove((union ctl_io *)ctsio);
7196	return (CTL_RETVAL_COMPLETE);
7197}
7198
7199int
7200ctl_get_lba_status(struct ctl_scsiio *ctsio)
7201{
7202	struct scsi_get_lba_status *cdb;
7203	struct scsi_get_lba_status_data *data;
7204	struct ctl_lun *lun;
7205	struct ctl_lba_len_flags *lbalen;
7206	uint64_t lba;
7207	uint32_t alloc_len, total_len;
7208	int retval;
7209
7210	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7211
7212	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7213	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7214	lba = scsi_8btou64(cdb->addr);
7215	alloc_len = scsi_4btoul(cdb->alloc_len);
7216
7217	if (lba > lun->be_lun->maxlba) {
7218		ctl_set_lba_out_of_range(ctsio);
7219		ctl_done((union ctl_io *)ctsio);
7220		return (CTL_RETVAL_COMPLETE);
7221	}
7222
7223	total_len = sizeof(*data) + sizeof(data->descr[0]);
7224	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7225	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7226
7227	if (total_len < alloc_len) {
7228		ctsio->residual = alloc_len - total_len;
7229		ctsio->kern_data_len = total_len;
7230		ctsio->kern_total_len = total_len;
7231	} else {
7232		ctsio->residual = 0;
7233		ctsio->kern_data_len = alloc_len;
7234		ctsio->kern_total_len = alloc_len;
7235	}
7236	ctsio->kern_data_resid = 0;
7237	ctsio->kern_rel_offset = 0;
7238	ctsio->kern_sg_entries = 0;
7239
7240	/* Fill dummy data in case backend can't tell anything. */
7241	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7242	scsi_u64to8b(lba, data->descr[0].addr);
7243	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7244	    data->descr[0].length);
7245	data->descr[0].status = 0; /* Mapped or unknown. */
7246
7247	ctl_set_success(ctsio);
7248	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7249	ctsio->be_move_done = ctl_config_move_done;
7250
7251	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7252	lbalen->lba = lba;
7253	lbalen->len = total_len;
7254	lbalen->flags = 0;
7255	retval = lun->backend->config_read((union ctl_io *)ctsio);
7256	return (CTL_RETVAL_COMPLETE);
7257}
7258
7259int
7260ctl_read_defect(struct ctl_scsiio *ctsio)
7261{
7262	struct scsi_read_defect_data_10 *ccb10;
7263	struct scsi_read_defect_data_12 *ccb12;
7264	struct scsi_read_defect_data_hdr_10 *data10;
7265	struct scsi_read_defect_data_hdr_12 *data12;
7266	uint32_t alloc_len, data_len;
7267	uint8_t format;
7268
7269	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7270
7271	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7272		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7273		format = ccb10->format;
7274		alloc_len = scsi_2btoul(ccb10->alloc_length);
7275		data_len = sizeof(*data10);
7276	} else {
7277		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7278		format = ccb12->format;
7279		alloc_len = scsi_4btoul(ccb12->alloc_length);
7280		data_len = sizeof(*data12);
7281	}
7282	if (alloc_len == 0) {
7283		ctl_set_success(ctsio);
7284		ctl_done((union ctl_io *)ctsio);
7285		return (CTL_RETVAL_COMPLETE);
7286	}
7287
7288	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7289	if (data_len < alloc_len) {
7290		ctsio->residual = alloc_len - data_len;
7291		ctsio->kern_data_len = data_len;
7292		ctsio->kern_total_len = data_len;
7293	} else {
7294		ctsio->residual = 0;
7295		ctsio->kern_data_len = alloc_len;
7296		ctsio->kern_total_len = alloc_len;
7297	}
7298	ctsio->kern_data_resid = 0;
7299	ctsio->kern_rel_offset = 0;
7300	ctsio->kern_sg_entries = 0;
7301
7302	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7303		data10 = (struct scsi_read_defect_data_hdr_10 *)
7304		    ctsio->kern_data_ptr;
7305		data10->format = format;
7306		scsi_ulto2b(0, data10->length);
7307	} else {
7308		data12 = (struct scsi_read_defect_data_hdr_12 *)
7309		    ctsio->kern_data_ptr;
7310		data12->format = format;
7311		scsi_ulto2b(0, data12->generation);
7312		scsi_ulto4b(0, data12->length);
7313	}
7314
7315	ctl_set_success(ctsio);
7316	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7317	ctsio->be_move_done = ctl_config_move_done;
7318	ctl_datamove((union ctl_io *)ctsio);
7319	return (CTL_RETVAL_COMPLETE);
7320}
7321
7322int
7323ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7324{
7325	struct scsi_maintenance_in *cdb;
7326	int retval;
7327	int alloc_len, ext, total_len = 0, g, pc, pg, gs, os;
7328	int num_target_port_groups, num_target_ports;
7329	struct ctl_lun *lun;
7330	struct ctl_softc *softc;
7331	struct ctl_port *port;
7332	struct scsi_target_group_data *rtg_ptr;
7333	struct scsi_target_group_data_extended *rtg_ext_ptr;
7334	struct scsi_target_port_group_descriptor *tpg_desc;
7335
7336	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7337
7338	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7339	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7340	softc = lun->ctl_softc;
7341
7342	retval = CTL_RETVAL_COMPLETE;
7343
7344	switch (cdb->byte2 & STG_PDF_MASK) {
7345	case STG_PDF_LENGTH:
7346		ext = 0;
7347		break;
7348	case STG_PDF_EXTENDED:
7349		ext = 1;
7350		break;
7351	default:
7352		ctl_set_invalid_field(/*ctsio*/ ctsio,
7353				      /*sks_valid*/ 1,
7354				      /*command*/ 1,
7355				      /*field*/ 2,
7356				      /*bit_valid*/ 1,
7357				      /*bit*/ 5);
7358		ctl_done((union ctl_io *)ctsio);
7359		return(retval);
7360	}
7361
7362	if (softc->is_single)
7363		num_target_port_groups = 1;
7364	else
7365		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7366	num_target_ports = 0;
7367	mtx_lock(&softc->ctl_lock);
7368	STAILQ_FOREACH(port, &softc->port_list, links) {
7369		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7370			continue;
7371		if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7372			continue;
7373		num_target_ports++;
7374	}
7375	mtx_unlock(&softc->ctl_lock);
7376
7377	if (ext)
7378		total_len = sizeof(struct scsi_target_group_data_extended);
7379	else
7380		total_len = sizeof(struct scsi_target_group_data);
7381	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7382		num_target_port_groups +
7383	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7384
7385	alloc_len = scsi_4btoul(cdb->length);
7386
7387	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7388
7389	ctsio->kern_sg_entries = 0;
7390
7391	if (total_len < alloc_len) {
7392		ctsio->residual = alloc_len - total_len;
7393		ctsio->kern_data_len = total_len;
7394		ctsio->kern_total_len = total_len;
7395	} else {
7396		ctsio->residual = 0;
7397		ctsio->kern_data_len = alloc_len;
7398		ctsio->kern_total_len = alloc_len;
7399	}
7400	ctsio->kern_data_resid = 0;
7401	ctsio->kern_rel_offset = 0;
7402
7403	if (ext) {
7404		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7405		    ctsio->kern_data_ptr;
7406		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7407		rtg_ext_ptr->format_type = 0x10;
7408		rtg_ext_ptr->implicit_transition_time = 0;
7409		tpg_desc = &rtg_ext_ptr->groups[0];
7410	} else {
7411		rtg_ptr = (struct scsi_target_group_data *)
7412		    ctsio->kern_data_ptr;
7413		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7414		tpg_desc = &rtg_ptr->groups[0];
7415	}
7416
7417	mtx_lock(&softc->ctl_lock);
7418	pg = softc->port_min / softc->port_cnt;
7419	if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7420		gs = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7421	else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7422		gs = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7423	else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7424		gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7425	else
7426		gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7427	if (lun->flags & CTL_LUN_PRIMARY_SC) {
7428		os = gs;
7429		gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7430	} else
7431		os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7432	for (g = 0; g < num_target_port_groups; g++) {
7433		tpg_desc->pref_state = (g == pg) ? gs : os;
7434		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7435		    TPG_U_SUP | TPG_T_SUP;
7436		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7437		tpg_desc->status = TPG_IMPLICIT;
7438		pc = 0;
7439		STAILQ_FOREACH(port, &softc->port_list, links) {
7440			if (port->targ_port < g * softc->port_cnt ||
7441			    port->targ_port >= (g + 1) * softc->port_cnt)
7442				continue;
7443			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7444				continue;
7445			if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7446				continue;
7447			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7448			    relative_target_port_identifier);
7449			pc++;
7450		}
7451		tpg_desc->target_port_count = pc;
7452		tpg_desc = (struct scsi_target_port_group_descriptor *)
7453		    &tpg_desc->descriptors[pc];
7454	}
7455	mtx_unlock(&softc->ctl_lock);
7456
7457	ctl_set_success(ctsio);
7458	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7459	ctsio->be_move_done = ctl_config_move_done;
7460	ctl_datamove((union ctl_io *)ctsio);
7461	return(retval);
7462}
7463
7464int
7465ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7466{
7467	struct ctl_lun *lun;
7468	struct scsi_report_supported_opcodes *cdb;
7469	const struct ctl_cmd_entry *entry, *sentry;
7470	struct scsi_report_supported_opcodes_all *all;
7471	struct scsi_report_supported_opcodes_descr *descr;
7472	struct scsi_report_supported_opcodes_one *one;
7473	int retval;
7474	int alloc_len, total_len;
7475	int opcode, service_action, i, j, num;
7476
7477	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7478
7479	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7480	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7481
7482	retval = CTL_RETVAL_COMPLETE;
7483
7484	opcode = cdb->requested_opcode;
7485	service_action = scsi_2btoul(cdb->requested_service_action);
7486	switch (cdb->options & RSO_OPTIONS_MASK) {
7487	case RSO_OPTIONS_ALL:
7488		num = 0;
7489		for (i = 0; i < 256; i++) {
7490			entry = &ctl_cmd_table[i];
7491			if (entry->flags & CTL_CMD_FLAG_SA5) {
7492				for (j = 0; j < 32; j++) {
7493					sentry = &((const struct ctl_cmd_entry *)
7494					    entry->execute)[j];
7495					if (ctl_cmd_applicable(
7496					    lun->be_lun->lun_type, sentry))
7497						num++;
7498				}
7499			} else {
7500				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7501				    entry))
7502					num++;
7503			}
7504		}
7505		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7506		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7507		break;
7508	case RSO_OPTIONS_OC:
7509		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7510			ctl_set_invalid_field(/*ctsio*/ ctsio,
7511					      /*sks_valid*/ 1,
7512					      /*command*/ 1,
7513					      /*field*/ 2,
7514					      /*bit_valid*/ 1,
7515					      /*bit*/ 2);
7516			ctl_done((union ctl_io *)ctsio);
7517			return (CTL_RETVAL_COMPLETE);
7518		}
7519		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7520		break;
7521	case RSO_OPTIONS_OC_SA:
7522		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7523		    service_action >= 32) {
7524			ctl_set_invalid_field(/*ctsio*/ ctsio,
7525					      /*sks_valid*/ 1,
7526					      /*command*/ 1,
7527					      /*field*/ 2,
7528					      /*bit_valid*/ 1,
7529					      /*bit*/ 2);
7530			ctl_done((union ctl_io *)ctsio);
7531			return (CTL_RETVAL_COMPLETE);
7532		}
7533		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7534		break;
7535	default:
7536		ctl_set_invalid_field(/*ctsio*/ ctsio,
7537				      /*sks_valid*/ 1,
7538				      /*command*/ 1,
7539				      /*field*/ 2,
7540				      /*bit_valid*/ 1,
7541				      /*bit*/ 2);
7542		ctl_done((union ctl_io *)ctsio);
7543		return (CTL_RETVAL_COMPLETE);
7544	}
7545
7546	alloc_len = scsi_4btoul(cdb->length);
7547
7548	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7549
7550	ctsio->kern_sg_entries = 0;
7551
7552	if (total_len < alloc_len) {
7553		ctsio->residual = alloc_len - total_len;
7554		ctsio->kern_data_len = total_len;
7555		ctsio->kern_total_len = total_len;
7556	} else {
7557		ctsio->residual = 0;
7558		ctsio->kern_data_len = alloc_len;
7559		ctsio->kern_total_len = alloc_len;
7560	}
7561	ctsio->kern_data_resid = 0;
7562	ctsio->kern_rel_offset = 0;
7563
7564	switch (cdb->options & RSO_OPTIONS_MASK) {
7565	case RSO_OPTIONS_ALL:
7566		all = (struct scsi_report_supported_opcodes_all *)
7567		    ctsio->kern_data_ptr;
7568		num = 0;
7569		for (i = 0; i < 256; i++) {
7570			entry = &ctl_cmd_table[i];
7571			if (entry->flags & CTL_CMD_FLAG_SA5) {
7572				for (j = 0; j < 32; j++) {
7573					sentry = &((const struct ctl_cmd_entry *)
7574					    entry->execute)[j];
7575					if (!ctl_cmd_applicable(
7576					    lun->be_lun->lun_type, sentry))
7577						continue;
7578					descr = &all->descr[num++];
7579					descr->opcode = i;
7580					scsi_ulto2b(j, descr->service_action);
7581					descr->flags = RSO_SERVACTV;
7582					scsi_ulto2b(sentry->length,
7583					    descr->cdb_length);
7584				}
7585			} else {
7586				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7587				    entry))
7588					continue;
7589				descr = &all->descr[num++];
7590				descr->opcode = i;
7591				scsi_ulto2b(0, descr->service_action);
7592				descr->flags = 0;
7593				scsi_ulto2b(entry->length, descr->cdb_length);
7594			}
7595		}
7596		scsi_ulto4b(
7597		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7598		    all->length);
7599		break;
7600	case RSO_OPTIONS_OC:
7601		one = (struct scsi_report_supported_opcodes_one *)
7602		    ctsio->kern_data_ptr;
7603		entry = &ctl_cmd_table[opcode];
7604		goto fill_one;
7605	case RSO_OPTIONS_OC_SA:
7606		one = (struct scsi_report_supported_opcodes_one *)
7607		    ctsio->kern_data_ptr;
7608		entry = &ctl_cmd_table[opcode];
7609		entry = &((const struct ctl_cmd_entry *)
7610		    entry->execute)[service_action];
7611fill_one:
7612		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7613			one->support = 3;
7614			scsi_ulto2b(entry->length, one->cdb_length);
7615			one->cdb_usage[0] = opcode;
7616			memcpy(&one->cdb_usage[1], entry->usage,
7617			    entry->length - 1);
7618		} else
7619			one->support = 1;
7620		break;
7621	}
7622
7623	ctl_set_success(ctsio);
7624	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7625	ctsio->be_move_done = ctl_config_move_done;
7626	ctl_datamove((union ctl_io *)ctsio);
7627	return(retval);
7628}
7629
7630int
7631ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7632{
7633	struct scsi_report_supported_tmf *cdb;
7634	struct scsi_report_supported_tmf_data *data;
7635	int retval;
7636	int alloc_len, total_len;
7637
7638	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7639
7640	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7641
7642	retval = CTL_RETVAL_COMPLETE;
7643
7644	total_len = sizeof(struct scsi_report_supported_tmf_data);
7645	alloc_len = scsi_4btoul(cdb->length);
7646
7647	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7648
7649	ctsio->kern_sg_entries = 0;
7650
7651	if (total_len < alloc_len) {
7652		ctsio->residual = alloc_len - total_len;
7653		ctsio->kern_data_len = total_len;
7654		ctsio->kern_total_len = total_len;
7655	} else {
7656		ctsio->residual = 0;
7657		ctsio->kern_data_len = alloc_len;
7658		ctsio->kern_total_len = alloc_len;
7659	}
7660	ctsio->kern_data_resid = 0;
7661	ctsio->kern_rel_offset = 0;
7662
7663	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7664	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7665	    RST_TRS;
7666	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7667
7668	ctl_set_success(ctsio);
7669	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7670	ctsio->be_move_done = ctl_config_move_done;
7671	ctl_datamove((union ctl_io *)ctsio);
7672	return (retval);
7673}
7674
7675int
7676ctl_report_timestamp(struct ctl_scsiio *ctsio)
7677{
7678	struct scsi_report_timestamp *cdb;
7679	struct scsi_report_timestamp_data *data;
7680	struct timeval tv;
7681	int64_t timestamp;
7682	int retval;
7683	int alloc_len, total_len;
7684
7685	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7686
7687	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7688
7689	retval = CTL_RETVAL_COMPLETE;
7690
7691	total_len = sizeof(struct scsi_report_timestamp_data);
7692	alloc_len = scsi_4btoul(cdb->length);
7693
7694	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7695
7696	ctsio->kern_sg_entries = 0;
7697
7698	if (total_len < alloc_len) {
7699		ctsio->residual = alloc_len - total_len;
7700		ctsio->kern_data_len = total_len;
7701		ctsio->kern_total_len = total_len;
7702	} else {
7703		ctsio->residual = 0;
7704		ctsio->kern_data_len = alloc_len;
7705		ctsio->kern_total_len = alloc_len;
7706	}
7707	ctsio->kern_data_resid = 0;
7708	ctsio->kern_rel_offset = 0;
7709
7710	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7711	scsi_ulto2b(sizeof(*data) - 2, data->length);
7712	data->origin = RTS_ORIG_OUTSIDE;
7713	getmicrotime(&tv);
7714	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7715	scsi_ulto4b(timestamp >> 16, data->timestamp);
7716	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7717
7718	ctl_set_success(ctsio);
7719	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7720	ctsio->be_move_done = ctl_config_move_done;
7721	ctl_datamove((union ctl_io *)ctsio);
7722	return (retval);
7723}
7724
7725int
7726ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7727{
7728	struct scsi_per_res_in *cdb;
7729	int alloc_len, total_len = 0;
7730	/* struct scsi_per_res_in_rsrv in_data; */
7731	struct ctl_lun *lun;
7732	struct ctl_softc *softc;
7733	uint64_t key;
7734
7735	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7736
7737	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7738
7739	alloc_len = scsi_2btoul(cdb->length);
7740
7741	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7742	softc = lun->ctl_softc;
7743
7744retry:
7745	mtx_lock(&lun->lun_lock);
7746	switch (cdb->action) {
7747	case SPRI_RK: /* read keys */
7748		total_len = sizeof(struct scsi_per_res_in_keys) +
7749			lun->pr_key_count *
7750			sizeof(struct scsi_per_res_key);
7751		break;
7752	case SPRI_RR: /* read reservation */
7753		if (lun->flags & CTL_LUN_PR_RESERVED)
7754			total_len = sizeof(struct scsi_per_res_in_rsrv);
7755		else
7756			total_len = sizeof(struct scsi_per_res_in_header);
7757		break;
7758	case SPRI_RC: /* report capabilities */
7759		total_len = sizeof(struct scsi_per_res_cap);
7760		break;
7761	case SPRI_RS: /* read full status */
7762		total_len = sizeof(struct scsi_per_res_in_header) +
7763		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7764		    lun->pr_key_count;
7765		break;
7766	default:
7767		panic("Invalid PR type %x", cdb->action);
7768	}
7769	mtx_unlock(&lun->lun_lock);
7770
7771	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7772
7773	if (total_len < alloc_len) {
7774		ctsio->residual = alloc_len - total_len;
7775		ctsio->kern_data_len = total_len;
7776		ctsio->kern_total_len = total_len;
7777	} else {
7778		ctsio->residual = 0;
7779		ctsio->kern_data_len = alloc_len;
7780		ctsio->kern_total_len = alloc_len;
7781	}
7782
7783	ctsio->kern_data_resid = 0;
7784	ctsio->kern_rel_offset = 0;
7785	ctsio->kern_sg_entries = 0;
7786
7787	mtx_lock(&lun->lun_lock);
7788	switch (cdb->action) {
7789	case SPRI_RK: { // read keys
7790        struct scsi_per_res_in_keys *res_keys;
7791		int i, key_count;
7792
7793		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7794
7795		/*
7796		 * We had to drop the lock to allocate our buffer, which
7797		 * leaves time for someone to come in with another
7798		 * persistent reservation.  (That is unlikely, though,
7799		 * since this should be the only persistent reservation
7800		 * command active right now.)
7801		 */
7802		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7803		    (lun->pr_key_count *
7804		     sizeof(struct scsi_per_res_key)))){
7805			mtx_unlock(&lun->lun_lock);
7806			free(ctsio->kern_data_ptr, M_CTL);
7807			printf("%s: reservation length changed, retrying\n",
7808			       __func__);
7809			goto retry;
7810		}
7811
7812		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7813
7814		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7815			     lun->pr_key_count, res_keys->header.length);
7816
7817		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7818			if ((key = ctl_get_prkey(lun, i)) == 0)
7819				continue;
7820
7821			/*
7822			 * We used lun->pr_key_count to calculate the
7823			 * size to allocate.  If it turns out the number of
7824			 * initiators with the registered flag set is
7825			 * larger than that (i.e. they haven't been kept in
7826			 * sync), we've got a problem.
7827			 */
7828			if (key_count >= lun->pr_key_count) {
7829#ifdef NEEDTOPORT
7830				csevent_log(CSC_CTL | CSC_SHELF_SW |
7831					    CTL_PR_ERROR,
7832					    csevent_LogType_Fault,
7833					    csevent_AlertLevel_Yellow,
7834					    csevent_FRU_ShelfController,
7835					    csevent_FRU_Firmware,
7836				        csevent_FRU_Unknown,
7837					    "registered keys %d >= key "
7838					    "count %d", key_count,
7839					    lun->pr_key_count);
7840#endif
7841				key_count++;
7842				continue;
7843			}
7844			scsi_u64to8b(key, res_keys->keys[key_count].key);
7845			key_count++;
7846		}
7847		break;
7848	}
7849	case SPRI_RR: { // read reservation
7850		struct scsi_per_res_in_rsrv *res;
7851		int tmp_len, header_only;
7852
7853		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7854
7855		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7856
7857		if (lun->flags & CTL_LUN_PR_RESERVED)
7858		{
7859			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7860			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7861				    res->header.length);
7862			header_only = 0;
7863		} else {
7864			tmp_len = sizeof(struct scsi_per_res_in_header);
7865			scsi_ulto4b(0, res->header.length);
7866			header_only = 1;
7867		}
7868
7869		/*
7870		 * We had to drop the lock to allocate our buffer, which
7871		 * leaves time for someone to come in with another
7872		 * persistent reservation.  (That is unlikely, though,
7873		 * since this should be the only persistent reservation
7874		 * command active right now.)
7875		 */
7876		if (tmp_len != total_len) {
7877			mtx_unlock(&lun->lun_lock);
7878			free(ctsio->kern_data_ptr, M_CTL);
7879			printf("%s: reservation status changed, retrying\n",
7880			       __func__);
7881			goto retry;
7882		}
7883
7884		/*
7885		 * No reservation held, so we're done.
7886		 */
7887		if (header_only != 0)
7888			break;
7889
7890		/*
7891		 * If the registration is an All Registrants type, the key
7892		 * is 0, since it doesn't really matter.
7893		 */
7894		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7895			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7896			    res->data.reservation);
7897		}
7898		res->data.scopetype = lun->res_type;
7899		break;
7900	}
7901	case SPRI_RC:     //report capabilities
7902	{
7903		struct scsi_per_res_cap *res_cap;
7904		uint16_t type_mask;
7905
7906		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7907		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7908		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7909		type_mask = SPRI_TM_WR_EX_AR |
7910			    SPRI_TM_EX_AC_RO |
7911			    SPRI_TM_WR_EX_RO |
7912			    SPRI_TM_EX_AC |
7913			    SPRI_TM_WR_EX |
7914			    SPRI_TM_EX_AC_AR;
7915		scsi_ulto2b(type_mask, res_cap->type_mask);
7916		break;
7917	}
7918	case SPRI_RS: { // read full status
7919		struct scsi_per_res_in_full *res_status;
7920		struct scsi_per_res_in_full_desc *res_desc;
7921		struct ctl_port *port;
7922		int i, len;
7923
7924		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7925
7926		/*
7927		 * We had to drop the lock to allocate our buffer, which
7928		 * leaves time for someone to come in with another
7929		 * persistent reservation.  (That is unlikely, though,
7930		 * since this should be the only persistent reservation
7931		 * command active right now.)
7932		 */
7933		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7934		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7935		     lun->pr_key_count)){
7936			mtx_unlock(&lun->lun_lock);
7937			free(ctsio->kern_data_ptr, M_CTL);
7938			printf("%s: reservation length changed, retrying\n",
7939			       __func__);
7940			goto retry;
7941		}
7942
7943		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7944
7945		res_desc = &res_status->desc[0];
7946		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7947			if ((key = ctl_get_prkey(lun, i)) == 0)
7948				continue;
7949
7950			scsi_u64to8b(key, res_desc->res_key.key);
7951			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7952			    (lun->pr_res_idx == i ||
7953			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7954				res_desc->flags = SPRI_FULL_R_HOLDER;
7955				res_desc->scopetype = lun->res_type;
7956			}
7957			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7958			    res_desc->rel_trgt_port_id);
7959			len = 0;
7960			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7961			if (port != NULL)
7962				len = ctl_create_iid(port,
7963				    i % CTL_MAX_INIT_PER_PORT,
7964				    res_desc->transport_id);
7965			scsi_ulto4b(len, res_desc->additional_length);
7966			res_desc = (struct scsi_per_res_in_full_desc *)
7967			    &res_desc->transport_id[len];
7968		}
7969		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7970		    res_status->header.length);
7971		break;
7972	}
7973	default:
7974		/*
7975		 * This is a bug, because we just checked for this above,
7976		 * and should have returned an error.
7977		 */
7978		panic("Invalid PR type %x", cdb->action);
7979		break; /* NOTREACHED */
7980	}
7981	mtx_unlock(&lun->lun_lock);
7982
7983	ctl_set_success(ctsio);
7984	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7985	ctsio->be_move_done = ctl_config_move_done;
7986	ctl_datamove((union ctl_io *)ctsio);
7987	return (CTL_RETVAL_COMPLETE);
7988}
7989
7990/*
7991 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7992 * it should return.
7993 */
7994static int
7995ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7996		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7997		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7998		struct scsi_per_res_out_parms* param)
7999{
8000	union ctl_ha_msg persis_io;
8001	int i;
8002
8003	mtx_lock(&lun->lun_lock);
8004	if (sa_res_key == 0) {
8005		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8006			/* validate scope and type */
8007			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8008			     SPR_LU_SCOPE) {
8009				mtx_unlock(&lun->lun_lock);
8010				ctl_set_invalid_field(/*ctsio*/ ctsio,
8011						      /*sks_valid*/ 1,
8012						      /*command*/ 1,
8013						      /*field*/ 2,
8014						      /*bit_valid*/ 1,
8015						      /*bit*/ 4);
8016				ctl_done((union ctl_io *)ctsio);
8017				return (1);
8018			}
8019
8020		        if (type>8 || type==2 || type==4 || type==0) {
8021				mtx_unlock(&lun->lun_lock);
8022				ctl_set_invalid_field(/*ctsio*/ ctsio,
8023       	           				      /*sks_valid*/ 1,
8024						      /*command*/ 1,
8025						      /*field*/ 2,
8026						      /*bit_valid*/ 1,
8027						      /*bit*/ 0);
8028				ctl_done((union ctl_io *)ctsio);
8029				return (1);
8030		        }
8031
8032			/*
8033			 * Unregister everybody else and build UA for
8034			 * them
8035			 */
8036			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8037				if (i == residx || ctl_get_prkey(lun, i) == 0)
8038					continue;
8039
8040				ctl_clr_prkey(lun, i);
8041				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8042			}
8043			lun->pr_key_count = 1;
8044			lun->res_type = type;
8045			if (lun->res_type != SPR_TYPE_WR_EX_AR
8046			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8047				lun->pr_res_idx = residx;
8048			lun->PRGeneration++;
8049			mtx_unlock(&lun->lun_lock);
8050
8051			/* send msg to other side */
8052			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8053			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8054			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8055			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8056			persis_io.pr.pr_info.res_type = type;
8057			memcpy(persis_io.pr.pr_info.sa_res_key,
8058			       param->serv_act_res_key,
8059			       sizeof(param->serv_act_res_key));
8060			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8061			    sizeof(persis_io.pr), M_WAITOK);
8062		} else {
8063			/* not all registrants */
8064			mtx_unlock(&lun->lun_lock);
8065			free(ctsio->kern_data_ptr, M_CTL);
8066			ctl_set_invalid_field(ctsio,
8067					      /*sks_valid*/ 1,
8068					      /*command*/ 0,
8069					      /*field*/ 8,
8070					      /*bit_valid*/ 0,
8071					      /*bit*/ 0);
8072			ctl_done((union ctl_io *)ctsio);
8073			return (1);
8074		}
8075	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8076		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8077		int found = 0;
8078
8079		if (res_key == sa_res_key) {
8080			/* special case */
8081			/*
8082			 * The spec implies this is not good but doesn't
8083			 * say what to do. There are two choices either
8084			 * generate a res conflict or check condition
8085			 * with illegal field in parameter data. Since
8086			 * that is what is done when the sa_res_key is
8087			 * zero I'll take that approach since this has
8088			 * to do with the sa_res_key.
8089			 */
8090			mtx_unlock(&lun->lun_lock);
8091			free(ctsio->kern_data_ptr, M_CTL);
8092			ctl_set_invalid_field(ctsio,
8093					      /*sks_valid*/ 1,
8094					      /*command*/ 0,
8095					      /*field*/ 8,
8096					      /*bit_valid*/ 0,
8097					      /*bit*/ 0);
8098			ctl_done((union ctl_io *)ctsio);
8099			return (1);
8100		}
8101
8102		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8103			if (ctl_get_prkey(lun, i) != sa_res_key)
8104				continue;
8105
8106			found = 1;
8107			ctl_clr_prkey(lun, i);
8108			lun->pr_key_count--;
8109			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8110		}
8111		if (!found) {
8112			mtx_unlock(&lun->lun_lock);
8113			free(ctsio->kern_data_ptr, M_CTL);
8114			ctl_set_reservation_conflict(ctsio);
8115			ctl_done((union ctl_io *)ctsio);
8116			return (CTL_RETVAL_COMPLETE);
8117		}
8118		lun->PRGeneration++;
8119		mtx_unlock(&lun->lun_lock);
8120
8121		/* send msg to other side */
8122		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8123		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8124		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8125		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8126		persis_io.pr.pr_info.res_type = type;
8127		memcpy(persis_io.pr.pr_info.sa_res_key,
8128		       param->serv_act_res_key,
8129		       sizeof(param->serv_act_res_key));
8130		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8131		    sizeof(persis_io.pr), M_WAITOK);
8132	} else {
8133		/* Reserved but not all registrants */
8134		/* sa_res_key is res holder */
8135		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
8136			/* validate scope and type */
8137			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8138			     SPR_LU_SCOPE) {
8139				mtx_unlock(&lun->lun_lock);
8140				ctl_set_invalid_field(/*ctsio*/ ctsio,
8141						      /*sks_valid*/ 1,
8142						      /*command*/ 1,
8143						      /*field*/ 2,
8144						      /*bit_valid*/ 1,
8145						      /*bit*/ 4);
8146				ctl_done((union ctl_io *)ctsio);
8147				return (1);
8148			}
8149
8150			if (type>8 || type==2 || type==4 || type==0) {
8151				mtx_unlock(&lun->lun_lock);
8152				ctl_set_invalid_field(/*ctsio*/ ctsio,
8153						      /*sks_valid*/ 1,
8154						      /*command*/ 1,
8155						      /*field*/ 2,
8156						      /*bit_valid*/ 1,
8157						      /*bit*/ 0);
8158				ctl_done((union ctl_io *)ctsio);
8159				return (1);
8160			}
8161
8162			/*
8163			 * Do the following:
8164			 * if sa_res_key != res_key remove all
8165			 * registrants w/sa_res_key and generate UA
8166			 * for these registrants(Registrations
8167			 * Preempted) if it wasn't an exclusive
8168			 * reservation generate UA(Reservations
8169			 * Preempted) for all other registered nexuses
8170			 * if the type has changed. Establish the new
8171			 * reservation and holder. If res_key and
8172			 * sa_res_key are the same do the above
8173			 * except don't unregister the res holder.
8174			 */
8175
8176			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8177				if (i == residx || ctl_get_prkey(lun, i) == 0)
8178					continue;
8179
8180				if (sa_res_key == ctl_get_prkey(lun, i)) {
8181					ctl_clr_prkey(lun, i);
8182					lun->pr_key_count--;
8183					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8184				} else if (type != lun->res_type
8185					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8186					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8187					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8188				}
8189			}
8190			lun->res_type = type;
8191			if (lun->res_type != SPR_TYPE_WR_EX_AR
8192			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8193				lun->pr_res_idx = residx;
8194			else
8195				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8196			lun->PRGeneration++;
8197			mtx_unlock(&lun->lun_lock);
8198
8199			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8200			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8201			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8202			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8203			persis_io.pr.pr_info.res_type = type;
8204			memcpy(persis_io.pr.pr_info.sa_res_key,
8205			       param->serv_act_res_key,
8206			       sizeof(param->serv_act_res_key));
8207			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8208			    sizeof(persis_io.pr), M_WAITOK);
8209		} else {
8210			/*
8211			 * sa_res_key is not the res holder just
8212			 * remove registrants
8213			 */
8214			int found=0;
8215
8216			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8217				if (sa_res_key != ctl_get_prkey(lun, i))
8218					continue;
8219
8220				found = 1;
8221				ctl_clr_prkey(lun, i);
8222				lun->pr_key_count--;
8223				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8224			}
8225
8226			if (!found) {
8227				mtx_unlock(&lun->lun_lock);
8228				free(ctsio->kern_data_ptr, M_CTL);
8229				ctl_set_reservation_conflict(ctsio);
8230				ctl_done((union ctl_io *)ctsio);
8231		        	return (1);
8232			}
8233			lun->PRGeneration++;
8234			mtx_unlock(&lun->lun_lock);
8235
8236			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8237			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8238			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8239			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8240			persis_io.pr.pr_info.res_type = type;
8241			memcpy(persis_io.pr.pr_info.sa_res_key,
8242			       param->serv_act_res_key,
8243			       sizeof(param->serv_act_res_key));
8244			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8245			    sizeof(persis_io.pr), M_WAITOK);
8246		}
8247	}
8248	return (0);
8249}
8250
8251static void
8252ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8253{
8254	uint64_t sa_res_key;
8255	int i;
8256
8257	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8258
8259	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8260	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8261	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8262		if (sa_res_key == 0) {
8263			/*
8264			 * Unregister everybody else and build UA for
8265			 * them
8266			 */
8267			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8268				if (i == msg->pr.pr_info.residx ||
8269				    ctl_get_prkey(lun, i) == 0)
8270					continue;
8271
8272				ctl_clr_prkey(lun, i);
8273				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8274			}
8275
8276			lun->pr_key_count = 1;
8277			lun->res_type = msg->pr.pr_info.res_type;
8278			if (lun->res_type != SPR_TYPE_WR_EX_AR
8279			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8280				lun->pr_res_idx = msg->pr.pr_info.residx;
8281		} else {
8282		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8283				if (sa_res_key == ctl_get_prkey(lun, i))
8284					continue;
8285
8286				ctl_clr_prkey(lun, i);
8287				lun->pr_key_count--;
8288				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8289			}
8290		}
8291	} else {
8292		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8293			if (i == msg->pr.pr_info.residx ||
8294			    ctl_get_prkey(lun, i) == 0)
8295				continue;
8296
8297			if (sa_res_key == ctl_get_prkey(lun, i)) {
8298				ctl_clr_prkey(lun, i);
8299				lun->pr_key_count--;
8300				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8301			} else if (msg->pr.pr_info.res_type != lun->res_type
8302				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8303				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8304				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8305			}
8306		}
8307		lun->res_type = msg->pr.pr_info.res_type;
8308		if (lun->res_type != SPR_TYPE_WR_EX_AR
8309		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8310			lun->pr_res_idx = msg->pr.pr_info.residx;
8311		else
8312			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8313	}
8314	lun->PRGeneration++;
8315
8316}
8317
8318
8319int
8320ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8321{
8322	int retval;
8323	u_int32_t param_len;
8324	struct scsi_per_res_out *cdb;
8325	struct ctl_lun *lun;
8326	struct scsi_per_res_out_parms* param;
8327	struct ctl_softc *softc;
8328	uint32_t residx;
8329	uint64_t res_key, sa_res_key, key;
8330	uint8_t type;
8331	union ctl_ha_msg persis_io;
8332	int    i;
8333
8334	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8335
8336	retval = CTL_RETVAL_COMPLETE;
8337
8338	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8339	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8340	softc = lun->ctl_softc;
8341
8342	/*
8343	 * We only support whole-LUN scope.  The scope & type are ignored for
8344	 * register, register and ignore existing key and clear.
8345	 * We sometimes ignore scope and type on preempts too!!
8346	 * Verify reservation type here as well.
8347	 */
8348	type = cdb->scope_type & SPR_TYPE_MASK;
8349	if ((cdb->action == SPRO_RESERVE)
8350	 || (cdb->action == SPRO_RELEASE)) {
8351		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8352			ctl_set_invalid_field(/*ctsio*/ ctsio,
8353					      /*sks_valid*/ 1,
8354					      /*command*/ 1,
8355					      /*field*/ 2,
8356					      /*bit_valid*/ 1,
8357					      /*bit*/ 4);
8358			ctl_done((union ctl_io *)ctsio);
8359			return (CTL_RETVAL_COMPLETE);
8360		}
8361
8362		if (type>8 || type==2 || type==4 || type==0) {
8363			ctl_set_invalid_field(/*ctsio*/ ctsio,
8364					      /*sks_valid*/ 1,
8365					      /*command*/ 1,
8366					      /*field*/ 2,
8367					      /*bit_valid*/ 1,
8368					      /*bit*/ 0);
8369			ctl_done((union ctl_io *)ctsio);
8370			return (CTL_RETVAL_COMPLETE);
8371		}
8372	}
8373
8374	param_len = scsi_4btoul(cdb->length);
8375
8376	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8377		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8378		ctsio->kern_data_len = param_len;
8379		ctsio->kern_total_len = param_len;
8380		ctsio->kern_data_resid = 0;
8381		ctsio->kern_rel_offset = 0;
8382		ctsio->kern_sg_entries = 0;
8383		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8384		ctsio->be_move_done = ctl_config_move_done;
8385		ctl_datamove((union ctl_io *)ctsio);
8386
8387		return (CTL_RETVAL_COMPLETE);
8388	}
8389
8390	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8391
8392	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8393	res_key = scsi_8btou64(param->res_key.key);
8394	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8395
8396	/*
8397	 * Validate the reservation key here except for SPRO_REG_IGNO
8398	 * This must be done for all other service actions
8399	 */
8400	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8401		mtx_lock(&lun->lun_lock);
8402		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8403			if (res_key != key) {
8404				/*
8405				 * The current key passed in doesn't match
8406				 * the one the initiator previously
8407				 * registered.
8408				 */
8409				mtx_unlock(&lun->lun_lock);
8410				free(ctsio->kern_data_ptr, M_CTL);
8411				ctl_set_reservation_conflict(ctsio);
8412				ctl_done((union ctl_io *)ctsio);
8413				return (CTL_RETVAL_COMPLETE);
8414			}
8415		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8416			/*
8417			 * We are not registered
8418			 */
8419			mtx_unlock(&lun->lun_lock);
8420			free(ctsio->kern_data_ptr, M_CTL);
8421			ctl_set_reservation_conflict(ctsio);
8422			ctl_done((union ctl_io *)ctsio);
8423			return (CTL_RETVAL_COMPLETE);
8424		} else if (res_key != 0) {
8425			/*
8426			 * We are not registered and trying to register but
8427			 * the register key isn't zero.
8428			 */
8429			mtx_unlock(&lun->lun_lock);
8430			free(ctsio->kern_data_ptr, M_CTL);
8431			ctl_set_reservation_conflict(ctsio);
8432			ctl_done((union ctl_io *)ctsio);
8433			return (CTL_RETVAL_COMPLETE);
8434		}
8435		mtx_unlock(&lun->lun_lock);
8436	}
8437
8438	switch (cdb->action & SPRO_ACTION_MASK) {
8439	case SPRO_REGISTER:
8440	case SPRO_REG_IGNO: {
8441
8442#if 0
8443		printf("Registration received\n");
8444#endif
8445
8446		/*
8447		 * We don't support any of these options, as we report in
8448		 * the read capabilities request (see
8449		 * ctl_persistent_reserve_in(), above).
8450		 */
8451		if ((param->flags & SPR_SPEC_I_PT)
8452		 || (param->flags & SPR_ALL_TG_PT)
8453		 || (param->flags & SPR_APTPL)) {
8454			int bit_ptr;
8455
8456			if (param->flags & SPR_APTPL)
8457				bit_ptr = 0;
8458			else if (param->flags & SPR_ALL_TG_PT)
8459				bit_ptr = 2;
8460			else /* SPR_SPEC_I_PT */
8461				bit_ptr = 3;
8462
8463			free(ctsio->kern_data_ptr, M_CTL);
8464			ctl_set_invalid_field(ctsio,
8465					      /*sks_valid*/ 1,
8466					      /*command*/ 0,
8467					      /*field*/ 20,
8468					      /*bit_valid*/ 1,
8469					      /*bit*/ bit_ptr);
8470			ctl_done((union ctl_io *)ctsio);
8471			return (CTL_RETVAL_COMPLETE);
8472		}
8473
8474		mtx_lock(&lun->lun_lock);
8475
8476		/*
8477		 * The initiator wants to clear the
8478		 * key/unregister.
8479		 */
8480		if (sa_res_key == 0) {
8481			if ((res_key == 0
8482			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8483			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8484			  && ctl_get_prkey(lun, residx) == 0)) {
8485				mtx_unlock(&lun->lun_lock);
8486				goto done;
8487			}
8488
8489			ctl_clr_prkey(lun, residx);
8490			lun->pr_key_count--;
8491
8492			if (residx == lun->pr_res_idx) {
8493				lun->flags &= ~CTL_LUN_PR_RESERVED;
8494				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8495
8496				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8497				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8498				 && lun->pr_key_count) {
8499					/*
8500					 * If the reservation is a registrants
8501					 * only type we need to generate a UA
8502					 * for other registered inits.  The
8503					 * sense code should be RESERVATIONS
8504					 * RELEASED
8505					 */
8506
8507					for (i = softc->init_min; i < softc->init_max; i++){
8508						if (ctl_get_prkey(lun, i) == 0)
8509							continue;
8510						ctl_est_ua(lun, i,
8511						    CTL_UA_RES_RELEASE);
8512					}
8513				}
8514				lun->res_type = 0;
8515			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8516				if (lun->pr_key_count==0) {
8517					lun->flags &= ~CTL_LUN_PR_RESERVED;
8518					lun->res_type = 0;
8519					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8520				}
8521			}
8522			lun->PRGeneration++;
8523			mtx_unlock(&lun->lun_lock);
8524
8525			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8526			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8527			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8528			persis_io.pr.pr_info.residx = residx;
8529			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8530			    sizeof(persis_io.pr), M_WAITOK);
8531		} else /* sa_res_key != 0 */ {
8532
8533			/*
8534			 * If we aren't registered currently then increment
8535			 * the key count and set the registered flag.
8536			 */
8537			ctl_alloc_prkey(lun, residx);
8538			if (ctl_get_prkey(lun, residx) == 0)
8539				lun->pr_key_count++;
8540			ctl_set_prkey(lun, residx, sa_res_key);
8541			lun->PRGeneration++;
8542			mtx_unlock(&lun->lun_lock);
8543
8544			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8545			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8546			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8547			persis_io.pr.pr_info.residx = residx;
8548			memcpy(persis_io.pr.pr_info.sa_res_key,
8549			       param->serv_act_res_key,
8550			       sizeof(param->serv_act_res_key));
8551			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8552			    sizeof(persis_io.pr), M_WAITOK);
8553		}
8554
8555		break;
8556	}
8557	case SPRO_RESERVE:
8558#if 0
8559                printf("Reserve executed type %d\n", type);
8560#endif
8561		mtx_lock(&lun->lun_lock);
8562		if (lun->flags & CTL_LUN_PR_RESERVED) {
8563			/*
8564			 * if this isn't the reservation holder and it's
8565			 * not a "all registrants" type or if the type is
8566			 * different then we have a conflict
8567			 */
8568			if ((lun->pr_res_idx != residx
8569			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8570			 || lun->res_type != type) {
8571				mtx_unlock(&lun->lun_lock);
8572				free(ctsio->kern_data_ptr, M_CTL);
8573				ctl_set_reservation_conflict(ctsio);
8574				ctl_done((union ctl_io *)ctsio);
8575				return (CTL_RETVAL_COMPLETE);
8576			}
8577			mtx_unlock(&lun->lun_lock);
8578		} else /* create a reservation */ {
8579			/*
8580			 * If it's not an "all registrants" type record
8581			 * reservation holder
8582			 */
8583			if (type != SPR_TYPE_WR_EX_AR
8584			 && type != SPR_TYPE_EX_AC_AR)
8585				lun->pr_res_idx = residx; /* Res holder */
8586			else
8587				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8588
8589			lun->flags |= CTL_LUN_PR_RESERVED;
8590			lun->res_type = type;
8591
8592			mtx_unlock(&lun->lun_lock);
8593
8594			/* send msg to other side */
8595			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8596			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8597			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8598			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8599			persis_io.pr.pr_info.res_type = type;
8600			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8601			    sizeof(persis_io.pr), M_WAITOK);
8602		}
8603		break;
8604
8605	case SPRO_RELEASE:
8606		mtx_lock(&lun->lun_lock);
8607		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8608			/* No reservation exists return good status */
8609			mtx_unlock(&lun->lun_lock);
8610			goto done;
8611		}
8612		/*
8613		 * Is this nexus a reservation holder?
8614		 */
8615		if (lun->pr_res_idx != residx
8616		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8617			/*
8618			 * not a res holder return good status but
8619			 * do nothing
8620			 */
8621			mtx_unlock(&lun->lun_lock);
8622			goto done;
8623		}
8624
8625		if (lun->res_type != type) {
8626			mtx_unlock(&lun->lun_lock);
8627			free(ctsio->kern_data_ptr, M_CTL);
8628			ctl_set_illegal_pr_release(ctsio);
8629			ctl_done((union ctl_io *)ctsio);
8630			return (CTL_RETVAL_COMPLETE);
8631		}
8632
8633		/* okay to release */
8634		lun->flags &= ~CTL_LUN_PR_RESERVED;
8635		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8636		lun->res_type = 0;
8637
8638		/*
8639		 * if this isn't an exclusive access
8640		 * res generate UA for all other
8641		 * registrants.
8642		 */
8643		if (type != SPR_TYPE_EX_AC
8644		 && type != SPR_TYPE_WR_EX) {
8645			for (i = softc->init_min; i < softc->init_max; i++) {
8646				if (i == residx || ctl_get_prkey(lun, i) == 0)
8647					continue;
8648				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8649			}
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_RELEASE;
8657		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8658		     sizeof(persis_io.pr), M_WAITOK);
8659		break;
8660
8661	case SPRO_CLEAR:
8662		/* send msg to other side */
8663
8664		mtx_lock(&lun->lun_lock);
8665		lun->flags &= ~CTL_LUN_PR_RESERVED;
8666		lun->res_type = 0;
8667		lun->pr_key_count = 0;
8668		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8669
8670		ctl_clr_prkey(lun, residx);
8671		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8672			if (ctl_get_prkey(lun, i) != 0) {
8673				ctl_clr_prkey(lun, i);
8674				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8675			}
8676		lun->PRGeneration++;
8677		mtx_unlock(&lun->lun_lock);
8678
8679		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8680		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8681		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8682		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8683		     sizeof(persis_io.pr), M_WAITOK);
8684		break;
8685
8686	case SPRO_PREEMPT:
8687	case SPRO_PRE_ABO: {
8688		int nretval;
8689
8690		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8691					  residx, ctsio, cdb, param);
8692		if (nretval != 0)
8693			return (CTL_RETVAL_COMPLETE);
8694		break;
8695	}
8696	default:
8697		panic("Invalid PR type %x", cdb->action);
8698	}
8699
8700done:
8701	free(ctsio->kern_data_ptr, M_CTL);
8702	ctl_set_success(ctsio);
8703	ctl_done((union ctl_io *)ctsio);
8704
8705	return (retval);
8706}
8707
8708/*
8709 * This routine is for handling a message from the other SC pertaining to
8710 * persistent reserve out. All the error checking will have been done
8711 * so only perorming the action need be done here to keep the two
8712 * in sync.
8713 */
8714static void
8715ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8716{
8717	struct ctl_softc *softc = control_softc;
8718	struct ctl_lun *lun;
8719	int i;
8720	uint32_t residx, targ_lun;
8721
8722	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8723	mtx_lock(&softc->ctl_lock);
8724	if ((targ_lun >= CTL_MAX_LUNS) ||
8725	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
8726		mtx_unlock(&softc->ctl_lock);
8727		return;
8728	}
8729	mtx_lock(&lun->lun_lock);
8730	mtx_unlock(&softc->ctl_lock);
8731	if (lun->flags & CTL_LUN_DISABLED) {
8732		mtx_unlock(&lun->lun_lock);
8733		return;
8734	}
8735	residx = ctl_get_initindex(&msg->hdr.nexus);
8736	switch(msg->pr.pr_info.action) {
8737	case CTL_PR_REG_KEY:
8738		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8739		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8740			lun->pr_key_count++;
8741		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8742		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8743		lun->PRGeneration++;
8744		break;
8745
8746	case CTL_PR_UNREG_KEY:
8747		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8748		lun->pr_key_count--;
8749
8750		/* XXX Need to see if the reservation has been released */
8751		/* if so do we need to generate UA? */
8752		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8753			lun->flags &= ~CTL_LUN_PR_RESERVED;
8754			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8755
8756			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8757			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8758			 && lun->pr_key_count) {
8759				/*
8760				 * If the reservation is a registrants
8761				 * only type we need to generate a UA
8762				 * for other registered inits.  The
8763				 * sense code should be RESERVATIONS
8764				 * RELEASED
8765				 */
8766
8767				for (i = softc->init_min; i < softc->init_max; i++) {
8768					if (ctl_get_prkey(lun, i) == 0)
8769						continue;
8770
8771					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8772				}
8773			}
8774			lun->res_type = 0;
8775		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8776			if (lun->pr_key_count==0) {
8777				lun->flags &= ~CTL_LUN_PR_RESERVED;
8778				lun->res_type = 0;
8779				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8780			}
8781		}
8782		lun->PRGeneration++;
8783		break;
8784
8785	case CTL_PR_RESERVE:
8786		lun->flags |= CTL_LUN_PR_RESERVED;
8787		lun->res_type = msg->pr.pr_info.res_type;
8788		lun->pr_res_idx = msg->pr.pr_info.residx;
8789
8790		break;
8791
8792	case CTL_PR_RELEASE:
8793		/*
8794		 * if this isn't an exclusive access res generate UA for all
8795		 * other registrants.
8796		 */
8797		if (lun->res_type != SPR_TYPE_EX_AC
8798		 && lun->res_type != SPR_TYPE_WR_EX) {
8799			for (i = softc->init_min; i < softc->init_max; i++)
8800				if (i == residx || ctl_get_prkey(lun, i) == 0)
8801					continue;
8802				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8803		}
8804
8805		lun->flags &= ~CTL_LUN_PR_RESERVED;
8806		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8807		lun->res_type = 0;
8808		break;
8809
8810	case CTL_PR_PREEMPT:
8811		ctl_pro_preempt_other(lun, msg);
8812		break;
8813	case CTL_PR_CLEAR:
8814		lun->flags &= ~CTL_LUN_PR_RESERVED;
8815		lun->res_type = 0;
8816		lun->pr_key_count = 0;
8817		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8818
8819		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8820			if (ctl_get_prkey(lun, i) == 0)
8821				continue;
8822			ctl_clr_prkey(lun, i);
8823			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8824		}
8825		lun->PRGeneration++;
8826		break;
8827	}
8828
8829	mtx_unlock(&lun->lun_lock);
8830}
8831
8832int
8833ctl_read_write(struct ctl_scsiio *ctsio)
8834{
8835	struct ctl_lun *lun;
8836	struct ctl_lba_len_flags *lbalen;
8837	uint64_t lba;
8838	uint32_t num_blocks;
8839	int flags, retval;
8840	int isread;
8841
8842	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8843
8844	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8845
8846	flags = 0;
8847	retval = CTL_RETVAL_COMPLETE;
8848
8849	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8850	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8851	switch (ctsio->cdb[0]) {
8852	case READ_6:
8853	case WRITE_6: {
8854		struct scsi_rw_6 *cdb;
8855
8856		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8857
8858		lba = scsi_3btoul(cdb->addr);
8859		/* only 5 bits are valid in the most significant address byte */
8860		lba &= 0x1fffff;
8861		num_blocks = cdb->length;
8862		/*
8863		 * This is correct according to SBC-2.
8864		 */
8865		if (num_blocks == 0)
8866			num_blocks = 256;
8867		break;
8868	}
8869	case READ_10:
8870	case WRITE_10: {
8871		struct scsi_rw_10 *cdb;
8872
8873		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8874		if (cdb->byte2 & SRW10_FUA)
8875			flags |= CTL_LLF_FUA;
8876		if (cdb->byte2 & SRW10_DPO)
8877			flags |= CTL_LLF_DPO;
8878		lba = scsi_4btoul(cdb->addr);
8879		num_blocks = scsi_2btoul(cdb->length);
8880		break;
8881	}
8882	case WRITE_VERIFY_10: {
8883		struct scsi_write_verify_10 *cdb;
8884
8885		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8886		flags |= CTL_LLF_FUA;
8887		if (cdb->byte2 & SWV_DPO)
8888			flags |= CTL_LLF_DPO;
8889		lba = scsi_4btoul(cdb->addr);
8890		num_blocks = scsi_2btoul(cdb->length);
8891		break;
8892	}
8893	case READ_12:
8894	case WRITE_12: {
8895		struct scsi_rw_12 *cdb;
8896
8897		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8898		if (cdb->byte2 & SRW12_FUA)
8899			flags |= CTL_LLF_FUA;
8900		if (cdb->byte2 & SRW12_DPO)
8901			flags |= CTL_LLF_DPO;
8902		lba = scsi_4btoul(cdb->addr);
8903		num_blocks = scsi_4btoul(cdb->length);
8904		break;
8905	}
8906	case WRITE_VERIFY_12: {
8907		struct scsi_write_verify_12 *cdb;
8908
8909		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8910		flags |= CTL_LLF_FUA;
8911		if (cdb->byte2 & SWV_DPO)
8912			flags |= CTL_LLF_DPO;
8913		lba = scsi_4btoul(cdb->addr);
8914		num_blocks = scsi_4btoul(cdb->length);
8915		break;
8916	}
8917	case READ_16:
8918	case WRITE_16: {
8919		struct scsi_rw_16 *cdb;
8920
8921		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8922		if (cdb->byte2 & SRW12_FUA)
8923			flags |= CTL_LLF_FUA;
8924		if (cdb->byte2 & SRW12_DPO)
8925			flags |= CTL_LLF_DPO;
8926		lba = scsi_8btou64(cdb->addr);
8927		num_blocks = scsi_4btoul(cdb->length);
8928		break;
8929	}
8930	case WRITE_ATOMIC_16: {
8931		struct scsi_write_atomic_16 *cdb;
8932
8933		if (lun->be_lun->atomicblock == 0) {
8934			ctl_set_invalid_opcode(ctsio);
8935			ctl_done((union ctl_io *)ctsio);
8936			return (CTL_RETVAL_COMPLETE);
8937		}
8938
8939		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8940		if (cdb->byte2 & SRW12_FUA)
8941			flags |= CTL_LLF_FUA;
8942		if (cdb->byte2 & SRW12_DPO)
8943			flags |= CTL_LLF_DPO;
8944		lba = scsi_8btou64(cdb->addr);
8945		num_blocks = scsi_2btoul(cdb->length);
8946		if (num_blocks > lun->be_lun->atomicblock) {
8947			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8948			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8949			    /*bit*/ 0);
8950			ctl_done((union ctl_io *)ctsio);
8951			return (CTL_RETVAL_COMPLETE);
8952		}
8953		break;
8954	}
8955	case WRITE_VERIFY_16: {
8956		struct scsi_write_verify_16 *cdb;
8957
8958		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8959		flags |= CTL_LLF_FUA;
8960		if (cdb->byte2 & SWV_DPO)
8961			flags |= CTL_LLF_DPO;
8962		lba = scsi_8btou64(cdb->addr);
8963		num_blocks = scsi_4btoul(cdb->length);
8964		break;
8965	}
8966	default:
8967		/*
8968		 * We got a command we don't support.  This shouldn't
8969		 * happen, commands should be filtered out above us.
8970		 */
8971		ctl_set_invalid_opcode(ctsio);
8972		ctl_done((union ctl_io *)ctsio);
8973
8974		return (CTL_RETVAL_COMPLETE);
8975		break; /* NOTREACHED */
8976	}
8977
8978	/*
8979	 * The first check is to make sure we're in bounds, the second
8980	 * check is to catch wrap-around problems.  If the lba + num blocks
8981	 * is less than the lba, then we've wrapped around and the block
8982	 * range is invalid anyway.
8983	 */
8984	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8985	 || ((lba + num_blocks) < lba)) {
8986		ctl_set_lba_out_of_range(ctsio);
8987		ctl_done((union ctl_io *)ctsio);
8988		return (CTL_RETVAL_COMPLETE);
8989	}
8990
8991	/*
8992	 * According to SBC-3, a transfer length of 0 is not an error.
8993	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8994	 * translates to 256 blocks for those commands.
8995	 */
8996	if (num_blocks == 0) {
8997		ctl_set_success(ctsio);
8998		ctl_done((union ctl_io *)ctsio);
8999		return (CTL_RETVAL_COMPLETE);
9000	}
9001
9002	/* Set FUA and/or DPO if caches are disabled. */
9003	if (isread) {
9004		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9005		    SCP_RCD) != 0)
9006			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9007	} else {
9008		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9009		    SCP_WCE) == 0)
9010			flags |= CTL_LLF_FUA;
9011	}
9012
9013	lbalen = (struct ctl_lba_len_flags *)
9014	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9015	lbalen->lba = lba;
9016	lbalen->len = num_blocks;
9017	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9018
9019	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9020	ctsio->kern_rel_offset = 0;
9021
9022	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9023
9024	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9025
9026	return (retval);
9027}
9028
9029static int
9030ctl_cnw_cont(union ctl_io *io)
9031{
9032	struct ctl_scsiio *ctsio;
9033	struct ctl_lun *lun;
9034	struct ctl_lba_len_flags *lbalen;
9035	int retval;
9036
9037	ctsio = &io->scsiio;
9038	ctsio->io_hdr.status = CTL_STATUS_NONE;
9039	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9040	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9041	lbalen = (struct ctl_lba_len_flags *)
9042	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9043	lbalen->flags &= ~CTL_LLF_COMPARE;
9044	lbalen->flags |= CTL_LLF_WRITE;
9045
9046	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9047	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9048	return (retval);
9049}
9050
9051int
9052ctl_cnw(struct ctl_scsiio *ctsio)
9053{
9054	struct ctl_lun *lun;
9055	struct ctl_lba_len_flags *lbalen;
9056	uint64_t lba;
9057	uint32_t num_blocks;
9058	int flags, retval;
9059
9060	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9061
9062	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9063
9064	flags = 0;
9065	retval = CTL_RETVAL_COMPLETE;
9066
9067	switch (ctsio->cdb[0]) {
9068	case COMPARE_AND_WRITE: {
9069		struct scsi_compare_and_write *cdb;
9070
9071		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9072		if (cdb->byte2 & SRW10_FUA)
9073			flags |= CTL_LLF_FUA;
9074		if (cdb->byte2 & SRW10_DPO)
9075			flags |= CTL_LLF_DPO;
9076		lba = scsi_8btou64(cdb->addr);
9077		num_blocks = cdb->length;
9078		break;
9079	}
9080	default:
9081		/*
9082		 * We got a command we don't support.  This shouldn't
9083		 * happen, commands should be filtered out above us.
9084		 */
9085		ctl_set_invalid_opcode(ctsio);
9086		ctl_done((union ctl_io *)ctsio);
9087
9088		return (CTL_RETVAL_COMPLETE);
9089		break; /* NOTREACHED */
9090	}
9091
9092	/*
9093	 * The first check is to make sure we're in bounds, the second
9094	 * check is to catch wrap-around problems.  If the lba + num blocks
9095	 * is less than the lba, then we've wrapped around and the block
9096	 * range is invalid anyway.
9097	 */
9098	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9099	 || ((lba + num_blocks) < lba)) {
9100		ctl_set_lba_out_of_range(ctsio);
9101		ctl_done((union ctl_io *)ctsio);
9102		return (CTL_RETVAL_COMPLETE);
9103	}
9104
9105	/*
9106	 * According to SBC-3, a transfer length of 0 is not an error.
9107	 */
9108	if (num_blocks == 0) {
9109		ctl_set_success(ctsio);
9110		ctl_done((union ctl_io *)ctsio);
9111		return (CTL_RETVAL_COMPLETE);
9112	}
9113
9114	/* Set FUA if write cache is disabled. */
9115	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9116	    SCP_WCE) == 0)
9117		flags |= CTL_LLF_FUA;
9118
9119	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9120	ctsio->kern_rel_offset = 0;
9121
9122	/*
9123	 * Set the IO_CONT flag, so that if this I/O gets passed to
9124	 * ctl_data_submit_done(), it'll get passed back to
9125	 * ctl_ctl_cnw_cont() for further processing.
9126	 */
9127	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9128	ctsio->io_cont = ctl_cnw_cont;
9129
9130	lbalen = (struct ctl_lba_len_flags *)
9131	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9132	lbalen->lba = lba;
9133	lbalen->len = num_blocks;
9134	lbalen->flags = CTL_LLF_COMPARE | flags;
9135
9136	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9137	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9138	return (retval);
9139}
9140
9141int
9142ctl_verify(struct ctl_scsiio *ctsio)
9143{
9144	struct ctl_lun *lun;
9145	struct ctl_lba_len_flags *lbalen;
9146	uint64_t lba;
9147	uint32_t num_blocks;
9148	int bytchk, flags;
9149	int retval;
9150
9151	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9152
9153	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9154
9155	bytchk = 0;
9156	flags = CTL_LLF_FUA;
9157	retval = CTL_RETVAL_COMPLETE;
9158
9159	switch (ctsio->cdb[0]) {
9160	case VERIFY_10: {
9161		struct scsi_verify_10 *cdb;
9162
9163		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9164		if (cdb->byte2 & SVFY_BYTCHK)
9165			bytchk = 1;
9166		if (cdb->byte2 & SVFY_DPO)
9167			flags |= CTL_LLF_DPO;
9168		lba = scsi_4btoul(cdb->addr);
9169		num_blocks = scsi_2btoul(cdb->length);
9170		break;
9171	}
9172	case VERIFY_12: {
9173		struct scsi_verify_12 *cdb;
9174
9175		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9176		if (cdb->byte2 & SVFY_BYTCHK)
9177			bytchk = 1;
9178		if (cdb->byte2 & SVFY_DPO)
9179			flags |= CTL_LLF_DPO;
9180		lba = scsi_4btoul(cdb->addr);
9181		num_blocks = scsi_4btoul(cdb->length);
9182		break;
9183	}
9184	case VERIFY_16: {
9185		struct scsi_rw_16 *cdb;
9186
9187		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9188		if (cdb->byte2 & SVFY_BYTCHK)
9189			bytchk = 1;
9190		if (cdb->byte2 & SVFY_DPO)
9191			flags |= CTL_LLF_DPO;
9192		lba = scsi_8btou64(cdb->addr);
9193		num_blocks = scsi_4btoul(cdb->length);
9194		break;
9195	}
9196	default:
9197		/*
9198		 * We got a command we don't support.  This shouldn't
9199		 * happen, commands should be filtered out above us.
9200		 */
9201		ctl_set_invalid_opcode(ctsio);
9202		ctl_done((union ctl_io *)ctsio);
9203		return (CTL_RETVAL_COMPLETE);
9204	}
9205
9206	/*
9207	 * The first check is to make sure we're in bounds, the second
9208	 * check is to catch wrap-around problems.  If the lba + num blocks
9209	 * is less than the lba, then we've wrapped around and the block
9210	 * range is invalid anyway.
9211	 */
9212	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9213	 || ((lba + num_blocks) < lba)) {
9214		ctl_set_lba_out_of_range(ctsio);
9215		ctl_done((union ctl_io *)ctsio);
9216		return (CTL_RETVAL_COMPLETE);
9217	}
9218
9219	/*
9220	 * According to SBC-3, a transfer length of 0 is not an error.
9221	 */
9222	if (num_blocks == 0) {
9223		ctl_set_success(ctsio);
9224		ctl_done((union ctl_io *)ctsio);
9225		return (CTL_RETVAL_COMPLETE);
9226	}
9227
9228	lbalen = (struct ctl_lba_len_flags *)
9229	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9230	lbalen->lba = lba;
9231	lbalen->len = num_blocks;
9232	if (bytchk) {
9233		lbalen->flags = CTL_LLF_COMPARE | flags;
9234		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9235	} else {
9236		lbalen->flags = CTL_LLF_VERIFY | flags;
9237		ctsio->kern_total_len = 0;
9238	}
9239	ctsio->kern_rel_offset = 0;
9240
9241	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9242	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9243	return (retval);
9244}
9245
9246int
9247ctl_report_luns(struct ctl_scsiio *ctsio)
9248{
9249	struct ctl_softc *softc;
9250	struct scsi_report_luns *cdb;
9251	struct scsi_report_luns_data *lun_data;
9252	struct ctl_lun *lun, *request_lun;
9253	struct ctl_port *port;
9254	int num_luns, retval;
9255	uint32_t alloc_len, lun_datalen;
9256	int num_filled;
9257	uint32_t initidx, targ_lun_id, lun_id;
9258
9259	retval = CTL_RETVAL_COMPLETE;
9260	cdb = (struct scsi_report_luns *)ctsio->cdb;
9261	port = ctl_io_port(&ctsio->io_hdr);
9262	softc = port->ctl_softc;
9263
9264	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9265
9266	mtx_lock(&softc->ctl_lock);
9267	num_luns = 0;
9268	for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
9269		if (ctl_lun_map_from_port(port, targ_lun_id) < CTL_MAX_LUNS)
9270			num_luns++;
9271	}
9272	mtx_unlock(&softc->ctl_lock);
9273
9274	switch (cdb->select_report) {
9275	case RPL_REPORT_DEFAULT:
9276	case RPL_REPORT_ALL:
9277	case RPL_REPORT_NONSUBSID:
9278		break;
9279	case RPL_REPORT_WELLKNOWN:
9280	case RPL_REPORT_ADMIN:
9281	case RPL_REPORT_CONGLOM:
9282		num_luns = 0;
9283		break;
9284	default:
9285		ctl_set_invalid_field(ctsio,
9286				      /*sks_valid*/ 1,
9287				      /*command*/ 1,
9288				      /*field*/ 2,
9289				      /*bit_valid*/ 0,
9290				      /*bit*/ 0);
9291		ctl_done((union ctl_io *)ctsio);
9292		return (retval);
9293		break; /* NOTREACHED */
9294	}
9295
9296	alloc_len = scsi_4btoul(cdb->length);
9297	/*
9298	 * The initiator has to allocate at least 16 bytes for this request,
9299	 * so he can at least get the header and the first LUN.  Otherwise
9300	 * we reject the request (per SPC-3 rev 14, section 6.21).
9301	 */
9302	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9303	    sizeof(struct scsi_report_luns_lundata))) {
9304		ctl_set_invalid_field(ctsio,
9305				      /*sks_valid*/ 1,
9306				      /*command*/ 1,
9307				      /*field*/ 6,
9308				      /*bit_valid*/ 0,
9309				      /*bit*/ 0);
9310		ctl_done((union ctl_io *)ctsio);
9311		return (retval);
9312	}
9313
9314	request_lun = (struct ctl_lun *)
9315		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9316
9317	lun_datalen = sizeof(*lun_data) +
9318		(num_luns * sizeof(struct scsi_report_luns_lundata));
9319
9320	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9321	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9322	ctsio->kern_sg_entries = 0;
9323
9324	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9325
9326	mtx_lock(&softc->ctl_lock);
9327	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9328		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9329		if (lun_id >= CTL_MAX_LUNS)
9330			continue;
9331		lun = softc->ctl_luns[lun_id];
9332		if (lun == NULL)
9333			continue;
9334
9335		if (targ_lun_id <= 0xff) {
9336			/*
9337			 * Peripheral addressing method, bus number 0.
9338			 */
9339			lun_data->luns[num_filled].lundata[0] =
9340				RPL_LUNDATA_ATYP_PERIPH;
9341			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9342			num_filled++;
9343		} else if (targ_lun_id <= 0x3fff) {
9344			/*
9345			 * Flat addressing method.
9346			 */
9347			lun_data->luns[num_filled].lundata[0] =
9348				RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9349			lun_data->luns[num_filled].lundata[1] =
9350				(targ_lun_id & 0xff);
9351			num_filled++;
9352		} else if (targ_lun_id <= 0xffffff) {
9353			/*
9354			 * Extended flat addressing method.
9355			 */
9356			lun_data->luns[num_filled].lundata[0] =
9357			    RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9358			scsi_ulto3b(targ_lun_id,
9359			    &lun_data->luns[num_filled].lundata[1]);
9360			num_filled++;
9361		} else {
9362			printf("ctl_report_luns: bogus LUN number %jd, "
9363			       "skipping\n", (intmax_t)targ_lun_id);
9364		}
9365		/*
9366		 * According to SPC-3, rev 14 section 6.21:
9367		 *
9368		 * "The execution of a REPORT LUNS command to any valid and
9369		 * installed logical unit shall clear the REPORTED LUNS DATA
9370		 * HAS CHANGED unit attention condition for all logical
9371		 * units of that target with respect to the requesting
9372		 * initiator. A valid and installed logical unit is one
9373		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9374		 * INQUIRY data (see 6.4.2)."
9375		 *
9376		 * If request_lun is NULL, the LUN this report luns command
9377		 * was issued to is either disabled or doesn't exist. In that
9378		 * case, we shouldn't clear any pending lun change unit
9379		 * attention.
9380		 */
9381		if (request_lun != NULL) {
9382			mtx_lock(&lun->lun_lock);
9383			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9384			mtx_unlock(&lun->lun_lock);
9385		}
9386	}
9387	mtx_unlock(&softc->ctl_lock);
9388
9389	/*
9390	 * It's quite possible that we've returned fewer LUNs than we allocated
9391	 * space for.  Trim it.
9392	 */
9393	lun_datalen = sizeof(*lun_data) +
9394		(num_filled * sizeof(struct scsi_report_luns_lundata));
9395
9396	if (lun_datalen < alloc_len) {
9397		ctsio->residual = alloc_len - lun_datalen;
9398		ctsio->kern_data_len = lun_datalen;
9399		ctsio->kern_total_len = lun_datalen;
9400	} else {
9401		ctsio->residual = 0;
9402		ctsio->kern_data_len = alloc_len;
9403		ctsio->kern_total_len = alloc_len;
9404	}
9405	ctsio->kern_data_resid = 0;
9406	ctsio->kern_rel_offset = 0;
9407	ctsio->kern_sg_entries = 0;
9408
9409	/*
9410	 * We set this to the actual data length, regardless of how much
9411	 * space we actually have to return results.  If the user looks at
9412	 * this value, he'll know whether or not he allocated enough space
9413	 * and reissue the command if necessary.  We don't support well
9414	 * known logical units, so if the user asks for that, return none.
9415	 */
9416	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9417
9418	/*
9419	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9420	 * this request.
9421	 */
9422	ctl_set_success(ctsio);
9423	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9424	ctsio->be_move_done = ctl_config_move_done;
9425	ctl_datamove((union ctl_io *)ctsio);
9426	return (retval);
9427}
9428
9429int
9430ctl_request_sense(struct ctl_scsiio *ctsio)
9431{
9432	struct scsi_request_sense *cdb;
9433	struct scsi_sense_data *sense_ptr;
9434	struct ctl_softc *ctl_softc;
9435	struct ctl_lun *lun;
9436	uint32_t initidx;
9437	int have_error;
9438	scsi_sense_data_type sense_format;
9439	ctl_ua_type ua_type;
9440
9441	cdb = (struct scsi_request_sense *)ctsio->cdb;
9442
9443	ctl_softc = control_softc;
9444	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9445
9446	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9447
9448	/*
9449	 * Determine which sense format the user wants.
9450	 */
9451	if (cdb->byte2 & SRS_DESC)
9452		sense_format = SSD_TYPE_DESC;
9453	else
9454		sense_format = SSD_TYPE_FIXED;
9455
9456	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9457	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9458	ctsio->kern_sg_entries = 0;
9459
9460	/*
9461	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9462	 * larger than the largest allowed value for the length field in the
9463	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9464	 */
9465	ctsio->residual = 0;
9466	ctsio->kern_data_len = cdb->length;
9467	ctsio->kern_total_len = cdb->length;
9468
9469	ctsio->kern_data_resid = 0;
9470	ctsio->kern_rel_offset = 0;
9471	ctsio->kern_sg_entries = 0;
9472
9473	/*
9474	 * If we don't have a LUN, we don't have any pending sense.
9475	 */
9476	if (lun == NULL)
9477		goto no_sense;
9478
9479	have_error = 0;
9480	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9481	/*
9482	 * Check for pending sense, and then for pending unit attentions.
9483	 * Pending sense gets returned first, then pending unit attentions.
9484	 */
9485	mtx_lock(&lun->lun_lock);
9486#ifdef CTL_WITH_CA
9487	if (ctl_is_set(lun->have_ca, initidx)) {
9488		scsi_sense_data_type stored_format;
9489
9490		/*
9491		 * Check to see which sense format was used for the stored
9492		 * sense data.
9493		 */
9494		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9495
9496		/*
9497		 * If the user requested a different sense format than the
9498		 * one we stored, then we need to convert it to the other
9499		 * format.  If we're going from descriptor to fixed format
9500		 * sense data, we may lose things in translation, depending
9501		 * on what options were used.
9502		 *
9503		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9504		 * for some reason we'll just copy it out as-is.
9505		 */
9506		if ((stored_format == SSD_TYPE_FIXED)
9507		 && (sense_format == SSD_TYPE_DESC))
9508			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9509			    &lun->pending_sense[initidx],
9510			    (struct scsi_sense_data_desc *)sense_ptr);
9511		else if ((stored_format == SSD_TYPE_DESC)
9512		      && (sense_format == SSD_TYPE_FIXED))
9513			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9514			    &lun->pending_sense[initidx],
9515			    (struct scsi_sense_data_fixed *)sense_ptr);
9516		else
9517			memcpy(sense_ptr, &lun->pending_sense[initidx],
9518			       MIN(sizeof(*sense_ptr),
9519			       sizeof(lun->pending_sense[initidx])));
9520
9521		ctl_clear_mask(lun->have_ca, initidx);
9522		have_error = 1;
9523	} else
9524#endif
9525	{
9526		ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9527		if (ua_type != CTL_UA_NONE)
9528			have_error = 1;
9529		if (ua_type == CTL_UA_LUN_CHANGE) {
9530			mtx_unlock(&lun->lun_lock);
9531			mtx_lock(&ctl_softc->ctl_lock);
9532			ctl_clr_ua_allluns(ctl_softc, initidx, ua_type);
9533			mtx_unlock(&ctl_softc->ctl_lock);
9534			mtx_lock(&lun->lun_lock);
9535		}
9536
9537	}
9538	mtx_unlock(&lun->lun_lock);
9539
9540	/*
9541	 * We already have a pending error, return it.
9542	 */
9543	if (have_error != 0) {
9544		/*
9545		 * We report the SCSI status as OK, since the status of the
9546		 * request sense command itself is OK.
9547		 * We report 0 for the sense length, because we aren't doing
9548		 * autosense in this case.  We're reporting sense as
9549		 * parameter data.
9550		 */
9551		ctl_set_success(ctsio);
9552		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9553		ctsio->be_move_done = ctl_config_move_done;
9554		ctl_datamove((union ctl_io *)ctsio);
9555		return (CTL_RETVAL_COMPLETE);
9556	}
9557
9558no_sense:
9559
9560	/*
9561	 * No sense information to report, so we report that everything is
9562	 * okay.
9563	 */
9564	ctl_set_sense_data(sense_ptr,
9565			   lun,
9566			   sense_format,
9567			   /*current_error*/ 1,
9568			   /*sense_key*/ SSD_KEY_NO_SENSE,
9569			   /*asc*/ 0x00,
9570			   /*ascq*/ 0x00,
9571			   SSD_ELEM_NONE);
9572
9573	/*
9574	 * We report 0 for the sense length, because we aren't doing
9575	 * autosense in this case.  We're reporting sense as parameter data.
9576	 */
9577	ctl_set_success(ctsio);
9578	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9579	ctsio->be_move_done = ctl_config_move_done;
9580	ctl_datamove((union ctl_io *)ctsio);
9581	return (CTL_RETVAL_COMPLETE);
9582}
9583
9584int
9585ctl_tur(struct ctl_scsiio *ctsio)
9586{
9587
9588	CTL_DEBUG_PRINT(("ctl_tur\n"));
9589
9590	ctl_set_success(ctsio);
9591	ctl_done((union ctl_io *)ctsio);
9592
9593	return (CTL_RETVAL_COMPLETE);
9594}
9595
9596/*
9597 * SCSI VPD page 0x00, the Supported VPD Pages page.
9598 */
9599static int
9600ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9601{
9602	struct scsi_vpd_supported_pages *pages;
9603	int sup_page_size;
9604	struct ctl_lun *lun;
9605	int p;
9606
9607	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9608
9609	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9610	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9611	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9612	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9613	ctsio->kern_sg_entries = 0;
9614
9615	if (sup_page_size < alloc_len) {
9616		ctsio->residual = alloc_len - sup_page_size;
9617		ctsio->kern_data_len = sup_page_size;
9618		ctsio->kern_total_len = sup_page_size;
9619	} else {
9620		ctsio->residual = 0;
9621		ctsio->kern_data_len = alloc_len;
9622		ctsio->kern_total_len = alloc_len;
9623	}
9624	ctsio->kern_data_resid = 0;
9625	ctsio->kern_rel_offset = 0;
9626	ctsio->kern_sg_entries = 0;
9627
9628	/*
9629	 * The control device is always connected.  The disk device, on the
9630	 * other hand, may not be online all the time.  Need to change this
9631	 * to figure out whether the disk device is actually online or not.
9632	 */
9633	if (lun != NULL)
9634		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9635				lun->be_lun->lun_type;
9636	else
9637		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9638
9639	p = 0;
9640	/* Supported VPD pages */
9641	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9642	/* Serial Number */
9643	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9644	/* Device Identification */
9645	pages->page_list[p++] = SVPD_DEVICE_ID;
9646	/* Extended INQUIRY Data */
9647	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9648	/* Mode Page Policy */
9649	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9650	/* SCSI Ports */
9651	pages->page_list[p++] = SVPD_SCSI_PORTS;
9652	/* Third-party Copy */
9653	pages->page_list[p++] = SVPD_SCSI_TPC;
9654	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9655		/* Block limits */
9656		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9657		/* Block Device Characteristics */
9658		pages->page_list[p++] = SVPD_BDC;
9659		/* Logical Block Provisioning */
9660		pages->page_list[p++] = SVPD_LBP;
9661	}
9662	pages->length = p;
9663
9664	ctl_set_success(ctsio);
9665	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9666	ctsio->be_move_done = ctl_config_move_done;
9667	ctl_datamove((union ctl_io *)ctsio);
9668	return (CTL_RETVAL_COMPLETE);
9669}
9670
9671/*
9672 * SCSI VPD page 0x80, the Unit Serial Number page.
9673 */
9674static int
9675ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9676{
9677	struct scsi_vpd_unit_serial_number *sn_ptr;
9678	struct ctl_lun *lun;
9679	int data_len;
9680
9681	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9682
9683	data_len = 4 + CTL_SN_LEN;
9684	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9685	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9686	if (data_len < alloc_len) {
9687		ctsio->residual = alloc_len - data_len;
9688		ctsio->kern_data_len = data_len;
9689		ctsio->kern_total_len = data_len;
9690	} else {
9691		ctsio->residual = 0;
9692		ctsio->kern_data_len = alloc_len;
9693		ctsio->kern_total_len = alloc_len;
9694	}
9695	ctsio->kern_data_resid = 0;
9696	ctsio->kern_rel_offset = 0;
9697	ctsio->kern_sg_entries = 0;
9698
9699	/*
9700	 * The control device is always connected.  The disk device, on the
9701	 * other hand, may not be online all the time.  Need to change this
9702	 * to figure out whether the disk device is actually online or not.
9703	 */
9704	if (lun != NULL)
9705		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9706				  lun->be_lun->lun_type;
9707	else
9708		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9709
9710	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9711	sn_ptr->length = CTL_SN_LEN;
9712	/*
9713	 * If we don't have a LUN, we just leave the serial number as
9714	 * all spaces.
9715	 */
9716	if (lun != NULL) {
9717		strncpy((char *)sn_ptr->serial_num,
9718			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9719	} else
9720		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9721
9722	ctl_set_success(ctsio);
9723	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9724	ctsio->be_move_done = ctl_config_move_done;
9725	ctl_datamove((union ctl_io *)ctsio);
9726	return (CTL_RETVAL_COMPLETE);
9727}
9728
9729
9730/*
9731 * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9732 */
9733static int
9734ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9735{
9736	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9737	struct ctl_lun *lun;
9738	int data_len;
9739
9740	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9741
9742	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9743	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9744	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9745	ctsio->kern_sg_entries = 0;
9746
9747	if (data_len < alloc_len) {
9748		ctsio->residual = alloc_len - data_len;
9749		ctsio->kern_data_len = data_len;
9750		ctsio->kern_total_len = data_len;
9751	} else {
9752		ctsio->residual = 0;
9753		ctsio->kern_data_len = alloc_len;
9754		ctsio->kern_total_len = alloc_len;
9755	}
9756	ctsio->kern_data_resid = 0;
9757	ctsio->kern_rel_offset = 0;
9758	ctsio->kern_sg_entries = 0;
9759
9760	/*
9761	 * The control device is always connected.  The disk device, on the
9762	 * other hand, may not be online all the time.
9763	 */
9764	if (lun != NULL)
9765		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9766				     lun->be_lun->lun_type;
9767	else
9768		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9769	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9770	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9771	/*
9772	 * We support head of queue, ordered and simple tags.
9773	 */
9774	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9775	/*
9776	 * Volatile cache supported.
9777	 */
9778	eid_ptr->flags3 = SVPD_EID_V_SUP;
9779
9780	/*
9781	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9782	 * attention for a particular IT nexus on all LUNs once we report
9783	 * it to that nexus once.  This bit is required as of SPC-4.
9784	 */
9785	eid_ptr->flags4 = SVPD_EID_LUICLT;
9786
9787	/*
9788	 * XXX KDM in order to correctly answer this, we would need
9789	 * information from the SIM to determine how much sense data it
9790	 * can send.  So this would really be a path inquiry field, most
9791	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9792	 * but the hardware may or may not be able to support that much.
9793	 * 0 just means that the maximum sense data length is not reported.
9794	 */
9795	eid_ptr->max_sense_length = 0;
9796
9797	ctl_set_success(ctsio);
9798	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9799	ctsio->be_move_done = ctl_config_move_done;
9800	ctl_datamove((union ctl_io *)ctsio);
9801	return (CTL_RETVAL_COMPLETE);
9802}
9803
9804static int
9805ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9806{
9807	struct scsi_vpd_mode_page_policy *mpp_ptr;
9808	struct ctl_lun *lun;
9809	int data_len;
9810
9811	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9812
9813	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9814	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9815
9816	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9817	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9818	ctsio->kern_sg_entries = 0;
9819
9820	if (data_len < alloc_len) {
9821		ctsio->residual = alloc_len - data_len;
9822		ctsio->kern_data_len = data_len;
9823		ctsio->kern_total_len = data_len;
9824	} else {
9825		ctsio->residual = 0;
9826		ctsio->kern_data_len = alloc_len;
9827		ctsio->kern_total_len = alloc_len;
9828	}
9829	ctsio->kern_data_resid = 0;
9830	ctsio->kern_rel_offset = 0;
9831	ctsio->kern_sg_entries = 0;
9832
9833	/*
9834	 * The control device is always connected.  The disk device, on the
9835	 * other hand, may not be online all the time.
9836	 */
9837	if (lun != NULL)
9838		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9839				     lun->be_lun->lun_type;
9840	else
9841		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9842	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9843	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9844	mpp_ptr->descr[0].page_code = 0x3f;
9845	mpp_ptr->descr[0].subpage_code = 0xff;
9846	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9847
9848	ctl_set_success(ctsio);
9849	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9850	ctsio->be_move_done = ctl_config_move_done;
9851	ctl_datamove((union ctl_io *)ctsio);
9852	return (CTL_RETVAL_COMPLETE);
9853}
9854
9855/*
9856 * SCSI VPD page 0x83, the Device Identification page.
9857 */
9858static int
9859ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9860{
9861	struct scsi_vpd_device_id *devid_ptr;
9862	struct scsi_vpd_id_descriptor *desc;
9863	struct ctl_softc *softc;
9864	struct ctl_lun *lun;
9865	struct ctl_port *port;
9866	int data_len;
9867	uint8_t proto;
9868
9869	softc = control_softc;
9870
9871	port = ctl_io_port(&ctsio->io_hdr);
9872	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9873
9874	data_len = sizeof(struct scsi_vpd_device_id) +
9875	    sizeof(struct scsi_vpd_id_descriptor) +
9876		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9877	    sizeof(struct scsi_vpd_id_descriptor) +
9878		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9879	if (lun && lun->lun_devid)
9880		data_len += lun->lun_devid->len;
9881	if (port && port->port_devid)
9882		data_len += port->port_devid->len;
9883	if (port && port->target_devid)
9884		data_len += port->target_devid->len;
9885
9886	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9887	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9888	ctsio->kern_sg_entries = 0;
9889
9890	if (data_len < alloc_len) {
9891		ctsio->residual = alloc_len - data_len;
9892		ctsio->kern_data_len = data_len;
9893		ctsio->kern_total_len = data_len;
9894	} else {
9895		ctsio->residual = 0;
9896		ctsio->kern_data_len = alloc_len;
9897		ctsio->kern_total_len = alloc_len;
9898	}
9899	ctsio->kern_data_resid = 0;
9900	ctsio->kern_rel_offset = 0;
9901	ctsio->kern_sg_entries = 0;
9902
9903	/*
9904	 * The control device is always connected.  The disk device, on the
9905	 * other hand, may not be online all the time.
9906	 */
9907	if (lun != NULL)
9908		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9909				     lun->be_lun->lun_type;
9910	else
9911		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9912	devid_ptr->page_code = SVPD_DEVICE_ID;
9913	scsi_ulto2b(data_len - 4, devid_ptr->length);
9914
9915	if (port && port->port_type == CTL_PORT_FC)
9916		proto = SCSI_PROTO_FC << 4;
9917	else if (port && port->port_type == CTL_PORT_ISCSI)
9918		proto = SCSI_PROTO_ISCSI << 4;
9919	else
9920		proto = SCSI_PROTO_SPI << 4;
9921	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9922
9923	/*
9924	 * We're using a LUN association here.  i.e., this device ID is a
9925	 * per-LUN identifier.
9926	 */
9927	if (lun && lun->lun_devid) {
9928		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9929		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9930		    lun->lun_devid->len);
9931	}
9932
9933	/*
9934	 * This is for the WWPN which is a port association.
9935	 */
9936	if (port && port->port_devid) {
9937		memcpy(desc, port->port_devid->data, port->port_devid->len);
9938		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9939		    port->port_devid->len);
9940	}
9941
9942	/*
9943	 * This is for the Relative Target Port(type 4h) identifier
9944	 */
9945	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9946	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9947	    SVPD_ID_TYPE_RELTARG;
9948	desc->length = 4;
9949	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9950	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9951	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9952
9953	/*
9954	 * This is for the Target Port Group(type 5h) 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_TPORTGRP;
9959	desc->length = 4;
9960	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / softc->port_cnt + 1,
9961	    &desc->identifier[2]);
9962	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9963	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9964
9965	/*
9966	 * This is for the Target identifier
9967	 */
9968	if (port && port->target_devid) {
9969		memcpy(desc, port->target_devid->data, port->target_devid->len);
9970	}
9971
9972	ctl_set_success(ctsio);
9973	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9974	ctsio->be_move_done = ctl_config_move_done;
9975	ctl_datamove((union ctl_io *)ctsio);
9976	return (CTL_RETVAL_COMPLETE);
9977}
9978
9979static int
9980ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9981{
9982	struct ctl_softc *softc = control_softc;
9983	struct scsi_vpd_scsi_ports *sp;
9984	struct scsi_vpd_port_designation *pd;
9985	struct scsi_vpd_port_designation_cont *pdc;
9986	struct ctl_lun *lun;
9987	struct ctl_port *port;
9988	int data_len, num_target_ports, iid_len, id_len;
9989
9990	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9991
9992	num_target_ports = 0;
9993	iid_len = 0;
9994	id_len = 0;
9995	mtx_lock(&softc->ctl_lock);
9996	STAILQ_FOREACH(port, &softc->port_list, links) {
9997		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9998			continue;
9999		if (lun != NULL &&
10000		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
10001			continue;
10002		num_target_ports++;
10003		if (port->init_devid)
10004			iid_len += port->init_devid->len;
10005		if (port->port_devid)
10006			id_len += port->port_devid->len;
10007	}
10008	mtx_unlock(&softc->ctl_lock);
10009
10010	data_len = sizeof(struct scsi_vpd_scsi_ports) +
10011	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10012	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10013	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10014	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10015	ctsio->kern_sg_entries = 0;
10016
10017	if (data_len < alloc_len) {
10018		ctsio->residual = alloc_len - data_len;
10019		ctsio->kern_data_len = data_len;
10020		ctsio->kern_total_len = data_len;
10021	} else {
10022		ctsio->residual = 0;
10023		ctsio->kern_data_len = alloc_len;
10024		ctsio->kern_total_len = alloc_len;
10025	}
10026	ctsio->kern_data_resid = 0;
10027	ctsio->kern_rel_offset = 0;
10028	ctsio->kern_sg_entries = 0;
10029
10030	/*
10031	 * The control device is always connected.  The disk device, on the
10032	 * other hand, may not be online all the time.  Need to change this
10033	 * to figure out whether the disk device is actually online or not.
10034	 */
10035	if (lun != NULL)
10036		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10037				  lun->be_lun->lun_type;
10038	else
10039		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10040
10041	sp->page_code = SVPD_SCSI_PORTS;
10042	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10043	    sp->page_length);
10044	pd = &sp->design[0];
10045
10046	mtx_lock(&softc->ctl_lock);
10047	STAILQ_FOREACH(port, &softc->port_list, links) {
10048		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10049			continue;
10050		if (lun != NULL &&
10051		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
10052			continue;
10053		scsi_ulto2b(port->targ_port, pd->relative_port_id);
10054		if (port->init_devid) {
10055			iid_len = port->init_devid->len;
10056			memcpy(pd->initiator_transportid,
10057			    port->init_devid->data, port->init_devid->len);
10058		} else
10059			iid_len = 0;
10060		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10061		pdc = (struct scsi_vpd_port_designation_cont *)
10062		    (&pd->initiator_transportid[iid_len]);
10063		if (port->port_devid) {
10064			id_len = port->port_devid->len;
10065			memcpy(pdc->target_port_descriptors,
10066			    port->port_devid->data, port->port_devid->len);
10067		} else
10068			id_len = 0;
10069		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10070		pd = (struct scsi_vpd_port_designation *)
10071		    ((uint8_t *)pdc->target_port_descriptors + id_len);
10072	}
10073	mtx_unlock(&softc->ctl_lock);
10074
10075	ctl_set_success(ctsio);
10076	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10077	ctsio->be_move_done = ctl_config_move_done;
10078	ctl_datamove((union ctl_io *)ctsio);
10079	return (CTL_RETVAL_COMPLETE);
10080}
10081
10082static int
10083ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10084{
10085	struct scsi_vpd_block_limits *bl_ptr;
10086	struct ctl_lun *lun;
10087	int bs;
10088
10089	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10090
10091	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10092	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10093	ctsio->kern_sg_entries = 0;
10094
10095	if (sizeof(*bl_ptr) < alloc_len) {
10096		ctsio->residual = alloc_len - sizeof(*bl_ptr);
10097		ctsio->kern_data_len = sizeof(*bl_ptr);
10098		ctsio->kern_total_len = sizeof(*bl_ptr);
10099	} else {
10100		ctsio->residual = 0;
10101		ctsio->kern_data_len = alloc_len;
10102		ctsio->kern_total_len = alloc_len;
10103	}
10104	ctsio->kern_data_resid = 0;
10105	ctsio->kern_rel_offset = 0;
10106	ctsio->kern_sg_entries = 0;
10107
10108	/*
10109	 * The control device is always connected.  The disk device, on the
10110	 * other hand, may not be online all the time.  Need to change this
10111	 * to figure out whether the disk device is actually online or not.
10112	 */
10113	if (lun != NULL)
10114		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10115				  lun->be_lun->lun_type;
10116	else
10117		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10118
10119	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10120	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10121	bl_ptr->max_cmp_write_len = 0xff;
10122	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10123	if (lun != NULL) {
10124		bs = lun->be_lun->blocksize;
10125		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
10126		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10127			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10128			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10129			if (lun->be_lun->ublockexp != 0) {
10130				scsi_ulto4b((1 << lun->be_lun->ublockexp),
10131				    bl_ptr->opt_unmap_grain);
10132				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
10133				    bl_ptr->unmap_grain_align);
10134			}
10135		}
10136		scsi_ulto4b(lun->be_lun->atomicblock,
10137		    bl_ptr->max_atomic_transfer_length);
10138		scsi_ulto4b(0, bl_ptr->atomic_alignment);
10139		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10140		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
10141		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
10142	}
10143	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10144
10145	ctl_set_success(ctsio);
10146	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10147	ctsio->be_move_done = ctl_config_move_done;
10148	ctl_datamove((union ctl_io *)ctsio);
10149	return (CTL_RETVAL_COMPLETE);
10150}
10151
10152static int
10153ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10154{
10155	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10156	struct ctl_lun *lun;
10157	const char *value;
10158	u_int i;
10159
10160	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10161
10162	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10163	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10164	ctsio->kern_sg_entries = 0;
10165
10166	if (sizeof(*bdc_ptr) < alloc_len) {
10167		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10168		ctsio->kern_data_len = sizeof(*bdc_ptr);
10169		ctsio->kern_total_len = sizeof(*bdc_ptr);
10170	} else {
10171		ctsio->residual = 0;
10172		ctsio->kern_data_len = alloc_len;
10173		ctsio->kern_total_len = alloc_len;
10174	}
10175	ctsio->kern_data_resid = 0;
10176	ctsio->kern_rel_offset = 0;
10177	ctsio->kern_sg_entries = 0;
10178
10179	/*
10180	 * The control device is always connected.  The disk device, on the
10181	 * other hand, may not be online all the time.  Need to change this
10182	 * to figure out whether the disk device is actually online or not.
10183	 */
10184	if (lun != NULL)
10185		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10186				  lun->be_lun->lun_type;
10187	else
10188		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10189	bdc_ptr->page_code = SVPD_BDC;
10190	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10191	if (lun != NULL &&
10192	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10193		i = strtol(value, NULL, 0);
10194	else
10195		i = CTL_DEFAULT_ROTATION_RATE;
10196	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10197	if (lun != NULL &&
10198	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10199		i = strtol(value, NULL, 0);
10200	else
10201		i = 0;
10202	bdc_ptr->wab_wac_ff = (i & 0x0f);
10203	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10204
10205	ctl_set_success(ctsio);
10206	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10207	ctsio->be_move_done = ctl_config_move_done;
10208	ctl_datamove((union ctl_io *)ctsio);
10209	return (CTL_RETVAL_COMPLETE);
10210}
10211
10212static int
10213ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10214{
10215	struct scsi_vpd_logical_block_prov *lbp_ptr;
10216	struct ctl_lun *lun;
10217
10218	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10219
10220	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10221	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10222	ctsio->kern_sg_entries = 0;
10223
10224	if (sizeof(*lbp_ptr) < alloc_len) {
10225		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10226		ctsio->kern_data_len = sizeof(*lbp_ptr);
10227		ctsio->kern_total_len = sizeof(*lbp_ptr);
10228	} else {
10229		ctsio->residual = 0;
10230		ctsio->kern_data_len = alloc_len;
10231		ctsio->kern_total_len = alloc_len;
10232	}
10233	ctsio->kern_data_resid = 0;
10234	ctsio->kern_rel_offset = 0;
10235	ctsio->kern_sg_entries = 0;
10236
10237	/*
10238	 * The control device is always connected.  The disk device, on the
10239	 * other hand, may not be online all the time.  Need to change this
10240	 * to figure out whether the disk device is actually online or not.
10241	 */
10242	if (lun != NULL)
10243		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10244				  lun->be_lun->lun_type;
10245	else
10246		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10247
10248	lbp_ptr->page_code = SVPD_LBP;
10249	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10250	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10251	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10252		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10253		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10254		lbp_ptr->prov_type = SVPD_LBP_THIN;
10255	}
10256
10257	ctl_set_success(ctsio);
10258	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10259	ctsio->be_move_done = ctl_config_move_done;
10260	ctl_datamove((union ctl_io *)ctsio);
10261	return (CTL_RETVAL_COMPLETE);
10262}
10263
10264/*
10265 * INQUIRY with the EVPD bit set.
10266 */
10267static int
10268ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10269{
10270	struct ctl_lun *lun;
10271	struct scsi_inquiry *cdb;
10272	int alloc_len, retval;
10273
10274	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10275	cdb = (struct scsi_inquiry *)ctsio->cdb;
10276	alloc_len = scsi_2btoul(cdb->length);
10277
10278	switch (cdb->page_code) {
10279	case SVPD_SUPPORTED_PAGES:
10280		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10281		break;
10282	case SVPD_UNIT_SERIAL_NUMBER:
10283		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10284		break;
10285	case SVPD_DEVICE_ID:
10286		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10287		break;
10288	case SVPD_EXTENDED_INQUIRY_DATA:
10289		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10290		break;
10291	case SVPD_MODE_PAGE_POLICY:
10292		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10293		break;
10294	case SVPD_SCSI_PORTS:
10295		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10296		break;
10297	case SVPD_SCSI_TPC:
10298		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10299		break;
10300	case SVPD_BLOCK_LIMITS:
10301		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10302			goto err;
10303		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10304		break;
10305	case SVPD_BDC:
10306		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10307			goto err;
10308		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10309		break;
10310	case SVPD_LBP:
10311		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10312			goto err;
10313		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10314		break;
10315	default:
10316err:
10317		ctl_set_invalid_field(ctsio,
10318				      /*sks_valid*/ 1,
10319				      /*command*/ 1,
10320				      /*field*/ 2,
10321				      /*bit_valid*/ 0,
10322				      /*bit*/ 0);
10323		ctl_done((union ctl_io *)ctsio);
10324		retval = CTL_RETVAL_COMPLETE;
10325		break;
10326	}
10327
10328	return (retval);
10329}
10330
10331/*
10332 * Standard INQUIRY data.
10333 */
10334static int
10335ctl_inquiry_std(struct ctl_scsiio *ctsio)
10336{
10337	struct scsi_inquiry_data *inq_ptr;
10338	struct scsi_inquiry *cdb;
10339	struct ctl_softc *softc = control_softc;
10340	struct ctl_port *port;
10341	struct ctl_lun *lun;
10342	char *val;
10343	uint32_t alloc_len, data_len;
10344	ctl_port_type port_type;
10345
10346	/*
10347	 * Figure out whether we're talking to a Fibre Channel port or not.
10348	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10349	 * SCSI front ends.
10350	 */
10351	port = ctl_io_port(&ctsio->io_hdr);
10352	if (port != NULL)
10353		port_type = port->port_type;
10354	else
10355		port_type = CTL_PORT_SCSI;
10356	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10357		port_type = CTL_PORT_SCSI;
10358
10359	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10360	cdb = (struct scsi_inquiry *)ctsio->cdb;
10361	alloc_len = scsi_2btoul(cdb->length);
10362
10363	/*
10364	 * We malloc the full inquiry data size here and fill it
10365	 * in.  If the user only asks for less, we'll give him
10366	 * that much.
10367	 */
10368	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10369	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10370	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10371	ctsio->kern_sg_entries = 0;
10372	ctsio->kern_data_resid = 0;
10373	ctsio->kern_rel_offset = 0;
10374
10375	if (data_len < alloc_len) {
10376		ctsio->residual = alloc_len - data_len;
10377		ctsio->kern_data_len = data_len;
10378		ctsio->kern_total_len = data_len;
10379	} else {
10380		ctsio->residual = 0;
10381		ctsio->kern_data_len = alloc_len;
10382		ctsio->kern_total_len = alloc_len;
10383	}
10384
10385	if (lun != NULL) {
10386		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10387		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10388			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10389			    lun->be_lun->lun_type;
10390		} else {
10391			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10392			    lun->be_lun->lun_type;
10393		}
10394	} else
10395		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10396
10397	/* RMB in byte 2 is 0 */
10398	inq_ptr->version = SCSI_REV_SPC4;
10399
10400	/*
10401	 * According to SAM-3, even if a device only supports a single
10402	 * level of LUN addressing, it should still set the HISUP bit:
10403	 *
10404	 * 4.9.1 Logical unit numbers overview
10405	 *
10406	 * All logical unit number formats described in this standard are
10407	 * hierarchical in structure even when only a single level in that
10408	 * hierarchy is used. The HISUP bit shall be set to one in the
10409	 * standard INQUIRY data (see SPC-2) when any logical unit number
10410	 * format described in this standard is used.  Non-hierarchical
10411	 * formats are outside the scope of this standard.
10412	 *
10413	 * Therefore we set the HiSup bit here.
10414	 *
10415	 * The reponse format is 2, per SPC-3.
10416	 */
10417	inq_ptr->response_format = SID_HiSup | 2;
10418
10419	inq_ptr->additional_length = data_len -
10420	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10421	CTL_DEBUG_PRINT(("additional_length = %d\n",
10422			 inq_ptr->additional_length));
10423
10424	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10425	/* 16 bit addressing */
10426	if (port_type == CTL_PORT_SCSI)
10427		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10428	/* XXX set the SID_MultiP bit here if we're actually going to
10429	   respond on multiple ports */
10430	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10431
10432	/* 16 bit data bus, synchronous transfers */
10433	if (port_type == CTL_PORT_SCSI)
10434		inq_ptr->flags = SID_WBus16 | SID_Sync;
10435	/*
10436	 * XXX KDM do we want to support tagged queueing on the control
10437	 * device at all?
10438	 */
10439	if ((lun == NULL)
10440	 || (lun->be_lun->lun_type != T_PROCESSOR))
10441		inq_ptr->flags |= SID_CmdQue;
10442	/*
10443	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10444	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10445	 * name and 4 bytes for the revision.
10446	 */
10447	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10448	    "vendor")) == NULL) {
10449		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10450	} else {
10451		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10452		strncpy(inq_ptr->vendor, val,
10453		    min(sizeof(inq_ptr->vendor), strlen(val)));
10454	}
10455	if (lun == NULL) {
10456		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10457		    sizeof(inq_ptr->product));
10458	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10459		switch (lun->be_lun->lun_type) {
10460		case T_DIRECT:
10461			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10462			    sizeof(inq_ptr->product));
10463			break;
10464		case T_PROCESSOR:
10465			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10466			    sizeof(inq_ptr->product));
10467			break;
10468		default:
10469			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10470			    sizeof(inq_ptr->product));
10471			break;
10472		}
10473	} else {
10474		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10475		strncpy(inq_ptr->product, val,
10476		    min(sizeof(inq_ptr->product), strlen(val)));
10477	}
10478
10479	/*
10480	 * XXX make this a macro somewhere so it automatically gets
10481	 * incremented when we make changes.
10482	 */
10483	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10484	    "revision")) == NULL) {
10485		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10486	} else {
10487		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10488		strncpy(inq_ptr->revision, val,
10489		    min(sizeof(inq_ptr->revision), strlen(val)));
10490	}
10491
10492	/*
10493	 * For parallel SCSI, we support double transition and single
10494	 * transition clocking.  We also support QAS (Quick Arbitration
10495	 * and Selection) and Information Unit transfers on both the
10496	 * control and array devices.
10497	 */
10498	if (port_type == CTL_PORT_SCSI)
10499		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10500				    SID_SPI_IUS;
10501
10502	/* SAM-5 (no version claimed) */
10503	scsi_ulto2b(0x00A0, inq_ptr->version1);
10504	/* SPC-4 (no version claimed) */
10505	scsi_ulto2b(0x0460, inq_ptr->version2);
10506	if (port_type == CTL_PORT_FC) {
10507		/* FCP-2 ANSI INCITS.350:2003 */
10508		scsi_ulto2b(0x0917, inq_ptr->version3);
10509	} else if (port_type == CTL_PORT_SCSI) {
10510		/* SPI-4 ANSI INCITS.362:200x */
10511		scsi_ulto2b(0x0B56, inq_ptr->version3);
10512	} else if (port_type == CTL_PORT_ISCSI) {
10513		/* iSCSI (no version claimed) */
10514		scsi_ulto2b(0x0960, inq_ptr->version3);
10515	} else if (port_type == CTL_PORT_SAS) {
10516		/* SAS (no version claimed) */
10517		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10518	}
10519
10520	if (lun == NULL) {
10521		/* SBC-4 (no version claimed) */
10522		scsi_ulto2b(0x0600, inq_ptr->version4);
10523	} else {
10524		switch (lun->be_lun->lun_type) {
10525		case T_DIRECT:
10526			/* SBC-4 (no version claimed) */
10527			scsi_ulto2b(0x0600, inq_ptr->version4);
10528			break;
10529		case T_PROCESSOR:
10530		default:
10531			break;
10532		}
10533	}
10534
10535	ctl_set_success(ctsio);
10536	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10537	ctsio->be_move_done = ctl_config_move_done;
10538	ctl_datamove((union ctl_io *)ctsio);
10539	return (CTL_RETVAL_COMPLETE);
10540}
10541
10542int
10543ctl_inquiry(struct ctl_scsiio *ctsio)
10544{
10545	struct scsi_inquiry *cdb;
10546	int retval;
10547
10548	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10549
10550	cdb = (struct scsi_inquiry *)ctsio->cdb;
10551	if (cdb->byte2 & SI_EVPD)
10552		retval = ctl_inquiry_evpd(ctsio);
10553	else if (cdb->page_code == 0)
10554		retval = ctl_inquiry_std(ctsio);
10555	else {
10556		ctl_set_invalid_field(ctsio,
10557				      /*sks_valid*/ 1,
10558				      /*command*/ 1,
10559				      /*field*/ 2,
10560				      /*bit_valid*/ 0,
10561				      /*bit*/ 0);
10562		ctl_done((union ctl_io *)ctsio);
10563		return (CTL_RETVAL_COMPLETE);
10564	}
10565
10566	return (retval);
10567}
10568
10569/*
10570 * For known CDB types, parse the LBA and length.
10571 */
10572static int
10573ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10574{
10575	if (io->io_hdr.io_type != CTL_IO_SCSI)
10576		return (1);
10577
10578	switch (io->scsiio.cdb[0]) {
10579	case COMPARE_AND_WRITE: {
10580		struct scsi_compare_and_write *cdb;
10581
10582		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10583
10584		*lba = scsi_8btou64(cdb->addr);
10585		*len = cdb->length;
10586		break;
10587	}
10588	case READ_6:
10589	case WRITE_6: {
10590		struct scsi_rw_6 *cdb;
10591
10592		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10593
10594		*lba = scsi_3btoul(cdb->addr);
10595		/* only 5 bits are valid in the most significant address byte */
10596		*lba &= 0x1fffff;
10597		*len = cdb->length;
10598		break;
10599	}
10600	case READ_10:
10601	case WRITE_10: {
10602		struct scsi_rw_10 *cdb;
10603
10604		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10605
10606		*lba = scsi_4btoul(cdb->addr);
10607		*len = scsi_2btoul(cdb->length);
10608		break;
10609	}
10610	case WRITE_VERIFY_10: {
10611		struct scsi_write_verify_10 *cdb;
10612
10613		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10614
10615		*lba = scsi_4btoul(cdb->addr);
10616		*len = scsi_2btoul(cdb->length);
10617		break;
10618	}
10619	case READ_12:
10620	case WRITE_12: {
10621		struct scsi_rw_12 *cdb;
10622
10623		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10624
10625		*lba = scsi_4btoul(cdb->addr);
10626		*len = scsi_4btoul(cdb->length);
10627		break;
10628	}
10629	case WRITE_VERIFY_12: {
10630		struct scsi_write_verify_12 *cdb;
10631
10632		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10633
10634		*lba = scsi_4btoul(cdb->addr);
10635		*len = scsi_4btoul(cdb->length);
10636		break;
10637	}
10638	case READ_16:
10639	case WRITE_16: {
10640		struct scsi_rw_16 *cdb;
10641
10642		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10643
10644		*lba = scsi_8btou64(cdb->addr);
10645		*len = scsi_4btoul(cdb->length);
10646		break;
10647	}
10648	case WRITE_ATOMIC_16: {
10649		struct scsi_write_atomic_16 *cdb;
10650
10651		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10652
10653		*lba = scsi_8btou64(cdb->addr);
10654		*len = scsi_2btoul(cdb->length);
10655		break;
10656	}
10657	case WRITE_VERIFY_16: {
10658		struct scsi_write_verify_16 *cdb;
10659
10660		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10661
10662		*lba = scsi_8btou64(cdb->addr);
10663		*len = scsi_4btoul(cdb->length);
10664		break;
10665	}
10666	case WRITE_SAME_10: {
10667		struct scsi_write_same_10 *cdb;
10668
10669		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10670
10671		*lba = scsi_4btoul(cdb->addr);
10672		*len = scsi_2btoul(cdb->length);
10673		break;
10674	}
10675	case WRITE_SAME_16: {
10676		struct scsi_write_same_16 *cdb;
10677
10678		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10679
10680		*lba = scsi_8btou64(cdb->addr);
10681		*len = scsi_4btoul(cdb->length);
10682		break;
10683	}
10684	case VERIFY_10: {
10685		struct scsi_verify_10 *cdb;
10686
10687		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10688
10689		*lba = scsi_4btoul(cdb->addr);
10690		*len = scsi_2btoul(cdb->length);
10691		break;
10692	}
10693	case VERIFY_12: {
10694		struct scsi_verify_12 *cdb;
10695
10696		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10697
10698		*lba = scsi_4btoul(cdb->addr);
10699		*len = scsi_4btoul(cdb->length);
10700		break;
10701	}
10702	case VERIFY_16: {
10703		struct scsi_verify_16 *cdb;
10704
10705		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10706
10707		*lba = scsi_8btou64(cdb->addr);
10708		*len = scsi_4btoul(cdb->length);
10709		break;
10710	}
10711	case UNMAP: {
10712		*lba = 0;
10713		*len = UINT64_MAX;
10714		break;
10715	}
10716	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10717		struct scsi_get_lba_status *cdb;
10718
10719		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10720		*lba = scsi_8btou64(cdb->addr);
10721		*len = UINT32_MAX;
10722		break;
10723	}
10724	default:
10725		return (1);
10726		break; /* NOTREACHED */
10727	}
10728
10729	return (0);
10730}
10731
10732static ctl_action
10733ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10734    bool seq)
10735{
10736	uint64_t endlba1, endlba2;
10737
10738	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10739	endlba2 = lba2 + len2 - 1;
10740
10741	if ((endlba1 < lba2) || (endlba2 < lba1))
10742		return (CTL_ACTION_PASS);
10743	else
10744		return (CTL_ACTION_BLOCK);
10745}
10746
10747static int
10748ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10749{
10750	struct ctl_ptr_len_flags *ptrlen;
10751	struct scsi_unmap_desc *buf, *end, *range;
10752	uint64_t lba;
10753	uint32_t len;
10754
10755	/* If not UNMAP -- go other way. */
10756	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10757	    io->scsiio.cdb[0] != UNMAP)
10758		return (CTL_ACTION_ERROR);
10759
10760	/* If UNMAP without data -- block and wait for data. */
10761	ptrlen = (struct ctl_ptr_len_flags *)
10762	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10763	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10764	    ptrlen->ptr == NULL)
10765		return (CTL_ACTION_BLOCK);
10766
10767	/* UNMAP with data -- check for collision. */
10768	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10769	end = buf + ptrlen->len / sizeof(*buf);
10770	for (range = buf; range < end; range++) {
10771		lba = scsi_8btou64(range->lba);
10772		len = scsi_4btoul(range->length);
10773		if ((lba < lba2 + len2) && (lba + len > lba2))
10774			return (CTL_ACTION_BLOCK);
10775	}
10776	return (CTL_ACTION_PASS);
10777}
10778
10779static ctl_action
10780ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10781{
10782	uint64_t lba1, lba2;
10783	uint64_t len1, len2;
10784	int retval;
10785
10786	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10787		return (CTL_ACTION_ERROR);
10788
10789	retval = ctl_extent_check_unmap(io1, lba2, len2);
10790	if (retval != CTL_ACTION_ERROR)
10791		return (retval);
10792
10793	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10794		return (CTL_ACTION_ERROR);
10795
10796	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10797		seq = FALSE;
10798	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10799}
10800
10801static ctl_action
10802ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10803{
10804	uint64_t lba1, lba2;
10805	uint64_t len1, len2;
10806
10807	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10808		return (CTL_ACTION_PASS);
10809	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10810		return (CTL_ACTION_ERROR);
10811	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10812		return (CTL_ACTION_ERROR);
10813
10814	if (lba1 + len1 == lba2)
10815		return (CTL_ACTION_BLOCK);
10816	return (CTL_ACTION_PASS);
10817}
10818
10819static ctl_action
10820ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10821    union ctl_io *ooa_io)
10822{
10823	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10824	ctl_serialize_action *serialize_row;
10825
10826	/*
10827	 * The initiator attempted multiple untagged commands at the same
10828	 * time.  Can't do that.
10829	 */
10830	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10831	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10832	 && ((pending_io->io_hdr.nexus.targ_port ==
10833	      ooa_io->io_hdr.nexus.targ_port)
10834	  && (pending_io->io_hdr.nexus.initid ==
10835	      ooa_io->io_hdr.nexus.initid))
10836	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10837	      CTL_FLAG_STATUS_SENT)) == 0))
10838		return (CTL_ACTION_OVERLAP);
10839
10840	/*
10841	 * The initiator attempted to send multiple tagged commands with
10842	 * the same ID.  (It's fine if different initiators have the same
10843	 * tag ID.)
10844	 *
10845	 * Even if all of those conditions are true, we don't kill the I/O
10846	 * if the command ahead of us has been aborted.  We won't end up
10847	 * sending it to the FETD, and it's perfectly legal to resend a
10848	 * command with the same tag number as long as the previous
10849	 * instance of this tag number has been aborted somehow.
10850	 */
10851	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10852	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10853	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10854	 && ((pending_io->io_hdr.nexus.targ_port ==
10855	      ooa_io->io_hdr.nexus.targ_port)
10856	  && (pending_io->io_hdr.nexus.initid ==
10857	      ooa_io->io_hdr.nexus.initid))
10858	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10859	      CTL_FLAG_STATUS_SENT)) == 0))
10860		return (CTL_ACTION_OVERLAP_TAG);
10861
10862	/*
10863	 * If we get a head of queue tag, SAM-3 says that we should
10864	 * immediately execute it.
10865	 *
10866	 * What happens if this command would normally block for some other
10867	 * reason?  e.g. a request sense with a head of queue tag
10868	 * immediately after a write.  Normally that would block, but this
10869	 * will result in its getting executed immediately...
10870	 *
10871	 * We currently return "pass" instead of "skip", so we'll end up
10872	 * going through the rest of the queue to check for overlapped tags.
10873	 *
10874	 * XXX KDM check for other types of blockage first??
10875	 */
10876	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10877		return (CTL_ACTION_PASS);
10878
10879	/*
10880	 * Ordered tags have to block until all items ahead of them
10881	 * have completed.  If we get called with an ordered tag, we always
10882	 * block, if something else is ahead of us in the queue.
10883	 */
10884	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10885		return (CTL_ACTION_BLOCK);
10886
10887	/*
10888	 * Simple tags get blocked until all head of queue and ordered tags
10889	 * ahead of them have completed.  I'm lumping untagged commands in
10890	 * with simple tags here.  XXX KDM is that the right thing to do?
10891	 */
10892	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10893	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10894	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10895	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10896		return (CTL_ACTION_BLOCK);
10897
10898	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10899	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10900
10901	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10902
10903	switch (serialize_row[pending_entry->seridx]) {
10904	case CTL_SER_BLOCK:
10905		return (CTL_ACTION_BLOCK);
10906	case CTL_SER_EXTENT:
10907		return (ctl_extent_check(ooa_io, pending_io,
10908		    (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10909	case CTL_SER_EXTENTOPT:
10910		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10911		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10912			return (ctl_extent_check(ooa_io, pending_io,
10913			    (lun->be_lun &&
10914			     lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10915		return (CTL_ACTION_PASS);
10916	case CTL_SER_EXTENTSEQ:
10917		if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
10918			return (ctl_extent_check_seq(ooa_io, pending_io));
10919		return (CTL_ACTION_PASS);
10920	case CTL_SER_PASS:
10921		return (CTL_ACTION_PASS);
10922	case CTL_SER_BLOCKOPT:
10923		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10924		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10925			return (CTL_ACTION_BLOCK);
10926		return (CTL_ACTION_PASS);
10927	case CTL_SER_SKIP:
10928		return (CTL_ACTION_SKIP);
10929	default:
10930		panic("invalid serialization value %d",
10931		      serialize_row[pending_entry->seridx]);
10932	}
10933
10934	return (CTL_ACTION_ERROR);
10935}
10936
10937/*
10938 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10939 * Assumptions:
10940 * - pending_io is generally either incoming, or on the blocked queue
10941 * - starting I/O is the I/O we want to start the check with.
10942 */
10943static ctl_action
10944ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10945	      union ctl_io *starting_io)
10946{
10947	union ctl_io *ooa_io;
10948	ctl_action action;
10949
10950	mtx_assert(&lun->lun_lock, MA_OWNED);
10951
10952	/*
10953	 * Run back along the OOA queue, starting with the current
10954	 * blocked I/O and going through every I/O before it on the
10955	 * queue.  If starting_io is NULL, we'll just end up returning
10956	 * CTL_ACTION_PASS.
10957	 */
10958	for (ooa_io = starting_io; ooa_io != NULL;
10959	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10960	     ooa_links)){
10961
10962		/*
10963		 * This routine just checks to see whether
10964		 * cur_blocked is blocked by ooa_io, which is ahead
10965		 * of it in the queue.  It doesn't queue/dequeue
10966		 * cur_blocked.
10967		 */
10968		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10969		switch (action) {
10970		case CTL_ACTION_BLOCK:
10971		case CTL_ACTION_OVERLAP:
10972		case CTL_ACTION_OVERLAP_TAG:
10973		case CTL_ACTION_SKIP:
10974		case CTL_ACTION_ERROR:
10975			return (action);
10976			break; /* NOTREACHED */
10977		case CTL_ACTION_PASS:
10978			break;
10979		default:
10980			panic("invalid action %d", action);
10981			break;  /* NOTREACHED */
10982		}
10983	}
10984
10985	return (CTL_ACTION_PASS);
10986}
10987
10988/*
10989 * Assumptions:
10990 * - An I/O has just completed, and has been removed from the per-LUN OOA
10991 *   queue, so some items on the blocked queue may now be unblocked.
10992 */
10993static int
10994ctl_check_blocked(struct ctl_lun *lun)
10995{
10996	struct ctl_softc *softc = lun->ctl_softc;
10997	union ctl_io *cur_blocked, *next_blocked;
10998
10999	mtx_assert(&lun->lun_lock, MA_OWNED);
11000
11001	/*
11002	 * Run forward from the head of the blocked queue, checking each
11003	 * entry against the I/Os prior to it on the OOA queue to see if
11004	 * there is still any blockage.
11005	 *
11006	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11007	 * with our removing a variable on it while it is traversing the
11008	 * list.
11009	 */
11010	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11011	     cur_blocked != NULL; cur_blocked = next_blocked) {
11012		union ctl_io *prev_ooa;
11013		ctl_action action;
11014
11015		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11016							  blocked_links);
11017
11018		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11019						      ctl_ooaq, ooa_links);
11020
11021		/*
11022		 * If cur_blocked happens to be the first item in the OOA
11023		 * queue now, prev_ooa will be NULL, and the action
11024		 * returned will just be CTL_ACTION_PASS.
11025		 */
11026		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11027
11028		switch (action) {
11029		case CTL_ACTION_BLOCK:
11030			/* Nothing to do here, still blocked */
11031			break;
11032		case CTL_ACTION_OVERLAP:
11033		case CTL_ACTION_OVERLAP_TAG:
11034			/*
11035			 * This shouldn't happen!  In theory we've already
11036			 * checked this command for overlap...
11037			 */
11038			break;
11039		case CTL_ACTION_PASS:
11040		case CTL_ACTION_SKIP: {
11041			const struct ctl_cmd_entry *entry;
11042
11043			/*
11044			 * The skip case shouldn't happen, this transaction
11045			 * should have never made it onto the blocked queue.
11046			 */
11047			/*
11048			 * This I/O is no longer blocked, we can remove it
11049			 * from the blocked queue.  Since this is a TAILQ
11050			 * (doubly linked list), we can do O(1) removals
11051			 * from any place on the list.
11052			 */
11053			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11054				     blocked_links);
11055			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11056
11057			if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11058			    (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11059				/*
11060				 * Need to send IO back to original side to
11061				 * run
11062				 */
11063				union ctl_ha_msg msg_info;
11064
11065				cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11066				msg_info.hdr.original_sc =
11067					cur_blocked->io_hdr.original_sc;
11068				msg_info.hdr.serializing_sc = cur_blocked;
11069				msg_info.hdr.msg_type = CTL_MSG_R2R;
11070				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11071				    sizeof(msg_info.hdr), M_NOWAIT);
11072				break;
11073			}
11074			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11075
11076			/*
11077			 * Check this I/O for LUN state changes that may
11078			 * have happened while this command was blocked.
11079			 * The LUN state may have been changed by a command
11080			 * ahead of us in the queue, so we need to re-check
11081			 * for any states that can be caused by SCSI
11082			 * commands.
11083			 */
11084			if (ctl_scsiio_lun_check(lun, entry,
11085						 &cur_blocked->scsiio) == 0) {
11086				cur_blocked->io_hdr.flags |=
11087				                      CTL_FLAG_IS_WAS_ON_RTR;
11088				ctl_enqueue_rtr(cur_blocked);
11089			} else
11090				ctl_done(cur_blocked);
11091			break;
11092		}
11093		default:
11094			/*
11095			 * This probably shouldn't happen -- we shouldn't
11096			 * get CTL_ACTION_ERROR, or anything else.
11097			 */
11098			break;
11099		}
11100	}
11101
11102	return (CTL_RETVAL_COMPLETE);
11103}
11104
11105/*
11106 * This routine (with one exception) checks LUN flags that can be set by
11107 * commands ahead of us in the OOA queue.  These flags have to be checked
11108 * when a command initially comes in, and when we pull a command off the
11109 * blocked queue and are preparing to execute it.  The reason we have to
11110 * check these flags for commands on the blocked queue is that the LUN
11111 * state may have been changed by a command ahead of us while we're on the
11112 * blocked queue.
11113 *
11114 * Ordering is somewhat important with these checks, so please pay
11115 * careful attention to the placement of any new checks.
11116 */
11117static int
11118ctl_scsiio_lun_check(struct ctl_lun *lun,
11119    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11120{
11121	struct ctl_softc *softc = lun->ctl_softc;
11122	int retval;
11123	uint32_t residx;
11124
11125	retval = 0;
11126
11127	mtx_assert(&lun->lun_lock, MA_OWNED);
11128
11129	/*
11130	 * If this shelf is a secondary shelf controller, we may have to
11131	 * reject some commands disallowed by HA mode and link state.
11132	 */
11133	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11134		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11135		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11136			ctl_set_lun_unavail(ctsio);
11137			retval = 1;
11138			goto bailout;
11139		}
11140		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11141		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11142			ctl_set_lun_transit(ctsio);
11143			retval = 1;
11144			goto bailout;
11145		}
11146		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11147		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11148			ctl_set_lun_standby(ctsio);
11149			retval = 1;
11150			goto bailout;
11151		}
11152
11153		/* The rest of checks are only done on executing side */
11154		if (softc->ha_mode == CTL_HA_MODE_XFER)
11155			goto bailout;
11156	}
11157
11158	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11159		if (lun->be_lun &&
11160		    lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11161			ctl_set_hw_write_protected(ctsio);
11162			retval = 1;
11163			goto bailout;
11164		}
11165		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11166		    .eca_and_aen & SCP_SWP) != 0) {
11167			ctl_set_sense(ctsio, /*current_error*/ 1,
11168			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11169			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11170			retval = 1;
11171			goto bailout;
11172		}
11173	}
11174
11175	/*
11176	 * Check for a reservation conflict.  If this command isn't allowed
11177	 * even on reserved LUNs, and if this initiator isn't the one who
11178	 * reserved us, reject the command with a reservation conflict.
11179	 */
11180	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11181	if ((lun->flags & CTL_LUN_RESERVED)
11182	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11183		if (lun->res_idx != residx) {
11184			ctl_set_reservation_conflict(ctsio);
11185			retval = 1;
11186			goto bailout;
11187		}
11188	}
11189
11190	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11191	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11192		/* No reservation or command is allowed. */;
11193	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11194	    (lun->res_type == SPR_TYPE_WR_EX ||
11195	     lun->res_type == SPR_TYPE_WR_EX_RO ||
11196	     lun->res_type == SPR_TYPE_WR_EX_AR)) {
11197		/* The command is allowed for Write Exclusive resv. */;
11198	} else {
11199		/*
11200		 * if we aren't registered or it's a res holder type
11201		 * reservation and this isn't the res holder then set a
11202		 * conflict.
11203		 */
11204		if (ctl_get_prkey(lun, residx) == 0
11205		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11206			ctl_set_reservation_conflict(ctsio);
11207			retval = 1;
11208			goto bailout;
11209		}
11210	}
11211
11212	if ((lun->flags & CTL_LUN_OFFLINE)
11213	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0)) {
11214		ctl_set_lun_not_ready(ctsio);
11215		retval = 1;
11216		goto bailout;
11217	}
11218
11219	if ((lun->flags & CTL_LUN_STOPPED)
11220	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11221		/* "Logical unit not ready, initializing cmd. required" */
11222		ctl_set_lun_stopped(ctsio);
11223		retval = 1;
11224		goto bailout;
11225	}
11226
11227	if ((lun->flags & CTL_LUN_INOPERABLE)
11228	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11229		/* "Medium format corrupted" */
11230		ctl_set_medium_format_corrupted(ctsio);
11231		retval = 1;
11232		goto bailout;
11233	}
11234
11235bailout:
11236	return (retval);
11237}
11238
11239static void
11240ctl_failover_io(union ctl_io *io, int have_lock)
11241{
11242	ctl_set_busy(&io->scsiio);
11243	ctl_done(io);
11244}
11245
11246static void
11247ctl_failover_lun(struct ctl_lun *lun)
11248{
11249	struct ctl_softc *softc = lun->ctl_softc;
11250	struct ctl_io_hdr *io, *next_io;
11251
11252	CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", lun->lun));
11253	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11254		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11255			/* We are master */
11256			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11257				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11258					io->flags |= CTL_FLAG_ABORT;
11259					io->flags |= CTL_FLAG_FAILOVER;
11260				} else { /* This can be only due to DATAMOVE */
11261					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11262					io->flags &= ~CTL_FLAG_DMA_INPROG;
11263					io->flags |= CTL_FLAG_IO_ACTIVE;
11264					io->port_status = 31340;
11265					ctl_enqueue_isc((union ctl_io *)io);
11266				}
11267			}
11268			/* We are slave */
11269			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11270				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11271				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11272					io->flags |= CTL_FLAG_FAILOVER;
11273				} else {
11274					ctl_set_busy(&((union ctl_io *)io)->
11275					    scsiio);
11276					ctl_done((union ctl_io *)io);
11277				}
11278			}
11279		}
11280	} else { /* SERIALIZE modes */
11281		TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11282		    next_io) {
11283			/* We are master */
11284			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11285				TAILQ_REMOVE(&lun->blocked_queue, io,
11286				    blocked_links);
11287				io->flags &= ~CTL_FLAG_BLOCKED;
11288				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11289				ctl_free_io((union ctl_io *)io);
11290			}
11291		}
11292		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11293			/* We are master */
11294			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11295				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11296				ctl_free_io((union ctl_io *)io);
11297			}
11298			/* We are slave */
11299			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11300				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11301				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11302					ctl_set_busy(&((union ctl_io *)io)->
11303					    scsiio);
11304					ctl_done((union ctl_io *)io);
11305				}
11306			}
11307		}
11308		ctl_check_blocked(lun);
11309	}
11310}
11311
11312static int
11313ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11314{
11315	struct ctl_lun *lun;
11316	const struct ctl_cmd_entry *entry;
11317	uint32_t initidx, targ_lun;
11318	int retval;
11319
11320	retval = 0;
11321
11322	lun = NULL;
11323
11324	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11325	if ((targ_lun < CTL_MAX_LUNS)
11326	 && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11327		/*
11328		 * If the LUN is invalid, pretend that it doesn't exist.
11329		 * It will go away as soon as all pending I/O has been
11330		 * completed.
11331		 */
11332		mtx_lock(&lun->lun_lock);
11333		if (lun->flags & CTL_LUN_DISABLED) {
11334			mtx_unlock(&lun->lun_lock);
11335			lun = NULL;
11336			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11337			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11338		} else {
11339			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11340			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11341				lun->be_lun;
11342
11343			/*
11344			 * Every I/O goes into the OOA queue for a
11345			 * particular LUN, and stays there until completion.
11346			 */
11347#ifdef CTL_TIME_IO
11348			if (TAILQ_EMPTY(&lun->ooa_queue)) {
11349				lun->idle_time += getsbinuptime() -
11350				    lun->last_busy;
11351			}
11352#endif
11353			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11354			    ooa_links);
11355		}
11356	} else {
11357		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11358		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11359	}
11360
11361	/* Get command entry and return error if it is unsuppotyed. */
11362	entry = ctl_validate_command(ctsio);
11363	if (entry == NULL) {
11364		if (lun)
11365			mtx_unlock(&lun->lun_lock);
11366		return (retval);
11367	}
11368
11369	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11370	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11371
11372	/*
11373	 * Check to see whether we can send this command to LUNs that don't
11374	 * exist.  This should pretty much only be the case for inquiry
11375	 * and request sense.  Further checks, below, really require having
11376	 * a LUN, so we can't really check the command anymore.  Just put
11377	 * it on the rtr queue.
11378	 */
11379	if (lun == NULL) {
11380		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11381			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11382			ctl_enqueue_rtr((union ctl_io *)ctsio);
11383			return (retval);
11384		}
11385
11386		ctl_set_unsupported_lun(ctsio);
11387		ctl_done((union ctl_io *)ctsio);
11388		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11389		return (retval);
11390	} else {
11391		/*
11392		 * Make sure we support this particular command on this LUN.
11393		 * e.g., we don't support writes to the control LUN.
11394		 */
11395		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11396			mtx_unlock(&lun->lun_lock);
11397			ctl_set_invalid_opcode(ctsio);
11398			ctl_done((union ctl_io *)ctsio);
11399			return (retval);
11400		}
11401	}
11402
11403	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11404
11405#ifdef CTL_WITH_CA
11406	/*
11407	 * If we've got a request sense, it'll clear the contingent
11408	 * allegiance condition.  Otherwise, if we have a CA condition for
11409	 * this initiator, clear it, because it sent down a command other
11410	 * than request sense.
11411	 */
11412	if ((ctsio->cdb[0] != REQUEST_SENSE)
11413	 && (ctl_is_set(lun->have_ca, initidx)))
11414		ctl_clear_mask(lun->have_ca, initidx);
11415#endif
11416
11417	/*
11418	 * If the command has this flag set, it handles its own unit
11419	 * attention reporting, we shouldn't do anything.  Otherwise we
11420	 * check for any pending unit attentions, and send them back to the
11421	 * initiator.  We only do this when a command initially comes in,
11422	 * not when we pull it off the blocked queue.
11423	 *
11424	 * According to SAM-3, section 5.3.2, the order that things get
11425	 * presented back to the host is basically unit attentions caused
11426	 * by some sort of reset event, busy status, reservation conflicts
11427	 * or task set full, and finally any other status.
11428	 *
11429	 * One issue here is that some of the unit attentions we report
11430	 * don't fall into the "reset" category (e.g. "reported luns data
11431	 * has changed").  So reporting it here, before the reservation
11432	 * check, may be technically wrong.  I guess the only thing to do
11433	 * would be to check for and report the reset events here, and then
11434	 * check for the other unit attention types after we check for a
11435	 * reservation conflict.
11436	 *
11437	 * XXX KDM need to fix this
11438	 */
11439	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11440		ctl_ua_type ua_type;
11441
11442		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11443		    SSD_TYPE_NONE);
11444		if (ua_type != CTL_UA_NONE) {
11445			mtx_unlock(&lun->lun_lock);
11446			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11447			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11448			ctsio->sense_len = SSD_FULL_SIZE;
11449			ctl_done((union ctl_io *)ctsio);
11450			return (retval);
11451		}
11452	}
11453
11454
11455	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11456		mtx_unlock(&lun->lun_lock);
11457		ctl_done((union ctl_io *)ctsio);
11458		return (retval);
11459	}
11460
11461	/*
11462	 * XXX CHD this is where we want to send IO to other side if
11463	 * this LUN is secondary on this SC. We will need to make a copy
11464	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11465	 * the copy we send as FROM_OTHER.
11466	 * We also need to stuff the address of the original IO so we can
11467	 * find it easily. Something similar will need be done on the other
11468	 * side so when we are done we can find the copy.
11469	 */
11470	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11471	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11472	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11473		union ctl_ha_msg msg_info;
11474		int isc_retval;
11475
11476		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11477		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11478		mtx_unlock(&lun->lun_lock);
11479
11480		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11481		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11482		msg_info.hdr.serializing_sc = NULL;
11483		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11484		msg_info.scsi.tag_num = ctsio->tag_num;
11485		msg_info.scsi.tag_type = ctsio->tag_type;
11486		msg_info.scsi.cdb_len = ctsio->cdb_len;
11487		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11488
11489		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11490		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11491		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11492			ctl_set_busy(ctsio);
11493			ctl_done((union ctl_io *)ctsio);
11494			return (retval);
11495		}
11496		return (retval);
11497	}
11498
11499	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11500			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11501			      ctl_ooaq, ooa_links))) {
11502	case CTL_ACTION_BLOCK:
11503		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11504		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11505				  blocked_links);
11506		mtx_unlock(&lun->lun_lock);
11507		return (retval);
11508	case CTL_ACTION_PASS:
11509	case CTL_ACTION_SKIP:
11510		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11511		mtx_unlock(&lun->lun_lock);
11512		ctl_enqueue_rtr((union ctl_io *)ctsio);
11513		break;
11514	case CTL_ACTION_OVERLAP:
11515		mtx_unlock(&lun->lun_lock);
11516		ctl_set_overlapped_cmd(ctsio);
11517		ctl_done((union ctl_io *)ctsio);
11518		break;
11519	case CTL_ACTION_OVERLAP_TAG:
11520		mtx_unlock(&lun->lun_lock);
11521		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11522		ctl_done((union ctl_io *)ctsio);
11523		break;
11524	case CTL_ACTION_ERROR:
11525	default:
11526		mtx_unlock(&lun->lun_lock);
11527		ctl_set_internal_failure(ctsio,
11528					 /*sks_valid*/ 0,
11529					 /*retry_count*/ 0);
11530		ctl_done((union ctl_io *)ctsio);
11531		break;
11532	}
11533	return (retval);
11534}
11535
11536const struct ctl_cmd_entry *
11537ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11538{
11539	const struct ctl_cmd_entry *entry;
11540	int service_action;
11541
11542	entry = &ctl_cmd_table[ctsio->cdb[0]];
11543	if (sa)
11544		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11545	if (entry->flags & CTL_CMD_FLAG_SA5) {
11546		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11547		entry = &((const struct ctl_cmd_entry *)
11548		    entry->execute)[service_action];
11549	}
11550	return (entry);
11551}
11552
11553const struct ctl_cmd_entry *
11554ctl_validate_command(struct ctl_scsiio *ctsio)
11555{
11556	const struct ctl_cmd_entry *entry;
11557	int i, sa;
11558	uint8_t diff;
11559
11560	entry = ctl_get_cmd_entry(ctsio, &sa);
11561	if (entry->execute == NULL) {
11562		if (sa)
11563			ctl_set_invalid_field(ctsio,
11564					      /*sks_valid*/ 1,
11565					      /*command*/ 1,
11566					      /*field*/ 1,
11567					      /*bit_valid*/ 1,
11568					      /*bit*/ 4);
11569		else
11570			ctl_set_invalid_opcode(ctsio);
11571		ctl_done((union ctl_io *)ctsio);
11572		return (NULL);
11573	}
11574	KASSERT(entry->length > 0,
11575	    ("Not defined length for command 0x%02x/0x%02x",
11576	     ctsio->cdb[0], ctsio->cdb[1]));
11577	for (i = 1; i < entry->length; i++) {
11578		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11579		if (diff == 0)
11580			continue;
11581		ctl_set_invalid_field(ctsio,
11582				      /*sks_valid*/ 1,
11583				      /*command*/ 1,
11584				      /*field*/ i,
11585				      /*bit_valid*/ 1,
11586				      /*bit*/ fls(diff) - 1);
11587		ctl_done((union ctl_io *)ctsio);
11588		return (NULL);
11589	}
11590	return (entry);
11591}
11592
11593static int
11594ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11595{
11596
11597	switch (lun_type) {
11598	case T_PROCESSOR:
11599		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11600			return (0);
11601		break;
11602	case T_DIRECT:
11603		if ((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0)
11604			return (0);
11605		break;
11606	default:
11607		return (0);
11608	}
11609	return (1);
11610}
11611
11612static int
11613ctl_scsiio(struct ctl_scsiio *ctsio)
11614{
11615	int retval;
11616	const struct ctl_cmd_entry *entry;
11617
11618	retval = CTL_RETVAL_COMPLETE;
11619
11620	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11621
11622	entry = ctl_get_cmd_entry(ctsio, NULL);
11623
11624	/*
11625	 * If this I/O has been aborted, just send it straight to
11626	 * ctl_done() without executing it.
11627	 */
11628	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11629		ctl_done((union ctl_io *)ctsio);
11630		goto bailout;
11631	}
11632
11633	/*
11634	 * All the checks should have been handled by ctl_scsiio_precheck().
11635	 * We should be clear now to just execute the I/O.
11636	 */
11637	retval = entry->execute(ctsio);
11638
11639bailout:
11640	return (retval);
11641}
11642
11643/*
11644 * Since we only implement one target right now, a bus reset simply resets
11645 * our single target.
11646 */
11647static int
11648ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11649{
11650	return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11651}
11652
11653static int
11654ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11655		 ctl_ua_type ua_type)
11656{
11657	struct ctl_port *port;
11658	struct ctl_lun *lun;
11659	int retval;
11660
11661	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11662		union ctl_ha_msg msg_info;
11663
11664		msg_info.hdr.nexus = io->io_hdr.nexus;
11665		if (ua_type==CTL_UA_TARG_RESET)
11666			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11667		else
11668			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11669		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11670		msg_info.hdr.original_sc = NULL;
11671		msg_info.hdr.serializing_sc = NULL;
11672		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11673		    sizeof(msg_info.task), M_WAITOK);
11674	}
11675	retval = 0;
11676
11677	mtx_lock(&softc->ctl_lock);
11678	port = softc->ctl_ports[io->io_hdr.nexus.targ_port];
11679	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11680		if (port != NULL &&
11681		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
11682			continue;
11683		retval += ctl_do_lun_reset(lun, io, ua_type);
11684	}
11685	mtx_unlock(&softc->ctl_lock);
11686	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11687	return (retval);
11688}
11689
11690/*
11691 * The LUN should always be set.  The I/O is optional, and is used to
11692 * distinguish between I/Os sent by this initiator, and by other
11693 * initiators.  We set unit attention for initiators other than this one.
11694 * SAM-3 is vague on this point.  It does say that a unit attention should
11695 * be established for other initiators when a LUN is reset (see section
11696 * 5.7.3), but it doesn't specifically say that the unit attention should
11697 * be established for this particular initiator when a LUN is reset.  Here
11698 * is the relevant text, from SAM-3 rev 8:
11699 *
11700 * 5.7.2 When a SCSI initiator port aborts its own tasks
11701 *
11702 * When a SCSI initiator port causes its own task(s) to be aborted, no
11703 * notification that the task(s) have been aborted shall be returned to
11704 * the SCSI initiator port other than the completion response for the
11705 * command or task management function action that caused the task(s) to
11706 * be aborted and notification(s) associated with related effects of the
11707 * action (e.g., a reset unit attention condition).
11708 *
11709 * XXX KDM for now, we're setting unit attention for all initiators.
11710 */
11711static int
11712ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11713{
11714	union ctl_io *xio;
11715#if 0
11716	uint32_t initidx;
11717#endif
11718#ifdef CTL_WITH_CA
11719	int i;
11720#endif
11721
11722	mtx_lock(&lun->lun_lock);
11723	/*
11724	 * Run through the OOA queue and abort each I/O.
11725	 */
11726	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11727	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11728		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11729	}
11730
11731	/*
11732	 * This version sets unit attention for every
11733	 */
11734#if 0
11735	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11736	ctl_est_ua_all(lun, initidx, ua_type);
11737#else
11738	ctl_est_ua_all(lun, -1, ua_type);
11739#endif
11740
11741	/*
11742	 * A reset (any kind, really) clears reservations established with
11743	 * RESERVE/RELEASE.  It does not clear reservations established
11744	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11745	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11746	 * reservations made with the RESERVE/RELEASE commands, because
11747	 * those commands are obsolete in SPC-3.
11748	 */
11749	lun->flags &= ~CTL_LUN_RESERVED;
11750
11751#ifdef CTL_WITH_CA
11752	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11753		ctl_clear_mask(lun->have_ca, i);
11754#endif
11755	mtx_unlock(&lun->lun_lock);
11756
11757	return (0);
11758}
11759
11760static int
11761ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
11762{
11763	struct ctl_lun *lun;
11764	uint32_t targ_lun;
11765	int retval;
11766
11767	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11768	mtx_lock(&softc->ctl_lock);
11769	if ((targ_lun >= CTL_MAX_LUNS) ||
11770	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11771		mtx_unlock(&softc->ctl_lock);
11772		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11773		return (1);
11774	}
11775	retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
11776	mtx_unlock(&softc->ctl_lock);
11777	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11778
11779	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11780		union ctl_ha_msg msg_info;
11781
11782		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11783		msg_info.hdr.nexus = io->io_hdr.nexus;
11784		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11785		msg_info.hdr.original_sc = NULL;
11786		msg_info.hdr.serializing_sc = NULL;
11787		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11788		    sizeof(msg_info.task), M_WAITOK);
11789	}
11790	return (retval);
11791}
11792
11793static void
11794ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11795    int other_sc)
11796{
11797	union ctl_io *xio;
11798
11799	mtx_assert(&lun->lun_lock, MA_OWNED);
11800
11801	/*
11802	 * Run through the OOA queue and attempt to find the given I/O.
11803	 * The target port, initiator ID, tag type and tag number have to
11804	 * match the values that we got from the initiator.  If we have an
11805	 * untagged command to abort, simply abort the first untagged command
11806	 * we come to.  We only allow one untagged command at a time of course.
11807	 */
11808	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11809	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11810
11811		if ((targ_port == UINT32_MAX ||
11812		     targ_port == xio->io_hdr.nexus.targ_port) &&
11813		    (init_id == UINT32_MAX ||
11814		     init_id == xio->io_hdr.nexus.initid)) {
11815			if (targ_port != xio->io_hdr.nexus.targ_port ||
11816			    init_id != xio->io_hdr.nexus.initid)
11817				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11818			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11819			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11820				union ctl_ha_msg msg_info;
11821
11822				msg_info.hdr.nexus = xio->io_hdr.nexus;
11823				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11824				msg_info.task.tag_num = xio->scsiio.tag_num;
11825				msg_info.task.tag_type = xio->scsiio.tag_type;
11826				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11827				msg_info.hdr.original_sc = NULL;
11828				msg_info.hdr.serializing_sc = NULL;
11829				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11830				    sizeof(msg_info.task), M_NOWAIT);
11831			}
11832		}
11833	}
11834}
11835
11836static int
11837ctl_abort_task_set(union ctl_io *io)
11838{
11839	struct ctl_softc *softc = control_softc;
11840	struct ctl_lun *lun;
11841	uint32_t targ_lun;
11842
11843	/*
11844	 * Look up the LUN.
11845	 */
11846	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11847	mtx_lock(&softc->ctl_lock);
11848	if ((targ_lun >= CTL_MAX_LUNS) ||
11849	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11850		mtx_unlock(&softc->ctl_lock);
11851		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11852		return (1);
11853	}
11854
11855	mtx_lock(&lun->lun_lock);
11856	mtx_unlock(&softc->ctl_lock);
11857	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11858		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11859		    io->io_hdr.nexus.initid,
11860		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11861	} else { /* CTL_TASK_CLEAR_TASK_SET */
11862		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11863		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11864	}
11865	mtx_unlock(&lun->lun_lock);
11866	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11867	return (0);
11868}
11869
11870static int
11871ctl_i_t_nexus_reset(union ctl_io *io)
11872{
11873	struct ctl_softc *softc = control_softc;
11874	struct ctl_lun *lun;
11875	uint32_t initidx;
11876
11877	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11878		union ctl_ha_msg msg_info;
11879
11880		msg_info.hdr.nexus = io->io_hdr.nexus;
11881		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
11882		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11883		msg_info.hdr.original_sc = NULL;
11884		msg_info.hdr.serializing_sc = NULL;
11885		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11886		    sizeof(msg_info.task), M_WAITOK);
11887	}
11888
11889	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11890	mtx_lock(&softc->ctl_lock);
11891	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11892		mtx_lock(&lun->lun_lock);
11893		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11894		    io->io_hdr.nexus.initid, 1);
11895#ifdef CTL_WITH_CA
11896		ctl_clear_mask(lun->have_ca, initidx);
11897#endif
11898		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
11899			lun->flags &= ~CTL_LUN_RESERVED;
11900		ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
11901		mtx_unlock(&lun->lun_lock);
11902	}
11903	mtx_unlock(&softc->ctl_lock);
11904	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11905	return (0);
11906}
11907
11908static int
11909ctl_abort_task(union ctl_io *io)
11910{
11911	union ctl_io *xio;
11912	struct ctl_lun *lun;
11913	struct ctl_softc *softc;
11914#if 0
11915	struct sbuf sb;
11916	char printbuf[128];
11917#endif
11918	int found;
11919	uint32_t targ_lun;
11920
11921	softc = control_softc;
11922	found = 0;
11923
11924	/*
11925	 * Look up the LUN.
11926	 */
11927	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11928	mtx_lock(&softc->ctl_lock);
11929	if ((targ_lun >= CTL_MAX_LUNS) ||
11930	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11931		mtx_unlock(&softc->ctl_lock);
11932		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11933		return (1);
11934	}
11935
11936#if 0
11937	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11938	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11939#endif
11940
11941	mtx_lock(&lun->lun_lock);
11942	mtx_unlock(&softc->ctl_lock);
11943	/*
11944	 * Run through the OOA queue and attempt to find the given I/O.
11945	 * The target port, initiator ID, tag type and tag number have to
11946	 * match the values that we got from the initiator.  If we have an
11947	 * untagged command to abort, simply abort the first untagged command
11948	 * we come to.  We only allow one untagged command at a time of course.
11949	 */
11950	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11951	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11952#if 0
11953		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
11954
11955		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
11956			    lun->lun, xio->scsiio.tag_num,
11957			    xio->scsiio.tag_type,
11958			    (xio->io_hdr.blocked_links.tqe_prev
11959			    == NULL) ? "" : " BLOCKED",
11960			    (xio->io_hdr.flags &
11961			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
11962			    (xio->io_hdr.flags &
11963			    CTL_FLAG_ABORT) ? " ABORT" : "",
11964			    (xio->io_hdr.flags &
11965			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
11966		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
11967		sbuf_finish(&sb);
11968		printf("%s\n", sbuf_data(&sb));
11969#endif
11970
11971		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
11972		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
11973		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
11974			continue;
11975
11976		/*
11977		 * If the abort says that the task is untagged, the
11978		 * task in the queue must be untagged.  Otherwise,
11979		 * we just check to see whether the tag numbers
11980		 * match.  This is because the QLogic firmware
11981		 * doesn't pass back the tag type in an abort
11982		 * request.
11983		 */
11984#if 0
11985		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
11986		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
11987		 || (xio->scsiio.tag_num == io->taskio.tag_num))
11988#endif
11989		/*
11990		 * XXX KDM we've got problems with FC, because it
11991		 * doesn't send down a tag type with aborts.  So we
11992		 * can only really go by the tag number...
11993		 * This may cause problems with parallel SCSI.
11994		 * Need to figure that out!!
11995		 */
11996		if (xio->scsiio.tag_num == io->taskio.tag_num) {
11997			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11998			found = 1;
11999			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12000			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12001				union ctl_ha_msg msg_info;
12002
12003				msg_info.hdr.nexus = io->io_hdr.nexus;
12004				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12005				msg_info.task.tag_num = io->taskio.tag_num;
12006				msg_info.task.tag_type = io->taskio.tag_type;
12007				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12008				msg_info.hdr.original_sc = NULL;
12009				msg_info.hdr.serializing_sc = NULL;
12010#if 0
12011				printf("Sent Abort to other side\n");
12012#endif
12013				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12014				    sizeof(msg_info.task), M_NOWAIT);
12015			}
12016#if 0
12017			printf("ctl_abort_task: found I/O to abort\n");
12018#endif
12019		}
12020	}
12021	mtx_unlock(&lun->lun_lock);
12022
12023	if (found == 0) {
12024		/*
12025		 * This isn't really an error.  It's entirely possible for
12026		 * the abort and command completion to cross on the wire.
12027		 * This is more of an informative/diagnostic error.
12028		 */
12029#if 0
12030		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12031		       "%u:%u:%u tag %d type %d\n",
12032		       io->io_hdr.nexus.initid,
12033		       io->io_hdr.nexus.targ_port,
12034		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12035		       io->taskio.tag_type);
12036#endif
12037	}
12038	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12039	return (0);
12040}
12041
12042static int
12043ctl_query_task(union ctl_io *io, int task_set)
12044{
12045	union ctl_io *xio;
12046	struct ctl_lun *lun;
12047	struct ctl_softc *softc;
12048	int found = 0;
12049	uint32_t targ_lun;
12050
12051	softc = control_softc;
12052	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12053	mtx_lock(&softc->ctl_lock);
12054	if ((targ_lun >= CTL_MAX_LUNS) ||
12055	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12056		mtx_unlock(&softc->ctl_lock);
12057		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12058		return (1);
12059	}
12060	mtx_lock(&lun->lun_lock);
12061	mtx_unlock(&softc->ctl_lock);
12062	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12063	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12064
12065		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12066		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12067		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12068			continue;
12069
12070		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12071			found = 1;
12072			break;
12073		}
12074	}
12075	mtx_unlock(&lun->lun_lock);
12076	if (found)
12077		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12078	else
12079		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12080	return (0);
12081}
12082
12083static int
12084ctl_query_async_event(union ctl_io *io)
12085{
12086	struct ctl_lun *lun;
12087	struct ctl_softc *softc;
12088	ctl_ua_type ua;
12089	uint32_t targ_lun, initidx;
12090
12091	softc = control_softc;
12092	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12093	mtx_lock(&softc->ctl_lock);
12094	if ((targ_lun >= CTL_MAX_LUNS) ||
12095	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12096		mtx_unlock(&softc->ctl_lock);
12097		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12098		return (1);
12099	}
12100	mtx_lock(&lun->lun_lock);
12101	mtx_unlock(&softc->ctl_lock);
12102	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12103	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12104	mtx_unlock(&lun->lun_lock);
12105	if (ua != CTL_UA_NONE)
12106		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12107	else
12108		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12109	return (0);
12110}
12111
12112static void
12113ctl_run_task(union ctl_io *io)
12114{
12115	struct ctl_softc *softc = control_softc;
12116	int retval = 1;
12117
12118	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12119	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12120	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12121	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12122	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12123	switch (io->taskio.task_action) {
12124	case CTL_TASK_ABORT_TASK:
12125		retval = ctl_abort_task(io);
12126		break;
12127	case CTL_TASK_ABORT_TASK_SET:
12128	case CTL_TASK_CLEAR_TASK_SET:
12129		retval = ctl_abort_task_set(io);
12130		break;
12131	case CTL_TASK_CLEAR_ACA:
12132		break;
12133	case CTL_TASK_I_T_NEXUS_RESET:
12134		retval = ctl_i_t_nexus_reset(io);
12135		break;
12136	case CTL_TASK_LUN_RESET:
12137		retval = ctl_lun_reset(softc, io);
12138		break;
12139	case CTL_TASK_TARGET_RESET:
12140		retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12141		break;
12142	case CTL_TASK_BUS_RESET:
12143		retval = ctl_bus_reset(softc, io);
12144		break;
12145	case CTL_TASK_PORT_LOGIN:
12146		break;
12147	case CTL_TASK_PORT_LOGOUT:
12148		break;
12149	case CTL_TASK_QUERY_TASK:
12150		retval = ctl_query_task(io, 0);
12151		break;
12152	case CTL_TASK_QUERY_TASK_SET:
12153		retval = ctl_query_task(io, 1);
12154		break;
12155	case CTL_TASK_QUERY_ASYNC_EVENT:
12156		retval = ctl_query_async_event(io);
12157		break;
12158	default:
12159		printf("%s: got unknown task management event %d\n",
12160		       __func__, io->taskio.task_action);
12161		break;
12162	}
12163	if (retval == 0)
12164		io->io_hdr.status = CTL_SUCCESS;
12165	else
12166		io->io_hdr.status = CTL_ERROR;
12167	ctl_done(io);
12168}
12169
12170/*
12171 * For HA operation.  Handle commands that come in from the other
12172 * controller.
12173 */
12174static void
12175ctl_handle_isc(union ctl_io *io)
12176{
12177	int free_io;
12178	struct ctl_lun *lun;
12179	struct ctl_softc *softc = control_softc;
12180	uint32_t targ_lun;
12181
12182	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12183	lun = softc->ctl_luns[targ_lun];
12184
12185	switch (io->io_hdr.msg_type) {
12186	case CTL_MSG_SERIALIZE:
12187		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12188		break;
12189	case CTL_MSG_R2R: {
12190		const struct ctl_cmd_entry *entry;
12191
12192		/*
12193		 * This is only used in SER_ONLY mode.
12194		 */
12195		free_io = 0;
12196		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12197		mtx_lock(&lun->lun_lock);
12198		if (ctl_scsiio_lun_check(lun,
12199		    entry, (struct ctl_scsiio *)io) != 0) {
12200			mtx_unlock(&lun->lun_lock);
12201			ctl_done(io);
12202			break;
12203		}
12204		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12205		mtx_unlock(&lun->lun_lock);
12206		ctl_enqueue_rtr(io);
12207		break;
12208	}
12209	case CTL_MSG_FINISH_IO:
12210		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12211			free_io = 0;
12212			ctl_done(io);
12213		} else {
12214			free_io = 1;
12215			mtx_lock(&lun->lun_lock);
12216			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12217				     ooa_links);
12218			ctl_check_blocked(lun);
12219			mtx_unlock(&lun->lun_lock);
12220		}
12221		break;
12222	case CTL_MSG_PERS_ACTION:
12223		ctl_hndl_per_res_out_on_other_sc(
12224			(union ctl_ha_msg *)&io->presio.pr_msg);
12225		free_io = 1;
12226		break;
12227	case CTL_MSG_BAD_JUJU:
12228		free_io = 0;
12229		ctl_done(io);
12230		break;
12231	case CTL_MSG_DATAMOVE:
12232		/* Only used in XFER mode */
12233		free_io = 0;
12234		ctl_datamove_remote(io);
12235		break;
12236	case CTL_MSG_DATAMOVE_DONE:
12237		/* Only used in XFER mode */
12238		free_io = 0;
12239		io->scsiio.be_move_done(io);
12240		break;
12241	case CTL_MSG_FAILOVER:
12242		mtx_lock(&lun->lun_lock);
12243		ctl_failover_lun(lun);
12244		mtx_unlock(&lun->lun_lock);
12245		free_io = 1;
12246		break;
12247	default:
12248		free_io = 1;
12249		printf("%s: Invalid message type %d\n",
12250		       __func__, io->io_hdr.msg_type);
12251		break;
12252	}
12253	if (free_io)
12254		ctl_free_io(io);
12255
12256}
12257
12258
12259/*
12260 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12261 * there is no match.
12262 */
12263static ctl_lun_error_pattern
12264ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12265{
12266	const struct ctl_cmd_entry *entry;
12267	ctl_lun_error_pattern filtered_pattern, pattern;
12268
12269	pattern = desc->error_pattern;
12270
12271	/*
12272	 * XXX KDM we need more data passed into this function to match a
12273	 * custom pattern, and we actually need to implement custom pattern
12274	 * matching.
12275	 */
12276	if (pattern & CTL_LUN_PAT_CMD)
12277		return (CTL_LUN_PAT_CMD);
12278
12279	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12280		return (CTL_LUN_PAT_ANY);
12281
12282	entry = ctl_get_cmd_entry(ctsio, NULL);
12283
12284	filtered_pattern = entry->pattern & pattern;
12285
12286	/*
12287	 * If the user requested specific flags in the pattern (e.g.
12288	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12289	 * flags.
12290	 *
12291	 * If the user did not specify any flags, it doesn't matter whether
12292	 * or not the command supports the flags.
12293	 */
12294	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12295	     (pattern & ~CTL_LUN_PAT_MASK))
12296		return (CTL_LUN_PAT_NONE);
12297
12298	/*
12299	 * If the user asked for a range check, see if the requested LBA
12300	 * range overlaps with this command's LBA range.
12301	 */
12302	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12303		uint64_t lba1;
12304		uint64_t len1;
12305		ctl_action action;
12306		int retval;
12307
12308		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12309		if (retval != 0)
12310			return (CTL_LUN_PAT_NONE);
12311
12312		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12313					      desc->lba_range.len, FALSE);
12314		/*
12315		 * A "pass" means that the LBA ranges don't overlap, so
12316		 * this doesn't match the user's range criteria.
12317		 */
12318		if (action == CTL_ACTION_PASS)
12319			return (CTL_LUN_PAT_NONE);
12320	}
12321
12322	return (filtered_pattern);
12323}
12324
12325static void
12326ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12327{
12328	struct ctl_error_desc *desc, *desc2;
12329
12330	mtx_assert(&lun->lun_lock, MA_OWNED);
12331
12332	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12333		ctl_lun_error_pattern pattern;
12334		/*
12335		 * Check to see whether this particular command matches
12336		 * the pattern in the descriptor.
12337		 */
12338		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12339		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12340			continue;
12341
12342		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12343		case CTL_LUN_INJ_ABORTED:
12344			ctl_set_aborted(&io->scsiio);
12345			break;
12346		case CTL_LUN_INJ_MEDIUM_ERR:
12347			ctl_set_medium_error(&io->scsiio,
12348			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12349			     CTL_FLAG_DATA_OUT);
12350			break;
12351		case CTL_LUN_INJ_UA:
12352			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12353			 * OCCURRED */
12354			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12355			break;
12356		case CTL_LUN_INJ_CUSTOM:
12357			/*
12358			 * We're assuming the user knows what he is doing.
12359			 * Just copy the sense information without doing
12360			 * checks.
12361			 */
12362			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12363			      MIN(sizeof(desc->custom_sense),
12364				  sizeof(io->scsiio.sense_data)));
12365			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12366			io->scsiio.sense_len = SSD_FULL_SIZE;
12367			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12368			break;
12369		case CTL_LUN_INJ_NONE:
12370		default:
12371			/*
12372			 * If this is an error injection type we don't know
12373			 * about, clear the continuous flag (if it is set)
12374			 * so it will get deleted below.
12375			 */
12376			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12377			break;
12378		}
12379		/*
12380		 * By default, each error injection action is a one-shot
12381		 */
12382		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12383			continue;
12384
12385		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12386
12387		free(desc, M_CTL);
12388	}
12389}
12390
12391#ifdef CTL_IO_DELAY
12392static void
12393ctl_datamove_timer_wakeup(void *arg)
12394{
12395	union ctl_io *io;
12396
12397	io = (union ctl_io *)arg;
12398
12399	ctl_datamove(io);
12400}
12401#endif /* CTL_IO_DELAY */
12402
12403void
12404ctl_datamove(union ctl_io *io)
12405{
12406	struct ctl_lun *lun;
12407	void (*fe_datamove)(union ctl_io *io);
12408
12409	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12410
12411	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12412
12413	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12414#ifdef CTL_TIME_IO
12415	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12416		char str[256];
12417		char path_str[64];
12418		struct sbuf sb;
12419
12420		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12421		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12422
12423		sbuf_cat(&sb, path_str);
12424		switch (io->io_hdr.io_type) {
12425		case CTL_IO_SCSI:
12426			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12427			sbuf_printf(&sb, "\n");
12428			sbuf_cat(&sb, path_str);
12429			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12430				    io->scsiio.tag_num, io->scsiio.tag_type);
12431			break;
12432		case CTL_IO_TASK:
12433			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12434				    "Tag Type: %d\n", io->taskio.task_action,
12435				    io->taskio.tag_num, io->taskio.tag_type);
12436			break;
12437		default:
12438			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12439			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12440			break;
12441		}
12442		sbuf_cat(&sb, path_str);
12443		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12444			    (intmax_t)time_uptime - io->io_hdr.start_time);
12445		sbuf_finish(&sb);
12446		printf("%s", sbuf_data(&sb));
12447	}
12448#endif /* CTL_TIME_IO */
12449
12450#ifdef CTL_IO_DELAY
12451	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12452		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12453	} else {
12454		if ((lun != NULL)
12455		 && (lun->delay_info.datamove_delay > 0)) {
12456
12457			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12458			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12459			callout_reset(&io->io_hdr.delay_callout,
12460				      lun->delay_info.datamove_delay * hz,
12461				      ctl_datamove_timer_wakeup, io);
12462			if (lun->delay_info.datamove_type ==
12463			    CTL_DELAY_TYPE_ONESHOT)
12464				lun->delay_info.datamove_delay = 0;
12465			return;
12466		}
12467	}
12468#endif
12469
12470	/*
12471	 * This command has been aborted.  Set the port status, so we fail
12472	 * the data move.
12473	 */
12474	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12475		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12476		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12477		       io->io_hdr.nexus.targ_port,
12478		       io->io_hdr.nexus.targ_lun);
12479		io->io_hdr.port_status = 31337;
12480		/*
12481		 * Note that the backend, in this case, will get the
12482		 * callback in its context.  In other cases it may get
12483		 * called in the frontend's interrupt thread context.
12484		 */
12485		io->scsiio.be_move_done(io);
12486		return;
12487	}
12488
12489	/* Don't confuse frontend with zero length data move. */
12490	if (io->scsiio.kern_data_len == 0) {
12491		io->scsiio.be_move_done(io);
12492		return;
12493	}
12494
12495	/*
12496	 * If we're in XFER mode and this I/O is from the other shelf
12497	 * controller, we need to send the DMA to the other side to
12498	 * actually transfer the data to/from the host.  In serialize only
12499	 * mode the transfer happens below CTL and ctl_datamove() is only
12500	 * called on the machine that originally received the I/O.
12501	 */
12502	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12503	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12504		union ctl_ha_msg msg;
12505		uint32_t sg_entries_sent;
12506		int do_sg_copy;
12507		int i;
12508
12509		memset(&msg, 0, sizeof(msg));
12510		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12511		msg.hdr.original_sc = io->io_hdr.original_sc;
12512		msg.hdr.serializing_sc = io;
12513		msg.hdr.nexus = io->io_hdr.nexus;
12514		msg.hdr.status = io->io_hdr.status;
12515		msg.dt.flags = io->io_hdr.flags;
12516		/*
12517		 * We convert everything into a S/G list here.  We can't
12518		 * pass by reference, only by value between controllers.
12519		 * So we can't pass a pointer to the S/G list, only as many
12520		 * S/G entries as we can fit in here.  If it's possible for
12521		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12522		 * then we need to break this up into multiple transfers.
12523		 */
12524		if (io->scsiio.kern_sg_entries == 0) {
12525			msg.dt.kern_sg_entries = 1;
12526#if 0
12527			/*
12528			 * Convert to a physical address if this is a
12529			 * virtual address.
12530			 */
12531			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12532				msg.dt.sg_list[0].addr =
12533					io->scsiio.kern_data_ptr;
12534			} else {
12535				/*
12536				 * XXX KDM use busdma here!
12537				 */
12538				msg.dt.sg_list[0].addr = (void *)
12539					vtophys(io->scsiio.kern_data_ptr);
12540			}
12541#else
12542			KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12543			    ("HA does not support BUS_ADDR"));
12544			msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
12545#endif
12546
12547			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12548			do_sg_copy = 0;
12549		} else {
12550			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12551			do_sg_copy = 1;
12552		}
12553
12554		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12555		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12556		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12557		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12558		msg.dt.sg_sequence = 0;
12559
12560		/*
12561		 * Loop until we've sent all of the S/G entries.  On the
12562		 * other end, we'll recompose these S/G entries into one
12563		 * contiguous list before passing it to the
12564		 */
12565		for (sg_entries_sent = 0; sg_entries_sent <
12566		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12567			msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list)/
12568				sizeof(msg.dt.sg_list[0])),
12569				msg.dt.kern_sg_entries - sg_entries_sent);
12570
12571			if (do_sg_copy != 0) {
12572				struct ctl_sg_entry *sgl;
12573				int j;
12574
12575				sgl = (struct ctl_sg_entry *)
12576					io->scsiio.kern_data_ptr;
12577				/*
12578				 * If this is in cached memory, flush the cache
12579				 * before we send the DMA request to the other
12580				 * controller.  We want to do this in either
12581				 * the * read or the write case.  The read
12582				 * case is straightforward.  In the write
12583				 * case, we want to make sure nothing is
12584				 * in the local cache that could overwrite
12585				 * the DMAed data.
12586				 */
12587
12588				for (i = sg_entries_sent, j = 0;
12589				     i < msg.dt.cur_sg_entries; i++, j++) {
12590#if 0
12591					if ((io->io_hdr.flags &
12592					     CTL_FLAG_BUS_ADDR) == 0) {
12593						/*
12594						 * XXX KDM use busdma.
12595						 */
12596						msg.dt.sg_list[j].addr =(void *)
12597						       vtophys(sgl[i].addr);
12598					} else {
12599						msg.dt.sg_list[j].addr =
12600							sgl[i].addr;
12601					}
12602#else
12603					KASSERT((io->io_hdr.flags &
12604					    CTL_FLAG_BUS_ADDR) == 0,
12605					    ("HA does not support BUS_ADDR"));
12606					msg.dt.sg_list[j].addr = sgl[i].addr;
12607#endif
12608					msg.dt.sg_list[j].len = sgl[i].len;
12609				}
12610			}
12611
12612			sg_entries_sent += msg.dt.cur_sg_entries;
12613			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12614				msg.dt.sg_last = 1;
12615			else
12616				msg.dt.sg_last = 0;
12617
12618			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12619			    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
12620			    sizeof(struct ctl_sg_entry)*msg.dt.cur_sg_entries,
12621			    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
12622				io->io_hdr.port_status = 31341;
12623				io->scsiio.be_move_done(io);
12624				return;
12625			}
12626
12627			msg.dt.sent_sg_entries = sg_entries_sent;
12628		}
12629
12630		/*
12631		 * Officially handover the request from us to peer.
12632		 * If failover has just happened, then we must return error.
12633		 * If failover happen just after, then it is not our problem.
12634		 */
12635		if (lun)
12636			mtx_lock(&lun->lun_lock);
12637		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12638			if (lun)
12639				mtx_unlock(&lun->lun_lock);
12640			io->io_hdr.port_status = 31342;
12641			io->scsiio.be_move_done(io);
12642			return;
12643		}
12644		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12645		io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
12646		if (lun)
12647			mtx_unlock(&lun->lun_lock);
12648	} else {
12649
12650		/*
12651		 * Lookup the fe_datamove() function for this particular
12652		 * front end.
12653		 */
12654		fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12655
12656		fe_datamove(io);
12657	}
12658}
12659
12660static void
12661ctl_send_datamove_done(union ctl_io *io, int have_lock)
12662{
12663	union ctl_ha_msg msg;
12664
12665	memset(&msg, 0, sizeof(msg));
12666
12667	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12668	msg.hdr.original_sc = io;
12669	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12670	msg.hdr.nexus = io->io_hdr.nexus;
12671	msg.hdr.status = io->io_hdr.status;
12672	msg.scsi.tag_num = io->scsiio.tag_num;
12673	msg.scsi.tag_type = io->scsiio.tag_type;
12674	msg.scsi.scsi_status = io->scsiio.scsi_status;
12675	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12676	       io->scsiio.sense_len);
12677	msg.scsi.sense_len = io->scsiio.sense_len;
12678	msg.scsi.sense_residual = io->scsiio.sense_residual;
12679	msg.scsi.fetd_status = io->io_hdr.port_status;
12680	msg.scsi.residual = io->scsiio.residual;
12681	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12682
12683	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12684		ctl_failover_io(io, /*have_lock*/ have_lock);
12685		return;
12686	}
12687
12688	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12689	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12690	    msg.scsi.sense_len, M_WAITOK);
12691}
12692
12693/*
12694 * The DMA to the remote side is done, now we need to tell the other side
12695 * we're done so it can continue with its data movement.
12696 */
12697static void
12698ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12699{
12700	union ctl_io *io;
12701	int i;
12702
12703	io = rq->context;
12704
12705	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12706		printf("%s: ISC DMA write failed with error %d", __func__,
12707		       rq->ret);
12708		ctl_set_internal_failure(&io->scsiio,
12709					 /*sks_valid*/ 1,
12710					 /*retry_count*/ rq->ret);
12711	}
12712
12713	ctl_dt_req_free(rq);
12714
12715	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12716		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12717	free(io->io_hdr.remote_sglist, M_CTL);
12718	io->io_hdr.remote_sglist = NULL;
12719	io->io_hdr.local_sglist = NULL;
12720
12721	/*
12722	 * The data is in local and remote memory, so now we need to send
12723	 * status (good or back) back to the other side.
12724	 */
12725	ctl_send_datamove_done(io, /*have_lock*/ 0);
12726}
12727
12728/*
12729 * We've moved the data from the host/controller into local memory.  Now we
12730 * need to push it over to the remote controller's memory.
12731 */
12732static int
12733ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12734{
12735	int retval;
12736
12737	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12738					  ctl_datamove_remote_write_cb);
12739	return (retval);
12740}
12741
12742static void
12743ctl_datamove_remote_write(union ctl_io *io)
12744{
12745	int retval;
12746	void (*fe_datamove)(union ctl_io *io);
12747
12748	/*
12749	 * - Get the data from the host/HBA into local memory.
12750	 * - DMA memory from the local controller to the remote controller.
12751	 * - Send status back to the remote controller.
12752	 */
12753
12754	retval = ctl_datamove_remote_sgl_setup(io);
12755	if (retval != 0)
12756		return;
12757
12758	/* Switch the pointer over so the FETD knows what to do */
12759	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12760
12761	/*
12762	 * Use a custom move done callback, since we need to send completion
12763	 * back to the other controller, not to the backend on this side.
12764	 */
12765	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12766
12767	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12768	fe_datamove(io);
12769}
12770
12771static int
12772ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12773{
12774#if 0
12775	char str[256];
12776	char path_str[64];
12777	struct sbuf sb;
12778#endif
12779	int i;
12780
12781	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12782		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12783	free(io->io_hdr.remote_sglist, M_CTL);
12784	io->io_hdr.remote_sglist = NULL;
12785	io->io_hdr.local_sglist = NULL;
12786
12787#if 0
12788	scsi_path_string(io, path_str, sizeof(path_str));
12789	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12790	sbuf_cat(&sb, path_str);
12791	scsi_command_string(&io->scsiio, NULL, &sb);
12792	sbuf_printf(&sb, "\n");
12793	sbuf_cat(&sb, path_str);
12794	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12795		    io->scsiio.tag_num, io->scsiio.tag_type);
12796	sbuf_cat(&sb, path_str);
12797	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12798		    io->io_hdr.flags, io->io_hdr.status);
12799	sbuf_finish(&sb);
12800	printk("%s", sbuf_data(&sb));
12801#endif
12802
12803
12804	/*
12805	 * The read is done, now we need to send status (good or bad) back
12806	 * to the other side.
12807	 */
12808	ctl_send_datamove_done(io, /*have_lock*/ 0);
12809
12810	return (0);
12811}
12812
12813static void
12814ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12815{
12816	union ctl_io *io;
12817	void (*fe_datamove)(union ctl_io *io);
12818
12819	io = rq->context;
12820
12821	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12822		printf("%s: ISC DMA read failed with error %d\n", __func__,
12823		       rq->ret);
12824		ctl_set_internal_failure(&io->scsiio,
12825					 /*sks_valid*/ 1,
12826					 /*retry_count*/ rq->ret);
12827	}
12828
12829	ctl_dt_req_free(rq);
12830
12831	/* Switch the pointer over so the FETD knows what to do */
12832	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12833
12834	/*
12835	 * Use a custom move done callback, since we need to send completion
12836	 * back to the other controller, not to the backend on this side.
12837	 */
12838	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12839
12840	/* XXX KDM add checks like the ones in ctl_datamove? */
12841
12842	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12843	fe_datamove(io);
12844}
12845
12846static int
12847ctl_datamove_remote_sgl_setup(union ctl_io *io)
12848{
12849	struct ctl_sg_entry *local_sglist;
12850	uint32_t len_to_go;
12851	int retval;
12852	int i;
12853
12854	retval = 0;
12855	local_sglist = io->io_hdr.local_sglist;
12856	len_to_go = io->scsiio.kern_data_len;
12857
12858	/*
12859	 * The difficult thing here is that the size of the various
12860	 * S/G segments may be different than the size from the
12861	 * remote controller.  That'll make it harder when DMAing
12862	 * the data back to the other side.
12863	 */
12864	for (i = 0; len_to_go > 0; i++) {
12865		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12866		local_sglist[i].addr =
12867		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12868
12869		len_to_go -= local_sglist[i].len;
12870	}
12871	/*
12872	 * Reset the number of S/G entries accordingly.  The original
12873	 * number of S/G entries is available in rem_sg_entries.
12874	 */
12875	io->scsiio.kern_sg_entries = i;
12876
12877#if 0
12878	printf("%s: kern_sg_entries = %d\n", __func__,
12879	       io->scsiio.kern_sg_entries);
12880	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12881		printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12882		       local_sglist[i].addr, local_sglist[i].len);
12883#endif
12884
12885	return (retval);
12886}
12887
12888static int
12889ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12890			 ctl_ha_dt_cb callback)
12891{
12892	struct ctl_ha_dt_req *rq;
12893	struct ctl_sg_entry *remote_sglist, *local_sglist;
12894	uint32_t local_used, remote_used, total_used;
12895	int i, j, isc_ret;
12896
12897	rq = ctl_dt_req_alloc();
12898
12899	/*
12900	 * If we failed to allocate the request, and if the DMA didn't fail
12901	 * anyway, set busy status.  This is just a resource allocation
12902	 * failure.
12903	 */
12904	if ((rq == NULL)
12905	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12906	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12907		ctl_set_busy(&io->scsiio);
12908
12909	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12910	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12911
12912		if (rq != NULL)
12913			ctl_dt_req_free(rq);
12914
12915		/*
12916		 * The data move failed.  We need to return status back
12917		 * to the other controller.  No point in trying to DMA
12918		 * data to the remote controller.
12919		 */
12920
12921		ctl_send_datamove_done(io, /*have_lock*/ 0);
12922
12923		return (1);
12924	}
12925
12926	local_sglist = io->io_hdr.local_sglist;
12927	remote_sglist = io->io_hdr.remote_sglist;
12928	local_used = 0;
12929	remote_used = 0;
12930	total_used = 0;
12931
12932	/*
12933	 * Pull/push the data over the wire from/to the other controller.
12934	 * This takes into account the possibility that the local and
12935	 * remote sglists may not be identical in terms of the size of
12936	 * the elements and the number of elements.
12937	 *
12938	 * One fundamental assumption here is that the length allocated for
12939	 * both the local and remote sglists is identical.  Otherwise, we've
12940	 * essentially got a coding error of some sort.
12941	 */
12942	isc_ret = CTL_HA_STATUS_SUCCESS;
12943	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12944		uint32_t cur_len;
12945		uint8_t *tmp_ptr;
12946
12947		rq->command = command;
12948		rq->context = io;
12949
12950		/*
12951		 * Both pointers should be aligned.  But it is possible
12952		 * that the allocation length is not.  They should both
12953		 * also have enough slack left over at the end, though,
12954		 * to round up to the next 8 byte boundary.
12955		 */
12956		cur_len = MIN(local_sglist[i].len - local_used,
12957			      remote_sglist[j].len - remote_used);
12958		rq->size = cur_len;
12959
12960		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12961		tmp_ptr += local_used;
12962
12963#if 0
12964		/* Use physical addresses when talking to ISC hardware */
12965		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12966			/* XXX KDM use busdma */
12967			rq->local = vtophys(tmp_ptr);
12968		} else
12969			rq->local = tmp_ptr;
12970#else
12971		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12972		    ("HA does not support BUS_ADDR"));
12973		rq->local = tmp_ptr;
12974#endif
12975
12976		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12977		tmp_ptr += remote_used;
12978		rq->remote = tmp_ptr;
12979
12980		rq->callback = NULL;
12981
12982		local_used += cur_len;
12983		if (local_used >= local_sglist[i].len) {
12984			i++;
12985			local_used = 0;
12986		}
12987
12988		remote_used += cur_len;
12989		if (remote_used >= remote_sglist[j].len) {
12990			j++;
12991			remote_used = 0;
12992		}
12993		total_used += cur_len;
12994
12995		if (total_used >= io->scsiio.kern_data_len)
12996			rq->callback = callback;
12997
12998#if 0
12999		printf("%s: %s: local %p remote %p size %d\n", __func__,
13000		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13001		       rq->local, rq->remote, rq->size);
13002#endif
13003
13004		isc_ret = ctl_dt_single(rq);
13005		if (isc_ret > CTL_HA_STATUS_SUCCESS)
13006			break;
13007	}
13008	if (isc_ret != CTL_HA_STATUS_WAIT) {
13009		rq->ret = isc_ret;
13010		callback(rq);
13011	}
13012
13013	return (0);
13014}
13015
13016static void
13017ctl_datamove_remote_read(union ctl_io *io)
13018{
13019	int retval;
13020	int i;
13021
13022	/*
13023	 * This will send an error to the other controller in the case of a
13024	 * failure.
13025	 */
13026	retval = ctl_datamove_remote_sgl_setup(io);
13027	if (retval != 0)
13028		return;
13029
13030	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13031					  ctl_datamove_remote_read_cb);
13032	if (retval != 0) {
13033		/*
13034		 * Make sure we free memory if there was an error..  The
13035		 * ctl_datamove_remote_xfer() function will send the
13036		 * datamove done message, or call the callback with an
13037		 * error if there is a problem.
13038		 */
13039		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13040			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13041		free(io->io_hdr.remote_sglist, M_CTL);
13042		io->io_hdr.remote_sglist = NULL;
13043		io->io_hdr.local_sglist = NULL;
13044	}
13045}
13046
13047/*
13048 * Process a datamove request from the other controller.  This is used for
13049 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13050 * first.  Once that is complete, the data gets DMAed into the remote
13051 * controller's memory.  For reads, we DMA from the remote controller's
13052 * memory into our memory first, and then move it out to the FETD.
13053 */
13054static void
13055ctl_datamove_remote(union ctl_io *io)
13056{
13057
13058	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
13059
13060	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13061		ctl_failover_io(io, /*have_lock*/ 0);
13062		return;
13063	}
13064
13065	/*
13066	 * Note that we look for an aborted I/O here, but don't do some of
13067	 * the other checks that ctl_datamove() normally does.
13068	 * We don't need to run the datamove delay code, since that should
13069	 * have been done if need be on the other controller.
13070	 */
13071	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13072		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
13073		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
13074		       io->io_hdr.nexus.targ_port,
13075		       io->io_hdr.nexus.targ_lun);
13076		io->io_hdr.port_status = 31338;
13077		ctl_send_datamove_done(io, /*have_lock*/ 0);
13078		return;
13079	}
13080
13081	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
13082		ctl_datamove_remote_write(io);
13083	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
13084		ctl_datamove_remote_read(io);
13085	else {
13086		io->io_hdr.port_status = 31339;
13087		ctl_send_datamove_done(io, /*have_lock*/ 0);
13088	}
13089}
13090
13091static int
13092ctl_process_done(union ctl_io *io)
13093{
13094	struct ctl_lun *lun;
13095	struct ctl_softc *softc = control_softc;
13096	void (*fe_done)(union ctl_io *io);
13097	union ctl_ha_msg msg;
13098	uint32_t targ_port = io->io_hdr.nexus.targ_port;
13099
13100	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13101
13102	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0)
13103		fe_done = softc->ctl_ports[targ_port]->fe_done;
13104	else
13105		fe_done = NULL;
13106
13107#ifdef CTL_TIME_IO
13108	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13109		char str[256];
13110		char path_str[64];
13111		struct sbuf sb;
13112
13113		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13114		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13115
13116		sbuf_cat(&sb, path_str);
13117		switch (io->io_hdr.io_type) {
13118		case CTL_IO_SCSI:
13119			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13120			sbuf_printf(&sb, "\n");
13121			sbuf_cat(&sb, path_str);
13122			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13123				    io->scsiio.tag_num, io->scsiio.tag_type);
13124			break;
13125		case CTL_IO_TASK:
13126			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13127				    "Tag Type: %d\n", io->taskio.task_action,
13128				    io->taskio.tag_num, io->taskio.tag_type);
13129			break;
13130		default:
13131			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13132			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13133			break;
13134		}
13135		sbuf_cat(&sb, path_str);
13136		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13137			    (intmax_t)time_uptime - io->io_hdr.start_time);
13138		sbuf_finish(&sb);
13139		printf("%s", sbuf_data(&sb));
13140	}
13141#endif /* CTL_TIME_IO */
13142
13143	switch (io->io_hdr.io_type) {
13144	case CTL_IO_SCSI:
13145		break;
13146	case CTL_IO_TASK:
13147		if (ctl_debug & CTL_DEBUG_INFO)
13148			ctl_io_error_print(io, NULL);
13149		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13150			ctl_free_io(io);
13151		else
13152			fe_done(io);
13153		return (CTL_RETVAL_COMPLETE);
13154	default:
13155		panic("ctl_process_done: invalid io type %d\n",
13156		      io->io_hdr.io_type);
13157		break; /* NOTREACHED */
13158	}
13159
13160	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13161	if (lun == NULL) {
13162		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13163				 io->io_hdr.nexus.targ_mapped_lun));
13164		goto bailout;
13165	}
13166
13167	mtx_lock(&lun->lun_lock);
13168
13169	/*
13170	 * Check to see if we have any errors to inject here.  We only
13171	 * inject errors for commands that don't already have errors set.
13172	 */
13173	if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
13174	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13175	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13176		ctl_inject_error(lun, io);
13177
13178	/*
13179	 * XXX KDM how do we treat commands that aren't completed
13180	 * successfully?
13181	 *
13182	 * XXX KDM should we also track I/O latency?
13183	 */
13184	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13185	    io->io_hdr.io_type == CTL_IO_SCSI) {
13186#ifdef CTL_TIME_IO
13187		struct bintime cur_bt;
13188#endif
13189		int type;
13190
13191		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13192		    CTL_FLAG_DATA_IN)
13193			type = CTL_STATS_READ;
13194		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13195		    CTL_FLAG_DATA_OUT)
13196			type = CTL_STATS_WRITE;
13197		else
13198			type = CTL_STATS_NO_IO;
13199
13200		lun->stats.ports[targ_port].bytes[type] +=
13201		    io->scsiio.kern_total_len;
13202		lun->stats.ports[targ_port].operations[type]++;
13203#ifdef CTL_TIME_IO
13204		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13205		   &io->io_hdr.dma_bt);
13206		lun->stats.ports[targ_port].num_dmas[type] +=
13207		    io->io_hdr.num_dmas;
13208		getbintime(&cur_bt);
13209		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13210		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13211#endif
13212	}
13213
13214	/*
13215	 * Remove this from the OOA queue.
13216	 */
13217	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13218#ifdef CTL_TIME_IO
13219	if (TAILQ_EMPTY(&lun->ooa_queue))
13220		lun->last_busy = getsbinuptime();
13221#endif
13222
13223	/*
13224	 * Run through the blocked queue on this LUN and see if anything
13225	 * has become unblocked, now that this transaction is done.
13226	 */
13227	ctl_check_blocked(lun);
13228
13229	/*
13230	 * If the LUN has been invalidated, free it if there is nothing
13231	 * left on its OOA queue.
13232	 */
13233	if ((lun->flags & CTL_LUN_INVALID)
13234	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13235		mtx_unlock(&lun->lun_lock);
13236		mtx_lock(&softc->ctl_lock);
13237		ctl_free_lun(lun);
13238		mtx_unlock(&softc->ctl_lock);
13239	} else
13240		mtx_unlock(&lun->lun_lock);
13241
13242bailout:
13243
13244	/*
13245	 * If this command has been aborted, make sure we set the status
13246	 * properly.  The FETD is responsible for freeing the I/O and doing
13247	 * whatever it needs to do to clean up its state.
13248	 */
13249	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13250		ctl_set_task_aborted(&io->scsiio);
13251
13252	/*
13253	 * If enabled, print command error status.
13254	 */
13255	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13256	    (ctl_debug & CTL_DEBUG_INFO) != 0)
13257		ctl_io_error_print(io, NULL);
13258
13259	/*
13260	 * Tell the FETD or the other shelf controller we're done with this
13261	 * command.  Note that only SCSI commands get to this point.  Task
13262	 * management commands are completed above.
13263	 */
13264	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13265	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13266		memset(&msg, 0, sizeof(msg));
13267		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13268		msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13269		msg.hdr.nexus = io->io_hdr.nexus;
13270		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13271		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13272		    M_WAITOK);
13273	}
13274	if ((softc->ha_mode == CTL_HA_MODE_XFER)
13275	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13276		memset(&msg, 0, sizeof(msg));
13277		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13278		msg.hdr.original_sc = io->io_hdr.original_sc;
13279		msg.hdr.nexus = io->io_hdr.nexus;
13280		msg.hdr.status = io->io_hdr.status;
13281		msg.scsi.scsi_status = io->scsiio.scsi_status;
13282		msg.scsi.tag_num = io->scsiio.tag_num;
13283		msg.scsi.tag_type = io->scsiio.tag_type;
13284		msg.scsi.sense_len = io->scsiio.sense_len;
13285		msg.scsi.sense_residual = io->scsiio.sense_residual;
13286		msg.scsi.residual = io->scsiio.residual;
13287		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13288		       io->scsiio.sense_len);
13289
13290		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13291		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
13292		    msg.scsi.sense_len, M_WAITOK);
13293		ctl_free_io(io);
13294	} else
13295		fe_done(io);
13296
13297	return (CTL_RETVAL_COMPLETE);
13298}
13299
13300#ifdef CTL_WITH_CA
13301/*
13302 * Front end should call this if it doesn't do autosense.  When the request
13303 * sense comes back in from the initiator, we'll dequeue this and send it.
13304 */
13305int
13306ctl_queue_sense(union ctl_io *io)
13307{
13308	struct ctl_lun *lun;
13309	struct ctl_port *port;
13310	struct ctl_softc *softc;
13311	uint32_t initidx, targ_lun;
13312
13313	softc = control_softc;
13314
13315	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13316
13317	/*
13318	 * LUN lookup will likely move to the ctl_work_thread() once we
13319	 * have our new queueing infrastructure (that doesn't put things on
13320	 * a per-LUN queue initially).  That is so that we can handle
13321	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13322	 * can't deal with that right now.
13323	 */
13324	mtx_lock(&softc->ctl_lock);
13325
13326	/*
13327	 * If we don't have a LUN for this, just toss the sense
13328	 * information.
13329	 */
13330	port = ctl_io_port(&ctsio->io_hdr);
13331	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13332	if ((targ_lun < CTL_MAX_LUNS)
13333	 && (softc->ctl_luns[targ_lun] != NULL))
13334		lun = softc->ctl_luns[targ_lun];
13335	else
13336		goto bailout;
13337
13338	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13339
13340	mtx_lock(&lun->lun_lock);
13341	/*
13342	 * Already have CA set for this LUN...toss the sense information.
13343	 */
13344	if (ctl_is_set(lun->have_ca, initidx)) {
13345		mtx_unlock(&lun->lun_lock);
13346		goto bailout;
13347	}
13348
13349	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13350	       MIN(sizeof(lun->pending_sense[initidx]),
13351	       sizeof(io->scsiio.sense_data)));
13352	ctl_set_mask(lun->have_ca, initidx);
13353	mtx_unlock(&lun->lun_lock);
13354
13355bailout:
13356	mtx_unlock(&softc->ctl_lock);
13357
13358	ctl_free_io(io);
13359
13360	return (CTL_RETVAL_COMPLETE);
13361}
13362#endif
13363
13364/*
13365 * Primary command inlet from frontend ports.  All SCSI and task I/O
13366 * requests must go through this function.
13367 */
13368int
13369ctl_queue(union ctl_io *io)
13370{
13371	struct ctl_port *port;
13372
13373	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13374
13375#ifdef CTL_TIME_IO
13376	io->io_hdr.start_time = time_uptime;
13377	getbintime(&io->io_hdr.start_bt);
13378#endif /* CTL_TIME_IO */
13379
13380	/* Map FE-specific LUN ID into global one. */
13381	port = ctl_io_port(&io->io_hdr);
13382	io->io_hdr.nexus.targ_mapped_lun =
13383	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13384
13385	switch (io->io_hdr.io_type) {
13386	case CTL_IO_SCSI:
13387	case CTL_IO_TASK:
13388		if (ctl_debug & CTL_DEBUG_CDB)
13389			ctl_io_print(io);
13390		ctl_enqueue_incoming(io);
13391		break;
13392	default:
13393		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13394		return (EINVAL);
13395	}
13396
13397	return (CTL_RETVAL_COMPLETE);
13398}
13399
13400#ifdef CTL_IO_DELAY
13401static void
13402ctl_done_timer_wakeup(void *arg)
13403{
13404	union ctl_io *io;
13405
13406	io = (union ctl_io *)arg;
13407	ctl_done(io);
13408}
13409#endif /* CTL_IO_DELAY */
13410
13411void
13412ctl_serseq_done(union ctl_io *io)
13413{
13414	struct ctl_lun *lun;
13415
13416	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13417	if (lun->be_lun == NULL ||
13418	    lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13419		return;
13420	mtx_lock(&lun->lun_lock);
13421	io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13422	ctl_check_blocked(lun);
13423	mtx_unlock(&lun->lun_lock);
13424}
13425
13426void
13427ctl_done(union ctl_io *io)
13428{
13429
13430	/*
13431	 * Enable this to catch duplicate completion issues.
13432	 */
13433#if 0
13434	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13435		printf("%s: type %d msg %d cdb %x iptl: "
13436		       "%u:%u:%u tag 0x%04x "
13437		       "flag %#x status %x\n",
13438			__func__,
13439			io->io_hdr.io_type,
13440			io->io_hdr.msg_type,
13441			io->scsiio.cdb[0],
13442			io->io_hdr.nexus.initid,
13443			io->io_hdr.nexus.targ_port,
13444			io->io_hdr.nexus.targ_lun,
13445			(io->io_hdr.io_type ==
13446			CTL_IO_TASK) ?
13447			io->taskio.tag_num :
13448			io->scsiio.tag_num,
13449		        io->io_hdr.flags,
13450			io->io_hdr.status);
13451	} else
13452		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13453#endif
13454
13455	/*
13456	 * This is an internal copy of an I/O, and should not go through
13457	 * the normal done processing logic.
13458	 */
13459	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13460		return;
13461
13462#ifdef CTL_IO_DELAY
13463	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13464		struct ctl_lun *lun;
13465
13466		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13467
13468		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13469	} else {
13470		struct ctl_lun *lun;
13471
13472		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13473
13474		if ((lun != NULL)
13475		 && (lun->delay_info.done_delay > 0)) {
13476
13477			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13478			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13479			callout_reset(&io->io_hdr.delay_callout,
13480				      lun->delay_info.done_delay * hz,
13481				      ctl_done_timer_wakeup, io);
13482			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13483				lun->delay_info.done_delay = 0;
13484			return;
13485		}
13486	}
13487#endif /* CTL_IO_DELAY */
13488
13489	ctl_enqueue_done(io);
13490}
13491
13492static void
13493ctl_work_thread(void *arg)
13494{
13495	struct ctl_thread *thr = (struct ctl_thread *)arg;
13496	struct ctl_softc *softc = thr->ctl_softc;
13497	union ctl_io *io;
13498	int retval;
13499
13500	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13501
13502	for (;;) {
13503		retval = 0;
13504
13505		/*
13506		 * We handle the queues in this order:
13507		 * - ISC
13508		 * - done queue (to free up resources, unblock other commands)
13509		 * - RtR queue
13510		 * - incoming queue
13511		 *
13512		 * If those queues are empty, we break out of the loop and
13513		 * go to sleep.
13514		 */
13515		mtx_lock(&thr->queue_lock);
13516		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13517		if (io != NULL) {
13518			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13519			mtx_unlock(&thr->queue_lock);
13520			ctl_handle_isc(io);
13521			continue;
13522		}
13523		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13524		if (io != NULL) {
13525			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13526			/* clear any blocked commands, call fe_done */
13527			mtx_unlock(&thr->queue_lock);
13528			retval = ctl_process_done(io);
13529			continue;
13530		}
13531		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13532		if (io != NULL) {
13533			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13534			mtx_unlock(&thr->queue_lock);
13535			if (io->io_hdr.io_type == CTL_IO_TASK)
13536				ctl_run_task(io);
13537			else
13538				ctl_scsiio_precheck(softc, &io->scsiio);
13539			continue;
13540		}
13541		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13542		if (io != NULL) {
13543			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13544			mtx_unlock(&thr->queue_lock);
13545			retval = ctl_scsiio(&io->scsiio);
13546			if (retval != CTL_RETVAL_COMPLETE)
13547				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13548			continue;
13549		}
13550
13551		/* Sleep until we have something to do. */
13552		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13553	}
13554}
13555
13556static void
13557ctl_lun_thread(void *arg)
13558{
13559	struct ctl_softc *softc = (struct ctl_softc *)arg;
13560	struct ctl_be_lun *be_lun;
13561	int retval;
13562
13563	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13564
13565	for (;;) {
13566		retval = 0;
13567		mtx_lock(&softc->ctl_lock);
13568		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13569		if (be_lun != NULL) {
13570			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13571			mtx_unlock(&softc->ctl_lock);
13572			ctl_create_lun(be_lun);
13573			continue;
13574		}
13575
13576		/* Sleep until we have something to do. */
13577		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13578		    PDROP | PRIBIO, "-", 0);
13579	}
13580}
13581
13582static void
13583ctl_thresh_thread(void *arg)
13584{
13585	struct ctl_softc *softc = (struct ctl_softc *)arg;
13586	struct ctl_lun *lun;
13587	struct ctl_be_lun *be_lun;
13588	struct scsi_da_rw_recovery_page *rwpage;
13589	struct ctl_logical_block_provisioning_page *page;
13590	const char *attr;
13591	union ctl_ha_msg msg;
13592	uint64_t thres, val;
13593	int i, e, set;
13594
13595	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13596
13597	for (;;) {
13598		mtx_lock(&softc->ctl_lock);
13599		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13600			be_lun = lun->be_lun;
13601			if ((lun->flags & CTL_LUN_DISABLED) ||
13602			    (lun->flags & CTL_LUN_OFFLINE) ||
13603			    lun->backend->lun_attr == NULL)
13604				continue;
13605			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13606			    softc->ha_mode == CTL_HA_MODE_XFER)
13607				continue;
13608			rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13609			if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13610				continue;
13611			e = 0;
13612			page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13613			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13614				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13615					continue;
13616				thres = scsi_4btoul(page->descr[i].count);
13617				thres <<= CTL_LBP_EXPONENT;
13618				switch (page->descr[i].resource) {
13619				case 0x01:
13620					attr = "blocksavail";
13621					break;
13622				case 0x02:
13623					attr = "blocksused";
13624					break;
13625				case 0xf1:
13626					attr = "poolblocksavail";
13627					break;
13628				case 0xf2:
13629					attr = "poolblocksused";
13630					break;
13631				default:
13632					continue;
13633				}
13634				mtx_unlock(&softc->ctl_lock); // XXX
13635				val = lun->backend->lun_attr(
13636				    lun->be_lun->be_lun, attr);
13637				mtx_lock(&softc->ctl_lock);
13638				if (val == UINT64_MAX)
13639					continue;
13640				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13641				    == SLBPPD_ARMING_INC)
13642					e = (val >= thres);
13643				else
13644					e = (val <= thres);
13645				if (e)
13646					break;
13647			}
13648			mtx_lock(&lun->lun_lock);
13649			if (e) {
13650				scsi_u64to8b((uint8_t *)&page->descr[i] -
13651				    (uint8_t *)page, lun->ua_tpt_info);
13652				if (lun->lasttpt == 0 ||
13653				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13654					lun->lasttpt = time_uptime;
13655					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13656					set = 1;
13657				} else
13658					set = 0;
13659			} else {
13660				lun->lasttpt = 0;
13661				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13662				set = -1;
13663			}
13664			mtx_unlock(&lun->lun_lock);
13665			if (set != 0 &&
13666			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13667				/* Send msg to other side. */
13668				bzero(&msg.ua, sizeof(msg.ua));
13669				msg.hdr.msg_type = CTL_MSG_UA;
13670				msg.hdr.nexus.initid = -1;
13671				msg.hdr.nexus.targ_port = -1;
13672				msg.hdr.nexus.targ_lun = lun->lun;
13673				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13674				msg.ua.ua_all = 1;
13675				msg.ua.ua_set = (set > 0);
13676				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13677				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13678				mtx_unlock(&softc->ctl_lock); // XXX
13679				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13680				    sizeof(msg.ua), M_WAITOK);
13681				mtx_lock(&softc->ctl_lock);
13682			}
13683		}
13684		mtx_unlock(&softc->ctl_lock);
13685		pause("-", CTL_LBP_PERIOD * hz);
13686	}
13687}
13688
13689static void
13690ctl_enqueue_incoming(union ctl_io *io)
13691{
13692	struct ctl_softc *softc = control_softc;
13693	struct ctl_thread *thr;
13694	u_int idx;
13695
13696	idx = (io->io_hdr.nexus.targ_port * 127 +
13697	       io->io_hdr.nexus.initid) % worker_threads;
13698	thr = &softc->threads[idx];
13699	mtx_lock(&thr->queue_lock);
13700	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13701	mtx_unlock(&thr->queue_lock);
13702	wakeup(thr);
13703}
13704
13705static void
13706ctl_enqueue_rtr(union ctl_io *io)
13707{
13708	struct ctl_softc *softc = control_softc;
13709	struct ctl_thread *thr;
13710
13711	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13712	mtx_lock(&thr->queue_lock);
13713	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13714	mtx_unlock(&thr->queue_lock);
13715	wakeup(thr);
13716}
13717
13718static void
13719ctl_enqueue_done(union ctl_io *io)
13720{
13721	struct ctl_softc *softc = control_softc;
13722	struct ctl_thread *thr;
13723
13724	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13725	mtx_lock(&thr->queue_lock);
13726	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13727	mtx_unlock(&thr->queue_lock);
13728	wakeup(thr);
13729}
13730
13731static void
13732ctl_enqueue_isc(union ctl_io *io)
13733{
13734	struct ctl_softc *softc = control_softc;
13735	struct ctl_thread *thr;
13736
13737	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13738	mtx_lock(&thr->queue_lock);
13739	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13740	mtx_unlock(&thr->queue_lock);
13741	wakeup(thr);
13742}
13743
13744/*
13745 *  vim: ts=8
13746 */
13747