ctl.c revision 288165
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: head/sys/cam/ctl/ctl.c 288165 2015-09-24 07:16:34Z 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;
358SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
359    &worker_threads, 1, "Number of worker threads");
360static int ctl_debug = CTL_DEBUG_NONE;
361SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
362    &ctl_debug, 0, "Enabled debug flags");
363
364/*
365 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
366 * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
367 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
368 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
369 */
370#define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
371
372static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
373				  int param);
374static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
375static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
376static int ctl_init(void);
377void ctl_shutdown(void);
378static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
379static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
380static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
381static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
382			      struct ctl_ooa *ooa_hdr,
383			      struct ctl_ooa_entry *kern_entries);
384static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
385		     struct thread *td);
386static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
387			 struct ctl_be_lun *be_lun);
388static int ctl_free_lun(struct ctl_lun *lun);
389static void ctl_create_lun(struct ctl_be_lun *be_lun);
390static struct ctl_port * ctl_io_port(struct ctl_io_hdr *io_hdr);
391
392static int ctl_do_mode_select(union ctl_io *io);
393static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
394			   uint64_t res_key, uint64_t sa_res_key,
395			   uint8_t type, uint32_t residx,
396			   struct ctl_scsiio *ctsio,
397			   struct scsi_per_res_out *cdb,
398			   struct scsi_per_res_out_parms* param);
399static void ctl_pro_preempt_other(struct ctl_lun *lun,
400				  union ctl_ha_msg *msg);
401static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
402static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
403static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
404static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
405static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
406static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
407static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
408					 int alloc_len);
409static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
410					 int alloc_len);
411static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
412static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
413static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
414static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
415static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
416static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
417    bool seq);
418static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
419static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
420    union ctl_io *pending_io, union ctl_io *ooa_io);
421static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
422				union ctl_io *starting_io);
423static int ctl_check_blocked(struct ctl_lun *lun);
424static int ctl_scsiio_lun_check(struct ctl_lun *lun,
425				const struct ctl_cmd_entry *entry,
426				struct ctl_scsiio *ctsio);
427static void ctl_failover_lun(struct ctl_lun *lun);
428static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
429			       struct ctl_scsiio *ctsio);
430static int ctl_scsiio(struct ctl_scsiio *ctsio);
431
432static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
433static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
434			    ctl_ua_type ua_type);
435static int ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io,
436			 ctl_ua_type ua_type);
437static int ctl_lun_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
438static int ctl_abort_task(union ctl_io *io);
439static int ctl_abort_task_set(union ctl_io *io);
440static int ctl_query_task(union ctl_io *io, int task_set);
441static int ctl_i_t_nexus_reset(union ctl_io *io);
442static int ctl_query_async_event(union ctl_io *io);
443static void ctl_run_task(union ctl_io *io);
444#ifdef CTL_IO_DELAY
445static void ctl_datamove_timer_wakeup(void *arg);
446static void ctl_done_timer_wakeup(void *arg);
447#endif /* CTL_IO_DELAY */
448
449static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
450static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
451static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
452static void ctl_datamove_remote_write(union ctl_io *io);
453static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
454static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
455static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
456static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
457				    ctl_ha_dt_cb callback);
458static void ctl_datamove_remote_read(union ctl_io *io);
459static void ctl_datamove_remote(union ctl_io *io);
460static int ctl_process_done(union ctl_io *io);
461static void ctl_lun_thread(void *arg);
462static void ctl_thresh_thread(void *arg);
463static void ctl_work_thread(void *arg);
464static void ctl_enqueue_incoming(union ctl_io *io);
465static void ctl_enqueue_rtr(union ctl_io *io);
466static void ctl_enqueue_done(union ctl_io *io);
467static void ctl_enqueue_isc(union ctl_io *io);
468static const struct ctl_cmd_entry *
469    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
470static const struct ctl_cmd_entry *
471    ctl_validate_command(struct ctl_scsiio *ctsio);
472static int ctl_cmd_applicable(uint8_t lun_type,
473    const struct ctl_cmd_entry *entry);
474
475static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
476static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
477static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
478static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
479
480/*
481 * Load the serialization table.  This isn't very pretty, but is probably
482 * the easiest way to do it.
483 */
484#include "ctl_ser_table.c"
485
486/*
487 * We only need to define open, close and ioctl routines for this driver.
488 */
489static struct cdevsw ctl_cdevsw = {
490	.d_version =	D_VERSION,
491	.d_flags =	0,
492	.d_open =	ctl_open,
493	.d_close =	ctl_close,
494	.d_ioctl =	ctl_ioctl,
495	.d_name =	"ctl",
496};
497
498
499MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
500
501static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
502
503static moduledata_t ctl_moduledata = {
504	"ctl",
505	ctl_module_event_handler,
506	NULL
507};
508
509DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
510MODULE_VERSION(ctl, 1);
511
512static struct ctl_frontend ha_frontend =
513{
514	.name = "ha",
515};
516
517static void
518ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
519			    union ctl_ha_msg *msg_info)
520{
521	struct ctl_scsiio *ctsio;
522
523	if (msg_info->hdr.original_sc == NULL) {
524		printf("%s: original_sc == NULL!\n", __func__);
525		/* XXX KDM now what? */
526		return;
527	}
528
529	ctsio = &msg_info->hdr.original_sc->scsiio;
530	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
531	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
532	ctsio->io_hdr.status = msg_info->hdr.status;
533	ctsio->scsi_status = msg_info->scsi.scsi_status;
534	ctsio->sense_len = msg_info->scsi.sense_len;
535	ctsio->sense_residual = msg_info->scsi.sense_residual;
536	ctsio->residual = msg_info->scsi.residual;
537	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
538	       msg_info->scsi.sense_len);
539	ctl_enqueue_isc((union ctl_io *)ctsio);
540}
541
542static void
543ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
544				union ctl_ha_msg *msg_info)
545{
546	struct ctl_scsiio *ctsio;
547
548	if (msg_info->hdr.serializing_sc == NULL) {
549		printf("%s: serializing_sc == NULL!\n", __func__);
550		/* XXX KDM now what? */
551		return;
552	}
553
554	ctsio = &msg_info->hdr.serializing_sc->scsiio;
555	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
556	ctl_enqueue_isc((union ctl_io *)ctsio);
557}
558
559void
560ctl_isc_announce_lun(struct ctl_lun *lun)
561{
562	struct ctl_softc *softc = lun->ctl_softc;
563	union ctl_ha_msg *msg;
564	struct ctl_ha_msg_lun_pr_key pr_key;
565	int i, k;
566
567	if (softc->ha_link != CTL_HA_LINK_ONLINE)
568		return;
569	mtx_lock(&lun->lun_lock);
570	i = sizeof(msg->lun);
571	if (lun->lun_devid)
572		i += lun->lun_devid->len;
573	i += sizeof(pr_key) * lun->pr_key_count;
574alloc:
575	mtx_unlock(&lun->lun_lock);
576	msg = malloc(i, M_CTL, M_WAITOK);
577	mtx_lock(&lun->lun_lock);
578	k = sizeof(msg->lun);
579	if (lun->lun_devid)
580		k += lun->lun_devid->len;
581	k += sizeof(pr_key) * lun->pr_key_count;
582	if (i < k) {
583		free(msg, M_CTL);
584		i = k;
585		goto alloc;
586	}
587	bzero(&msg->lun, sizeof(msg->lun));
588	msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
589	msg->hdr.nexus.targ_lun = lun->lun;
590	msg->hdr.nexus.targ_mapped_lun = lun->lun;
591	msg->lun.flags = lun->flags;
592	msg->lun.pr_generation = lun->PRGeneration;
593	msg->lun.pr_res_idx = lun->pr_res_idx;
594	msg->lun.pr_res_type = lun->res_type;
595	msg->lun.pr_key_count = lun->pr_key_count;
596	i = 0;
597	if (lun->lun_devid) {
598		msg->lun.lun_devid_len = lun->lun_devid->len;
599		memcpy(&msg->lun.data[i], lun->lun_devid->data,
600		    msg->lun.lun_devid_len);
601		i += msg->lun.lun_devid_len;
602	}
603	for (k = 0; k < CTL_MAX_INITIATORS; k++) {
604		if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
605			continue;
606		pr_key.pr_iid = k;
607		memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
608		i += sizeof(pr_key);
609	}
610	mtx_unlock(&lun->lun_lock);
611	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
612	    M_WAITOK);
613	free(msg, M_CTL);
614
615	if (lun->flags & CTL_LUN_PRIMARY_SC) {
616		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
617			ctl_isc_announce_mode(lun, -1,
618			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
619			    lun->mode_pages.index[i].subpage);
620		}
621	}
622}
623
624void
625ctl_isc_announce_port(struct ctl_port *port)
626{
627	struct ctl_softc *softc = control_softc;
628	union ctl_ha_msg *msg;
629	int i;
630
631	if (port->targ_port < softc->port_min ||
632	    port->targ_port >= softc->port_max ||
633	    softc->ha_link != CTL_HA_LINK_ONLINE)
634		return;
635	i = sizeof(msg->port) + strlen(port->port_name) + 1;
636	if (port->lun_map)
637		i += sizeof(uint32_t) * CTL_MAX_LUNS;
638	if (port->port_devid)
639		i += port->port_devid->len;
640	if (port->target_devid)
641		i += port->target_devid->len;
642	if (port->init_devid)
643		i += port->init_devid->len;
644	msg = malloc(i, M_CTL, M_WAITOK);
645	bzero(&msg->port, sizeof(msg->port));
646	msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
647	msg->hdr.nexus.targ_port = port->targ_port;
648	msg->port.port_type = port->port_type;
649	msg->port.physical_port = port->physical_port;
650	msg->port.virtual_port = port->virtual_port;
651	msg->port.status = port->status;
652	i = 0;
653	msg->port.name_len = sprintf(&msg->port.data[i],
654	    "%d:%s", softc->ha_id, port->port_name) + 1;
655	i += msg->port.name_len;
656	if (port->lun_map) {
657		msg->port.lun_map_len = sizeof(uint32_t) * CTL_MAX_LUNS;
658		memcpy(&msg->port.data[i], port->lun_map,
659		    msg->port.lun_map_len);
660		i += msg->port.lun_map_len;
661	}
662	if (port->port_devid) {
663		msg->port.port_devid_len = port->port_devid->len;
664		memcpy(&msg->port.data[i], port->port_devid->data,
665		    msg->port.port_devid_len);
666		i += msg->port.port_devid_len;
667	}
668	if (port->target_devid) {
669		msg->port.target_devid_len = port->target_devid->len;
670		memcpy(&msg->port.data[i], port->target_devid->data,
671		    msg->port.target_devid_len);
672		i += msg->port.target_devid_len;
673	}
674	if (port->init_devid) {
675		msg->port.init_devid_len = port->init_devid->len;
676		memcpy(&msg->port.data[i], port->init_devid->data,
677		    msg->port.init_devid_len);
678		i += msg->port.init_devid_len;
679	}
680	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
681	    M_WAITOK);
682	free(msg, M_CTL);
683}
684
685void
686ctl_isc_announce_iid(struct ctl_port *port, int iid)
687{
688	struct ctl_softc *softc = control_softc;
689	union ctl_ha_msg *msg;
690	int i, l;
691
692	if (port->targ_port < softc->port_min ||
693	    port->targ_port >= softc->port_max ||
694	    softc->ha_link != CTL_HA_LINK_ONLINE)
695		return;
696	mtx_lock(&softc->ctl_lock);
697	i = sizeof(msg->iid);
698	l = 0;
699	if (port->wwpn_iid[iid].name)
700		l = strlen(port->wwpn_iid[iid].name) + 1;
701	i += l;
702	msg = malloc(i, M_CTL, M_NOWAIT);
703	if (msg == NULL) {
704		mtx_unlock(&softc->ctl_lock);
705		return;
706	}
707	bzero(&msg->iid, sizeof(msg->iid));
708	msg->hdr.msg_type = CTL_MSG_IID_SYNC;
709	msg->hdr.nexus.targ_port = port->targ_port;
710	msg->hdr.nexus.initid = iid;
711	msg->iid.in_use = port->wwpn_iid[iid].in_use;
712	msg->iid.name_len = l;
713	msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
714	if (port->wwpn_iid[iid].name)
715		strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
716	mtx_unlock(&softc->ctl_lock);
717	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
718	free(msg, M_CTL);
719}
720
721void
722ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
723    uint8_t page, uint8_t subpage)
724{
725	struct ctl_softc *softc = lun->ctl_softc;
726	union ctl_ha_msg msg;
727	int i;
728
729	if (softc->ha_link != CTL_HA_LINK_ONLINE)
730		return;
731	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
732		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
733		    page && lun->mode_pages.index[i].subpage == subpage)
734			break;
735	}
736	if (i == CTL_NUM_MODE_PAGES)
737		return;
738	bzero(&msg.mode, sizeof(msg.mode));
739	msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
740	msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
741	msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
742	msg.hdr.nexus.targ_lun = lun->lun;
743	msg.hdr.nexus.targ_mapped_lun = lun->lun;
744	msg.mode.page_code = page;
745	msg.mode.subpage = subpage;
746	msg.mode.page_len = lun->mode_pages.index[i].page_len;
747	memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
748	    msg.mode.page_len);
749	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
750	    M_WAITOK);
751}
752
753static void
754ctl_isc_ha_link_up(struct ctl_softc *softc)
755{
756	struct ctl_port *port;
757	struct ctl_lun *lun;
758	union ctl_ha_msg msg;
759	int i;
760
761	/* Announce this node parameters to peer for validation. */
762	msg.login.msg_type = CTL_MSG_LOGIN;
763	msg.login.version = CTL_HA_VERSION;
764	msg.login.ha_mode = softc->ha_mode;
765	msg.login.ha_id = softc->ha_id;
766	msg.login.max_luns = CTL_MAX_LUNS;
767	msg.login.max_ports = CTL_MAX_PORTS;
768	msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
769	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
770	    M_WAITOK);
771
772	STAILQ_FOREACH(port, &softc->port_list, links) {
773		ctl_isc_announce_port(port);
774		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
775			if (port->wwpn_iid[i].in_use)
776				ctl_isc_announce_iid(port, i);
777		}
778	}
779	STAILQ_FOREACH(lun, &softc->lun_list, links)
780		ctl_isc_announce_lun(lun);
781}
782
783static void
784ctl_isc_ha_link_down(struct ctl_softc *softc)
785{
786	struct ctl_port *port;
787	struct ctl_lun *lun;
788	union ctl_io *io;
789	int i;
790
791	mtx_lock(&softc->ctl_lock);
792	STAILQ_FOREACH(lun, &softc->lun_list, links) {
793		mtx_lock(&lun->lun_lock);
794		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
795			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
796			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
797		}
798		mtx_unlock(&lun->lun_lock);
799
800		mtx_unlock(&softc->ctl_lock);
801		io = ctl_alloc_io(softc->othersc_pool);
802		mtx_lock(&softc->ctl_lock);
803		ctl_zero_io(io);
804		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
805		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
806		ctl_enqueue_isc(io);
807	}
808
809	STAILQ_FOREACH(port, &softc->port_list, links) {
810		if (port->targ_port >= softc->port_min &&
811		    port->targ_port < softc->port_max)
812			continue;
813		port->status &= ~CTL_PORT_STATUS_ONLINE;
814		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
815			port->wwpn_iid[i].in_use = 0;
816			free(port->wwpn_iid[i].name, M_CTL);
817			port->wwpn_iid[i].name = NULL;
818		}
819	}
820	mtx_unlock(&softc->ctl_lock);
821}
822
823static void
824ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
825{
826	struct ctl_lun *lun;
827	uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
828
829	mtx_lock(&softc->ctl_lock);
830	if (msg->hdr.nexus.targ_lun < CTL_MAX_LUNS &&
831	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) != NULL) {
832		mtx_lock(&lun->lun_lock);
833		mtx_unlock(&softc->ctl_lock);
834		if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES &&
835		    msg->ua.ua_set)
836			memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
837		if (msg->ua.ua_all) {
838			if (msg->ua.ua_set)
839				ctl_est_ua_all(lun, iid, msg->ua.ua_type);
840			else
841				ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
842		} else {
843			if (msg->ua.ua_set)
844				ctl_est_ua(lun, iid, msg->ua.ua_type);
845			else
846				ctl_clr_ua(lun, iid, msg->ua.ua_type);
847		}
848		mtx_unlock(&lun->lun_lock);
849	} else
850		mtx_unlock(&softc->ctl_lock);
851}
852
853static void
854ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
855{
856	struct ctl_lun *lun;
857	struct ctl_ha_msg_lun_pr_key pr_key;
858	int i, k;
859	ctl_lun_flags oflags;
860	uint32_t targ_lun;
861
862	targ_lun = msg->hdr.nexus.targ_mapped_lun;
863	mtx_lock(&softc->ctl_lock);
864	if ((targ_lun >= CTL_MAX_LUNS) ||
865	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
866		mtx_unlock(&softc->ctl_lock);
867		return;
868	}
869	mtx_lock(&lun->lun_lock);
870	mtx_unlock(&softc->ctl_lock);
871	if (lun->flags & CTL_LUN_DISABLED) {
872		mtx_unlock(&lun->lun_lock);
873		return;
874	}
875	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
876	if (msg->lun.lun_devid_len != i || (i > 0 &&
877	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
878		mtx_unlock(&lun->lun_lock);
879		printf("%s: Received conflicting HA LUN %d\n",
880		    __func__, msg->hdr.nexus.targ_lun);
881		return;
882	} else {
883		/* Record whether peer is primary. */
884		oflags = lun->flags;
885		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
886		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
887			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
888		else
889			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
890		if (oflags != lun->flags)
891			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
892
893		/* If peer is primary and we are not -- use data */
894		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
895		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
896			lun->PRGeneration = msg->lun.pr_generation;
897			lun->pr_res_idx = msg->lun.pr_res_idx;
898			lun->res_type = msg->lun.pr_res_type;
899			lun->pr_key_count = msg->lun.pr_key_count;
900			for (k = 0; k < CTL_MAX_INITIATORS; k++)
901				ctl_clr_prkey(lun, k);
902			for (k = 0; k < msg->lun.pr_key_count; k++) {
903				memcpy(&pr_key, &msg->lun.data[i],
904				    sizeof(pr_key));
905				ctl_alloc_prkey(lun, pr_key.pr_iid);
906				ctl_set_prkey(lun, pr_key.pr_iid,
907				    pr_key.pr_key);
908				i += sizeof(pr_key);
909			}
910		}
911
912		mtx_unlock(&lun->lun_lock);
913		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
914		    __func__, msg->hdr.nexus.targ_lun,
915		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
916		    "primary" : "secondary"));
917
918		/* If we are primary but peer doesn't know -- notify */
919		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
920		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
921			ctl_isc_announce_lun(lun);
922	}
923}
924
925static void
926ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
927{
928	struct ctl_port *port;
929	struct ctl_lun *lun;
930	int i, new;
931
932	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
933	if (port == NULL) {
934		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
935		    msg->hdr.nexus.targ_port));
936		new = 1;
937		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
938		port->frontend = &ha_frontend;
939		port->targ_port = msg->hdr.nexus.targ_port;
940	} else if (port->frontend == &ha_frontend) {
941		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
942		    msg->hdr.nexus.targ_port));
943		new = 0;
944	} else {
945		printf("%s: Received conflicting HA port %d\n",
946		    __func__, msg->hdr.nexus.targ_port);
947		return;
948	}
949	port->port_type = msg->port.port_type;
950	port->physical_port = msg->port.physical_port;
951	port->virtual_port = msg->port.virtual_port;
952	port->status = msg->port.status;
953	i = 0;
954	free(port->port_name, M_CTL);
955	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
956	    M_CTL);
957	i += msg->port.name_len;
958	if (msg->port.lun_map_len != 0) {
959		if (port->lun_map == NULL)
960			port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
961			    M_CTL, M_WAITOK);
962		memcpy(port->lun_map, &msg->port.data[i],
963		    sizeof(uint32_t) * CTL_MAX_LUNS);
964		i += msg->port.lun_map_len;
965	} else {
966		free(port->lun_map, M_CTL);
967		port->lun_map = NULL;
968	}
969	if (msg->port.port_devid_len != 0) {
970		if (port->port_devid == NULL ||
971		    port->port_devid->len != msg->port.port_devid_len) {
972			free(port->port_devid, M_CTL);
973			port->port_devid = malloc(sizeof(struct ctl_devid) +
974			    msg->port.port_devid_len, M_CTL, M_WAITOK);
975		}
976		memcpy(port->port_devid->data, &msg->port.data[i],
977		    msg->port.port_devid_len);
978		port->port_devid->len = msg->port.port_devid_len;
979		i += msg->port.port_devid_len;
980	} else {
981		free(port->port_devid, M_CTL);
982		port->port_devid = NULL;
983	}
984	if (msg->port.target_devid_len != 0) {
985		if (port->target_devid == NULL ||
986		    port->target_devid->len != msg->port.target_devid_len) {
987			free(port->target_devid, M_CTL);
988			port->target_devid = malloc(sizeof(struct ctl_devid) +
989			    msg->port.target_devid_len, M_CTL, M_WAITOK);
990		}
991		memcpy(port->target_devid->data, &msg->port.data[i],
992		    msg->port.target_devid_len);
993		port->target_devid->len = msg->port.target_devid_len;
994		i += msg->port.target_devid_len;
995	} else {
996		free(port->target_devid, M_CTL);
997		port->target_devid = NULL;
998	}
999	if (msg->port.init_devid_len != 0) {
1000		if (port->init_devid == NULL ||
1001		    port->init_devid->len != msg->port.init_devid_len) {
1002			free(port->init_devid, M_CTL);
1003			port->init_devid = malloc(sizeof(struct ctl_devid) +
1004			    msg->port.init_devid_len, M_CTL, M_WAITOK);
1005		}
1006		memcpy(port->init_devid->data, &msg->port.data[i],
1007		    msg->port.init_devid_len);
1008		port->init_devid->len = msg->port.init_devid_len;
1009		i += msg->port.init_devid_len;
1010	} else {
1011		free(port->init_devid, M_CTL);
1012		port->init_devid = NULL;
1013	}
1014	if (new) {
1015		if (ctl_port_register(port) != 0) {
1016			printf("%s: ctl_port_register() failed with error\n",
1017			    __func__);
1018		}
1019	}
1020	mtx_lock(&softc->ctl_lock);
1021	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1022		if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
1023			continue;
1024		mtx_lock(&lun->lun_lock);
1025		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1026		mtx_unlock(&lun->lun_lock);
1027	}
1028	mtx_unlock(&softc->ctl_lock);
1029}
1030
1031static void
1032ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1033{
1034	struct ctl_port *port;
1035	int iid;
1036
1037	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1038	if (port == NULL) {
1039		printf("%s: Received IID for unknown port %d\n",
1040		    __func__, msg->hdr.nexus.targ_port);
1041		return;
1042	}
1043	iid = msg->hdr.nexus.initid;
1044	port->wwpn_iid[iid].in_use = msg->iid.in_use;
1045	port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1046	free(port->wwpn_iid[iid].name, M_CTL);
1047	if (msg->iid.name_len) {
1048		port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1049		    msg->iid.name_len, M_CTL);
1050	} else
1051		port->wwpn_iid[iid].name = NULL;
1052}
1053
1054static void
1055ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1056{
1057
1058	if (msg->login.version != CTL_HA_VERSION) {
1059		printf("CTL HA peers have different versions %d != %d\n",
1060		    msg->login.version, CTL_HA_VERSION);
1061		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1062		return;
1063	}
1064	if (msg->login.ha_mode != softc->ha_mode) {
1065		printf("CTL HA peers have different ha_mode %d != %d\n",
1066		    msg->login.ha_mode, softc->ha_mode);
1067		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1068		return;
1069	}
1070	if (msg->login.ha_id == softc->ha_id) {
1071		printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1072		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1073		return;
1074	}
1075	if (msg->login.max_luns != CTL_MAX_LUNS ||
1076	    msg->login.max_ports != CTL_MAX_PORTS ||
1077	    msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1078		printf("CTL HA peers have different limits\n");
1079		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1080		return;
1081	}
1082}
1083
1084static void
1085ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1086{
1087	struct ctl_lun *lun;
1088	int i;
1089	uint32_t initidx, targ_lun;
1090
1091	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1092	mtx_lock(&softc->ctl_lock);
1093	if ((targ_lun >= CTL_MAX_LUNS) ||
1094	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
1095		mtx_unlock(&softc->ctl_lock);
1096		return;
1097	}
1098	mtx_lock(&lun->lun_lock);
1099	mtx_unlock(&softc->ctl_lock);
1100	if (lun->flags & CTL_LUN_DISABLED) {
1101		mtx_unlock(&lun->lun_lock);
1102		return;
1103	}
1104	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1105		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1106		    msg->mode.page_code &&
1107		    lun->mode_pages.index[i].subpage == msg->mode.subpage)
1108			break;
1109	}
1110	if (i == CTL_NUM_MODE_PAGES) {
1111		mtx_unlock(&lun->lun_lock);
1112		return;
1113	}
1114	memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1115	    lun->mode_pages.index[i].page_len);
1116	initidx = ctl_get_initindex(&msg->hdr.nexus);
1117	if (initidx != -1)
1118		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1119	mtx_unlock(&lun->lun_lock);
1120}
1121
1122/*
1123 * ISC (Inter Shelf Communication) event handler.  Events from the HA
1124 * subsystem come in here.
1125 */
1126static void
1127ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1128{
1129	struct ctl_softc *softc;
1130	union ctl_io *io;
1131	struct ctl_prio *presio;
1132	ctl_ha_status isc_status;
1133
1134	softc = control_softc;
1135	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1136	if (event == CTL_HA_EVT_MSG_RECV) {
1137		union ctl_ha_msg *msg, msgbuf;
1138
1139		if (param > sizeof(msgbuf))
1140			msg = malloc(param, M_CTL, M_WAITOK);
1141		else
1142			msg = &msgbuf;
1143		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1144		    M_WAITOK);
1145		if (isc_status != CTL_HA_STATUS_SUCCESS) {
1146			printf("%s: Error receiving message: %d\n",
1147			    __func__, isc_status);
1148			if (msg != &msgbuf)
1149				free(msg, M_CTL);
1150			return;
1151		}
1152
1153		CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1154		switch (msg->hdr.msg_type) {
1155		case CTL_MSG_SERIALIZE:
1156			io = ctl_alloc_io(softc->othersc_pool);
1157			ctl_zero_io(io);
1158			// populate ctsio from msg
1159			io->io_hdr.io_type = CTL_IO_SCSI;
1160			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1161			io->io_hdr.original_sc = msg->hdr.original_sc;
1162			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1163					    CTL_FLAG_IO_ACTIVE;
1164			/*
1165			 * If we're in serialization-only mode, we don't
1166			 * want to go through full done processing.  Thus
1167			 * the COPY flag.
1168			 *
1169			 * XXX KDM add another flag that is more specific.
1170			 */
1171			if (softc->ha_mode != CTL_HA_MODE_XFER)
1172				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1173			io->io_hdr.nexus = msg->hdr.nexus;
1174#if 0
1175			printf("port %u, iid %u, lun %u\n",
1176			       io->io_hdr.nexus.targ_port,
1177			       io->io_hdr.nexus.initid,
1178			       io->io_hdr.nexus.targ_lun);
1179#endif
1180			io->scsiio.tag_num = msg->scsi.tag_num;
1181			io->scsiio.tag_type = msg->scsi.tag_type;
1182#ifdef CTL_TIME_IO
1183			io->io_hdr.start_time = time_uptime;
1184			getbintime(&io->io_hdr.start_bt);
1185#endif /* CTL_TIME_IO */
1186			io->scsiio.cdb_len = msg->scsi.cdb_len;
1187			memcpy(io->scsiio.cdb, msg->scsi.cdb,
1188			       CTL_MAX_CDBLEN);
1189			if (softc->ha_mode == CTL_HA_MODE_XFER) {
1190				const struct ctl_cmd_entry *entry;
1191
1192				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1193				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1194				io->io_hdr.flags |=
1195					entry->flags & CTL_FLAG_DATA_MASK;
1196			}
1197			ctl_enqueue_isc(io);
1198			break;
1199
1200		/* Performed on the Originating SC, XFER mode only */
1201		case CTL_MSG_DATAMOVE: {
1202			struct ctl_sg_entry *sgl;
1203			int i, j;
1204
1205			io = msg->hdr.original_sc;
1206			if (io == NULL) {
1207				printf("%s: original_sc == NULL!\n", __func__);
1208				/* XXX KDM do something here */
1209				break;
1210			}
1211			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1212			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1213			/*
1214			 * Keep track of this, we need to send it back over
1215			 * when the datamove is complete.
1216			 */
1217			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1218			if (msg->hdr.status == CTL_SUCCESS)
1219				io->io_hdr.status = msg->hdr.status;
1220
1221			if (msg->dt.sg_sequence == 0) {
1222				i = msg->dt.kern_sg_entries +
1223				    msg->dt.kern_data_len /
1224				    CTL_HA_DATAMOVE_SEGMENT + 1;
1225				sgl = malloc(sizeof(*sgl) * i, M_CTL,
1226				    M_WAITOK | M_ZERO);
1227				io->io_hdr.remote_sglist = sgl;
1228				io->io_hdr.local_sglist =
1229				    &sgl[msg->dt.kern_sg_entries];
1230
1231				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1232
1233				io->scsiio.kern_sg_entries =
1234					msg->dt.kern_sg_entries;
1235				io->scsiio.rem_sg_entries =
1236					msg->dt.kern_sg_entries;
1237				io->scsiio.kern_data_len =
1238					msg->dt.kern_data_len;
1239				io->scsiio.kern_total_len =
1240					msg->dt.kern_total_len;
1241				io->scsiio.kern_data_resid =
1242					msg->dt.kern_data_resid;
1243				io->scsiio.kern_rel_offset =
1244					msg->dt.kern_rel_offset;
1245				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1246				io->io_hdr.flags |= msg->dt.flags &
1247				    CTL_FLAG_BUS_ADDR;
1248			} else
1249				sgl = (struct ctl_sg_entry *)
1250					io->scsiio.kern_data_ptr;
1251
1252			for (i = msg->dt.sent_sg_entries, j = 0;
1253			     i < (msg->dt.sent_sg_entries +
1254			     msg->dt.cur_sg_entries); i++, j++) {
1255				sgl[i].addr = msg->dt.sg_list[j].addr;
1256				sgl[i].len = msg->dt.sg_list[j].len;
1257
1258#if 0
1259				printf("%s: DATAMOVE: %p,%lu j=%d, i=%d\n",
1260				    __func__, sgl[i].addr, sgl[i].len, j, i);
1261#endif
1262			}
1263
1264			/*
1265			 * If this is the last piece of the I/O, we've got
1266			 * the full S/G list.  Queue processing in the thread.
1267			 * Otherwise wait for the next piece.
1268			 */
1269			if (msg->dt.sg_last != 0)
1270				ctl_enqueue_isc(io);
1271			break;
1272		}
1273		/* Performed on the Serializing (primary) SC, XFER mode only */
1274		case CTL_MSG_DATAMOVE_DONE: {
1275			if (msg->hdr.serializing_sc == NULL) {
1276				printf("%s: serializing_sc == NULL!\n",
1277				       __func__);
1278				/* XXX KDM now what? */
1279				break;
1280			}
1281			/*
1282			 * We grab the sense information here in case
1283			 * there was a failure, so we can return status
1284			 * back to the initiator.
1285			 */
1286			io = msg->hdr.serializing_sc;
1287			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1288			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1289			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1290			io->io_hdr.port_status = msg->scsi.fetd_status;
1291			io->scsiio.residual = msg->scsi.residual;
1292			if (msg->hdr.status != CTL_STATUS_NONE) {
1293				io->io_hdr.status = msg->hdr.status;
1294				io->scsiio.scsi_status = msg->scsi.scsi_status;
1295				io->scsiio.sense_len = msg->scsi.sense_len;
1296				io->scsiio.sense_residual =msg->scsi.sense_residual;
1297				memcpy(&io->scsiio.sense_data,
1298				    &msg->scsi.sense_data,
1299				    msg->scsi.sense_len);
1300				if (msg->hdr.status == CTL_SUCCESS)
1301					io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1302			}
1303			ctl_enqueue_isc(io);
1304			break;
1305		}
1306
1307		/* Preformed on Originating SC, SER_ONLY mode */
1308		case CTL_MSG_R2R:
1309			io = msg->hdr.original_sc;
1310			if (io == NULL) {
1311				printf("%s: original_sc == NULL!\n",
1312				    __func__);
1313				break;
1314			}
1315			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1316			io->io_hdr.msg_type = CTL_MSG_R2R;
1317			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1318			ctl_enqueue_isc(io);
1319			break;
1320
1321		/*
1322		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1323		 * mode.
1324		 * Performed on the Originating (i.e. secondary) SC in XFER
1325		 * mode
1326		 */
1327		case CTL_MSG_FINISH_IO:
1328			if (softc->ha_mode == CTL_HA_MODE_XFER)
1329				ctl_isc_handler_finish_xfer(softc, msg);
1330			else
1331				ctl_isc_handler_finish_ser_only(softc, msg);
1332			break;
1333
1334		/* Preformed on Originating SC */
1335		case CTL_MSG_BAD_JUJU:
1336			io = msg->hdr.original_sc;
1337			if (io == NULL) {
1338				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1339				       __func__);
1340				break;
1341			}
1342			ctl_copy_sense_data(msg, io);
1343			/*
1344			 * IO should have already been cleaned up on other
1345			 * SC so clear this flag so we won't send a message
1346			 * back to finish the IO there.
1347			 */
1348			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1349			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1350
1351			/* io = msg->hdr.serializing_sc; */
1352			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1353			ctl_enqueue_isc(io);
1354			break;
1355
1356		/* Handle resets sent from the other side */
1357		case CTL_MSG_MANAGE_TASKS: {
1358			struct ctl_taskio *taskio;
1359			taskio = (struct ctl_taskio *)ctl_alloc_io(
1360			    softc->othersc_pool);
1361			ctl_zero_io((union ctl_io *)taskio);
1362			taskio->io_hdr.io_type = CTL_IO_TASK;
1363			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1364			taskio->io_hdr.nexus = msg->hdr.nexus;
1365			taskio->task_action = msg->task.task_action;
1366			taskio->tag_num = msg->task.tag_num;
1367			taskio->tag_type = msg->task.tag_type;
1368#ifdef CTL_TIME_IO
1369			taskio->io_hdr.start_time = time_uptime;
1370			getbintime(&taskio->io_hdr.start_bt);
1371#endif /* CTL_TIME_IO */
1372			ctl_run_task((union ctl_io *)taskio);
1373			break;
1374		}
1375		/* Persistent Reserve action which needs attention */
1376		case CTL_MSG_PERS_ACTION:
1377			presio = (struct ctl_prio *)ctl_alloc_io(
1378			    softc->othersc_pool);
1379			ctl_zero_io((union ctl_io *)presio);
1380			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1381			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1382			presio->io_hdr.nexus = msg->hdr.nexus;
1383			presio->pr_msg = msg->pr;
1384			ctl_enqueue_isc((union ctl_io *)presio);
1385			break;
1386		case CTL_MSG_UA:
1387			ctl_isc_ua(softc, msg, param);
1388			break;
1389		case CTL_MSG_PORT_SYNC:
1390			ctl_isc_port_sync(softc, msg, param);
1391			break;
1392		case CTL_MSG_LUN_SYNC:
1393			ctl_isc_lun_sync(softc, msg, param);
1394			break;
1395		case CTL_MSG_IID_SYNC:
1396			ctl_isc_iid_sync(softc, msg, param);
1397			break;
1398		case CTL_MSG_LOGIN:
1399			ctl_isc_login(softc, msg, param);
1400			break;
1401		case CTL_MSG_MODE_SYNC:
1402			ctl_isc_mode_sync(softc, msg, param);
1403			break;
1404		default:
1405			printf("Received HA message of unknown type %d\n",
1406			    msg->hdr.msg_type);
1407			ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1408			break;
1409		}
1410		if (msg != &msgbuf)
1411			free(msg, M_CTL);
1412	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1413		printf("CTL: HA link status changed from %d to %d\n",
1414		    softc->ha_link, param);
1415		if (param == softc->ha_link)
1416			return;
1417		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1418			softc->ha_link = param;
1419			ctl_isc_ha_link_down(softc);
1420		} else {
1421			softc->ha_link = param;
1422			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1423				ctl_isc_ha_link_up(softc);
1424		}
1425		return;
1426	} else {
1427		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1428		return;
1429	}
1430}
1431
1432static void
1433ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1434{
1435
1436	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1437	    src->scsi.sense_len);
1438	dest->scsiio.scsi_status = src->scsi.scsi_status;
1439	dest->scsiio.sense_len = src->scsi.sense_len;
1440	dest->io_hdr.status = src->hdr.status;
1441}
1442
1443static void
1444ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1445{
1446
1447	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1448	    src->scsiio.sense_len);
1449	dest->scsi.scsi_status = src->scsiio.scsi_status;
1450	dest->scsi.sense_len = src->scsiio.sense_len;
1451	dest->hdr.status = src->io_hdr.status;
1452}
1453
1454void
1455ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1456{
1457	struct ctl_softc *softc = lun->ctl_softc;
1458	ctl_ua_type *pu;
1459
1460	if (initidx < softc->init_min || initidx >= softc->init_max)
1461		return;
1462	mtx_assert(&lun->lun_lock, MA_OWNED);
1463	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1464	if (pu == NULL)
1465		return;
1466	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1467}
1468
1469void
1470ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1471{
1472	int i;
1473
1474	mtx_assert(&lun->lun_lock, MA_OWNED);
1475	if (lun->pending_ua[port] == NULL)
1476		return;
1477	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1478		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1479			continue;
1480		lun->pending_ua[port][i] |= ua;
1481	}
1482}
1483
1484void
1485ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1486{
1487	struct ctl_softc *softc = lun->ctl_softc;
1488	int i;
1489
1490	mtx_assert(&lun->lun_lock, MA_OWNED);
1491	for (i = softc->port_min; i < softc->port_max; i++)
1492		ctl_est_ua_port(lun, i, except, ua);
1493}
1494
1495void
1496ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1497{
1498	struct ctl_softc *softc = lun->ctl_softc;
1499	ctl_ua_type *pu;
1500
1501	if (initidx < softc->init_min || initidx >= softc->init_max)
1502		return;
1503	mtx_assert(&lun->lun_lock, MA_OWNED);
1504	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1505	if (pu == NULL)
1506		return;
1507	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1508}
1509
1510void
1511ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1512{
1513	struct ctl_softc *softc = lun->ctl_softc;
1514	int i, j;
1515
1516	mtx_assert(&lun->lun_lock, MA_OWNED);
1517	for (i = softc->port_min; i < softc->port_max; i++) {
1518		if (lun->pending_ua[i] == NULL)
1519			continue;
1520		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1521			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1522				continue;
1523			lun->pending_ua[i][j] &= ~ua;
1524		}
1525	}
1526}
1527
1528void
1529ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1530    ctl_ua_type ua_type)
1531{
1532	struct ctl_lun *lun;
1533
1534	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1535	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1536		mtx_lock(&lun->lun_lock);
1537		ctl_clr_ua(lun, initidx, ua_type);
1538		mtx_unlock(&lun->lun_lock);
1539	}
1540}
1541
1542static int
1543ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1544{
1545	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1546	struct ctl_lun *lun;
1547	struct ctl_lun_req ireq;
1548	int error, value;
1549
1550	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1551	error = sysctl_handle_int(oidp, &value, 0, req);
1552	if ((error != 0) || (req->newptr == NULL))
1553		return (error);
1554
1555	mtx_lock(&softc->ctl_lock);
1556	if (value == 0)
1557		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1558	else
1559		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1560	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1561		mtx_unlock(&softc->ctl_lock);
1562		bzero(&ireq, sizeof(ireq));
1563		ireq.reqtype = CTL_LUNREQ_MODIFY;
1564		ireq.reqdata.modify.lun_id = lun->lun;
1565		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1566		    curthread);
1567		if (ireq.status != CTL_LUN_OK) {
1568			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1569			    __func__, ireq.status, ireq.error_str);
1570		}
1571		mtx_lock(&softc->ctl_lock);
1572	}
1573	mtx_unlock(&softc->ctl_lock);
1574	return (0);
1575}
1576
1577static int
1578ctl_init(void)
1579{
1580	struct ctl_softc *softc;
1581	void *other_pool;
1582	int i, error, retval;
1583
1584	retval = 0;
1585	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1586			       M_WAITOK | M_ZERO);
1587	softc = control_softc;
1588
1589	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1590			      "cam/ctl");
1591
1592	softc->dev->si_drv1 = softc;
1593
1594	sysctl_ctx_init(&softc->sysctl_ctx);
1595	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1596		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1597		CTLFLAG_RD, 0, "CAM Target Layer");
1598
1599	if (softc->sysctl_tree == NULL) {
1600		printf("%s: unable to allocate sysctl tree\n", __func__);
1601		destroy_dev(softc->dev);
1602		free(control_softc, M_DEVBUF);
1603		control_softc = NULL;
1604		return (ENOMEM);
1605	}
1606
1607	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1608	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1609	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1610	softc->open_count = 0;
1611
1612	/*
1613	 * Default to actually sending a SYNCHRONIZE CACHE command down to
1614	 * the drive.
1615	 */
1616	softc->flags = CTL_FLAG_REAL_SYNC;
1617
1618	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1619	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1620	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1621
1622	/*
1623	 * In Copan's HA scheme, the "master" and "slave" roles are
1624	 * figured out through the slot the controller is in.  Although it
1625	 * is an active/active system, someone has to be in charge.
1626	 */
1627	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1628	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1629	    "HA head ID (0 - no HA)");
1630	if (softc->ha_id == 0 || softc->ha_id > NUM_TARGET_PORT_GROUPS) {
1631		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1632		softc->is_single = 1;
1633		softc->port_cnt = CTL_MAX_PORTS;
1634		softc->port_min = 0;
1635	} else {
1636		softc->port_cnt = CTL_MAX_PORTS / NUM_TARGET_PORT_GROUPS;
1637		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1638	}
1639	softc->port_max = softc->port_min + softc->port_cnt;
1640	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1641	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1642
1643	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1644	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1645	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
1646
1647	STAILQ_INIT(&softc->lun_list);
1648	STAILQ_INIT(&softc->pending_lun_queue);
1649	STAILQ_INIT(&softc->fe_list);
1650	STAILQ_INIT(&softc->port_list);
1651	STAILQ_INIT(&softc->be_list);
1652	ctl_tpc_init(softc);
1653
1654	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1655	                    &other_pool) != 0)
1656	{
1657		printf("ctl: can't allocate %d entry other SC pool, "
1658		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1659		return (ENOMEM);
1660	}
1661	softc->othersc_pool = other_pool;
1662
1663	if (worker_threads <= 0)
1664		worker_threads = max(1, mp_ncpus / 4);
1665	if (worker_threads > CTL_MAX_THREADS)
1666		worker_threads = CTL_MAX_THREADS;
1667
1668	for (i = 0; i < worker_threads; i++) {
1669		struct ctl_thread *thr = &softc->threads[i];
1670
1671		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1672		thr->ctl_softc = softc;
1673		STAILQ_INIT(&thr->incoming_queue);
1674		STAILQ_INIT(&thr->rtr_queue);
1675		STAILQ_INIT(&thr->done_queue);
1676		STAILQ_INIT(&thr->isc_queue);
1677
1678		error = kproc_kthread_add(ctl_work_thread, thr,
1679		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1680		if (error != 0) {
1681			printf("error creating CTL work thread!\n");
1682			ctl_pool_free(other_pool);
1683			return (error);
1684		}
1685	}
1686	error = kproc_kthread_add(ctl_lun_thread, softc,
1687	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1688	if (error != 0) {
1689		printf("error creating CTL lun thread!\n");
1690		ctl_pool_free(other_pool);
1691		return (error);
1692	}
1693	error = kproc_kthread_add(ctl_thresh_thread, softc,
1694	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1695	if (error != 0) {
1696		printf("error creating CTL threshold thread!\n");
1697		ctl_pool_free(other_pool);
1698		return (error);
1699	}
1700
1701	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1702	    OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1703	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1704
1705	if (softc->is_single == 0) {
1706		ctl_frontend_register(&ha_frontend);
1707		if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
1708			printf("ctl_init: ctl_ha_msg_init failed.\n");
1709			softc->is_single = 1;
1710		} else
1711		if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
1712		    != CTL_HA_STATUS_SUCCESS) {
1713			printf("ctl_init: ctl_ha_msg_register failed.\n");
1714			softc->is_single = 1;
1715		}
1716	}
1717	return (0);
1718}
1719
1720void
1721ctl_shutdown(void)
1722{
1723	struct ctl_softc *softc;
1724	struct ctl_lun *lun, *next_lun;
1725
1726	softc = (struct ctl_softc *)control_softc;
1727
1728	if (softc->is_single == 0) {
1729		ctl_ha_msg_shutdown(softc);
1730		if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL)
1731		    != CTL_HA_STATUS_SUCCESS)
1732			printf("%s: ctl_ha_msg_deregister failed.\n", __func__);
1733		if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
1734			printf("%s: ctl_ha_msg_destroy failed.\n", __func__);
1735		ctl_frontend_deregister(&ha_frontend);
1736	}
1737
1738	mtx_lock(&softc->ctl_lock);
1739
1740	/*
1741	 * Free up each LUN.
1742	 */
1743	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1744		next_lun = STAILQ_NEXT(lun, links);
1745		ctl_free_lun(lun);
1746	}
1747
1748	mtx_unlock(&softc->ctl_lock);
1749
1750#if 0
1751	ctl_shutdown_thread(softc->work_thread);
1752	mtx_destroy(&softc->queue_lock);
1753#endif
1754
1755	ctl_tpc_shutdown(softc);
1756	uma_zdestroy(softc->io_zone);
1757	mtx_destroy(&softc->ctl_lock);
1758
1759	destroy_dev(softc->dev);
1760
1761	sysctl_ctx_free(&softc->sysctl_ctx);
1762
1763	free(control_softc, M_DEVBUF);
1764	control_softc = NULL;
1765}
1766
1767static int
1768ctl_module_event_handler(module_t mod, int what, void *arg)
1769{
1770
1771	switch (what) {
1772	case MOD_LOAD:
1773		return (ctl_init());
1774	case MOD_UNLOAD:
1775		return (EBUSY);
1776	default:
1777		return (EOPNOTSUPP);
1778	}
1779}
1780
1781/*
1782 * XXX KDM should we do some access checks here?  Bump a reference count to
1783 * prevent a CTL module from being unloaded while someone has it open?
1784 */
1785static int
1786ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1787{
1788	return (0);
1789}
1790
1791static int
1792ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1793{
1794	return (0);
1795}
1796
1797/*
1798 * Remove an initiator by port number and initiator ID.
1799 * Returns 0 for success, -1 for failure.
1800 */
1801int
1802ctl_remove_initiator(struct ctl_port *port, int iid)
1803{
1804	struct ctl_softc *softc = control_softc;
1805
1806	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1807
1808	if (iid > CTL_MAX_INIT_PER_PORT) {
1809		printf("%s: initiator ID %u > maximun %u!\n",
1810		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1811		return (-1);
1812	}
1813
1814	mtx_lock(&softc->ctl_lock);
1815	port->wwpn_iid[iid].in_use--;
1816	port->wwpn_iid[iid].last_use = time_uptime;
1817	mtx_unlock(&softc->ctl_lock);
1818	ctl_isc_announce_iid(port, iid);
1819
1820	return (0);
1821}
1822
1823/*
1824 * Add an initiator to the initiator map.
1825 * Returns iid for success, < 0 for failure.
1826 */
1827int
1828ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1829{
1830	struct ctl_softc *softc = control_softc;
1831	time_t best_time;
1832	int i, best;
1833
1834	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1835
1836	if (iid >= CTL_MAX_INIT_PER_PORT) {
1837		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1838		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1839		free(name, M_CTL);
1840		return (-1);
1841	}
1842
1843	mtx_lock(&softc->ctl_lock);
1844
1845	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1846		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1847			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1848				iid = i;
1849				break;
1850			}
1851			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1852			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1853				iid = i;
1854				break;
1855			}
1856		}
1857	}
1858
1859	if (iid < 0) {
1860		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1861			if (port->wwpn_iid[i].in_use == 0 &&
1862			    port->wwpn_iid[i].wwpn == 0 &&
1863			    port->wwpn_iid[i].name == NULL) {
1864				iid = i;
1865				break;
1866			}
1867		}
1868	}
1869
1870	if (iid < 0) {
1871		best = -1;
1872		best_time = INT32_MAX;
1873		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1874			if (port->wwpn_iid[i].in_use == 0) {
1875				if (port->wwpn_iid[i].last_use < best_time) {
1876					best = i;
1877					best_time = port->wwpn_iid[i].last_use;
1878				}
1879			}
1880		}
1881		iid = best;
1882	}
1883
1884	if (iid < 0) {
1885		mtx_unlock(&softc->ctl_lock);
1886		free(name, M_CTL);
1887		return (-2);
1888	}
1889
1890	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1891		/*
1892		 * This is not an error yet.
1893		 */
1894		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1895#if 0
1896			printf("%s: port %d iid %u WWPN %#jx arrived"
1897			    " again\n", __func__, port->targ_port,
1898			    iid, (uintmax_t)wwpn);
1899#endif
1900			goto take;
1901		}
1902		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1903		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1904#if 0
1905			printf("%s: port %d iid %u name '%s' arrived"
1906			    " again\n", __func__, port->targ_port,
1907			    iid, name);
1908#endif
1909			goto take;
1910		}
1911
1912		/*
1913		 * This is an error, but what do we do about it?  The
1914		 * driver is telling us we have a new WWPN for this
1915		 * initiator ID, so we pretty much need to use it.
1916		 */
1917		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1918		    " but WWPN %#jx '%s' is still at that address\n",
1919		    __func__, port->targ_port, iid, wwpn, name,
1920		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1921		    port->wwpn_iid[iid].name);
1922
1923		/*
1924		 * XXX KDM clear have_ca and ua_pending on each LUN for
1925		 * this initiator.
1926		 */
1927	}
1928take:
1929	free(port->wwpn_iid[iid].name, M_CTL);
1930	port->wwpn_iid[iid].name = name;
1931	port->wwpn_iid[iid].wwpn = wwpn;
1932	port->wwpn_iid[iid].in_use++;
1933	mtx_unlock(&softc->ctl_lock);
1934	ctl_isc_announce_iid(port, iid);
1935
1936	return (iid);
1937}
1938
1939static int
1940ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1941{
1942	int len;
1943
1944	switch (port->port_type) {
1945	case CTL_PORT_FC:
1946	{
1947		struct scsi_transportid_fcp *id =
1948		    (struct scsi_transportid_fcp *)buf;
1949		if (port->wwpn_iid[iid].wwpn == 0)
1950			return (0);
1951		memset(id, 0, sizeof(*id));
1952		id->format_protocol = SCSI_PROTO_FC;
1953		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1954		return (sizeof(*id));
1955	}
1956	case CTL_PORT_ISCSI:
1957	{
1958		struct scsi_transportid_iscsi_port *id =
1959		    (struct scsi_transportid_iscsi_port *)buf;
1960		if (port->wwpn_iid[iid].name == NULL)
1961			return (0);
1962		memset(id, 0, 256);
1963		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1964		    SCSI_PROTO_ISCSI;
1965		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1966		len = roundup2(min(len, 252), 4);
1967		scsi_ulto2b(len, id->additional_length);
1968		return (sizeof(*id) + len);
1969	}
1970	case CTL_PORT_SAS:
1971	{
1972		struct scsi_transportid_sas *id =
1973		    (struct scsi_transportid_sas *)buf;
1974		if (port->wwpn_iid[iid].wwpn == 0)
1975			return (0);
1976		memset(id, 0, sizeof(*id));
1977		id->format_protocol = SCSI_PROTO_SAS;
1978		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1979		return (sizeof(*id));
1980	}
1981	default:
1982	{
1983		struct scsi_transportid_spi *id =
1984		    (struct scsi_transportid_spi *)buf;
1985		memset(id, 0, sizeof(*id));
1986		id->format_protocol = SCSI_PROTO_SPI;
1987		scsi_ulto2b(iid, id->scsi_addr);
1988		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1989		return (sizeof(*id));
1990	}
1991	}
1992}
1993
1994/*
1995 * Serialize a command that went down the "wrong" side, and so was sent to
1996 * this controller for execution.  The logic is a little different than the
1997 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1998 * sent back to the other side, but in the success case, we execute the
1999 * command on this side (XFER mode) or tell the other side to execute it
2000 * (SER_ONLY mode).
2001 */
2002static int
2003ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2004{
2005	struct ctl_softc *softc;
2006	union ctl_ha_msg msg_info;
2007	struct ctl_lun *lun;
2008	const struct ctl_cmd_entry *entry;
2009	int retval = 0;
2010	uint32_t targ_lun;
2011
2012	softc = control_softc;
2013
2014	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2015	mtx_lock(&softc->ctl_lock);
2016	if ((targ_lun < CTL_MAX_LUNS) &&
2017	    ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
2018		mtx_lock(&lun->lun_lock);
2019		mtx_unlock(&softc->ctl_lock);
2020		/*
2021		 * If the LUN is invalid, pretend that it doesn't exist.
2022		 * It will go away as soon as all pending I/O has been
2023		 * completed.
2024		 */
2025		if (lun->flags & CTL_LUN_DISABLED) {
2026			mtx_unlock(&lun->lun_lock);
2027			lun = NULL;
2028		}
2029	} else {
2030		mtx_unlock(&softc->ctl_lock);
2031		lun = NULL;
2032	}
2033	if (lun == NULL) {
2034		/*
2035		 * The other node would not send this request to us unless
2036		 * received announce that we are primary node for this LUN.
2037		 * If this LUN does not exist now, it is probably result of
2038		 * a race, so respond to initiator in the most opaque way.
2039		 */
2040		ctl_set_busy(ctsio);
2041		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2042		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2043		msg_info.hdr.serializing_sc = NULL;
2044		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2045		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2046		    sizeof(msg_info.scsi), M_WAITOK);
2047		return(1);
2048	}
2049
2050	entry = ctl_get_cmd_entry(ctsio, NULL);
2051	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2052		mtx_unlock(&lun->lun_lock);
2053		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2054		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2055		msg_info.hdr.serializing_sc = NULL;
2056		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2057		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2058		    sizeof(msg_info.scsi), M_WAITOK);
2059		return(1);
2060	}
2061
2062	ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
2063	ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = lun->be_lun;
2064
2065	/*
2066	 * Every I/O goes into the OOA queue for a
2067	 * particular LUN, and stays there until completion.
2068	 */
2069#ifdef CTL_TIME_IO
2070	if (TAILQ_EMPTY(&lun->ooa_queue))
2071		lun->idle_time += getsbinuptime() - lun->last_busy;
2072#endif
2073	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2074
2075	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2076		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2077		 ooa_links))) {
2078	case CTL_ACTION_BLOCK:
2079		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2080		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2081				  blocked_links);
2082		mtx_unlock(&lun->lun_lock);
2083		break;
2084	case CTL_ACTION_PASS:
2085	case CTL_ACTION_SKIP:
2086		if (softc->ha_mode == CTL_HA_MODE_XFER) {
2087			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2088			ctl_enqueue_rtr((union ctl_io *)ctsio);
2089			mtx_unlock(&lun->lun_lock);
2090		} else {
2091			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2092			mtx_unlock(&lun->lun_lock);
2093
2094			/* send msg back to other side */
2095			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2096			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2097			msg_info.hdr.msg_type = CTL_MSG_R2R;
2098			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2099			    sizeof(msg_info.hdr), M_WAITOK);
2100		}
2101		break;
2102	case CTL_ACTION_OVERLAP:
2103		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2104		mtx_unlock(&lun->lun_lock);
2105		retval = 1;
2106
2107		ctl_set_overlapped_cmd(ctsio);
2108		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2109		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2110		msg_info.hdr.serializing_sc = NULL;
2111		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2112		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2113		    sizeof(msg_info.scsi), M_WAITOK);
2114		break;
2115	case CTL_ACTION_OVERLAP_TAG:
2116		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2117		mtx_unlock(&lun->lun_lock);
2118		retval = 1;
2119		ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2120		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2121		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2122		msg_info.hdr.serializing_sc = NULL;
2123		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2124		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2125		    sizeof(msg_info.scsi), M_WAITOK);
2126		break;
2127	case CTL_ACTION_ERROR:
2128	default:
2129		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2130		mtx_unlock(&lun->lun_lock);
2131		retval = 1;
2132
2133		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2134					 /*retry_count*/ 0);
2135		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2136		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2137		msg_info.hdr.serializing_sc = NULL;
2138		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2139		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2140		    sizeof(msg_info.scsi), M_WAITOK);
2141		break;
2142	}
2143	return (retval);
2144}
2145
2146/*
2147 * Returns 0 for success, errno for failure.
2148 */
2149static int
2150ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2151		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2152{
2153	union ctl_io *io;
2154	int retval;
2155
2156	retval = 0;
2157
2158	mtx_lock(&lun->lun_lock);
2159	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2160	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2161	     ooa_links)) {
2162		struct ctl_ooa_entry *entry;
2163
2164		/*
2165		 * If we've got more than we can fit, just count the
2166		 * remaining entries.
2167		 */
2168		if (*cur_fill_num >= ooa_hdr->alloc_num)
2169			continue;
2170
2171		entry = &kern_entries[*cur_fill_num];
2172
2173		entry->tag_num = io->scsiio.tag_num;
2174		entry->lun_num = lun->lun;
2175#ifdef CTL_TIME_IO
2176		entry->start_bt = io->io_hdr.start_bt;
2177#endif
2178		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2179		entry->cdb_len = io->scsiio.cdb_len;
2180		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2181			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2182
2183		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2184			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2185
2186		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2187			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2188
2189		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2190			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2191
2192		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2193			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2194	}
2195	mtx_unlock(&lun->lun_lock);
2196
2197	return (retval);
2198}
2199
2200static void *
2201ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2202		 size_t error_str_len)
2203{
2204	void *kptr;
2205
2206	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2207
2208	if (copyin(user_addr, kptr, len) != 0) {
2209		snprintf(error_str, error_str_len, "Error copying %d bytes "
2210			 "from user address %p to kernel address %p", len,
2211			 user_addr, kptr);
2212		free(kptr, M_CTL);
2213		return (NULL);
2214	}
2215
2216	return (kptr);
2217}
2218
2219static void
2220ctl_free_args(int num_args, struct ctl_be_arg *args)
2221{
2222	int i;
2223
2224	if (args == NULL)
2225		return;
2226
2227	for (i = 0; i < num_args; i++) {
2228		free(args[i].kname, M_CTL);
2229		free(args[i].kvalue, M_CTL);
2230	}
2231
2232	free(args, M_CTL);
2233}
2234
2235static struct ctl_be_arg *
2236ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2237		char *error_str, size_t error_str_len)
2238{
2239	struct ctl_be_arg *args;
2240	int i;
2241
2242	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2243				error_str, error_str_len);
2244
2245	if (args == NULL)
2246		goto bailout;
2247
2248	for (i = 0; i < num_args; i++) {
2249		args[i].kname = NULL;
2250		args[i].kvalue = NULL;
2251	}
2252
2253	for (i = 0; i < num_args; i++) {
2254		uint8_t *tmpptr;
2255
2256		args[i].kname = ctl_copyin_alloc(args[i].name,
2257			args[i].namelen, error_str, error_str_len);
2258		if (args[i].kname == NULL)
2259			goto bailout;
2260
2261		if (args[i].kname[args[i].namelen - 1] != '\0') {
2262			snprintf(error_str, error_str_len, "Argument %d "
2263				 "name is not NUL-terminated", i);
2264			goto bailout;
2265		}
2266
2267		if (args[i].flags & CTL_BEARG_RD) {
2268			tmpptr = ctl_copyin_alloc(args[i].value,
2269				args[i].vallen, error_str, error_str_len);
2270			if (tmpptr == NULL)
2271				goto bailout;
2272			if ((args[i].flags & CTL_BEARG_ASCII)
2273			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2274				snprintf(error_str, error_str_len, "Argument "
2275				    "%d value is not NUL-terminated", i);
2276				goto bailout;
2277			}
2278			args[i].kvalue = tmpptr;
2279		} else {
2280			args[i].kvalue = malloc(args[i].vallen,
2281			    M_CTL, M_WAITOK | M_ZERO);
2282		}
2283	}
2284
2285	return (args);
2286bailout:
2287
2288	ctl_free_args(num_args, args);
2289
2290	return (NULL);
2291}
2292
2293static void
2294ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2295{
2296	int i;
2297
2298	for (i = 0; i < num_args; i++) {
2299		if (args[i].flags & CTL_BEARG_WR)
2300			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2301	}
2302}
2303
2304/*
2305 * Escape characters that are illegal or not recommended in XML.
2306 */
2307int
2308ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2309{
2310	char *end = str + size;
2311	int retval;
2312
2313	retval = 0;
2314
2315	for (; *str && str < end; str++) {
2316		switch (*str) {
2317		case '&':
2318			retval = sbuf_printf(sb, "&amp;");
2319			break;
2320		case '>':
2321			retval = sbuf_printf(sb, "&gt;");
2322			break;
2323		case '<':
2324			retval = sbuf_printf(sb, "&lt;");
2325			break;
2326		default:
2327			retval = sbuf_putc(sb, *str);
2328			break;
2329		}
2330
2331		if (retval != 0)
2332			break;
2333
2334	}
2335
2336	return (retval);
2337}
2338
2339static void
2340ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2341{
2342	struct scsi_vpd_id_descriptor *desc;
2343	int i;
2344
2345	if (id == NULL || id->len < 4)
2346		return;
2347	desc = (struct scsi_vpd_id_descriptor *)id->data;
2348	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2349	case SVPD_ID_TYPE_T10:
2350		sbuf_printf(sb, "t10.");
2351		break;
2352	case SVPD_ID_TYPE_EUI64:
2353		sbuf_printf(sb, "eui.");
2354		break;
2355	case SVPD_ID_TYPE_NAA:
2356		sbuf_printf(sb, "naa.");
2357		break;
2358	case SVPD_ID_TYPE_SCSI_NAME:
2359		break;
2360	}
2361	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2362	case SVPD_ID_CODESET_BINARY:
2363		for (i = 0; i < desc->length; i++)
2364			sbuf_printf(sb, "%02x", desc->identifier[i]);
2365		break;
2366	case SVPD_ID_CODESET_ASCII:
2367		sbuf_printf(sb, "%.*s", (int)desc->length,
2368		    (char *)desc->identifier);
2369		break;
2370	case SVPD_ID_CODESET_UTF8:
2371		sbuf_printf(sb, "%s", (char *)desc->identifier);
2372		break;
2373	}
2374}
2375
2376static int
2377ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2378	  struct thread *td)
2379{
2380	struct ctl_softc *softc;
2381	struct ctl_lun *lun;
2382	int retval;
2383
2384	softc = control_softc;
2385
2386	retval = 0;
2387
2388	switch (cmd) {
2389	case CTL_IO:
2390		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2391		break;
2392	case CTL_ENABLE_PORT:
2393	case CTL_DISABLE_PORT:
2394	case CTL_SET_PORT_WWNS: {
2395		struct ctl_port *port;
2396		struct ctl_port_entry *entry;
2397
2398		entry = (struct ctl_port_entry *)addr;
2399
2400		mtx_lock(&softc->ctl_lock);
2401		STAILQ_FOREACH(port, &softc->port_list, links) {
2402			int action, done;
2403
2404			if (port->targ_port < softc->port_min ||
2405			    port->targ_port >= softc->port_max)
2406				continue;
2407
2408			action = 0;
2409			done = 0;
2410			if ((entry->port_type == CTL_PORT_NONE)
2411			 && (entry->targ_port == port->targ_port)) {
2412				/*
2413				 * If the user only wants to enable or
2414				 * disable or set WWNs on a specific port,
2415				 * do the operation and we're done.
2416				 */
2417				action = 1;
2418				done = 1;
2419			} else if (entry->port_type & port->port_type) {
2420				/*
2421				 * Compare the user's type mask with the
2422				 * particular frontend type to see if we
2423				 * have a match.
2424				 */
2425				action = 1;
2426				done = 0;
2427
2428				/*
2429				 * Make sure the user isn't trying to set
2430				 * WWNs on multiple ports at the same time.
2431				 */
2432				if (cmd == CTL_SET_PORT_WWNS) {
2433					printf("%s: Can't set WWNs on "
2434					       "multiple ports\n", __func__);
2435					retval = EINVAL;
2436					break;
2437				}
2438			}
2439			if (action == 0)
2440				continue;
2441
2442			/*
2443			 * XXX KDM we have to drop the lock here, because
2444			 * the online/offline operations can potentially
2445			 * block.  We need to reference count the frontends
2446			 * so they can't go away,
2447			 */
2448			if (cmd == CTL_ENABLE_PORT) {
2449				mtx_unlock(&softc->ctl_lock);
2450				ctl_port_online(port);
2451				mtx_lock(&softc->ctl_lock);
2452			} else if (cmd == CTL_DISABLE_PORT) {
2453				mtx_unlock(&softc->ctl_lock);
2454				ctl_port_offline(port);
2455				mtx_lock(&softc->ctl_lock);
2456			} else if (cmd == CTL_SET_PORT_WWNS) {
2457				ctl_port_set_wwns(port,
2458				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2459				    1 : 0, entry->wwnn,
2460				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2461				    1 : 0, entry->wwpn);
2462			}
2463			if (done != 0)
2464				break;
2465		}
2466		mtx_unlock(&softc->ctl_lock);
2467		break;
2468	}
2469	case CTL_GET_PORT_LIST: {
2470		struct ctl_port *port;
2471		struct ctl_port_list *list;
2472		int i;
2473
2474		list = (struct ctl_port_list *)addr;
2475
2476		if (list->alloc_len != (list->alloc_num *
2477		    sizeof(struct ctl_port_entry))) {
2478			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2479			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2480			       "%zu\n", __func__, list->alloc_len,
2481			       list->alloc_num, sizeof(struct ctl_port_entry));
2482			retval = EINVAL;
2483			break;
2484		}
2485		list->fill_len = 0;
2486		list->fill_num = 0;
2487		list->dropped_num = 0;
2488		i = 0;
2489		mtx_lock(&softc->ctl_lock);
2490		STAILQ_FOREACH(port, &softc->port_list, links) {
2491			struct ctl_port_entry entry, *list_entry;
2492
2493			if (list->fill_num >= list->alloc_num) {
2494				list->dropped_num++;
2495				continue;
2496			}
2497
2498			entry.port_type = port->port_type;
2499			strlcpy(entry.port_name, port->port_name,
2500				sizeof(entry.port_name));
2501			entry.targ_port = port->targ_port;
2502			entry.physical_port = port->physical_port;
2503			entry.virtual_port = port->virtual_port;
2504			entry.wwnn = port->wwnn;
2505			entry.wwpn = port->wwpn;
2506			if (port->status & CTL_PORT_STATUS_ONLINE)
2507				entry.online = 1;
2508			else
2509				entry.online = 0;
2510
2511			list_entry = &list->entries[i];
2512
2513			retval = copyout(&entry, list_entry, sizeof(entry));
2514			if (retval != 0) {
2515				printf("%s: CTL_GET_PORT_LIST: copyout "
2516				       "returned %d\n", __func__, retval);
2517				break;
2518			}
2519			i++;
2520			list->fill_num++;
2521			list->fill_len += sizeof(entry);
2522		}
2523		mtx_unlock(&softc->ctl_lock);
2524
2525		/*
2526		 * If this is non-zero, we had a copyout fault, so there's
2527		 * probably no point in attempting to set the status inside
2528		 * the structure.
2529		 */
2530		if (retval != 0)
2531			break;
2532
2533		if (list->dropped_num > 0)
2534			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2535		else
2536			list->status = CTL_PORT_LIST_OK;
2537		break;
2538	}
2539	case CTL_DUMP_OOA: {
2540		union ctl_io *io;
2541		char printbuf[128];
2542		struct sbuf sb;
2543
2544		mtx_lock(&softc->ctl_lock);
2545		printf("Dumping OOA queues:\n");
2546		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2547			mtx_lock(&lun->lun_lock);
2548			for (io = (union ctl_io *)TAILQ_FIRST(
2549			     &lun->ooa_queue); io != NULL;
2550			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2551			     ooa_links)) {
2552				sbuf_new(&sb, printbuf, sizeof(printbuf),
2553					 SBUF_FIXEDLEN);
2554				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2555					    (intmax_t)lun->lun,
2556					    io->scsiio.tag_num,
2557					    (io->io_hdr.flags &
2558					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2559					    (io->io_hdr.flags &
2560					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2561					    (io->io_hdr.flags &
2562					    CTL_FLAG_ABORT) ? " ABORT" : "",
2563			                    (io->io_hdr.flags &
2564		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2565				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2566				sbuf_finish(&sb);
2567				printf("%s\n", sbuf_data(&sb));
2568			}
2569			mtx_unlock(&lun->lun_lock);
2570		}
2571		printf("OOA queues dump done\n");
2572		mtx_unlock(&softc->ctl_lock);
2573		break;
2574	}
2575	case CTL_GET_OOA: {
2576		struct ctl_ooa *ooa_hdr;
2577		struct ctl_ooa_entry *entries;
2578		uint32_t cur_fill_num;
2579
2580		ooa_hdr = (struct ctl_ooa *)addr;
2581
2582		if ((ooa_hdr->alloc_len == 0)
2583		 || (ooa_hdr->alloc_num == 0)) {
2584			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2585			       "must be non-zero\n", __func__,
2586			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2587			retval = EINVAL;
2588			break;
2589		}
2590
2591		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2592		    sizeof(struct ctl_ooa_entry))) {
2593			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2594			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2595			       __func__, ooa_hdr->alloc_len,
2596			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2597			retval = EINVAL;
2598			break;
2599		}
2600
2601		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2602		if (entries == NULL) {
2603			printf("%s: could not allocate %d bytes for OOA "
2604			       "dump\n", __func__, ooa_hdr->alloc_len);
2605			retval = ENOMEM;
2606			break;
2607		}
2608
2609		mtx_lock(&softc->ctl_lock);
2610		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2611		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2612		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2613			mtx_unlock(&softc->ctl_lock);
2614			free(entries, M_CTL);
2615			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2616			       __func__, (uintmax_t)ooa_hdr->lun_num);
2617			retval = EINVAL;
2618			break;
2619		}
2620
2621		cur_fill_num = 0;
2622
2623		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2624			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2625				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2626					ooa_hdr, entries);
2627				if (retval != 0)
2628					break;
2629			}
2630			if (retval != 0) {
2631				mtx_unlock(&softc->ctl_lock);
2632				free(entries, M_CTL);
2633				break;
2634			}
2635		} else {
2636			lun = softc->ctl_luns[ooa_hdr->lun_num];
2637
2638			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2639						    entries);
2640		}
2641		mtx_unlock(&softc->ctl_lock);
2642
2643		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2644		ooa_hdr->fill_len = ooa_hdr->fill_num *
2645			sizeof(struct ctl_ooa_entry);
2646		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2647		if (retval != 0) {
2648			printf("%s: error copying out %d bytes for OOA dump\n",
2649			       __func__, ooa_hdr->fill_len);
2650		}
2651
2652		getbintime(&ooa_hdr->cur_bt);
2653
2654		if (cur_fill_num > ooa_hdr->alloc_num) {
2655			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2656			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2657		} else {
2658			ooa_hdr->dropped_num = 0;
2659			ooa_hdr->status = CTL_OOA_OK;
2660		}
2661
2662		free(entries, M_CTL);
2663		break;
2664	}
2665	case CTL_CHECK_OOA: {
2666		union ctl_io *io;
2667		struct ctl_ooa_info *ooa_info;
2668
2669
2670		ooa_info = (struct ctl_ooa_info *)addr;
2671
2672		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2673			ooa_info->status = CTL_OOA_INVALID_LUN;
2674			break;
2675		}
2676		mtx_lock(&softc->ctl_lock);
2677		lun = softc->ctl_luns[ooa_info->lun_id];
2678		if (lun == NULL) {
2679			mtx_unlock(&softc->ctl_lock);
2680			ooa_info->status = CTL_OOA_INVALID_LUN;
2681			break;
2682		}
2683		mtx_lock(&lun->lun_lock);
2684		mtx_unlock(&softc->ctl_lock);
2685		ooa_info->num_entries = 0;
2686		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2687		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2688		     &io->io_hdr, ooa_links)) {
2689			ooa_info->num_entries++;
2690		}
2691		mtx_unlock(&lun->lun_lock);
2692
2693		ooa_info->status = CTL_OOA_SUCCESS;
2694
2695		break;
2696	}
2697	case CTL_DELAY_IO: {
2698		struct ctl_io_delay_info *delay_info;
2699
2700		delay_info = (struct ctl_io_delay_info *)addr;
2701
2702#ifdef CTL_IO_DELAY
2703		mtx_lock(&softc->ctl_lock);
2704
2705		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2706		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2707			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2708		} else {
2709			lun = softc->ctl_luns[delay_info->lun_id];
2710			mtx_lock(&lun->lun_lock);
2711
2712			delay_info->status = CTL_DELAY_STATUS_OK;
2713
2714			switch (delay_info->delay_type) {
2715			case CTL_DELAY_TYPE_CONT:
2716				break;
2717			case CTL_DELAY_TYPE_ONESHOT:
2718				break;
2719			default:
2720				delay_info->status =
2721					CTL_DELAY_STATUS_INVALID_TYPE;
2722				break;
2723			}
2724
2725			switch (delay_info->delay_loc) {
2726			case CTL_DELAY_LOC_DATAMOVE:
2727				lun->delay_info.datamove_type =
2728					delay_info->delay_type;
2729				lun->delay_info.datamove_delay =
2730					delay_info->delay_secs;
2731				break;
2732			case CTL_DELAY_LOC_DONE:
2733				lun->delay_info.done_type =
2734					delay_info->delay_type;
2735				lun->delay_info.done_delay =
2736					delay_info->delay_secs;
2737				break;
2738			default:
2739				delay_info->status =
2740					CTL_DELAY_STATUS_INVALID_LOC;
2741				break;
2742			}
2743			mtx_unlock(&lun->lun_lock);
2744		}
2745
2746		mtx_unlock(&softc->ctl_lock);
2747#else
2748		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2749#endif /* CTL_IO_DELAY */
2750		break;
2751	}
2752	case CTL_REALSYNC_SET: {
2753		int *syncstate;
2754
2755		syncstate = (int *)addr;
2756
2757		mtx_lock(&softc->ctl_lock);
2758		switch (*syncstate) {
2759		case 0:
2760			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2761			break;
2762		case 1:
2763			softc->flags |= CTL_FLAG_REAL_SYNC;
2764			break;
2765		default:
2766			retval = EINVAL;
2767			break;
2768		}
2769		mtx_unlock(&softc->ctl_lock);
2770		break;
2771	}
2772	case CTL_REALSYNC_GET: {
2773		int *syncstate;
2774
2775		syncstate = (int*)addr;
2776
2777		mtx_lock(&softc->ctl_lock);
2778		if (softc->flags & CTL_FLAG_REAL_SYNC)
2779			*syncstate = 1;
2780		else
2781			*syncstate = 0;
2782		mtx_unlock(&softc->ctl_lock);
2783
2784		break;
2785	}
2786	case CTL_SETSYNC:
2787	case CTL_GETSYNC: {
2788		struct ctl_sync_info *sync_info;
2789
2790		sync_info = (struct ctl_sync_info *)addr;
2791
2792		mtx_lock(&softc->ctl_lock);
2793		lun = softc->ctl_luns[sync_info->lun_id];
2794		if (lun == NULL) {
2795			mtx_unlock(&softc->ctl_lock);
2796			sync_info->status = CTL_GS_SYNC_NO_LUN;
2797			break;
2798		}
2799		/*
2800		 * Get or set the sync interval.  We're not bounds checking
2801		 * in the set case, hopefully the user won't do something
2802		 * silly.
2803		 */
2804		mtx_lock(&lun->lun_lock);
2805		mtx_unlock(&softc->ctl_lock);
2806		if (cmd == CTL_GETSYNC)
2807			sync_info->sync_interval = lun->sync_interval;
2808		else
2809			lun->sync_interval = sync_info->sync_interval;
2810		mtx_unlock(&lun->lun_lock);
2811
2812		sync_info->status = CTL_GS_SYNC_OK;
2813
2814		break;
2815	}
2816	case CTL_GETSTATS: {
2817		struct ctl_stats *stats;
2818		int i;
2819
2820		stats = (struct ctl_stats *)addr;
2821
2822		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2823		     stats->alloc_len) {
2824			stats->status = CTL_SS_NEED_MORE_SPACE;
2825			stats->num_luns = softc->num_luns;
2826			break;
2827		}
2828		/*
2829		 * XXX KDM no locking here.  If the LUN list changes,
2830		 * things can blow up.
2831		 */
2832		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2833		     i++, lun = STAILQ_NEXT(lun, links)) {
2834			retval = copyout(&lun->stats, &stats->lun_stats[i],
2835					 sizeof(lun->stats));
2836			if (retval != 0)
2837				break;
2838		}
2839		stats->num_luns = softc->num_luns;
2840		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2841				 softc->num_luns;
2842		stats->status = CTL_SS_OK;
2843#ifdef CTL_TIME_IO
2844		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2845#else
2846		stats->flags = CTL_STATS_FLAG_NONE;
2847#endif
2848		getnanouptime(&stats->timestamp);
2849		break;
2850	}
2851	case CTL_ERROR_INJECT: {
2852		struct ctl_error_desc *err_desc, *new_err_desc;
2853
2854		err_desc = (struct ctl_error_desc *)addr;
2855
2856		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2857				      M_WAITOK | M_ZERO);
2858		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2859
2860		mtx_lock(&softc->ctl_lock);
2861		lun = softc->ctl_luns[err_desc->lun_id];
2862		if (lun == NULL) {
2863			mtx_unlock(&softc->ctl_lock);
2864			free(new_err_desc, M_CTL);
2865			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2866			       __func__, (uintmax_t)err_desc->lun_id);
2867			retval = EINVAL;
2868			break;
2869		}
2870		mtx_lock(&lun->lun_lock);
2871		mtx_unlock(&softc->ctl_lock);
2872
2873		/*
2874		 * We could do some checking here to verify the validity
2875		 * of the request, but given the complexity of error
2876		 * injection requests, the checking logic would be fairly
2877		 * complex.
2878		 *
2879		 * For now, if the request is invalid, it just won't get
2880		 * executed and might get deleted.
2881		 */
2882		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2883
2884		/*
2885		 * XXX KDM check to make sure the serial number is unique,
2886		 * in case we somehow manage to wrap.  That shouldn't
2887		 * happen for a very long time, but it's the right thing to
2888		 * do.
2889		 */
2890		new_err_desc->serial = lun->error_serial;
2891		err_desc->serial = lun->error_serial;
2892		lun->error_serial++;
2893
2894		mtx_unlock(&lun->lun_lock);
2895		break;
2896	}
2897	case CTL_ERROR_INJECT_DELETE: {
2898		struct ctl_error_desc *delete_desc, *desc, *desc2;
2899		int delete_done;
2900
2901		delete_desc = (struct ctl_error_desc *)addr;
2902		delete_done = 0;
2903
2904		mtx_lock(&softc->ctl_lock);
2905		lun = softc->ctl_luns[delete_desc->lun_id];
2906		if (lun == NULL) {
2907			mtx_unlock(&softc->ctl_lock);
2908			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2909			       __func__, (uintmax_t)delete_desc->lun_id);
2910			retval = EINVAL;
2911			break;
2912		}
2913		mtx_lock(&lun->lun_lock);
2914		mtx_unlock(&softc->ctl_lock);
2915		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2916			if (desc->serial != delete_desc->serial)
2917				continue;
2918
2919			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2920				      links);
2921			free(desc, M_CTL);
2922			delete_done = 1;
2923		}
2924		mtx_unlock(&lun->lun_lock);
2925		if (delete_done == 0) {
2926			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2927			       "error serial %ju on LUN %u\n", __func__,
2928			       delete_desc->serial, delete_desc->lun_id);
2929			retval = EINVAL;
2930			break;
2931		}
2932		break;
2933	}
2934	case CTL_DUMP_STRUCTS: {
2935		int i, j, k;
2936		struct ctl_port *port;
2937		struct ctl_frontend *fe;
2938
2939		mtx_lock(&softc->ctl_lock);
2940		printf("CTL Persistent Reservation information start:\n");
2941		for (i = 0; i < CTL_MAX_LUNS; i++) {
2942			lun = softc->ctl_luns[i];
2943
2944			if ((lun == NULL)
2945			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
2946				continue;
2947
2948			for (j = 0; j < CTL_MAX_PORTS; j++) {
2949				if (lun->pr_keys[j] == NULL)
2950					continue;
2951				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2952					if (lun->pr_keys[j][k] == 0)
2953						continue;
2954					printf("  LUN %d port %d iid %d key "
2955					       "%#jx\n", i, j, k,
2956					       (uintmax_t)lun->pr_keys[j][k]);
2957				}
2958			}
2959		}
2960		printf("CTL Persistent Reservation information end\n");
2961		printf("CTL Ports:\n");
2962		STAILQ_FOREACH(port, &softc->port_list, links) {
2963			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2964			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2965			       port->frontend->name, port->port_type,
2966			       port->physical_port, port->virtual_port,
2967			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2968			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2969				if (port->wwpn_iid[j].in_use == 0 &&
2970				    port->wwpn_iid[j].wwpn == 0 &&
2971				    port->wwpn_iid[j].name == NULL)
2972					continue;
2973
2974				printf("    iid %u use %d WWPN %#jx '%s'\n",
2975				    j, port->wwpn_iid[j].in_use,
2976				    (uintmax_t)port->wwpn_iid[j].wwpn,
2977				    port->wwpn_iid[j].name);
2978			}
2979		}
2980		printf("CTL Port information end\n");
2981		mtx_unlock(&softc->ctl_lock);
2982		/*
2983		 * XXX KDM calling this without a lock.  We'd likely want
2984		 * to drop the lock before calling the frontend's dump
2985		 * routine anyway.
2986		 */
2987		printf("CTL Frontends:\n");
2988		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2989			printf("  Frontend '%s'\n", fe->name);
2990			if (fe->fe_dump != NULL)
2991				fe->fe_dump();
2992		}
2993		printf("CTL Frontend information end\n");
2994		break;
2995	}
2996	case CTL_LUN_REQ: {
2997		struct ctl_lun_req *lun_req;
2998		struct ctl_backend_driver *backend;
2999
3000		lun_req = (struct ctl_lun_req *)addr;
3001
3002		backend = ctl_backend_find(lun_req->backend);
3003		if (backend == NULL) {
3004			lun_req->status = CTL_LUN_ERROR;
3005			snprintf(lun_req->error_str,
3006				 sizeof(lun_req->error_str),
3007				 "Backend \"%s\" not found.",
3008				 lun_req->backend);
3009			break;
3010		}
3011		if (lun_req->num_be_args > 0) {
3012			lun_req->kern_be_args = ctl_copyin_args(
3013				lun_req->num_be_args,
3014				lun_req->be_args,
3015				lun_req->error_str,
3016				sizeof(lun_req->error_str));
3017			if (lun_req->kern_be_args == NULL) {
3018				lun_req->status = CTL_LUN_ERROR;
3019				break;
3020			}
3021		}
3022
3023		retval = backend->ioctl(dev, cmd, addr, flag, td);
3024
3025		if (lun_req->num_be_args > 0) {
3026			ctl_copyout_args(lun_req->num_be_args,
3027				      lun_req->kern_be_args);
3028			ctl_free_args(lun_req->num_be_args,
3029				      lun_req->kern_be_args);
3030		}
3031		break;
3032	}
3033	case CTL_LUN_LIST: {
3034		struct sbuf *sb;
3035		struct ctl_lun_list *list;
3036		struct ctl_option *opt;
3037
3038		list = (struct ctl_lun_list *)addr;
3039
3040		/*
3041		 * Allocate a fixed length sbuf here, based on the length
3042		 * of the user's buffer.  We could allocate an auto-extending
3043		 * buffer, and then tell the user how much larger our
3044		 * amount of data is than his buffer, but that presents
3045		 * some problems:
3046		 *
3047		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3048		 *     we can't hold a lock while calling them with an
3049		 *     auto-extending buffer.
3050 		 *
3051		 * 2.  There is not currently a LUN reference counting
3052		 *     mechanism, outside of outstanding transactions on
3053		 *     the LUN's OOA queue.  So a LUN could go away on us
3054		 *     while we're getting the LUN number, backend-specific
3055		 *     information, etc.  Thus, given the way things
3056		 *     currently work, we need to hold the CTL lock while
3057		 *     grabbing LUN information.
3058		 *
3059		 * So, from the user's standpoint, the best thing to do is
3060		 * allocate what he thinks is a reasonable buffer length,
3061		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3062		 * double the buffer length and try again.  (And repeat
3063		 * that until he succeeds.)
3064		 */
3065		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3066		if (sb == NULL) {
3067			list->status = CTL_LUN_LIST_ERROR;
3068			snprintf(list->error_str, sizeof(list->error_str),
3069				 "Unable to allocate %d bytes for LUN list",
3070				 list->alloc_len);
3071			break;
3072		}
3073
3074		sbuf_printf(sb, "<ctllunlist>\n");
3075
3076		mtx_lock(&softc->ctl_lock);
3077		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3078			mtx_lock(&lun->lun_lock);
3079			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3080					     (uintmax_t)lun->lun);
3081
3082			/*
3083			 * Bail out as soon as we see that we've overfilled
3084			 * the buffer.
3085			 */
3086			if (retval != 0)
3087				break;
3088
3089			retval = sbuf_printf(sb, "\t<backend_type>%s"
3090					     "</backend_type>\n",
3091					     (lun->backend == NULL) ?  "none" :
3092					     lun->backend->name);
3093
3094			if (retval != 0)
3095				break;
3096
3097			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3098					     lun->be_lun->lun_type);
3099
3100			if (retval != 0)
3101				break;
3102
3103			if (lun->backend == NULL) {
3104				retval = sbuf_printf(sb, "</lun>\n");
3105				if (retval != 0)
3106					break;
3107				continue;
3108			}
3109
3110			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3111					     (lun->be_lun->maxlba > 0) ?
3112					     lun->be_lun->maxlba + 1 : 0);
3113
3114			if (retval != 0)
3115				break;
3116
3117			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3118					     lun->be_lun->blocksize);
3119
3120			if (retval != 0)
3121				break;
3122
3123			retval = sbuf_printf(sb, "\t<serial_number>");
3124
3125			if (retval != 0)
3126				break;
3127
3128			retval = ctl_sbuf_printf_esc(sb,
3129			    lun->be_lun->serial_num,
3130			    sizeof(lun->be_lun->serial_num));
3131
3132			if (retval != 0)
3133				break;
3134
3135			retval = sbuf_printf(sb, "</serial_number>\n");
3136
3137			if (retval != 0)
3138				break;
3139
3140			retval = sbuf_printf(sb, "\t<device_id>");
3141
3142			if (retval != 0)
3143				break;
3144
3145			retval = ctl_sbuf_printf_esc(sb,
3146			    lun->be_lun->device_id,
3147			    sizeof(lun->be_lun->device_id));
3148
3149			if (retval != 0)
3150				break;
3151
3152			retval = sbuf_printf(sb, "</device_id>\n");
3153
3154			if (retval != 0)
3155				break;
3156
3157			if (lun->backend->lun_info != NULL) {
3158				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3159				if (retval != 0)
3160					break;
3161			}
3162			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3163				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3164				    opt->name, opt->value, opt->name);
3165				if (retval != 0)
3166					break;
3167			}
3168
3169			retval = sbuf_printf(sb, "</lun>\n");
3170
3171			if (retval != 0)
3172				break;
3173			mtx_unlock(&lun->lun_lock);
3174		}
3175		if (lun != NULL)
3176			mtx_unlock(&lun->lun_lock);
3177		mtx_unlock(&softc->ctl_lock);
3178
3179		if ((retval != 0)
3180		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3181			retval = 0;
3182			sbuf_delete(sb);
3183			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3184			snprintf(list->error_str, sizeof(list->error_str),
3185				 "Out of space, %d bytes is too small",
3186				 list->alloc_len);
3187			break;
3188		}
3189
3190		sbuf_finish(sb);
3191
3192		retval = copyout(sbuf_data(sb), list->lun_xml,
3193				 sbuf_len(sb) + 1);
3194
3195		list->fill_len = sbuf_len(sb) + 1;
3196		list->status = CTL_LUN_LIST_OK;
3197		sbuf_delete(sb);
3198		break;
3199	}
3200	case CTL_ISCSI: {
3201		struct ctl_iscsi *ci;
3202		struct ctl_frontend *fe;
3203
3204		ci = (struct ctl_iscsi *)addr;
3205
3206		fe = ctl_frontend_find("iscsi");
3207		if (fe == NULL) {
3208			ci->status = CTL_ISCSI_ERROR;
3209			snprintf(ci->error_str, sizeof(ci->error_str),
3210			    "Frontend \"iscsi\" not found.");
3211			break;
3212		}
3213
3214		retval = fe->ioctl(dev, cmd, addr, flag, td);
3215		break;
3216	}
3217	case CTL_PORT_REQ: {
3218		struct ctl_req *req;
3219		struct ctl_frontend *fe;
3220
3221		req = (struct ctl_req *)addr;
3222
3223		fe = ctl_frontend_find(req->driver);
3224		if (fe == NULL) {
3225			req->status = CTL_LUN_ERROR;
3226			snprintf(req->error_str, sizeof(req->error_str),
3227			    "Frontend \"%s\" not found.", req->driver);
3228			break;
3229		}
3230		if (req->num_args > 0) {
3231			req->kern_args = ctl_copyin_args(req->num_args,
3232			    req->args, req->error_str, sizeof(req->error_str));
3233			if (req->kern_args == NULL) {
3234				req->status = CTL_LUN_ERROR;
3235				break;
3236			}
3237		}
3238
3239		if (fe->ioctl)
3240			retval = fe->ioctl(dev, cmd, addr, flag, td);
3241		else
3242			retval = ENODEV;
3243
3244		if (req->num_args > 0) {
3245			ctl_copyout_args(req->num_args, req->kern_args);
3246			ctl_free_args(req->num_args, req->kern_args);
3247		}
3248		break;
3249	}
3250	case CTL_PORT_LIST: {
3251		struct sbuf *sb;
3252		struct ctl_port *port;
3253		struct ctl_lun_list *list;
3254		struct ctl_option *opt;
3255		int j;
3256		uint32_t plun;
3257
3258		list = (struct ctl_lun_list *)addr;
3259
3260		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3261		if (sb == NULL) {
3262			list->status = CTL_LUN_LIST_ERROR;
3263			snprintf(list->error_str, sizeof(list->error_str),
3264				 "Unable to allocate %d bytes for LUN list",
3265				 list->alloc_len);
3266			break;
3267		}
3268
3269		sbuf_printf(sb, "<ctlportlist>\n");
3270
3271		mtx_lock(&softc->ctl_lock);
3272		STAILQ_FOREACH(port, &softc->port_list, links) {
3273			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3274					     (uintmax_t)port->targ_port);
3275
3276			/*
3277			 * Bail out as soon as we see that we've overfilled
3278			 * the buffer.
3279			 */
3280			if (retval != 0)
3281				break;
3282
3283			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3284			    "</frontend_type>\n", port->frontend->name);
3285			if (retval != 0)
3286				break;
3287
3288			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3289					     port->port_type);
3290			if (retval != 0)
3291				break;
3292
3293			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3294			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3295			if (retval != 0)
3296				break;
3297
3298			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3299			    port->port_name);
3300			if (retval != 0)
3301				break;
3302
3303			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3304			    port->physical_port);
3305			if (retval != 0)
3306				break;
3307
3308			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3309			    port->virtual_port);
3310			if (retval != 0)
3311				break;
3312
3313			if (port->target_devid != NULL) {
3314				sbuf_printf(sb, "\t<target>");
3315				ctl_id_sbuf(port->target_devid, sb);
3316				sbuf_printf(sb, "</target>\n");
3317			}
3318
3319			if (port->port_devid != NULL) {
3320				sbuf_printf(sb, "\t<port>");
3321				ctl_id_sbuf(port->port_devid, sb);
3322				sbuf_printf(sb, "</port>\n");
3323			}
3324
3325			if (port->port_info != NULL) {
3326				retval = port->port_info(port->onoff_arg, sb);
3327				if (retval != 0)
3328					break;
3329			}
3330			STAILQ_FOREACH(opt, &port->options, links) {
3331				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3332				    opt->name, opt->value, opt->name);
3333				if (retval != 0)
3334					break;
3335			}
3336
3337			if (port->lun_map != NULL) {
3338				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3339				for (j = 0; j < CTL_MAX_LUNS; j++) {
3340					plun = ctl_lun_map_from_port(port, j);
3341					if (plun >= CTL_MAX_LUNS)
3342						continue;
3343					sbuf_printf(sb,
3344					    "\t<lun id=\"%u\">%u</lun>\n",
3345					    j, plun);
3346				}
3347			}
3348
3349			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3350				if (port->wwpn_iid[j].in_use == 0 ||
3351				    (port->wwpn_iid[j].wwpn == 0 &&
3352				     port->wwpn_iid[j].name == NULL))
3353					continue;
3354
3355				if (port->wwpn_iid[j].name != NULL)
3356					retval = sbuf_printf(sb,
3357					    "\t<initiator id=\"%u\">%s</initiator>\n",
3358					    j, port->wwpn_iid[j].name);
3359				else
3360					retval = sbuf_printf(sb,
3361					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3362					    j, port->wwpn_iid[j].wwpn);
3363				if (retval != 0)
3364					break;
3365			}
3366			if (retval != 0)
3367				break;
3368
3369			retval = sbuf_printf(sb, "</targ_port>\n");
3370			if (retval != 0)
3371				break;
3372		}
3373		mtx_unlock(&softc->ctl_lock);
3374
3375		if ((retval != 0)
3376		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3377			retval = 0;
3378			sbuf_delete(sb);
3379			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3380			snprintf(list->error_str, sizeof(list->error_str),
3381				 "Out of space, %d bytes is too small",
3382				 list->alloc_len);
3383			break;
3384		}
3385
3386		sbuf_finish(sb);
3387
3388		retval = copyout(sbuf_data(sb), list->lun_xml,
3389				 sbuf_len(sb) + 1);
3390
3391		list->fill_len = sbuf_len(sb) + 1;
3392		list->status = CTL_LUN_LIST_OK;
3393		sbuf_delete(sb);
3394		break;
3395	}
3396	case CTL_LUN_MAP: {
3397		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3398		struct ctl_port *port;
3399
3400		mtx_lock(&softc->ctl_lock);
3401		if (lm->port < softc->port_min ||
3402		    lm->port >= softc->port_max ||
3403		    (port = softc->ctl_ports[lm->port]) == NULL) {
3404			mtx_unlock(&softc->ctl_lock);
3405			return (ENXIO);
3406		}
3407		if (port->status & CTL_PORT_STATUS_ONLINE) {
3408			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3409				if (ctl_lun_map_to_port(port, lun->lun) >=
3410				    CTL_MAX_LUNS)
3411					continue;
3412				mtx_lock(&lun->lun_lock);
3413				ctl_est_ua_port(lun, lm->port, -1,
3414				    CTL_UA_LUN_CHANGE);
3415				mtx_unlock(&lun->lun_lock);
3416			}
3417		}
3418		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3419		if (lm->plun < CTL_MAX_LUNS) {
3420			if (lm->lun == UINT32_MAX)
3421				retval = ctl_lun_map_unset(port, lm->plun);
3422			else if (lm->lun < CTL_MAX_LUNS &&
3423			    softc->ctl_luns[lm->lun] != NULL)
3424				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3425			else
3426				return (ENXIO);
3427		} else if (lm->plun == UINT32_MAX) {
3428			if (lm->lun == UINT32_MAX)
3429				retval = ctl_lun_map_deinit(port);
3430			else
3431				retval = ctl_lun_map_init(port);
3432		} else
3433			return (ENXIO);
3434		if (port->status & CTL_PORT_STATUS_ONLINE)
3435			ctl_isc_announce_port(port);
3436		break;
3437	}
3438	default: {
3439		/* XXX KDM should we fix this? */
3440#if 0
3441		struct ctl_backend_driver *backend;
3442		unsigned int type;
3443		int found;
3444
3445		found = 0;
3446
3447		/*
3448		 * We encode the backend type as the ioctl type for backend
3449		 * ioctls.  So parse it out here, and then search for a
3450		 * backend of this type.
3451		 */
3452		type = _IOC_TYPE(cmd);
3453
3454		STAILQ_FOREACH(backend, &softc->be_list, links) {
3455			if (backend->type == type) {
3456				found = 1;
3457				break;
3458			}
3459		}
3460		if (found == 0) {
3461			printf("ctl: unknown ioctl command %#lx or backend "
3462			       "%d\n", cmd, type);
3463			retval = EINVAL;
3464			break;
3465		}
3466		retval = backend->ioctl(dev, cmd, addr, flag, td);
3467#endif
3468		retval = ENOTTY;
3469		break;
3470	}
3471	}
3472	return (retval);
3473}
3474
3475uint32_t
3476ctl_get_initindex(struct ctl_nexus *nexus)
3477{
3478	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3479}
3480
3481int
3482ctl_lun_map_init(struct ctl_port *port)
3483{
3484	struct ctl_softc *softc = control_softc;
3485	struct ctl_lun *lun;
3486	uint32_t i;
3487
3488	if (port->lun_map == NULL)
3489		port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3490		    M_CTL, M_NOWAIT);
3491	if (port->lun_map == NULL)
3492		return (ENOMEM);
3493	for (i = 0; i < CTL_MAX_LUNS; i++)
3494		port->lun_map[i] = UINT32_MAX;
3495	if (port->status & CTL_PORT_STATUS_ONLINE) {
3496		if (port->lun_disable != NULL) {
3497			STAILQ_FOREACH(lun, &softc->lun_list, links)
3498				port->lun_disable(port->targ_lun_arg, lun->lun);
3499		}
3500		ctl_isc_announce_port(port);
3501	}
3502	return (0);
3503}
3504
3505int
3506ctl_lun_map_deinit(struct ctl_port *port)
3507{
3508	struct ctl_softc *softc = control_softc;
3509	struct ctl_lun *lun;
3510
3511	if (port->lun_map == NULL)
3512		return (0);
3513	free(port->lun_map, M_CTL);
3514	port->lun_map = NULL;
3515	if (port->status & CTL_PORT_STATUS_ONLINE) {
3516		if (port->lun_enable != NULL) {
3517			STAILQ_FOREACH(lun, &softc->lun_list, links)
3518				port->lun_enable(port->targ_lun_arg, lun->lun);
3519		}
3520		ctl_isc_announce_port(port);
3521	}
3522	return (0);
3523}
3524
3525int
3526ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3527{
3528	int status;
3529	uint32_t old;
3530
3531	if (port->lun_map == NULL) {
3532		status = ctl_lun_map_init(port);
3533		if (status != 0)
3534			return (status);
3535	}
3536	old = port->lun_map[plun];
3537	port->lun_map[plun] = glun;
3538	if ((port->status & CTL_PORT_STATUS_ONLINE) && old >= CTL_MAX_LUNS) {
3539		if (port->lun_enable != NULL)
3540			port->lun_enable(port->targ_lun_arg, plun);
3541		ctl_isc_announce_port(port);
3542	}
3543	return (0);
3544}
3545
3546int
3547ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3548{
3549	uint32_t old;
3550
3551	if (port->lun_map == NULL)
3552		return (0);
3553	old = port->lun_map[plun];
3554	port->lun_map[plun] = UINT32_MAX;
3555	if ((port->status & CTL_PORT_STATUS_ONLINE) && old < CTL_MAX_LUNS) {
3556		if (port->lun_disable != NULL)
3557			port->lun_disable(port->targ_lun_arg, plun);
3558		ctl_isc_announce_port(port);
3559	}
3560	return (0);
3561}
3562
3563uint32_t
3564ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3565{
3566
3567	if (port == NULL)
3568		return (UINT32_MAX);
3569	if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3570		return (lun_id);
3571	return (port->lun_map[lun_id]);
3572}
3573
3574uint32_t
3575ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3576{
3577	uint32_t i;
3578
3579	if (port == NULL)
3580		return (UINT32_MAX);
3581	if (port->lun_map == NULL)
3582		return (lun_id);
3583	for (i = 0; i < CTL_MAX_LUNS; i++) {
3584		if (port->lun_map[i] == lun_id)
3585			return (i);
3586	}
3587	return (UINT32_MAX);
3588}
3589
3590static struct ctl_port *
3591ctl_io_port(struct ctl_io_hdr *io_hdr)
3592{
3593
3594	return (control_softc->ctl_ports[io_hdr->nexus.targ_port]);
3595}
3596
3597int
3598ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3599{
3600	int i;
3601
3602	for (i = first; i < last; i++) {
3603		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3604			return (i);
3605	}
3606	return (-1);
3607}
3608
3609int
3610ctl_set_mask(uint32_t *mask, uint32_t bit)
3611{
3612	uint32_t chunk, piece;
3613
3614	chunk = bit >> 5;
3615	piece = bit % (sizeof(uint32_t) * 8);
3616
3617	if ((mask[chunk] & (1 << piece)) != 0)
3618		return (-1);
3619	else
3620		mask[chunk] |= (1 << piece);
3621
3622	return (0);
3623}
3624
3625int
3626ctl_clear_mask(uint32_t *mask, uint32_t bit)
3627{
3628	uint32_t chunk, piece;
3629
3630	chunk = bit >> 5;
3631	piece = bit % (sizeof(uint32_t) * 8);
3632
3633	if ((mask[chunk] & (1 << piece)) == 0)
3634		return (-1);
3635	else
3636		mask[chunk] &= ~(1 << piece);
3637
3638	return (0);
3639}
3640
3641int
3642ctl_is_set(uint32_t *mask, uint32_t bit)
3643{
3644	uint32_t chunk, piece;
3645
3646	chunk = bit >> 5;
3647	piece = bit % (sizeof(uint32_t) * 8);
3648
3649	if ((mask[chunk] & (1 << piece)) == 0)
3650		return (0);
3651	else
3652		return (1);
3653}
3654
3655static uint64_t
3656ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3657{
3658	uint64_t *t;
3659
3660	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3661	if (t == NULL)
3662		return (0);
3663	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3664}
3665
3666static void
3667ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3668{
3669	uint64_t *t;
3670
3671	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3672	if (t == NULL)
3673		return;
3674	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3675}
3676
3677static void
3678ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3679{
3680	uint64_t *p;
3681	u_int i;
3682
3683	i = residx/CTL_MAX_INIT_PER_PORT;
3684	if (lun->pr_keys[i] != NULL)
3685		return;
3686	mtx_unlock(&lun->lun_lock);
3687	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3688	    M_WAITOK | M_ZERO);
3689	mtx_lock(&lun->lun_lock);
3690	if (lun->pr_keys[i] == NULL)
3691		lun->pr_keys[i] = p;
3692	else
3693		free(p, M_CTL);
3694}
3695
3696static void
3697ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3698{
3699	uint64_t *t;
3700
3701	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3702	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3703	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3704}
3705
3706/*
3707 * ctl_softc, pool_name, total_ctl_io are passed in.
3708 * npool is passed out.
3709 */
3710int
3711ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3712		uint32_t total_ctl_io, void **npool)
3713{
3714#ifdef IO_POOLS
3715	struct ctl_io_pool *pool;
3716
3717	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3718					    M_NOWAIT | M_ZERO);
3719	if (pool == NULL)
3720		return (ENOMEM);
3721
3722	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3723	pool->ctl_softc = ctl_softc;
3724	pool->zone = uma_zsecond_create(pool->name, NULL,
3725	    NULL, NULL, NULL, ctl_softc->io_zone);
3726	/* uma_prealloc(pool->zone, total_ctl_io); */
3727
3728	*npool = pool;
3729#else
3730	*npool = ctl_softc->io_zone;
3731#endif
3732	return (0);
3733}
3734
3735void
3736ctl_pool_free(struct ctl_io_pool *pool)
3737{
3738
3739	if (pool == NULL)
3740		return;
3741
3742#ifdef IO_POOLS
3743	uma_zdestroy(pool->zone);
3744	free(pool, M_CTL);
3745#endif
3746}
3747
3748union ctl_io *
3749ctl_alloc_io(void *pool_ref)
3750{
3751	union ctl_io *io;
3752#ifdef IO_POOLS
3753	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3754
3755	io = uma_zalloc(pool->zone, M_WAITOK);
3756#else
3757	io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3758#endif
3759	if (io != NULL)
3760		io->io_hdr.pool = pool_ref;
3761	return (io);
3762}
3763
3764union ctl_io *
3765ctl_alloc_io_nowait(void *pool_ref)
3766{
3767	union ctl_io *io;
3768#ifdef IO_POOLS
3769	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3770
3771	io = uma_zalloc(pool->zone, M_NOWAIT);
3772#else
3773	io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3774#endif
3775	if (io != NULL)
3776		io->io_hdr.pool = pool_ref;
3777	return (io);
3778}
3779
3780void
3781ctl_free_io(union ctl_io *io)
3782{
3783#ifdef IO_POOLS
3784	struct ctl_io_pool *pool;
3785#endif
3786
3787	if (io == NULL)
3788		return;
3789
3790#ifdef IO_POOLS
3791	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3792	uma_zfree(pool->zone, io);
3793#else
3794	uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3795#endif
3796}
3797
3798void
3799ctl_zero_io(union ctl_io *io)
3800{
3801	void *pool_ref;
3802
3803	if (io == NULL)
3804		return;
3805
3806	/*
3807	 * May need to preserve linked list pointers at some point too.
3808	 */
3809	pool_ref = io->io_hdr.pool;
3810	memset(io, 0, sizeof(*io));
3811	io->io_hdr.pool = pool_ref;
3812}
3813
3814/*
3815 * This routine is currently used for internal copies of ctl_ios that need
3816 * to persist for some reason after we've already returned status to the
3817 * FETD.  (Thus the flag set.)
3818 *
3819 * XXX XXX
3820 * Note that this makes a blind copy of all fields in the ctl_io, except
3821 * for the pool reference.  This includes any memory that has been
3822 * allocated!  That memory will no longer be valid after done has been
3823 * called, so this would be VERY DANGEROUS for command that actually does
3824 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3825 * start and stop commands, which don't transfer any data, so this is not a
3826 * problem.  If it is used for anything else, the caller would also need to
3827 * allocate data buffer space and this routine would need to be modified to
3828 * copy the data buffer(s) as well.
3829 */
3830void
3831ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3832{
3833	void *pool_ref;
3834
3835	if ((src == NULL)
3836	 || (dest == NULL))
3837		return;
3838
3839	/*
3840	 * May need to preserve linked list pointers at some point too.
3841	 */
3842	pool_ref = dest->io_hdr.pool;
3843
3844	memcpy(dest, src, MIN(sizeof(*src), sizeof(*dest)));
3845
3846	dest->io_hdr.pool = pool_ref;
3847	/*
3848	 * We need to know that this is an internal copy, and doesn't need
3849	 * to get passed back to the FETD that allocated it.
3850	 */
3851	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3852}
3853
3854int
3855ctl_expand_number(const char *buf, uint64_t *num)
3856{
3857	char *endptr;
3858	uint64_t number;
3859	unsigned shift;
3860
3861	number = strtoq(buf, &endptr, 0);
3862
3863	switch (tolower((unsigned char)*endptr)) {
3864	case 'e':
3865		shift = 60;
3866		break;
3867	case 'p':
3868		shift = 50;
3869		break;
3870	case 't':
3871		shift = 40;
3872		break;
3873	case 'g':
3874		shift = 30;
3875		break;
3876	case 'm':
3877		shift = 20;
3878		break;
3879	case 'k':
3880		shift = 10;
3881		break;
3882	case 'b':
3883	case '\0': /* No unit. */
3884		*num = number;
3885		return (0);
3886	default:
3887		/* Unrecognized unit. */
3888		return (-1);
3889	}
3890
3891	if ((number << shift) >> shift != number) {
3892		/* Overflow */
3893		return (-1);
3894	}
3895	*num = number << shift;
3896	return (0);
3897}
3898
3899
3900/*
3901 * This routine could be used in the future to load default and/or saved
3902 * mode page parameters for a particuar lun.
3903 */
3904static int
3905ctl_init_page_index(struct ctl_lun *lun)
3906{
3907	int i;
3908	struct ctl_page_index *page_index;
3909	const char *value;
3910	uint64_t ival;
3911
3912	memcpy(&lun->mode_pages.index, page_index_template,
3913	       sizeof(page_index_template));
3914
3915	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3916
3917		page_index = &lun->mode_pages.index[i];
3918		/*
3919		 * If this is a disk-only mode page, there's no point in
3920		 * setting it up.  For some pages, we have to have some
3921		 * basic information about the disk in order to calculate the
3922		 * mode page data.
3923		 */
3924		if ((lun->be_lun->lun_type != T_DIRECT)
3925		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3926			continue;
3927
3928		switch (page_index->page_code & SMPH_PC_MASK) {
3929		case SMS_RW_ERROR_RECOVERY_PAGE: {
3930			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3931				panic("subpage is incorrect!");
3932			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3933			       &rw_er_page_default,
3934			       sizeof(rw_er_page_default));
3935			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3936			       &rw_er_page_changeable,
3937			       sizeof(rw_er_page_changeable));
3938			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3939			       &rw_er_page_default,
3940			       sizeof(rw_er_page_default));
3941			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3942			       &rw_er_page_default,
3943			       sizeof(rw_er_page_default));
3944			page_index->page_data =
3945				(uint8_t *)lun->mode_pages.rw_er_page;
3946			break;
3947		}
3948		case SMS_FORMAT_DEVICE_PAGE: {
3949			struct scsi_format_page *format_page;
3950
3951			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3952				panic("subpage is incorrect!");
3953
3954			/*
3955			 * Sectors per track are set above.  Bytes per
3956			 * sector need to be set here on a per-LUN basis.
3957			 */
3958			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3959			       &format_page_default,
3960			       sizeof(format_page_default));
3961			memcpy(&lun->mode_pages.format_page[
3962			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
3963			       sizeof(format_page_changeable));
3964			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3965			       &format_page_default,
3966			       sizeof(format_page_default));
3967			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3968			       &format_page_default,
3969			       sizeof(format_page_default));
3970
3971			format_page = &lun->mode_pages.format_page[
3972				CTL_PAGE_CURRENT];
3973			scsi_ulto2b(lun->be_lun->blocksize,
3974				    format_page->bytes_per_sector);
3975
3976			format_page = &lun->mode_pages.format_page[
3977				CTL_PAGE_DEFAULT];
3978			scsi_ulto2b(lun->be_lun->blocksize,
3979				    format_page->bytes_per_sector);
3980
3981			format_page = &lun->mode_pages.format_page[
3982				CTL_PAGE_SAVED];
3983			scsi_ulto2b(lun->be_lun->blocksize,
3984				    format_page->bytes_per_sector);
3985
3986			page_index->page_data =
3987				(uint8_t *)lun->mode_pages.format_page;
3988			break;
3989		}
3990		case SMS_RIGID_DISK_PAGE: {
3991			struct scsi_rigid_disk_page *rigid_disk_page;
3992			uint32_t sectors_per_cylinder;
3993			uint64_t cylinders;
3994#ifndef	__XSCALE__
3995			int shift;
3996#endif /* !__XSCALE__ */
3997
3998			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3999				panic("invalid subpage value %d",
4000				      page_index->subpage);
4001
4002			/*
4003			 * Rotation rate and sectors per track are set
4004			 * above.  We calculate the cylinders here based on
4005			 * capacity.  Due to the number of heads and
4006			 * sectors per track we're using, smaller arrays
4007			 * may turn out to have 0 cylinders.  Linux and
4008			 * FreeBSD don't pay attention to these mode pages
4009			 * to figure out capacity, but Solaris does.  It
4010			 * seems to deal with 0 cylinders just fine, and
4011			 * works out a fake geometry based on the capacity.
4012			 */
4013			memcpy(&lun->mode_pages.rigid_disk_page[
4014			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4015			       sizeof(rigid_disk_page_default));
4016			memcpy(&lun->mode_pages.rigid_disk_page[
4017			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4018			       sizeof(rigid_disk_page_changeable));
4019
4020			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4021				CTL_DEFAULT_HEADS;
4022
4023			/*
4024			 * The divide method here will be more accurate,
4025			 * probably, but results in floating point being
4026			 * used in the kernel on i386 (__udivdi3()).  On the
4027			 * XScale, though, __udivdi3() is implemented in
4028			 * software.
4029			 *
4030			 * The shift method for cylinder calculation is
4031			 * accurate if sectors_per_cylinder is a power of
4032			 * 2.  Otherwise it might be slightly off -- you
4033			 * might have a bit of a truncation problem.
4034			 */
4035#ifdef	__XSCALE__
4036			cylinders = (lun->be_lun->maxlba + 1) /
4037				sectors_per_cylinder;
4038#else
4039			for (shift = 31; shift > 0; shift--) {
4040				if (sectors_per_cylinder & (1 << shift))
4041					break;
4042			}
4043			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4044#endif
4045
4046			/*
4047			 * We've basically got 3 bytes, or 24 bits for the
4048			 * cylinder size in the mode page.  If we're over,
4049			 * just round down to 2^24.
4050			 */
4051			if (cylinders > 0xffffff)
4052				cylinders = 0xffffff;
4053
4054			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4055				CTL_PAGE_DEFAULT];
4056			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4057
4058			if ((value = ctl_get_opt(&lun->be_lun->options,
4059			    "rpm")) != NULL) {
4060				scsi_ulto2b(strtol(value, NULL, 0),
4061				     rigid_disk_page->rotation_rate);
4062			}
4063
4064			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4065			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4066			       sizeof(rigid_disk_page_default));
4067			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4068			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4069			       sizeof(rigid_disk_page_default));
4070
4071			page_index->page_data =
4072				(uint8_t *)lun->mode_pages.rigid_disk_page;
4073			break;
4074		}
4075		case SMS_CACHING_PAGE: {
4076			struct scsi_caching_page *caching_page;
4077
4078			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4079				panic("invalid subpage value %d",
4080				      page_index->subpage);
4081			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4082			       &caching_page_default,
4083			       sizeof(caching_page_default));
4084			memcpy(&lun->mode_pages.caching_page[
4085			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4086			       sizeof(caching_page_changeable));
4087			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4088			       &caching_page_default,
4089			       sizeof(caching_page_default));
4090			caching_page = &lun->mode_pages.caching_page[
4091			    CTL_PAGE_SAVED];
4092			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4093			if (value != NULL && strcmp(value, "off") == 0)
4094				caching_page->flags1 &= ~SCP_WCE;
4095			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4096			if (value != NULL && strcmp(value, "off") == 0)
4097				caching_page->flags1 |= SCP_RCD;
4098			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4099			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4100			       sizeof(caching_page_default));
4101			page_index->page_data =
4102				(uint8_t *)lun->mode_pages.caching_page;
4103			break;
4104		}
4105		case SMS_CONTROL_MODE_PAGE: {
4106			switch (page_index->subpage) {
4107			case SMS_SUBPAGE_PAGE_0: {
4108				struct scsi_control_page *control_page;
4109
4110				memcpy(&lun->mode_pages.control_page[
4111				    CTL_PAGE_DEFAULT],
4112				       &control_page_default,
4113				       sizeof(control_page_default));
4114				memcpy(&lun->mode_pages.control_page[
4115				    CTL_PAGE_CHANGEABLE],
4116				       &control_page_changeable,
4117				       sizeof(control_page_changeable));
4118				memcpy(&lun->mode_pages.control_page[
4119				    CTL_PAGE_SAVED],
4120				       &control_page_default,
4121				       sizeof(control_page_default));
4122				control_page = &lun->mode_pages.control_page[
4123				    CTL_PAGE_SAVED];
4124				value = ctl_get_opt(&lun->be_lun->options,
4125				    "reordering");
4126				if (value != NULL &&
4127				    strcmp(value, "unrestricted") == 0) {
4128					control_page->queue_flags &=
4129					    ~SCP_QUEUE_ALG_MASK;
4130					control_page->queue_flags |=
4131					    SCP_QUEUE_ALG_UNRESTRICTED;
4132				}
4133				memcpy(&lun->mode_pages.control_page[
4134				    CTL_PAGE_CURRENT],
4135				       &lun->mode_pages.control_page[
4136				    CTL_PAGE_SAVED],
4137				       sizeof(control_page_default));
4138				page_index->page_data =
4139				    (uint8_t *)lun->mode_pages.control_page;
4140				break;
4141			}
4142			case 0x01:
4143				memcpy(&lun->mode_pages.control_ext_page[
4144				    CTL_PAGE_DEFAULT],
4145				       &control_ext_page_default,
4146				       sizeof(control_ext_page_default));
4147				memcpy(&lun->mode_pages.control_ext_page[
4148				    CTL_PAGE_CHANGEABLE],
4149				       &control_ext_page_changeable,
4150				       sizeof(control_ext_page_changeable));
4151				memcpy(&lun->mode_pages.control_ext_page[
4152				    CTL_PAGE_SAVED],
4153				       &control_ext_page_default,
4154				       sizeof(control_ext_page_default));
4155				memcpy(&lun->mode_pages.control_ext_page[
4156				    CTL_PAGE_CURRENT],
4157				       &lun->mode_pages.control_ext_page[
4158				    CTL_PAGE_SAVED],
4159				       sizeof(control_ext_page_default));
4160				page_index->page_data =
4161				    (uint8_t *)lun->mode_pages.control_ext_page;
4162				break;
4163			}
4164			break;
4165		}
4166		case SMS_INFO_EXCEPTIONS_PAGE: {
4167			switch (page_index->subpage) {
4168			case SMS_SUBPAGE_PAGE_0:
4169				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4170				       &ie_page_default,
4171				       sizeof(ie_page_default));
4172				memcpy(&lun->mode_pages.ie_page[
4173				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4174				       sizeof(ie_page_changeable));
4175				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4176				       &ie_page_default,
4177				       sizeof(ie_page_default));
4178				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4179				       &ie_page_default,
4180				       sizeof(ie_page_default));
4181				page_index->page_data =
4182					(uint8_t *)lun->mode_pages.ie_page;
4183				break;
4184			case 0x02: {
4185				struct ctl_logical_block_provisioning_page *page;
4186
4187				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4188				       &lbp_page_default,
4189				       sizeof(lbp_page_default));
4190				memcpy(&lun->mode_pages.lbp_page[
4191				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4192				       sizeof(lbp_page_changeable));
4193				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4194				       &lbp_page_default,
4195				       sizeof(lbp_page_default));
4196				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4197				value = ctl_get_opt(&lun->be_lun->options,
4198				    "avail-threshold");
4199				if (value != NULL &&
4200				    ctl_expand_number(value, &ival) == 0) {
4201					page->descr[0].flags |= SLBPPD_ENABLED |
4202					    SLBPPD_ARMING_DEC;
4203					if (lun->be_lun->blocksize)
4204						ival /= lun->be_lun->blocksize;
4205					else
4206						ival /= 512;
4207					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4208					    page->descr[0].count);
4209				}
4210				value = ctl_get_opt(&lun->be_lun->options,
4211				    "used-threshold");
4212				if (value != NULL &&
4213				    ctl_expand_number(value, &ival) == 0) {
4214					page->descr[1].flags |= SLBPPD_ENABLED |
4215					    SLBPPD_ARMING_INC;
4216					if (lun->be_lun->blocksize)
4217						ival /= lun->be_lun->blocksize;
4218					else
4219						ival /= 512;
4220					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4221					    page->descr[1].count);
4222				}
4223				value = ctl_get_opt(&lun->be_lun->options,
4224				    "pool-avail-threshold");
4225				if (value != NULL &&
4226				    ctl_expand_number(value, &ival) == 0) {
4227					page->descr[2].flags |= SLBPPD_ENABLED |
4228					    SLBPPD_ARMING_DEC;
4229					if (lun->be_lun->blocksize)
4230						ival /= lun->be_lun->blocksize;
4231					else
4232						ival /= 512;
4233					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4234					    page->descr[2].count);
4235				}
4236				value = ctl_get_opt(&lun->be_lun->options,
4237				    "pool-used-threshold");
4238				if (value != NULL &&
4239				    ctl_expand_number(value, &ival) == 0) {
4240					page->descr[3].flags |= SLBPPD_ENABLED |
4241					    SLBPPD_ARMING_INC;
4242					if (lun->be_lun->blocksize)
4243						ival /= lun->be_lun->blocksize;
4244					else
4245						ival /= 512;
4246					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4247					    page->descr[3].count);
4248				}
4249				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4250				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4251				       sizeof(lbp_page_default));
4252				page_index->page_data =
4253					(uint8_t *)lun->mode_pages.lbp_page;
4254			}}
4255			break;
4256		}
4257		case SMS_VENDOR_SPECIFIC_PAGE:{
4258			switch (page_index->subpage) {
4259			case DBGCNF_SUBPAGE_CODE: {
4260				struct copan_debugconf_subpage *current_page,
4261							       *saved_page;
4262
4263				memcpy(&lun->mode_pages.debugconf_subpage[
4264				       CTL_PAGE_CURRENT],
4265				       &debugconf_page_default,
4266				       sizeof(debugconf_page_default));
4267				memcpy(&lun->mode_pages.debugconf_subpage[
4268				       CTL_PAGE_CHANGEABLE],
4269				       &debugconf_page_changeable,
4270				       sizeof(debugconf_page_changeable));
4271				memcpy(&lun->mode_pages.debugconf_subpage[
4272				       CTL_PAGE_DEFAULT],
4273				       &debugconf_page_default,
4274				       sizeof(debugconf_page_default));
4275				memcpy(&lun->mode_pages.debugconf_subpage[
4276				       CTL_PAGE_SAVED],
4277				       &debugconf_page_default,
4278				       sizeof(debugconf_page_default));
4279				page_index->page_data =
4280					(uint8_t *)lun->mode_pages.debugconf_subpage;
4281
4282				current_page = (struct copan_debugconf_subpage *)
4283					(page_index->page_data +
4284					 (page_index->page_len *
4285					  CTL_PAGE_CURRENT));
4286				saved_page = (struct copan_debugconf_subpage *)
4287					(page_index->page_data +
4288					 (page_index->page_len *
4289					  CTL_PAGE_SAVED));
4290				break;
4291			}
4292			default:
4293				panic("invalid subpage value %d",
4294				      page_index->subpage);
4295				break;
4296			}
4297   			break;
4298		}
4299		default:
4300			panic("invalid page value %d",
4301			      page_index->page_code & SMPH_PC_MASK);
4302			break;
4303    	}
4304	}
4305
4306	return (CTL_RETVAL_COMPLETE);
4307}
4308
4309static int
4310ctl_init_log_page_index(struct ctl_lun *lun)
4311{
4312	struct ctl_page_index *page_index;
4313	int i, j, k, prev;
4314
4315	memcpy(&lun->log_pages.index, log_page_index_template,
4316	       sizeof(log_page_index_template));
4317
4318	prev = -1;
4319	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4320
4321		page_index = &lun->log_pages.index[i];
4322		/*
4323		 * If this is a disk-only mode page, there's no point in
4324		 * setting it up.  For some pages, we have to have some
4325		 * basic information about the disk in order to calculate the
4326		 * mode page data.
4327		 */
4328		if ((lun->be_lun->lun_type != T_DIRECT)
4329		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4330			continue;
4331
4332		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4333		     lun->backend->lun_attr == NULL)
4334			continue;
4335
4336		if (page_index->page_code != prev) {
4337			lun->log_pages.pages_page[j] = page_index->page_code;
4338			prev = page_index->page_code;
4339			j++;
4340		}
4341		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4342		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4343		k++;
4344	}
4345	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4346	lun->log_pages.index[0].page_len = j;
4347	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4348	lun->log_pages.index[1].page_len = k * 2;
4349	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4350	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4351	lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4352	lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4353
4354	return (CTL_RETVAL_COMPLETE);
4355}
4356
4357static int
4358hex2bin(const char *str, uint8_t *buf, int buf_size)
4359{
4360	int i;
4361	u_char c;
4362
4363	memset(buf, 0, buf_size);
4364	while (isspace(str[0]))
4365		str++;
4366	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4367		str += 2;
4368	buf_size *= 2;
4369	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4370		c = str[i];
4371		if (isdigit(c))
4372			c -= '0';
4373		else if (isalpha(c))
4374			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4375		else
4376			break;
4377		if (c >= 16)
4378			break;
4379		if ((i & 1) == 0)
4380			buf[i / 2] |= (c << 4);
4381		else
4382			buf[i / 2] |= c;
4383	}
4384	return ((i + 1) / 2);
4385}
4386
4387/*
4388 * LUN allocation.
4389 *
4390 * Requirements:
4391 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4392 *   wants us to allocate the LUN and he can block.
4393 * - ctl_softc is always set
4394 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4395 *
4396 * Returns 0 for success, non-zero (errno) for failure.
4397 */
4398static int
4399ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4400	      struct ctl_be_lun *const be_lun)
4401{
4402	struct ctl_lun *nlun, *lun;
4403	struct scsi_vpd_id_descriptor *desc;
4404	struct scsi_vpd_id_t10 *t10id;
4405	const char *eui, *naa, *scsiname, *vendor;
4406	int lun_number, i, lun_malloced;
4407	int devidlen, idlen1, idlen2 = 0, len;
4408
4409	if (be_lun == NULL)
4410		return (EINVAL);
4411
4412	/*
4413	 * We currently only support Direct Access or Processor LUN types.
4414	 */
4415	switch (be_lun->lun_type) {
4416	case T_DIRECT:
4417		break;
4418	case T_PROCESSOR:
4419		break;
4420	case T_SEQUENTIAL:
4421	case T_CHANGER:
4422	default:
4423		be_lun->lun_config_status(be_lun->be_lun,
4424					  CTL_LUN_CONFIG_FAILURE);
4425		break;
4426	}
4427	if (ctl_lun == NULL) {
4428		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4429		lun_malloced = 1;
4430	} else {
4431		lun_malloced = 0;
4432		lun = ctl_lun;
4433	}
4434
4435	memset(lun, 0, sizeof(*lun));
4436	if (lun_malloced)
4437		lun->flags = CTL_LUN_MALLOCED;
4438
4439	/* Generate LUN ID. */
4440	devidlen = max(CTL_DEVID_MIN_LEN,
4441	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4442	idlen1 = sizeof(*t10id) + devidlen;
4443	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4444	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4445	if (scsiname != NULL) {
4446		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4447		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4448	}
4449	eui = ctl_get_opt(&be_lun->options, "eui");
4450	if (eui != NULL) {
4451		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4452	}
4453	naa = ctl_get_opt(&be_lun->options, "naa");
4454	if (naa != NULL) {
4455		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4456	}
4457	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4458	    M_CTL, M_WAITOK | M_ZERO);
4459	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4460	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4461	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4462	desc->length = idlen1;
4463	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4464	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4465	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4466		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4467	} else {
4468		strncpy(t10id->vendor, vendor,
4469		    min(sizeof(t10id->vendor), strlen(vendor)));
4470	}
4471	strncpy((char *)t10id->vendor_spec_id,
4472	    (char *)be_lun->device_id, devidlen);
4473	if (scsiname != NULL) {
4474		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4475		    desc->length);
4476		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4477		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4478		    SVPD_ID_TYPE_SCSI_NAME;
4479		desc->length = idlen2;
4480		strlcpy(desc->identifier, scsiname, idlen2);
4481	}
4482	if (eui != NULL) {
4483		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4484		    desc->length);
4485		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4486		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4487		    SVPD_ID_TYPE_EUI64;
4488		desc->length = hex2bin(eui, desc->identifier, 16);
4489		desc->length = desc->length > 12 ? 16 :
4490		    (desc->length > 8 ? 12 : 8);
4491		len -= 16 - desc->length;
4492	}
4493	if (naa != NULL) {
4494		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4495		    desc->length);
4496		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4497		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4498		    SVPD_ID_TYPE_NAA;
4499		desc->length = hex2bin(naa, desc->identifier, 16);
4500		desc->length = desc->length > 8 ? 16 : 8;
4501		len -= 16 - desc->length;
4502	}
4503	lun->lun_devid->len = len;
4504
4505	mtx_lock(&ctl_softc->ctl_lock);
4506	/*
4507	 * See if the caller requested a particular LUN number.  If so, see
4508	 * if it is available.  Otherwise, allocate the first available LUN.
4509	 */
4510	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4511		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4512		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4513			mtx_unlock(&ctl_softc->ctl_lock);
4514			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4515				printf("ctl: requested LUN ID %d is higher "
4516				       "than CTL_MAX_LUNS - 1 (%d)\n",
4517				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4518			} else {
4519				/*
4520				 * XXX KDM return an error, or just assign
4521				 * another LUN ID in this case??
4522				 */
4523				printf("ctl: requested LUN ID %d is already "
4524				       "in use\n", be_lun->req_lun_id);
4525			}
4526			if (lun->flags & CTL_LUN_MALLOCED)
4527				free(lun, M_CTL);
4528			be_lun->lun_config_status(be_lun->be_lun,
4529						  CTL_LUN_CONFIG_FAILURE);
4530			return (ENOSPC);
4531		}
4532		lun_number = be_lun->req_lun_id;
4533	} else {
4534		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4535		if (lun_number == -1) {
4536			mtx_unlock(&ctl_softc->ctl_lock);
4537			printf("ctl: can't allocate LUN, out of LUNs\n");
4538			if (lun->flags & CTL_LUN_MALLOCED)
4539				free(lun, M_CTL);
4540			be_lun->lun_config_status(be_lun->be_lun,
4541						  CTL_LUN_CONFIG_FAILURE);
4542			return (ENOSPC);
4543		}
4544	}
4545	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4546
4547	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4548	lun->lun = lun_number;
4549	lun->be_lun = be_lun;
4550	/*
4551	 * The processor LUN is always enabled.  Disk LUNs come on line
4552	 * disabled, and must be enabled by the backend.
4553	 */
4554	lun->flags |= CTL_LUN_DISABLED;
4555	lun->backend = be_lun->be;
4556	be_lun->ctl_lun = lun;
4557	be_lun->lun_id = lun_number;
4558	atomic_add_int(&be_lun->be->num_luns, 1);
4559	if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4560		lun->flags |= CTL_LUN_OFFLINE;
4561
4562	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4563		lun->flags |= CTL_LUN_STOPPED;
4564
4565	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4566		lun->flags |= CTL_LUN_INOPERABLE;
4567
4568	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4569		lun->flags |= CTL_LUN_PRIMARY_SC;
4570
4571	lun->ctl_softc = ctl_softc;
4572#ifdef CTL_TIME_IO
4573	lun->last_busy = getsbinuptime();
4574#endif
4575	TAILQ_INIT(&lun->ooa_queue);
4576	TAILQ_INIT(&lun->blocked_queue);
4577	STAILQ_INIT(&lun->error_list);
4578	ctl_tpc_lun_init(lun);
4579
4580	/*
4581	 * Initialize the mode and log page index.
4582	 */
4583	ctl_init_page_index(lun);
4584	ctl_init_log_page_index(lun);
4585
4586	/*
4587	 * Now, before we insert this lun on the lun list, set the lun
4588	 * inventory changed UA for all other luns.
4589	 */
4590	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4591		mtx_lock(&nlun->lun_lock);
4592		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4593		mtx_unlock(&nlun->lun_lock);
4594	}
4595
4596	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4597
4598	ctl_softc->ctl_luns[lun_number] = lun;
4599
4600	ctl_softc->num_luns++;
4601
4602	/* Setup statistics gathering */
4603	lun->stats.device_type = be_lun->lun_type;
4604	lun->stats.lun_number = lun_number;
4605	if (lun->stats.device_type == T_DIRECT)
4606		lun->stats.blocksize = be_lun->blocksize;
4607	else
4608		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4609	for (i = 0;i < CTL_MAX_PORTS;i++)
4610		lun->stats.ports[i].targ_port = i;
4611
4612	mtx_unlock(&ctl_softc->ctl_lock);
4613
4614	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4615	return (0);
4616}
4617
4618/*
4619 * Delete a LUN.
4620 * Assumptions:
4621 * - LUN has already been marked invalid and any pending I/O has been taken
4622 *   care of.
4623 */
4624static int
4625ctl_free_lun(struct ctl_lun *lun)
4626{
4627	struct ctl_softc *softc;
4628	struct ctl_lun *nlun;
4629	int i;
4630
4631	softc = lun->ctl_softc;
4632
4633	mtx_assert(&softc->ctl_lock, MA_OWNED);
4634
4635	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4636
4637	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4638
4639	softc->ctl_luns[lun->lun] = NULL;
4640
4641	if (!TAILQ_EMPTY(&lun->ooa_queue))
4642		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4643
4644	softc->num_luns--;
4645
4646	/*
4647	 * Tell the backend to free resources, if this LUN has a backend.
4648	 */
4649	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4650	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4651
4652	ctl_tpc_lun_shutdown(lun);
4653	mtx_destroy(&lun->lun_lock);
4654	free(lun->lun_devid, M_CTL);
4655	for (i = 0; i < CTL_MAX_PORTS; i++)
4656		free(lun->pending_ua[i], M_CTL);
4657	for (i = 0; i < CTL_MAX_PORTS; i++)
4658		free(lun->pr_keys[i], M_CTL);
4659	free(lun->write_buffer, M_CTL);
4660	if (lun->flags & CTL_LUN_MALLOCED)
4661		free(lun, M_CTL);
4662
4663	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4664		mtx_lock(&nlun->lun_lock);
4665		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4666		mtx_unlock(&nlun->lun_lock);
4667	}
4668
4669	return (0);
4670}
4671
4672static void
4673ctl_create_lun(struct ctl_be_lun *be_lun)
4674{
4675	struct ctl_softc *softc;
4676
4677	softc = control_softc;
4678
4679	/*
4680	 * ctl_alloc_lun() should handle all potential failure cases.
4681	 */
4682	ctl_alloc_lun(softc, NULL, be_lun);
4683}
4684
4685int
4686ctl_add_lun(struct ctl_be_lun *be_lun)
4687{
4688	struct ctl_softc *softc = control_softc;
4689
4690	mtx_lock(&softc->ctl_lock);
4691	STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4692	mtx_unlock(&softc->ctl_lock);
4693	wakeup(&softc->pending_lun_queue);
4694
4695	return (0);
4696}
4697
4698int
4699ctl_enable_lun(struct ctl_be_lun *be_lun)
4700{
4701	struct ctl_softc *softc;
4702	struct ctl_port *port, *nport;
4703	struct ctl_lun *lun;
4704	int retval;
4705
4706	lun = (struct ctl_lun *)be_lun->ctl_lun;
4707	softc = lun->ctl_softc;
4708
4709	mtx_lock(&softc->ctl_lock);
4710	mtx_lock(&lun->lun_lock);
4711	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4712		/*
4713		 * eh?  Why did we get called if the LUN is already
4714		 * enabled?
4715		 */
4716		mtx_unlock(&lun->lun_lock);
4717		mtx_unlock(&softc->ctl_lock);
4718		return (0);
4719	}
4720	lun->flags &= ~CTL_LUN_DISABLED;
4721	mtx_unlock(&lun->lun_lock);
4722
4723	for (port = STAILQ_FIRST(&softc->port_list); port != NULL; port = nport) {
4724		nport = STAILQ_NEXT(port, links);
4725		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4726		    port->lun_map != NULL || port->lun_enable == NULL)
4727			continue;
4728
4729		/*
4730		 * Drop the lock while we call the FETD's enable routine.
4731		 * This can lead to a callback into CTL (at least in the
4732		 * case of the internal initiator frontend.
4733		 */
4734		mtx_unlock(&softc->ctl_lock);
4735		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4736		mtx_lock(&softc->ctl_lock);
4737		if (retval != 0) {
4738			printf("%s: FETD %s port %d returned error "
4739			       "%d for lun_enable on lun %jd\n",
4740			       __func__, port->port_name, port->targ_port,
4741			       retval, (intmax_t)lun->lun);
4742		}
4743	}
4744
4745	mtx_unlock(&softc->ctl_lock);
4746	ctl_isc_announce_lun(lun);
4747
4748	return (0);
4749}
4750
4751int
4752ctl_disable_lun(struct ctl_be_lun *be_lun)
4753{
4754	struct ctl_softc *softc;
4755	struct ctl_port *port;
4756	struct ctl_lun *lun;
4757	int retval;
4758
4759	lun = (struct ctl_lun *)be_lun->ctl_lun;
4760	softc = lun->ctl_softc;
4761
4762	mtx_lock(&softc->ctl_lock);
4763	mtx_lock(&lun->lun_lock);
4764	if (lun->flags & CTL_LUN_DISABLED) {
4765		mtx_unlock(&lun->lun_lock);
4766		mtx_unlock(&softc->ctl_lock);
4767		return (0);
4768	}
4769	lun->flags |= CTL_LUN_DISABLED;
4770	mtx_unlock(&lun->lun_lock);
4771
4772	STAILQ_FOREACH(port, &softc->port_list, links) {
4773		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4774		    port->lun_map != NULL || port->lun_disable == NULL)
4775			continue;
4776
4777		/*
4778		 * Drop the lock before we call the frontend's disable
4779		 * routine, to avoid lock order reversals.
4780		 *
4781		 * XXX KDM what happens if the frontend list changes while
4782		 * we're traversing it?  It's unlikely, but should be handled.
4783		 */
4784		mtx_unlock(&softc->ctl_lock);
4785		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4786		mtx_lock(&softc->ctl_lock);
4787		if (retval != 0) {
4788			printf("%s: FETD %s port %d returned error "
4789			       "%d for lun_disable on lun %jd\n",
4790			       __func__, port->port_name, port->targ_port,
4791			       retval, (intmax_t)lun->lun);
4792		}
4793	}
4794
4795	mtx_unlock(&softc->ctl_lock);
4796	ctl_isc_announce_lun(lun);
4797
4798	return (0);
4799}
4800
4801int
4802ctl_start_lun(struct ctl_be_lun *be_lun)
4803{
4804	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4805
4806	mtx_lock(&lun->lun_lock);
4807	lun->flags &= ~CTL_LUN_STOPPED;
4808	mtx_unlock(&lun->lun_lock);
4809	return (0);
4810}
4811
4812int
4813ctl_stop_lun(struct ctl_be_lun *be_lun)
4814{
4815	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4816
4817	mtx_lock(&lun->lun_lock);
4818	lun->flags |= CTL_LUN_STOPPED;
4819	mtx_unlock(&lun->lun_lock);
4820	return (0);
4821}
4822
4823int
4824ctl_lun_offline(struct ctl_be_lun *be_lun)
4825{
4826	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4827
4828	mtx_lock(&lun->lun_lock);
4829	lun->flags |= CTL_LUN_OFFLINE;
4830	mtx_unlock(&lun->lun_lock);
4831	return (0);
4832}
4833
4834int
4835ctl_lun_online(struct ctl_be_lun *be_lun)
4836{
4837	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4838
4839	mtx_lock(&lun->lun_lock);
4840	lun->flags &= ~CTL_LUN_OFFLINE;
4841	mtx_unlock(&lun->lun_lock);
4842	return (0);
4843}
4844
4845int
4846ctl_lun_primary(struct ctl_be_lun *be_lun)
4847{
4848	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4849
4850	mtx_lock(&lun->lun_lock);
4851	lun->flags |= CTL_LUN_PRIMARY_SC;
4852	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4853	mtx_unlock(&lun->lun_lock);
4854	ctl_isc_announce_lun(lun);
4855	return (0);
4856}
4857
4858int
4859ctl_lun_secondary(struct ctl_be_lun *be_lun)
4860{
4861	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4862
4863	mtx_lock(&lun->lun_lock);
4864	lun->flags &= ~CTL_LUN_PRIMARY_SC;
4865	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4866	mtx_unlock(&lun->lun_lock);
4867	ctl_isc_announce_lun(lun);
4868	return (0);
4869}
4870
4871int
4872ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4873{
4874	struct ctl_softc *softc;
4875	struct ctl_lun *lun;
4876
4877	lun = (struct ctl_lun *)be_lun->ctl_lun;
4878	softc = lun->ctl_softc;
4879
4880	mtx_lock(&lun->lun_lock);
4881
4882	/*
4883	 * The LUN needs to be disabled before it can be marked invalid.
4884	 */
4885	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4886		mtx_unlock(&lun->lun_lock);
4887		return (-1);
4888	}
4889	/*
4890	 * Mark the LUN invalid.
4891	 */
4892	lun->flags |= CTL_LUN_INVALID;
4893
4894	/*
4895	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4896	 * If we have something in the OOA queue, we'll free it when the
4897	 * last I/O completes.
4898	 */
4899	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4900		mtx_unlock(&lun->lun_lock);
4901		mtx_lock(&softc->ctl_lock);
4902		ctl_free_lun(lun);
4903		mtx_unlock(&softc->ctl_lock);
4904	} else
4905		mtx_unlock(&lun->lun_lock);
4906
4907	return (0);
4908}
4909
4910int
4911ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4912{
4913	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4914
4915	mtx_lock(&lun->lun_lock);
4916	lun->flags |= CTL_LUN_INOPERABLE;
4917	mtx_unlock(&lun->lun_lock);
4918	return (0);
4919}
4920
4921int
4922ctl_lun_operable(struct ctl_be_lun *be_lun)
4923{
4924	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4925
4926	mtx_lock(&lun->lun_lock);
4927	lun->flags &= ~CTL_LUN_INOPERABLE;
4928	mtx_unlock(&lun->lun_lock);
4929	return (0);
4930}
4931
4932void
4933ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4934{
4935	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4936	union ctl_ha_msg msg;
4937
4938	mtx_lock(&lun->lun_lock);
4939	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGED);
4940	mtx_unlock(&lun->lun_lock);
4941	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4942		/* Send msg to other side. */
4943		bzero(&msg.ua, sizeof(msg.ua));
4944		msg.hdr.msg_type = CTL_MSG_UA;
4945		msg.hdr.nexus.initid = -1;
4946		msg.hdr.nexus.targ_port = -1;
4947		msg.hdr.nexus.targ_lun = lun->lun;
4948		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4949		msg.ua.ua_all = 1;
4950		msg.ua.ua_set = 1;
4951		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGED;
4952		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4953		    M_WAITOK);
4954	}
4955}
4956
4957/*
4958 * Backend "memory move is complete" callback for requests that never
4959 * make it down to say RAIDCore's configuration code.
4960 */
4961int
4962ctl_config_move_done(union ctl_io *io)
4963{
4964	int retval;
4965
4966	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4967	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4968	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
4969
4970	if ((io->io_hdr.port_status != 0) &&
4971	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4972	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4973		/*
4974		 * For hardware error sense keys, the sense key
4975		 * specific value is defined to be a retry count,
4976		 * but we use it to pass back an internal FETD
4977		 * error code.  XXX KDM  Hopefully the FETD is only
4978		 * using 16 bits for an error code, since that's
4979		 * all the space we have in the sks field.
4980		 */
4981		ctl_set_internal_failure(&io->scsiio,
4982					 /*sks_valid*/ 1,
4983					 /*retry_count*/
4984					 io->io_hdr.port_status);
4985	}
4986
4987	if (ctl_debug & CTL_DEBUG_CDB_DATA)
4988		ctl_data_print(io);
4989	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
4990	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4991	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
4992	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
4993		/*
4994		 * XXX KDM just assuming a single pointer here, and not a
4995		 * S/G list.  If we start using S/G lists for config data,
4996		 * we'll need to know how to clean them up here as well.
4997		 */
4998		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4999			free(io->scsiio.kern_data_ptr, M_CTL);
5000		ctl_done(io);
5001		retval = CTL_RETVAL_COMPLETE;
5002	} else {
5003		/*
5004		 * XXX KDM now we need to continue data movement.  Some
5005		 * options:
5006		 * - call ctl_scsiio() again?  We don't do this for data
5007		 *   writes, because for those at least we know ahead of
5008		 *   time where the write will go and how long it is.  For
5009		 *   config writes, though, that information is largely
5010		 *   contained within the write itself, thus we need to
5011		 *   parse out the data again.
5012		 *
5013		 * - Call some other function once the data is in?
5014		 */
5015
5016		/*
5017		 * XXX KDM call ctl_scsiio() again for now, and check flag
5018		 * bits to see whether we're allocated or not.
5019		 */
5020		retval = ctl_scsiio(&io->scsiio);
5021	}
5022	return (retval);
5023}
5024
5025/*
5026 * This gets called by a backend driver when it is done with a
5027 * data_submit method.
5028 */
5029void
5030ctl_data_submit_done(union ctl_io *io)
5031{
5032	/*
5033	 * If the IO_CONT flag is set, we need to call the supplied
5034	 * function to continue processing the I/O, instead of completing
5035	 * the I/O just yet.
5036	 *
5037	 * If there is an error, though, we don't want to keep processing.
5038	 * Instead, just send status back to the initiator.
5039	 */
5040	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5041	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5042	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5043	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5044		io->scsiio.io_cont(io);
5045		return;
5046	}
5047	ctl_done(io);
5048}
5049
5050/*
5051 * This gets called by a backend driver when it is done with a
5052 * configuration write.
5053 */
5054void
5055ctl_config_write_done(union ctl_io *io)
5056{
5057	uint8_t *buf;
5058
5059	/*
5060	 * If the IO_CONT flag is set, we need to call the supplied
5061	 * function to continue processing the I/O, instead of completing
5062	 * the I/O just yet.
5063	 *
5064	 * If there is an error, though, we don't want to keep processing.
5065	 * Instead, just send status back to the initiator.
5066	 */
5067	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5068	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5069	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5070	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5071		io->scsiio.io_cont(io);
5072		return;
5073	}
5074	/*
5075	 * Since a configuration write can be done for commands that actually
5076	 * have data allocated, like write buffer, and commands that have
5077	 * no data, like start/stop unit, we need to check here.
5078	 */
5079	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5080		buf = io->scsiio.kern_data_ptr;
5081	else
5082		buf = NULL;
5083	ctl_done(io);
5084	if (buf)
5085		free(buf, M_CTL);
5086}
5087
5088void
5089ctl_config_read_done(union ctl_io *io)
5090{
5091	uint8_t *buf;
5092
5093	/*
5094	 * If there is some error -- we are done, skip data transfer.
5095	 */
5096	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5097	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5098	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5099		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5100			buf = io->scsiio.kern_data_ptr;
5101		else
5102			buf = NULL;
5103		ctl_done(io);
5104		if (buf)
5105			free(buf, M_CTL);
5106		return;
5107	}
5108
5109	/*
5110	 * If the IO_CONT flag is set, we need to call the supplied
5111	 * function to continue processing the I/O, instead of completing
5112	 * the I/O just yet.
5113	 */
5114	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5115		io->scsiio.io_cont(io);
5116		return;
5117	}
5118
5119	ctl_datamove(io);
5120}
5121
5122/*
5123 * SCSI release command.
5124 */
5125int
5126ctl_scsi_release(struct ctl_scsiio *ctsio)
5127{
5128	int length, longid, thirdparty_id, resv_id;
5129	struct ctl_lun *lun;
5130	uint32_t residx;
5131
5132	length = 0;
5133	resv_id = 0;
5134
5135	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5136
5137	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5138	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5139
5140	switch (ctsio->cdb[0]) {
5141	case RELEASE_10: {
5142		struct scsi_release_10 *cdb;
5143
5144		cdb = (struct scsi_release_10 *)ctsio->cdb;
5145
5146		if (cdb->byte2 & SR10_LONGID)
5147			longid = 1;
5148		else
5149			thirdparty_id = cdb->thirdparty_id;
5150
5151		resv_id = cdb->resv_id;
5152		length = scsi_2btoul(cdb->length);
5153		break;
5154	}
5155	}
5156
5157
5158	/*
5159	 * XXX KDM right now, we only support LUN reservation.  We don't
5160	 * support 3rd party reservations, or extent reservations, which
5161	 * might actually need the parameter list.  If we've gotten this
5162	 * far, we've got a LUN reservation.  Anything else got kicked out
5163	 * above.  So, according to SPC, ignore the length.
5164	 */
5165	length = 0;
5166
5167	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5168	 && (length > 0)) {
5169		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5170		ctsio->kern_data_len = length;
5171		ctsio->kern_total_len = length;
5172		ctsio->kern_data_resid = 0;
5173		ctsio->kern_rel_offset = 0;
5174		ctsio->kern_sg_entries = 0;
5175		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5176		ctsio->be_move_done = ctl_config_move_done;
5177		ctl_datamove((union ctl_io *)ctsio);
5178
5179		return (CTL_RETVAL_COMPLETE);
5180	}
5181
5182	if (length > 0)
5183		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5184
5185	mtx_lock(&lun->lun_lock);
5186
5187	/*
5188	 * According to SPC, it is not an error for an intiator to attempt
5189	 * to release a reservation on a LUN that isn't reserved, or that
5190	 * is reserved by another initiator.  The reservation can only be
5191	 * released, though, by the initiator who made it or by one of
5192	 * several reset type events.
5193	 */
5194	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5195			lun->flags &= ~CTL_LUN_RESERVED;
5196
5197	mtx_unlock(&lun->lun_lock);
5198
5199	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5200		free(ctsio->kern_data_ptr, M_CTL);
5201		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5202	}
5203
5204	ctl_set_success(ctsio);
5205	ctl_done((union ctl_io *)ctsio);
5206	return (CTL_RETVAL_COMPLETE);
5207}
5208
5209int
5210ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5211{
5212	int extent, thirdparty, longid;
5213	int resv_id, length;
5214	uint64_t thirdparty_id;
5215	struct ctl_lun *lun;
5216	uint32_t residx;
5217
5218	extent = 0;
5219	thirdparty = 0;
5220	longid = 0;
5221	resv_id = 0;
5222	length = 0;
5223	thirdparty_id = 0;
5224
5225	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5226
5227	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5228	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5229
5230	switch (ctsio->cdb[0]) {
5231	case RESERVE_10: {
5232		struct scsi_reserve_10 *cdb;
5233
5234		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5235
5236		if (cdb->byte2 & SR10_LONGID)
5237			longid = 1;
5238		else
5239			thirdparty_id = cdb->thirdparty_id;
5240
5241		resv_id = cdb->resv_id;
5242		length = scsi_2btoul(cdb->length);
5243		break;
5244	}
5245	}
5246
5247	/*
5248	 * XXX KDM right now, we only support LUN reservation.  We don't
5249	 * support 3rd party reservations, or extent reservations, which
5250	 * might actually need the parameter list.  If we've gotten this
5251	 * far, we've got a LUN reservation.  Anything else got kicked out
5252	 * above.  So, according to SPC, ignore the length.
5253	 */
5254	length = 0;
5255
5256	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5257	 && (length > 0)) {
5258		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5259		ctsio->kern_data_len = length;
5260		ctsio->kern_total_len = length;
5261		ctsio->kern_data_resid = 0;
5262		ctsio->kern_rel_offset = 0;
5263		ctsio->kern_sg_entries = 0;
5264		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5265		ctsio->be_move_done = ctl_config_move_done;
5266		ctl_datamove((union ctl_io *)ctsio);
5267
5268		return (CTL_RETVAL_COMPLETE);
5269	}
5270
5271	if (length > 0)
5272		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5273
5274	mtx_lock(&lun->lun_lock);
5275	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5276		ctl_set_reservation_conflict(ctsio);
5277		goto bailout;
5278	}
5279
5280	lun->flags |= CTL_LUN_RESERVED;
5281	lun->res_idx = residx;
5282
5283	ctl_set_success(ctsio);
5284
5285bailout:
5286	mtx_unlock(&lun->lun_lock);
5287
5288	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5289		free(ctsio->kern_data_ptr, M_CTL);
5290		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5291	}
5292
5293	ctl_done((union ctl_io *)ctsio);
5294	return (CTL_RETVAL_COMPLETE);
5295}
5296
5297int
5298ctl_start_stop(struct ctl_scsiio *ctsio)
5299{
5300	struct scsi_start_stop_unit *cdb;
5301	struct ctl_lun *lun;
5302	int retval;
5303
5304	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5305
5306	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5307	retval = 0;
5308
5309	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5310
5311	/*
5312	 * XXX KDM
5313	 * We don't support the immediate bit on a stop unit.  In order to
5314	 * do that, we would need to code up a way to know that a stop is
5315	 * pending, and hold off any new commands until it completes, one
5316	 * way or another.  Then we could accept or reject those commands
5317	 * depending on its status.  We would almost need to do the reverse
5318	 * of what we do below for an immediate start -- return the copy of
5319	 * the ctl_io to the FETD with status to send to the host (and to
5320	 * free the copy!) and then free the original I/O once the stop
5321	 * actually completes.  That way, the OOA queue mechanism can work
5322	 * to block commands that shouldn't proceed.  Another alternative
5323	 * would be to put the copy in the queue in place of the original,
5324	 * and return the original back to the caller.  That could be
5325	 * slightly safer..
5326	 */
5327	if ((cdb->byte2 & SSS_IMMED)
5328	 && ((cdb->how & SSS_START) == 0)) {
5329		ctl_set_invalid_field(ctsio,
5330				      /*sks_valid*/ 1,
5331				      /*command*/ 1,
5332				      /*field*/ 1,
5333				      /*bit_valid*/ 1,
5334				      /*bit*/ 0);
5335		ctl_done((union ctl_io *)ctsio);
5336		return (CTL_RETVAL_COMPLETE);
5337	}
5338
5339	if ((lun->flags & CTL_LUN_PR_RESERVED)
5340	 && ((cdb->how & SSS_START)==0)) {
5341		uint32_t residx;
5342
5343		residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5344		if (ctl_get_prkey(lun, residx) == 0
5345		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5346
5347			ctl_set_reservation_conflict(ctsio);
5348			ctl_done((union ctl_io *)ctsio);
5349			return (CTL_RETVAL_COMPLETE);
5350		}
5351	}
5352
5353	/*
5354	 * If there is no backend on this device, we can't start or stop
5355	 * it.  In theory we shouldn't get any start/stop commands in the
5356	 * first place at this level if the LUN doesn't have a backend.
5357	 * That should get stopped by the command decode code.
5358	 */
5359	if (lun->backend == NULL) {
5360		ctl_set_invalid_opcode(ctsio);
5361		ctl_done((union ctl_io *)ctsio);
5362		return (CTL_RETVAL_COMPLETE);
5363	}
5364
5365	/*
5366	 * XXX KDM Copan-specific offline behavior.
5367	 * Figure out a reasonable way to port this?
5368	 */
5369#ifdef NEEDTOPORT
5370	mtx_lock(&lun->lun_lock);
5371
5372	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5373	 && (lun->flags & CTL_LUN_OFFLINE)) {
5374		/*
5375		 * If the LUN is offline, and the on/offline bit isn't set,
5376		 * reject the start or stop.  Otherwise, let it through.
5377		 */
5378		mtx_unlock(&lun->lun_lock);
5379		ctl_set_lun_not_ready(ctsio);
5380		ctl_done((union ctl_io *)ctsio);
5381	} else {
5382		mtx_unlock(&lun->lun_lock);
5383#endif /* NEEDTOPORT */
5384		/*
5385		 * This could be a start or a stop when we're online,
5386		 * or a stop/offline or start/online.  A start or stop when
5387		 * we're offline is covered in the case above.
5388		 */
5389		/*
5390		 * In the non-immediate case, we send the request to
5391		 * the backend and return status to the user when
5392		 * it is done.
5393		 *
5394		 * In the immediate case, we allocate a new ctl_io
5395		 * to hold a copy of the request, and send that to
5396		 * the backend.  We then set good status on the
5397		 * user's request and return it immediately.
5398		 */
5399		if (cdb->byte2 & SSS_IMMED) {
5400			union ctl_io *new_io;
5401
5402			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5403			ctl_copy_io((union ctl_io *)ctsio, new_io);
5404			retval = lun->backend->config_write(new_io);
5405			ctl_set_success(ctsio);
5406			ctl_done((union ctl_io *)ctsio);
5407		} else {
5408			retval = lun->backend->config_write(
5409				(union ctl_io *)ctsio);
5410		}
5411#ifdef NEEDTOPORT
5412	}
5413#endif
5414	return (retval);
5415}
5416
5417/*
5418 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5419 * we don't really do anything with the LBA and length fields if the user
5420 * passes them in.  Instead we'll just flush out the cache for the entire
5421 * LUN.
5422 */
5423int
5424ctl_sync_cache(struct ctl_scsiio *ctsio)
5425{
5426	struct ctl_lun *lun;
5427	struct ctl_softc *softc;
5428	struct ctl_lba_len_flags *lbalen;
5429	uint64_t starting_lba;
5430	uint32_t block_count;
5431	int retval;
5432	uint8_t byte2;
5433
5434	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5435
5436	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5437	softc = lun->ctl_softc;
5438	retval = 0;
5439
5440	switch (ctsio->cdb[0]) {
5441	case SYNCHRONIZE_CACHE: {
5442		struct scsi_sync_cache *cdb;
5443		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5444
5445		starting_lba = scsi_4btoul(cdb->begin_lba);
5446		block_count = scsi_2btoul(cdb->lb_count);
5447		byte2 = cdb->byte2;
5448		break;
5449	}
5450	case SYNCHRONIZE_CACHE_16: {
5451		struct scsi_sync_cache_16 *cdb;
5452		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5453
5454		starting_lba = scsi_8btou64(cdb->begin_lba);
5455		block_count = scsi_4btoul(cdb->lb_count);
5456		byte2 = cdb->byte2;
5457		break;
5458	}
5459	default:
5460		ctl_set_invalid_opcode(ctsio);
5461		ctl_done((union ctl_io *)ctsio);
5462		goto bailout;
5463		break; /* NOTREACHED */
5464	}
5465
5466	/*
5467	 * We check the LBA and length, but don't do anything with them.
5468	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5469	 * get flushed.  This check will just help satisfy anyone who wants
5470	 * to see an error for an out of range LBA.
5471	 */
5472	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5473		ctl_set_lba_out_of_range(ctsio);
5474		ctl_done((union ctl_io *)ctsio);
5475		goto bailout;
5476	}
5477
5478	/*
5479	 * If this LUN has no backend, we can't flush the cache anyway.
5480	 */
5481	if (lun->backend == NULL) {
5482		ctl_set_invalid_opcode(ctsio);
5483		ctl_done((union ctl_io *)ctsio);
5484		goto bailout;
5485	}
5486
5487	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5488	lbalen->lba = starting_lba;
5489	lbalen->len = block_count;
5490	lbalen->flags = byte2;
5491
5492	/*
5493	 * Check to see whether we're configured to send the SYNCHRONIZE
5494	 * CACHE command directly to the back end.
5495	 */
5496	mtx_lock(&lun->lun_lock);
5497	if ((softc->flags & CTL_FLAG_REAL_SYNC)
5498	 && (++(lun->sync_count) >= lun->sync_interval)) {
5499		lun->sync_count = 0;
5500		mtx_unlock(&lun->lun_lock);
5501		retval = lun->backend->config_write((union ctl_io *)ctsio);
5502	} else {
5503		mtx_unlock(&lun->lun_lock);
5504		ctl_set_success(ctsio);
5505		ctl_done((union ctl_io *)ctsio);
5506	}
5507
5508bailout:
5509
5510	return (retval);
5511}
5512
5513int
5514ctl_format(struct ctl_scsiio *ctsio)
5515{
5516	struct scsi_format *cdb;
5517	struct ctl_lun *lun;
5518	int length, defect_list_len;
5519
5520	CTL_DEBUG_PRINT(("ctl_format\n"));
5521
5522	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5523
5524	cdb = (struct scsi_format *)ctsio->cdb;
5525
5526	length = 0;
5527	if (cdb->byte2 & SF_FMTDATA) {
5528		if (cdb->byte2 & SF_LONGLIST)
5529			length = sizeof(struct scsi_format_header_long);
5530		else
5531			length = sizeof(struct scsi_format_header_short);
5532	}
5533
5534	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5535	 && (length > 0)) {
5536		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5537		ctsio->kern_data_len = length;
5538		ctsio->kern_total_len = length;
5539		ctsio->kern_data_resid = 0;
5540		ctsio->kern_rel_offset = 0;
5541		ctsio->kern_sg_entries = 0;
5542		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5543		ctsio->be_move_done = ctl_config_move_done;
5544		ctl_datamove((union ctl_io *)ctsio);
5545
5546		return (CTL_RETVAL_COMPLETE);
5547	}
5548
5549	defect_list_len = 0;
5550
5551	if (cdb->byte2 & SF_FMTDATA) {
5552		if (cdb->byte2 & SF_LONGLIST) {
5553			struct scsi_format_header_long *header;
5554
5555			header = (struct scsi_format_header_long *)
5556				ctsio->kern_data_ptr;
5557
5558			defect_list_len = scsi_4btoul(header->defect_list_len);
5559			if (defect_list_len != 0) {
5560				ctl_set_invalid_field(ctsio,
5561						      /*sks_valid*/ 1,
5562						      /*command*/ 0,
5563						      /*field*/ 2,
5564						      /*bit_valid*/ 0,
5565						      /*bit*/ 0);
5566				goto bailout;
5567			}
5568		} else {
5569			struct scsi_format_header_short *header;
5570
5571			header = (struct scsi_format_header_short *)
5572				ctsio->kern_data_ptr;
5573
5574			defect_list_len = scsi_2btoul(header->defect_list_len);
5575			if (defect_list_len != 0) {
5576				ctl_set_invalid_field(ctsio,
5577						      /*sks_valid*/ 1,
5578						      /*command*/ 0,
5579						      /*field*/ 2,
5580						      /*bit_valid*/ 0,
5581						      /*bit*/ 0);
5582				goto bailout;
5583			}
5584		}
5585	}
5586
5587	/*
5588	 * The format command will clear out the "Medium format corrupted"
5589	 * status if set by the configuration code.  That status is really
5590	 * just a way to notify the host that we have lost the media, and
5591	 * get them to issue a command that will basically make them think
5592	 * they're blowing away the media.
5593	 */
5594	mtx_lock(&lun->lun_lock);
5595	lun->flags &= ~CTL_LUN_INOPERABLE;
5596	mtx_unlock(&lun->lun_lock);
5597
5598	ctl_set_success(ctsio);
5599bailout:
5600
5601	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5602		free(ctsio->kern_data_ptr, M_CTL);
5603		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5604	}
5605
5606	ctl_done((union ctl_io *)ctsio);
5607	return (CTL_RETVAL_COMPLETE);
5608}
5609
5610int
5611ctl_read_buffer(struct ctl_scsiio *ctsio)
5612{
5613	struct ctl_lun *lun;
5614	uint64_t buffer_offset;
5615	uint32_t len;
5616	uint8_t byte2;
5617	static uint8_t descr[4];
5618	static uint8_t echo_descr[4] = { 0 };
5619
5620	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5621	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5622	switch (ctsio->cdb[0]) {
5623	case READ_BUFFER: {
5624		struct scsi_read_buffer *cdb;
5625
5626		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5627		buffer_offset = scsi_3btoul(cdb->offset);
5628		len = scsi_3btoul(cdb->length);
5629		byte2 = cdb->byte2;
5630		break;
5631	}
5632	case READ_BUFFER_16: {
5633		struct scsi_read_buffer_16 *cdb;
5634
5635		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5636		buffer_offset = scsi_8btou64(cdb->offset);
5637		len = scsi_4btoul(cdb->length);
5638		byte2 = cdb->byte2;
5639		break;
5640	}
5641	default: /* This shouldn't happen. */
5642		ctl_set_invalid_opcode(ctsio);
5643		ctl_done((union ctl_io *)ctsio);
5644		return (CTL_RETVAL_COMPLETE);
5645	}
5646
5647	if ((byte2 & RWB_MODE) != RWB_MODE_DATA &&
5648	    (byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5649	    (byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5650		ctl_set_invalid_field(ctsio,
5651				      /*sks_valid*/ 1,
5652				      /*command*/ 1,
5653				      /*field*/ 1,
5654				      /*bit_valid*/ 1,
5655				      /*bit*/ 4);
5656		ctl_done((union ctl_io *)ctsio);
5657		return (CTL_RETVAL_COMPLETE);
5658	}
5659
5660	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5661	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5662		ctl_set_invalid_field(ctsio,
5663				      /*sks_valid*/ 1,
5664				      /*command*/ 1,
5665				      /*field*/ 6,
5666				      /*bit_valid*/ 0,
5667				      /*bit*/ 0);
5668		ctl_done((union ctl_io *)ctsio);
5669		return (CTL_RETVAL_COMPLETE);
5670	}
5671
5672	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5673		descr[0] = 0;
5674		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5675		ctsio->kern_data_ptr = descr;
5676		len = min(len, sizeof(descr));
5677	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5678		ctsio->kern_data_ptr = echo_descr;
5679		len = min(len, sizeof(echo_descr));
5680	} else {
5681		if (lun->write_buffer == NULL) {
5682			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5683			    M_CTL, M_WAITOK);
5684		}
5685		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5686	}
5687	ctsio->kern_data_len = len;
5688	ctsio->kern_total_len = len;
5689	ctsio->kern_data_resid = 0;
5690	ctsio->kern_rel_offset = 0;
5691	ctsio->kern_sg_entries = 0;
5692	ctl_set_success(ctsio);
5693	ctsio->be_move_done = ctl_config_move_done;
5694	ctl_datamove((union ctl_io *)ctsio);
5695	return (CTL_RETVAL_COMPLETE);
5696}
5697
5698int
5699ctl_write_buffer(struct ctl_scsiio *ctsio)
5700{
5701	struct scsi_write_buffer *cdb;
5702	struct ctl_lun *lun;
5703	int buffer_offset, len;
5704
5705	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5706
5707	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5708	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5709
5710	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5711		ctl_set_invalid_field(ctsio,
5712				      /*sks_valid*/ 1,
5713				      /*command*/ 1,
5714				      /*field*/ 1,
5715				      /*bit_valid*/ 1,
5716				      /*bit*/ 4);
5717		ctl_done((union ctl_io *)ctsio);
5718		return (CTL_RETVAL_COMPLETE);
5719	}
5720
5721	len = scsi_3btoul(cdb->length);
5722	buffer_offset = scsi_3btoul(cdb->offset);
5723
5724	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5725		ctl_set_invalid_field(ctsio,
5726				      /*sks_valid*/ 1,
5727				      /*command*/ 1,
5728				      /*field*/ 6,
5729				      /*bit_valid*/ 0,
5730				      /*bit*/ 0);
5731		ctl_done((union ctl_io *)ctsio);
5732		return (CTL_RETVAL_COMPLETE);
5733	}
5734
5735	/*
5736	 * If we've got a kernel request that hasn't been malloced yet,
5737	 * malloc it and tell the caller the data buffer is here.
5738	 */
5739	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5740		if (lun->write_buffer == NULL) {
5741			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5742			    M_CTL, M_WAITOK);
5743		}
5744		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5745		ctsio->kern_data_len = len;
5746		ctsio->kern_total_len = len;
5747		ctsio->kern_data_resid = 0;
5748		ctsio->kern_rel_offset = 0;
5749		ctsio->kern_sg_entries = 0;
5750		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5751		ctsio->be_move_done = ctl_config_move_done;
5752		ctl_datamove((union ctl_io *)ctsio);
5753
5754		return (CTL_RETVAL_COMPLETE);
5755	}
5756
5757	ctl_set_success(ctsio);
5758	ctl_done((union ctl_io *)ctsio);
5759	return (CTL_RETVAL_COMPLETE);
5760}
5761
5762int
5763ctl_write_same(struct ctl_scsiio *ctsio)
5764{
5765	struct ctl_lun *lun;
5766	struct ctl_lba_len_flags *lbalen;
5767	uint64_t lba;
5768	uint32_t num_blocks;
5769	int len, retval;
5770	uint8_t byte2;
5771
5772	retval = CTL_RETVAL_COMPLETE;
5773
5774	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5775
5776	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5777
5778	switch (ctsio->cdb[0]) {
5779	case WRITE_SAME_10: {
5780		struct scsi_write_same_10 *cdb;
5781
5782		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5783
5784		lba = scsi_4btoul(cdb->addr);
5785		num_blocks = scsi_2btoul(cdb->length);
5786		byte2 = cdb->byte2;
5787		break;
5788	}
5789	case WRITE_SAME_16: {
5790		struct scsi_write_same_16 *cdb;
5791
5792		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5793
5794		lba = scsi_8btou64(cdb->addr);
5795		num_blocks = scsi_4btoul(cdb->length);
5796		byte2 = cdb->byte2;
5797		break;
5798	}
5799	default:
5800		/*
5801		 * We got a command we don't support.  This shouldn't
5802		 * happen, commands should be filtered out above us.
5803		 */
5804		ctl_set_invalid_opcode(ctsio);
5805		ctl_done((union ctl_io *)ctsio);
5806
5807		return (CTL_RETVAL_COMPLETE);
5808		break; /* NOTREACHED */
5809	}
5810
5811	/* NDOB and ANCHOR flags can be used only together with UNMAP */
5812	if ((byte2 & SWS_UNMAP) == 0 &&
5813	    (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5814		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5815		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5816		ctl_done((union ctl_io *)ctsio);
5817		return (CTL_RETVAL_COMPLETE);
5818	}
5819
5820	/*
5821	 * The first check is to make sure we're in bounds, the second
5822	 * check is to catch wrap-around problems.  If the lba + num blocks
5823	 * is less than the lba, then we've wrapped around and the block
5824	 * range is invalid anyway.
5825	 */
5826	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5827	 || ((lba + num_blocks) < lba)) {
5828		ctl_set_lba_out_of_range(ctsio);
5829		ctl_done((union ctl_io *)ctsio);
5830		return (CTL_RETVAL_COMPLETE);
5831	}
5832
5833	/* Zero number of blocks means "to the last logical block" */
5834	if (num_blocks == 0) {
5835		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5836			ctl_set_invalid_field(ctsio,
5837					      /*sks_valid*/ 0,
5838					      /*command*/ 1,
5839					      /*field*/ 0,
5840					      /*bit_valid*/ 0,
5841					      /*bit*/ 0);
5842			ctl_done((union ctl_io *)ctsio);
5843			return (CTL_RETVAL_COMPLETE);
5844		}
5845		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5846	}
5847
5848	len = lun->be_lun->blocksize;
5849
5850	/*
5851	 * If we've got a kernel request that hasn't been malloced yet,
5852	 * malloc it and tell the caller the data buffer is here.
5853	 */
5854	if ((byte2 & SWS_NDOB) == 0 &&
5855	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5856		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5857		ctsio->kern_data_len = len;
5858		ctsio->kern_total_len = len;
5859		ctsio->kern_data_resid = 0;
5860		ctsio->kern_rel_offset = 0;
5861		ctsio->kern_sg_entries = 0;
5862		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5863		ctsio->be_move_done = ctl_config_move_done;
5864		ctl_datamove((union ctl_io *)ctsio);
5865
5866		return (CTL_RETVAL_COMPLETE);
5867	}
5868
5869	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5870	lbalen->lba = lba;
5871	lbalen->len = num_blocks;
5872	lbalen->flags = byte2;
5873	retval = lun->backend->config_write((union ctl_io *)ctsio);
5874
5875	return (retval);
5876}
5877
5878int
5879ctl_unmap(struct ctl_scsiio *ctsio)
5880{
5881	struct ctl_lun *lun;
5882	struct scsi_unmap *cdb;
5883	struct ctl_ptr_len_flags *ptrlen;
5884	struct scsi_unmap_header *hdr;
5885	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5886	uint64_t lba;
5887	uint32_t num_blocks;
5888	int len, retval;
5889	uint8_t byte2;
5890
5891	retval = CTL_RETVAL_COMPLETE;
5892
5893	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5894
5895	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5896	cdb = (struct scsi_unmap *)ctsio->cdb;
5897
5898	len = scsi_2btoul(cdb->length);
5899	byte2 = cdb->byte2;
5900
5901	/*
5902	 * If we've got a kernel request that hasn't been malloced yet,
5903	 * malloc it and tell the caller the data buffer is here.
5904	 */
5905	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5906		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5907		ctsio->kern_data_len = len;
5908		ctsio->kern_total_len = len;
5909		ctsio->kern_data_resid = 0;
5910		ctsio->kern_rel_offset = 0;
5911		ctsio->kern_sg_entries = 0;
5912		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5913		ctsio->be_move_done = ctl_config_move_done;
5914		ctl_datamove((union ctl_io *)ctsio);
5915
5916		return (CTL_RETVAL_COMPLETE);
5917	}
5918
5919	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5920	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5921	if (len < sizeof (*hdr) ||
5922	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5923	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5924	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5925		ctl_set_invalid_field(ctsio,
5926				      /*sks_valid*/ 0,
5927				      /*command*/ 0,
5928				      /*field*/ 0,
5929				      /*bit_valid*/ 0,
5930				      /*bit*/ 0);
5931		goto done;
5932	}
5933	len = scsi_2btoul(hdr->desc_length);
5934	buf = (struct scsi_unmap_desc *)(hdr + 1);
5935	end = buf + len / sizeof(*buf);
5936
5937	endnz = buf;
5938	for (range = buf; range < end; range++) {
5939		lba = scsi_8btou64(range->lba);
5940		num_blocks = scsi_4btoul(range->length);
5941		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5942		 || ((lba + num_blocks) < lba)) {
5943			ctl_set_lba_out_of_range(ctsio);
5944			ctl_done((union ctl_io *)ctsio);
5945			return (CTL_RETVAL_COMPLETE);
5946		}
5947		if (num_blocks != 0)
5948			endnz = range + 1;
5949	}
5950
5951	/*
5952	 * Block backend can not handle zero last range.
5953	 * Filter it out and return if there is nothing left.
5954	 */
5955	len = (uint8_t *)endnz - (uint8_t *)buf;
5956	if (len == 0) {
5957		ctl_set_success(ctsio);
5958		goto done;
5959	}
5960
5961	mtx_lock(&lun->lun_lock);
5962	ptrlen = (struct ctl_ptr_len_flags *)
5963	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5964	ptrlen->ptr = (void *)buf;
5965	ptrlen->len = len;
5966	ptrlen->flags = byte2;
5967	ctl_check_blocked(lun);
5968	mtx_unlock(&lun->lun_lock);
5969
5970	retval = lun->backend->config_write((union ctl_io *)ctsio);
5971	return (retval);
5972
5973done:
5974	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5975		free(ctsio->kern_data_ptr, M_CTL);
5976		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5977	}
5978	ctl_done((union ctl_io *)ctsio);
5979	return (CTL_RETVAL_COMPLETE);
5980}
5981
5982/*
5983 * Note that this function currently doesn't actually do anything inside
5984 * CTL to enforce things if the DQue bit is turned on.
5985 *
5986 * Also note that this function can't be used in the default case, because
5987 * the DQue bit isn't set in the changeable mask for the control mode page
5988 * anyway.  This is just here as an example for how to implement a page
5989 * handler, and a placeholder in case we want to allow the user to turn
5990 * tagged queueing on and off.
5991 *
5992 * The D_SENSE bit handling is functional, however, and will turn
5993 * descriptor sense on and off for a given LUN.
5994 */
5995int
5996ctl_control_page_handler(struct ctl_scsiio *ctsio,
5997			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5998{
5999	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6000	struct ctl_lun *lun;
6001	int set_ua;
6002	uint32_t initidx;
6003
6004	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6005	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6006	set_ua = 0;
6007
6008	user_cp = (struct scsi_control_page *)page_ptr;
6009	current_cp = (struct scsi_control_page *)
6010		(page_index->page_data + (page_index->page_len *
6011		CTL_PAGE_CURRENT));
6012	saved_cp = (struct scsi_control_page *)
6013		(page_index->page_data + (page_index->page_len *
6014		CTL_PAGE_SAVED));
6015
6016	mtx_lock(&lun->lun_lock);
6017	if (((current_cp->rlec & SCP_DSENSE) == 0)
6018	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6019		/*
6020		 * Descriptor sense is currently turned off and the user
6021		 * wants to turn it on.
6022		 */
6023		current_cp->rlec |= SCP_DSENSE;
6024		saved_cp->rlec |= SCP_DSENSE;
6025		lun->flags |= CTL_LUN_SENSE_DESC;
6026		set_ua = 1;
6027	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6028		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6029		/*
6030		 * Descriptor sense is currently turned on, and the user
6031		 * wants to turn it off.
6032		 */
6033		current_cp->rlec &= ~SCP_DSENSE;
6034		saved_cp->rlec &= ~SCP_DSENSE;
6035		lun->flags &= ~CTL_LUN_SENSE_DESC;
6036		set_ua = 1;
6037	}
6038	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6039	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6040		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6041		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6042		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6043		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6044		set_ua = 1;
6045	}
6046	if ((current_cp->eca_and_aen & SCP_SWP) !=
6047	    (user_cp->eca_and_aen & SCP_SWP)) {
6048		current_cp->eca_and_aen &= ~SCP_SWP;
6049		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6050		saved_cp->eca_and_aen &= ~SCP_SWP;
6051		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6052		set_ua = 1;
6053	}
6054	if (set_ua != 0)
6055		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6056	mtx_unlock(&lun->lun_lock);
6057	if (set_ua) {
6058		ctl_isc_announce_mode(lun,
6059		    ctl_get_initindex(&ctsio->io_hdr.nexus),
6060		    page_index->page_code, page_index->subpage);
6061	}
6062	return (0);
6063}
6064
6065int
6066ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6067		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6068{
6069	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6070	struct ctl_lun *lun;
6071	int set_ua;
6072	uint32_t initidx;
6073
6074	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6075	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6076	set_ua = 0;
6077
6078	user_cp = (struct scsi_caching_page *)page_ptr;
6079	current_cp = (struct scsi_caching_page *)
6080		(page_index->page_data + (page_index->page_len *
6081		CTL_PAGE_CURRENT));
6082	saved_cp = (struct scsi_caching_page *)
6083		(page_index->page_data + (page_index->page_len *
6084		CTL_PAGE_SAVED));
6085
6086	mtx_lock(&lun->lun_lock);
6087	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6088	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6089		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6090		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6091		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6092		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6093		set_ua = 1;
6094	}
6095	if (set_ua != 0)
6096		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6097	mtx_unlock(&lun->lun_lock);
6098	if (set_ua) {
6099		ctl_isc_announce_mode(lun,
6100		    ctl_get_initindex(&ctsio->io_hdr.nexus),
6101		    page_index->page_code, page_index->subpage);
6102	}
6103	return (0);
6104}
6105
6106int
6107ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6108				struct ctl_page_index *page_index,
6109				uint8_t *page_ptr)
6110{
6111	uint8_t *c;
6112	int i;
6113
6114	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6115	ctl_time_io_secs =
6116		(c[0] << 8) |
6117		(c[1] << 0) |
6118		0;
6119	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6120	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6121	printf("page data:");
6122	for (i=0; i<8; i++)
6123		printf(" %.2x",page_ptr[i]);
6124	printf("\n");
6125	return (0);
6126}
6127
6128int
6129ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6130			       struct ctl_page_index *page_index,
6131			       int pc)
6132{
6133	struct copan_debugconf_subpage *page;
6134
6135	page = (struct copan_debugconf_subpage *)page_index->page_data +
6136		(page_index->page_len * pc);
6137
6138	switch (pc) {
6139	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6140	case SMS_PAGE_CTRL_DEFAULT >> 6:
6141	case SMS_PAGE_CTRL_SAVED >> 6:
6142		/*
6143		 * We don't update the changable or default bits for this page.
6144		 */
6145		break;
6146	case SMS_PAGE_CTRL_CURRENT >> 6:
6147		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6148		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6149		break;
6150	default:
6151#ifdef NEEDTOPORT
6152		EPRINT(0, "Invalid PC %d!!", pc);
6153#endif /* NEEDTOPORT */
6154		break;
6155	}
6156	return (0);
6157}
6158
6159
6160static int
6161ctl_do_mode_select(union ctl_io *io)
6162{
6163	struct scsi_mode_page_header *page_header;
6164	struct ctl_page_index *page_index;
6165	struct ctl_scsiio *ctsio;
6166	int control_dev, page_len;
6167	int page_len_offset, page_len_size;
6168	union ctl_modepage_info *modepage_info;
6169	struct ctl_lun *lun;
6170	int *len_left, *len_used;
6171	int retval, i;
6172
6173	ctsio = &io->scsiio;
6174	page_index = NULL;
6175	page_len = 0;
6176	retval = CTL_RETVAL_COMPLETE;
6177
6178	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6179
6180	if (lun->be_lun->lun_type != T_DIRECT)
6181		control_dev = 1;
6182	else
6183		control_dev = 0;
6184
6185	modepage_info = (union ctl_modepage_info *)
6186		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6187	len_left = &modepage_info->header.len_left;
6188	len_used = &modepage_info->header.len_used;
6189
6190do_next_page:
6191
6192	page_header = (struct scsi_mode_page_header *)
6193		(ctsio->kern_data_ptr + *len_used);
6194
6195	if (*len_left == 0) {
6196		free(ctsio->kern_data_ptr, M_CTL);
6197		ctl_set_success(ctsio);
6198		ctl_done((union ctl_io *)ctsio);
6199		return (CTL_RETVAL_COMPLETE);
6200	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6201
6202		free(ctsio->kern_data_ptr, M_CTL);
6203		ctl_set_param_len_error(ctsio);
6204		ctl_done((union ctl_io *)ctsio);
6205		return (CTL_RETVAL_COMPLETE);
6206
6207	} else if ((page_header->page_code & SMPH_SPF)
6208		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6209
6210		free(ctsio->kern_data_ptr, M_CTL);
6211		ctl_set_param_len_error(ctsio);
6212		ctl_done((union ctl_io *)ctsio);
6213		return (CTL_RETVAL_COMPLETE);
6214	}
6215
6216
6217	/*
6218	 * XXX KDM should we do something with the block descriptor?
6219	 */
6220	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6221
6222		if ((control_dev != 0)
6223		 && (lun->mode_pages.index[i].page_flags &
6224		     CTL_PAGE_FLAG_DISK_ONLY))
6225			continue;
6226
6227		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6228		    (page_header->page_code & SMPH_PC_MASK))
6229			continue;
6230
6231		/*
6232		 * If neither page has a subpage code, then we've got a
6233		 * match.
6234		 */
6235		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6236		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6237			page_index = &lun->mode_pages.index[i];
6238			page_len = page_header->page_length;
6239			break;
6240		}
6241
6242		/*
6243		 * If both pages have subpages, then the subpage numbers
6244		 * have to match.
6245		 */
6246		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6247		  && (page_header->page_code & SMPH_SPF)) {
6248			struct scsi_mode_page_header_sp *sph;
6249
6250			sph = (struct scsi_mode_page_header_sp *)page_header;
6251
6252			if (lun->mode_pages.index[i].subpage ==
6253			    sph->subpage) {
6254				page_index = &lun->mode_pages.index[i];
6255				page_len = scsi_2btoul(sph->page_length);
6256				break;
6257			}
6258		}
6259	}
6260
6261	/*
6262	 * If we couldn't find the page, or if we don't have a mode select
6263	 * handler for it, send back an error to the user.
6264	 */
6265	if ((page_index == NULL)
6266	 || (page_index->select_handler == NULL)) {
6267		ctl_set_invalid_field(ctsio,
6268				      /*sks_valid*/ 1,
6269				      /*command*/ 0,
6270				      /*field*/ *len_used,
6271				      /*bit_valid*/ 0,
6272				      /*bit*/ 0);
6273		free(ctsio->kern_data_ptr, M_CTL);
6274		ctl_done((union ctl_io *)ctsio);
6275		return (CTL_RETVAL_COMPLETE);
6276	}
6277
6278	if (page_index->page_code & SMPH_SPF) {
6279		page_len_offset = 2;
6280		page_len_size = 2;
6281	} else {
6282		page_len_size = 1;
6283		page_len_offset = 1;
6284	}
6285
6286	/*
6287	 * If the length the initiator gives us isn't the one we specify in
6288	 * the mode page header, or if they didn't specify enough data in
6289	 * the CDB to avoid truncating this page, kick out the request.
6290	 */
6291	if ((page_len != (page_index->page_len - page_len_offset -
6292			  page_len_size))
6293	 || (*len_left < page_index->page_len)) {
6294
6295
6296		ctl_set_invalid_field(ctsio,
6297				      /*sks_valid*/ 1,
6298				      /*command*/ 0,
6299				      /*field*/ *len_used + page_len_offset,
6300				      /*bit_valid*/ 0,
6301				      /*bit*/ 0);
6302		free(ctsio->kern_data_ptr, M_CTL);
6303		ctl_done((union ctl_io *)ctsio);
6304		return (CTL_RETVAL_COMPLETE);
6305	}
6306
6307	/*
6308	 * Run through the mode page, checking to make sure that the bits
6309	 * the user changed are actually legal for him to change.
6310	 */
6311	for (i = 0; i < page_index->page_len; i++) {
6312		uint8_t *user_byte, *change_mask, *current_byte;
6313		int bad_bit;
6314		int j;
6315
6316		user_byte = (uint8_t *)page_header + i;
6317		change_mask = page_index->page_data +
6318			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6319		current_byte = page_index->page_data +
6320			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6321
6322		/*
6323		 * Check to see whether the user set any bits in this byte
6324		 * that he is not allowed to set.
6325		 */
6326		if ((*user_byte & ~(*change_mask)) ==
6327		    (*current_byte & ~(*change_mask)))
6328			continue;
6329
6330		/*
6331		 * Go through bit by bit to determine which one is illegal.
6332		 */
6333		bad_bit = 0;
6334		for (j = 7; j >= 0; j--) {
6335			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6336			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6337				bad_bit = i;
6338				break;
6339			}
6340		}
6341		ctl_set_invalid_field(ctsio,
6342				      /*sks_valid*/ 1,
6343				      /*command*/ 0,
6344				      /*field*/ *len_used + i,
6345				      /*bit_valid*/ 1,
6346				      /*bit*/ bad_bit);
6347		free(ctsio->kern_data_ptr, M_CTL);
6348		ctl_done((union ctl_io *)ctsio);
6349		return (CTL_RETVAL_COMPLETE);
6350	}
6351
6352	/*
6353	 * Decrement these before we call the page handler, since we may
6354	 * end up getting called back one way or another before the handler
6355	 * returns to this context.
6356	 */
6357	*len_left -= page_index->page_len;
6358	*len_used += page_index->page_len;
6359
6360	retval = page_index->select_handler(ctsio, page_index,
6361					    (uint8_t *)page_header);
6362
6363	/*
6364	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6365	 * wait until this queued command completes to finish processing
6366	 * the mode page.  If it returns anything other than
6367	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6368	 * already set the sense information, freed the data pointer, and
6369	 * completed the io for us.
6370	 */
6371	if (retval != CTL_RETVAL_COMPLETE)
6372		goto bailout_no_done;
6373
6374	/*
6375	 * If the initiator sent us more than one page, parse the next one.
6376	 */
6377	if (*len_left > 0)
6378		goto do_next_page;
6379
6380	ctl_set_success(ctsio);
6381	free(ctsio->kern_data_ptr, M_CTL);
6382	ctl_done((union ctl_io *)ctsio);
6383
6384bailout_no_done:
6385
6386	return (CTL_RETVAL_COMPLETE);
6387
6388}
6389
6390int
6391ctl_mode_select(struct ctl_scsiio *ctsio)
6392{
6393	int param_len, pf, sp;
6394	int header_size, bd_len;
6395	int len_left, len_used;
6396	struct ctl_page_index *page_index;
6397	struct ctl_lun *lun;
6398	int control_dev, page_len;
6399	union ctl_modepage_info *modepage_info;
6400	int retval;
6401
6402	pf = 0;
6403	sp = 0;
6404	page_len = 0;
6405	len_used = 0;
6406	len_left = 0;
6407	retval = 0;
6408	bd_len = 0;
6409	page_index = NULL;
6410
6411	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6412
6413	if (lun->be_lun->lun_type != T_DIRECT)
6414		control_dev = 1;
6415	else
6416		control_dev = 0;
6417
6418	switch (ctsio->cdb[0]) {
6419	case MODE_SELECT_6: {
6420		struct scsi_mode_select_6 *cdb;
6421
6422		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6423
6424		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6425		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6426
6427		param_len = cdb->length;
6428		header_size = sizeof(struct scsi_mode_header_6);
6429		break;
6430	}
6431	case MODE_SELECT_10: {
6432		struct scsi_mode_select_10 *cdb;
6433
6434		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6435
6436		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6437		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6438
6439		param_len = scsi_2btoul(cdb->length);
6440		header_size = sizeof(struct scsi_mode_header_10);
6441		break;
6442	}
6443	default:
6444		ctl_set_invalid_opcode(ctsio);
6445		ctl_done((union ctl_io *)ctsio);
6446		return (CTL_RETVAL_COMPLETE);
6447		break; /* NOTREACHED */
6448	}
6449
6450	/*
6451	 * From SPC-3:
6452	 * "A parameter list length of zero indicates that the Data-Out Buffer
6453	 * shall be empty. This condition shall not be considered as an error."
6454	 */
6455	if (param_len == 0) {
6456		ctl_set_success(ctsio);
6457		ctl_done((union ctl_io *)ctsio);
6458		return (CTL_RETVAL_COMPLETE);
6459	}
6460
6461	/*
6462	 * Since we'll hit this the first time through, prior to
6463	 * allocation, we don't need to free a data buffer here.
6464	 */
6465	if (param_len < header_size) {
6466		ctl_set_param_len_error(ctsio);
6467		ctl_done((union ctl_io *)ctsio);
6468		return (CTL_RETVAL_COMPLETE);
6469	}
6470
6471	/*
6472	 * Allocate the data buffer and grab the user's data.  In theory,
6473	 * we shouldn't have to sanity check the parameter list length here
6474	 * because the maximum size is 64K.  We should be able to malloc
6475	 * that much without too many problems.
6476	 */
6477	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6478		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6479		ctsio->kern_data_len = param_len;
6480		ctsio->kern_total_len = param_len;
6481		ctsio->kern_data_resid = 0;
6482		ctsio->kern_rel_offset = 0;
6483		ctsio->kern_sg_entries = 0;
6484		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6485		ctsio->be_move_done = ctl_config_move_done;
6486		ctl_datamove((union ctl_io *)ctsio);
6487
6488		return (CTL_RETVAL_COMPLETE);
6489	}
6490
6491	switch (ctsio->cdb[0]) {
6492	case MODE_SELECT_6: {
6493		struct scsi_mode_header_6 *mh6;
6494
6495		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6496		bd_len = mh6->blk_desc_len;
6497		break;
6498	}
6499	case MODE_SELECT_10: {
6500		struct scsi_mode_header_10 *mh10;
6501
6502		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6503		bd_len = scsi_2btoul(mh10->blk_desc_len);
6504		break;
6505	}
6506	default:
6507		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6508		break;
6509	}
6510
6511	if (param_len < (header_size + bd_len)) {
6512		free(ctsio->kern_data_ptr, M_CTL);
6513		ctl_set_param_len_error(ctsio);
6514		ctl_done((union ctl_io *)ctsio);
6515		return (CTL_RETVAL_COMPLETE);
6516	}
6517
6518	/*
6519	 * Set the IO_CONT flag, so that if this I/O gets passed to
6520	 * ctl_config_write_done(), it'll get passed back to
6521	 * ctl_do_mode_select() for further processing, or completion if
6522	 * we're all done.
6523	 */
6524	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6525	ctsio->io_cont = ctl_do_mode_select;
6526
6527	modepage_info = (union ctl_modepage_info *)
6528		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6529
6530	memset(modepage_info, 0, sizeof(*modepage_info));
6531
6532	len_left = param_len - header_size - bd_len;
6533	len_used = header_size + bd_len;
6534
6535	modepage_info->header.len_left = len_left;
6536	modepage_info->header.len_used = len_used;
6537
6538	return (ctl_do_mode_select((union ctl_io *)ctsio));
6539}
6540
6541int
6542ctl_mode_sense(struct ctl_scsiio *ctsio)
6543{
6544	struct ctl_lun *lun;
6545	int pc, page_code, dbd, llba, subpage;
6546	int alloc_len, page_len, header_len, total_len;
6547	struct scsi_mode_block_descr *block_desc;
6548	struct ctl_page_index *page_index;
6549	int control_dev;
6550
6551	dbd = 0;
6552	llba = 0;
6553	block_desc = NULL;
6554	page_index = NULL;
6555
6556	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6557
6558	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6559
6560	if (lun->be_lun->lun_type != T_DIRECT)
6561		control_dev = 1;
6562	else
6563		control_dev = 0;
6564
6565	switch (ctsio->cdb[0]) {
6566	case MODE_SENSE_6: {
6567		struct scsi_mode_sense_6 *cdb;
6568
6569		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6570
6571		header_len = sizeof(struct scsi_mode_hdr_6);
6572		if (cdb->byte2 & SMS_DBD)
6573			dbd = 1;
6574		else
6575			header_len += sizeof(struct scsi_mode_block_descr);
6576
6577		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6578		page_code = cdb->page & SMS_PAGE_CODE;
6579		subpage = cdb->subpage;
6580		alloc_len = cdb->length;
6581		break;
6582	}
6583	case MODE_SENSE_10: {
6584		struct scsi_mode_sense_10 *cdb;
6585
6586		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6587
6588		header_len = sizeof(struct scsi_mode_hdr_10);
6589
6590		if (cdb->byte2 & SMS_DBD)
6591			dbd = 1;
6592		else
6593			header_len += sizeof(struct scsi_mode_block_descr);
6594		if (cdb->byte2 & SMS10_LLBAA)
6595			llba = 1;
6596		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6597		page_code = cdb->page & SMS_PAGE_CODE;
6598		subpage = cdb->subpage;
6599		alloc_len = scsi_2btoul(cdb->length);
6600		break;
6601	}
6602	default:
6603		ctl_set_invalid_opcode(ctsio);
6604		ctl_done((union ctl_io *)ctsio);
6605		return (CTL_RETVAL_COMPLETE);
6606		break; /* NOTREACHED */
6607	}
6608
6609	/*
6610	 * We have to make a first pass through to calculate the size of
6611	 * the pages that match the user's query.  Then we allocate enough
6612	 * memory to hold it, and actually copy the data into the buffer.
6613	 */
6614	switch (page_code) {
6615	case SMS_ALL_PAGES_PAGE: {
6616		int i;
6617
6618		page_len = 0;
6619
6620		/*
6621		 * At the moment, values other than 0 and 0xff here are
6622		 * reserved according to SPC-3.
6623		 */
6624		if ((subpage != SMS_SUBPAGE_PAGE_0)
6625		 && (subpage != SMS_SUBPAGE_ALL)) {
6626			ctl_set_invalid_field(ctsio,
6627					      /*sks_valid*/ 1,
6628					      /*command*/ 1,
6629					      /*field*/ 3,
6630					      /*bit_valid*/ 0,
6631					      /*bit*/ 0);
6632			ctl_done((union ctl_io *)ctsio);
6633			return (CTL_RETVAL_COMPLETE);
6634		}
6635
6636		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6637			if ((control_dev != 0)
6638			 && (lun->mode_pages.index[i].page_flags &
6639			     CTL_PAGE_FLAG_DISK_ONLY))
6640				continue;
6641
6642			/*
6643			 * We don't use this subpage if the user didn't
6644			 * request all subpages.
6645			 */
6646			if ((lun->mode_pages.index[i].subpage != 0)
6647			 && (subpage == SMS_SUBPAGE_PAGE_0))
6648				continue;
6649
6650#if 0
6651			printf("found page %#x len %d\n",
6652			       lun->mode_pages.index[i].page_code &
6653			       SMPH_PC_MASK,
6654			       lun->mode_pages.index[i].page_len);
6655#endif
6656			page_len += lun->mode_pages.index[i].page_len;
6657		}
6658		break;
6659	}
6660	default: {
6661		int i;
6662
6663		page_len = 0;
6664
6665		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6666			/* Look for the right page code */
6667			if ((lun->mode_pages.index[i].page_code &
6668			     SMPH_PC_MASK) != page_code)
6669				continue;
6670
6671			/* Look for the right subpage or the subpage wildcard*/
6672			if ((lun->mode_pages.index[i].subpage != subpage)
6673			 && (subpage != SMS_SUBPAGE_ALL))
6674				continue;
6675
6676			/* Make sure the page is supported for this dev type */
6677			if ((control_dev != 0)
6678			 && (lun->mode_pages.index[i].page_flags &
6679			     CTL_PAGE_FLAG_DISK_ONLY))
6680				continue;
6681
6682#if 0
6683			printf("found page %#x len %d\n",
6684			       lun->mode_pages.index[i].page_code &
6685			       SMPH_PC_MASK,
6686			       lun->mode_pages.index[i].page_len);
6687#endif
6688
6689			page_len += lun->mode_pages.index[i].page_len;
6690		}
6691
6692		if (page_len == 0) {
6693			ctl_set_invalid_field(ctsio,
6694					      /*sks_valid*/ 1,
6695					      /*command*/ 1,
6696					      /*field*/ 2,
6697					      /*bit_valid*/ 1,
6698					      /*bit*/ 5);
6699			ctl_done((union ctl_io *)ctsio);
6700			return (CTL_RETVAL_COMPLETE);
6701		}
6702		break;
6703	}
6704	}
6705
6706	total_len = header_len + page_len;
6707#if 0
6708	printf("header_len = %d, page_len = %d, total_len = %d\n",
6709	       header_len, page_len, total_len);
6710#endif
6711
6712	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6713	ctsio->kern_sg_entries = 0;
6714	ctsio->kern_data_resid = 0;
6715	ctsio->kern_rel_offset = 0;
6716	if (total_len < alloc_len) {
6717		ctsio->residual = alloc_len - total_len;
6718		ctsio->kern_data_len = total_len;
6719		ctsio->kern_total_len = total_len;
6720	} else {
6721		ctsio->residual = 0;
6722		ctsio->kern_data_len = alloc_len;
6723		ctsio->kern_total_len = alloc_len;
6724	}
6725
6726	switch (ctsio->cdb[0]) {
6727	case MODE_SENSE_6: {
6728		struct scsi_mode_hdr_6 *header;
6729
6730		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6731
6732		header->datalen = MIN(total_len - 1, 254);
6733		if (control_dev == 0) {
6734			header->dev_specific = 0x10; /* DPOFUA */
6735			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6736			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6737			    .eca_and_aen & SCP_SWP) != 0)
6738				    header->dev_specific |= 0x80; /* WP */
6739		}
6740		if (dbd)
6741			header->block_descr_len = 0;
6742		else
6743			header->block_descr_len =
6744				sizeof(struct scsi_mode_block_descr);
6745		block_desc = (struct scsi_mode_block_descr *)&header[1];
6746		break;
6747	}
6748	case MODE_SENSE_10: {
6749		struct scsi_mode_hdr_10 *header;
6750		int datalen;
6751
6752		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6753
6754		datalen = MIN(total_len - 2, 65533);
6755		scsi_ulto2b(datalen, header->datalen);
6756		if (control_dev == 0) {
6757			header->dev_specific = 0x10; /* DPOFUA */
6758			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6759			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6760			    .eca_and_aen & SCP_SWP) != 0)
6761				    header->dev_specific |= 0x80; /* WP */
6762		}
6763		if (dbd)
6764			scsi_ulto2b(0, header->block_descr_len);
6765		else
6766			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6767				    header->block_descr_len);
6768		block_desc = (struct scsi_mode_block_descr *)&header[1];
6769		break;
6770	}
6771	default:
6772		panic("invalid CDB type %#x", ctsio->cdb[0]);
6773		break; /* NOTREACHED */
6774	}
6775
6776	/*
6777	 * If we've got a disk, use its blocksize in the block
6778	 * descriptor.  Otherwise, just set it to 0.
6779	 */
6780	if (dbd == 0) {
6781		if (control_dev == 0)
6782			scsi_ulto3b(lun->be_lun->blocksize,
6783				    block_desc->block_len);
6784		else
6785			scsi_ulto3b(0, block_desc->block_len);
6786	}
6787
6788	switch (page_code) {
6789	case SMS_ALL_PAGES_PAGE: {
6790		int i, data_used;
6791
6792		data_used = header_len;
6793		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6794			struct ctl_page_index *page_index;
6795
6796			page_index = &lun->mode_pages.index[i];
6797
6798			if ((control_dev != 0)
6799			 && (page_index->page_flags &
6800			    CTL_PAGE_FLAG_DISK_ONLY))
6801				continue;
6802
6803			/*
6804			 * We don't use this subpage if the user didn't
6805			 * request all subpages.  We already checked (above)
6806			 * to make sure the user only specified a subpage
6807			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6808			 */
6809			if ((page_index->subpage != 0)
6810			 && (subpage == SMS_SUBPAGE_PAGE_0))
6811				continue;
6812
6813			/*
6814			 * Call the handler, if it exists, to update the
6815			 * page to the latest values.
6816			 */
6817			if (page_index->sense_handler != NULL)
6818				page_index->sense_handler(ctsio, page_index,pc);
6819
6820			memcpy(ctsio->kern_data_ptr + data_used,
6821			       page_index->page_data +
6822			       (page_index->page_len * pc),
6823			       page_index->page_len);
6824			data_used += page_index->page_len;
6825		}
6826		break;
6827	}
6828	default: {
6829		int i, data_used;
6830
6831		data_used = header_len;
6832
6833		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6834			struct ctl_page_index *page_index;
6835
6836			page_index = &lun->mode_pages.index[i];
6837
6838			/* Look for the right page code */
6839			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6840				continue;
6841
6842			/* Look for the right subpage or the subpage wildcard*/
6843			if ((page_index->subpage != subpage)
6844			 && (subpage != SMS_SUBPAGE_ALL))
6845				continue;
6846
6847			/* Make sure the page is supported for this dev type */
6848			if ((control_dev != 0)
6849			 && (page_index->page_flags &
6850			     CTL_PAGE_FLAG_DISK_ONLY))
6851				continue;
6852
6853			/*
6854			 * Call the handler, if it exists, to update the
6855			 * page to the latest values.
6856			 */
6857			if (page_index->sense_handler != NULL)
6858				page_index->sense_handler(ctsio, page_index,pc);
6859
6860			memcpy(ctsio->kern_data_ptr + data_used,
6861			       page_index->page_data +
6862			       (page_index->page_len * pc),
6863			       page_index->page_len);
6864			data_used += page_index->page_len;
6865		}
6866		break;
6867	}
6868	}
6869
6870	ctl_set_success(ctsio);
6871	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6872	ctsio->be_move_done = ctl_config_move_done;
6873	ctl_datamove((union ctl_io *)ctsio);
6874	return (CTL_RETVAL_COMPLETE);
6875}
6876
6877int
6878ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6879			       struct ctl_page_index *page_index,
6880			       int pc)
6881{
6882	struct ctl_lun *lun;
6883	struct scsi_log_param_header *phdr;
6884	uint8_t *data;
6885	uint64_t val;
6886
6887	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6888	data = page_index->page_data;
6889
6890	if (lun->backend->lun_attr != NULL &&
6891	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6892	     != UINT64_MAX) {
6893		phdr = (struct scsi_log_param_header *)data;
6894		scsi_ulto2b(0x0001, phdr->param_code);
6895		phdr->param_control = SLP_LBIN | SLP_LP;
6896		phdr->param_len = 8;
6897		data = (uint8_t *)(phdr + 1);
6898		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6899		data[4] = 0x02; /* per-pool */
6900		data += phdr->param_len;
6901	}
6902
6903	if (lun->backend->lun_attr != NULL &&
6904	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6905	     != UINT64_MAX) {
6906		phdr = (struct scsi_log_param_header *)data;
6907		scsi_ulto2b(0x0002, phdr->param_code);
6908		phdr->param_control = SLP_LBIN | SLP_LP;
6909		phdr->param_len = 8;
6910		data = (uint8_t *)(phdr + 1);
6911		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6912		data[4] = 0x01; /* per-LUN */
6913		data += phdr->param_len;
6914	}
6915
6916	if (lun->backend->lun_attr != NULL &&
6917	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6918	     != UINT64_MAX) {
6919		phdr = (struct scsi_log_param_header *)data;
6920		scsi_ulto2b(0x00f1, phdr->param_code);
6921		phdr->param_control = SLP_LBIN | SLP_LP;
6922		phdr->param_len = 8;
6923		data = (uint8_t *)(phdr + 1);
6924		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6925		data[4] = 0x02; /* per-pool */
6926		data += phdr->param_len;
6927	}
6928
6929	if (lun->backend->lun_attr != NULL &&
6930	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6931	     != UINT64_MAX) {
6932		phdr = (struct scsi_log_param_header *)data;
6933		scsi_ulto2b(0x00f2, phdr->param_code);
6934		phdr->param_control = SLP_LBIN | SLP_LP;
6935		phdr->param_len = 8;
6936		data = (uint8_t *)(phdr + 1);
6937		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6938		data[4] = 0x02; /* per-pool */
6939		data += phdr->param_len;
6940	}
6941
6942	page_index->page_len = data - page_index->page_data;
6943	return (0);
6944}
6945
6946int
6947ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6948			       struct ctl_page_index *page_index,
6949			       int pc)
6950{
6951	struct ctl_lun *lun;
6952	struct stat_page *data;
6953	uint64_t rn, wn, rb, wb;
6954	struct bintime rt, wt;
6955	int i;
6956
6957	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6958	data = (struct stat_page *)page_index->page_data;
6959
6960	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6961	data->sap.hdr.param_control = SLP_LBIN;
6962	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6963	    sizeof(struct scsi_log_param_header);
6964	rn = wn = rb = wb = 0;
6965	bintime_clear(&rt);
6966	bintime_clear(&wt);
6967	for (i = 0; i < CTL_MAX_PORTS; i++) {
6968		rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6969		wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6970		rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6971		wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6972		bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6973		bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6974	}
6975	scsi_u64to8b(rn, data->sap.read_num);
6976	scsi_u64to8b(wn, data->sap.write_num);
6977	if (lun->stats.blocksize > 0) {
6978		scsi_u64to8b(wb / lun->stats.blocksize,
6979		    data->sap.recvieved_lba);
6980		scsi_u64to8b(rb / lun->stats.blocksize,
6981		    data->sap.transmitted_lba);
6982	}
6983	scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6984	    data->sap.read_int);
6985	scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6986	    data->sap.write_int);
6987	scsi_u64to8b(0, data->sap.weighted_num);
6988	scsi_u64to8b(0, data->sap.weighted_int);
6989	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6990	data->it.hdr.param_control = SLP_LBIN;
6991	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6992	    sizeof(struct scsi_log_param_header);
6993#ifdef CTL_TIME_IO
6994	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6995#endif
6996	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6997	data->it.hdr.param_control = SLP_LBIN;
6998	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6999	    sizeof(struct scsi_log_param_header);
7000	scsi_ulto4b(3, data->ti.exponent);
7001	scsi_ulto4b(1, data->ti.integer);
7002
7003	page_index->page_len = sizeof(*data);
7004	return (0);
7005}
7006
7007int
7008ctl_log_sense(struct ctl_scsiio *ctsio)
7009{
7010	struct ctl_lun *lun;
7011	int i, pc, page_code, subpage;
7012	int alloc_len, total_len;
7013	struct ctl_page_index *page_index;
7014	struct scsi_log_sense *cdb;
7015	struct scsi_log_header *header;
7016
7017	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
7018
7019	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7020	cdb = (struct scsi_log_sense *)ctsio->cdb;
7021	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
7022	page_code = cdb->page & SLS_PAGE_CODE;
7023	subpage = cdb->subpage;
7024	alloc_len = scsi_2btoul(cdb->length);
7025
7026	page_index = NULL;
7027	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
7028		page_index = &lun->log_pages.index[i];
7029
7030		/* Look for the right page code */
7031		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
7032			continue;
7033
7034		/* Look for the right subpage or the subpage wildcard*/
7035		if (page_index->subpage != subpage)
7036			continue;
7037
7038		break;
7039	}
7040	if (i >= CTL_NUM_LOG_PAGES) {
7041		ctl_set_invalid_field(ctsio,
7042				      /*sks_valid*/ 1,
7043				      /*command*/ 1,
7044				      /*field*/ 2,
7045				      /*bit_valid*/ 0,
7046				      /*bit*/ 0);
7047		ctl_done((union ctl_io *)ctsio);
7048		return (CTL_RETVAL_COMPLETE);
7049	}
7050
7051	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
7052
7053	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7054	ctsio->kern_sg_entries = 0;
7055	ctsio->kern_data_resid = 0;
7056	ctsio->kern_rel_offset = 0;
7057	if (total_len < alloc_len) {
7058		ctsio->residual = alloc_len - total_len;
7059		ctsio->kern_data_len = total_len;
7060		ctsio->kern_total_len = total_len;
7061	} else {
7062		ctsio->residual = 0;
7063		ctsio->kern_data_len = alloc_len;
7064		ctsio->kern_total_len = alloc_len;
7065	}
7066
7067	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7068	header->page = page_index->page_code;
7069	if (page_index->subpage) {
7070		header->page |= SL_SPF;
7071		header->subpage = page_index->subpage;
7072	}
7073	scsi_ulto2b(page_index->page_len, header->datalen);
7074
7075	/*
7076	 * Call the handler, if it exists, to update the
7077	 * page to the latest values.
7078	 */
7079	if (page_index->sense_handler != NULL)
7080		page_index->sense_handler(ctsio, page_index, pc);
7081
7082	memcpy(header + 1, page_index->page_data, page_index->page_len);
7083
7084	ctl_set_success(ctsio);
7085	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7086	ctsio->be_move_done = ctl_config_move_done;
7087	ctl_datamove((union ctl_io *)ctsio);
7088	return (CTL_RETVAL_COMPLETE);
7089}
7090
7091int
7092ctl_read_capacity(struct ctl_scsiio *ctsio)
7093{
7094	struct scsi_read_capacity *cdb;
7095	struct scsi_read_capacity_data *data;
7096	struct ctl_lun *lun;
7097	uint32_t lba;
7098
7099	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7100
7101	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7102
7103	lba = scsi_4btoul(cdb->addr);
7104	if (((cdb->pmi & SRC_PMI) == 0)
7105	 && (lba != 0)) {
7106		ctl_set_invalid_field(/*ctsio*/ ctsio,
7107				      /*sks_valid*/ 1,
7108				      /*command*/ 1,
7109				      /*field*/ 2,
7110				      /*bit_valid*/ 0,
7111				      /*bit*/ 0);
7112		ctl_done((union ctl_io *)ctsio);
7113		return (CTL_RETVAL_COMPLETE);
7114	}
7115
7116	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7117
7118	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7119	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7120	ctsio->residual = 0;
7121	ctsio->kern_data_len = sizeof(*data);
7122	ctsio->kern_total_len = sizeof(*data);
7123	ctsio->kern_data_resid = 0;
7124	ctsio->kern_rel_offset = 0;
7125	ctsio->kern_sg_entries = 0;
7126
7127	/*
7128	 * If the maximum LBA is greater than 0xfffffffe, the user must
7129	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7130	 * serivce action set.
7131	 */
7132	if (lun->be_lun->maxlba > 0xfffffffe)
7133		scsi_ulto4b(0xffffffff, data->addr);
7134	else
7135		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7136
7137	/*
7138	 * XXX KDM this may not be 512 bytes...
7139	 */
7140	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7141
7142	ctl_set_success(ctsio);
7143	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7144	ctsio->be_move_done = ctl_config_move_done;
7145	ctl_datamove((union ctl_io *)ctsio);
7146	return (CTL_RETVAL_COMPLETE);
7147}
7148
7149int
7150ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7151{
7152	struct scsi_read_capacity_16 *cdb;
7153	struct scsi_read_capacity_data_long *data;
7154	struct ctl_lun *lun;
7155	uint64_t lba;
7156	uint32_t alloc_len;
7157
7158	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7159
7160	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7161
7162	alloc_len = scsi_4btoul(cdb->alloc_len);
7163	lba = scsi_8btou64(cdb->addr);
7164
7165	if ((cdb->reladr & SRC16_PMI)
7166	 && (lba != 0)) {
7167		ctl_set_invalid_field(/*ctsio*/ ctsio,
7168				      /*sks_valid*/ 1,
7169				      /*command*/ 1,
7170				      /*field*/ 2,
7171				      /*bit_valid*/ 0,
7172				      /*bit*/ 0);
7173		ctl_done((union ctl_io *)ctsio);
7174		return (CTL_RETVAL_COMPLETE);
7175	}
7176
7177	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7178
7179	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7180	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7181
7182	if (sizeof(*data) < alloc_len) {
7183		ctsio->residual = alloc_len - sizeof(*data);
7184		ctsio->kern_data_len = sizeof(*data);
7185		ctsio->kern_total_len = sizeof(*data);
7186	} else {
7187		ctsio->residual = 0;
7188		ctsio->kern_data_len = alloc_len;
7189		ctsio->kern_total_len = alloc_len;
7190	}
7191	ctsio->kern_data_resid = 0;
7192	ctsio->kern_rel_offset = 0;
7193	ctsio->kern_sg_entries = 0;
7194
7195	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7196	/* XXX KDM this may not be 512 bytes... */
7197	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7198	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7199	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7200	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7201		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7202
7203	ctl_set_success(ctsio);
7204	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7205	ctsio->be_move_done = ctl_config_move_done;
7206	ctl_datamove((union ctl_io *)ctsio);
7207	return (CTL_RETVAL_COMPLETE);
7208}
7209
7210int
7211ctl_get_lba_status(struct ctl_scsiio *ctsio)
7212{
7213	struct scsi_get_lba_status *cdb;
7214	struct scsi_get_lba_status_data *data;
7215	struct ctl_lun *lun;
7216	struct ctl_lba_len_flags *lbalen;
7217	uint64_t lba;
7218	uint32_t alloc_len, total_len;
7219	int retval;
7220
7221	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7222
7223	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7224	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7225	lba = scsi_8btou64(cdb->addr);
7226	alloc_len = scsi_4btoul(cdb->alloc_len);
7227
7228	if (lba > lun->be_lun->maxlba) {
7229		ctl_set_lba_out_of_range(ctsio);
7230		ctl_done((union ctl_io *)ctsio);
7231		return (CTL_RETVAL_COMPLETE);
7232	}
7233
7234	total_len = sizeof(*data) + sizeof(data->descr[0]);
7235	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7236	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7237
7238	if (total_len < alloc_len) {
7239		ctsio->residual = alloc_len - total_len;
7240		ctsio->kern_data_len = total_len;
7241		ctsio->kern_total_len = total_len;
7242	} else {
7243		ctsio->residual = 0;
7244		ctsio->kern_data_len = alloc_len;
7245		ctsio->kern_total_len = alloc_len;
7246	}
7247	ctsio->kern_data_resid = 0;
7248	ctsio->kern_rel_offset = 0;
7249	ctsio->kern_sg_entries = 0;
7250
7251	/* Fill dummy data in case backend can't tell anything. */
7252	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7253	scsi_u64to8b(lba, data->descr[0].addr);
7254	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7255	    data->descr[0].length);
7256	data->descr[0].status = 0; /* Mapped or unknown. */
7257
7258	ctl_set_success(ctsio);
7259	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7260	ctsio->be_move_done = ctl_config_move_done;
7261
7262	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7263	lbalen->lba = lba;
7264	lbalen->len = total_len;
7265	lbalen->flags = 0;
7266	retval = lun->backend->config_read((union ctl_io *)ctsio);
7267	return (CTL_RETVAL_COMPLETE);
7268}
7269
7270int
7271ctl_read_defect(struct ctl_scsiio *ctsio)
7272{
7273	struct scsi_read_defect_data_10 *ccb10;
7274	struct scsi_read_defect_data_12 *ccb12;
7275	struct scsi_read_defect_data_hdr_10 *data10;
7276	struct scsi_read_defect_data_hdr_12 *data12;
7277	uint32_t alloc_len, data_len;
7278	uint8_t format;
7279
7280	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7281
7282	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7283		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7284		format = ccb10->format;
7285		alloc_len = scsi_2btoul(ccb10->alloc_length);
7286		data_len = sizeof(*data10);
7287	} else {
7288		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7289		format = ccb12->format;
7290		alloc_len = scsi_4btoul(ccb12->alloc_length);
7291		data_len = sizeof(*data12);
7292	}
7293	if (alloc_len == 0) {
7294		ctl_set_success(ctsio);
7295		ctl_done((union ctl_io *)ctsio);
7296		return (CTL_RETVAL_COMPLETE);
7297	}
7298
7299	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7300	if (data_len < alloc_len) {
7301		ctsio->residual = alloc_len - data_len;
7302		ctsio->kern_data_len = data_len;
7303		ctsio->kern_total_len = data_len;
7304	} else {
7305		ctsio->residual = 0;
7306		ctsio->kern_data_len = alloc_len;
7307		ctsio->kern_total_len = alloc_len;
7308	}
7309	ctsio->kern_data_resid = 0;
7310	ctsio->kern_rel_offset = 0;
7311	ctsio->kern_sg_entries = 0;
7312
7313	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7314		data10 = (struct scsi_read_defect_data_hdr_10 *)
7315		    ctsio->kern_data_ptr;
7316		data10->format = format;
7317		scsi_ulto2b(0, data10->length);
7318	} else {
7319		data12 = (struct scsi_read_defect_data_hdr_12 *)
7320		    ctsio->kern_data_ptr;
7321		data12->format = format;
7322		scsi_ulto2b(0, data12->generation);
7323		scsi_ulto4b(0, data12->length);
7324	}
7325
7326	ctl_set_success(ctsio);
7327	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7328	ctsio->be_move_done = ctl_config_move_done;
7329	ctl_datamove((union ctl_io *)ctsio);
7330	return (CTL_RETVAL_COMPLETE);
7331}
7332
7333int
7334ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7335{
7336	struct scsi_maintenance_in *cdb;
7337	int retval;
7338	int alloc_len, ext, total_len = 0, g, pc, pg, gs, os;
7339	int num_target_port_groups, num_target_ports;
7340	struct ctl_lun *lun;
7341	struct ctl_softc *softc;
7342	struct ctl_port *port;
7343	struct scsi_target_group_data *rtg_ptr;
7344	struct scsi_target_group_data_extended *rtg_ext_ptr;
7345	struct scsi_target_port_group_descriptor *tpg_desc;
7346
7347	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7348
7349	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7350	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7351	softc = lun->ctl_softc;
7352
7353	retval = CTL_RETVAL_COMPLETE;
7354
7355	switch (cdb->byte2 & STG_PDF_MASK) {
7356	case STG_PDF_LENGTH:
7357		ext = 0;
7358		break;
7359	case STG_PDF_EXTENDED:
7360		ext = 1;
7361		break;
7362	default:
7363		ctl_set_invalid_field(/*ctsio*/ ctsio,
7364				      /*sks_valid*/ 1,
7365				      /*command*/ 1,
7366				      /*field*/ 2,
7367				      /*bit_valid*/ 1,
7368				      /*bit*/ 5);
7369		ctl_done((union ctl_io *)ctsio);
7370		return(retval);
7371	}
7372
7373	if (softc->is_single)
7374		num_target_port_groups = 1;
7375	else
7376		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7377	num_target_ports = 0;
7378	mtx_lock(&softc->ctl_lock);
7379	STAILQ_FOREACH(port, &softc->port_list, links) {
7380		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7381			continue;
7382		if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7383			continue;
7384		num_target_ports++;
7385	}
7386	mtx_unlock(&softc->ctl_lock);
7387
7388	if (ext)
7389		total_len = sizeof(struct scsi_target_group_data_extended);
7390	else
7391		total_len = sizeof(struct scsi_target_group_data);
7392	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7393		num_target_port_groups +
7394	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7395
7396	alloc_len = scsi_4btoul(cdb->length);
7397
7398	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7399
7400	ctsio->kern_sg_entries = 0;
7401
7402	if (total_len < alloc_len) {
7403		ctsio->residual = alloc_len - total_len;
7404		ctsio->kern_data_len = total_len;
7405		ctsio->kern_total_len = total_len;
7406	} else {
7407		ctsio->residual = 0;
7408		ctsio->kern_data_len = alloc_len;
7409		ctsio->kern_total_len = alloc_len;
7410	}
7411	ctsio->kern_data_resid = 0;
7412	ctsio->kern_rel_offset = 0;
7413
7414	if (ext) {
7415		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7416		    ctsio->kern_data_ptr;
7417		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7418		rtg_ext_ptr->format_type = 0x10;
7419		rtg_ext_ptr->implicit_transition_time = 0;
7420		tpg_desc = &rtg_ext_ptr->groups[0];
7421	} else {
7422		rtg_ptr = (struct scsi_target_group_data *)
7423		    ctsio->kern_data_ptr;
7424		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7425		tpg_desc = &rtg_ptr->groups[0];
7426	}
7427
7428	mtx_lock(&softc->ctl_lock);
7429	pg = softc->port_min / softc->port_cnt;
7430	if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7431		gs = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7432	else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7433		gs = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7434	else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7435		gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7436	else
7437		gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7438	if (lun->flags & CTL_LUN_PRIMARY_SC) {
7439		os = gs;
7440		gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7441	} else
7442		os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7443	for (g = 0; g < num_target_port_groups; g++) {
7444		tpg_desc->pref_state = (g == pg) ? gs : os;
7445		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7446		    TPG_U_SUP | TPG_T_SUP;
7447		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7448		tpg_desc->status = TPG_IMPLICIT;
7449		pc = 0;
7450		STAILQ_FOREACH(port, &softc->port_list, links) {
7451			if (port->targ_port < g * softc->port_cnt ||
7452			    port->targ_port >= (g + 1) * softc->port_cnt)
7453				continue;
7454			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7455				continue;
7456			if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7457				continue;
7458			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7459			    relative_target_port_identifier);
7460			pc++;
7461		}
7462		tpg_desc->target_port_count = pc;
7463		tpg_desc = (struct scsi_target_port_group_descriptor *)
7464		    &tpg_desc->descriptors[pc];
7465	}
7466	mtx_unlock(&softc->ctl_lock);
7467
7468	ctl_set_success(ctsio);
7469	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7470	ctsio->be_move_done = ctl_config_move_done;
7471	ctl_datamove((union ctl_io *)ctsio);
7472	return(retval);
7473}
7474
7475int
7476ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7477{
7478	struct ctl_lun *lun;
7479	struct scsi_report_supported_opcodes *cdb;
7480	const struct ctl_cmd_entry *entry, *sentry;
7481	struct scsi_report_supported_opcodes_all *all;
7482	struct scsi_report_supported_opcodes_descr *descr;
7483	struct scsi_report_supported_opcodes_one *one;
7484	int retval;
7485	int alloc_len, total_len;
7486	int opcode, service_action, i, j, num;
7487
7488	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7489
7490	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7491	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7492
7493	retval = CTL_RETVAL_COMPLETE;
7494
7495	opcode = cdb->requested_opcode;
7496	service_action = scsi_2btoul(cdb->requested_service_action);
7497	switch (cdb->options & RSO_OPTIONS_MASK) {
7498	case RSO_OPTIONS_ALL:
7499		num = 0;
7500		for (i = 0; i < 256; i++) {
7501			entry = &ctl_cmd_table[i];
7502			if (entry->flags & CTL_CMD_FLAG_SA5) {
7503				for (j = 0; j < 32; j++) {
7504					sentry = &((const struct ctl_cmd_entry *)
7505					    entry->execute)[j];
7506					if (ctl_cmd_applicable(
7507					    lun->be_lun->lun_type, sentry))
7508						num++;
7509				}
7510			} else {
7511				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7512				    entry))
7513					num++;
7514			}
7515		}
7516		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7517		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7518		break;
7519	case RSO_OPTIONS_OC:
7520		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7521			ctl_set_invalid_field(/*ctsio*/ ctsio,
7522					      /*sks_valid*/ 1,
7523					      /*command*/ 1,
7524					      /*field*/ 2,
7525					      /*bit_valid*/ 1,
7526					      /*bit*/ 2);
7527			ctl_done((union ctl_io *)ctsio);
7528			return (CTL_RETVAL_COMPLETE);
7529		}
7530		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7531		break;
7532	case RSO_OPTIONS_OC_SA:
7533		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7534		    service_action >= 32) {
7535			ctl_set_invalid_field(/*ctsio*/ ctsio,
7536					      /*sks_valid*/ 1,
7537					      /*command*/ 1,
7538					      /*field*/ 2,
7539					      /*bit_valid*/ 1,
7540					      /*bit*/ 2);
7541			ctl_done((union ctl_io *)ctsio);
7542			return (CTL_RETVAL_COMPLETE);
7543		}
7544		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7545		break;
7546	default:
7547		ctl_set_invalid_field(/*ctsio*/ ctsio,
7548				      /*sks_valid*/ 1,
7549				      /*command*/ 1,
7550				      /*field*/ 2,
7551				      /*bit_valid*/ 1,
7552				      /*bit*/ 2);
7553		ctl_done((union ctl_io *)ctsio);
7554		return (CTL_RETVAL_COMPLETE);
7555	}
7556
7557	alloc_len = scsi_4btoul(cdb->length);
7558
7559	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7560
7561	ctsio->kern_sg_entries = 0;
7562
7563	if (total_len < alloc_len) {
7564		ctsio->residual = alloc_len - total_len;
7565		ctsio->kern_data_len = total_len;
7566		ctsio->kern_total_len = total_len;
7567	} else {
7568		ctsio->residual = 0;
7569		ctsio->kern_data_len = alloc_len;
7570		ctsio->kern_total_len = alloc_len;
7571	}
7572	ctsio->kern_data_resid = 0;
7573	ctsio->kern_rel_offset = 0;
7574
7575	switch (cdb->options & RSO_OPTIONS_MASK) {
7576	case RSO_OPTIONS_ALL:
7577		all = (struct scsi_report_supported_opcodes_all *)
7578		    ctsio->kern_data_ptr;
7579		num = 0;
7580		for (i = 0; i < 256; i++) {
7581			entry = &ctl_cmd_table[i];
7582			if (entry->flags & CTL_CMD_FLAG_SA5) {
7583				for (j = 0; j < 32; j++) {
7584					sentry = &((const struct ctl_cmd_entry *)
7585					    entry->execute)[j];
7586					if (!ctl_cmd_applicable(
7587					    lun->be_lun->lun_type, sentry))
7588						continue;
7589					descr = &all->descr[num++];
7590					descr->opcode = i;
7591					scsi_ulto2b(j, descr->service_action);
7592					descr->flags = RSO_SERVACTV;
7593					scsi_ulto2b(sentry->length,
7594					    descr->cdb_length);
7595				}
7596			} else {
7597				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7598				    entry))
7599					continue;
7600				descr = &all->descr[num++];
7601				descr->opcode = i;
7602				scsi_ulto2b(0, descr->service_action);
7603				descr->flags = 0;
7604				scsi_ulto2b(entry->length, descr->cdb_length);
7605			}
7606		}
7607		scsi_ulto4b(
7608		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7609		    all->length);
7610		break;
7611	case RSO_OPTIONS_OC:
7612		one = (struct scsi_report_supported_opcodes_one *)
7613		    ctsio->kern_data_ptr;
7614		entry = &ctl_cmd_table[opcode];
7615		goto fill_one;
7616	case RSO_OPTIONS_OC_SA:
7617		one = (struct scsi_report_supported_opcodes_one *)
7618		    ctsio->kern_data_ptr;
7619		entry = &ctl_cmd_table[opcode];
7620		entry = &((const struct ctl_cmd_entry *)
7621		    entry->execute)[service_action];
7622fill_one:
7623		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7624			one->support = 3;
7625			scsi_ulto2b(entry->length, one->cdb_length);
7626			one->cdb_usage[0] = opcode;
7627			memcpy(&one->cdb_usage[1], entry->usage,
7628			    entry->length - 1);
7629		} else
7630			one->support = 1;
7631		break;
7632	}
7633
7634	ctl_set_success(ctsio);
7635	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7636	ctsio->be_move_done = ctl_config_move_done;
7637	ctl_datamove((union ctl_io *)ctsio);
7638	return(retval);
7639}
7640
7641int
7642ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7643{
7644	struct scsi_report_supported_tmf *cdb;
7645	struct scsi_report_supported_tmf_data *data;
7646	int retval;
7647	int alloc_len, total_len;
7648
7649	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7650
7651	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7652
7653	retval = CTL_RETVAL_COMPLETE;
7654
7655	total_len = sizeof(struct scsi_report_supported_tmf_data);
7656	alloc_len = scsi_4btoul(cdb->length);
7657
7658	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7659
7660	ctsio->kern_sg_entries = 0;
7661
7662	if (total_len < alloc_len) {
7663		ctsio->residual = alloc_len - total_len;
7664		ctsio->kern_data_len = total_len;
7665		ctsio->kern_total_len = total_len;
7666	} else {
7667		ctsio->residual = 0;
7668		ctsio->kern_data_len = alloc_len;
7669		ctsio->kern_total_len = alloc_len;
7670	}
7671	ctsio->kern_data_resid = 0;
7672	ctsio->kern_rel_offset = 0;
7673
7674	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7675	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7676	    RST_TRS;
7677	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7678
7679	ctl_set_success(ctsio);
7680	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7681	ctsio->be_move_done = ctl_config_move_done;
7682	ctl_datamove((union ctl_io *)ctsio);
7683	return (retval);
7684}
7685
7686int
7687ctl_report_timestamp(struct ctl_scsiio *ctsio)
7688{
7689	struct scsi_report_timestamp *cdb;
7690	struct scsi_report_timestamp_data *data;
7691	struct timeval tv;
7692	int64_t timestamp;
7693	int retval;
7694	int alloc_len, total_len;
7695
7696	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7697
7698	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7699
7700	retval = CTL_RETVAL_COMPLETE;
7701
7702	total_len = sizeof(struct scsi_report_timestamp_data);
7703	alloc_len = scsi_4btoul(cdb->length);
7704
7705	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7706
7707	ctsio->kern_sg_entries = 0;
7708
7709	if (total_len < alloc_len) {
7710		ctsio->residual = alloc_len - total_len;
7711		ctsio->kern_data_len = total_len;
7712		ctsio->kern_total_len = total_len;
7713	} else {
7714		ctsio->residual = 0;
7715		ctsio->kern_data_len = alloc_len;
7716		ctsio->kern_total_len = alloc_len;
7717	}
7718	ctsio->kern_data_resid = 0;
7719	ctsio->kern_rel_offset = 0;
7720
7721	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7722	scsi_ulto2b(sizeof(*data) - 2, data->length);
7723	data->origin = RTS_ORIG_OUTSIDE;
7724	getmicrotime(&tv);
7725	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7726	scsi_ulto4b(timestamp >> 16, data->timestamp);
7727	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7728
7729	ctl_set_success(ctsio);
7730	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7731	ctsio->be_move_done = ctl_config_move_done;
7732	ctl_datamove((union ctl_io *)ctsio);
7733	return (retval);
7734}
7735
7736int
7737ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7738{
7739	struct scsi_per_res_in *cdb;
7740	int alloc_len, total_len = 0;
7741	/* struct scsi_per_res_in_rsrv in_data; */
7742	struct ctl_lun *lun;
7743	struct ctl_softc *softc;
7744	uint64_t key;
7745
7746	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7747
7748	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7749
7750	alloc_len = scsi_2btoul(cdb->length);
7751
7752	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7753	softc = lun->ctl_softc;
7754
7755retry:
7756	mtx_lock(&lun->lun_lock);
7757	switch (cdb->action) {
7758	case SPRI_RK: /* read keys */
7759		total_len = sizeof(struct scsi_per_res_in_keys) +
7760			lun->pr_key_count *
7761			sizeof(struct scsi_per_res_key);
7762		break;
7763	case SPRI_RR: /* read reservation */
7764		if (lun->flags & CTL_LUN_PR_RESERVED)
7765			total_len = sizeof(struct scsi_per_res_in_rsrv);
7766		else
7767			total_len = sizeof(struct scsi_per_res_in_header);
7768		break;
7769	case SPRI_RC: /* report capabilities */
7770		total_len = sizeof(struct scsi_per_res_cap);
7771		break;
7772	case SPRI_RS: /* read full status */
7773		total_len = sizeof(struct scsi_per_res_in_header) +
7774		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7775		    lun->pr_key_count;
7776		break;
7777	default:
7778		panic("Invalid PR type %x", cdb->action);
7779	}
7780	mtx_unlock(&lun->lun_lock);
7781
7782	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7783
7784	if (total_len < alloc_len) {
7785		ctsio->residual = alloc_len - total_len;
7786		ctsio->kern_data_len = total_len;
7787		ctsio->kern_total_len = total_len;
7788	} else {
7789		ctsio->residual = 0;
7790		ctsio->kern_data_len = alloc_len;
7791		ctsio->kern_total_len = alloc_len;
7792	}
7793
7794	ctsio->kern_data_resid = 0;
7795	ctsio->kern_rel_offset = 0;
7796	ctsio->kern_sg_entries = 0;
7797
7798	mtx_lock(&lun->lun_lock);
7799	switch (cdb->action) {
7800	case SPRI_RK: { // read keys
7801        struct scsi_per_res_in_keys *res_keys;
7802		int i, key_count;
7803
7804		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7805
7806		/*
7807		 * We had to drop the lock to allocate our buffer, which
7808		 * leaves time for someone to come in with another
7809		 * persistent reservation.  (That is unlikely, though,
7810		 * since this should be the only persistent reservation
7811		 * command active right now.)
7812		 */
7813		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7814		    (lun->pr_key_count *
7815		     sizeof(struct scsi_per_res_key)))){
7816			mtx_unlock(&lun->lun_lock);
7817			free(ctsio->kern_data_ptr, M_CTL);
7818			printf("%s: reservation length changed, retrying\n",
7819			       __func__);
7820			goto retry;
7821		}
7822
7823		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7824
7825		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7826			     lun->pr_key_count, res_keys->header.length);
7827
7828		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7829			if ((key = ctl_get_prkey(lun, i)) == 0)
7830				continue;
7831
7832			/*
7833			 * We used lun->pr_key_count to calculate the
7834			 * size to allocate.  If it turns out the number of
7835			 * initiators with the registered flag set is
7836			 * larger than that (i.e. they haven't been kept in
7837			 * sync), we've got a problem.
7838			 */
7839			if (key_count >= lun->pr_key_count) {
7840#ifdef NEEDTOPORT
7841				csevent_log(CSC_CTL | CSC_SHELF_SW |
7842					    CTL_PR_ERROR,
7843					    csevent_LogType_Fault,
7844					    csevent_AlertLevel_Yellow,
7845					    csevent_FRU_ShelfController,
7846					    csevent_FRU_Firmware,
7847				        csevent_FRU_Unknown,
7848					    "registered keys %d >= key "
7849					    "count %d", key_count,
7850					    lun->pr_key_count);
7851#endif
7852				key_count++;
7853				continue;
7854			}
7855			scsi_u64to8b(key, res_keys->keys[key_count].key);
7856			key_count++;
7857		}
7858		break;
7859	}
7860	case SPRI_RR: { // read reservation
7861		struct scsi_per_res_in_rsrv *res;
7862		int tmp_len, header_only;
7863
7864		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7865
7866		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7867
7868		if (lun->flags & CTL_LUN_PR_RESERVED)
7869		{
7870			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7871			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7872				    res->header.length);
7873			header_only = 0;
7874		} else {
7875			tmp_len = sizeof(struct scsi_per_res_in_header);
7876			scsi_ulto4b(0, res->header.length);
7877			header_only = 1;
7878		}
7879
7880		/*
7881		 * We had to drop the lock to allocate our buffer, which
7882		 * leaves time for someone to come in with another
7883		 * persistent reservation.  (That is unlikely, though,
7884		 * since this should be the only persistent reservation
7885		 * command active right now.)
7886		 */
7887		if (tmp_len != total_len) {
7888			mtx_unlock(&lun->lun_lock);
7889			free(ctsio->kern_data_ptr, M_CTL);
7890			printf("%s: reservation status changed, retrying\n",
7891			       __func__);
7892			goto retry;
7893		}
7894
7895		/*
7896		 * No reservation held, so we're done.
7897		 */
7898		if (header_only != 0)
7899			break;
7900
7901		/*
7902		 * If the registration is an All Registrants type, the key
7903		 * is 0, since it doesn't really matter.
7904		 */
7905		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7906			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7907			    res->data.reservation);
7908		}
7909		res->data.scopetype = lun->res_type;
7910		break;
7911	}
7912	case SPRI_RC:     //report capabilities
7913	{
7914		struct scsi_per_res_cap *res_cap;
7915		uint16_t type_mask;
7916
7917		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7918		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7919		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7920		type_mask = SPRI_TM_WR_EX_AR |
7921			    SPRI_TM_EX_AC_RO |
7922			    SPRI_TM_WR_EX_RO |
7923			    SPRI_TM_EX_AC |
7924			    SPRI_TM_WR_EX |
7925			    SPRI_TM_EX_AC_AR;
7926		scsi_ulto2b(type_mask, res_cap->type_mask);
7927		break;
7928	}
7929	case SPRI_RS: { // read full status
7930		struct scsi_per_res_in_full *res_status;
7931		struct scsi_per_res_in_full_desc *res_desc;
7932		struct ctl_port *port;
7933		int i, len;
7934
7935		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7936
7937		/*
7938		 * We had to drop the lock to allocate our buffer, which
7939		 * leaves time for someone to come in with another
7940		 * persistent reservation.  (That is unlikely, though,
7941		 * since this should be the only persistent reservation
7942		 * command active right now.)
7943		 */
7944		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7945		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7946		     lun->pr_key_count)){
7947			mtx_unlock(&lun->lun_lock);
7948			free(ctsio->kern_data_ptr, M_CTL);
7949			printf("%s: reservation length changed, retrying\n",
7950			       __func__);
7951			goto retry;
7952		}
7953
7954		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7955
7956		res_desc = &res_status->desc[0];
7957		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7958			if ((key = ctl_get_prkey(lun, i)) == 0)
7959				continue;
7960
7961			scsi_u64to8b(key, res_desc->res_key.key);
7962			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7963			    (lun->pr_res_idx == i ||
7964			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7965				res_desc->flags = SPRI_FULL_R_HOLDER;
7966				res_desc->scopetype = lun->res_type;
7967			}
7968			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7969			    res_desc->rel_trgt_port_id);
7970			len = 0;
7971			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7972			if (port != NULL)
7973				len = ctl_create_iid(port,
7974				    i % CTL_MAX_INIT_PER_PORT,
7975				    res_desc->transport_id);
7976			scsi_ulto4b(len, res_desc->additional_length);
7977			res_desc = (struct scsi_per_res_in_full_desc *)
7978			    &res_desc->transport_id[len];
7979		}
7980		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7981		    res_status->header.length);
7982		break;
7983	}
7984	default:
7985		/*
7986		 * This is a bug, because we just checked for this above,
7987		 * and should have returned an error.
7988		 */
7989		panic("Invalid PR type %x", cdb->action);
7990		break; /* NOTREACHED */
7991	}
7992	mtx_unlock(&lun->lun_lock);
7993
7994	ctl_set_success(ctsio);
7995	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7996	ctsio->be_move_done = ctl_config_move_done;
7997	ctl_datamove((union ctl_io *)ctsio);
7998	return (CTL_RETVAL_COMPLETE);
7999}
8000
8001/*
8002 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
8003 * it should return.
8004 */
8005static int
8006ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
8007		uint64_t sa_res_key, uint8_t type, uint32_t residx,
8008		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
8009		struct scsi_per_res_out_parms* param)
8010{
8011	union ctl_ha_msg persis_io;
8012	int i;
8013
8014	mtx_lock(&lun->lun_lock);
8015	if (sa_res_key == 0) {
8016		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8017			/* validate scope and type */
8018			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8019			     SPR_LU_SCOPE) {
8020				mtx_unlock(&lun->lun_lock);
8021				ctl_set_invalid_field(/*ctsio*/ ctsio,
8022						      /*sks_valid*/ 1,
8023						      /*command*/ 1,
8024						      /*field*/ 2,
8025						      /*bit_valid*/ 1,
8026						      /*bit*/ 4);
8027				ctl_done((union ctl_io *)ctsio);
8028				return (1);
8029			}
8030
8031		        if (type>8 || type==2 || type==4 || type==0) {
8032				mtx_unlock(&lun->lun_lock);
8033				ctl_set_invalid_field(/*ctsio*/ ctsio,
8034       	           				      /*sks_valid*/ 1,
8035						      /*command*/ 1,
8036						      /*field*/ 2,
8037						      /*bit_valid*/ 1,
8038						      /*bit*/ 0);
8039				ctl_done((union ctl_io *)ctsio);
8040				return (1);
8041		        }
8042
8043			/*
8044			 * Unregister everybody else and build UA for
8045			 * them
8046			 */
8047			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8048				if (i == residx || ctl_get_prkey(lun, i) == 0)
8049					continue;
8050
8051				ctl_clr_prkey(lun, i);
8052				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8053			}
8054			lun->pr_key_count = 1;
8055			lun->res_type = type;
8056			if (lun->res_type != SPR_TYPE_WR_EX_AR
8057			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8058				lun->pr_res_idx = residx;
8059			lun->PRGeneration++;
8060			mtx_unlock(&lun->lun_lock);
8061
8062			/* send msg to other side */
8063			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8064			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8065			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8066			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8067			persis_io.pr.pr_info.res_type = type;
8068			memcpy(persis_io.pr.pr_info.sa_res_key,
8069			       param->serv_act_res_key,
8070			       sizeof(param->serv_act_res_key));
8071			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8072			    sizeof(persis_io.pr), M_WAITOK);
8073		} else {
8074			/* not all registrants */
8075			mtx_unlock(&lun->lun_lock);
8076			free(ctsio->kern_data_ptr, M_CTL);
8077			ctl_set_invalid_field(ctsio,
8078					      /*sks_valid*/ 1,
8079					      /*command*/ 0,
8080					      /*field*/ 8,
8081					      /*bit_valid*/ 0,
8082					      /*bit*/ 0);
8083			ctl_done((union ctl_io *)ctsio);
8084			return (1);
8085		}
8086	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8087		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8088		int found = 0;
8089
8090		if (res_key == sa_res_key) {
8091			/* special case */
8092			/*
8093			 * The spec implies this is not good but doesn't
8094			 * say what to do. There are two choices either
8095			 * generate a res conflict or check condition
8096			 * with illegal field in parameter data. Since
8097			 * that is what is done when the sa_res_key is
8098			 * zero I'll take that approach since this has
8099			 * to do with the sa_res_key.
8100			 */
8101			mtx_unlock(&lun->lun_lock);
8102			free(ctsio->kern_data_ptr, M_CTL);
8103			ctl_set_invalid_field(ctsio,
8104					      /*sks_valid*/ 1,
8105					      /*command*/ 0,
8106					      /*field*/ 8,
8107					      /*bit_valid*/ 0,
8108					      /*bit*/ 0);
8109			ctl_done((union ctl_io *)ctsio);
8110			return (1);
8111		}
8112
8113		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8114			if (ctl_get_prkey(lun, i) != sa_res_key)
8115				continue;
8116
8117			found = 1;
8118			ctl_clr_prkey(lun, i);
8119			lun->pr_key_count--;
8120			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8121		}
8122		if (!found) {
8123			mtx_unlock(&lun->lun_lock);
8124			free(ctsio->kern_data_ptr, M_CTL);
8125			ctl_set_reservation_conflict(ctsio);
8126			ctl_done((union ctl_io *)ctsio);
8127			return (CTL_RETVAL_COMPLETE);
8128		}
8129		lun->PRGeneration++;
8130		mtx_unlock(&lun->lun_lock);
8131
8132		/* send msg to other side */
8133		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8134		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8135		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8136		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8137		persis_io.pr.pr_info.res_type = type;
8138		memcpy(persis_io.pr.pr_info.sa_res_key,
8139		       param->serv_act_res_key,
8140		       sizeof(param->serv_act_res_key));
8141		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8142		    sizeof(persis_io.pr), M_WAITOK);
8143	} else {
8144		/* Reserved but not all registrants */
8145		/* sa_res_key is res holder */
8146		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
8147			/* validate scope and type */
8148			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8149			     SPR_LU_SCOPE) {
8150				mtx_unlock(&lun->lun_lock);
8151				ctl_set_invalid_field(/*ctsio*/ ctsio,
8152						      /*sks_valid*/ 1,
8153						      /*command*/ 1,
8154						      /*field*/ 2,
8155						      /*bit_valid*/ 1,
8156						      /*bit*/ 4);
8157				ctl_done((union ctl_io *)ctsio);
8158				return (1);
8159			}
8160
8161			if (type>8 || type==2 || type==4 || type==0) {
8162				mtx_unlock(&lun->lun_lock);
8163				ctl_set_invalid_field(/*ctsio*/ ctsio,
8164						      /*sks_valid*/ 1,
8165						      /*command*/ 1,
8166						      /*field*/ 2,
8167						      /*bit_valid*/ 1,
8168						      /*bit*/ 0);
8169				ctl_done((union ctl_io *)ctsio);
8170				return (1);
8171			}
8172
8173			/*
8174			 * Do the following:
8175			 * if sa_res_key != res_key remove all
8176			 * registrants w/sa_res_key and generate UA
8177			 * for these registrants(Registrations
8178			 * Preempted) if it wasn't an exclusive
8179			 * reservation generate UA(Reservations
8180			 * Preempted) for all other registered nexuses
8181			 * if the type has changed. Establish the new
8182			 * reservation and holder. If res_key and
8183			 * sa_res_key are the same do the above
8184			 * except don't unregister the res holder.
8185			 */
8186
8187			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8188				if (i == residx || ctl_get_prkey(lun, i) == 0)
8189					continue;
8190
8191				if (sa_res_key == ctl_get_prkey(lun, i)) {
8192					ctl_clr_prkey(lun, i);
8193					lun->pr_key_count--;
8194					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8195				} else if (type != lun->res_type
8196					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8197					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8198					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8199				}
8200			}
8201			lun->res_type = type;
8202			if (lun->res_type != SPR_TYPE_WR_EX_AR
8203			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8204				lun->pr_res_idx = residx;
8205			else
8206				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8207			lun->PRGeneration++;
8208			mtx_unlock(&lun->lun_lock);
8209
8210			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8211			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8212			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8213			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8214			persis_io.pr.pr_info.res_type = type;
8215			memcpy(persis_io.pr.pr_info.sa_res_key,
8216			       param->serv_act_res_key,
8217			       sizeof(param->serv_act_res_key));
8218			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8219			    sizeof(persis_io.pr), M_WAITOK);
8220		} else {
8221			/*
8222			 * sa_res_key is not the res holder just
8223			 * remove registrants
8224			 */
8225			int found=0;
8226
8227			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8228				if (sa_res_key != ctl_get_prkey(lun, i))
8229					continue;
8230
8231				found = 1;
8232				ctl_clr_prkey(lun, i);
8233				lun->pr_key_count--;
8234				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8235			}
8236
8237			if (!found) {
8238				mtx_unlock(&lun->lun_lock);
8239				free(ctsio->kern_data_ptr, M_CTL);
8240				ctl_set_reservation_conflict(ctsio);
8241				ctl_done((union ctl_io *)ctsio);
8242		        	return (1);
8243			}
8244			lun->PRGeneration++;
8245			mtx_unlock(&lun->lun_lock);
8246
8247			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8248			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8249			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8250			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8251			persis_io.pr.pr_info.res_type = type;
8252			memcpy(persis_io.pr.pr_info.sa_res_key,
8253			       param->serv_act_res_key,
8254			       sizeof(param->serv_act_res_key));
8255			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8256			    sizeof(persis_io.pr), M_WAITOK);
8257		}
8258	}
8259	return (0);
8260}
8261
8262static void
8263ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8264{
8265	uint64_t sa_res_key;
8266	int i;
8267
8268	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8269
8270	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8271	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8272	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8273		if (sa_res_key == 0) {
8274			/*
8275			 * Unregister everybody else and build UA for
8276			 * them
8277			 */
8278			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8279				if (i == msg->pr.pr_info.residx ||
8280				    ctl_get_prkey(lun, i) == 0)
8281					continue;
8282
8283				ctl_clr_prkey(lun, i);
8284				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8285			}
8286
8287			lun->pr_key_count = 1;
8288			lun->res_type = msg->pr.pr_info.res_type;
8289			if (lun->res_type != SPR_TYPE_WR_EX_AR
8290			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8291				lun->pr_res_idx = msg->pr.pr_info.residx;
8292		} else {
8293		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8294				if (sa_res_key == ctl_get_prkey(lun, i))
8295					continue;
8296
8297				ctl_clr_prkey(lun, i);
8298				lun->pr_key_count--;
8299				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8300			}
8301		}
8302	} else {
8303		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8304			if (i == msg->pr.pr_info.residx ||
8305			    ctl_get_prkey(lun, i) == 0)
8306				continue;
8307
8308			if (sa_res_key == ctl_get_prkey(lun, i)) {
8309				ctl_clr_prkey(lun, i);
8310				lun->pr_key_count--;
8311				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8312			} else if (msg->pr.pr_info.res_type != lun->res_type
8313				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8314				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8315				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8316			}
8317		}
8318		lun->res_type = msg->pr.pr_info.res_type;
8319		if (lun->res_type != SPR_TYPE_WR_EX_AR
8320		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8321			lun->pr_res_idx = msg->pr.pr_info.residx;
8322		else
8323			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8324	}
8325	lun->PRGeneration++;
8326
8327}
8328
8329
8330int
8331ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8332{
8333	int retval;
8334	u_int32_t param_len;
8335	struct scsi_per_res_out *cdb;
8336	struct ctl_lun *lun;
8337	struct scsi_per_res_out_parms* param;
8338	struct ctl_softc *softc;
8339	uint32_t residx;
8340	uint64_t res_key, sa_res_key, key;
8341	uint8_t type;
8342	union ctl_ha_msg persis_io;
8343	int    i;
8344
8345	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8346
8347	retval = CTL_RETVAL_COMPLETE;
8348
8349	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8350	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8351	softc = lun->ctl_softc;
8352
8353	/*
8354	 * We only support whole-LUN scope.  The scope & type are ignored for
8355	 * register, register and ignore existing key and clear.
8356	 * We sometimes ignore scope and type on preempts too!!
8357	 * Verify reservation type here as well.
8358	 */
8359	type = cdb->scope_type & SPR_TYPE_MASK;
8360	if ((cdb->action == SPRO_RESERVE)
8361	 || (cdb->action == SPRO_RELEASE)) {
8362		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8363			ctl_set_invalid_field(/*ctsio*/ ctsio,
8364					      /*sks_valid*/ 1,
8365					      /*command*/ 1,
8366					      /*field*/ 2,
8367					      /*bit_valid*/ 1,
8368					      /*bit*/ 4);
8369			ctl_done((union ctl_io *)ctsio);
8370			return (CTL_RETVAL_COMPLETE);
8371		}
8372
8373		if (type>8 || type==2 || type==4 || type==0) {
8374			ctl_set_invalid_field(/*ctsio*/ ctsio,
8375					      /*sks_valid*/ 1,
8376					      /*command*/ 1,
8377					      /*field*/ 2,
8378					      /*bit_valid*/ 1,
8379					      /*bit*/ 0);
8380			ctl_done((union ctl_io *)ctsio);
8381			return (CTL_RETVAL_COMPLETE);
8382		}
8383	}
8384
8385	param_len = scsi_4btoul(cdb->length);
8386
8387	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8388		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8389		ctsio->kern_data_len = param_len;
8390		ctsio->kern_total_len = param_len;
8391		ctsio->kern_data_resid = 0;
8392		ctsio->kern_rel_offset = 0;
8393		ctsio->kern_sg_entries = 0;
8394		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8395		ctsio->be_move_done = ctl_config_move_done;
8396		ctl_datamove((union ctl_io *)ctsio);
8397
8398		return (CTL_RETVAL_COMPLETE);
8399	}
8400
8401	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8402
8403	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8404	res_key = scsi_8btou64(param->res_key.key);
8405	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8406
8407	/*
8408	 * Validate the reservation key here except for SPRO_REG_IGNO
8409	 * This must be done for all other service actions
8410	 */
8411	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8412		mtx_lock(&lun->lun_lock);
8413		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8414			if (res_key != key) {
8415				/*
8416				 * The current key passed in doesn't match
8417				 * the one the initiator previously
8418				 * registered.
8419				 */
8420				mtx_unlock(&lun->lun_lock);
8421				free(ctsio->kern_data_ptr, M_CTL);
8422				ctl_set_reservation_conflict(ctsio);
8423				ctl_done((union ctl_io *)ctsio);
8424				return (CTL_RETVAL_COMPLETE);
8425			}
8426		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8427			/*
8428			 * We are not registered
8429			 */
8430			mtx_unlock(&lun->lun_lock);
8431			free(ctsio->kern_data_ptr, M_CTL);
8432			ctl_set_reservation_conflict(ctsio);
8433			ctl_done((union ctl_io *)ctsio);
8434			return (CTL_RETVAL_COMPLETE);
8435		} else if (res_key != 0) {
8436			/*
8437			 * We are not registered and trying to register but
8438			 * the register key isn't zero.
8439			 */
8440			mtx_unlock(&lun->lun_lock);
8441			free(ctsio->kern_data_ptr, M_CTL);
8442			ctl_set_reservation_conflict(ctsio);
8443			ctl_done((union ctl_io *)ctsio);
8444			return (CTL_RETVAL_COMPLETE);
8445		}
8446		mtx_unlock(&lun->lun_lock);
8447	}
8448
8449	switch (cdb->action & SPRO_ACTION_MASK) {
8450	case SPRO_REGISTER:
8451	case SPRO_REG_IGNO: {
8452
8453#if 0
8454		printf("Registration received\n");
8455#endif
8456
8457		/*
8458		 * We don't support any of these options, as we report in
8459		 * the read capabilities request (see
8460		 * ctl_persistent_reserve_in(), above).
8461		 */
8462		if ((param->flags & SPR_SPEC_I_PT)
8463		 || (param->flags & SPR_ALL_TG_PT)
8464		 || (param->flags & SPR_APTPL)) {
8465			int bit_ptr;
8466
8467			if (param->flags & SPR_APTPL)
8468				bit_ptr = 0;
8469			else if (param->flags & SPR_ALL_TG_PT)
8470				bit_ptr = 2;
8471			else /* SPR_SPEC_I_PT */
8472				bit_ptr = 3;
8473
8474			free(ctsio->kern_data_ptr, M_CTL);
8475			ctl_set_invalid_field(ctsio,
8476					      /*sks_valid*/ 1,
8477					      /*command*/ 0,
8478					      /*field*/ 20,
8479					      /*bit_valid*/ 1,
8480					      /*bit*/ bit_ptr);
8481			ctl_done((union ctl_io *)ctsio);
8482			return (CTL_RETVAL_COMPLETE);
8483		}
8484
8485		mtx_lock(&lun->lun_lock);
8486
8487		/*
8488		 * The initiator wants to clear the
8489		 * key/unregister.
8490		 */
8491		if (sa_res_key == 0) {
8492			if ((res_key == 0
8493			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8494			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8495			  && ctl_get_prkey(lun, residx) == 0)) {
8496				mtx_unlock(&lun->lun_lock);
8497				goto done;
8498			}
8499
8500			ctl_clr_prkey(lun, residx);
8501			lun->pr_key_count--;
8502
8503			if (residx == lun->pr_res_idx) {
8504				lun->flags &= ~CTL_LUN_PR_RESERVED;
8505				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8506
8507				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8508				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8509				 && lun->pr_key_count) {
8510					/*
8511					 * If the reservation is a registrants
8512					 * only type we need to generate a UA
8513					 * for other registered inits.  The
8514					 * sense code should be RESERVATIONS
8515					 * RELEASED
8516					 */
8517
8518					for (i = softc->init_min; i < softc->init_max; i++){
8519						if (ctl_get_prkey(lun, i) == 0)
8520							continue;
8521						ctl_est_ua(lun, i,
8522						    CTL_UA_RES_RELEASE);
8523					}
8524				}
8525				lun->res_type = 0;
8526			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8527				if (lun->pr_key_count==0) {
8528					lun->flags &= ~CTL_LUN_PR_RESERVED;
8529					lun->res_type = 0;
8530					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8531				}
8532			}
8533			lun->PRGeneration++;
8534			mtx_unlock(&lun->lun_lock);
8535
8536			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8537			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8538			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8539			persis_io.pr.pr_info.residx = residx;
8540			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8541			    sizeof(persis_io.pr), M_WAITOK);
8542		} else /* sa_res_key != 0 */ {
8543
8544			/*
8545			 * If we aren't registered currently then increment
8546			 * the key count and set the registered flag.
8547			 */
8548			ctl_alloc_prkey(lun, residx);
8549			if (ctl_get_prkey(lun, residx) == 0)
8550				lun->pr_key_count++;
8551			ctl_set_prkey(lun, residx, sa_res_key);
8552			lun->PRGeneration++;
8553			mtx_unlock(&lun->lun_lock);
8554
8555			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8556			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8557			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8558			persis_io.pr.pr_info.residx = residx;
8559			memcpy(persis_io.pr.pr_info.sa_res_key,
8560			       param->serv_act_res_key,
8561			       sizeof(param->serv_act_res_key));
8562			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8563			    sizeof(persis_io.pr), M_WAITOK);
8564		}
8565
8566		break;
8567	}
8568	case SPRO_RESERVE:
8569#if 0
8570                printf("Reserve executed type %d\n", type);
8571#endif
8572		mtx_lock(&lun->lun_lock);
8573		if (lun->flags & CTL_LUN_PR_RESERVED) {
8574			/*
8575			 * if this isn't the reservation holder and it's
8576			 * not a "all registrants" type or if the type is
8577			 * different then we have a conflict
8578			 */
8579			if ((lun->pr_res_idx != residx
8580			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8581			 || lun->res_type != type) {
8582				mtx_unlock(&lun->lun_lock);
8583				free(ctsio->kern_data_ptr, M_CTL);
8584				ctl_set_reservation_conflict(ctsio);
8585				ctl_done((union ctl_io *)ctsio);
8586				return (CTL_RETVAL_COMPLETE);
8587			}
8588			mtx_unlock(&lun->lun_lock);
8589		} else /* create a reservation */ {
8590			/*
8591			 * If it's not an "all registrants" type record
8592			 * reservation holder
8593			 */
8594			if (type != SPR_TYPE_WR_EX_AR
8595			 && type != SPR_TYPE_EX_AC_AR)
8596				lun->pr_res_idx = residx; /* Res holder */
8597			else
8598				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8599
8600			lun->flags |= CTL_LUN_PR_RESERVED;
8601			lun->res_type = type;
8602
8603			mtx_unlock(&lun->lun_lock);
8604
8605			/* send msg to other side */
8606			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8607			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8608			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8609			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8610			persis_io.pr.pr_info.res_type = type;
8611			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8612			    sizeof(persis_io.pr), M_WAITOK);
8613		}
8614		break;
8615
8616	case SPRO_RELEASE:
8617		mtx_lock(&lun->lun_lock);
8618		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8619			/* No reservation exists return good status */
8620			mtx_unlock(&lun->lun_lock);
8621			goto done;
8622		}
8623		/*
8624		 * Is this nexus a reservation holder?
8625		 */
8626		if (lun->pr_res_idx != residx
8627		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8628			/*
8629			 * not a res holder return good status but
8630			 * do nothing
8631			 */
8632			mtx_unlock(&lun->lun_lock);
8633			goto done;
8634		}
8635
8636		if (lun->res_type != type) {
8637			mtx_unlock(&lun->lun_lock);
8638			free(ctsio->kern_data_ptr, M_CTL);
8639			ctl_set_illegal_pr_release(ctsio);
8640			ctl_done((union ctl_io *)ctsio);
8641			return (CTL_RETVAL_COMPLETE);
8642		}
8643
8644		/* okay to release */
8645		lun->flags &= ~CTL_LUN_PR_RESERVED;
8646		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8647		lun->res_type = 0;
8648
8649		/*
8650		 * if this isn't an exclusive access
8651		 * res generate UA for all other
8652		 * registrants.
8653		 */
8654		if (type != SPR_TYPE_EX_AC
8655		 && type != SPR_TYPE_WR_EX) {
8656			for (i = softc->init_min; i < softc->init_max; i++) {
8657				if (i == residx || ctl_get_prkey(lun, i) == 0)
8658					continue;
8659				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8660			}
8661		}
8662		mtx_unlock(&lun->lun_lock);
8663
8664		/* Send msg to other side */
8665		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8666		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8667		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8668		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8669		     sizeof(persis_io.pr), M_WAITOK);
8670		break;
8671
8672	case SPRO_CLEAR:
8673		/* send msg to other side */
8674
8675		mtx_lock(&lun->lun_lock);
8676		lun->flags &= ~CTL_LUN_PR_RESERVED;
8677		lun->res_type = 0;
8678		lun->pr_key_count = 0;
8679		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8680
8681		ctl_clr_prkey(lun, residx);
8682		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8683			if (ctl_get_prkey(lun, i) != 0) {
8684				ctl_clr_prkey(lun, i);
8685				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8686			}
8687		lun->PRGeneration++;
8688		mtx_unlock(&lun->lun_lock);
8689
8690		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8691		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8692		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8693		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8694		     sizeof(persis_io.pr), M_WAITOK);
8695		break;
8696
8697	case SPRO_PREEMPT:
8698	case SPRO_PRE_ABO: {
8699		int nretval;
8700
8701		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8702					  residx, ctsio, cdb, param);
8703		if (nretval != 0)
8704			return (CTL_RETVAL_COMPLETE);
8705		break;
8706	}
8707	default:
8708		panic("Invalid PR type %x", cdb->action);
8709	}
8710
8711done:
8712	free(ctsio->kern_data_ptr, M_CTL);
8713	ctl_set_success(ctsio);
8714	ctl_done((union ctl_io *)ctsio);
8715
8716	return (retval);
8717}
8718
8719/*
8720 * This routine is for handling a message from the other SC pertaining to
8721 * persistent reserve out. All the error checking will have been done
8722 * so only perorming the action need be done here to keep the two
8723 * in sync.
8724 */
8725static void
8726ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8727{
8728	struct ctl_lun *lun;
8729	struct ctl_softc *softc;
8730	int i;
8731	uint32_t residx, targ_lun;
8732
8733	softc = control_softc;
8734	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8735	mtx_lock(&softc->ctl_lock);
8736	if ((targ_lun >= CTL_MAX_LUNS) ||
8737	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
8738		mtx_unlock(&softc->ctl_lock);
8739		return;
8740	}
8741	mtx_lock(&lun->lun_lock);
8742	mtx_unlock(&softc->ctl_lock);
8743	if (lun->flags & CTL_LUN_DISABLED) {
8744		mtx_unlock(&lun->lun_lock);
8745		return;
8746	}
8747	residx = ctl_get_initindex(&msg->hdr.nexus);
8748	switch(msg->pr.pr_info.action) {
8749	case CTL_PR_REG_KEY:
8750		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8751		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8752			lun->pr_key_count++;
8753		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8754		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8755		lun->PRGeneration++;
8756		break;
8757
8758	case CTL_PR_UNREG_KEY:
8759		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8760		lun->pr_key_count--;
8761
8762		/* XXX Need to see if the reservation has been released */
8763		/* if so do we need to generate UA? */
8764		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8765			lun->flags &= ~CTL_LUN_PR_RESERVED;
8766			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8767
8768			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8769			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8770			 && lun->pr_key_count) {
8771				/*
8772				 * If the reservation is a registrants
8773				 * only type we need to generate a UA
8774				 * for other registered inits.  The
8775				 * sense code should be RESERVATIONS
8776				 * RELEASED
8777				 */
8778
8779				for (i = softc->init_min; i < softc->init_max; i++) {
8780					if (ctl_get_prkey(lun, i) == 0)
8781						continue;
8782
8783					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8784				}
8785			}
8786			lun->res_type = 0;
8787		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8788			if (lun->pr_key_count==0) {
8789				lun->flags &= ~CTL_LUN_PR_RESERVED;
8790				lun->res_type = 0;
8791				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8792			}
8793		}
8794		lun->PRGeneration++;
8795		break;
8796
8797	case CTL_PR_RESERVE:
8798		lun->flags |= CTL_LUN_PR_RESERVED;
8799		lun->res_type = msg->pr.pr_info.res_type;
8800		lun->pr_res_idx = msg->pr.pr_info.residx;
8801
8802		break;
8803
8804	case CTL_PR_RELEASE:
8805		/*
8806		 * if this isn't an exclusive access res generate UA for all
8807		 * other registrants.
8808		 */
8809		if (lun->res_type != SPR_TYPE_EX_AC
8810		 && lun->res_type != SPR_TYPE_WR_EX) {
8811			for (i = softc->init_min; i < softc->init_max; i++)
8812				if (i == residx || ctl_get_prkey(lun, i) == 0)
8813					continue;
8814				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8815		}
8816
8817		lun->flags &= ~CTL_LUN_PR_RESERVED;
8818		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8819		lun->res_type = 0;
8820		break;
8821
8822	case CTL_PR_PREEMPT:
8823		ctl_pro_preempt_other(lun, msg);
8824		break;
8825	case CTL_PR_CLEAR:
8826		lun->flags &= ~CTL_LUN_PR_RESERVED;
8827		lun->res_type = 0;
8828		lun->pr_key_count = 0;
8829		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8830
8831		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8832			if (ctl_get_prkey(lun, i) == 0)
8833				continue;
8834			ctl_clr_prkey(lun, i);
8835			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8836		}
8837		lun->PRGeneration++;
8838		break;
8839	}
8840
8841	mtx_unlock(&lun->lun_lock);
8842}
8843
8844int
8845ctl_read_write(struct ctl_scsiio *ctsio)
8846{
8847	struct ctl_lun *lun;
8848	struct ctl_lba_len_flags *lbalen;
8849	uint64_t lba;
8850	uint32_t num_blocks;
8851	int flags, retval;
8852	int isread;
8853
8854	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8855
8856	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8857
8858	flags = 0;
8859	retval = CTL_RETVAL_COMPLETE;
8860
8861	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8862	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8863	switch (ctsio->cdb[0]) {
8864	case READ_6:
8865	case WRITE_6: {
8866		struct scsi_rw_6 *cdb;
8867
8868		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8869
8870		lba = scsi_3btoul(cdb->addr);
8871		/* only 5 bits are valid in the most significant address byte */
8872		lba &= 0x1fffff;
8873		num_blocks = cdb->length;
8874		/*
8875		 * This is correct according to SBC-2.
8876		 */
8877		if (num_blocks == 0)
8878			num_blocks = 256;
8879		break;
8880	}
8881	case READ_10:
8882	case WRITE_10: {
8883		struct scsi_rw_10 *cdb;
8884
8885		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8886		if (cdb->byte2 & SRW10_FUA)
8887			flags |= CTL_LLF_FUA;
8888		if (cdb->byte2 & SRW10_DPO)
8889			flags |= CTL_LLF_DPO;
8890		lba = scsi_4btoul(cdb->addr);
8891		num_blocks = scsi_2btoul(cdb->length);
8892		break;
8893	}
8894	case WRITE_VERIFY_10: {
8895		struct scsi_write_verify_10 *cdb;
8896
8897		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8898		flags |= CTL_LLF_FUA;
8899		if (cdb->byte2 & SWV_DPO)
8900			flags |= CTL_LLF_DPO;
8901		lba = scsi_4btoul(cdb->addr);
8902		num_blocks = scsi_2btoul(cdb->length);
8903		break;
8904	}
8905	case READ_12:
8906	case WRITE_12: {
8907		struct scsi_rw_12 *cdb;
8908
8909		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8910		if (cdb->byte2 & SRW12_FUA)
8911			flags |= CTL_LLF_FUA;
8912		if (cdb->byte2 & SRW12_DPO)
8913			flags |= CTL_LLF_DPO;
8914		lba = scsi_4btoul(cdb->addr);
8915		num_blocks = scsi_4btoul(cdb->length);
8916		break;
8917	}
8918	case WRITE_VERIFY_12: {
8919		struct scsi_write_verify_12 *cdb;
8920
8921		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8922		flags |= CTL_LLF_FUA;
8923		if (cdb->byte2 & SWV_DPO)
8924			flags |= CTL_LLF_DPO;
8925		lba = scsi_4btoul(cdb->addr);
8926		num_blocks = scsi_4btoul(cdb->length);
8927		break;
8928	}
8929	case READ_16:
8930	case WRITE_16: {
8931		struct scsi_rw_16 *cdb;
8932
8933		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8934		if (cdb->byte2 & SRW12_FUA)
8935			flags |= CTL_LLF_FUA;
8936		if (cdb->byte2 & SRW12_DPO)
8937			flags |= CTL_LLF_DPO;
8938		lba = scsi_8btou64(cdb->addr);
8939		num_blocks = scsi_4btoul(cdb->length);
8940		break;
8941	}
8942	case WRITE_ATOMIC_16: {
8943		struct scsi_rw_16 *cdb;
8944
8945		if (lun->be_lun->atomicblock == 0) {
8946			ctl_set_invalid_opcode(ctsio);
8947			ctl_done((union ctl_io *)ctsio);
8948			return (CTL_RETVAL_COMPLETE);
8949		}
8950
8951		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8952		if (cdb->byte2 & SRW12_FUA)
8953			flags |= CTL_LLF_FUA;
8954		if (cdb->byte2 & SRW12_DPO)
8955			flags |= CTL_LLF_DPO;
8956		lba = scsi_8btou64(cdb->addr);
8957		num_blocks = scsi_4btoul(cdb->length);
8958		if (num_blocks > lun->be_lun->atomicblock) {
8959			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8960			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8961			    /*bit*/ 0);
8962			ctl_done((union ctl_io *)ctsio);
8963			return (CTL_RETVAL_COMPLETE);
8964		}
8965		break;
8966	}
8967	case WRITE_VERIFY_16: {
8968		struct scsi_write_verify_16 *cdb;
8969
8970		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8971		flags |= CTL_LLF_FUA;
8972		if (cdb->byte2 & SWV_DPO)
8973			flags |= CTL_LLF_DPO;
8974		lba = scsi_8btou64(cdb->addr);
8975		num_blocks = scsi_4btoul(cdb->length);
8976		break;
8977	}
8978	default:
8979		/*
8980		 * We got a command we don't support.  This shouldn't
8981		 * happen, commands should be filtered out above us.
8982		 */
8983		ctl_set_invalid_opcode(ctsio);
8984		ctl_done((union ctl_io *)ctsio);
8985
8986		return (CTL_RETVAL_COMPLETE);
8987		break; /* NOTREACHED */
8988	}
8989
8990	/*
8991	 * The first check is to make sure we're in bounds, the second
8992	 * check is to catch wrap-around problems.  If the lba + num blocks
8993	 * is less than the lba, then we've wrapped around and the block
8994	 * range is invalid anyway.
8995	 */
8996	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8997	 || ((lba + num_blocks) < lba)) {
8998		ctl_set_lba_out_of_range(ctsio);
8999		ctl_done((union ctl_io *)ctsio);
9000		return (CTL_RETVAL_COMPLETE);
9001	}
9002
9003	/*
9004	 * According to SBC-3, a transfer length of 0 is not an error.
9005	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
9006	 * translates to 256 blocks for those commands.
9007	 */
9008	if (num_blocks == 0) {
9009		ctl_set_success(ctsio);
9010		ctl_done((union ctl_io *)ctsio);
9011		return (CTL_RETVAL_COMPLETE);
9012	}
9013
9014	/* Set FUA and/or DPO if caches are disabled. */
9015	if (isread) {
9016		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9017		    SCP_RCD) != 0)
9018			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9019	} else {
9020		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9021		    SCP_WCE) == 0)
9022			flags |= CTL_LLF_FUA;
9023	}
9024
9025	lbalen = (struct ctl_lba_len_flags *)
9026	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9027	lbalen->lba = lba;
9028	lbalen->len = num_blocks;
9029	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9030
9031	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9032	ctsio->kern_rel_offset = 0;
9033
9034	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9035
9036	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9037
9038	return (retval);
9039}
9040
9041static int
9042ctl_cnw_cont(union ctl_io *io)
9043{
9044	struct ctl_scsiio *ctsio;
9045	struct ctl_lun *lun;
9046	struct ctl_lba_len_flags *lbalen;
9047	int retval;
9048
9049	ctsio = &io->scsiio;
9050	ctsio->io_hdr.status = CTL_STATUS_NONE;
9051	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9052	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9053	lbalen = (struct ctl_lba_len_flags *)
9054	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9055	lbalen->flags &= ~CTL_LLF_COMPARE;
9056	lbalen->flags |= CTL_LLF_WRITE;
9057
9058	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9059	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9060	return (retval);
9061}
9062
9063int
9064ctl_cnw(struct ctl_scsiio *ctsio)
9065{
9066	struct ctl_lun *lun;
9067	struct ctl_lba_len_flags *lbalen;
9068	uint64_t lba;
9069	uint32_t num_blocks;
9070	int flags, retval;
9071
9072	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9073
9074	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9075
9076	flags = 0;
9077	retval = CTL_RETVAL_COMPLETE;
9078
9079	switch (ctsio->cdb[0]) {
9080	case COMPARE_AND_WRITE: {
9081		struct scsi_compare_and_write *cdb;
9082
9083		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9084		if (cdb->byte2 & SRW10_FUA)
9085			flags |= CTL_LLF_FUA;
9086		if (cdb->byte2 & SRW10_DPO)
9087			flags |= CTL_LLF_DPO;
9088		lba = scsi_8btou64(cdb->addr);
9089		num_blocks = cdb->length;
9090		break;
9091	}
9092	default:
9093		/*
9094		 * We got a command we don't support.  This shouldn't
9095		 * happen, commands should be filtered out above us.
9096		 */
9097		ctl_set_invalid_opcode(ctsio);
9098		ctl_done((union ctl_io *)ctsio);
9099
9100		return (CTL_RETVAL_COMPLETE);
9101		break; /* NOTREACHED */
9102	}
9103
9104	/*
9105	 * The first check is to make sure we're in bounds, the second
9106	 * check is to catch wrap-around problems.  If the lba + num blocks
9107	 * is less than the lba, then we've wrapped around and the block
9108	 * range is invalid anyway.
9109	 */
9110	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9111	 || ((lba + num_blocks) < lba)) {
9112		ctl_set_lba_out_of_range(ctsio);
9113		ctl_done((union ctl_io *)ctsio);
9114		return (CTL_RETVAL_COMPLETE);
9115	}
9116
9117	/*
9118	 * According to SBC-3, a transfer length of 0 is not an error.
9119	 */
9120	if (num_blocks == 0) {
9121		ctl_set_success(ctsio);
9122		ctl_done((union ctl_io *)ctsio);
9123		return (CTL_RETVAL_COMPLETE);
9124	}
9125
9126	/* Set FUA if write cache is disabled. */
9127	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9128	    SCP_WCE) == 0)
9129		flags |= CTL_LLF_FUA;
9130
9131	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9132	ctsio->kern_rel_offset = 0;
9133
9134	/*
9135	 * Set the IO_CONT flag, so that if this I/O gets passed to
9136	 * ctl_data_submit_done(), it'll get passed back to
9137	 * ctl_ctl_cnw_cont() for further processing.
9138	 */
9139	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9140	ctsio->io_cont = ctl_cnw_cont;
9141
9142	lbalen = (struct ctl_lba_len_flags *)
9143	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9144	lbalen->lba = lba;
9145	lbalen->len = num_blocks;
9146	lbalen->flags = CTL_LLF_COMPARE | flags;
9147
9148	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9149	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9150	return (retval);
9151}
9152
9153int
9154ctl_verify(struct ctl_scsiio *ctsio)
9155{
9156	struct ctl_lun *lun;
9157	struct ctl_lba_len_flags *lbalen;
9158	uint64_t lba;
9159	uint32_t num_blocks;
9160	int bytchk, flags;
9161	int retval;
9162
9163	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9164
9165	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9166
9167	bytchk = 0;
9168	flags = CTL_LLF_FUA;
9169	retval = CTL_RETVAL_COMPLETE;
9170
9171	switch (ctsio->cdb[0]) {
9172	case VERIFY_10: {
9173		struct scsi_verify_10 *cdb;
9174
9175		cdb = (struct scsi_verify_10 *)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_2btoul(cdb->length);
9182		break;
9183	}
9184	case VERIFY_12: {
9185		struct scsi_verify_12 *cdb;
9186
9187		cdb = (struct scsi_verify_12 *)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_4btoul(cdb->addr);
9193		num_blocks = scsi_4btoul(cdb->length);
9194		break;
9195	}
9196	case VERIFY_16: {
9197		struct scsi_rw_16 *cdb;
9198
9199		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9200		if (cdb->byte2 & SVFY_BYTCHK)
9201			bytchk = 1;
9202		if (cdb->byte2 & SVFY_DPO)
9203			flags |= CTL_LLF_DPO;
9204		lba = scsi_8btou64(cdb->addr);
9205		num_blocks = scsi_4btoul(cdb->length);
9206		break;
9207	}
9208	default:
9209		/*
9210		 * We got a command we don't support.  This shouldn't
9211		 * happen, commands should be filtered out above us.
9212		 */
9213		ctl_set_invalid_opcode(ctsio);
9214		ctl_done((union ctl_io *)ctsio);
9215		return (CTL_RETVAL_COMPLETE);
9216	}
9217
9218	/*
9219	 * The first check is to make sure we're in bounds, the second
9220	 * check is to catch wrap-around problems.  If the lba + num blocks
9221	 * is less than the lba, then we've wrapped around and the block
9222	 * range is invalid anyway.
9223	 */
9224	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9225	 || ((lba + num_blocks) < lba)) {
9226		ctl_set_lba_out_of_range(ctsio);
9227		ctl_done((union ctl_io *)ctsio);
9228		return (CTL_RETVAL_COMPLETE);
9229	}
9230
9231	/*
9232	 * According to SBC-3, a transfer length of 0 is not an error.
9233	 */
9234	if (num_blocks == 0) {
9235		ctl_set_success(ctsio);
9236		ctl_done((union ctl_io *)ctsio);
9237		return (CTL_RETVAL_COMPLETE);
9238	}
9239
9240	lbalen = (struct ctl_lba_len_flags *)
9241	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9242	lbalen->lba = lba;
9243	lbalen->len = num_blocks;
9244	if (bytchk) {
9245		lbalen->flags = CTL_LLF_COMPARE | flags;
9246		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9247	} else {
9248		lbalen->flags = CTL_LLF_VERIFY | flags;
9249		ctsio->kern_total_len = 0;
9250	}
9251	ctsio->kern_rel_offset = 0;
9252
9253	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9254	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9255	return (retval);
9256}
9257
9258int
9259ctl_report_luns(struct ctl_scsiio *ctsio)
9260{
9261	struct ctl_softc *softc = control_softc;
9262	struct scsi_report_luns *cdb;
9263	struct scsi_report_luns_data *lun_data;
9264	struct ctl_lun *lun, *request_lun;
9265	struct ctl_port *port;
9266	int num_luns, retval;
9267	uint32_t alloc_len, lun_datalen;
9268	int num_filled, well_known;
9269	uint32_t initidx, targ_lun_id, lun_id;
9270
9271	retval = CTL_RETVAL_COMPLETE;
9272	well_known = 0;
9273
9274	cdb = (struct scsi_report_luns *)ctsio->cdb;
9275	port = ctl_io_port(&ctsio->io_hdr);
9276
9277	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9278
9279	mtx_lock(&softc->ctl_lock);
9280	num_luns = 0;
9281	for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
9282		if (ctl_lun_map_from_port(port, targ_lun_id) < CTL_MAX_LUNS)
9283			num_luns++;
9284	}
9285	mtx_unlock(&softc->ctl_lock);
9286
9287	switch (cdb->select_report) {
9288	case RPL_REPORT_DEFAULT:
9289	case RPL_REPORT_ALL:
9290		break;
9291	case RPL_REPORT_WELLKNOWN:
9292		well_known = 1;
9293		num_luns = 0;
9294		break;
9295	default:
9296		ctl_set_invalid_field(ctsio,
9297				      /*sks_valid*/ 1,
9298				      /*command*/ 1,
9299				      /*field*/ 2,
9300				      /*bit_valid*/ 0,
9301				      /*bit*/ 0);
9302		ctl_done((union ctl_io *)ctsio);
9303		return (retval);
9304		break; /* NOTREACHED */
9305	}
9306
9307	alloc_len = scsi_4btoul(cdb->length);
9308	/*
9309	 * The initiator has to allocate at least 16 bytes for this request,
9310	 * so he can at least get the header and the first LUN.  Otherwise
9311	 * we reject the request (per SPC-3 rev 14, section 6.21).
9312	 */
9313	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9314	    sizeof(struct scsi_report_luns_lundata))) {
9315		ctl_set_invalid_field(ctsio,
9316				      /*sks_valid*/ 1,
9317				      /*command*/ 1,
9318				      /*field*/ 6,
9319				      /*bit_valid*/ 0,
9320				      /*bit*/ 0);
9321		ctl_done((union ctl_io *)ctsio);
9322		return (retval);
9323	}
9324
9325	request_lun = (struct ctl_lun *)
9326		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9327
9328	lun_datalen = sizeof(*lun_data) +
9329		(num_luns * sizeof(struct scsi_report_luns_lundata));
9330
9331	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9332	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9333	ctsio->kern_sg_entries = 0;
9334
9335	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9336
9337	mtx_lock(&softc->ctl_lock);
9338	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9339		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9340		if (lun_id >= CTL_MAX_LUNS)
9341			continue;
9342		lun = softc->ctl_luns[lun_id];
9343		if (lun == NULL)
9344			continue;
9345
9346		if (targ_lun_id <= 0xff) {
9347			/*
9348			 * Peripheral addressing method, bus number 0.
9349			 */
9350			lun_data->luns[num_filled].lundata[0] =
9351				RPL_LUNDATA_ATYP_PERIPH;
9352			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9353			num_filled++;
9354		} else if (targ_lun_id <= 0x3fff) {
9355			/*
9356			 * Flat addressing method.
9357			 */
9358			lun_data->luns[num_filled].lundata[0] =
9359				RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9360			lun_data->luns[num_filled].lundata[1] =
9361				(targ_lun_id & 0xff);
9362			num_filled++;
9363		} else if (targ_lun_id <= 0xffffff) {
9364			/*
9365			 * Extended flat addressing method.
9366			 */
9367			lun_data->luns[num_filled].lundata[0] =
9368			    RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9369			scsi_ulto3b(targ_lun_id,
9370			    &lun_data->luns[num_filled].lundata[1]);
9371			num_filled++;
9372		} else {
9373			printf("ctl_report_luns: bogus LUN number %jd, "
9374			       "skipping\n", (intmax_t)targ_lun_id);
9375		}
9376		/*
9377		 * According to SPC-3, rev 14 section 6.21:
9378		 *
9379		 * "The execution of a REPORT LUNS command to any valid and
9380		 * installed logical unit shall clear the REPORTED LUNS DATA
9381		 * HAS CHANGED unit attention condition for all logical
9382		 * units of that target with respect to the requesting
9383		 * initiator. A valid and installed logical unit is one
9384		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9385		 * INQUIRY data (see 6.4.2)."
9386		 *
9387		 * If request_lun is NULL, the LUN this report luns command
9388		 * was issued to is either disabled or doesn't exist. In that
9389		 * case, we shouldn't clear any pending lun change unit
9390		 * attention.
9391		 */
9392		if (request_lun != NULL) {
9393			mtx_lock(&lun->lun_lock);
9394			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9395			mtx_unlock(&lun->lun_lock);
9396		}
9397	}
9398	mtx_unlock(&softc->ctl_lock);
9399
9400	/*
9401	 * It's quite possible that we've returned fewer LUNs than we allocated
9402	 * space for.  Trim it.
9403	 */
9404	lun_datalen = sizeof(*lun_data) +
9405		(num_filled * sizeof(struct scsi_report_luns_lundata));
9406
9407	if (lun_datalen < alloc_len) {
9408		ctsio->residual = alloc_len - lun_datalen;
9409		ctsio->kern_data_len = lun_datalen;
9410		ctsio->kern_total_len = lun_datalen;
9411	} else {
9412		ctsio->residual = 0;
9413		ctsio->kern_data_len = alloc_len;
9414		ctsio->kern_total_len = alloc_len;
9415	}
9416	ctsio->kern_data_resid = 0;
9417	ctsio->kern_rel_offset = 0;
9418	ctsio->kern_sg_entries = 0;
9419
9420	/*
9421	 * We set this to the actual data length, regardless of how much
9422	 * space we actually have to return results.  If the user looks at
9423	 * this value, he'll know whether or not he allocated enough space
9424	 * and reissue the command if necessary.  We don't support well
9425	 * known logical units, so if the user asks for that, return none.
9426	 */
9427	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9428
9429	/*
9430	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9431	 * this request.
9432	 */
9433	ctl_set_success(ctsio);
9434	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9435	ctsio->be_move_done = ctl_config_move_done;
9436	ctl_datamove((union ctl_io *)ctsio);
9437	return (retval);
9438}
9439
9440int
9441ctl_request_sense(struct ctl_scsiio *ctsio)
9442{
9443	struct scsi_request_sense *cdb;
9444	struct scsi_sense_data *sense_ptr;
9445	struct ctl_softc *ctl_softc;
9446	struct ctl_lun *lun;
9447	uint32_t initidx;
9448	int have_error;
9449	scsi_sense_data_type sense_format;
9450	ctl_ua_type ua_type;
9451
9452	cdb = (struct scsi_request_sense *)ctsio->cdb;
9453
9454	ctl_softc = control_softc;
9455	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9456
9457	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9458
9459	/*
9460	 * Determine which sense format the user wants.
9461	 */
9462	if (cdb->byte2 & SRS_DESC)
9463		sense_format = SSD_TYPE_DESC;
9464	else
9465		sense_format = SSD_TYPE_FIXED;
9466
9467	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9468	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9469	ctsio->kern_sg_entries = 0;
9470
9471	/*
9472	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9473	 * larger than the largest allowed value for the length field in the
9474	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9475	 */
9476	ctsio->residual = 0;
9477	ctsio->kern_data_len = cdb->length;
9478	ctsio->kern_total_len = cdb->length;
9479
9480	ctsio->kern_data_resid = 0;
9481	ctsio->kern_rel_offset = 0;
9482	ctsio->kern_sg_entries = 0;
9483
9484	/*
9485	 * If we don't have a LUN, we don't have any pending sense.
9486	 */
9487	if (lun == NULL)
9488		goto no_sense;
9489
9490	have_error = 0;
9491	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9492	/*
9493	 * Check for pending sense, and then for pending unit attentions.
9494	 * Pending sense gets returned first, then pending unit attentions.
9495	 */
9496	mtx_lock(&lun->lun_lock);
9497#ifdef CTL_WITH_CA
9498	if (ctl_is_set(lun->have_ca, initidx)) {
9499		scsi_sense_data_type stored_format;
9500
9501		/*
9502		 * Check to see which sense format was used for the stored
9503		 * sense data.
9504		 */
9505		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9506
9507		/*
9508		 * If the user requested a different sense format than the
9509		 * one we stored, then we need to convert it to the other
9510		 * format.  If we're going from descriptor to fixed format
9511		 * sense data, we may lose things in translation, depending
9512		 * on what options were used.
9513		 *
9514		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9515		 * for some reason we'll just copy it out as-is.
9516		 */
9517		if ((stored_format == SSD_TYPE_FIXED)
9518		 && (sense_format == SSD_TYPE_DESC))
9519			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9520			    &lun->pending_sense[initidx],
9521			    (struct scsi_sense_data_desc *)sense_ptr);
9522		else if ((stored_format == SSD_TYPE_DESC)
9523		      && (sense_format == SSD_TYPE_FIXED))
9524			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9525			    &lun->pending_sense[initidx],
9526			    (struct scsi_sense_data_fixed *)sense_ptr);
9527		else
9528			memcpy(sense_ptr, &lun->pending_sense[initidx],
9529			       MIN(sizeof(*sense_ptr),
9530			       sizeof(lun->pending_sense[initidx])));
9531
9532		ctl_clear_mask(lun->have_ca, initidx);
9533		have_error = 1;
9534	} else
9535#endif
9536	{
9537		ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9538		if (ua_type != CTL_UA_NONE)
9539			have_error = 1;
9540		if (ua_type == CTL_UA_LUN_CHANGE) {
9541			mtx_unlock(&lun->lun_lock);
9542			mtx_lock(&ctl_softc->ctl_lock);
9543			ctl_clr_ua_allluns(ctl_softc, initidx, ua_type);
9544			mtx_unlock(&ctl_softc->ctl_lock);
9545			mtx_lock(&lun->lun_lock);
9546		}
9547
9548	}
9549	mtx_unlock(&lun->lun_lock);
9550
9551	/*
9552	 * We already have a pending error, return it.
9553	 */
9554	if (have_error != 0) {
9555		/*
9556		 * We report the SCSI status as OK, since the status of the
9557		 * request sense command itself is OK.
9558		 * We report 0 for the sense length, because we aren't doing
9559		 * autosense in this case.  We're reporting sense as
9560		 * parameter data.
9561		 */
9562		ctl_set_success(ctsio);
9563		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9564		ctsio->be_move_done = ctl_config_move_done;
9565		ctl_datamove((union ctl_io *)ctsio);
9566		return (CTL_RETVAL_COMPLETE);
9567	}
9568
9569no_sense:
9570
9571	/*
9572	 * No sense information to report, so we report that everything is
9573	 * okay.
9574	 */
9575	ctl_set_sense_data(sense_ptr,
9576			   lun,
9577			   sense_format,
9578			   /*current_error*/ 1,
9579			   /*sense_key*/ SSD_KEY_NO_SENSE,
9580			   /*asc*/ 0x00,
9581			   /*ascq*/ 0x00,
9582			   SSD_ELEM_NONE);
9583
9584	/*
9585	 * We report 0 for the sense length, because we aren't doing
9586	 * autosense in this case.  We're reporting sense as parameter data.
9587	 */
9588	ctl_set_success(ctsio);
9589	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9590	ctsio->be_move_done = ctl_config_move_done;
9591	ctl_datamove((union ctl_io *)ctsio);
9592	return (CTL_RETVAL_COMPLETE);
9593}
9594
9595int
9596ctl_tur(struct ctl_scsiio *ctsio)
9597{
9598
9599	CTL_DEBUG_PRINT(("ctl_tur\n"));
9600
9601	ctl_set_success(ctsio);
9602	ctl_done((union ctl_io *)ctsio);
9603
9604	return (CTL_RETVAL_COMPLETE);
9605}
9606
9607/*
9608 * SCSI VPD page 0x00, the Supported VPD Pages page.
9609 */
9610static int
9611ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9612{
9613	struct scsi_vpd_supported_pages *pages;
9614	int sup_page_size;
9615	struct ctl_lun *lun;
9616	int p;
9617
9618	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9619
9620	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9621	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9622	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9623	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9624	ctsio->kern_sg_entries = 0;
9625
9626	if (sup_page_size < alloc_len) {
9627		ctsio->residual = alloc_len - sup_page_size;
9628		ctsio->kern_data_len = sup_page_size;
9629		ctsio->kern_total_len = sup_page_size;
9630	} else {
9631		ctsio->residual = 0;
9632		ctsio->kern_data_len = alloc_len;
9633		ctsio->kern_total_len = alloc_len;
9634	}
9635	ctsio->kern_data_resid = 0;
9636	ctsio->kern_rel_offset = 0;
9637	ctsio->kern_sg_entries = 0;
9638
9639	/*
9640	 * The control device is always connected.  The disk device, on the
9641	 * other hand, may not be online all the time.  Need to change this
9642	 * to figure out whether the disk device is actually online or not.
9643	 */
9644	if (lun != NULL)
9645		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9646				lun->be_lun->lun_type;
9647	else
9648		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9649
9650	p = 0;
9651	/* Supported VPD pages */
9652	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9653	/* Serial Number */
9654	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9655	/* Device Identification */
9656	pages->page_list[p++] = SVPD_DEVICE_ID;
9657	/* Extended INQUIRY Data */
9658	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9659	/* Mode Page Policy */
9660	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9661	/* SCSI Ports */
9662	pages->page_list[p++] = SVPD_SCSI_PORTS;
9663	/* Third-party Copy */
9664	pages->page_list[p++] = SVPD_SCSI_TPC;
9665	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9666		/* Block limits */
9667		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9668		/* Block Device Characteristics */
9669		pages->page_list[p++] = SVPD_BDC;
9670		/* Logical Block Provisioning */
9671		pages->page_list[p++] = SVPD_LBP;
9672	}
9673	pages->length = p;
9674
9675	ctl_set_success(ctsio);
9676	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9677	ctsio->be_move_done = ctl_config_move_done;
9678	ctl_datamove((union ctl_io *)ctsio);
9679	return (CTL_RETVAL_COMPLETE);
9680}
9681
9682/*
9683 * SCSI VPD page 0x80, the Unit Serial Number page.
9684 */
9685static int
9686ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9687{
9688	struct scsi_vpd_unit_serial_number *sn_ptr;
9689	struct ctl_lun *lun;
9690	int data_len;
9691
9692	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9693
9694	data_len = 4 + CTL_SN_LEN;
9695	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9696	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9697	if (data_len < alloc_len) {
9698		ctsio->residual = alloc_len - data_len;
9699		ctsio->kern_data_len = data_len;
9700		ctsio->kern_total_len = data_len;
9701	} else {
9702		ctsio->residual = 0;
9703		ctsio->kern_data_len = alloc_len;
9704		ctsio->kern_total_len = alloc_len;
9705	}
9706	ctsio->kern_data_resid = 0;
9707	ctsio->kern_rel_offset = 0;
9708	ctsio->kern_sg_entries = 0;
9709
9710	/*
9711	 * The control device is always connected.  The disk device, on the
9712	 * other hand, may not be online all the time.  Need to change this
9713	 * to figure out whether the disk device is actually online or not.
9714	 */
9715	if (lun != NULL)
9716		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9717				  lun->be_lun->lun_type;
9718	else
9719		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9720
9721	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9722	sn_ptr->length = CTL_SN_LEN;
9723	/*
9724	 * If we don't have a LUN, we just leave the serial number as
9725	 * all spaces.
9726	 */
9727	if (lun != NULL) {
9728		strncpy((char *)sn_ptr->serial_num,
9729			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9730	} else
9731		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9732
9733	ctl_set_success(ctsio);
9734	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9735	ctsio->be_move_done = ctl_config_move_done;
9736	ctl_datamove((union ctl_io *)ctsio);
9737	return (CTL_RETVAL_COMPLETE);
9738}
9739
9740
9741/*
9742 * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9743 */
9744static int
9745ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9746{
9747	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9748	struct ctl_lun *lun;
9749	int data_len;
9750
9751	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9752
9753	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9754	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9755	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9756	ctsio->kern_sg_entries = 0;
9757
9758	if (data_len < alloc_len) {
9759		ctsio->residual = alloc_len - data_len;
9760		ctsio->kern_data_len = data_len;
9761		ctsio->kern_total_len = data_len;
9762	} else {
9763		ctsio->residual = 0;
9764		ctsio->kern_data_len = alloc_len;
9765		ctsio->kern_total_len = alloc_len;
9766	}
9767	ctsio->kern_data_resid = 0;
9768	ctsio->kern_rel_offset = 0;
9769	ctsio->kern_sg_entries = 0;
9770
9771	/*
9772	 * The control device is always connected.  The disk device, on the
9773	 * other hand, may not be online all the time.
9774	 */
9775	if (lun != NULL)
9776		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9777				     lun->be_lun->lun_type;
9778	else
9779		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9780	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9781	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9782	/*
9783	 * We support head of queue, ordered and simple tags.
9784	 */
9785	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9786	/*
9787	 * Volatile cache supported.
9788	 */
9789	eid_ptr->flags3 = SVPD_EID_V_SUP;
9790
9791	/*
9792	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9793	 * attention for a particular IT nexus on all LUNs once we report
9794	 * it to that nexus once.  This bit is required as of SPC-4.
9795	 */
9796	eid_ptr->flags4 = SVPD_EID_LUICLT;
9797
9798	/*
9799	 * XXX KDM in order to correctly answer this, we would need
9800	 * information from the SIM to determine how much sense data it
9801	 * can send.  So this would really be a path inquiry field, most
9802	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9803	 * but the hardware may or may not be able to support that much.
9804	 * 0 just means that the maximum sense data length is not reported.
9805	 */
9806	eid_ptr->max_sense_length = 0;
9807
9808	ctl_set_success(ctsio);
9809	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9810	ctsio->be_move_done = ctl_config_move_done;
9811	ctl_datamove((union ctl_io *)ctsio);
9812	return (CTL_RETVAL_COMPLETE);
9813}
9814
9815static int
9816ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9817{
9818	struct scsi_vpd_mode_page_policy *mpp_ptr;
9819	struct ctl_lun *lun;
9820	int data_len;
9821
9822	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9823
9824	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9825	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9826
9827	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9828	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9829	ctsio->kern_sg_entries = 0;
9830
9831	if (data_len < alloc_len) {
9832		ctsio->residual = alloc_len - data_len;
9833		ctsio->kern_data_len = data_len;
9834		ctsio->kern_total_len = data_len;
9835	} else {
9836		ctsio->residual = 0;
9837		ctsio->kern_data_len = alloc_len;
9838		ctsio->kern_total_len = alloc_len;
9839	}
9840	ctsio->kern_data_resid = 0;
9841	ctsio->kern_rel_offset = 0;
9842	ctsio->kern_sg_entries = 0;
9843
9844	/*
9845	 * The control device is always connected.  The disk device, on the
9846	 * other hand, may not be online all the time.
9847	 */
9848	if (lun != NULL)
9849		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9850				     lun->be_lun->lun_type;
9851	else
9852		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9853	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9854	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9855	mpp_ptr->descr[0].page_code = 0x3f;
9856	mpp_ptr->descr[0].subpage_code = 0xff;
9857	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9858
9859	ctl_set_success(ctsio);
9860	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9861	ctsio->be_move_done = ctl_config_move_done;
9862	ctl_datamove((union ctl_io *)ctsio);
9863	return (CTL_RETVAL_COMPLETE);
9864}
9865
9866/*
9867 * SCSI VPD page 0x83, the Device Identification page.
9868 */
9869static int
9870ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9871{
9872	struct scsi_vpd_device_id *devid_ptr;
9873	struct scsi_vpd_id_descriptor *desc;
9874	struct ctl_softc *softc;
9875	struct ctl_lun *lun;
9876	struct ctl_port *port;
9877	int data_len;
9878	uint8_t proto;
9879
9880	softc = control_softc;
9881
9882	port = ctl_io_port(&ctsio->io_hdr);
9883	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9884
9885	data_len = sizeof(struct scsi_vpd_device_id) +
9886	    sizeof(struct scsi_vpd_id_descriptor) +
9887		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9888	    sizeof(struct scsi_vpd_id_descriptor) +
9889		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9890	if (lun && lun->lun_devid)
9891		data_len += lun->lun_devid->len;
9892	if (port && port->port_devid)
9893		data_len += port->port_devid->len;
9894	if (port && port->target_devid)
9895		data_len += port->target_devid->len;
9896
9897	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9898	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9899	ctsio->kern_sg_entries = 0;
9900
9901	if (data_len < alloc_len) {
9902		ctsio->residual = alloc_len - data_len;
9903		ctsio->kern_data_len = data_len;
9904		ctsio->kern_total_len = data_len;
9905	} else {
9906		ctsio->residual = 0;
9907		ctsio->kern_data_len = alloc_len;
9908		ctsio->kern_total_len = alloc_len;
9909	}
9910	ctsio->kern_data_resid = 0;
9911	ctsio->kern_rel_offset = 0;
9912	ctsio->kern_sg_entries = 0;
9913
9914	/*
9915	 * The control device is always connected.  The disk device, on the
9916	 * other hand, may not be online all the time.
9917	 */
9918	if (lun != NULL)
9919		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9920				     lun->be_lun->lun_type;
9921	else
9922		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9923	devid_ptr->page_code = SVPD_DEVICE_ID;
9924	scsi_ulto2b(data_len - 4, devid_ptr->length);
9925
9926	if (port && port->port_type == CTL_PORT_FC)
9927		proto = SCSI_PROTO_FC << 4;
9928	else if (port && port->port_type == CTL_PORT_ISCSI)
9929		proto = SCSI_PROTO_ISCSI << 4;
9930	else
9931		proto = SCSI_PROTO_SPI << 4;
9932	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9933
9934	/*
9935	 * We're using a LUN association here.  i.e., this device ID is a
9936	 * per-LUN identifier.
9937	 */
9938	if (lun && lun->lun_devid) {
9939		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9940		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9941		    lun->lun_devid->len);
9942	}
9943
9944	/*
9945	 * This is for the WWPN which is a port association.
9946	 */
9947	if (port && port->port_devid) {
9948		memcpy(desc, port->port_devid->data, port->port_devid->len);
9949		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9950		    port->port_devid->len);
9951	}
9952
9953	/*
9954	 * This is for the Relative Target Port(type 4h) identifier
9955	 */
9956	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9957	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9958	    SVPD_ID_TYPE_RELTARG;
9959	desc->length = 4;
9960	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9961	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9962	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9963
9964	/*
9965	 * This is for the Target Port Group(type 5h) identifier
9966	 */
9967	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9968	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9969	    SVPD_ID_TYPE_TPORTGRP;
9970	desc->length = 4;
9971	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / softc->port_cnt + 1,
9972	    &desc->identifier[2]);
9973	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9974	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9975
9976	/*
9977	 * This is for the Target identifier
9978	 */
9979	if (port && port->target_devid) {
9980		memcpy(desc, port->target_devid->data, port->target_devid->len);
9981	}
9982
9983	ctl_set_success(ctsio);
9984	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9985	ctsio->be_move_done = ctl_config_move_done;
9986	ctl_datamove((union ctl_io *)ctsio);
9987	return (CTL_RETVAL_COMPLETE);
9988}
9989
9990static int
9991ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9992{
9993	struct ctl_softc *softc = control_softc;
9994	struct scsi_vpd_scsi_ports *sp;
9995	struct scsi_vpd_port_designation *pd;
9996	struct scsi_vpd_port_designation_cont *pdc;
9997	struct ctl_lun *lun;
9998	struct ctl_port *port;
9999	int data_len, num_target_ports, iid_len, id_len;
10000
10001	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10002
10003	num_target_ports = 0;
10004	iid_len = 0;
10005	id_len = 0;
10006	mtx_lock(&softc->ctl_lock);
10007	STAILQ_FOREACH(port, &softc->port_list, links) {
10008		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10009			continue;
10010		if (lun != NULL &&
10011		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
10012			continue;
10013		num_target_ports++;
10014		if (port->init_devid)
10015			iid_len += port->init_devid->len;
10016		if (port->port_devid)
10017			id_len += port->port_devid->len;
10018	}
10019	mtx_unlock(&softc->ctl_lock);
10020
10021	data_len = sizeof(struct scsi_vpd_scsi_ports) +
10022	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10023	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10024	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10025	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10026	ctsio->kern_sg_entries = 0;
10027
10028	if (data_len < alloc_len) {
10029		ctsio->residual = alloc_len - data_len;
10030		ctsio->kern_data_len = data_len;
10031		ctsio->kern_total_len = data_len;
10032	} else {
10033		ctsio->residual = 0;
10034		ctsio->kern_data_len = alloc_len;
10035		ctsio->kern_total_len = alloc_len;
10036	}
10037	ctsio->kern_data_resid = 0;
10038	ctsio->kern_rel_offset = 0;
10039	ctsio->kern_sg_entries = 0;
10040
10041	/*
10042	 * The control device is always connected.  The disk device, on the
10043	 * other hand, may not be online all the time.  Need to change this
10044	 * to figure out whether the disk device is actually online or not.
10045	 */
10046	if (lun != NULL)
10047		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10048				  lun->be_lun->lun_type;
10049	else
10050		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10051
10052	sp->page_code = SVPD_SCSI_PORTS;
10053	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10054	    sp->page_length);
10055	pd = &sp->design[0];
10056
10057	mtx_lock(&softc->ctl_lock);
10058	STAILQ_FOREACH(port, &softc->port_list, links) {
10059		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10060			continue;
10061		if (lun != NULL &&
10062		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
10063			continue;
10064		scsi_ulto2b(port->targ_port, pd->relative_port_id);
10065		if (port->init_devid) {
10066			iid_len = port->init_devid->len;
10067			memcpy(pd->initiator_transportid,
10068			    port->init_devid->data, port->init_devid->len);
10069		} else
10070			iid_len = 0;
10071		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10072		pdc = (struct scsi_vpd_port_designation_cont *)
10073		    (&pd->initiator_transportid[iid_len]);
10074		if (port->port_devid) {
10075			id_len = port->port_devid->len;
10076			memcpy(pdc->target_port_descriptors,
10077			    port->port_devid->data, port->port_devid->len);
10078		} else
10079			id_len = 0;
10080		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10081		pd = (struct scsi_vpd_port_designation *)
10082		    ((uint8_t *)pdc->target_port_descriptors + id_len);
10083	}
10084	mtx_unlock(&softc->ctl_lock);
10085
10086	ctl_set_success(ctsio);
10087	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10088	ctsio->be_move_done = ctl_config_move_done;
10089	ctl_datamove((union ctl_io *)ctsio);
10090	return (CTL_RETVAL_COMPLETE);
10091}
10092
10093static int
10094ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10095{
10096	struct scsi_vpd_block_limits *bl_ptr;
10097	struct ctl_lun *lun;
10098	int bs;
10099
10100	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10101
10102	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10103	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10104	ctsio->kern_sg_entries = 0;
10105
10106	if (sizeof(*bl_ptr) < alloc_len) {
10107		ctsio->residual = alloc_len - sizeof(*bl_ptr);
10108		ctsio->kern_data_len = sizeof(*bl_ptr);
10109		ctsio->kern_total_len = sizeof(*bl_ptr);
10110	} else {
10111		ctsio->residual = 0;
10112		ctsio->kern_data_len = alloc_len;
10113		ctsio->kern_total_len = alloc_len;
10114	}
10115	ctsio->kern_data_resid = 0;
10116	ctsio->kern_rel_offset = 0;
10117	ctsio->kern_sg_entries = 0;
10118
10119	/*
10120	 * The control device is always connected.  The disk device, on the
10121	 * other hand, may not be online all the time.  Need to change this
10122	 * to figure out whether the disk device is actually online or not.
10123	 */
10124	if (lun != NULL)
10125		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10126				  lun->be_lun->lun_type;
10127	else
10128		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10129
10130	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10131	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10132	bl_ptr->max_cmp_write_len = 0xff;
10133	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10134	if (lun != NULL) {
10135		bs = lun->be_lun->blocksize;
10136		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
10137		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10138			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10139			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10140			if (lun->be_lun->ublockexp != 0) {
10141				scsi_ulto4b((1 << lun->be_lun->ublockexp),
10142				    bl_ptr->opt_unmap_grain);
10143				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
10144				    bl_ptr->unmap_grain_align);
10145			}
10146		}
10147		scsi_ulto4b(lun->be_lun->atomicblock,
10148		    bl_ptr->max_atomic_transfer_length);
10149		scsi_ulto4b(0, bl_ptr->atomic_alignment);
10150		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10151	}
10152	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10153
10154	ctl_set_success(ctsio);
10155	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10156	ctsio->be_move_done = ctl_config_move_done;
10157	ctl_datamove((union ctl_io *)ctsio);
10158	return (CTL_RETVAL_COMPLETE);
10159}
10160
10161static int
10162ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10163{
10164	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10165	struct ctl_lun *lun;
10166	const char *value;
10167	u_int i;
10168
10169	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10170
10171	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10172	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10173	ctsio->kern_sg_entries = 0;
10174
10175	if (sizeof(*bdc_ptr) < alloc_len) {
10176		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10177		ctsio->kern_data_len = sizeof(*bdc_ptr);
10178		ctsio->kern_total_len = sizeof(*bdc_ptr);
10179	} else {
10180		ctsio->residual = 0;
10181		ctsio->kern_data_len = alloc_len;
10182		ctsio->kern_total_len = alloc_len;
10183	}
10184	ctsio->kern_data_resid = 0;
10185	ctsio->kern_rel_offset = 0;
10186	ctsio->kern_sg_entries = 0;
10187
10188	/*
10189	 * The control device is always connected.  The disk device, on the
10190	 * other hand, may not be online all the time.  Need to change this
10191	 * to figure out whether the disk device is actually online or not.
10192	 */
10193	if (lun != NULL)
10194		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10195				  lun->be_lun->lun_type;
10196	else
10197		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10198	bdc_ptr->page_code = SVPD_BDC;
10199	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10200	if (lun != NULL &&
10201	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10202		i = strtol(value, NULL, 0);
10203	else
10204		i = CTL_DEFAULT_ROTATION_RATE;
10205	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10206	if (lun != NULL &&
10207	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10208		i = strtol(value, NULL, 0);
10209	else
10210		i = 0;
10211	bdc_ptr->wab_wac_ff = (i & 0x0f);
10212	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10213
10214	ctl_set_success(ctsio);
10215	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10216	ctsio->be_move_done = ctl_config_move_done;
10217	ctl_datamove((union ctl_io *)ctsio);
10218	return (CTL_RETVAL_COMPLETE);
10219}
10220
10221static int
10222ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10223{
10224	struct scsi_vpd_logical_block_prov *lbp_ptr;
10225	struct ctl_lun *lun;
10226
10227	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10228
10229	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10230	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10231	ctsio->kern_sg_entries = 0;
10232
10233	if (sizeof(*lbp_ptr) < alloc_len) {
10234		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10235		ctsio->kern_data_len = sizeof(*lbp_ptr);
10236		ctsio->kern_total_len = sizeof(*lbp_ptr);
10237	} else {
10238		ctsio->residual = 0;
10239		ctsio->kern_data_len = alloc_len;
10240		ctsio->kern_total_len = alloc_len;
10241	}
10242	ctsio->kern_data_resid = 0;
10243	ctsio->kern_rel_offset = 0;
10244	ctsio->kern_sg_entries = 0;
10245
10246	/*
10247	 * The control device is always connected.  The disk device, on the
10248	 * other hand, may not be online all the time.  Need to change this
10249	 * to figure out whether the disk device is actually online or not.
10250	 */
10251	if (lun != NULL)
10252		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10253				  lun->be_lun->lun_type;
10254	else
10255		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10256
10257	lbp_ptr->page_code = SVPD_LBP;
10258	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10259	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10260	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10261		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10262		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10263		lbp_ptr->prov_type = SVPD_LBP_THIN;
10264	}
10265
10266	ctl_set_success(ctsio);
10267	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10268	ctsio->be_move_done = ctl_config_move_done;
10269	ctl_datamove((union ctl_io *)ctsio);
10270	return (CTL_RETVAL_COMPLETE);
10271}
10272
10273/*
10274 * INQUIRY with the EVPD bit set.
10275 */
10276static int
10277ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10278{
10279	struct ctl_lun *lun;
10280	struct scsi_inquiry *cdb;
10281	int alloc_len, retval;
10282
10283	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10284	cdb = (struct scsi_inquiry *)ctsio->cdb;
10285	alloc_len = scsi_2btoul(cdb->length);
10286
10287	switch (cdb->page_code) {
10288	case SVPD_SUPPORTED_PAGES:
10289		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10290		break;
10291	case SVPD_UNIT_SERIAL_NUMBER:
10292		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10293		break;
10294	case SVPD_DEVICE_ID:
10295		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10296		break;
10297	case SVPD_EXTENDED_INQUIRY_DATA:
10298		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10299		break;
10300	case SVPD_MODE_PAGE_POLICY:
10301		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10302		break;
10303	case SVPD_SCSI_PORTS:
10304		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10305		break;
10306	case SVPD_SCSI_TPC:
10307		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10308		break;
10309	case SVPD_BLOCK_LIMITS:
10310		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10311			goto err;
10312		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10313		break;
10314	case SVPD_BDC:
10315		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10316			goto err;
10317		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10318		break;
10319	case SVPD_LBP:
10320		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10321			goto err;
10322		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10323		break;
10324	default:
10325err:
10326		ctl_set_invalid_field(ctsio,
10327				      /*sks_valid*/ 1,
10328				      /*command*/ 1,
10329				      /*field*/ 2,
10330				      /*bit_valid*/ 0,
10331				      /*bit*/ 0);
10332		ctl_done((union ctl_io *)ctsio);
10333		retval = CTL_RETVAL_COMPLETE;
10334		break;
10335	}
10336
10337	return (retval);
10338}
10339
10340/*
10341 * Standard INQUIRY data.
10342 */
10343static int
10344ctl_inquiry_std(struct ctl_scsiio *ctsio)
10345{
10346	struct scsi_inquiry_data *inq_ptr;
10347	struct scsi_inquiry *cdb;
10348	struct ctl_softc *softc;
10349	struct ctl_port *port;
10350	struct ctl_lun *lun;
10351	char *val;
10352	uint32_t alloc_len, data_len;
10353	ctl_port_type port_type;
10354
10355	softc = control_softc;
10356
10357	/*
10358	 * Figure out whether we're talking to a Fibre Channel port or not.
10359	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10360	 * SCSI front ends.
10361	 */
10362	port = ctl_io_port(&ctsio->io_hdr);
10363	if (port != NULL)
10364		port_type = port->port_type;
10365	else
10366		port_type = CTL_PORT_SCSI;
10367	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10368		port_type = CTL_PORT_SCSI;
10369
10370	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10371	cdb = (struct scsi_inquiry *)ctsio->cdb;
10372	alloc_len = scsi_2btoul(cdb->length);
10373
10374	/*
10375	 * We malloc the full inquiry data size here and fill it
10376	 * in.  If the user only asks for less, we'll give him
10377	 * that much.
10378	 */
10379	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10380	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10381	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10382	ctsio->kern_sg_entries = 0;
10383	ctsio->kern_data_resid = 0;
10384	ctsio->kern_rel_offset = 0;
10385
10386	if (data_len < alloc_len) {
10387		ctsio->residual = alloc_len - data_len;
10388		ctsio->kern_data_len = data_len;
10389		ctsio->kern_total_len = data_len;
10390	} else {
10391		ctsio->residual = 0;
10392		ctsio->kern_data_len = alloc_len;
10393		ctsio->kern_total_len = alloc_len;
10394	}
10395
10396	if (lun != NULL) {
10397		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10398		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10399			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10400			    lun->be_lun->lun_type;
10401		} else {
10402			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10403			    lun->be_lun->lun_type;
10404		}
10405	} else
10406		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10407
10408	/* RMB in byte 2 is 0 */
10409	inq_ptr->version = SCSI_REV_SPC4;
10410
10411	/*
10412	 * According to SAM-3, even if a device only supports a single
10413	 * level of LUN addressing, it should still set the HISUP bit:
10414	 *
10415	 * 4.9.1 Logical unit numbers overview
10416	 *
10417	 * All logical unit number formats described in this standard are
10418	 * hierarchical in structure even when only a single level in that
10419	 * hierarchy is used. The HISUP bit shall be set to one in the
10420	 * standard INQUIRY data (see SPC-2) when any logical unit number
10421	 * format described in this standard is used.  Non-hierarchical
10422	 * formats are outside the scope of this standard.
10423	 *
10424	 * Therefore we set the HiSup bit here.
10425	 *
10426	 * The reponse format is 2, per SPC-3.
10427	 */
10428	inq_ptr->response_format = SID_HiSup | 2;
10429
10430	inq_ptr->additional_length = data_len -
10431	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10432	CTL_DEBUG_PRINT(("additional_length = %d\n",
10433			 inq_ptr->additional_length));
10434
10435	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10436	/* 16 bit addressing */
10437	if (port_type == CTL_PORT_SCSI)
10438		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10439	/* XXX set the SID_MultiP bit here if we're actually going to
10440	   respond on multiple ports */
10441	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10442
10443	/* 16 bit data bus, synchronous transfers */
10444	if (port_type == CTL_PORT_SCSI)
10445		inq_ptr->flags = SID_WBus16 | SID_Sync;
10446	/*
10447	 * XXX KDM do we want to support tagged queueing on the control
10448	 * device at all?
10449	 */
10450	if ((lun == NULL)
10451	 || (lun->be_lun->lun_type != T_PROCESSOR))
10452		inq_ptr->flags |= SID_CmdQue;
10453	/*
10454	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10455	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10456	 * name and 4 bytes for the revision.
10457	 */
10458	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10459	    "vendor")) == NULL) {
10460		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10461	} else {
10462		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10463		strncpy(inq_ptr->vendor, val,
10464		    min(sizeof(inq_ptr->vendor), strlen(val)));
10465	}
10466	if (lun == NULL) {
10467		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10468		    sizeof(inq_ptr->product));
10469	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10470		switch (lun->be_lun->lun_type) {
10471		case T_DIRECT:
10472			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10473			    sizeof(inq_ptr->product));
10474			break;
10475		case T_PROCESSOR:
10476			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10477			    sizeof(inq_ptr->product));
10478			break;
10479		default:
10480			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10481			    sizeof(inq_ptr->product));
10482			break;
10483		}
10484	} else {
10485		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10486		strncpy(inq_ptr->product, val,
10487		    min(sizeof(inq_ptr->product), strlen(val)));
10488	}
10489
10490	/*
10491	 * XXX make this a macro somewhere so it automatically gets
10492	 * incremented when we make changes.
10493	 */
10494	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10495	    "revision")) == NULL) {
10496		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10497	} else {
10498		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10499		strncpy(inq_ptr->revision, val,
10500		    min(sizeof(inq_ptr->revision), strlen(val)));
10501	}
10502
10503	/*
10504	 * For parallel SCSI, we support double transition and single
10505	 * transition clocking.  We also support QAS (Quick Arbitration
10506	 * and Selection) and Information Unit transfers on both the
10507	 * control and array devices.
10508	 */
10509	if (port_type == CTL_PORT_SCSI)
10510		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10511				    SID_SPI_IUS;
10512
10513	/* SAM-5 (no version claimed) */
10514	scsi_ulto2b(0x00A0, inq_ptr->version1);
10515	/* SPC-4 (no version claimed) */
10516	scsi_ulto2b(0x0460, inq_ptr->version2);
10517	if (port_type == CTL_PORT_FC) {
10518		/* FCP-2 ANSI INCITS.350:2003 */
10519		scsi_ulto2b(0x0917, inq_ptr->version3);
10520	} else if (port_type == CTL_PORT_SCSI) {
10521		/* SPI-4 ANSI INCITS.362:200x */
10522		scsi_ulto2b(0x0B56, inq_ptr->version3);
10523	} else if (port_type == CTL_PORT_ISCSI) {
10524		/* iSCSI (no version claimed) */
10525		scsi_ulto2b(0x0960, inq_ptr->version3);
10526	} else if (port_type == CTL_PORT_SAS) {
10527		/* SAS (no version claimed) */
10528		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10529	}
10530
10531	if (lun == NULL) {
10532		/* SBC-4 (no version claimed) */
10533		scsi_ulto2b(0x0600, inq_ptr->version4);
10534	} else {
10535		switch (lun->be_lun->lun_type) {
10536		case T_DIRECT:
10537			/* SBC-4 (no version claimed) */
10538			scsi_ulto2b(0x0600, inq_ptr->version4);
10539			break;
10540		case T_PROCESSOR:
10541		default:
10542			break;
10543		}
10544	}
10545
10546	ctl_set_success(ctsio);
10547	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10548	ctsio->be_move_done = ctl_config_move_done;
10549	ctl_datamove((union ctl_io *)ctsio);
10550	return (CTL_RETVAL_COMPLETE);
10551}
10552
10553int
10554ctl_inquiry(struct ctl_scsiio *ctsio)
10555{
10556	struct scsi_inquiry *cdb;
10557	int retval;
10558
10559	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10560
10561	cdb = (struct scsi_inquiry *)ctsio->cdb;
10562	if (cdb->byte2 & SI_EVPD)
10563		retval = ctl_inquiry_evpd(ctsio);
10564	else if (cdb->page_code == 0)
10565		retval = ctl_inquiry_std(ctsio);
10566	else {
10567		ctl_set_invalid_field(ctsio,
10568				      /*sks_valid*/ 1,
10569				      /*command*/ 1,
10570				      /*field*/ 2,
10571				      /*bit_valid*/ 0,
10572				      /*bit*/ 0);
10573		ctl_done((union ctl_io *)ctsio);
10574		return (CTL_RETVAL_COMPLETE);
10575	}
10576
10577	return (retval);
10578}
10579
10580/*
10581 * For known CDB types, parse the LBA and length.
10582 */
10583static int
10584ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10585{
10586	if (io->io_hdr.io_type != CTL_IO_SCSI)
10587		return (1);
10588
10589	switch (io->scsiio.cdb[0]) {
10590	case COMPARE_AND_WRITE: {
10591		struct scsi_compare_and_write *cdb;
10592
10593		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10594
10595		*lba = scsi_8btou64(cdb->addr);
10596		*len = cdb->length;
10597		break;
10598	}
10599	case READ_6:
10600	case WRITE_6: {
10601		struct scsi_rw_6 *cdb;
10602
10603		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10604
10605		*lba = scsi_3btoul(cdb->addr);
10606		/* only 5 bits are valid in the most significant address byte */
10607		*lba &= 0x1fffff;
10608		*len = cdb->length;
10609		break;
10610	}
10611	case READ_10:
10612	case WRITE_10: {
10613		struct scsi_rw_10 *cdb;
10614
10615		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10616
10617		*lba = scsi_4btoul(cdb->addr);
10618		*len = scsi_2btoul(cdb->length);
10619		break;
10620	}
10621	case WRITE_VERIFY_10: {
10622		struct scsi_write_verify_10 *cdb;
10623
10624		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10625
10626		*lba = scsi_4btoul(cdb->addr);
10627		*len = scsi_2btoul(cdb->length);
10628		break;
10629	}
10630	case READ_12:
10631	case WRITE_12: {
10632		struct scsi_rw_12 *cdb;
10633
10634		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10635
10636		*lba = scsi_4btoul(cdb->addr);
10637		*len = scsi_4btoul(cdb->length);
10638		break;
10639	}
10640	case WRITE_VERIFY_12: {
10641		struct scsi_write_verify_12 *cdb;
10642
10643		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10644
10645		*lba = scsi_4btoul(cdb->addr);
10646		*len = scsi_4btoul(cdb->length);
10647		break;
10648	}
10649	case READ_16:
10650	case WRITE_16:
10651	case WRITE_ATOMIC_16: {
10652		struct scsi_rw_16 *cdb;
10653
10654		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10655
10656		*lba = scsi_8btou64(cdb->addr);
10657		*len = scsi_4btoul(cdb->length);
10658		break;
10659	}
10660	case WRITE_VERIFY_16: {
10661		struct scsi_write_verify_16 *cdb;
10662
10663		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10664
10665		*lba = scsi_8btou64(cdb->addr);
10666		*len = scsi_4btoul(cdb->length);
10667		break;
10668	}
10669	case WRITE_SAME_10: {
10670		struct scsi_write_same_10 *cdb;
10671
10672		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10673
10674		*lba = scsi_4btoul(cdb->addr);
10675		*len = scsi_2btoul(cdb->length);
10676		break;
10677	}
10678	case WRITE_SAME_16: {
10679		struct scsi_write_same_16 *cdb;
10680
10681		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10682
10683		*lba = scsi_8btou64(cdb->addr);
10684		*len = scsi_4btoul(cdb->length);
10685		break;
10686	}
10687	case VERIFY_10: {
10688		struct scsi_verify_10 *cdb;
10689
10690		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10691
10692		*lba = scsi_4btoul(cdb->addr);
10693		*len = scsi_2btoul(cdb->length);
10694		break;
10695	}
10696	case VERIFY_12: {
10697		struct scsi_verify_12 *cdb;
10698
10699		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10700
10701		*lba = scsi_4btoul(cdb->addr);
10702		*len = scsi_4btoul(cdb->length);
10703		break;
10704	}
10705	case VERIFY_16: {
10706		struct scsi_verify_16 *cdb;
10707
10708		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10709
10710		*lba = scsi_8btou64(cdb->addr);
10711		*len = scsi_4btoul(cdb->length);
10712		break;
10713	}
10714	case UNMAP: {
10715		*lba = 0;
10716		*len = UINT64_MAX;
10717		break;
10718	}
10719	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10720		struct scsi_get_lba_status *cdb;
10721
10722		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10723		*lba = scsi_8btou64(cdb->addr);
10724		*len = UINT32_MAX;
10725		break;
10726	}
10727	default:
10728		return (1);
10729		break; /* NOTREACHED */
10730	}
10731
10732	return (0);
10733}
10734
10735static ctl_action
10736ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10737    bool seq)
10738{
10739	uint64_t endlba1, endlba2;
10740
10741	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10742	endlba2 = lba2 + len2 - 1;
10743
10744	if ((endlba1 < lba2) || (endlba2 < lba1))
10745		return (CTL_ACTION_PASS);
10746	else
10747		return (CTL_ACTION_BLOCK);
10748}
10749
10750static int
10751ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10752{
10753	struct ctl_ptr_len_flags *ptrlen;
10754	struct scsi_unmap_desc *buf, *end, *range;
10755	uint64_t lba;
10756	uint32_t len;
10757
10758	/* If not UNMAP -- go other way. */
10759	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10760	    io->scsiio.cdb[0] != UNMAP)
10761		return (CTL_ACTION_ERROR);
10762
10763	/* If UNMAP without data -- block and wait for data. */
10764	ptrlen = (struct ctl_ptr_len_flags *)
10765	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10766	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10767	    ptrlen->ptr == NULL)
10768		return (CTL_ACTION_BLOCK);
10769
10770	/* UNMAP with data -- check for collision. */
10771	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10772	end = buf + ptrlen->len / sizeof(*buf);
10773	for (range = buf; range < end; range++) {
10774		lba = scsi_8btou64(range->lba);
10775		len = scsi_4btoul(range->length);
10776		if ((lba < lba2 + len2) && (lba + len > lba2))
10777			return (CTL_ACTION_BLOCK);
10778	}
10779	return (CTL_ACTION_PASS);
10780}
10781
10782static ctl_action
10783ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10784{
10785	uint64_t lba1, lba2;
10786	uint64_t len1, len2;
10787	int retval;
10788
10789	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10790		return (CTL_ACTION_ERROR);
10791
10792	retval = ctl_extent_check_unmap(io1, lba2, len2);
10793	if (retval != CTL_ACTION_ERROR)
10794		return (retval);
10795
10796	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10797		return (CTL_ACTION_ERROR);
10798
10799	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10800		seq = FALSE;
10801	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10802}
10803
10804static ctl_action
10805ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10806{
10807	uint64_t lba1, lba2;
10808	uint64_t len1, len2;
10809
10810	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10811		return (CTL_ACTION_PASS);
10812	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10813		return (CTL_ACTION_ERROR);
10814	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10815		return (CTL_ACTION_ERROR);
10816
10817	if (lba1 + len1 == lba2)
10818		return (CTL_ACTION_BLOCK);
10819	return (CTL_ACTION_PASS);
10820}
10821
10822static ctl_action
10823ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10824    union ctl_io *ooa_io)
10825{
10826	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10827	ctl_serialize_action *serialize_row;
10828
10829	/*
10830	 * The initiator attempted multiple untagged commands at the same
10831	 * time.  Can't do that.
10832	 */
10833	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10834	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10835	 && ((pending_io->io_hdr.nexus.targ_port ==
10836	      ooa_io->io_hdr.nexus.targ_port)
10837	  && (pending_io->io_hdr.nexus.initid ==
10838	      ooa_io->io_hdr.nexus.initid))
10839	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10840	      CTL_FLAG_STATUS_SENT)) == 0))
10841		return (CTL_ACTION_OVERLAP);
10842
10843	/*
10844	 * The initiator attempted to send multiple tagged commands with
10845	 * the same ID.  (It's fine if different initiators have the same
10846	 * tag ID.)
10847	 *
10848	 * Even if all of those conditions are true, we don't kill the I/O
10849	 * if the command ahead of us has been aborted.  We won't end up
10850	 * sending it to the FETD, and it's perfectly legal to resend a
10851	 * command with the same tag number as long as the previous
10852	 * instance of this tag number has been aborted somehow.
10853	 */
10854	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10855	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10856	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10857	 && ((pending_io->io_hdr.nexus.targ_port ==
10858	      ooa_io->io_hdr.nexus.targ_port)
10859	  && (pending_io->io_hdr.nexus.initid ==
10860	      ooa_io->io_hdr.nexus.initid))
10861	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10862	      CTL_FLAG_STATUS_SENT)) == 0))
10863		return (CTL_ACTION_OVERLAP_TAG);
10864
10865	/*
10866	 * If we get a head of queue tag, SAM-3 says that we should
10867	 * immediately execute it.
10868	 *
10869	 * What happens if this command would normally block for some other
10870	 * reason?  e.g. a request sense with a head of queue tag
10871	 * immediately after a write.  Normally that would block, but this
10872	 * will result in its getting executed immediately...
10873	 *
10874	 * We currently return "pass" instead of "skip", so we'll end up
10875	 * going through the rest of the queue to check for overlapped tags.
10876	 *
10877	 * XXX KDM check for other types of blockage first??
10878	 */
10879	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10880		return (CTL_ACTION_PASS);
10881
10882	/*
10883	 * Ordered tags have to block until all items ahead of them
10884	 * have completed.  If we get called with an ordered tag, we always
10885	 * block, if something else is ahead of us in the queue.
10886	 */
10887	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10888		return (CTL_ACTION_BLOCK);
10889
10890	/*
10891	 * Simple tags get blocked until all head of queue and ordered tags
10892	 * ahead of them have completed.  I'm lumping untagged commands in
10893	 * with simple tags here.  XXX KDM is that the right thing to do?
10894	 */
10895	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10896	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10897	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10898	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10899		return (CTL_ACTION_BLOCK);
10900
10901	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10902	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10903
10904	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10905
10906	switch (serialize_row[pending_entry->seridx]) {
10907	case CTL_SER_BLOCK:
10908		return (CTL_ACTION_BLOCK);
10909	case CTL_SER_EXTENT:
10910		return (ctl_extent_check(ooa_io, pending_io,
10911		    (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10912	case CTL_SER_EXTENTOPT:
10913		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10914		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10915			return (ctl_extent_check(ooa_io, pending_io,
10916			    (lun->be_lun &&
10917			     lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10918		return (CTL_ACTION_PASS);
10919	case CTL_SER_EXTENTSEQ:
10920		if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
10921			return (ctl_extent_check_seq(ooa_io, pending_io));
10922		return (CTL_ACTION_PASS);
10923	case CTL_SER_PASS:
10924		return (CTL_ACTION_PASS);
10925	case CTL_SER_BLOCKOPT:
10926		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10927		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10928			return (CTL_ACTION_BLOCK);
10929		return (CTL_ACTION_PASS);
10930	case CTL_SER_SKIP:
10931		return (CTL_ACTION_SKIP);
10932	default:
10933		panic("invalid serialization value %d",
10934		      serialize_row[pending_entry->seridx]);
10935	}
10936
10937	return (CTL_ACTION_ERROR);
10938}
10939
10940/*
10941 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10942 * Assumptions:
10943 * - pending_io is generally either incoming, or on the blocked queue
10944 * - starting I/O is the I/O we want to start the check with.
10945 */
10946static ctl_action
10947ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10948	      union ctl_io *starting_io)
10949{
10950	union ctl_io *ooa_io;
10951	ctl_action action;
10952
10953	mtx_assert(&lun->lun_lock, MA_OWNED);
10954
10955	/*
10956	 * Run back along the OOA queue, starting with the current
10957	 * blocked I/O and going through every I/O before it on the
10958	 * queue.  If starting_io is NULL, we'll just end up returning
10959	 * CTL_ACTION_PASS.
10960	 */
10961	for (ooa_io = starting_io; ooa_io != NULL;
10962	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10963	     ooa_links)){
10964
10965		/*
10966		 * This routine just checks to see whether
10967		 * cur_blocked is blocked by ooa_io, which is ahead
10968		 * of it in the queue.  It doesn't queue/dequeue
10969		 * cur_blocked.
10970		 */
10971		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10972		switch (action) {
10973		case CTL_ACTION_BLOCK:
10974		case CTL_ACTION_OVERLAP:
10975		case CTL_ACTION_OVERLAP_TAG:
10976		case CTL_ACTION_SKIP:
10977		case CTL_ACTION_ERROR:
10978			return (action);
10979			break; /* NOTREACHED */
10980		case CTL_ACTION_PASS:
10981			break;
10982		default:
10983			panic("invalid action %d", action);
10984			break;  /* NOTREACHED */
10985		}
10986	}
10987
10988	return (CTL_ACTION_PASS);
10989}
10990
10991/*
10992 * Assumptions:
10993 * - An I/O has just completed, and has been removed from the per-LUN OOA
10994 *   queue, so some items on the blocked queue may now be unblocked.
10995 */
10996static int
10997ctl_check_blocked(struct ctl_lun *lun)
10998{
10999	struct ctl_softc *softc = lun->ctl_softc;
11000	union ctl_io *cur_blocked, *next_blocked;
11001
11002	mtx_assert(&lun->lun_lock, MA_OWNED);
11003
11004	/*
11005	 * Run forward from the head of the blocked queue, checking each
11006	 * entry against the I/Os prior to it on the OOA queue to see if
11007	 * there is still any blockage.
11008	 *
11009	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11010	 * with our removing a variable on it while it is traversing the
11011	 * list.
11012	 */
11013	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11014	     cur_blocked != NULL; cur_blocked = next_blocked) {
11015		union ctl_io *prev_ooa;
11016		ctl_action action;
11017
11018		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11019							  blocked_links);
11020
11021		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11022						      ctl_ooaq, ooa_links);
11023
11024		/*
11025		 * If cur_blocked happens to be the first item in the OOA
11026		 * queue now, prev_ooa will be NULL, and the action
11027		 * returned will just be CTL_ACTION_PASS.
11028		 */
11029		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11030
11031		switch (action) {
11032		case CTL_ACTION_BLOCK:
11033			/* Nothing to do here, still blocked */
11034			break;
11035		case CTL_ACTION_OVERLAP:
11036		case CTL_ACTION_OVERLAP_TAG:
11037			/*
11038			 * This shouldn't happen!  In theory we've already
11039			 * checked this command for overlap...
11040			 */
11041			break;
11042		case CTL_ACTION_PASS:
11043		case CTL_ACTION_SKIP: {
11044			const struct ctl_cmd_entry *entry;
11045
11046			/*
11047			 * The skip case shouldn't happen, this transaction
11048			 * should have never made it onto the blocked queue.
11049			 */
11050			/*
11051			 * This I/O is no longer blocked, we can remove it
11052			 * from the blocked queue.  Since this is a TAILQ
11053			 * (doubly linked list), we can do O(1) removals
11054			 * from any place on the list.
11055			 */
11056			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11057				     blocked_links);
11058			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11059
11060			if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11061			    (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11062				/*
11063				 * Need to send IO back to original side to
11064				 * run
11065				 */
11066				union ctl_ha_msg msg_info;
11067
11068				cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11069				msg_info.hdr.original_sc =
11070					cur_blocked->io_hdr.original_sc;
11071				msg_info.hdr.serializing_sc = cur_blocked;
11072				msg_info.hdr.msg_type = CTL_MSG_R2R;
11073				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11074				    sizeof(msg_info.hdr), M_NOWAIT);
11075				break;
11076			}
11077			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11078
11079			/*
11080			 * Check this I/O for LUN state changes that may
11081			 * have happened while this command was blocked.
11082			 * The LUN state may have been changed by a command
11083			 * ahead of us in the queue, so we need to re-check
11084			 * for any states that can be caused by SCSI
11085			 * commands.
11086			 */
11087			if (ctl_scsiio_lun_check(lun, entry,
11088						 &cur_blocked->scsiio) == 0) {
11089				cur_blocked->io_hdr.flags |=
11090				                      CTL_FLAG_IS_WAS_ON_RTR;
11091				ctl_enqueue_rtr(cur_blocked);
11092			} else
11093				ctl_done(cur_blocked);
11094			break;
11095		}
11096		default:
11097			/*
11098			 * This probably shouldn't happen -- we shouldn't
11099			 * get CTL_ACTION_ERROR, or anything else.
11100			 */
11101			break;
11102		}
11103	}
11104
11105	return (CTL_RETVAL_COMPLETE);
11106}
11107
11108/*
11109 * This routine (with one exception) checks LUN flags that can be set by
11110 * commands ahead of us in the OOA queue.  These flags have to be checked
11111 * when a command initially comes in, and when we pull a command off the
11112 * blocked queue and are preparing to execute it.  The reason we have to
11113 * check these flags for commands on the blocked queue is that the LUN
11114 * state may have been changed by a command ahead of us while we're on the
11115 * blocked queue.
11116 *
11117 * Ordering is somewhat important with these checks, so please pay
11118 * careful attention to the placement of any new checks.
11119 */
11120static int
11121ctl_scsiio_lun_check(struct ctl_lun *lun,
11122    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11123{
11124	struct ctl_softc *softc = lun->ctl_softc;
11125	int retval;
11126	uint32_t residx;
11127
11128	retval = 0;
11129
11130	mtx_assert(&lun->lun_lock, MA_OWNED);
11131
11132	/*
11133	 * If this shelf is a secondary shelf controller, we may have to
11134	 * reject some commands disallowed by HA mode and link state.
11135	 */
11136	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11137		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11138		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11139			ctl_set_lun_unavail(ctsio);
11140			retval = 1;
11141			goto bailout;
11142		}
11143		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11144		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11145			ctl_set_lun_transit(ctsio);
11146			retval = 1;
11147			goto bailout;
11148		}
11149		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11150		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11151			ctl_set_lun_standby(ctsio);
11152			retval = 1;
11153			goto bailout;
11154		}
11155
11156		/* The rest of checks are only done on executing side */
11157		if (softc->ha_mode == CTL_HA_MODE_XFER)
11158			goto bailout;
11159	}
11160
11161	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11162		if (lun->be_lun &&
11163		    lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11164			ctl_set_hw_write_protected(ctsio);
11165			retval = 1;
11166			goto bailout;
11167		}
11168		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11169		    .eca_and_aen & SCP_SWP) != 0) {
11170			ctl_set_sense(ctsio, /*current_error*/ 1,
11171			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11172			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11173			retval = 1;
11174			goto bailout;
11175		}
11176	}
11177
11178	/*
11179	 * Check for a reservation conflict.  If this command isn't allowed
11180	 * even on reserved LUNs, and if this initiator isn't the one who
11181	 * reserved us, reject the command with a reservation conflict.
11182	 */
11183	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11184	if ((lun->flags & CTL_LUN_RESERVED)
11185	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11186		if (lun->res_idx != residx) {
11187			ctl_set_reservation_conflict(ctsio);
11188			retval = 1;
11189			goto bailout;
11190		}
11191	}
11192
11193	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11194	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11195		/* No reservation or command is allowed. */;
11196	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11197	    (lun->res_type == SPR_TYPE_WR_EX ||
11198	     lun->res_type == SPR_TYPE_WR_EX_RO ||
11199	     lun->res_type == SPR_TYPE_WR_EX_AR)) {
11200		/* The command is allowed for Write Exclusive resv. */;
11201	} else {
11202		/*
11203		 * if we aren't registered or it's a res holder type
11204		 * reservation and this isn't the res holder then set a
11205		 * conflict.
11206		 */
11207		if (ctl_get_prkey(lun, residx) == 0
11208		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11209			ctl_set_reservation_conflict(ctsio);
11210			retval = 1;
11211			goto bailout;
11212		}
11213	}
11214
11215	if ((lun->flags & CTL_LUN_OFFLINE)
11216	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0)) {
11217		ctl_set_lun_not_ready(ctsio);
11218		retval = 1;
11219		goto bailout;
11220	}
11221
11222	if ((lun->flags & CTL_LUN_STOPPED)
11223	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11224		/* "Logical unit not ready, initializing cmd. required" */
11225		ctl_set_lun_stopped(ctsio);
11226		retval = 1;
11227		goto bailout;
11228	}
11229
11230	if ((lun->flags & CTL_LUN_INOPERABLE)
11231	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11232		/* "Medium format corrupted" */
11233		ctl_set_medium_format_corrupted(ctsio);
11234		retval = 1;
11235		goto bailout;
11236	}
11237
11238bailout:
11239	return (retval);
11240}
11241
11242static void
11243ctl_failover_io(union ctl_io *io, int have_lock)
11244{
11245	ctl_set_busy(&io->scsiio);
11246	ctl_done(io);
11247}
11248
11249static void
11250ctl_failover_lun(struct ctl_lun *lun)
11251{
11252	struct ctl_softc *softc = lun->ctl_softc;
11253	struct ctl_io_hdr *io, *next_io;
11254
11255	CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", lun->lun));
11256	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11257		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11258			/* We are master */
11259			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11260				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11261					io->flags |= CTL_FLAG_ABORT;
11262					io->flags |= CTL_FLAG_FAILOVER;
11263				} else { /* This can be only due to DATAMOVE */
11264					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11265					io->flags &= ~CTL_FLAG_DMA_INPROG;
11266					io->flags |= CTL_FLAG_IO_ACTIVE;
11267					io->port_status = 31340;
11268					ctl_enqueue_isc((union ctl_io *)io);
11269				}
11270			}
11271			/* We are slave */
11272			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11273				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11274				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11275					io->flags |= CTL_FLAG_FAILOVER;
11276				} else {
11277					ctl_set_busy(&((union ctl_io *)io)->
11278					    scsiio);
11279					ctl_done((union ctl_io *)io);
11280				}
11281			}
11282		}
11283	} else { /* SERIALIZE modes */
11284		TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11285		    next_io) {
11286			/* We are master */
11287			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11288				TAILQ_REMOVE(&lun->blocked_queue, io,
11289				    blocked_links);
11290				io->flags &= ~CTL_FLAG_BLOCKED;
11291				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11292				ctl_free_io((union ctl_io *)io);
11293			}
11294		}
11295		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11296			/* We are master */
11297			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11298				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11299				ctl_free_io((union ctl_io *)io);
11300			}
11301			/* We are slave */
11302			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11303				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11304				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11305					ctl_set_busy(&((union ctl_io *)io)->
11306					    scsiio);
11307					ctl_done((union ctl_io *)io);
11308				}
11309			}
11310		}
11311		ctl_check_blocked(lun);
11312	}
11313}
11314
11315static int
11316ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11317{
11318	struct ctl_lun *lun;
11319	const struct ctl_cmd_entry *entry;
11320	uint32_t initidx, targ_lun;
11321	int retval;
11322
11323	retval = 0;
11324
11325	lun = NULL;
11326
11327	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11328	if ((targ_lun < CTL_MAX_LUNS)
11329	 && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11330		/*
11331		 * If the LUN is invalid, pretend that it doesn't exist.
11332		 * It will go away as soon as all pending I/O has been
11333		 * completed.
11334		 */
11335		mtx_lock(&lun->lun_lock);
11336		if (lun->flags & CTL_LUN_DISABLED) {
11337			mtx_unlock(&lun->lun_lock);
11338			lun = NULL;
11339			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11340			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11341		} else {
11342			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11343			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11344				lun->be_lun;
11345
11346			/*
11347			 * Every I/O goes into the OOA queue for a
11348			 * particular LUN, and stays there until completion.
11349			 */
11350#ifdef CTL_TIME_IO
11351			if (TAILQ_EMPTY(&lun->ooa_queue)) {
11352				lun->idle_time += getsbinuptime() -
11353				    lun->last_busy;
11354			}
11355#endif
11356			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11357			    ooa_links);
11358		}
11359	} else {
11360		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11361		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11362	}
11363
11364	/* Get command entry and return error if it is unsuppotyed. */
11365	entry = ctl_validate_command(ctsio);
11366	if (entry == NULL) {
11367		if (lun)
11368			mtx_unlock(&lun->lun_lock);
11369		return (retval);
11370	}
11371
11372	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11373	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11374
11375	/*
11376	 * Check to see whether we can send this command to LUNs that don't
11377	 * exist.  This should pretty much only be the case for inquiry
11378	 * and request sense.  Further checks, below, really require having
11379	 * a LUN, so we can't really check the command anymore.  Just put
11380	 * it on the rtr queue.
11381	 */
11382	if (lun == NULL) {
11383		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11384			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11385			ctl_enqueue_rtr((union ctl_io *)ctsio);
11386			return (retval);
11387		}
11388
11389		ctl_set_unsupported_lun(ctsio);
11390		ctl_done((union ctl_io *)ctsio);
11391		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11392		return (retval);
11393	} else {
11394		/*
11395		 * Make sure we support this particular command on this LUN.
11396		 * e.g., we don't support writes to the control LUN.
11397		 */
11398		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11399			mtx_unlock(&lun->lun_lock);
11400			ctl_set_invalid_opcode(ctsio);
11401			ctl_done((union ctl_io *)ctsio);
11402			return (retval);
11403		}
11404	}
11405
11406	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11407
11408#ifdef CTL_WITH_CA
11409	/*
11410	 * If we've got a request sense, it'll clear the contingent
11411	 * allegiance condition.  Otherwise, if we have a CA condition for
11412	 * this initiator, clear it, because it sent down a command other
11413	 * than request sense.
11414	 */
11415	if ((ctsio->cdb[0] != REQUEST_SENSE)
11416	 && (ctl_is_set(lun->have_ca, initidx)))
11417		ctl_clear_mask(lun->have_ca, initidx);
11418#endif
11419
11420	/*
11421	 * If the command has this flag set, it handles its own unit
11422	 * attention reporting, we shouldn't do anything.  Otherwise we
11423	 * check for any pending unit attentions, and send them back to the
11424	 * initiator.  We only do this when a command initially comes in,
11425	 * not when we pull it off the blocked queue.
11426	 *
11427	 * According to SAM-3, section 5.3.2, the order that things get
11428	 * presented back to the host is basically unit attentions caused
11429	 * by some sort of reset event, busy status, reservation conflicts
11430	 * or task set full, and finally any other status.
11431	 *
11432	 * One issue here is that some of the unit attentions we report
11433	 * don't fall into the "reset" category (e.g. "reported luns data
11434	 * has changed").  So reporting it here, before the reservation
11435	 * check, may be technically wrong.  I guess the only thing to do
11436	 * would be to check for and report the reset events here, and then
11437	 * check for the other unit attention types after we check for a
11438	 * reservation conflict.
11439	 *
11440	 * XXX KDM need to fix this
11441	 */
11442	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11443		ctl_ua_type ua_type;
11444
11445		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11446		    SSD_TYPE_NONE);
11447		if (ua_type != CTL_UA_NONE) {
11448			mtx_unlock(&lun->lun_lock);
11449			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11450			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11451			ctsio->sense_len = SSD_FULL_SIZE;
11452			ctl_done((union ctl_io *)ctsio);
11453			return (retval);
11454		}
11455	}
11456
11457
11458	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11459		mtx_unlock(&lun->lun_lock);
11460		ctl_done((union ctl_io *)ctsio);
11461		return (retval);
11462	}
11463
11464	/*
11465	 * XXX CHD this is where we want to send IO to other side if
11466	 * this LUN is secondary on this SC. We will need to make a copy
11467	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11468	 * the copy we send as FROM_OTHER.
11469	 * We also need to stuff the address of the original IO so we can
11470	 * find it easily. Something similar will need be done on the other
11471	 * side so when we are done we can find the copy.
11472	 */
11473	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11474	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11475	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11476		union ctl_ha_msg msg_info;
11477		int isc_retval;
11478
11479		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11480		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11481		mtx_unlock(&lun->lun_lock);
11482
11483		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11484		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11485		msg_info.hdr.serializing_sc = NULL;
11486		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11487		msg_info.scsi.tag_num = ctsio->tag_num;
11488		msg_info.scsi.tag_type = ctsio->tag_type;
11489		msg_info.scsi.cdb_len = ctsio->cdb_len;
11490		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11491
11492		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11493		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11494		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11495			ctl_set_busy(ctsio);
11496			ctl_done((union ctl_io *)ctsio);
11497			return (retval);
11498		}
11499		return (retval);
11500	}
11501
11502	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11503			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11504			      ctl_ooaq, ooa_links))) {
11505	case CTL_ACTION_BLOCK:
11506		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11507		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11508				  blocked_links);
11509		mtx_unlock(&lun->lun_lock);
11510		return (retval);
11511	case CTL_ACTION_PASS:
11512	case CTL_ACTION_SKIP:
11513		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11514		mtx_unlock(&lun->lun_lock);
11515		ctl_enqueue_rtr((union ctl_io *)ctsio);
11516		break;
11517	case CTL_ACTION_OVERLAP:
11518		mtx_unlock(&lun->lun_lock);
11519		ctl_set_overlapped_cmd(ctsio);
11520		ctl_done((union ctl_io *)ctsio);
11521		break;
11522	case CTL_ACTION_OVERLAP_TAG:
11523		mtx_unlock(&lun->lun_lock);
11524		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11525		ctl_done((union ctl_io *)ctsio);
11526		break;
11527	case CTL_ACTION_ERROR:
11528	default:
11529		mtx_unlock(&lun->lun_lock);
11530		ctl_set_internal_failure(ctsio,
11531					 /*sks_valid*/ 0,
11532					 /*retry_count*/ 0);
11533		ctl_done((union ctl_io *)ctsio);
11534		break;
11535	}
11536	return (retval);
11537}
11538
11539const struct ctl_cmd_entry *
11540ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11541{
11542	const struct ctl_cmd_entry *entry;
11543	int service_action;
11544
11545	entry = &ctl_cmd_table[ctsio->cdb[0]];
11546	if (sa)
11547		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11548	if (entry->flags & CTL_CMD_FLAG_SA5) {
11549		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11550		entry = &((const struct ctl_cmd_entry *)
11551		    entry->execute)[service_action];
11552	}
11553	return (entry);
11554}
11555
11556const struct ctl_cmd_entry *
11557ctl_validate_command(struct ctl_scsiio *ctsio)
11558{
11559	const struct ctl_cmd_entry *entry;
11560	int i, sa;
11561	uint8_t diff;
11562
11563	entry = ctl_get_cmd_entry(ctsio, &sa);
11564	if (entry->execute == NULL) {
11565		if (sa)
11566			ctl_set_invalid_field(ctsio,
11567					      /*sks_valid*/ 1,
11568					      /*command*/ 1,
11569					      /*field*/ 1,
11570					      /*bit_valid*/ 1,
11571					      /*bit*/ 4);
11572		else
11573			ctl_set_invalid_opcode(ctsio);
11574		ctl_done((union ctl_io *)ctsio);
11575		return (NULL);
11576	}
11577	KASSERT(entry->length > 0,
11578	    ("Not defined length for command 0x%02x/0x%02x",
11579	     ctsio->cdb[0], ctsio->cdb[1]));
11580	for (i = 1; i < entry->length; i++) {
11581		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11582		if (diff == 0)
11583			continue;
11584		ctl_set_invalid_field(ctsio,
11585				      /*sks_valid*/ 1,
11586				      /*command*/ 1,
11587				      /*field*/ i,
11588				      /*bit_valid*/ 1,
11589				      /*bit*/ fls(diff) - 1);
11590		ctl_done((union ctl_io *)ctsio);
11591		return (NULL);
11592	}
11593	return (entry);
11594}
11595
11596static int
11597ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11598{
11599
11600	switch (lun_type) {
11601	case T_PROCESSOR:
11602		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11603			return (0);
11604		break;
11605	case T_DIRECT:
11606		if ((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0)
11607			return (0);
11608		break;
11609	default:
11610		return (0);
11611	}
11612	return (1);
11613}
11614
11615static int
11616ctl_scsiio(struct ctl_scsiio *ctsio)
11617{
11618	int retval;
11619	const struct ctl_cmd_entry *entry;
11620
11621	retval = CTL_RETVAL_COMPLETE;
11622
11623	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11624
11625	entry = ctl_get_cmd_entry(ctsio, NULL);
11626
11627	/*
11628	 * If this I/O has been aborted, just send it straight to
11629	 * ctl_done() without executing it.
11630	 */
11631	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11632		ctl_done((union ctl_io *)ctsio);
11633		goto bailout;
11634	}
11635
11636	/*
11637	 * All the checks should have been handled by ctl_scsiio_precheck().
11638	 * We should be clear now to just execute the I/O.
11639	 */
11640	retval = entry->execute(ctsio);
11641
11642bailout:
11643	return (retval);
11644}
11645
11646/*
11647 * Since we only implement one target right now, a bus reset simply resets
11648 * our single target.
11649 */
11650static int
11651ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11652{
11653	return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11654}
11655
11656static int
11657ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11658		 ctl_ua_type ua_type)
11659{
11660	struct ctl_port *port;
11661	struct ctl_lun *lun;
11662	int retval;
11663
11664	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11665		union ctl_ha_msg msg_info;
11666
11667		msg_info.hdr.nexus = io->io_hdr.nexus;
11668		if (ua_type==CTL_UA_TARG_RESET)
11669			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11670		else
11671			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11672		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11673		msg_info.hdr.original_sc = NULL;
11674		msg_info.hdr.serializing_sc = NULL;
11675		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11676		    sizeof(msg_info.task), M_WAITOK);
11677	}
11678	retval = 0;
11679
11680	mtx_lock(&softc->ctl_lock);
11681	port = softc->ctl_ports[io->io_hdr.nexus.targ_port];
11682	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11683		if (port != NULL &&
11684		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
11685			continue;
11686		retval += ctl_do_lun_reset(lun, io, ua_type);
11687	}
11688	mtx_unlock(&softc->ctl_lock);
11689	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11690	return (retval);
11691}
11692
11693/*
11694 * The LUN should always be set.  The I/O is optional, and is used to
11695 * distinguish between I/Os sent by this initiator, and by other
11696 * initiators.  We set unit attention for initiators other than this one.
11697 * SAM-3 is vague on this point.  It does say that a unit attention should
11698 * be established for other initiators when a LUN is reset (see section
11699 * 5.7.3), but it doesn't specifically say that the unit attention should
11700 * be established for this particular initiator when a LUN is reset.  Here
11701 * is the relevant text, from SAM-3 rev 8:
11702 *
11703 * 5.7.2 When a SCSI initiator port aborts its own tasks
11704 *
11705 * When a SCSI initiator port causes its own task(s) to be aborted, no
11706 * notification that the task(s) have been aborted shall be returned to
11707 * the SCSI initiator port other than the completion response for the
11708 * command or task management function action that caused the task(s) to
11709 * be aborted and notification(s) associated with related effects of the
11710 * action (e.g., a reset unit attention condition).
11711 *
11712 * XXX KDM for now, we're setting unit attention for all initiators.
11713 */
11714static int
11715ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11716{
11717	union ctl_io *xio;
11718#if 0
11719	uint32_t initidx;
11720#endif
11721#ifdef CTL_WITH_CA
11722	int i;
11723#endif
11724
11725	mtx_lock(&lun->lun_lock);
11726	/*
11727	 * Run through the OOA queue and abort each I/O.
11728	 */
11729	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11730	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11731		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11732	}
11733
11734	/*
11735	 * This version sets unit attention for every
11736	 */
11737#if 0
11738	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11739	ctl_est_ua_all(lun, initidx, ua_type);
11740#else
11741	ctl_est_ua_all(lun, -1, ua_type);
11742#endif
11743
11744	/*
11745	 * A reset (any kind, really) clears reservations established with
11746	 * RESERVE/RELEASE.  It does not clear reservations established
11747	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11748	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11749	 * reservations made with the RESERVE/RELEASE commands, because
11750	 * those commands are obsolete in SPC-3.
11751	 */
11752	lun->flags &= ~CTL_LUN_RESERVED;
11753
11754#ifdef CTL_WITH_CA
11755	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11756		ctl_clear_mask(lun->have_ca, i);
11757#endif
11758	mtx_unlock(&lun->lun_lock);
11759
11760	return (0);
11761}
11762
11763static int
11764ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
11765{
11766	struct ctl_lun *lun;
11767	uint32_t targ_lun;
11768	int retval;
11769
11770	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11771	mtx_lock(&softc->ctl_lock);
11772	if ((targ_lun >= CTL_MAX_LUNS) ||
11773	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11774		mtx_unlock(&softc->ctl_lock);
11775		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11776		return (1);
11777	}
11778	retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
11779	mtx_unlock(&softc->ctl_lock);
11780	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11781
11782	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11783		union ctl_ha_msg msg_info;
11784
11785		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11786		msg_info.hdr.nexus = io->io_hdr.nexus;
11787		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11788		msg_info.hdr.original_sc = NULL;
11789		msg_info.hdr.serializing_sc = NULL;
11790		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11791		    sizeof(msg_info.task), M_WAITOK);
11792	}
11793	return (retval);
11794}
11795
11796static void
11797ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11798    int other_sc)
11799{
11800	union ctl_io *xio;
11801
11802	mtx_assert(&lun->lun_lock, MA_OWNED);
11803
11804	/*
11805	 * Run through the OOA queue and attempt to find the given I/O.
11806	 * The target port, initiator ID, tag type and tag number have to
11807	 * match the values that we got from the initiator.  If we have an
11808	 * untagged command to abort, simply abort the first untagged command
11809	 * we come to.  We only allow one untagged command at a time of course.
11810	 */
11811	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11812	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11813
11814		if ((targ_port == UINT32_MAX ||
11815		     targ_port == xio->io_hdr.nexus.targ_port) &&
11816		    (init_id == UINT32_MAX ||
11817		     init_id == xio->io_hdr.nexus.initid)) {
11818			if (targ_port != xio->io_hdr.nexus.targ_port ||
11819			    init_id != xio->io_hdr.nexus.initid)
11820				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11821			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11822			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11823				union ctl_ha_msg msg_info;
11824
11825				msg_info.hdr.nexus = xio->io_hdr.nexus;
11826				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11827				msg_info.task.tag_num = xio->scsiio.tag_num;
11828				msg_info.task.tag_type = xio->scsiio.tag_type;
11829				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11830				msg_info.hdr.original_sc = NULL;
11831				msg_info.hdr.serializing_sc = NULL;
11832				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11833				    sizeof(msg_info.task), M_NOWAIT);
11834			}
11835		}
11836	}
11837}
11838
11839static int
11840ctl_abort_task_set(union ctl_io *io)
11841{
11842	struct ctl_softc *softc = control_softc;
11843	struct ctl_lun *lun;
11844	uint32_t targ_lun;
11845
11846	/*
11847	 * Look up the LUN.
11848	 */
11849	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11850	mtx_lock(&softc->ctl_lock);
11851	if ((targ_lun >= CTL_MAX_LUNS) ||
11852	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11853		mtx_unlock(&softc->ctl_lock);
11854		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11855		return (1);
11856	}
11857
11858	mtx_lock(&lun->lun_lock);
11859	mtx_unlock(&softc->ctl_lock);
11860	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11861		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11862		    io->io_hdr.nexus.initid,
11863		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11864	} else { /* CTL_TASK_CLEAR_TASK_SET */
11865		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11866		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11867	}
11868	mtx_unlock(&lun->lun_lock);
11869	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11870	return (0);
11871}
11872
11873static int
11874ctl_i_t_nexus_reset(union ctl_io *io)
11875{
11876	struct ctl_softc *softc = control_softc;
11877	struct ctl_lun *lun;
11878	uint32_t initidx;
11879
11880	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11881		union ctl_ha_msg msg_info;
11882
11883		msg_info.hdr.nexus = io->io_hdr.nexus;
11884		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
11885		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11886		msg_info.hdr.original_sc = NULL;
11887		msg_info.hdr.serializing_sc = NULL;
11888		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11889		    sizeof(msg_info.task), M_WAITOK);
11890	}
11891
11892	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11893	mtx_lock(&softc->ctl_lock);
11894	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11895		mtx_lock(&lun->lun_lock);
11896		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11897		    io->io_hdr.nexus.initid, 1);
11898#ifdef CTL_WITH_CA
11899		ctl_clear_mask(lun->have_ca, initidx);
11900#endif
11901		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
11902			lun->flags &= ~CTL_LUN_RESERVED;
11903		ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
11904		mtx_unlock(&lun->lun_lock);
11905	}
11906	mtx_unlock(&softc->ctl_lock);
11907	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11908	return (0);
11909}
11910
11911static int
11912ctl_abort_task(union ctl_io *io)
11913{
11914	union ctl_io *xio;
11915	struct ctl_lun *lun;
11916	struct ctl_softc *softc;
11917#if 0
11918	struct sbuf sb;
11919	char printbuf[128];
11920#endif
11921	int found;
11922	uint32_t targ_lun;
11923
11924	softc = control_softc;
11925	found = 0;
11926
11927	/*
11928	 * Look up the LUN.
11929	 */
11930	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11931	mtx_lock(&softc->ctl_lock);
11932	if ((targ_lun >= CTL_MAX_LUNS) ||
11933	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11934		mtx_unlock(&softc->ctl_lock);
11935		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11936		return (1);
11937	}
11938
11939#if 0
11940	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11941	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11942#endif
11943
11944	mtx_lock(&lun->lun_lock);
11945	mtx_unlock(&softc->ctl_lock);
11946	/*
11947	 * Run through the OOA queue and attempt to find the given I/O.
11948	 * The target port, initiator ID, tag type and tag number have to
11949	 * match the values that we got from the initiator.  If we have an
11950	 * untagged command to abort, simply abort the first untagged command
11951	 * we come to.  We only allow one untagged command at a time of course.
11952	 */
11953	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11954	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11955#if 0
11956		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
11957
11958		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
11959			    lun->lun, xio->scsiio.tag_num,
11960			    xio->scsiio.tag_type,
11961			    (xio->io_hdr.blocked_links.tqe_prev
11962			    == NULL) ? "" : " BLOCKED",
11963			    (xio->io_hdr.flags &
11964			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
11965			    (xio->io_hdr.flags &
11966			    CTL_FLAG_ABORT) ? " ABORT" : "",
11967			    (xio->io_hdr.flags &
11968			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
11969		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
11970		sbuf_finish(&sb);
11971		printf("%s\n", sbuf_data(&sb));
11972#endif
11973
11974		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
11975		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
11976		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
11977			continue;
11978
11979		/*
11980		 * If the abort says that the task is untagged, the
11981		 * task in the queue must be untagged.  Otherwise,
11982		 * we just check to see whether the tag numbers
11983		 * match.  This is because the QLogic firmware
11984		 * doesn't pass back the tag type in an abort
11985		 * request.
11986		 */
11987#if 0
11988		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
11989		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
11990		 || (xio->scsiio.tag_num == io->taskio.tag_num))
11991#endif
11992		/*
11993		 * XXX KDM we've got problems with FC, because it
11994		 * doesn't send down a tag type with aborts.  So we
11995		 * can only really go by the tag number...
11996		 * This may cause problems with parallel SCSI.
11997		 * Need to figure that out!!
11998		 */
11999		if (xio->scsiio.tag_num == io->taskio.tag_num) {
12000			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12001			found = 1;
12002			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12003			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12004				union ctl_ha_msg msg_info;
12005
12006				msg_info.hdr.nexus = io->io_hdr.nexus;
12007				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12008				msg_info.task.tag_num = io->taskio.tag_num;
12009				msg_info.task.tag_type = io->taskio.tag_type;
12010				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12011				msg_info.hdr.original_sc = NULL;
12012				msg_info.hdr.serializing_sc = NULL;
12013#if 0
12014				printf("Sent Abort to other side\n");
12015#endif
12016				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12017				    sizeof(msg_info.task), M_NOWAIT);
12018			}
12019#if 0
12020			printf("ctl_abort_task: found I/O to abort\n");
12021#endif
12022		}
12023	}
12024	mtx_unlock(&lun->lun_lock);
12025
12026	if (found == 0) {
12027		/*
12028		 * This isn't really an error.  It's entirely possible for
12029		 * the abort and command completion to cross on the wire.
12030		 * This is more of an informative/diagnostic error.
12031		 */
12032#if 0
12033		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12034		       "%u:%u:%u tag %d type %d\n",
12035		       io->io_hdr.nexus.initid,
12036		       io->io_hdr.nexus.targ_port,
12037		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12038		       io->taskio.tag_type);
12039#endif
12040	}
12041	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12042	return (0);
12043}
12044
12045static int
12046ctl_query_task(union ctl_io *io, int task_set)
12047{
12048	union ctl_io *xio;
12049	struct ctl_lun *lun;
12050	struct ctl_softc *softc;
12051	int found = 0;
12052	uint32_t targ_lun;
12053
12054	softc = control_softc;
12055	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12056	mtx_lock(&softc->ctl_lock);
12057	if ((targ_lun >= CTL_MAX_LUNS) ||
12058	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12059		mtx_unlock(&softc->ctl_lock);
12060		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12061		return (1);
12062	}
12063	mtx_lock(&lun->lun_lock);
12064	mtx_unlock(&softc->ctl_lock);
12065	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12066	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12067
12068		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12069		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12070		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12071			continue;
12072
12073		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12074			found = 1;
12075			break;
12076		}
12077	}
12078	mtx_unlock(&lun->lun_lock);
12079	if (found)
12080		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12081	else
12082		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12083	return (0);
12084}
12085
12086static int
12087ctl_query_async_event(union ctl_io *io)
12088{
12089	struct ctl_lun *lun;
12090	struct ctl_softc *softc;
12091	ctl_ua_type ua;
12092	uint32_t targ_lun, initidx;
12093
12094	softc = control_softc;
12095	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12096	mtx_lock(&softc->ctl_lock);
12097	if ((targ_lun >= CTL_MAX_LUNS) ||
12098	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12099		mtx_unlock(&softc->ctl_lock);
12100		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12101		return (1);
12102	}
12103	mtx_lock(&lun->lun_lock);
12104	mtx_unlock(&softc->ctl_lock);
12105	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12106	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12107	mtx_unlock(&lun->lun_lock);
12108	if (ua != CTL_UA_NONE)
12109		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12110	else
12111		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12112	return (0);
12113}
12114
12115static void
12116ctl_run_task(union ctl_io *io)
12117{
12118	struct ctl_softc *softc = control_softc;
12119	int retval = 1;
12120
12121	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12122	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12123	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12124	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12125	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12126	switch (io->taskio.task_action) {
12127	case CTL_TASK_ABORT_TASK:
12128		retval = ctl_abort_task(io);
12129		break;
12130	case CTL_TASK_ABORT_TASK_SET:
12131	case CTL_TASK_CLEAR_TASK_SET:
12132		retval = ctl_abort_task_set(io);
12133		break;
12134	case CTL_TASK_CLEAR_ACA:
12135		break;
12136	case CTL_TASK_I_T_NEXUS_RESET:
12137		retval = ctl_i_t_nexus_reset(io);
12138		break;
12139	case CTL_TASK_LUN_RESET:
12140		retval = ctl_lun_reset(softc, io);
12141		break;
12142	case CTL_TASK_TARGET_RESET:
12143		retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12144		break;
12145	case CTL_TASK_BUS_RESET:
12146		retval = ctl_bus_reset(softc, io);
12147		break;
12148	case CTL_TASK_PORT_LOGIN:
12149		break;
12150	case CTL_TASK_PORT_LOGOUT:
12151		break;
12152	case CTL_TASK_QUERY_TASK:
12153		retval = ctl_query_task(io, 0);
12154		break;
12155	case CTL_TASK_QUERY_TASK_SET:
12156		retval = ctl_query_task(io, 1);
12157		break;
12158	case CTL_TASK_QUERY_ASYNC_EVENT:
12159		retval = ctl_query_async_event(io);
12160		break;
12161	default:
12162		printf("%s: got unknown task management event %d\n",
12163		       __func__, io->taskio.task_action);
12164		break;
12165	}
12166	if (retval == 0)
12167		io->io_hdr.status = CTL_SUCCESS;
12168	else
12169		io->io_hdr.status = CTL_ERROR;
12170	ctl_done(io);
12171}
12172
12173/*
12174 * For HA operation.  Handle commands that come in from the other
12175 * controller.
12176 */
12177static void
12178ctl_handle_isc(union ctl_io *io)
12179{
12180	int free_io;
12181	struct ctl_lun *lun;
12182	struct ctl_softc *softc;
12183	uint32_t targ_lun;
12184
12185	softc = control_softc;
12186
12187	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12188	lun = softc->ctl_luns[targ_lun];
12189
12190	switch (io->io_hdr.msg_type) {
12191	case CTL_MSG_SERIALIZE:
12192		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12193		break;
12194	case CTL_MSG_R2R: {
12195		const struct ctl_cmd_entry *entry;
12196
12197		/*
12198		 * This is only used in SER_ONLY mode.
12199		 */
12200		free_io = 0;
12201		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12202		mtx_lock(&lun->lun_lock);
12203		if (ctl_scsiio_lun_check(lun,
12204		    entry, (struct ctl_scsiio *)io) != 0) {
12205			mtx_unlock(&lun->lun_lock);
12206			ctl_done(io);
12207			break;
12208		}
12209		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12210		mtx_unlock(&lun->lun_lock);
12211		ctl_enqueue_rtr(io);
12212		break;
12213	}
12214	case CTL_MSG_FINISH_IO:
12215		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12216			free_io = 0;
12217			ctl_done(io);
12218		} else {
12219			free_io = 1;
12220			mtx_lock(&lun->lun_lock);
12221			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12222				     ooa_links);
12223			ctl_check_blocked(lun);
12224			mtx_unlock(&lun->lun_lock);
12225		}
12226		break;
12227	case CTL_MSG_PERS_ACTION:
12228		ctl_hndl_per_res_out_on_other_sc(
12229			(union ctl_ha_msg *)&io->presio.pr_msg);
12230		free_io = 1;
12231		break;
12232	case CTL_MSG_BAD_JUJU:
12233		free_io = 0;
12234		ctl_done(io);
12235		break;
12236	case CTL_MSG_DATAMOVE:
12237		/* Only used in XFER mode */
12238		free_io = 0;
12239		ctl_datamove_remote(io);
12240		break;
12241	case CTL_MSG_DATAMOVE_DONE:
12242		/* Only used in XFER mode */
12243		free_io = 0;
12244		io->scsiio.be_move_done(io);
12245		break;
12246	case CTL_MSG_FAILOVER:
12247		mtx_lock(&lun->lun_lock);
12248		ctl_failover_lun(lun);
12249		mtx_unlock(&lun->lun_lock);
12250		free_io = 1;
12251		break;
12252	default:
12253		free_io = 1;
12254		printf("%s: Invalid message type %d\n",
12255		       __func__, io->io_hdr.msg_type);
12256		break;
12257	}
12258	if (free_io)
12259		ctl_free_io(io);
12260
12261}
12262
12263
12264/*
12265 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12266 * there is no match.
12267 */
12268static ctl_lun_error_pattern
12269ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12270{
12271	const struct ctl_cmd_entry *entry;
12272	ctl_lun_error_pattern filtered_pattern, pattern;
12273
12274	pattern = desc->error_pattern;
12275
12276	/*
12277	 * XXX KDM we need more data passed into this function to match a
12278	 * custom pattern, and we actually need to implement custom pattern
12279	 * matching.
12280	 */
12281	if (pattern & CTL_LUN_PAT_CMD)
12282		return (CTL_LUN_PAT_CMD);
12283
12284	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12285		return (CTL_LUN_PAT_ANY);
12286
12287	entry = ctl_get_cmd_entry(ctsio, NULL);
12288
12289	filtered_pattern = entry->pattern & pattern;
12290
12291	/*
12292	 * If the user requested specific flags in the pattern (e.g.
12293	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12294	 * flags.
12295	 *
12296	 * If the user did not specify any flags, it doesn't matter whether
12297	 * or not the command supports the flags.
12298	 */
12299	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12300	     (pattern & ~CTL_LUN_PAT_MASK))
12301		return (CTL_LUN_PAT_NONE);
12302
12303	/*
12304	 * If the user asked for a range check, see if the requested LBA
12305	 * range overlaps with this command's LBA range.
12306	 */
12307	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12308		uint64_t lba1;
12309		uint64_t len1;
12310		ctl_action action;
12311		int retval;
12312
12313		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12314		if (retval != 0)
12315			return (CTL_LUN_PAT_NONE);
12316
12317		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12318					      desc->lba_range.len, FALSE);
12319		/*
12320		 * A "pass" means that the LBA ranges don't overlap, so
12321		 * this doesn't match the user's range criteria.
12322		 */
12323		if (action == CTL_ACTION_PASS)
12324			return (CTL_LUN_PAT_NONE);
12325	}
12326
12327	return (filtered_pattern);
12328}
12329
12330static void
12331ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12332{
12333	struct ctl_error_desc *desc, *desc2;
12334
12335	mtx_assert(&lun->lun_lock, MA_OWNED);
12336
12337	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12338		ctl_lun_error_pattern pattern;
12339		/*
12340		 * Check to see whether this particular command matches
12341		 * the pattern in the descriptor.
12342		 */
12343		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12344		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12345			continue;
12346
12347		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12348		case CTL_LUN_INJ_ABORTED:
12349			ctl_set_aborted(&io->scsiio);
12350			break;
12351		case CTL_LUN_INJ_MEDIUM_ERR:
12352			ctl_set_medium_error(&io->scsiio,
12353			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12354			     CTL_FLAG_DATA_OUT);
12355			break;
12356		case CTL_LUN_INJ_UA:
12357			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12358			 * OCCURRED */
12359			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12360			break;
12361		case CTL_LUN_INJ_CUSTOM:
12362			/*
12363			 * We're assuming the user knows what he is doing.
12364			 * Just copy the sense information without doing
12365			 * checks.
12366			 */
12367			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12368			      MIN(sizeof(desc->custom_sense),
12369				  sizeof(io->scsiio.sense_data)));
12370			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12371			io->scsiio.sense_len = SSD_FULL_SIZE;
12372			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12373			break;
12374		case CTL_LUN_INJ_NONE:
12375		default:
12376			/*
12377			 * If this is an error injection type we don't know
12378			 * about, clear the continuous flag (if it is set)
12379			 * so it will get deleted below.
12380			 */
12381			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12382			break;
12383		}
12384		/*
12385		 * By default, each error injection action is a one-shot
12386		 */
12387		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12388			continue;
12389
12390		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12391
12392		free(desc, M_CTL);
12393	}
12394}
12395
12396#ifdef CTL_IO_DELAY
12397static void
12398ctl_datamove_timer_wakeup(void *arg)
12399{
12400	union ctl_io *io;
12401
12402	io = (union ctl_io *)arg;
12403
12404	ctl_datamove(io);
12405}
12406#endif /* CTL_IO_DELAY */
12407
12408void
12409ctl_datamove(union ctl_io *io)
12410{
12411	struct ctl_lun *lun;
12412	void (*fe_datamove)(union ctl_io *io);
12413
12414	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12415
12416	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12417
12418	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12419#ifdef CTL_TIME_IO
12420	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12421		char str[256];
12422		char path_str[64];
12423		struct sbuf sb;
12424
12425		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12426		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12427
12428		sbuf_cat(&sb, path_str);
12429		switch (io->io_hdr.io_type) {
12430		case CTL_IO_SCSI:
12431			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12432			sbuf_printf(&sb, "\n");
12433			sbuf_cat(&sb, path_str);
12434			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12435				    io->scsiio.tag_num, io->scsiio.tag_type);
12436			break;
12437		case CTL_IO_TASK:
12438			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12439				    "Tag Type: %d\n", io->taskio.task_action,
12440				    io->taskio.tag_num, io->taskio.tag_type);
12441			break;
12442		default:
12443			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12444			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12445			break;
12446		}
12447		sbuf_cat(&sb, path_str);
12448		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12449			    (intmax_t)time_uptime - io->io_hdr.start_time);
12450		sbuf_finish(&sb);
12451		printf("%s", sbuf_data(&sb));
12452	}
12453#endif /* CTL_TIME_IO */
12454
12455#ifdef CTL_IO_DELAY
12456	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12457		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12458	} else {
12459		if ((lun != NULL)
12460		 && (lun->delay_info.datamove_delay > 0)) {
12461
12462			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12463			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12464			callout_reset(&io->io_hdr.delay_callout,
12465				      lun->delay_info.datamove_delay * hz,
12466				      ctl_datamove_timer_wakeup, io);
12467			if (lun->delay_info.datamove_type ==
12468			    CTL_DELAY_TYPE_ONESHOT)
12469				lun->delay_info.datamove_delay = 0;
12470			return;
12471		}
12472	}
12473#endif
12474
12475	/*
12476	 * This command has been aborted.  Set the port status, so we fail
12477	 * the data move.
12478	 */
12479	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12480		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12481		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12482		       io->io_hdr.nexus.targ_port,
12483		       io->io_hdr.nexus.targ_lun);
12484		io->io_hdr.port_status = 31337;
12485		/*
12486		 * Note that the backend, in this case, will get the
12487		 * callback in its context.  In other cases it may get
12488		 * called in the frontend's interrupt thread context.
12489		 */
12490		io->scsiio.be_move_done(io);
12491		return;
12492	}
12493
12494	/* Don't confuse frontend with zero length data move. */
12495	if (io->scsiio.kern_data_len == 0) {
12496		io->scsiio.be_move_done(io);
12497		return;
12498	}
12499
12500	/*
12501	 * If we're in XFER mode and this I/O is from the other shelf
12502	 * controller, we need to send the DMA to the other side to
12503	 * actually transfer the data to/from the host.  In serialize only
12504	 * mode the transfer happens below CTL and ctl_datamove() is only
12505	 * called on the machine that originally received the I/O.
12506	 */
12507	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12508	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12509		union ctl_ha_msg msg;
12510		uint32_t sg_entries_sent;
12511		int do_sg_copy;
12512		int i;
12513
12514		memset(&msg, 0, sizeof(msg));
12515		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12516		msg.hdr.original_sc = io->io_hdr.original_sc;
12517		msg.hdr.serializing_sc = io;
12518		msg.hdr.nexus = io->io_hdr.nexus;
12519		msg.hdr.status = io->io_hdr.status;
12520		msg.dt.flags = io->io_hdr.flags;
12521		/*
12522		 * We convert everything into a S/G list here.  We can't
12523		 * pass by reference, only by value between controllers.
12524		 * So we can't pass a pointer to the S/G list, only as many
12525		 * S/G entries as we can fit in here.  If it's possible for
12526		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12527		 * then we need to break this up into multiple transfers.
12528		 */
12529		if (io->scsiio.kern_sg_entries == 0) {
12530			msg.dt.kern_sg_entries = 1;
12531#if 0
12532			/*
12533			 * Convert to a physical address if this is a
12534			 * virtual address.
12535			 */
12536			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12537				msg.dt.sg_list[0].addr =
12538					io->scsiio.kern_data_ptr;
12539			} else {
12540				/*
12541				 * XXX KDM use busdma here!
12542				 */
12543				msg.dt.sg_list[0].addr = (void *)
12544					vtophys(io->scsiio.kern_data_ptr);
12545			}
12546#else
12547			KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12548			    ("HA does not support BUS_ADDR"));
12549			msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
12550#endif
12551
12552			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12553			do_sg_copy = 0;
12554		} else {
12555			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12556			do_sg_copy = 1;
12557		}
12558
12559		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12560		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12561		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12562		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12563		msg.dt.sg_sequence = 0;
12564
12565		/*
12566		 * Loop until we've sent all of the S/G entries.  On the
12567		 * other end, we'll recompose these S/G entries into one
12568		 * contiguous list before passing it to the
12569		 */
12570		for (sg_entries_sent = 0; sg_entries_sent <
12571		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12572			msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list)/
12573				sizeof(msg.dt.sg_list[0])),
12574				msg.dt.kern_sg_entries - sg_entries_sent);
12575
12576			if (do_sg_copy != 0) {
12577				struct ctl_sg_entry *sgl;
12578				int j;
12579
12580				sgl = (struct ctl_sg_entry *)
12581					io->scsiio.kern_data_ptr;
12582				/*
12583				 * If this is in cached memory, flush the cache
12584				 * before we send the DMA request to the other
12585				 * controller.  We want to do this in either
12586				 * the * read or the write case.  The read
12587				 * case is straightforward.  In the write
12588				 * case, we want to make sure nothing is
12589				 * in the local cache that could overwrite
12590				 * the DMAed data.
12591				 */
12592
12593				for (i = sg_entries_sent, j = 0;
12594				     i < msg.dt.cur_sg_entries; i++, j++) {
12595#if 0
12596					if ((io->io_hdr.flags &
12597					     CTL_FLAG_BUS_ADDR) == 0) {
12598						/*
12599						 * XXX KDM use busdma.
12600						 */
12601						msg.dt.sg_list[j].addr =(void *)
12602						       vtophys(sgl[i].addr);
12603					} else {
12604						msg.dt.sg_list[j].addr =
12605							sgl[i].addr;
12606					}
12607#else
12608					KASSERT((io->io_hdr.flags &
12609					    CTL_FLAG_BUS_ADDR) == 0,
12610					    ("HA does not support BUS_ADDR"));
12611					msg.dt.sg_list[j].addr = sgl[i].addr;
12612#endif
12613					msg.dt.sg_list[j].len = sgl[i].len;
12614				}
12615			}
12616
12617			sg_entries_sent += msg.dt.cur_sg_entries;
12618			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12619				msg.dt.sg_last = 1;
12620			else
12621				msg.dt.sg_last = 0;
12622
12623			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12624			    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
12625			    sizeof(struct ctl_sg_entry)*msg.dt.cur_sg_entries,
12626			    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
12627				io->io_hdr.port_status = 31341;
12628				io->scsiio.be_move_done(io);
12629				return;
12630			}
12631
12632			msg.dt.sent_sg_entries = sg_entries_sent;
12633		}
12634
12635		/*
12636		 * Officially handover the request from us to peer.
12637		 * If failover has just happened, then we must return error.
12638		 * If failover happen just after, then it is not our problem.
12639		 */
12640		if (lun)
12641			mtx_lock(&lun->lun_lock);
12642		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12643			if (lun)
12644				mtx_unlock(&lun->lun_lock);
12645			io->io_hdr.port_status = 31342;
12646			io->scsiio.be_move_done(io);
12647			return;
12648		}
12649		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12650		io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
12651		if (lun)
12652			mtx_unlock(&lun->lun_lock);
12653	} else {
12654
12655		/*
12656		 * Lookup the fe_datamove() function for this particular
12657		 * front end.
12658		 */
12659		fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12660
12661		fe_datamove(io);
12662	}
12663}
12664
12665static void
12666ctl_send_datamove_done(union ctl_io *io, int have_lock)
12667{
12668	union ctl_ha_msg msg;
12669
12670	memset(&msg, 0, sizeof(msg));
12671
12672	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12673	msg.hdr.original_sc = io;
12674	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12675	msg.hdr.nexus = io->io_hdr.nexus;
12676	msg.hdr.status = io->io_hdr.status;
12677	msg.scsi.tag_num = io->scsiio.tag_num;
12678	msg.scsi.tag_type = io->scsiio.tag_type;
12679	msg.scsi.scsi_status = io->scsiio.scsi_status;
12680	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12681	       io->scsiio.sense_len);
12682	msg.scsi.sense_len = io->scsiio.sense_len;
12683	msg.scsi.sense_residual = io->scsiio.sense_residual;
12684	msg.scsi.fetd_status = io->io_hdr.port_status;
12685	msg.scsi.residual = io->scsiio.residual;
12686	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12687
12688	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12689		ctl_failover_io(io, /*have_lock*/ have_lock);
12690		return;
12691	}
12692
12693	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12694	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12695	    msg.scsi.sense_len, M_WAITOK);
12696}
12697
12698/*
12699 * The DMA to the remote side is done, now we need to tell the other side
12700 * we're done so it can continue with its data movement.
12701 */
12702static void
12703ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12704{
12705	union ctl_io *io;
12706	int i;
12707
12708	io = rq->context;
12709
12710	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12711		printf("%s: ISC DMA write failed with error %d", __func__,
12712		       rq->ret);
12713		ctl_set_internal_failure(&io->scsiio,
12714					 /*sks_valid*/ 1,
12715					 /*retry_count*/ rq->ret);
12716	}
12717
12718	ctl_dt_req_free(rq);
12719
12720	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12721		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12722	free(io->io_hdr.remote_sglist, M_CTL);
12723	io->io_hdr.remote_sglist = NULL;
12724	io->io_hdr.local_sglist = NULL;
12725
12726	/*
12727	 * The data is in local and remote memory, so now we need to send
12728	 * status (good or back) back to the other side.
12729	 */
12730	ctl_send_datamove_done(io, /*have_lock*/ 0);
12731}
12732
12733/*
12734 * We've moved the data from the host/controller into local memory.  Now we
12735 * need to push it over to the remote controller's memory.
12736 */
12737static int
12738ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12739{
12740	int retval;
12741
12742	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12743					  ctl_datamove_remote_write_cb);
12744	return (retval);
12745}
12746
12747static void
12748ctl_datamove_remote_write(union ctl_io *io)
12749{
12750	int retval;
12751	void (*fe_datamove)(union ctl_io *io);
12752
12753	/*
12754	 * - Get the data from the host/HBA into local memory.
12755	 * - DMA memory from the local controller to the remote controller.
12756	 * - Send status back to the remote controller.
12757	 */
12758
12759	retval = ctl_datamove_remote_sgl_setup(io);
12760	if (retval != 0)
12761		return;
12762
12763	/* Switch the pointer over so the FETD knows what to do */
12764	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12765
12766	/*
12767	 * Use a custom move done callback, since we need to send completion
12768	 * back to the other controller, not to the backend on this side.
12769	 */
12770	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12771
12772	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12773	fe_datamove(io);
12774}
12775
12776static int
12777ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12778{
12779#if 0
12780	char str[256];
12781	char path_str[64];
12782	struct sbuf sb;
12783#endif
12784	int i;
12785
12786	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12787		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12788	free(io->io_hdr.remote_sglist, M_CTL);
12789	io->io_hdr.remote_sglist = NULL;
12790	io->io_hdr.local_sglist = NULL;
12791
12792#if 0
12793	scsi_path_string(io, path_str, sizeof(path_str));
12794	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12795	sbuf_cat(&sb, path_str);
12796	scsi_command_string(&io->scsiio, NULL, &sb);
12797	sbuf_printf(&sb, "\n");
12798	sbuf_cat(&sb, path_str);
12799	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12800		    io->scsiio.tag_num, io->scsiio.tag_type);
12801	sbuf_cat(&sb, path_str);
12802	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12803		    io->io_hdr.flags, io->io_hdr.status);
12804	sbuf_finish(&sb);
12805	printk("%s", sbuf_data(&sb));
12806#endif
12807
12808
12809	/*
12810	 * The read is done, now we need to send status (good or bad) back
12811	 * to the other side.
12812	 */
12813	ctl_send_datamove_done(io, /*have_lock*/ 0);
12814
12815	return (0);
12816}
12817
12818static void
12819ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12820{
12821	union ctl_io *io;
12822	void (*fe_datamove)(union ctl_io *io);
12823
12824	io = rq->context;
12825
12826	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12827		printf("%s: ISC DMA read failed with error %d\n", __func__,
12828		       rq->ret);
12829		ctl_set_internal_failure(&io->scsiio,
12830					 /*sks_valid*/ 1,
12831					 /*retry_count*/ rq->ret);
12832	}
12833
12834	ctl_dt_req_free(rq);
12835
12836	/* Switch the pointer over so the FETD knows what to do */
12837	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12838
12839	/*
12840	 * Use a custom move done callback, since we need to send completion
12841	 * back to the other controller, not to the backend on this side.
12842	 */
12843	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12844
12845	/* XXX KDM add checks like the ones in ctl_datamove? */
12846
12847	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12848	fe_datamove(io);
12849}
12850
12851static int
12852ctl_datamove_remote_sgl_setup(union ctl_io *io)
12853{
12854	struct ctl_sg_entry *local_sglist;
12855	struct ctl_softc *softc;
12856	uint32_t len_to_go;
12857	int retval;
12858	int i;
12859
12860	retval = 0;
12861	softc = control_softc;
12862	local_sglist = io->io_hdr.local_sglist;
12863	len_to_go = io->scsiio.kern_data_len;
12864
12865	/*
12866	 * The difficult thing here is that the size of the various
12867	 * S/G segments may be different than the size from the
12868	 * remote controller.  That'll make it harder when DMAing
12869	 * the data back to the other side.
12870	 */
12871	for (i = 0; len_to_go > 0; i++) {
12872		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12873		local_sglist[i].addr =
12874		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12875
12876		len_to_go -= local_sglist[i].len;
12877	}
12878	/*
12879	 * Reset the number of S/G entries accordingly.  The original
12880	 * number of S/G entries is available in rem_sg_entries.
12881	 */
12882	io->scsiio.kern_sg_entries = i;
12883
12884#if 0
12885	printf("%s: kern_sg_entries = %d\n", __func__,
12886	       io->scsiio.kern_sg_entries);
12887	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12888		printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12889		       local_sglist[i].addr, local_sglist[i].len);
12890#endif
12891
12892	return (retval);
12893}
12894
12895static int
12896ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12897			 ctl_ha_dt_cb callback)
12898{
12899	struct ctl_ha_dt_req *rq;
12900	struct ctl_sg_entry *remote_sglist, *local_sglist;
12901	uint32_t local_used, remote_used, total_used;
12902	int i, j, isc_ret;
12903
12904	rq = ctl_dt_req_alloc();
12905
12906	/*
12907	 * If we failed to allocate the request, and if the DMA didn't fail
12908	 * anyway, set busy status.  This is just a resource allocation
12909	 * failure.
12910	 */
12911	if ((rq == NULL)
12912	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12913	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12914		ctl_set_busy(&io->scsiio);
12915
12916	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12917	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12918
12919		if (rq != NULL)
12920			ctl_dt_req_free(rq);
12921
12922		/*
12923		 * The data move failed.  We need to return status back
12924		 * to the other controller.  No point in trying to DMA
12925		 * data to the remote controller.
12926		 */
12927
12928		ctl_send_datamove_done(io, /*have_lock*/ 0);
12929
12930		return (1);
12931	}
12932
12933	local_sglist = io->io_hdr.local_sglist;
12934	remote_sglist = io->io_hdr.remote_sglist;
12935	local_used = 0;
12936	remote_used = 0;
12937	total_used = 0;
12938
12939	/*
12940	 * Pull/push the data over the wire from/to the other controller.
12941	 * This takes into account the possibility that the local and
12942	 * remote sglists may not be identical in terms of the size of
12943	 * the elements and the number of elements.
12944	 *
12945	 * One fundamental assumption here is that the length allocated for
12946	 * both the local and remote sglists is identical.  Otherwise, we've
12947	 * essentially got a coding error of some sort.
12948	 */
12949	isc_ret = CTL_HA_STATUS_SUCCESS;
12950	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12951		uint32_t cur_len;
12952		uint8_t *tmp_ptr;
12953
12954		rq->command = command;
12955		rq->context = io;
12956
12957		/*
12958		 * Both pointers should be aligned.  But it is possible
12959		 * that the allocation length is not.  They should both
12960		 * also have enough slack left over at the end, though,
12961		 * to round up to the next 8 byte boundary.
12962		 */
12963		cur_len = MIN(local_sglist[i].len - local_used,
12964			      remote_sglist[j].len - remote_used);
12965		rq->size = cur_len;
12966
12967		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12968		tmp_ptr += local_used;
12969
12970#if 0
12971		/* Use physical addresses when talking to ISC hardware */
12972		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12973			/* XXX KDM use busdma */
12974			rq->local = vtophys(tmp_ptr);
12975		} else
12976			rq->local = tmp_ptr;
12977#else
12978		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12979		    ("HA does not support BUS_ADDR"));
12980		rq->local = tmp_ptr;
12981#endif
12982
12983		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12984		tmp_ptr += remote_used;
12985		rq->remote = tmp_ptr;
12986
12987		rq->callback = NULL;
12988
12989		local_used += cur_len;
12990		if (local_used >= local_sglist[i].len) {
12991			i++;
12992			local_used = 0;
12993		}
12994
12995		remote_used += cur_len;
12996		if (remote_used >= remote_sglist[j].len) {
12997			j++;
12998			remote_used = 0;
12999		}
13000		total_used += cur_len;
13001
13002		if (total_used >= io->scsiio.kern_data_len)
13003			rq->callback = callback;
13004
13005#if 0
13006		printf("%s: %s: local %p remote %p size %d\n", __func__,
13007		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13008		       rq->local, rq->remote, rq->size);
13009#endif
13010
13011		isc_ret = ctl_dt_single(rq);
13012		if (isc_ret > CTL_HA_STATUS_SUCCESS)
13013			break;
13014	}
13015	if (isc_ret != CTL_HA_STATUS_WAIT) {
13016		rq->ret = isc_ret;
13017		callback(rq);
13018	}
13019
13020	return (0);
13021}
13022
13023static void
13024ctl_datamove_remote_read(union ctl_io *io)
13025{
13026	int retval;
13027	int i;
13028
13029	/*
13030	 * This will send an error to the other controller in the case of a
13031	 * failure.
13032	 */
13033	retval = ctl_datamove_remote_sgl_setup(io);
13034	if (retval != 0)
13035		return;
13036
13037	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13038					  ctl_datamove_remote_read_cb);
13039	if (retval != 0) {
13040		/*
13041		 * Make sure we free memory if there was an error..  The
13042		 * ctl_datamove_remote_xfer() function will send the
13043		 * datamove done message, or call the callback with an
13044		 * error if there is a problem.
13045		 */
13046		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13047			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13048		free(io->io_hdr.remote_sglist, M_CTL);
13049		io->io_hdr.remote_sglist = NULL;
13050		io->io_hdr.local_sglist = NULL;
13051	}
13052}
13053
13054/*
13055 * Process a datamove request from the other controller.  This is used for
13056 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13057 * first.  Once that is complete, the data gets DMAed into the remote
13058 * controller's memory.  For reads, we DMA from the remote controller's
13059 * memory into our memory first, and then move it out to the FETD.
13060 */
13061static void
13062ctl_datamove_remote(union ctl_io *io)
13063{
13064
13065	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
13066
13067	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13068		ctl_failover_io(io, /*have_lock*/ 0);
13069		return;
13070	}
13071
13072	/*
13073	 * Note that we look for an aborted I/O here, but don't do some of
13074	 * the other checks that ctl_datamove() normally does.
13075	 * We don't need to run the datamove delay code, since that should
13076	 * have been done if need be on the other controller.
13077	 */
13078	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13079		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
13080		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
13081		       io->io_hdr.nexus.targ_port,
13082		       io->io_hdr.nexus.targ_lun);
13083		io->io_hdr.port_status = 31338;
13084		ctl_send_datamove_done(io, /*have_lock*/ 0);
13085		return;
13086	}
13087
13088	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
13089		ctl_datamove_remote_write(io);
13090	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
13091		ctl_datamove_remote_read(io);
13092	else {
13093		io->io_hdr.port_status = 31339;
13094		ctl_send_datamove_done(io, /*have_lock*/ 0);
13095	}
13096}
13097
13098static int
13099ctl_process_done(union ctl_io *io)
13100{
13101	struct ctl_lun *lun;
13102	struct ctl_softc *softc = control_softc;
13103	void (*fe_done)(union ctl_io *io);
13104	union ctl_ha_msg msg;
13105	uint32_t targ_port = io->io_hdr.nexus.targ_port;
13106
13107	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13108
13109	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0)
13110		fe_done = softc->ctl_ports[targ_port]->fe_done;
13111	else
13112		fe_done = NULL;
13113
13114#ifdef CTL_TIME_IO
13115	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13116		char str[256];
13117		char path_str[64];
13118		struct sbuf sb;
13119
13120		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13121		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13122
13123		sbuf_cat(&sb, path_str);
13124		switch (io->io_hdr.io_type) {
13125		case CTL_IO_SCSI:
13126			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13127			sbuf_printf(&sb, "\n");
13128			sbuf_cat(&sb, path_str);
13129			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13130				    io->scsiio.tag_num, io->scsiio.tag_type);
13131			break;
13132		case CTL_IO_TASK:
13133			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13134				    "Tag Type: %d\n", io->taskio.task_action,
13135				    io->taskio.tag_num, io->taskio.tag_type);
13136			break;
13137		default:
13138			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13139			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13140			break;
13141		}
13142		sbuf_cat(&sb, path_str);
13143		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13144			    (intmax_t)time_uptime - io->io_hdr.start_time);
13145		sbuf_finish(&sb);
13146		printf("%s", sbuf_data(&sb));
13147	}
13148#endif /* CTL_TIME_IO */
13149
13150	switch (io->io_hdr.io_type) {
13151	case CTL_IO_SCSI:
13152		break;
13153	case CTL_IO_TASK:
13154		if (ctl_debug & CTL_DEBUG_INFO)
13155			ctl_io_error_print(io, NULL);
13156		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13157			ctl_free_io(io);
13158		else
13159			fe_done(io);
13160		return (CTL_RETVAL_COMPLETE);
13161	default:
13162		panic("ctl_process_done: invalid io type %d\n",
13163		      io->io_hdr.io_type);
13164		break; /* NOTREACHED */
13165	}
13166
13167	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13168	if (lun == NULL) {
13169		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13170				 io->io_hdr.nexus.targ_mapped_lun));
13171		goto bailout;
13172	}
13173
13174	mtx_lock(&lun->lun_lock);
13175
13176	/*
13177	 * Check to see if we have any errors to inject here.  We only
13178	 * inject errors for commands that don't already have errors set.
13179	 */
13180	if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
13181	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13182	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13183		ctl_inject_error(lun, io);
13184
13185	/*
13186	 * XXX KDM how do we treat commands that aren't completed
13187	 * successfully?
13188	 *
13189	 * XXX KDM should we also track I/O latency?
13190	 */
13191	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13192	    io->io_hdr.io_type == CTL_IO_SCSI) {
13193#ifdef CTL_TIME_IO
13194		struct bintime cur_bt;
13195#endif
13196		int type;
13197
13198		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13199		    CTL_FLAG_DATA_IN)
13200			type = CTL_STATS_READ;
13201		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13202		    CTL_FLAG_DATA_OUT)
13203			type = CTL_STATS_WRITE;
13204		else
13205			type = CTL_STATS_NO_IO;
13206
13207		lun->stats.ports[targ_port].bytes[type] +=
13208		    io->scsiio.kern_total_len;
13209		lun->stats.ports[targ_port].operations[type]++;
13210#ifdef CTL_TIME_IO
13211		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13212		   &io->io_hdr.dma_bt);
13213		lun->stats.ports[targ_port].num_dmas[type] +=
13214		    io->io_hdr.num_dmas;
13215		getbintime(&cur_bt);
13216		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13217		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13218#endif
13219	}
13220
13221	/*
13222	 * Remove this from the OOA queue.
13223	 */
13224	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13225#ifdef CTL_TIME_IO
13226	if (TAILQ_EMPTY(&lun->ooa_queue))
13227		lun->last_busy = getsbinuptime();
13228#endif
13229
13230	/*
13231	 * Run through the blocked queue on this LUN and see if anything
13232	 * has become unblocked, now that this transaction is done.
13233	 */
13234	ctl_check_blocked(lun);
13235
13236	/*
13237	 * If the LUN has been invalidated, free it if there is nothing
13238	 * left on its OOA queue.
13239	 */
13240	if ((lun->flags & CTL_LUN_INVALID)
13241	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13242		mtx_unlock(&lun->lun_lock);
13243		mtx_lock(&softc->ctl_lock);
13244		ctl_free_lun(lun);
13245		mtx_unlock(&softc->ctl_lock);
13246	} else
13247		mtx_unlock(&lun->lun_lock);
13248
13249bailout:
13250
13251	/*
13252	 * If this command has been aborted, make sure we set the status
13253	 * properly.  The FETD is responsible for freeing the I/O and doing
13254	 * whatever it needs to do to clean up its state.
13255	 */
13256	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13257		ctl_set_task_aborted(&io->scsiio);
13258
13259	/*
13260	 * If enabled, print command error status.
13261	 */
13262	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13263	    (ctl_debug & CTL_DEBUG_INFO) != 0)
13264		ctl_io_error_print(io, NULL);
13265
13266	/*
13267	 * Tell the FETD or the other shelf controller we're done with this
13268	 * command.  Note that only SCSI commands get to this point.  Task
13269	 * management commands are completed above.
13270	 */
13271	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13272	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13273		memset(&msg, 0, sizeof(msg));
13274		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13275		msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13276		msg.hdr.nexus = io->io_hdr.nexus;
13277		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13278		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13279		    M_WAITOK);
13280	}
13281	if ((softc->ha_mode == CTL_HA_MODE_XFER)
13282	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13283		memset(&msg, 0, sizeof(msg));
13284		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13285		msg.hdr.original_sc = io->io_hdr.original_sc;
13286		msg.hdr.nexus = io->io_hdr.nexus;
13287		msg.hdr.status = io->io_hdr.status;
13288		msg.scsi.scsi_status = io->scsiio.scsi_status;
13289		msg.scsi.tag_num = io->scsiio.tag_num;
13290		msg.scsi.tag_type = io->scsiio.tag_type;
13291		msg.scsi.sense_len = io->scsiio.sense_len;
13292		msg.scsi.sense_residual = io->scsiio.sense_residual;
13293		msg.scsi.residual = io->scsiio.residual;
13294		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13295		       io->scsiio.sense_len);
13296
13297		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13298		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
13299		    msg.scsi.sense_len, M_WAITOK);
13300		ctl_free_io(io);
13301	} else
13302		fe_done(io);
13303
13304	return (CTL_RETVAL_COMPLETE);
13305}
13306
13307#ifdef CTL_WITH_CA
13308/*
13309 * Front end should call this if it doesn't do autosense.  When the request
13310 * sense comes back in from the initiator, we'll dequeue this and send it.
13311 */
13312int
13313ctl_queue_sense(union ctl_io *io)
13314{
13315	struct ctl_lun *lun;
13316	struct ctl_port *port;
13317	struct ctl_softc *softc;
13318	uint32_t initidx, targ_lun;
13319
13320	softc = control_softc;
13321
13322	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13323
13324	/*
13325	 * LUN lookup will likely move to the ctl_work_thread() once we
13326	 * have our new queueing infrastructure (that doesn't put things on
13327	 * a per-LUN queue initially).  That is so that we can handle
13328	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13329	 * can't deal with that right now.
13330	 */
13331	mtx_lock(&softc->ctl_lock);
13332
13333	/*
13334	 * If we don't have a LUN for this, just toss the sense
13335	 * information.
13336	 */
13337	port = ctl_io_port(&ctsio->io_hdr);
13338	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13339	if ((targ_lun < CTL_MAX_LUNS)
13340	 && (softc->ctl_luns[targ_lun] != NULL))
13341		lun = softc->ctl_luns[targ_lun];
13342	else
13343		goto bailout;
13344
13345	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13346
13347	mtx_lock(&lun->lun_lock);
13348	/*
13349	 * Already have CA set for this LUN...toss the sense information.
13350	 */
13351	if (ctl_is_set(lun->have_ca, initidx)) {
13352		mtx_unlock(&lun->lun_lock);
13353		goto bailout;
13354	}
13355
13356	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13357	       MIN(sizeof(lun->pending_sense[initidx]),
13358	       sizeof(io->scsiio.sense_data)));
13359	ctl_set_mask(lun->have_ca, initidx);
13360	mtx_unlock(&lun->lun_lock);
13361
13362bailout:
13363	mtx_unlock(&softc->ctl_lock);
13364
13365	ctl_free_io(io);
13366
13367	return (CTL_RETVAL_COMPLETE);
13368}
13369#endif
13370
13371/*
13372 * Primary command inlet from frontend ports.  All SCSI and task I/O
13373 * requests must go through this function.
13374 */
13375int
13376ctl_queue(union ctl_io *io)
13377{
13378	struct ctl_port *port;
13379
13380	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13381
13382#ifdef CTL_TIME_IO
13383	io->io_hdr.start_time = time_uptime;
13384	getbintime(&io->io_hdr.start_bt);
13385#endif /* CTL_TIME_IO */
13386
13387	/* Map FE-specific LUN ID into global one. */
13388	port = ctl_io_port(&io->io_hdr);
13389	io->io_hdr.nexus.targ_mapped_lun =
13390	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13391
13392	switch (io->io_hdr.io_type) {
13393	case CTL_IO_SCSI:
13394	case CTL_IO_TASK:
13395		if (ctl_debug & CTL_DEBUG_CDB)
13396			ctl_io_print(io);
13397		ctl_enqueue_incoming(io);
13398		break;
13399	default:
13400		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13401		return (EINVAL);
13402	}
13403
13404	return (CTL_RETVAL_COMPLETE);
13405}
13406
13407#ifdef CTL_IO_DELAY
13408static void
13409ctl_done_timer_wakeup(void *arg)
13410{
13411	union ctl_io *io;
13412
13413	io = (union ctl_io *)arg;
13414	ctl_done(io);
13415}
13416#endif /* CTL_IO_DELAY */
13417
13418void
13419ctl_serseq_done(union ctl_io *io)
13420{
13421	struct ctl_lun *lun;
13422
13423	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13424	if (lun->be_lun == NULL ||
13425	    lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13426		return;
13427	mtx_lock(&lun->lun_lock);
13428	io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13429	ctl_check_blocked(lun);
13430	mtx_unlock(&lun->lun_lock);
13431}
13432
13433void
13434ctl_done(union ctl_io *io)
13435{
13436
13437	/*
13438	 * Enable this to catch duplicate completion issues.
13439	 */
13440#if 0
13441	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13442		printf("%s: type %d msg %d cdb %x iptl: "
13443		       "%u:%u:%u tag 0x%04x "
13444		       "flag %#x status %x\n",
13445			__func__,
13446			io->io_hdr.io_type,
13447			io->io_hdr.msg_type,
13448			io->scsiio.cdb[0],
13449			io->io_hdr.nexus.initid,
13450			io->io_hdr.nexus.targ_port,
13451			io->io_hdr.nexus.targ_lun,
13452			(io->io_hdr.io_type ==
13453			CTL_IO_TASK) ?
13454			io->taskio.tag_num :
13455			io->scsiio.tag_num,
13456		        io->io_hdr.flags,
13457			io->io_hdr.status);
13458	} else
13459		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13460#endif
13461
13462	/*
13463	 * This is an internal copy of an I/O, and should not go through
13464	 * the normal done processing logic.
13465	 */
13466	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13467		return;
13468
13469#ifdef CTL_IO_DELAY
13470	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13471		struct ctl_lun *lun;
13472
13473		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13474
13475		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13476	} else {
13477		struct ctl_lun *lun;
13478
13479		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13480
13481		if ((lun != NULL)
13482		 && (lun->delay_info.done_delay > 0)) {
13483
13484			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13485			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13486			callout_reset(&io->io_hdr.delay_callout,
13487				      lun->delay_info.done_delay * hz,
13488				      ctl_done_timer_wakeup, io);
13489			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13490				lun->delay_info.done_delay = 0;
13491			return;
13492		}
13493	}
13494#endif /* CTL_IO_DELAY */
13495
13496	ctl_enqueue_done(io);
13497}
13498
13499static void
13500ctl_work_thread(void *arg)
13501{
13502	struct ctl_thread *thr = (struct ctl_thread *)arg;
13503	struct ctl_softc *softc = thr->ctl_softc;
13504	union ctl_io *io;
13505	int retval;
13506
13507	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13508
13509	for (;;) {
13510		retval = 0;
13511
13512		/*
13513		 * We handle the queues in this order:
13514		 * - ISC
13515		 * - done queue (to free up resources, unblock other commands)
13516		 * - RtR queue
13517		 * - incoming queue
13518		 *
13519		 * If those queues are empty, we break out of the loop and
13520		 * go to sleep.
13521		 */
13522		mtx_lock(&thr->queue_lock);
13523		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13524		if (io != NULL) {
13525			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13526			mtx_unlock(&thr->queue_lock);
13527			ctl_handle_isc(io);
13528			continue;
13529		}
13530		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13531		if (io != NULL) {
13532			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13533			/* clear any blocked commands, call fe_done */
13534			mtx_unlock(&thr->queue_lock);
13535			retval = ctl_process_done(io);
13536			continue;
13537		}
13538		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13539		if (io != NULL) {
13540			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13541			mtx_unlock(&thr->queue_lock);
13542			if (io->io_hdr.io_type == CTL_IO_TASK)
13543				ctl_run_task(io);
13544			else
13545				ctl_scsiio_precheck(softc, &io->scsiio);
13546			continue;
13547		}
13548		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13549		if (io != NULL) {
13550			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13551			mtx_unlock(&thr->queue_lock);
13552			retval = ctl_scsiio(&io->scsiio);
13553			if (retval != CTL_RETVAL_COMPLETE)
13554				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13555			continue;
13556		}
13557
13558		/* Sleep until we have something to do. */
13559		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13560	}
13561}
13562
13563static void
13564ctl_lun_thread(void *arg)
13565{
13566	struct ctl_softc *softc = (struct ctl_softc *)arg;
13567	struct ctl_be_lun *be_lun;
13568	int retval;
13569
13570	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13571
13572	for (;;) {
13573		retval = 0;
13574		mtx_lock(&softc->ctl_lock);
13575		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13576		if (be_lun != NULL) {
13577			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13578			mtx_unlock(&softc->ctl_lock);
13579			ctl_create_lun(be_lun);
13580			continue;
13581		}
13582
13583		/* Sleep until we have something to do. */
13584		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13585		    PDROP | PRIBIO, "-", 0);
13586	}
13587}
13588
13589static void
13590ctl_thresh_thread(void *arg)
13591{
13592	struct ctl_softc *softc = (struct ctl_softc *)arg;
13593	struct ctl_lun *lun;
13594	struct ctl_be_lun *be_lun;
13595	struct scsi_da_rw_recovery_page *rwpage;
13596	struct ctl_logical_block_provisioning_page *page;
13597	const char *attr;
13598	union ctl_ha_msg msg;
13599	uint64_t thres, val;
13600	int i, e, set;
13601
13602	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13603
13604	for (;;) {
13605		mtx_lock(&softc->ctl_lock);
13606		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13607			be_lun = lun->be_lun;
13608			if ((lun->flags & CTL_LUN_DISABLED) ||
13609			    (lun->flags & CTL_LUN_OFFLINE) ||
13610			    lun->backend->lun_attr == NULL)
13611				continue;
13612			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13613			    softc->ha_mode == CTL_HA_MODE_XFER)
13614				continue;
13615			rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13616			if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13617				continue;
13618			e = 0;
13619			page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13620			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13621				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13622					continue;
13623				thres = scsi_4btoul(page->descr[i].count);
13624				thres <<= CTL_LBP_EXPONENT;
13625				switch (page->descr[i].resource) {
13626				case 0x01:
13627					attr = "blocksavail";
13628					break;
13629				case 0x02:
13630					attr = "blocksused";
13631					break;
13632				case 0xf1:
13633					attr = "poolblocksavail";
13634					break;
13635				case 0xf2:
13636					attr = "poolblocksused";
13637					break;
13638				default:
13639					continue;
13640				}
13641				mtx_unlock(&softc->ctl_lock); // XXX
13642				val = lun->backend->lun_attr(
13643				    lun->be_lun->be_lun, attr);
13644				mtx_lock(&softc->ctl_lock);
13645				if (val == UINT64_MAX)
13646					continue;
13647				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13648				    == SLBPPD_ARMING_INC)
13649					e = (val >= thres);
13650				else
13651					e = (val <= thres);
13652				if (e)
13653					break;
13654			}
13655			mtx_lock(&lun->lun_lock);
13656			if (e) {
13657				scsi_u64to8b((uint8_t *)&page->descr[i] -
13658				    (uint8_t *)page, lun->ua_tpt_info);
13659				if (lun->lasttpt == 0 ||
13660				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13661					lun->lasttpt = time_uptime;
13662					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13663					set = 1;
13664				} else
13665					set = 0;
13666			} else {
13667				lun->lasttpt = 0;
13668				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13669				set = -1;
13670			}
13671			mtx_unlock(&lun->lun_lock);
13672			if (set != 0 &&
13673			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13674				/* Send msg to other side. */
13675				bzero(&msg.ua, sizeof(msg.ua));
13676				msg.hdr.msg_type = CTL_MSG_UA;
13677				msg.hdr.nexus.initid = -1;
13678				msg.hdr.nexus.targ_port = -1;
13679				msg.hdr.nexus.targ_lun = lun->lun;
13680				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13681				msg.ua.ua_all = 1;
13682				msg.ua.ua_set = (set > 0);
13683				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13684				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13685				mtx_unlock(&softc->ctl_lock); // XXX
13686				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13687				    sizeof(msg.ua), M_WAITOK);
13688				mtx_lock(&softc->ctl_lock);
13689			}
13690		}
13691		mtx_unlock(&softc->ctl_lock);
13692		pause("-", CTL_LBP_PERIOD * hz);
13693	}
13694}
13695
13696static void
13697ctl_enqueue_incoming(union ctl_io *io)
13698{
13699	struct ctl_softc *softc = control_softc;
13700	struct ctl_thread *thr;
13701	u_int idx;
13702
13703	idx = (io->io_hdr.nexus.targ_port * 127 +
13704	       io->io_hdr.nexus.initid) % worker_threads;
13705	thr = &softc->threads[idx];
13706	mtx_lock(&thr->queue_lock);
13707	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13708	mtx_unlock(&thr->queue_lock);
13709	wakeup(thr);
13710}
13711
13712static void
13713ctl_enqueue_rtr(union ctl_io *io)
13714{
13715	struct ctl_softc *softc = control_softc;
13716	struct ctl_thread *thr;
13717
13718	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13719	mtx_lock(&thr->queue_lock);
13720	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13721	mtx_unlock(&thr->queue_lock);
13722	wakeup(thr);
13723}
13724
13725static void
13726ctl_enqueue_done(union ctl_io *io)
13727{
13728	struct ctl_softc *softc = control_softc;
13729	struct ctl_thread *thr;
13730
13731	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13732	mtx_lock(&thr->queue_lock);
13733	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13734	mtx_unlock(&thr->queue_lock);
13735	wakeup(thr);
13736}
13737
13738static void
13739ctl_enqueue_isc(union ctl_io *io)
13740{
13741	struct ctl_softc *softc = control_softc;
13742	struct ctl_thread *thr;
13743
13744	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13745	mtx_lock(&thr->queue_lock);
13746	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13747	mtx_unlock(&thr->queue_lock);
13748	wakeup(thr);
13749}
13750
13751/*
13752 *  vim: ts=8
13753 */
13754