ctl.c revision 287774
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 287774 2015-09-14 08:01:05Z 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
264const static struct scsi_info_exceptions_page ie_page_default = {
265	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
266	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
267	/*info_flags*/SIEP_FLAGS_DEXCPT,
268	/*mrie*/0,
269	/*interval_timer*/{0, 0, 0, 0},
270	/*report_count*/{0, 0, 0, 0}
271};
272
273const static struct scsi_info_exceptions_page ie_page_changeable = {
274	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
275	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
276	/*info_flags*/0,
277	/*mrie*/0,
278	/*interval_timer*/{0, 0, 0, 0},
279	/*report_count*/{0, 0, 0, 0}
280};
281
282#define CTL_LBPM_LEN	(sizeof(struct ctl_logical_block_provisioning_page) - 4)
283
284const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
285	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
286	/*subpage_code*/0x02,
287	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
288	/*flags*/0,
289	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
290	/*descr*/{}},
291	{{/*flags*/0,
292	  /*resource*/0x01,
293	  /*reserved*/{0, 0},
294	  /*count*/{0, 0, 0, 0}},
295	 {/*flags*/0,
296	  /*resource*/0x02,
297	  /*reserved*/{0, 0},
298	  /*count*/{0, 0, 0, 0}},
299	 {/*flags*/0,
300	  /*resource*/0xf1,
301	  /*reserved*/{0, 0},
302	  /*count*/{0, 0, 0, 0}},
303	 {/*flags*/0,
304	  /*resource*/0xf2,
305	  /*reserved*/{0, 0},
306	  /*count*/{0, 0, 0, 0}}
307	}
308};
309
310const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
311	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
312	/*subpage_code*/0x02,
313	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
314	/*flags*/0,
315	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
316	/*descr*/{}},
317	{{/*flags*/0,
318	  /*resource*/0,
319	  /*reserved*/{0, 0},
320	  /*count*/{0, 0, 0, 0}},
321	 {/*flags*/0,
322	  /*resource*/0,
323	  /*reserved*/{0, 0},
324	  /*count*/{0, 0, 0, 0}},
325	 {/*flags*/0,
326	  /*resource*/0,
327	  /*reserved*/{0, 0},
328	  /*count*/{0, 0, 0, 0}},
329	 {/*flags*/0,
330	  /*resource*/0,
331	  /*reserved*/{0, 0},
332	  /*count*/{0, 0, 0, 0}}
333	}
334};
335
336SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
337static int worker_threads = -1;
338SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
339    &worker_threads, 1, "Number of worker threads");
340static int ctl_debug = CTL_DEBUG_NONE;
341SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
342    &ctl_debug, 0, "Enabled debug flags");
343
344/*
345 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
346 * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
347 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
348 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
349 */
350#define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
351
352static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
353				  int param);
354static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
355static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
356static int ctl_init(void);
357void ctl_shutdown(void);
358static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
359static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
360static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
361static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
362			      struct ctl_ooa *ooa_hdr,
363			      struct ctl_ooa_entry *kern_entries);
364static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
365		     struct thread *td);
366static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
367			 struct ctl_be_lun *be_lun);
368static int ctl_free_lun(struct ctl_lun *lun);
369static void ctl_create_lun(struct ctl_be_lun *be_lun);
370static struct ctl_port * ctl_io_port(struct ctl_io_hdr *io_hdr);
371
372static int ctl_do_mode_select(union ctl_io *io);
373static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
374			   uint64_t res_key, uint64_t sa_res_key,
375			   uint8_t type, uint32_t residx,
376			   struct ctl_scsiio *ctsio,
377			   struct scsi_per_res_out *cdb,
378			   struct scsi_per_res_out_parms* param);
379static void ctl_pro_preempt_other(struct ctl_lun *lun,
380				  union ctl_ha_msg *msg);
381static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
382static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
383static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
384static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
385static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
386static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
387static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
388					 int alloc_len);
389static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
390					 int alloc_len);
391static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
392static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
393static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
394static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
395static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
396static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
397    bool seq);
398static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
399static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
400    union ctl_io *pending_io, union ctl_io *ooa_io);
401static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
402				union ctl_io *starting_io);
403static int ctl_check_blocked(struct ctl_lun *lun);
404static int ctl_scsiio_lun_check(struct ctl_lun *lun,
405				const struct ctl_cmd_entry *entry,
406				struct ctl_scsiio *ctsio);
407static void ctl_failover_lun(struct ctl_lun *lun);
408static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
409			       struct ctl_scsiio *ctsio);
410static int ctl_scsiio(struct ctl_scsiio *ctsio);
411
412static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
413static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
414			    ctl_ua_type ua_type);
415static int ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io,
416			 ctl_ua_type ua_type);
417static int ctl_lun_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
418static int ctl_abort_task(union ctl_io *io);
419static int ctl_abort_task_set(union ctl_io *io);
420static int ctl_query_task(union ctl_io *io, int task_set);
421static int ctl_i_t_nexus_reset(union ctl_io *io);
422static int ctl_query_async_event(union ctl_io *io);
423static void ctl_run_task(union ctl_io *io);
424#ifdef CTL_IO_DELAY
425static void ctl_datamove_timer_wakeup(void *arg);
426static void ctl_done_timer_wakeup(void *arg);
427#endif /* CTL_IO_DELAY */
428
429static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
430static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
431static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
432static void ctl_datamove_remote_write(union ctl_io *io);
433static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
434static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
435static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
436static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
437				    ctl_ha_dt_cb callback);
438static void ctl_datamove_remote_read(union ctl_io *io);
439static void ctl_datamove_remote(union ctl_io *io);
440static int ctl_process_done(union ctl_io *io);
441static void ctl_lun_thread(void *arg);
442static void ctl_thresh_thread(void *arg);
443static void ctl_work_thread(void *arg);
444static void ctl_enqueue_incoming(union ctl_io *io);
445static void ctl_enqueue_rtr(union ctl_io *io);
446static void ctl_enqueue_done(union ctl_io *io);
447static void ctl_enqueue_isc(union ctl_io *io);
448static const struct ctl_cmd_entry *
449    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
450static const struct ctl_cmd_entry *
451    ctl_validate_command(struct ctl_scsiio *ctsio);
452static int ctl_cmd_applicable(uint8_t lun_type,
453    const struct ctl_cmd_entry *entry);
454
455static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
456static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
457static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
458static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
459
460/*
461 * Load the serialization table.  This isn't very pretty, but is probably
462 * the easiest way to do it.
463 */
464#include "ctl_ser_table.c"
465
466/*
467 * We only need to define open, close and ioctl routines for this driver.
468 */
469static struct cdevsw ctl_cdevsw = {
470	.d_version =	D_VERSION,
471	.d_flags =	0,
472	.d_open =	ctl_open,
473	.d_close =	ctl_close,
474	.d_ioctl =	ctl_ioctl,
475	.d_name =	"ctl",
476};
477
478
479MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
480
481static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
482
483static moduledata_t ctl_moduledata = {
484	"ctl",
485	ctl_module_event_handler,
486	NULL
487};
488
489DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
490MODULE_VERSION(ctl, 1);
491
492static struct ctl_frontend ha_frontend =
493{
494	.name = "ha",
495};
496
497static void
498ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
499			    union ctl_ha_msg *msg_info)
500{
501	struct ctl_scsiio *ctsio;
502
503	if (msg_info->hdr.original_sc == NULL) {
504		printf("%s: original_sc == NULL!\n", __func__);
505		/* XXX KDM now what? */
506		return;
507	}
508
509	ctsio = &msg_info->hdr.original_sc->scsiio;
510	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
511	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
512	ctsio->io_hdr.status = msg_info->hdr.status;
513	ctsio->scsi_status = msg_info->scsi.scsi_status;
514	ctsio->sense_len = msg_info->scsi.sense_len;
515	ctsio->sense_residual = msg_info->scsi.sense_residual;
516	ctsio->residual = msg_info->scsi.residual;
517	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
518	       msg_info->scsi.sense_len);
519	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
520	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
521	ctl_enqueue_isc((union ctl_io *)ctsio);
522}
523
524static void
525ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
526				union ctl_ha_msg *msg_info)
527{
528	struct ctl_scsiio *ctsio;
529
530	if (msg_info->hdr.serializing_sc == NULL) {
531		printf("%s: serializing_sc == NULL!\n", __func__);
532		/* XXX KDM now what? */
533		return;
534	}
535
536	ctsio = &msg_info->hdr.serializing_sc->scsiio;
537	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
538	ctl_enqueue_isc((union ctl_io *)ctsio);
539}
540
541void
542ctl_isc_announce_lun(struct ctl_lun *lun)
543{
544	struct ctl_softc *softc = lun->ctl_softc;
545	union ctl_ha_msg *msg;
546	struct ctl_ha_msg_lun_pr_key pr_key;
547	int i, k;
548
549	if (softc->ha_link != CTL_HA_LINK_ONLINE)
550		return;
551	mtx_lock(&lun->lun_lock);
552	i = sizeof(msg->lun);
553	if (lun->lun_devid)
554		i += lun->lun_devid->len;
555	i += sizeof(pr_key) * lun->pr_key_count;
556alloc:
557	mtx_unlock(&lun->lun_lock);
558	msg = malloc(i, M_CTL, M_WAITOK);
559	mtx_lock(&lun->lun_lock);
560	k = sizeof(msg->lun);
561	if (lun->lun_devid)
562		k += lun->lun_devid->len;
563	k += sizeof(pr_key) * lun->pr_key_count;
564	if (i < k) {
565		free(msg, M_CTL);
566		i = k;
567		goto alloc;
568	}
569	bzero(&msg->lun, sizeof(msg->lun));
570	msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
571	msg->hdr.nexus.targ_lun = lun->lun;
572	msg->hdr.nexus.targ_mapped_lun = lun->lun;
573	msg->lun.flags = lun->flags;
574	msg->lun.pr_generation = lun->PRGeneration;
575	msg->lun.pr_res_idx = lun->pr_res_idx;
576	msg->lun.pr_res_type = lun->res_type;
577	msg->lun.pr_key_count = lun->pr_key_count;
578	i = 0;
579	if (lun->lun_devid) {
580		msg->lun.lun_devid_len = lun->lun_devid->len;
581		memcpy(&msg->lun.data[i], lun->lun_devid->data,
582		    msg->lun.lun_devid_len);
583		i += msg->lun.lun_devid_len;
584	}
585	for (k = 0; k < CTL_MAX_INITIATORS; k++) {
586		if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
587			continue;
588		pr_key.pr_iid = k;
589		memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
590		i += sizeof(pr_key);
591	}
592	mtx_unlock(&lun->lun_lock);
593	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
594	    M_WAITOK);
595	free(msg, M_CTL);
596}
597
598void
599ctl_isc_announce_port(struct ctl_port *port)
600{
601	struct ctl_softc *softc = control_softc;
602	union ctl_ha_msg *msg;
603	int i;
604
605	if (port->targ_port < softc->port_min ||
606	    port->targ_port >= softc->port_max ||
607	    softc->ha_link != CTL_HA_LINK_ONLINE)
608		return;
609	i = sizeof(msg->port) + strlen(port->port_name) + 1;
610	if (port->lun_map)
611		i += sizeof(uint32_t) * CTL_MAX_LUNS;
612	if (port->port_devid)
613		i += port->port_devid->len;
614	if (port->target_devid)
615		i += port->target_devid->len;
616	msg = malloc(i, M_CTL, M_WAITOK);
617	bzero(&msg->port, sizeof(msg->port));
618	msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
619	msg->hdr.nexus.targ_port = port->targ_port;
620	msg->port.port_type = port->port_type;
621	msg->port.physical_port = port->physical_port;
622	msg->port.virtual_port = port->virtual_port;
623	msg->port.status = port->status;
624	i = 0;
625	msg->port.name_len = sprintf(&msg->port.data[i],
626	    "%d:%s", softc->ha_id, port->port_name) + 1;
627	i += msg->port.name_len;
628	if (port->lun_map) {
629		msg->port.lun_map_len = sizeof(uint32_t) * CTL_MAX_LUNS;
630		memcpy(&msg->port.data[i], port->lun_map,
631		    msg->port.lun_map_len);
632		i += msg->port.lun_map_len;
633	}
634	if (port->port_devid) {
635		msg->port.port_devid_len = port->port_devid->len;
636		memcpy(&msg->port.data[i], port->port_devid->data,
637		    msg->port.port_devid_len);
638		i += msg->port.port_devid_len;
639	}
640	if (port->target_devid) {
641		msg->port.target_devid_len = port->target_devid->len;
642		memcpy(&msg->port.data[i], port->target_devid->data,
643		    msg->port.target_devid_len);
644		i += msg->port.target_devid_len;
645	}
646	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
647	    M_WAITOK);
648	free(msg, M_CTL);
649}
650
651static void
652ctl_isc_ha_link_up(struct ctl_softc *softc)
653{
654	struct ctl_port *port;
655	struct ctl_lun *lun;
656
657	STAILQ_FOREACH(port, &softc->port_list, links)
658		ctl_isc_announce_port(port);
659	STAILQ_FOREACH(lun, &softc->lun_list, links)
660		ctl_isc_announce_lun(lun);
661}
662
663static void
664ctl_isc_ha_link_down(struct ctl_softc *softc)
665{
666	struct ctl_port *port;
667	struct ctl_lun *lun;
668	union ctl_io *io;
669
670	mtx_lock(&softc->ctl_lock);
671	STAILQ_FOREACH(lun, &softc->lun_list, links) {
672		mtx_lock(&lun->lun_lock);
673		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
674			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
675			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
676		}
677		mtx_unlock(&lun->lun_lock);
678
679		mtx_unlock(&softc->ctl_lock);
680		io = ctl_alloc_io(softc->othersc_pool);
681		mtx_lock(&softc->ctl_lock);
682		ctl_zero_io(io);
683		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
684		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
685		ctl_enqueue_isc(io);
686	}
687
688	STAILQ_FOREACH(port, &softc->port_list, links) {
689		if (port->targ_port >= softc->port_min &&
690		    port->targ_port < softc->port_max)
691			continue;
692		port->status &= ~CTL_PORT_STATUS_ONLINE;
693	}
694	mtx_unlock(&softc->ctl_lock);
695}
696
697static void
698ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
699{
700	struct ctl_lun *lun;
701	uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
702
703	mtx_lock(&softc->ctl_lock);
704	if (msg->hdr.nexus.targ_lun < CTL_MAX_LUNS &&
705	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) != NULL) {
706		mtx_lock(&lun->lun_lock);
707		mtx_unlock(&softc->ctl_lock);
708		if (msg->ua.ua_all) {
709			if (msg->ua.ua_set)
710				ctl_est_ua_all(lun, iid, msg->ua.ua_type);
711			else
712				ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
713		} else {
714			if (msg->ua.ua_set)
715				ctl_est_ua(lun, iid, msg->ua.ua_type);
716			else
717				ctl_clr_ua(lun, iid, msg->ua.ua_type);
718		}
719		mtx_unlock(&lun->lun_lock);
720	} else
721		mtx_unlock(&softc->ctl_lock);
722}
723
724static void
725ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
726{
727	struct ctl_lun *lun;
728	struct ctl_ha_msg_lun_pr_key pr_key;
729	int i, k;
730	ctl_lun_flags oflags;
731	uint32_t targ_lun;
732
733	targ_lun = msg->hdr.nexus.targ_mapped_lun;
734	mtx_lock(&softc->ctl_lock);
735	if ((targ_lun >= CTL_MAX_LUNS) ||
736	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
737		mtx_unlock(&softc->ctl_lock);
738		return;
739	}
740	mtx_lock(&lun->lun_lock);
741	mtx_unlock(&softc->ctl_lock);
742	if (lun->flags & CTL_LUN_DISABLED) {
743		mtx_unlock(&lun->lun_lock);
744		return;
745	}
746	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
747	if (msg->lun.lun_devid_len != i || (i > 0 &&
748	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
749		mtx_unlock(&lun->lun_lock);
750		printf("%s: Received conflicting HA LUN %d\n",
751		    __func__, msg->hdr.nexus.targ_lun);
752		return;
753	} else {
754		/* Record whether peer is primary. */
755		oflags = lun->flags;
756		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
757		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
758			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
759		else
760			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
761		if (oflags != lun->flags)
762			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
763
764		/* If peer is primary and we are not -- use data */
765		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
766		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
767			lun->PRGeneration = msg->lun.pr_generation;
768			lun->pr_res_idx = msg->lun.pr_res_idx;
769			lun->res_type = msg->lun.pr_res_type;
770			lun->pr_key_count = msg->lun.pr_key_count;
771			for (k = 0; k < CTL_MAX_INITIATORS; k++)
772				ctl_clr_prkey(lun, k);
773			for (k = 0; k < msg->lun.pr_key_count; k++) {
774				memcpy(&pr_key, &msg->lun.data[i],
775				    sizeof(pr_key));
776				ctl_alloc_prkey(lun, pr_key.pr_iid);
777				ctl_set_prkey(lun, pr_key.pr_iid,
778				    pr_key.pr_key);
779				i += sizeof(pr_key);
780			}
781		}
782
783		mtx_unlock(&lun->lun_lock);
784		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
785		    __func__, msg->hdr.nexus.targ_lun,
786		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
787		    "primary" : "secondary"));
788
789		/* If we are primary but peer doesn't know -- notify */
790		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
791		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
792			ctl_isc_announce_lun(lun);
793	}
794}
795
796static void
797ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
798{
799	struct ctl_port *port;
800	struct ctl_lun *lun;
801	int i, new;
802
803	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
804	if (port == NULL) {
805		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
806		    msg->hdr.nexus.targ_port));
807		new = 1;
808		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
809		port->frontend = &ha_frontend;
810		port->targ_port = msg->hdr.nexus.targ_port;
811	} else if (port->frontend == &ha_frontend) {
812		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
813		    msg->hdr.nexus.targ_port));
814		new = 0;
815	} else {
816		printf("%s: Received conflicting HA port %d\n",
817		    __func__, msg->hdr.nexus.targ_port);
818		return;
819	}
820	port->port_type = msg->port.port_type;
821	port->physical_port = msg->port.physical_port;
822	port->virtual_port = msg->port.virtual_port;
823	port->status = msg->port.status;
824	i = 0;
825	free(port->port_name, M_CTL);
826	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
827	    M_CTL);
828	i += msg->port.name_len;
829	if (msg->port.lun_map_len != 0) {
830		if (port->lun_map == NULL)
831			port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
832			    M_CTL, M_WAITOK);
833		memcpy(port->lun_map, &msg->port.data[i],
834		    sizeof(uint32_t) * CTL_MAX_LUNS);
835		i += msg->port.lun_map_len;
836	} else {
837		free(port->lun_map, M_CTL);
838		port->lun_map = NULL;
839	}
840	if (msg->port.port_devid_len != 0) {
841		if (port->port_devid == NULL ||
842		    port->port_devid->len != msg->port.port_devid_len) {
843			free(port->port_devid, M_CTL);
844			port->port_devid = malloc(sizeof(struct ctl_devid) +
845			    msg->port.port_devid_len, M_CTL, M_WAITOK);
846		}
847		memcpy(port->port_devid->data, &msg->port.data[i],
848		    msg->port.port_devid_len);
849		port->port_devid->len = msg->port.port_devid_len;
850		i += msg->port.port_devid_len;
851	} else {
852		free(port->port_devid, M_CTL);
853		port->port_devid = NULL;
854	}
855	if (msg->port.target_devid_len != 0) {
856		if (port->target_devid == NULL ||
857		    port->target_devid->len != msg->port.target_devid_len) {
858			free(port->target_devid, M_CTL);
859			port->target_devid = malloc(sizeof(struct ctl_devid) +
860			    msg->port.target_devid_len, M_CTL, M_WAITOK);
861		}
862		memcpy(port->target_devid->data, &msg->port.data[i],
863		    msg->port.target_devid_len);
864		port->target_devid->len = msg->port.target_devid_len;
865		i += msg->port.target_devid_len;
866	} else {
867		free(port->port_devid, M_CTL);
868		port->port_devid = NULL;
869	}
870	if (new) {
871		if (ctl_port_register(port) != 0) {
872			printf("%s: ctl_port_register() failed with error\n",
873			    __func__);
874		}
875	}
876	mtx_lock(&softc->ctl_lock);
877	STAILQ_FOREACH(lun, &softc->lun_list, links) {
878		if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
879			continue;
880		mtx_lock(&lun->lun_lock);
881		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
882		mtx_unlock(&lun->lun_lock);
883	}
884	mtx_unlock(&softc->ctl_lock);
885}
886
887/*
888 * ISC (Inter Shelf Communication) event handler.  Events from the HA
889 * subsystem come in here.
890 */
891static void
892ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
893{
894	struct ctl_softc *softc;
895	union ctl_io *io;
896	struct ctl_prio *presio;
897	ctl_ha_status isc_status;
898
899	softc = control_softc;
900	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
901	if (event == CTL_HA_EVT_MSG_RECV) {
902		union ctl_ha_msg *msg, msgbuf;
903
904		if (param > sizeof(msgbuf))
905			msg = malloc(param, M_CTL, M_WAITOK);
906		else
907			msg = &msgbuf;
908		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
909		    M_WAITOK);
910		if (isc_status != CTL_HA_STATUS_SUCCESS) {
911			printf("%s: Error receiving message: %d\n",
912			    __func__, isc_status);
913			if (msg != &msgbuf)
914				free(msg, M_CTL);
915			return;
916		}
917
918		CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
919		switch (msg->hdr.msg_type) {
920		case CTL_MSG_SERIALIZE:
921			io = ctl_alloc_io(softc->othersc_pool);
922			ctl_zero_io(io);
923			// populate ctsio from msg
924			io->io_hdr.io_type = CTL_IO_SCSI;
925			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
926			io->io_hdr.original_sc = msg->hdr.original_sc;
927			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
928					    CTL_FLAG_IO_ACTIVE;
929			/*
930			 * If we're in serialization-only mode, we don't
931			 * want to go through full done processing.  Thus
932			 * the COPY flag.
933			 *
934			 * XXX KDM add another flag that is more specific.
935			 */
936			if (softc->ha_mode != CTL_HA_MODE_XFER)
937				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
938			io->io_hdr.nexus = msg->hdr.nexus;
939#if 0
940			printf("port %u, iid %u, lun %u\n",
941			       io->io_hdr.nexus.targ_port,
942			       io->io_hdr.nexus.initid,
943			       io->io_hdr.nexus.targ_lun);
944#endif
945			io->scsiio.tag_num = msg->scsi.tag_num;
946			io->scsiio.tag_type = msg->scsi.tag_type;
947#ifdef CTL_TIME_IO
948			io->io_hdr.start_time = time_uptime;
949			getbintime(&io->io_hdr.start_bt);
950#endif /* CTL_TIME_IO */
951			io->scsiio.cdb_len = msg->scsi.cdb_len;
952			memcpy(io->scsiio.cdb, msg->scsi.cdb,
953			       CTL_MAX_CDBLEN);
954			if (softc->ha_mode == CTL_HA_MODE_XFER) {
955				const struct ctl_cmd_entry *entry;
956
957				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
958				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
959				io->io_hdr.flags |=
960					entry->flags & CTL_FLAG_DATA_MASK;
961			}
962			ctl_enqueue_isc(io);
963			break;
964
965		/* Performed on the Originating SC, XFER mode only */
966		case CTL_MSG_DATAMOVE: {
967			struct ctl_sg_entry *sgl;
968			int i, j;
969
970			io = msg->hdr.original_sc;
971			if (io == NULL) {
972				printf("%s: original_sc == NULL!\n", __func__);
973				/* XXX KDM do something here */
974				break;
975			}
976			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
977			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
978			/*
979			 * Keep track of this, we need to send it back over
980			 * when the datamove is complete.
981			 */
982			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
983
984			if (msg->dt.sg_sequence == 0) {
985				i = msg->dt.kern_sg_entries +
986				    io->scsiio.kern_data_len /
987				    CTL_HA_DATAMOVE_SEGMENT + 1;
988				sgl = malloc(sizeof(*sgl) * i, M_CTL,
989				    M_WAITOK | M_ZERO);
990				io->io_hdr.remote_sglist = sgl;
991				io->io_hdr.local_sglist =
992				    &sgl[msg->dt.kern_sg_entries];
993
994				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
995
996				io->scsiio.kern_sg_entries =
997					msg->dt.kern_sg_entries;
998				io->scsiio.rem_sg_entries =
999					msg->dt.kern_sg_entries;
1000				io->scsiio.kern_data_len =
1001					msg->dt.kern_data_len;
1002				io->scsiio.kern_total_len =
1003					msg->dt.kern_total_len;
1004				io->scsiio.kern_data_resid =
1005					msg->dt.kern_data_resid;
1006				io->scsiio.kern_rel_offset =
1007					msg->dt.kern_rel_offset;
1008				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1009				io->io_hdr.flags |= msg->dt.flags &
1010				    CTL_FLAG_BUS_ADDR;
1011			} else
1012				sgl = (struct ctl_sg_entry *)
1013					io->scsiio.kern_data_ptr;
1014
1015			for (i = msg->dt.sent_sg_entries, j = 0;
1016			     i < (msg->dt.sent_sg_entries +
1017			     msg->dt.cur_sg_entries); i++, j++) {
1018				sgl[i].addr = msg->dt.sg_list[j].addr;
1019				sgl[i].len = msg->dt.sg_list[j].len;
1020
1021#if 0
1022				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
1023				       __func__,
1024				       msg->dt.sg_list[j].addr,
1025				       msg->dt.sg_list[j].len,
1026				       sgl[i].addr, sgl[i].len, j, i);
1027#endif
1028			}
1029
1030			/*
1031			 * If this is the last piece of the I/O, we've got
1032			 * the full S/G list.  Queue processing in the thread.
1033			 * Otherwise wait for the next piece.
1034			 */
1035			if (msg->dt.sg_last != 0)
1036				ctl_enqueue_isc(io);
1037			break;
1038		}
1039		/* Performed on the Serializing (primary) SC, XFER mode only */
1040		case CTL_MSG_DATAMOVE_DONE: {
1041			if (msg->hdr.serializing_sc == NULL) {
1042				printf("%s: serializing_sc == NULL!\n",
1043				       __func__);
1044				/* XXX KDM now what? */
1045				break;
1046			}
1047			/*
1048			 * We grab the sense information here in case
1049			 * there was a failure, so we can return status
1050			 * back to the initiator.
1051			 */
1052			io = msg->hdr.serializing_sc;
1053			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1054			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1055			io->io_hdr.port_status = msg->scsi.fetd_status;
1056			io->scsiio.residual = msg->scsi.residual;
1057			if (msg->hdr.status != CTL_STATUS_NONE) {
1058				io->io_hdr.status = msg->hdr.status;
1059				io->scsiio.scsi_status = msg->scsi.scsi_status;
1060				io->scsiio.sense_len = msg->scsi.sense_len;
1061				io->scsiio.sense_residual =msg->scsi.sense_residual;
1062				memcpy(&io->scsiio.sense_data,
1063				    &msg->scsi.sense_data,
1064				    msg->scsi.sense_len);
1065			}
1066			ctl_enqueue_isc(io);
1067			break;
1068		}
1069
1070		/* Preformed on Originating SC, SER_ONLY mode */
1071		case CTL_MSG_R2R:
1072			io = msg->hdr.original_sc;
1073			if (io == NULL) {
1074				printf("%s: original_sc == NULL!\n",
1075				    __func__);
1076				break;
1077			}
1078			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1079			io->io_hdr.msg_type = CTL_MSG_R2R;
1080			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1081			ctl_enqueue_isc(io);
1082			break;
1083
1084		/*
1085		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1086		 * mode.
1087		 * Performed on the Originating (i.e. secondary) SC in XFER
1088		 * mode
1089		 */
1090		case CTL_MSG_FINISH_IO:
1091			if (softc->ha_mode == CTL_HA_MODE_XFER)
1092				ctl_isc_handler_finish_xfer(softc, msg);
1093			else
1094				ctl_isc_handler_finish_ser_only(softc, msg);
1095			break;
1096
1097		/* Preformed on Originating SC */
1098		case CTL_MSG_BAD_JUJU:
1099			io = msg->hdr.original_sc;
1100			if (io == NULL) {
1101				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1102				       __func__);
1103				break;
1104			}
1105			ctl_copy_sense_data(msg, io);
1106			/*
1107			 * IO should have already been cleaned up on other
1108			 * SC so clear this flag so we won't send a message
1109			 * back to finish the IO there.
1110			 */
1111			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1112			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1113
1114			/* io = msg->hdr.serializing_sc; */
1115			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1116			ctl_enqueue_isc(io);
1117			break;
1118
1119		/* Handle resets sent from the other side */
1120		case CTL_MSG_MANAGE_TASKS: {
1121			struct ctl_taskio *taskio;
1122			taskio = (struct ctl_taskio *)ctl_alloc_io(
1123			    softc->othersc_pool);
1124			ctl_zero_io((union ctl_io *)taskio);
1125			taskio->io_hdr.io_type = CTL_IO_TASK;
1126			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1127			taskio->io_hdr.nexus = msg->hdr.nexus;
1128			taskio->task_action = msg->task.task_action;
1129			taskio->tag_num = msg->task.tag_num;
1130			taskio->tag_type = msg->task.tag_type;
1131#ifdef CTL_TIME_IO
1132			taskio->io_hdr.start_time = time_uptime;
1133			getbintime(&taskio->io_hdr.start_bt);
1134#endif /* CTL_TIME_IO */
1135			ctl_run_task((union ctl_io *)taskio);
1136			break;
1137		}
1138		/* Persistent Reserve action which needs attention */
1139		case CTL_MSG_PERS_ACTION:
1140			presio = (struct ctl_prio *)ctl_alloc_io(
1141			    softc->othersc_pool);
1142			ctl_zero_io((union ctl_io *)presio);
1143			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1144			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1145			presio->io_hdr.nexus = msg->hdr.nexus;
1146			presio->pr_msg = msg->pr;
1147			ctl_enqueue_isc((union ctl_io *)presio);
1148			break;
1149		case CTL_MSG_UA:
1150			ctl_isc_ua(softc, msg, param);
1151			break;
1152		case CTL_MSG_PORT_SYNC:
1153			ctl_isc_port_sync(softc, msg, param);
1154			break;
1155		case CTL_MSG_LUN_SYNC:
1156			ctl_isc_lun_sync(softc, msg, param);
1157			break;
1158		default:
1159			printf("Received HA message of unknown type %d\n",
1160			    msg->hdr.msg_type);
1161			break;
1162		}
1163		if (msg != &msgbuf)
1164			free(msg, M_CTL);
1165	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1166		printf("CTL: HA link status changed from %d to %d\n",
1167		    softc->ha_link, param);
1168		if (param == softc->ha_link)
1169			return;
1170		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1171			softc->ha_link = param;
1172			ctl_isc_ha_link_down(softc);
1173		} else {
1174			softc->ha_link = param;
1175			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1176				ctl_isc_ha_link_up(softc);
1177		}
1178		return;
1179	} else {
1180		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1181		return;
1182	}
1183}
1184
1185static void
1186ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1187{
1188
1189	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1190	    src->scsi.sense_len);
1191	dest->scsiio.scsi_status = src->scsi.scsi_status;
1192	dest->scsiio.sense_len = src->scsi.sense_len;
1193	dest->io_hdr.status = src->hdr.status;
1194}
1195
1196static void
1197ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1198{
1199
1200	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1201	    src->scsiio.sense_len);
1202	dest->scsi.scsi_status = src->scsiio.scsi_status;
1203	dest->scsi.sense_len = src->scsiio.sense_len;
1204	dest->hdr.status = src->io_hdr.status;
1205}
1206
1207void
1208ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1209{
1210	struct ctl_softc *softc = lun->ctl_softc;
1211	ctl_ua_type *pu;
1212
1213	if (initidx < softc->init_min || initidx >= softc->init_max)
1214		return;
1215	mtx_assert(&lun->lun_lock, MA_OWNED);
1216	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1217	if (pu == NULL)
1218		return;
1219	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1220}
1221
1222void
1223ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1224{
1225	int i;
1226
1227	mtx_assert(&lun->lun_lock, MA_OWNED);
1228	if (lun->pending_ua[port] == NULL)
1229		return;
1230	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1231		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1232			continue;
1233		lun->pending_ua[port][i] |= ua;
1234	}
1235}
1236
1237void
1238ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1239{
1240	struct ctl_softc *softc = lun->ctl_softc;
1241	int i;
1242
1243	mtx_assert(&lun->lun_lock, MA_OWNED);
1244	for (i = softc->port_min; i < softc->port_max; i++)
1245		ctl_est_ua_port(lun, i, except, ua);
1246}
1247
1248void
1249ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1250{
1251	struct ctl_softc *softc = lun->ctl_softc;
1252	ctl_ua_type *pu;
1253
1254	if (initidx < softc->init_min || initidx >= softc->init_max)
1255		return;
1256	mtx_assert(&lun->lun_lock, MA_OWNED);
1257	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1258	if (pu == NULL)
1259		return;
1260	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1261}
1262
1263void
1264ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1265{
1266	struct ctl_softc *softc = lun->ctl_softc;
1267	int i, j;
1268
1269	mtx_assert(&lun->lun_lock, MA_OWNED);
1270	for (i = softc->port_min; i < softc->port_max; i++) {
1271		if (lun->pending_ua[i] == NULL)
1272			continue;
1273		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1274			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1275				continue;
1276			lun->pending_ua[i][j] &= ~ua;
1277		}
1278	}
1279}
1280
1281void
1282ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1283    ctl_ua_type ua_type)
1284{
1285	struct ctl_lun *lun;
1286
1287	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1288	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1289		mtx_lock(&lun->lun_lock);
1290		ctl_clr_ua(lun, initidx, ua_type);
1291		mtx_unlock(&lun->lun_lock);
1292	}
1293}
1294
1295static int
1296ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1297{
1298	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1299	struct ctl_lun *lun;
1300	struct ctl_lun_req ireq;
1301	int error, value;
1302
1303	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1304	error = sysctl_handle_int(oidp, &value, 0, req);
1305	if ((error != 0) || (req->newptr == NULL))
1306		return (error);
1307
1308	mtx_lock(&softc->ctl_lock);
1309	if (value == 0)
1310		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1311	else
1312		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1313	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1314		mtx_unlock(&softc->ctl_lock);
1315		bzero(&ireq, sizeof(ireq));
1316		ireq.reqtype = CTL_LUNREQ_MODIFY;
1317		ireq.reqdata.modify.lun_id = lun->lun;
1318		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1319		    curthread);
1320		if (ireq.status != CTL_LUN_OK) {
1321			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1322			    __func__, ireq.status, ireq.error_str);
1323		}
1324		mtx_lock(&softc->ctl_lock);
1325	}
1326	mtx_unlock(&softc->ctl_lock);
1327	return (0);
1328}
1329
1330static int
1331ctl_init(void)
1332{
1333	struct ctl_softc *softc;
1334	void *other_pool;
1335	int i, error, retval;
1336
1337	retval = 0;
1338	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1339			       M_WAITOK | M_ZERO);
1340	softc = control_softc;
1341
1342	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1343			      "cam/ctl");
1344
1345	softc->dev->si_drv1 = softc;
1346
1347	sysctl_ctx_init(&softc->sysctl_ctx);
1348	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1349		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1350		CTLFLAG_RD, 0, "CAM Target Layer");
1351
1352	if (softc->sysctl_tree == NULL) {
1353		printf("%s: unable to allocate sysctl tree\n", __func__);
1354		destroy_dev(softc->dev);
1355		free(control_softc, M_DEVBUF);
1356		control_softc = NULL;
1357		return (ENOMEM);
1358	}
1359
1360	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1361	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1362	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1363	softc->open_count = 0;
1364
1365	/*
1366	 * Default to actually sending a SYNCHRONIZE CACHE command down to
1367	 * the drive.
1368	 */
1369	softc->flags = CTL_FLAG_REAL_SYNC;
1370
1371	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1372	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1373	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1374
1375	/*
1376	 * In Copan's HA scheme, the "master" and "slave" roles are
1377	 * figured out through the slot the controller is in.  Although it
1378	 * is an active/active system, someone has to be in charge.
1379	 */
1380	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1381	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1382	    "HA head ID (0 - no HA)");
1383	if (softc->ha_id == 0 || softc->ha_id > NUM_TARGET_PORT_GROUPS) {
1384		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1385		softc->is_single = 1;
1386		softc->port_cnt = CTL_MAX_PORTS;
1387		softc->port_min = 0;
1388	} else {
1389		softc->port_cnt = CTL_MAX_PORTS / NUM_TARGET_PORT_GROUPS;
1390		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1391	}
1392	softc->port_max = softc->port_min + softc->port_cnt;
1393	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1394	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1395
1396	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1397	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1398	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
1399
1400	STAILQ_INIT(&softc->lun_list);
1401	STAILQ_INIT(&softc->pending_lun_queue);
1402	STAILQ_INIT(&softc->fe_list);
1403	STAILQ_INIT(&softc->port_list);
1404	STAILQ_INIT(&softc->be_list);
1405	ctl_tpc_init(softc);
1406
1407	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1408	                    &other_pool) != 0)
1409	{
1410		printf("ctl: can't allocate %d entry other SC pool, "
1411		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1412		return (ENOMEM);
1413	}
1414	softc->othersc_pool = other_pool;
1415
1416	if (worker_threads <= 0)
1417		worker_threads = max(1, mp_ncpus / 4);
1418	if (worker_threads > CTL_MAX_THREADS)
1419		worker_threads = CTL_MAX_THREADS;
1420
1421	for (i = 0; i < worker_threads; i++) {
1422		struct ctl_thread *thr = &softc->threads[i];
1423
1424		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1425		thr->ctl_softc = softc;
1426		STAILQ_INIT(&thr->incoming_queue);
1427		STAILQ_INIT(&thr->rtr_queue);
1428		STAILQ_INIT(&thr->done_queue);
1429		STAILQ_INIT(&thr->isc_queue);
1430
1431		error = kproc_kthread_add(ctl_work_thread, thr,
1432		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1433		if (error != 0) {
1434			printf("error creating CTL work thread!\n");
1435			ctl_pool_free(other_pool);
1436			return (error);
1437		}
1438	}
1439	error = kproc_kthread_add(ctl_lun_thread, softc,
1440	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1441	if (error != 0) {
1442		printf("error creating CTL lun thread!\n");
1443		ctl_pool_free(other_pool);
1444		return (error);
1445	}
1446	error = kproc_kthread_add(ctl_thresh_thread, softc,
1447	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1448	if (error != 0) {
1449		printf("error creating CTL threshold thread!\n");
1450		ctl_pool_free(other_pool);
1451		return (error);
1452	}
1453
1454	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1455	    OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1456	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1457
1458	if (softc->is_single == 0) {
1459		ctl_frontend_register(&ha_frontend);
1460		if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
1461			printf("ctl_init: ctl_ha_msg_init failed.\n");
1462			softc->is_single = 1;
1463		} else
1464		if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
1465		    != CTL_HA_STATUS_SUCCESS) {
1466			printf("ctl_init: ctl_ha_msg_register failed.\n");
1467			softc->is_single = 1;
1468		}
1469	}
1470	return (0);
1471}
1472
1473void
1474ctl_shutdown(void)
1475{
1476	struct ctl_softc *softc;
1477	struct ctl_lun *lun, *next_lun;
1478
1479	softc = (struct ctl_softc *)control_softc;
1480
1481	if (softc->is_single == 0) {
1482		if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL)
1483		    != CTL_HA_STATUS_SUCCESS) {
1484			printf("ctl_shutdown: ctl_ha_msg_deregister failed.\n");
1485		}
1486		if (ctl_ha_msg_shutdown(softc) != CTL_HA_STATUS_SUCCESS) {
1487			printf("ctl_shutdown: ctl_ha_msg_shutdown failed.\n");
1488		}
1489		ctl_frontend_deregister(&ha_frontend);
1490	}
1491
1492	mtx_lock(&softc->ctl_lock);
1493
1494	/*
1495	 * Free up each LUN.
1496	 */
1497	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1498		next_lun = STAILQ_NEXT(lun, links);
1499		ctl_free_lun(lun);
1500	}
1501
1502	mtx_unlock(&softc->ctl_lock);
1503
1504#if 0
1505	ctl_shutdown_thread(softc->work_thread);
1506	mtx_destroy(&softc->queue_lock);
1507#endif
1508
1509	ctl_tpc_shutdown(softc);
1510	uma_zdestroy(softc->io_zone);
1511	mtx_destroy(&softc->ctl_lock);
1512
1513	destroy_dev(softc->dev);
1514
1515	sysctl_ctx_free(&softc->sysctl_ctx);
1516
1517	free(control_softc, M_DEVBUF);
1518	control_softc = NULL;
1519}
1520
1521static int
1522ctl_module_event_handler(module_t mod, int what, void *arg)
1523{
1524
1525	switch (what) {
1526	case MOD_LOAD:
1527		return (ctl_init());
1528	case MOD_UNLOAD:
1529		return (EBUSY);
1530	default:
1531		return (EOPNOTSUPP);
1532	}
1533}
1534
1535/*
1536 * XXX KDM should we do some access checks here?  Bump a reference count to
1537 * prevent a CTL module from being unloaded while someone has it open?
1538 */
1539static int
1540ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1541{
1542	return (0);
1543}
1544
1545static int
1546ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1547{
1548	return (0);
1549}
1550
1551/*
1552 * Remove an initiator by port number and initiator ID.
1553 * Returns 0 for success, -1 for failure.
1554 */
1555int
1556ctl_remove_initiator(struct ctl_port *port, int iid)
1557{
1558	struct ctl_softc *softc = control_softc;
1559
1560	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1561
1562	if (iid > CTL_MAX_INIT_PER_PORT) {
1563		printf("%s: initiator ID %u > maximun %u!\n",
1564		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1565		return (-1);
1566	}
1567
1568	mtx_lock(&softc->ctl_lock);
1569	port->wwpn_iid[iid].in_use--;
1570	port->wwpn_iid[iid].last_use = time_uptime;
1571	mtx_unlock(&softc->ctl_lock);
1572
1573	return (0);
1574}
1575
1576/*
1577 * Add an initiator to the initiator map.
1578 * Returns iid for success, < 0 for failure.
1579 */
1580int
1581ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1582{
1583	struct ctl_softc *softc = control_softc;
1584	time_t best_time;
1585	int i, best;
1586
1587	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1588
1589	if (iid >= CTL_MAX_INIT_PER_PORT) {
1590		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1591		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1592		free(name, M_CTL);
1593		return (-1);
1594	}
1595
1596	mtx_lock(&softc->ctl_lock);
1597
1598	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1599		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1600			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1601				iid = i;
1602				break;
1603			}
1604			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1605			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1606				iid = i;
1607				break;
1608			}
1609		}
1610	}
1611
1612	if (iid < 0) {
1613		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1614			if (port->wwpn_iid[i].in_use == 0 &&
1615			    port->wwpn_iid[i].wwpn == 0 &&
1616			    port->wwpn_iid[i].name == NULL) {
1617				iid = i;
1618				break;
1619			}
1620		}
1621	}
1622
1623	if (iid < 0) {
1624		best = -1;
1625		best_time = INT32_MAX;
1626		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1627			if (port->wwpn_iid[i].in_use == 0) {
1628				if (port->wwpn_iid[i].last_use < best_time) {
1629					best = i;
1630					best_time = port->wwpn_iid[i].last_use;
1631				}
1632			}
1633		}
1634		iid = best;
1635	}
1636
1637	if (iid < 0) {
1638		mtx_unlock(&softc->ctl_lock);
1639		free(name, M_CTL);
1640		return (-2);
1641	}
1642
1643	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1644		/*
1645		 * This is not an error yet.
1646		 */
1647		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1648#if 0
1649			printf("%s: port %d iid %u WWPN %#jx arrived"
1650			    " again\n", __func__, port->targ_port,
1651			    iid, (uintmax_t)wwpn);
1652#endif
1653			goto take;
1654		}
1655		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1656		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1657#if 0
1658			printf("%s: port %d iid %u name '%s' arrived"
1659			    " again\n", __func__, port->targ_port,
1660			    iid, name);
1661#endif
1662			goto take;
1663		}
1664
1665		/*
1666		 * This is an error, but what do we do about it?  The
1667		 * driver is telling us we have a new WWPN for this
1668		 * initiator ID, so we pretty much need to use it.
1669		 */
1670		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1671		    " but WWPN %#jx '%s' is still at that address\n",
1672		    __func__, port->targ_port, iid, wwpn, name,
1673		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1674		    port->wwpn_iid[iid].name);
1675
1676		/*
1677		 * XXX KDM clear have_ca and ua_pending on each LUN for
1678		 * this initiator.
1679		 */
1680	}
1681take:
1682	free(port->wwpn_iid[iid].name, M_CTL);
1683	port->wwpn_iid[iid].name = name;
1684	port->wwpn_iid[iid].wwpn = wwpn;
1685	port->wwpn_iid[iid].in_use++;
1686	mtx_unlock(&softc->ctl_lock);
1687
1688	return (iid);
1689}
1690
1691static int
1692ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1693{
1694	int len;
1695
1696	switch (port->port_type) {
1697	case CTL_PORT_FC:
1698	{
1699		struct scsi_transportid_fcp *id =
1700		    (struct scsi_transportid_fcp *)buf;
1701		if (port->wwpn_iid[iid].wwpn == 0)
1702			return (0);
1703		memset(id, 0, sizeof(*id));
1704		id->format_protocol = SCSI_PROTO_FC;
1705		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1706		return (sizeof(*id));
1707	}
1708	case CTL_PORT_ISCSI:
1709	{
1710		struct scsi_transportid_iscsi_port *id =
1711		    (struct scsi_transportid_iscsi_port *)buf;
1712		if (port->wwpn_iid[iid].name == NULL)
1713			return (0);
1714		memset(id, 0, 256);
1715		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1716		    SCSI_PROTO_ISCSI;
1717		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1718		len = roundup2(min(len, 252), 4);
1719		scsi_ulto2b(len, id->additional_length);
1720		return (sizeof(*id) + len);
1721	}
1722	case CTL_PORT_SAS:
1723	{
1724		struct scsi_transportid_sas *id =
1725		    (struct scsi_transportid_sas *)buf;
1726		if (port->wwpn_iid[iid].wwpn == 0)
1727			return (0);
1728		memset(id, 0, sizeof(*id));
1729		id->format_protocol = SCSI_PROTO_SAS;
1730		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1731		return (sizeof(*id));
1732	}
1733	default:
1734	{
1735		struct scsi_transportid_spi *id =
1736		    (struct scsi_transportid_spi *)buf;
1737		memset(id, 0, sizeof(*id));
1738		id->format_protocol = SCSI_PROTO_SPI;
1739		scsi_ulto2b(iid, id->scsi_addr);
1740		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1741		return (sizeof(*id));
1742	}
1743	}
1744}
1745
1746/*
1747 * Serialize a command that went down the "wrong" side, and so was sent to
1748 * this controller for execution.  The logic is a little different than the
1749 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1750 * sent back to the other side, but in the success case, we execute the
1751 * command on this side (XFER mode) or tell the other side to execute it
1752 * (SER_ONLY mode).
1753 */
1754static int
1755ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1756{
1757	struct ctl_softc *softc;
1758	union ctl_ha_msg msg_info;
1759	struct ctl_lun *lun;
1760	const struct ctl_cmd_entry *entry;
1761	int retval = 0;
1762	uint32_t targ_lun;
1763
1764	softc = control_softc;
1765
1766	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1767	mtx_lock(&softc->ctl_lock);
1768	if ((targ_lun < CTL_MAX_LUNS) &&
1769	    ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
1770		mtx_lock(&lun->lun_lock);
1771		mtx_unlock(&softc->ctl_lock);
1772		/*
1773		 * If the LUN is invalid, pretend that it doesn't exist.
1774		 * It will go away as soon as all pending I/O has been
1775		 * completed.
1776		 */
1777		if (lun->flags & CTL_LUN_DISABLED) {
1778			mtx_unlock(&lun->lun_lock);
1779			lun = NULL;
1780		}
1781	} else {
1782		mtx_unlock(&softc->ctl_lock);
1783		lun = NULL;
1784	}
1785	if (lun == NULL) {
1786		/*
1787		 * The other node would not send this request to us unless
1788		 * received announce that we are primary node for this LUN.
1789		 * If this LUN does not exist now, it is probably result of
1790		 * a race, so respond to initiator in the most opaque way.
1791		 */
1792		ctl_set_busy(ctsio);
1793		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
1794		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1795		msg_info.hdr.serializing_sc = NULL;
1796		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1797		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1798		    sizeof(msg_info.scsi), M_WAITOK);
1799		return(1);
1800	}
1801
1802	entry = ctl_get_cmd_entry(ctsio, NULL);
1803	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
1804		mtx_unlock(&lun->lun_lock);
1805		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
1806		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1807		msg_info.hdr.serializing_sc = NULL;
1808		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1809		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1810		    sizeof(msg_info.scsi), M_WAITOK);
1811		return(1);
1812	}
1813
1814	ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
1815	ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = lun->be_lun;
1816
1817	/*
1818	 * Every I/O goes into the OOA queue for a
1819	 * particular LUN, and stays there until completion.
1820	 */
1821#ifdef CTL_TIME_IO
1822	if (TAILQ_EMPTY(&lun->ooa_queue))
1823		lun->idle_time += getsbinuptime() - lun->last_busy;
1824#endif
1825	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1826
1827	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1828		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1829		 ooa_links))) {
1830	case CTL_ACTION_BLOCK:
1831		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1832		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1833				  blocked_links);
1834		mtx_unlock(&lun->lun_lock);
1835		break;
1836	case CTL_ACTION_PASS:
1837	case CTL_ACTION_SKIP:
1838		if (softc->ha_mode == CTL_HA_MODE_XFER) {
1839			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1840			ctl_enqueue_rtr((union ctl_io *)ctsio);
1841			mtx_unlock(&lun->lun_lock);
1842		} else {
1843			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
1844			mtx_unlock(&lun->lun_lock);
1845
1846			/* send msg back to other side */
1847			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1848			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1849			msg_info.hdr.msg_type = CTL_MSG_R2R;
1850			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1851			    sizeof(msg_info.hdr), M_WAITOK);
1852		}
1853		break;
1854	case CTL_ACTION_OVERLAP:
1855		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1856		mtx_unlock(&lun->lun_lock);
1857		retval = 1;
1858
1859		ctl_set_overlapped_cmd(ctsio);
1860		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
1861		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1862		msg_info.hdr.serializing_sc = NULL;
1863		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1864		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1865		    sizeof(msg_info.scsi), M_WAITOK);
1866		break;
1867	case CTL_ACTION_OVERLAP_TAG:
1868		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1869		mtx_unlock(&lun->lun_lock);
1870		retval = 1;
1871		ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
1872		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
1873		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1874		msg_info.hdr.serializing_sc = NULL;
1875		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1876		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1877		    sizeof(msg_info.scsi), M_WAITOK);
1878		break;
1879	case CTL_ACTION_ERROR:
1880	default:
1881		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1882		mtx_unlock(&lun->lun_lock);
1883		retval = 1;
1884
1885		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
1886					 /*retry_count*/ 0);
1887		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
1888		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1889		msg_info.hdr.serializing_sc = NULL;
1890		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1891		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1892		    sizeof(msg_info.scsi), M_WAITOK);
1893		break;
1894	}
1895	return (retval);
1896}
1897
1898/*
1899 * Returns 0 for success, errno for failure.
1900 */
1901static int
1902ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
1903		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
1904{
1905	union ctl_io *io;
1906	int retval;
1907
1908	retval = 0;
1909
1910	mtx_lock(&lun->lun_lock);
1911	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
1912	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
1913	     ooa_links)) {
1914		struct ctl_ooa_entry *entry;
1915
1916		/*
1917		 * If we've got more than we can fit, just count the
1918		 * remaining entries.
1919		 */
1920		if (*cur_fill_num >= ooa_hdr->alloc_num)
1921			continue;
1922
1923		entry = &kern_entries[*cur_fill_num];
1924
1925		entry->tag_num = io->scsiio.tag_num;
1926		entry->lun_num = lun->lun;
1927#ifdef CTL_TIME_IO
1928		entry->start_bt = io->io_hdr.start_bt;
1929#endif
1930		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
1931		entry->cdb_len = io->scsiio.cdb_len;
1932		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
1933			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
1934
1935		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
1936			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
1937
1938		if (io->io_hdr.flags & CTL_FLAG_ABORT)
1939			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
1940
1941		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
1942			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
1943
1944		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
1945			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
1946	}
1947	mtx_unlock(&lun->lun_lock);
1948
1949	return (retval);
1950}
1951
1952static void *
1953ctl_copyin_alloc(void *user_addr, int len, char *error_str,
1954		 size_t error_str_len)
1955{
1956	void *kptr;
1957
1958	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
1959
1960	if (copyin(user_addr, kptr, len) != 0) {
1961		snprintf(error_str, error_str_len, "Error copying %d bytes "
1962			 "from user address %p to kernel address %p", len,
1963			 user_addr, kptr);
1964		free(kptr, M_CTL);
1965		return (NULL);
1966	}
1967
1968	return (kptr);
1969}
1970
1971static void
1972ctl_free_args(int num_args, struct ctl_be_arg *args)
1973{
1974	int i;
1975
1976	if (args == NULL)
1977		return;
1978
1979	for (i = 0; i < num_args; i++) {
1980		free(args[i].kname, M_CTL);
1981		free(args[i].kvalue, M_CTL);
1982	}
1983
1984	free(args, M_CTL);
1985}
1986
1987static struct ctl_be_arg *
1988ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
1989		char *error_str, size_t error_str_len)
1990{
1991	struct ctl_be_arg *args;
1992	int i;
1993
1994	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
1995				error_str, error_str_len);
1996
1997	if (args == NULL)
1998		goto bailout;
1999
2000	for (i = 0; i < num_args; i++) {
2001		args[i].kname = NULL;
2002		args[i].kvalue = NULL;
2003	}
2004
2005	for (i = 0; i < num_args; i++) {
2006		uint8_t *tmpptr;
2007
2008		args[i].kname = ctl_copyin_alloc(args[i].name,
2009			args[i].namelen, error_str, error_str_len);
2010		if (args[i].kname == NULL)
2011			goto bailout;
2012
2013		if (args[i].kname[args[i].namelen - 1] != '\0') {
2014			snprintf(error_str, error_str_len, "Argument %d "
2015				 "name is not NUL-terminated", i);
2016			goto bailout;
2017		}
2018
2019		if (args[i].flags & CTL_BEARG_RD) {
2020			tmpptr = ctl_copyin_alloc(args[i].value,
2021				args[i].vallen, error_str, error_str_len);
2022			if (tmpptr == NULL)
2023				goto bailout;
2024			if ((args[i].flags & CTL_BEARG_ASCII)
2025			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2026				snprintf(error_str, error_str_len, "Argument "
2027				    "%d value is not NUL-terminated", i);
2028				goto bailout;
2029			}
2030			args[i].kvalue = tmpptr;
2031		} else {
2032			args[i].kvalue = malloc(args[i].vallen,
2033			    M_CTL, M_WAITOK | M_ZERO);
2034		}
2035	}
2036
2037	return (args);
2038bailout:
2039
2040	ctl_free_args(num_args, args);
2041
2042	return (NULL);
2043}
2044
2045static void
2046ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2047{
2048	int i;
2049
2050	for (i = 0; i < num_args; i++) {
2051		if (args[i].flags & CTL_BEARG_WR)
2052			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2053	}
2054}
2055
2056/*
2057 * Escape characters that are illegal or not recommended in XML.
2058 */
2059int
2060ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2061{
2062	char *end = str + size;
2063	int retval;
2064
2065	retval = 0;
2066
2067	for (; *str && str < end; str++) {
2068		switch (*str) {
2069		case '&':
2070			retval = sbuf_printf(sb, "&amp;");
2071			break;
2072		case '>':
2073			retval = sbuf_printf(sb, "&gt;");
2074			break;
2075		case '<':
2076			retval = sbuf_printf(sb, "&lt;");
2077			break;
2078		default:
2079			retval = sbuf_putc(sb, *str);
2080			break;
2081		}
2082
2083		if (retval != 0)
2084			break;
2085
2086	}
2087
2088	return (retval);
2089}
2090
2091static void
2092ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2093{
2094	struct scsi_vpd_id_descriptor *desc;
2095	int i;
2096
2097	if (id == NULL || id->len < 4)
2098		return;
2099	desc = (struct scsi_vpd_id_descriptor *)id->data;
2100	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2101	case SVPD_ID_TYPE_T10:
2102		sbuf_printf(sb, "t10.");
2103		break;
2104	case SVPD_ID_TYPE_EUI64:
2105		sbuf_printf(sb, "eui.");
2106		break;
2107	case SVPD_ID_TYPE_NAA:
2108		sbuf_printf(sb, "naa.");
2109		break;
2110	case SVPD_ID_TYPE_SCSI_NAME:
2111		break;
2112	}
2113	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2114	case SVPD_ID_CODESET_BINARY:
2115		for (i = 0; i < desc->length; i++)
2116			sbuf_printf(sb, "%02x", desc->identifier[i]);
2117		break;
2118	case SVPD_ID_CODESET_ASCII:
2119		sbuf_printf(sb, "%.*s", (int)desc->length,
2120		    (char *)desc->identifier);
2121		break;
2122	case SVPD_ID_CODESET_UTF8:
2123		sbuf_printf(sb, "%s", (char *)desc->identifier);
2124		break;
2125	}
2126}
2127
2128static int
2129ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2130	  struct thread *td)
2131{
2132	struct ctl_softc *softc;
2133	struct ctl_lun *lun;
2134	int retval;
2135
2136	softc = control_softc;
2137
2138	retval = 0;
2139
2140	switch (cmd) {
2141	case CTL_IO:
2142		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2143		break;
2144	case CTL_ENABLE_PORT:
2145	case CTL_DISABLE_PORT:
2146	case CTL_SET_PORT_WWNS: {
2147		struct ctl_port *port;
2148		struct ctl_port_entry *entry;
2149
2150		entry = (struct ctl_port_entry *)addr;
2151
2152		mtx_lock(&softc->ctl_lock);
2153		STAILQ_FOREACH(port, &softc->port_list, links) {
2154			int action, done;
2155
2156			if (port->targ_port < softc->port_min ||
2157			    port->targ_port >= softc->port_max)
2158				continue;
2159
2160			action = 0;
2161			done = 0;
2162			if ((entry->port_type == CTL_PORT_NONE)
2163			 && (entry->targ_port == port->targ_port)) {
2164				/*
2165				 * If the user only wants to enable or
2166				 * disable or set WWNs on a specific port,
2167				 * do the operation and we're done.
2168				 */
2169				action = 1;
2170				done = 1;
2171			} else if (entry->port_type & port->port_type) {
2172				/*
2173				 * Compare the user's type mask with the
2174				 * particular frontend type to see if we
2175				 * have a match.
2176				 */
2177				action = 1;
2178				done = 0;
2179
2180				/*
2181				 * Make sure the user isn't trying to set
2182				 * WWNs on multiple ports at the same time.
2183				 */
2184				if (cmd == CTL_SET_PORT_WWNS) {
2185					printf("%s: Can't set WWNs on "
2186					       "multiple ports\n", __func__);
2187					retval = EINVAL;
2188					break;
2189				}
2190			}
2191			if (action == 0)
2192				continue;
2193
2194			/*
2195			 * XXX KDM we have to drop the lock here, because
2196			 * the online/offline operations can potentially
2197			 * block.  We need to reference count the frontends
2198			 * so they can't go away,
2199			 */
2200			if (cmd == CTL_ENABLE_PORT) {
2201				mtx_unlock(&softc->ctl_lock);
2202				ctl_port_online(port);
2203				mtx_lock(&softc->ctl_lock);
2204			} else if (cmd == CTL_DISABLE_PORT) {
2205				mtx_unlock(&softc->ctl_lock);
2206				ctl_port_offline(port);
2207				mtx_lock(&softc->ctl_lock);
2208			} else if (cmd == CTL_SET_PORT_WWNS) {
2209				ctl_port_set_wwns(port,
2210				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2211				    1 : 0, entry->wwnn,
2212				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2213				    1 : 0, entry->wwpn);
2214			}
2215			if (done != 0)
2216				break;
2217		}
2218		mtx_unlock(&softc->ctl_lock);
2219		break;
2220	}
2221	case CTL_GET_PORT_LIST: {
2222		struct ctl_port *port;
2223		struct ctl_port_list *list;
2224		int i;
2225
2226		list = (struct ctl_port_list *)addr;
2227
2228		if (list->alloc_len != (list->alloc_num *
2229		    sizeof(struct ctl_port_entry))) {
2230			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2231			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2232			       "%zu\n", __func__, list->alloc_len,
2233			       list->alloc_num, sizeof(struct ctl_port_entry));
2234			retval = EINVAL;
2235			break;
2236		}
2237		list->fill_len = 0;
2238		list->fill_num = 0;
2239		list->dropped_num = 0;
2240		i = 0;
2241		mtx_lock(&softc->ctl_lock);
2242		STAILQ_FOREACH(port, &softc->port_list, links) {
2243			struct ctl_port_entry entry, *list_entry;
2244
2245			if (list->fill_num >= list->alloc_num) {
2246				list->dropped_num++;
2247				continue;
2248			}
2249
2250			entry.port_type = port->port_type;
2251			strlcpy(entry.port_name, port->port_name,
2252				sizeof(entry.port_name));
2253			entry.targ_port = port->targ_port;
2254			entry.physical_port = port->physical_port;
2255			entry.virtual_port = port->virtual_port;
2256			entry.wwnn = port->wwnn;
2257			entry.wwpn = port->wwpn;
2258			if (port->status & CTL_PORT_STATUS_ONLINE)
2259				entry.online = 1;
2260			else
2261				entry.online = 0;
2262
2263			list_entry = &list->entries[i];
2264
2265			retval = copyout(&entry, list_entry, sizeof(entry));
2266			if (retval != 0) {
2267				printf("%s: CTL_GET_PORT_LIST: copyout "
2268				       "returned %d\n", __func__, retval);
2269				break;
2270			}
2271			i++;
2272			list->fill_num++;
2273			list->fill_len += sizeof(entry);
2274		}
2275		mtx_unlock(&softc->ctl_lock);
2276
2277		/*
2278		 * If this is non-zero, we had a copyout fault, so there's
2279		 * probably no point in attempting to set the status inside
2280		 * the structure.
2281		 */
2282		if (retval != 0)
2283			break;
2284
2285		if (list->dropped_num > 0)
2286			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2287		else
2288			list->status = CTL_PORT_LIST_OK;
2289		break;
2290	}
2291	case CTL_DUMP_OOA: {
2292		union ctl_io *io;
2293		char printbuf[128];
2294		struct sbuf sb;
2295
2296		mtx_lock(&softc->ctl_lock);
2297		printf("Dumping OOA queues:\n");
2298		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2299			mtx_lock(&lun->lun_lock);
2300			for (io = (union ctl_io *)TAILQ_FIRST(
2301			     &lun->ooa_queue); io != NULL;
2302			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2303			     ooa_links)) {
2304				sbuf_new(&sb, printbuf, sizeof(printbuf),
2305					 SBUF_FIXEDLEN);
2306				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2307					    (intmax_t)lun->lun,
2308					    io->scsiio.tag_num,
2309					    (io->io_hdr.flags &
2310					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2311					    (io->io_hdr.flags &
2312					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2313					    (io->io_hdr.flags &
2314					    CTL_FLAG_ABORT) ? " ABORT" : "",
2315			                    (io->io_hdr.flags &
2316		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2317				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2318				sbuf_finish(&sb);
2319				printf("%s\n", sbuf_data(&sb));
2320			}
2321			mtx_unlock(&lun->lun_lock);
2322		}
2323		printf("OOA queues dump done\n");
2324		mtx_unlock(&softc->ctl_lock);
2325		break;
2326	}
2327	case CTL_GET_OOA: {
2328		struct ctl_ooa *ooa_hdr;
2329		struct ctl_ooa_entry *entries;
2330		uint32_t cur_fill_num;
2331
2332		ooa_hdr = (struct ctl_ooa *)addr;
2333
2334		if ((ooa_hdr->alloc_len == 0)
2335		 || (ooa_hdr->alloc_num == 0)) {
2336			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2337			       "must be non-zero\n", __func__,
2338			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2339			retval = EINVAL;
2340			break;
2341		}
2342
2343		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2344		    sizeof(struct ctl_ooa_entry))) {
2345			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2346			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2347			       __func__, ooa_hdr->alloc_len,
2348			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2349			retval = EINVAL;
2350			break;
2351		}
2352
2353		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2354		if (entries == NULL) {
2355			printf("%s: could not allocate %d bytes for OOA "
2356			       "dump\n", __func__, ooa_hdr->alloc_len);
2357			retval = ENOMEM;
2358			break;
2359		}
2360
2361		mtx_lock(&softc->ctl_lock);
2362		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2363		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2364		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2365			mtx_unlock(&softc->ctl_lock);
2366			free(entries, M_CTL);
2367			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2368			       __func__, (uintmax_t)ooa_hdr->lun_num);
2369			retval = EINVAL;
2370			break;
2371		}
2372
2373		cur_fill_num = 0;
2374
2375		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2376			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2377				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2378					ooa_hdr, entries);
2379				if (retval != 0)
2380					break;
2381			}
2382			if (retval != 0) {
2383				mtx_unlock(&softc->ctl_lock);
2384				free(entries, M_CTL);
2385				break;
2386			}
2387		} else {
2388			lun = softc->ctl_luns[ooa_hdr->lun_num];
2389
2390			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2391						    entries);
2392		}
2393		mtx_unlock(&softc->ctl_lock);
2394
2395		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2396		ooa_hdr->fill_len = ooa_hdr->fill_num *
2397			sizeof(struct ctl_ooa_entry);
2398		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2399		if (retval != 0) {
2400			printf("%s: error copying out %d bytes for OOA dump\n",
2401			       __func__, ooa_hdr->fill_len);
2402		}
2403
2404		getbintime(&ooa_hdr->cur_bt);
2405
2406		if (cur_fill_num > ooa_hdr->alloc_num) {
2407			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2408			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2409		} else {
2410			ooa_hdr->dropped_num = 0;
2411			ooa_hdr->status = CTL_OOA_OK;
2412		}
2413
2414		free(entries, M_CTL);
2415		break;
2416	}
2417	case CTL_CHECK_OOA: {
2418		union ctl_io *io;
2419		struct ctl_ooa_info *ooa_info;
2420
2421
2422		ooa_info = (struct ctl_ooa_info *)addr;
2423
2424		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2425			ooa_info->status = CTL_OOA_INVALID_LUN;
2426			break;
2427		}
2428		mtx_lock(&softc->ctl_lock);
2429		lun = softc->ctl_luns[ooa_info->lun_id];
2430		if (lun == NULL) {
2431			mtx_unlock(&softc->ctl_lock);
2432			ooa_info->status = CTL_OOA_INVALID_LUN;
2433			break;
2434		}
2435		mtx_lock(&lun->lun_lock);
2436		mtx_unlock(&softc->ctl_lock);
2437		ooa_info->num_entries = 0;
2438		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2439		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2440		     &io->io_hdr, ooa_links)) {
2441			ooa_info->num_entries++;
2442		}
2443		mtx_unlock(&lun->lun_lock);
2444
2445		ooa_info->status = CTL_OOA_SUCCESS;
2446
2447		break;
2448	}
2449	case CTL_DELAY_IO: {
2450		struct ctl_io_delay_info *delay_info;
2451
2452		delay_info = (struct ctl_io_delay_info *)addr;
2453
2454#ifdef CTL_IO_DELAY
2455		mtx_lock(&softc->ctl_lock);
2456
2457		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2458		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2459			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2460		} else {
2461			lun = softc->ctl_luns[delay_info->lun_id];
2462			mtx_lock(&lun->lun_lock);
2463
2464			delay_info->status = CTL_DELAY_STATUS_OK;
2465
2466			switch (delay_info->delay_type) {
2467			case CTL_DELAY_TYPE_CONT:
2468				break;
2469			case CTL_DELAY_TYPE_ONESHOT:
2470				break;
2471			default:
2472				delay_info->status =
2473					CTL_DELAY_STATUS_INVALID_TYPE;
2474				break;
2475			}
2476
2477			switch (delay_info->delay_loc) {
2478			case CTL_DELAY_LOC_DATAMOVE:
2479				lun->delay_info.datamove_type =
2480					delay_info->delay_type;
2481				lun->delay_info.datamove_delay =
2482					delay_info->delay_secs;
2483				break;
2484			case CTL_DELAY_LOC_DONE:
2485				lun->delay_info.done_type =
2486					delay_info->delay_type;
2487				lun->delay_info.done_delay =
2488					delay_info->delay_secs;
2489				break;
2490			default:
2491				delay_info->status =
2492					CTL_DELAY_STATUS_INVALID_LOC;
2493				break;
2494			}
2495			mtx_unlock(&lun->lun_lock);
2496		}
2497
2498		mtx_unlock(&softc->ctl_lock);
2499#else
2500		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2501#endif /* CTL_IO_DELAY */
2502		break;
2503	}
2504	case CTL_REALSYNC_SET: {
2505		int *syncstate;
2506
2507		syncstate = (int *)addr;
2508
2509		mtx_lock(&softc->ctl_lock);
2510		switch (*syncstate) {
2511		case 0:
2512			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2513			break;
2514		case 1:
2515			softc->flags |= CTL_FLAG_REAL_SYNC;
2516			break;
2517		default:
2518			retval = EINVAL;
2519			break;
2520		}
2521		mtx_unlock(&softc->ctl_lock);
2522		break;
2523	}
2524	case CTL_REALSYNC_GET: {
2525		int *syncstate;
2526
2527		syncstate = (int*)addr;
2528
2529		mtx_lock(&softc->ctl_lock);
2530		if (softc->flags & CTL_FLAG_REAL_SYNC)
2531			*syncstate = 1;
2532		else
2533			*syncstate = 0;
2534		mtx_unlock(&softc->ctl_lock);
2535
2536		break;
2537	}
2538	case CTL_SETSYNC:
2539	case CTL_GETSYNC: {
2540		struct ctl_sync_info *sync_info;
2541
2542		sync_info = (struct ctl_sync_info *)addr;
2543
2544		mtx_lock(&softc->ctl_lock);
2545		lun = softc->ctl_luns[sync_info->lun_id];
2546		if (lun == NULL) {
2547			mtx_unlock(&softc->ctl_lock);
2548			sync_info->status = CTL_GS_SYNC_NO_LUN;
2549			break;
2550		}
2551		/*
2552		 * Get or set the sync interval.  We're not bounds checking
2553		 * in the set case, hopefully the user won't do something
2554		 * silly.
2555		 */
2556		mtx_lock(&lun->lun_lock);
2557		mtx_unlock(&softc->ctl_lock);
2558		if (cmd == CTL_GETSYNC)
2559			sync_info->sync_interval = lun->sync_interval;
2560		else
2561			lun->sync_interval = sync_info->sync_interval;
2562		mtx_unlock(&lun->lun_lock);
2563
2564		sync_info->status = CTL_GS_SYNC_OK;
2565
2566		break;
2567	}
2568	case CTL_GETSTATS: {
2569		struct ctl_stats *stats;
2570		int i;
2571
2572		stats = (struct ctl_stats *)addr;
2573
2574		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2575		     stats->alloc_len) {
2576			stats->status = CTL_SS_NEED_MORE_SPACE;
2577			stats->num_luns = softc->num_luns;
2578			break;
2579		}
2580		/*
2581		 * XXX KDM no locking here.  If the LUN list changes,
2582		 * things can blow up.
2583		 */
2584		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2585		     i++, lun = STAILQ_NEXT(lun, links)) {
2586			retval = copyout(&lun->stats, &stats->lun_stats[i],
2587					 sizeof(lun->stats));
2588			if (retval != 0)
2589				break;
2590		}
2591		stats->num_luns = softc->num_luns;
2592		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2593				 softc->num_luns;
2594		stats->status = CTL_SS_OK;
2595#ifdef CTL_TIME_IO
2596		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2597#else
2598		stats->flags = CTL_STATS_FLAG_NONE;
2599#endif
2600		getnanouptime(&stats->timestamp);
2601		break;
2602	}
2603	case CTL_ERROR_INJECT: {
2604		struct ctl_error_desc *err_desc, *new_err_desc;
2605
2606		err_desc = (struct ctl_error_desc *)addr;
2607
2608		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2609				      M_WAITOK | M_ZERO);
2610		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2611
2612		mtx_lock(&softc->ctl_lock);
2613		lun = softc->ctl_luns[err_desc->lun_id];
2614		if (lun == NULL) {
2615			mtx_unlock(&softc->ctl_lock);
2616			free(new_err_desc, M_CTL);
2617			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2618			       __func__, (uintmax_t)err_desc->lun_id);
2619			retval = EINVAL;
2620			break;
2621		}
2622		mtx_lock(&lun->lun_lock);
2623		mtx_unlock(&softc->ctl_lock);
2624
2625		/*
2626		 * We could do some checking here to verify the validity
2627		 * of the request, but given the complexity of error
2628		 * injection requests, the checking logic would be fairly
2629		 * complex.
2630		 *
2631		 * For now, if the request is invalid, it just won't get
2632		 * executed and might get deleted.
2633		 */
2634		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2635
2636		/*
2637		 * XXX KDM check to make sure the serial number is unique,
2638		 * in case we somehow manage to wrap.  That shouldn't
2639		 * happen for a very long time, but it's the right thing to
2640		 * do.
2641		 */
2642		new_err_desc->serial = lun->error_serial;
2643		err_desc->serial = lun->error_serial;
2644		lun->error_serial++;
2645
2646		mtx_unlock(&lun->lun_lock);
2647		break;
2648	}
2649	case CTL_ERROR_INJECT_DELETE: {
2650		struct ctl_error_desc *delete_desc, *desc, *desc2;
2651		int delete_done;
2652
2653		delete_desc = (struct ctl_error_desc *)addr;
2654		delete_done = 0;
2655
2656		mtx_lock(&softc->ctl_lock);
2657		lun = softc->ctl_luns[delete_desc->lun_id];
2658		if (lun == NULL) {
2659			mtx_unlock(&softc->ctl_lock);
2660			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2661			       __func__, (uintmax_t)delete_desc->lun_id);
2662			retval = EINVAL;
2663			break;
2664		}
2665		mtx_lock(&lun->lun_lock);
2666		mtx_unlock(&softc->ctl_lock);
2667		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2668			if (desc->serial != delete_desc->serial)
2669				continue;
2670
2671			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2672				      links);
2673			free(desc, M_CTL);
2674			delete_done = 1;
2675		}
2676		mtx_unlock(&lun->lun_lock);
2677		if (delete_done == 0) {
2678			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2679			       "error serial %ju on LUN %u\n", __func__,
2680			       delete_desc->serial, delete_desc->lun_id);
2681			retval = EINVAL;
2682			break;
2683		}
2684		break;
2685	}
2686	case CTL_DUMP_STRUCTS: {
2687		int i, j, k;
2688		struct ctl_port *port;
2689		struct ctl_frontend *fe;
2690
2691		mtx_lock(&softc->ctl_lock);
2692		printf("CTL Persistent Reservation information start:\n");
2693		for (i = 0; i < CTL_MAX_LUNS; i++) {
2694			lun = softc->ctl_luns[i];
2695
2696			if ((lun == NULL)
2697			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
2698				continue;
2699
2700			for (j = 0; j < CTL_MAX_PORTS; j++) {
2701				if (lun->pr_keys[j] == NULL)
2702					continue;
2703				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2704					if (lun->pr_keys[j][k] == 0)
2705						continue;
2706					printf("  LUN %d port %d iid %d key "
2707					       "%#jx\n", i, j, k,
2708					       (uintmax_t)lun->pr_keys[j][k]);
2709				}
2710			}
2711		}
2712		printf("CTL Persistent Reservation information end\n");
2713		printf("CTL Ports:\n");
2714		STAILQ_FOREACH(port, &softc->port_list, links) {
2715			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2716			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2717			       port->frontend->name, port->port_type,
2718			       port->physical_port, port->virtual_port,
2719			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2720			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2721				if (port->wwpn_iid[j].in_use == 0 &&
2722				    port->wwpn_iid[j].wwpn == 0 &&
2723				    port->wwpn_iid[j].name == NULL)
2724					continue;
2725
2726				printf("    iid %u use %d WWPN %#jx '%s'\n",
2727				    j, port->wwpn_iid[j].in_use,
2728				    (uintmax_t)port->wwpn_iid[j].wwpn,
2729				    port->wwpn_iid[j].name);
2730			}
2731		}
2732		printf("CTL Port information end\n");
2733		mtx_unlock(&softc->ctl_lock);
2734		/*
2735		 * XXX KDM calling this without a lock.  We'd likely want
2736		 * to drop the lock before calling the frontend's dump
2737		 * routine anyway.
2738		 */
2739		printf("CTL Frontends:\n");
2740		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2741			printf("  Frontend '%s'\n", fe->name);
2742			if (fe->fe_dump != NULL)
2743				fe->fe_dump();
2744		}
2745		printf("CTL Frontend information end\n");
2746		break;
2747	}
2748	case CTL_LUN_REQ: {
2749		struct ctl_lun_req *lun_req;
2750		struct ctl_backend_driver *backend;
2751
2752		lun_req = (struct ctl_lun_req *)addr;
2753
2754		backend = ctl_backend_find(lun_req->backend);
2755		if (backend == NULL) {
2756			lun_req->status = CTL_LUN_ERROR;
2757			snprintf(lun_req->error_str,
2758				 sizeof(lun_req->error_str),
2759				 "Backend \"%s\" not found.",
2760				 lun_req->backend);
2761			break;
2762		}
2763		if (lun_req->num_be_args > 0) {
2764			lun_req->kern_be_args = ctl_copyin_args(
2765				lun_req->num_be_args,
2766				lun_req->be_args,
2767				lun_req->error_str,
2768				sizeof(lun_req->error_str));
2769			if (lun_req->kern_be_args == NULL) {
2770				lun_req->status = CTL_LUN_ERROR;
2771				break;
2772			}
2773		}
2774
2775		retval = backend->ioctl(dev, cmd, addr, flag, td);
2776
2777		if (lun_req->num_be_args > 0) {
2778			ctl_copyout_args(lun_req->num_be_args,
2779				      lun_req->kern_be_args);
2780			ctl_free_args(lun_req->num_be_args,
2781				      lun_req->kern_be_args);
2782		}
2783		break;
2784	}
2785	case CTL_LUN_LIST: {
2786		struct sbuf *sb;
2787		struct ctl_lun_list *list;
2788		struct ctl_option *opt;
2789
2790		list = (struct ctl_lun_list *)addr;
2791
2792		/*
2793		 * Allocate a fixed length sbuf here, based on the length
2794		 * of the user's buffer.  We could allocate an auto-extending
2795		 * buffer, and then tell the user how much larger our
2796		 * amount of data is than his buffer, but that presents
2797		 * some problems:
2798		 *
2799		 * 1.  The sbuf(9) routines use a blocking malloc, and so
2800		 *     we can't hold a lock while calling them with an
2801		 *     auto-extending buffer.
2802 		 *
2803		 * 2.  There is not currently a LUN reference counting
2804		 *     mechanism, outside of outstanding transactions on
2805		 *     the LUN's OOA queue.  So a LUN could go away on us
2806		 *     while we're getting the LUN number, backend-specific
2807		 *     information, etc.  Thus, given the way things
2808		 *     currently work, we need to hold the CTL lock while
2809		 *     grabbing LUN information.
2810		 *
2811		 * So, from the user's standpoint, the best thing to do is
2812		 * allocate what he thinks is a reasonable buffer length,
2813		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
2814		 * double the buffer length and try again.  (And repeat
2815		 * that until he succeeds.)
2816		 */
2817		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
2818		if (sb == NULL) {
2819			list->status = CTL_LUN_LIST_ERROR;
2820			snprintf(list->error_str, sizeof(list->error_str),
2821				 "Unable to allocate %d bytes for LUN list",
2822				 list->alloc_len);
2823			break;
2824		}
2825
2826		sbuf_printf(sb, "<ctllunlist>\n");
2827
2828		mtx_lock(&softc->ctl_lock);
2829		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2830			mtx_lock(&lun->lun_lock);
2831			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
2832					     (uintmax_t)lun->lun);
2833
2834			/*
2835			 * Bail out as soon as we see that we've overfilled
2836			 * the buffer.
2837			 */
2838			if (retval != 0)
2839				break;
2840
2841			retval = sbuf_printf(sb, "\t<backend_type>%s"
2842					     "</backend_type>\n",
2843					     (lun->backend == NULL) ?  "none" :
2844					     lun->backend->name);
2845
2846			if (retval != 0)
2847				break;
2848
2849			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
2850					     lun->be_lun->lun_type);
2851
2852			if (retval != 0)
2853				break;
2854
2855			if (lun->backend == NULL) {
2856				retval = sbuf_printf(sb, "</lun>\n");
2857				if (retval != 0)
2858					break;
2859				continue;
2860			}
2861
2862			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
2863					     (lun->be_lun->maxlba > 0) ?
2864					     lun->be_lun->maxlba + 1 : 0);
2865
2866			if (retval != 0)
2867				break;
2868
2869			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
2870					     lun->be_lun->blocksize);
2871
2872			if (retval != 0)
2873				break;
2874
2875			retval = sbuf_printf(sb, "\t<serial_number>");
2876
2877			if (retval != 0)
2878				break;
2879
2880			retval = ctl_sbuf_printf_esc(sb,
2881			    lun->be_lun->serial_num,
2882			    sizeof(lun->be_lun->serial_num));
2883
2884			if (retval != 0)
2885				break;
2886
2887			retval = sbuf_printf(sb, "</serial_number>\n");
2888
2889			if (retval != 0)
2890				break;
2891
2892			retval = sbuf_printf(sb, "\t<device_id>");
2893
2894			if (retval != 0)
2895				break;
2896
2897			retval = ctl_sbuf_printf_esc(sb,
2898			    lun->be_lun->device_id,
2899			    sizeof(lun->be_lun->device_id));
2900
2901			if (retval != 0)
2902				break;
2903
2904			retval = sbuf_printf(sb, "</device_id>\n");
2905
2906			if (retval != 0)
2907				break;
2908
2909			if (lun->backend->lun_info != NULL) {
2910				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
2911				if (retval != 0)
2912					break;
2913			}
2914			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
2915				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
2916				    opt->name, opt->value, opt->name);
2917				if (retval != 0)
2918					break;
2919			}
2920
2921			retval = sbuf_printf(sb, "</lun>\n");
2922
2923			if (retval != 0)
2924				break;
2925			mtx_unlock(&lun->lun_lock);
2926		}
2927		if (lun != NULL)
2928			mtx_unlock(&lun->lun_lock);
2929		mtx_unlock(&softc->ctl_lock);
2930
2931		if ((retval != 0)
2932		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
2933			retval = 0;
2934			sbuf_delete(sb);
2935			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
2936			snprintf(list->error_str, sizeof(list->error_str),
2937				 "Out of space, %d bytes is too small",
2938				 list->alloc_len);
2939			break;
2940		}
2941
2942		sbuf_finish(sb);
2943
2944		retval = copyout(sbuf_data(sb), list->lun_xml,
2945				 sbuf_len(sb) + 1);
2946
2947		list->fill_len = sbuf_len(sb) + 1;
2948		list->status = CTL_LUN_LIST_OK;
2949		sbuf_delete(sb);
2950		break;
2951	}
2952	case CTL_ISCSI: {
2953		struct ctl_iscsi *ci;
2954		struct ctl_frontend *fe;
2955
2956		ci = (struct ctl_iscsi *)addr;
2957
2958		fe = ctl_frontend_find("iscsi");
2959		if (fe == NULL) {
2960			ci->status = CTL_ISCSI_ERROR;
2961			snprintf(ci->error_str, sizeof(ci->error_str),
2962			    "Frontend \"iscsi\" not found.");
2963			break;
2964		}
2965
2966		retval = fe->ioctl(dev, cmd, addr, flag, td);
2967		break;
2968	}
2969	case CTL_PORT_REQ: {
2970		struct ctl_req *req;
2971		struct ctl_frontend *fe;
2972
2973		req = (struct ctl_req *)addr;
2974
2975		fe = ctl_frontend_find(req->driver);
2976		if (fe == NULL) {
2977			req->status = CTL_LUN_ERROR;
2978			snprintf(req->error_str, sizeof(req->error_str),
2979			    "Frontend \"%s\" not found.", req->driver);
2980			break;
2981		}
2982		if (req->num_args > 0) {
2983			req->kern_args = ctl_copyin_args(req->num_args,
2984			    req->args, req->error_str, sizeof(req->error_str));
2985			if (req->kern_args == NULL) {
2986				req->status = CTL_LUN_ERROR;
2987				break;
2988			}
2989		}
2990
2991		if (fe->ioctl)
2992			retval = fe->ioctl(dev, cmd, addr, flag, td);
2993		else
2994			retval = ENODEV;
2995
2996		if (req->num_args > 0) {
2997			ctl_copyout_args(req->num_args, req->kern_args);
2998			ctl_free_args(req->num_args, req->kern_args);
2999		}
3000		break;
3001	}
3002	case CTL_PORT_LIST: {
3003		struct sbuf *sb;
3004		struct ctl_port *port;
3005		struct ctl_lun_list *list;
3006		struct ctl_option *opt;
3007		int j;
3008		uint32_t plun;
3009
3010		list = (struct ctl_lun_list *)addr;
3011
3012		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3013		if (sb == NULL) {
3014			list->status = CTL_LUN_LIST_ERROR;
3015			snprintf(list->error_str, sizeof(list->error_str),
3016				 "Unable to allocate %d bytes for LUN list",
3017				 list->alloc_len);
3018			break;
3019		}
3020
3021		sbuf_printf(sb, "<ctlportlist>\n");
3022
3023		mtx_lock(&softc->ctl_lock);
3024		STAILQ_FOREACH(port, &softc->port_list, links) {
3025			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3026					     (uintmax_t)port->targ_port);
3027
3028			/*
3029			 * Bail out as soon as we see that we've overfilled
3030			 * the buffer.
3031			 */
3032			if (retval != 0)
3033				break;
3034
3035			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3036			    "</frontend_type>\n", port->frontend->name);
3037			if (retval != 0)
3038				break;
3039
3040			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3041					     port->port_type);
3042			if (retval != 0)
3043				break;
3044
3045			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3046			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3047			if (retval != 0)
3048				break;
3049
3050			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3051			    port->port_name);
3052			if (retval != 0)
3053				break;
3054
3055			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3056			    port->physical_port);
3057			if (retval != 0)
3058				break;
3059
3060			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3061			    port->virtual_port);
3062			if (retval != 0)
3063				break;
3064
3065			if (port->target_devid != NULL) {
3066				sbuf_printf(sb, "\t<target>");
3067				ctl_id_sbuf(port->target_devid, sb);
3068				sbuf_printf(sb, "</target>\n");
3069			}
3070
3071			if (port->port_devid != NULL) {
3072				sbuf_printf(sb, "\t<port>");
3073				ctl_id_sbuf(port->port_devid, sb);
3074				sbuf_printf(sb, "</port>\n");
3075			}
3076
3077			if (port->port_info != NULL) {
3078				retval = port->port_info(port->onoff_arg, sb);
3079				if (retval != 0)
3080					break;
3081			}
3082			STAILQ_FOREACH(opt, &port->options, links) {
3083				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3084				    opt->name, opt->value, opt->name);
3085				if (retval != 0)
3086					break;
3087			}
3088
3089			if (port->lun_map != NULL) {
3090				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3091				for (j = 0; j < CTL_MAX_LUNS; j++) {
3092					plun = ctl_lun_map_from_port(port, j);
3093					if (plun >= CTL_MAX_LUNS)
3094						continue;
3095					sbuf_printf(sb,
3096					    "\t<lun id=\"%u\">%u</lun>\n",
3097					    j, plun);
3098				}
3099			}
3100
3101			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3102				if (port->wwpn_iid[j].in_use == 0 ||
3103				    (port->wwpn_iid[j].wwpn == 0 &&
3104				     port->wwpn_iid[j].name == NULL))
3105					continue;
3106
3107				if (port->wwpn_iid[j].name != NULL)
3108					retval = sbuf_printf(sb,
3109					    "\t<initiator id=\"%u\">%s</initiator>\n",
3110					    j, port->wwpn_iid[j].name);
3111				else
3112					retval = sbuf_printf(sb,
3113					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3114					    j, port->wwpn_iid[j].wwpn);
3115				if (retval != 0)
3116					break;
3117			}
3118			if (retval != 0)
3119				break;
3120
3121			retval = sbuf_printf(sb, "</targ_port>\n");
3122			if (retval != 0)
3123				break;
3124		}
3125		mtx_unlock(&softc->ctl_lock);
3126
3127		if ((retval != 0)
3128		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3129			retval = 0;
3130			sbuf_delete(sb);
3131			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3132			snprintf(list->error_str, sizeof(list->error_str),
3133				 "Out of space, %d bytes is too small",
3134				 list->alloc_len);
3135			break;
3136		}
3137
3138		sbuf_finish(sb);
3139
3140		retval = copyout(sbuf_data(sb), list->lun_xml,
3141				 sbuf_len(sb) + 1);
3142
3143		list->fill_len = sbuf_len(sb) + 1;
3144		list->status = CTL_LUN_LIST_OK;
3145		sbuf_delete(sb);
3146		break;
3147	}
3148	case CTL_LUN_MAP: {
3149		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3150		struct ctl_port *port;
3151
3152		mtx_lock(&softc->ctl_lock);
3153		if (lm->port < softc->port_min ||
3154		    lm->port >= softc->port_max ||
3155		    (port = softc->ctl_ports[lm->port]) == NULL) {
3156			mtx_unlock(&softc->ctl_lock);
3157			return (ENXIO);
3158		}
3159		if (port->status & CTL_PORT_STATUS_ONLINE) {
3160			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3161				if (ctl_lun_map_to_port(port, lun->lun) >=
3162				    CTL_MAX_LUNS)
3163					continue;
3164				mtx_lock(&lun->lun_lock);
3165				ctl_est_ua_port(lun, lm->port, -1,
3166				    CTL_UA_LUN_CHANGE);
3167				mtx_unlock(&lun->lun_lock);
3168			}
3169		}
3170		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3171		if (lm->plun < CTL_MAX_LUNS) {
3172			if (lm->lun == UINT32_MAX)
3173				retval = ctl_lun_map_unset(port, lm->plun);
3174			else if (lm->lun < CTL_MAX_LUNS &&
3175			    softc->ctl_luns[lm->lun] != NULL)
3176				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3177			else
3178				return (ENXIO);
3179		} else if (lm->plun == UINT32_MAX) {
3180			if (lm->lun == UINT32_MAX)
3181				retval = ctl_lun_map_deinit(port);
3182			else
3183				retval = ctl_lun_map_init(port);
3184		} else
3185			return (ENXIO);
3186		if (port->status & CTL_PORT_STATUS_ONLINE)
3187			ctl_isc_announce_port(port);
3188		break;
3189	}
3190	default: {
3191		/* XXX KDM should we fix this? */
3192#if 0
3193		struct ctl_backend_driver *backend;
3194		unsigned int type;
3195		int found;
3196
3197		found = 0;
3198
3199		/*
3200		 * We encode the backend type as the ioctl type for backend
3201		 * ioctls.  So parse it out here, and then search for a
3202		 * backend of this type.
3203		 */
3204		type = _IOC_TYPE(cmd);
3205
3206		STAILQ_FOREACH(backend, &softc->be_list, links) {
3207			if (backend->type == type) {
3208				found = 1;
3209				break;
3210			}
3211		}
3212		if (found == 0) {
3213			printf("ctl: unknown ioctl command %#lx or backend "
3214			       "%d\n", cmd, type);
3215			retval = EINVAL;
3216			break;
3217		}
3218		retval = backend->ioctl(dev, cmd, addr, flag, td);
3219#endif
3220		retval = ENOTTY;
3221		break;
3222	}
3223	}
3224	return (retval);
3225}
3226
3227uint32_t
3228ctl_get_initindex(struct ctl_nexus *nexus)
3229{
3230	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3231}
3232
3233int
3234ctl_lun_map_init(struct ctl_port *port)
3235{
3236	struct ctl_softc *softc = control_softc;
3237	struct ctl_lun *lun;
3238	uint32_t i;
3239
3240	if (port->lun_map == NULL)
3241		port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3242		    M_CTL, M_NOWAIT);
3243	if (port->lun_map == NULL)
3244		return (ENOMEM);
3245	for (i = 0; i < CTL_MAX_LUNS; i++)
3246		port->lun_map[i] = UINT32_MAX;
3247	if (port->status & CTL_PORT_STATUS_ONLINE) {
3248		if (port->lun_disable != NULL) {
3249			STAILQ_FOREACH(lun, &softc->lun_list, links)
3250				port->lun_disable(port->targ_lun_arg, lun->lun);
3251		}
3252		ctl_isc_announce_port(port);
3253	}
3254	return (0);
3255}
3256
3257int
3258ctl_lun_map_deinit(struct ctl_port *port)
3259{
3260	struct ctl_softc *softc = control_softc;
3261	struct ctl_lun *lun;
3262
3263	if (port->lun_map == NULL)
3264		return (0);
3265	free(port->lun_map, M_CTL);
3266	port->lun_map = NULL;
3267	if (port->status & CTL_PORT_STATUS_ONLINE) {
3268		if (port->lun_enable != NULL) {
3269			STAILQ_FOREACH(lun, &softc->lun_list, links)
3270				port->lun_enable(port->targ_lun_arg, lun->lun);
3271		}
3272		ctl_isc_announce_port(port);
3273	}
3274	return (0);
3275}
3276
3277int
3278ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3279{
3280	int status;
3281	uint32_t old;
3282
3283	if (port->lun_map == NULL) {
3284		status = ctl_lun_map_init(port);
3285		if (status != 0)
3286			return (status);
3287	}
3288	old = port->lun_map[plun];
3289	port->lun_map[plun] = glun;
3290	if ((port->status & CTL_PORT_STATUS_ONLINE) && old >= CTL_MAX_LUNS) {
3291		if (port->lun_enable != NULL)
3292			port->lun_enable(port->targ_lun_arg, plun);
3293		ctl_isc_announce_port(port);
3294	}
3295	return (0);
3296}
3297
3298int
3299ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3300{
3301	uint32_t old;
3302
3303	if (port->lun_map == NULL)
3304		return (0);
3305	old = port->lun_map[plun];
3306	port->lun_map[plun] = UINT32_MAX;
3307	if ((port->status & CTL_PORT_STATUS_ONLINE) && old < CTL_MAX_LUNS) {
3308		if (port->lun_disable != NULL)
3309			port->lun_disable(port->targ_lun_arg, plun);
3310		ctl_isc_announce_port(port);
3311	}
3312	return (0);
3313}
3314
3315uint32_t
3316ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3317{
3318
3319	if (port == NULL)
3320		return (UINT32_MAX);
3321	if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3322		return (lun_id);
3323	return (port->lun_map[lun_id]);
3324}
3325
3326uint32_t
3327ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3328{
3329	uint32_t i;
3330
3331	if (port == NULL)
3332		return (UINT32_MAX);
3333	if (port->lun_map == NULL)
3334		return (lun_id);
3335	for (i = 0; i < CTL_MAX_LUNS; i++) {
3336		if (port->lun_map[i] == lun_id)
3337			return (i);
3338	}
3339	return (UINT32_MAX);
3340}
3341
3342static struct ctl_port *
3343ctl_io_port(struct ctl_io_hdr *io_hdr)
3344{
3345
3346	return (control_softc->ctl_ports[io_hdr->nexus.targ_port]);
3347}
3348
3349int
3350ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3351{
3352	int i;
3353
3354	for (i = first; i < last; i++) {
3355		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3356			return (i);
3357	}
3358	return (-1);
3359}
3360
3361int
3362ctl_set_mask(uint32_t *mask, uint32_t bit)
3363{
3364	uint32_t chunk, piece;
3365
3366	chunk = bit >> 5;
3367	piece = bit % (sizeof(uint32_t) * 8);
3368
3369	if ((mask[chunk] & (1 << piece)) != 0)
3370		return (-1);
3371	else
3372		mask[chunk] |= (1 << piece);
3373
3374	return (0);
3375}
3376
3377int
3378ctl_clear_mask(uint32_t *mask, uint32_t bit)
3379{
3380	uint32_t chunk, piece;
3381
3382	chunk = bit >> 5;
3383	piece = bit % (sizeof(uint32_t) * 8);
3384
3385	if ((mask[chunk] & (1 << piece)) == 0)
3386		return (-1);
3387	else
3388		mask[chunk] &= ~(1 << piece);
3389
3390	return (0);
3391}
3392
3393int
3394ctl_is_set(uint32_t *mask, uint32_t bit)
3395{
3396	uint32_t chunk, piece;
3397
3398	chunk = bit >> 5;
3399	piece = bit % (sizeof(uint32_t) * 8);
3400
3401	if ((mask[chunk] & (1 << piece)) == 0)
3402		return (0);
3403	else
3404		return (1);
3405}
3406
3407static uint64_t
3408ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3409{
3410	uint64_t *t;
3411
3412	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3413	if (t == NULL)
3414		return (0);
3415	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3416}
3417
3418static void
3419ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3420{
3421	uint64_t *t;
3422
3423	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3424	if (t == NULL)
3425		return;
3426	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3427}
3428
3429static void
3430ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3431{
3432	uint64_t *p;
3433	u_int i;
3434
3435	i = residx/CTL_MAX_INIT_PER_PORT;
3436	if (lun->pr_keys[i] != NULL)
3437		return;
3438	mtx_unlock(&lun->lun_lock);
3439	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3440	    M_WAITOK | M_ZERO);
3441	mtx_lock(&lun->lun_lock);
3442	if (lun->pr_keys[i] == NULL)
3443		lun->pr_keys[i] = p;
3444	else
3445		free(p, M_CTL);
3446}
3447
3448static void
3449ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3450{
3451	uint64_t *t;
3452
3453	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3454	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3455	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3456}
3457
3458/*
3459 * ctl_softc, pool_name, total_ctl_io are passed in.
3460 * npool is passed out.
3461 */
3462int
3463ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3464		uint32_t total_ctl_io, void **npool)
3465{
3466#ifdef IO_POOLS
3467	struct ctl_io_pool *pool;
3468
3469	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3470					    M_NOWAIT | M_ZERO);
3471	if (pool == NULL)
3472		return (ENOMEM);
3473
3474	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3475	pool->ctl_softc = ctl_softc;
3476	pool->zone = uma_zsecond_create(pool->name, NULL,
3477	    NULL, NULL, NULL, ctl_softc->io_zone);
3478	/* uma_prealloc(pool->zone, total_ctl_io); */
3479
3480	*npool = pool;
3481#else
3482	*npool = ctl_softc->io_zone;
3483#endif
3484	return (0);
3485}
3486
3487void
3488ctl_pool_free(struct ctl_io_pool *pool)
3489{
3490
3491	if (pool == NULL)
3492		return;
3493
3494#ifdef IO_POOLS
3495	uma_zdestroy(pool->zone);
3496	free(pool, M_CTL);
3497#endif
3498}
3499
3500union ctl_io *
3501ctl_alloc_io(void *pool_ref)
3502{
3503	union ctl_io *io;
3504#ifdef IO_POOLS
3505	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3506
3507	io = uma_zalloc(pool->zone, M_WAITOK);
3508#else
3509	io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3510#endif
3511	if (io != NULL)
3512		io->io_hdr.pool = pool_ref;
3513	return (io);
3514}
3515
3516union ctl_io *
3517ctl_alloc_io_nowait(void *pool_ref)
3518{
3519	union ctl_io *io;
3520#ifdef IO_POOLS
3521	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3522
3523	io = uma_zalloc(pool->zone, M_NOWAIT);
3524#else
3525	io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3526#endif
3527	if (io != NULL)
3528		io->io_hdr.pool = pool_ref;
3529	return (io);
3530}
3531
3532void
3533ctl_free_io(union ctl_io *io)
3534{
3535#ifdef IO_POOLS
3536	struct ctl_io_pool *pool;
3537#endif
3538
3539	if (io == NULL)
3540		return;
3541
3542#ifdef IO_POOLS
3543	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3544	uma_zfree(pool->zone, io);
3545#else
3546	uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3547#endif
3548}
3549
3550void
3551ctl_zero_io(union ctl_io *io)
3552{
3553	void *pool_ref;
3554
3555	if (io == NULL)
3556		return;
3557
3558	/*
3559	 * May need to preserve linked list pointers at some point too.
3560	 */
3561	pool_ref = io->io_hdr.pool;
3562	memset(io, 0, sizeof(*io));
3563	io->io_hdr.pool = pool_ref;
3564}
3565
3566/*
3567 * This routine is currently used for internal copies of ctl_ios that need
3568 * to persist for some reason after we've already returned status to the
3569 * FETD.  (Thus the flag set.)
3570 *
3571 * XXX XXX
3572 * Note that this makes a blind copy of all fields in the ctl_io, except
3573 * for the pool reference.  This includes any memory that has been
3574 * allocated!  That memory will no longer be valid after done has been
3575 * called, so this would be VERY DANGEROUS for command that actually does
3576 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3577 * start and stop commands, which don't transfer any data, so this is not a
3578 * problem.  If it is used for anything else, the caller would also need to
3579 * allocate data buffer space and this routine would need to be modified to
3580 * copy the data buffer(s) as well.
3581 */
3582void
3583ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3584{
3585	void *pool_ref;
3586
3587	if ((src == NULL)
3588	 || (dest == NULL))
3589		return;
3590
3591	/*
3592	 * May need to preserve linked list pointers at some point too.
3593	 */
3594	pool_ref = dest->io_hdr.pool;
3595
3596	memcpy(dest, src, MIN(sizeof(*src), sizeof(*dest)));
3597
3598	dest->io_hdr.pool = pool_ref;
3599	/*
3600	 * We need to know that this is an internal copy, and doesn't need
3601	 * to get passed back to the FETD that allocated it.
3602	 */
3603	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3604}
3605
3606int
3607ctl_expand_number(const char *buf, uint64_t *num)
3608{
3609	char *endptr;
3610	uint64_t number;
3611	unsigned shift;
3612
3613	number = strtoq(buf, &endptr, 0);
3614
3615	switch (tolower((unsigned char)*endptr)) {
3616	case 'e':
3617		shift = 60;
3618		break;
3619	case 'p':
3620		shift = 50;
3621		break;
3622	case 't':
3623		shift = 40;
3624		break;
3625	case 'g':
3626		shift = 30;
3627		break;
3628	case 'm':
3629		shift = 20;
3630		break;
3631	case 'k':
3632		shift = 10;
3633		break;
3634	case 'b':
3635	case '\0': /* No unit. */
3636		*num = number;
3637		return (0);
3638	default:
3639		/* Unrecognized unit. */
3640		return (-1);
3641	}
3642
3643	if ((number << shift) >> shift != number) {
3644		/* Overflow */
3645		return (-1);
3646	}
3647	*num = number << shift;
3648	return (0);
3649}
3650
3651
3652/*
3653 * This routine could be used in the future to load default and/or saved
3654 * mode page parameters for a particuar lun.
3655 */
3656static int
3657ctl_init_page_index(struct ctl_lun *lun)
3658{
3659	int i;
3660	struct ctl_page_index *page_index;
3661	const char *value;
3662	uint64_t ival;
3663
3664	memcpy(&lun->mode_pages.index, page_index_template,
3665	       sizeof(page_index_template));
3666
3667	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3668
3669		page_index = &lun->mode_pages.index[i];
3670		/*
3671		 * If this is a disk-only mode page, there's no point in
3672		 * setting it up.  For some pages, we have to have some
3673		 * basic information about the disk in order to calculate the
3674		 * mode page data.
3675		 */
3676		if ((lun->be_lun->lun_type != T_DIRECT)
3677		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3678			continue;
3679
3680		switch (page_index->page_code & SMPH_PC_MASK) {
3681		case SMS_RW_ERROR_RECOVERY_PAGE: {
3682			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3683				panic("subpage is incorrect!");
3684			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3685			       &rw_er_page_default,
3686			       sizeof(rw_er_page_default));
3687			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3688			       &rw_er_page_changeable,
3689			       sizeof(rw_er_page_changeable));
3690			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3691			       &rw_er_page_default,
3692			       sizeof(rw_er_page_default));
3693			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3694			       &rw_er_page_default,
3695			       sizeof(rw_er_page_default));
3696			page_index->page_data =
3697				(uint8_t *)lun->mode_pages.rw_er_page;
3698			break;
3699		}
3700		case SMS_FORMAT_DEVICE_PAGE: {
3701			struct scsi_format_page *format_page;
3702
3703			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3704				panic("subpage is incorrect!");
3705
3706			/*
3707			 * Sectors per track are set above.  Bytes per
3708			 * sector need to be set here on a per-LUN basis.
3709			 */
3710			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3711			       &format_page_default,
3712			       sizeof(format_page_default));
3713			memcpy(&lun->mode_pages.format_page[
3714			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
3715			       sizeof(format_page_changeable));
3716			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3717			       &format_page_default,
3718			       sizeof(format_page_default));
3719			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3720			       &format_page_default,
3721			       sizeof(format_page_default));
3722
3723			format_page = &lun->mode_pages.format_page[
3724				CTL_PAGE_CURRENT];
3725			scsi_ulto2b(lun->be_lun->blocksize,
3726				    format_page->bytes_per_sector);
3727
3728			format_page = &lun->mode_pages.format_page[
3729				CTL_PAGE_DEFAULT];
3730			scsi_ulto2b(lun->be_lun->blocksize,
3731				    format_page->bytes_per_sector);
3732
3733			format_page = &lun->mode_pages.format_page[
3734				CTL_PAGE_SAVED];
3735			scsi_ulto2b(lun->be_lun->blocksize,
3736				    format_page->bytes_per_sector);
3737
3738			page_index->page_data =
3739				(uint8_t *)lun->mode_pages.format_page;
3740			break;
3741		}
3742		case SMS_RIGID_DISK_PAGE: {
3743			struct scsi_rigid_disk_page *rigid_disk_page;
3744			uint32_t sectors_per_cylinder;
3745			uint64_t cylinders;
3746#ifndef	__XSCALE__
3747			int shift;
3748#endif /* !__XSCALE__ */
3749
3750			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3751				panic("invalid subpage value %d",
3752				      page_index->subpage);
3753
3754			/*
3755			 * Rotation rate and sectors per track are set
3756			 * above.  We calculate the cylinders here based on
3757			 * capacity.  Due to the number of heads and
3758			 * sectors per track we're using, smaller arrays
3759			 * may turn out to have 0 cylinders.  Linux and
3760			 * FreeBSD don't pay attention to these mode pages
3761			 * to figure out capacity, but Solaris does.  It
3762			 * seems to deal with 0 cylinders just fine, and
3763			 * works out a fake geometry based on the capacity.
3764			 */
3765			memcpy(&lun->mode_pages.rigid_disk_page[
3766			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
3767			       sizeof(rigid_disk_page_default));
3768			memcpy(&lun->mode_pages.rigid_disk_page[
3769			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
3770			       sizeof(rigid_disk_page_changeable));
3771
3772			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
3773				CTL_DEFAULT_HEADS;
3774
3775			/*
3776			 * The divide method here will be more accurate,
3777			 * probably, but results in floating point being
3778			 * used in the kernel on i386 (__udivdi3()).  On the
3779			 * XScale, though, __udivdi3() is implemented in
3780			 * software.
3781			 *
3782			 * The shift method for cylinder calculation is
3783			 * accurate if sectors_per_cylinder is a power of
3784			 * 2.  Otherwise it might be slightly off -- you
3785			 * might have a bit of a truncation problem.
3786			 */
3787#ifdef	__XSCALE__
3788			cylinders = (lun->be_lun->maxlba + 1) /
3789				sectors_per_cylinder;
3790#else
3791			for (shift = 31; shift > 0; shift--) {
3792				if (sectors_per_cylinder & (1 << shift))
3793					break;
3794			}
3795			cylinders = (lun->be_lun->maxlba + 1) >> shift;
3796#endif
3797
3798			/*
3799			 * We've basically got 3 bytes, or 24 bits for the
3800			 * cylinder size in the mode page.  If we're over,
3801			 * just round down to 2^24.
3802			 */
3803			if (cylinders > 0xffffff)
3804				cylinders = 0xffffff;
3805
3806			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
3807				CTL_PAGE_DEFAULT];
3808			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
3809
3810			if ((value = ctl_get_opt(&lun->be_lun->options,
3811			    "rpm")) != NULL) {
3812				scsi_ulto2b(strtol(value, NULL, 0),
3813				     rigid_disk_page->rotation_rate);
3814			}
3815
3816			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
3817			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
3818			       sizeof(rigid_disk_page_default));
3819			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
3820			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
3821			       sizeof(rigid_disk_page_default));
3822
3823			page_index->page_data =
3824				(uint8_t *)lun->mode_pages.rigid_disk_page;
3825			break;
3826		}
3827		case SMS_CACHING_PAGE: {
3828			struct scsi_caching_page *caching_page;
3829
3830			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3831				panic("invalid subpage value %d",
3832				      page_index->subpage);
3833			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
3834			       &caching_page_default,
3835			       sizeof(caching_page_default));
3836			memcpy(&lun->mode_pages.caching_page[
3837			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
3838			       sizeof(caching_page_changeable));
3839			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
3840			       &caching_page_default,
3841			       sizeof(caching_page_default));
3842			caching_page = &lun->mode_pages.caching_page[
3843			    CTL_PAGE_SAVED];
3844			value = ctl_get_opt(&lun->be_lun->options, "writecache");
3845			if (value != NULL && strcmp(value, "off") == 0)
3846				caching_page->flags1 &= ~SCP_WCE;
3847			value = ctl_get_opt(&lun->be_lun->options, "readcache");
3848			if (value != NULL && strcmp(value, "off") == 0)
3849				caching_page->flags1 |= SCP_RCD;
3850			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
3851			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
3852			       sizeof(caching_page_default));
3853			page_index->page_data =
3854				(uint8_t *)lun->mode_pages.caching_page;
3855			break;
3856		}
3857		case SMS_CONTROL_MODE_PAGE: {
3858			struct scsi_control_page *control_page;
3859
3860			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3861				panic("invalid subpage value %d",
3862				      page_index->subpage);
3863
3864			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
3865			       &control_page_default,
3866			       sizeof(control_page_default));
3867			memcpy(&lun->mode_pages.control_page[
3868			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
3869			       sizeof(control_page_changeable));
3870			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
3871			       &control_page_default,
3872			       sizeof(control_page_default));
3873			control_page = &lun->mode_pages.control_page[
3874			    CTL_PAGE_SAVED];
3875			value = ctl_get_opt(&lun->be_lun->options, "reordering");
3876			if (value != NULL && strcmp(value, "unrestricted") == 0) {
3877				control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
3878				control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
3879			}
3880			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
3881			       &lun->mode_pages.control_page[CTL_PAGE_SAVED],
3882			       sizeof(control_page_default));
3883			page_index->page_data =
3884				(uint8_t *)lun->mode_pages.control_page;
3885			break;
3886
3887		}
3888		case SMS_INFO_EXCEPTIONS_PAGE: {
3889			switch (page_index->subpage) {
3890			case SMS_SUBPAGE_PAGE_0:
3891				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
3892				       &ie_page_default,
3893				       sizeof(ie_page_default));
3894				memcpy(&lun->mode_pages.ie_page[
3895				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
3896				       sizeof(ie_page_changeable));
3897				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
3898				       &ie_page_default,
3899				       sizeof(ie_page_default));
3900				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
3901				       &ie_page_default,
3902				       sizeof(ie_page_default));
3903				page_index->page_data =
3904					(uint8_t *)lun->mode_pages.ie_page;
3905				break;
3906			case 0x02: {
3907				struct ctl_logical_block_provisioning_page *page;
3908
3909				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
3910				       &lbp_page_default,
3911				       sizeof(lbp_page_default));
3912				memcpy(&lun->mode_pages.lbp_page[
3913				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
3914				       sizeof(lbp_page_changeable));
3915				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
3916				       &lbp_page_default,
3917				       sizeof(lbp_page_default));
3918				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
3919				value = ctl_get_opt(&lun->be_lun->options,
3920				    "avail-threshold");
3921				if (value != NULL &&
3922				    ctl_expand_number(value, &ival) == 0) {
3923					page->descr[0].flags |= SLBPPD_ENABLED |
3924					    SLBPPD_ARMING_DEC;
3925					if (lun->be_lun->blocksize)
3926						ival /= lun->be_lun->blocksize;
3927					else
3928						ival /= 512;
3929					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
3930					    page->descr[0].count);
3931				}
3932				value = ctl_get_opt(&lun->be_lun->options,
3933				    "used-threshold");
3934				if (value != NULL &&
3935				    ctl_expand_number(value, &ival) == 0) {
3936					page->descr[1].flags |= SLBPPD_ENABLED |
3937					    SLBPPD_ARMING_INC;
3938					if (lun->be_lun->blocksize)
3939						ival /= lun->be_lun->blocksize;
3940					else
3941						ival /= 512;
3942					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
3943					    page->descr[1].count);
3944				}
3945				value = ctl_get_opt(&lun->be_lun->options,
3946				    "pool-avail-threshold");
3947				if (value != NULL &&
3948				    ctl_expand_number(value, &ival) == 0) {
3949					page->descr[2].flags |= SLBPPD_ENABLED |
3950					    SLBPPD_ARMING_DEC;
3951					if (lun->be_lun->blocksize)
3952						ival /= lun->be_lun->blocksize;
3953					else
3954						ival /= 512;
3955					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
3956					    page->descr[2].count);
3957				}
3958				value = ctl_get_opt(&lun->be_lun->options,
3959				    "pool-used-threshold");
3960				if (value != NULL &&
3961				    ctl_expand_number(value, &ival) == 0) {
3962					page->descr[3].flags |= SLBPPD_ENABLED |
3963					    SLBPPD_ARMING_INC;
3964					if (lun->be_lun->blocksize)
3965						ival /= lun->be_lun->blocksize;
3966					else
3967						ival /= 512;
3968					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
3969					    page->descr[3].count);
3970				}
3971				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
3972				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
3973				       sizeof(lbp_page_default));
3974				page_index->page_data =
3975					(uint8_t *)lun->mode_pages.lbp_page;
3976			}}
3977			break;
3978		}
3979		case SMS_VENDOR_SPECIFIC_PAGE:{
3980			switch (page_index->subpage) {
3981			case DBGCNF_SUBPAGE_CODE: {
3982				struct copan_debugconf_subpage *current_page,
3983							       *saved_page;
3984
3985				memcpy(&lun->mode_pages.debugconf_subpage[
3986				       CTL_PAGE_CURRENT],
3987				       &debugconf_page_default,
3988				       sizeof(debugconf_page_default));
3989				memcpy(&lun->mode_pages.debugconf_subpage[
3990				       CTL_PAGE_CHANGEABLE],
3991				       &debugconf_page_changeable,
3992				       sizeof(debugconf_page_changeable));
3993				memcpy(&lun->mode_pages.debugconf_subpage[
3994				       CTL_PAGE_DEFAULT],
3995				       &debugconf_page_default,
3996				       sizeof(debugconf_page_default));
3997				memcpy(&lun->mode_pages.debugconf_subpage[
3998				       CTL_PAGE_SAVED],
3999				       &debugconf_page_default,
4000				       sizeof(debugconf_page_default));
4001				page_index->page_data =
4002					(uint8_t *)lun->mode_pages.debugconf_subpage;
4003
4004				current_page = (struct copan_debugconf_subpage *)
4005					(page_index->page_data +
4006					 (page_index->page_len *
4007					  CTL_PAGE_CURRENT));
4008				saved_page = (struct copan_debugconf_subpage *)
4009					(page_index->page_data +
4010					 (page_index->page_len *
4011					  CTL_PAGE_SAVED));
4012				break;
4013			}
4014			default:
4015				panic("invalid subpage value %d",
4016				      page_index->subpage);
4017				break;
4018			}
4019   			break;
4020		}
4021		default:
4022			panic("invalid page value %d",
4023			      page_index->page_code & SMPH_PC_MASK);
4024			break;
4025    	}
4026	}
4027
4028	return (CTL_RETVAL_COMPLETE);
4029}
4030
4031static int
4032ctl_init_log_page_index(struct ctl_lun *lun)
4033{
4034	struct ctl_page_index *page_index;
4035	int i, j, k, prev;
4036
4037	memcpy(&lun->log_pages.index, log_page_index_template,
4038	       sizeof(log_page_index_template));
4039
4040	prev = -1;
4041	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4042
4043		page_index = &lun->log_pages.index[i];
4044		/*
4045		 * If this is a disk-only mode page, there's no point in
4046		 * setting it up.  For some pages, we have to have some
4047		 * basic information about the disk in order to calculate the
4048		 * mode page data.
4049		 */
4050		if ((lun->be_lun->lun_type != T_DIRECT)
4051		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4052			continue;
4053
4054		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4055		     lun->backend->lun_attr == NULL)
4056			continue;
4057
4058		if (page_index->page_code != prev) {
4059			lun->log_pages.pages_page[j] = page_index->page_code;
4060			prev = page_index->page_code;
4061			j++;
4062		}
4063		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4064		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4065		k++;
4066	}
4067	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4068	lun->log_pages.index[0].page_len = j;
4069	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4070	lun->log_pages.index[1].page_len = k * 2;
4071	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4072	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4073	lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4074	lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4075
4076	return (CTL_RETVAL_COMPLETE);
4077}
4078
4079static int
4080hex2bin(const char *str, uint8_t *buf, int buf_size)
4081{
4082	int i;
4083	u_char c;
4084
4085	memset(buf, 0, buf_size);
4086	while (isspace(str[0]))
4087		str++;
4088	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4089		str += 2;
4090	buf_size *= 2;
4091	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4092		c = str[i];
4093		if (isdigit(c))
4094			c -= '0';
4095		else if (isalpha(c))
4096			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4097		else
4098			break;
4099		if (c >= 16)
4100			break;
4101		if ((i & 1) == 0)
4102			buf[i / 2] |= (c << 4);
4103		else
4104			buf[i / 2] |= c;
4105	}
4106	return ((i + 1) / 2);
4107}
4108
4109/*
4110 * LUN allocation.
4111 *
4112 * Requirements:
4113 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4114 *   wants us to allocate the LUN and he can block.
4115 * - ctl_softc is always set
4116 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4117 *
4118 * Returns 0 for success, non-zero (errno) for failure.
4119 */
4120static int
4121ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4122	      struct ctl_be_lun *const be_lun)
4123{
4124	struct ctl_lun *nlun, *lun;
4125	struct scsi_vpd_id_descriptor *desc;
4126	struct scsi_vpd_id_t10 *t10id;
4127	const char *eui, *naa, *scsiname, *vendor;
4128	int lun_number, i, lun_malloced;
4129	int devidlen, idlen1, idlen2 = 0, len;
4130
4131	if (be_lun == NULL)
4132		return (EINVAL);
4133
4134	/*
4135	 * We currently only support Direct Access or Processor LUN types.
4136	 */
4137	switch (be_lun->lun_type) {
4138	case T_DIRECT:
4139		break;
4140	case T_PROCESSOR:
4141		break;
4142	case T_SEQUENTIAL:
4143	case T_CHANGER:
4144	default:
4145		be_lun->lun_config_status(be_lun->be_lun,
4146					  CTL_LUN_CONFIG_FAILURE);
4147		break;
4148	}
4149	if (ctl_lun == NULL) {
4150		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4151		lun_malloced = 1;
4152	} else {
4153		lun_malloced = 0;
4154		lun = ctl_lun;
4155	}
4156
4157	memset(lun, 0, sizeof(*lun));
4158	if (lun_malloced)
4159		lun->flags = CTL_LUN_MALLOCED;
4160
4161	/* Generate LUN ID. */
4162	devidlen = max(CTL_DEVID_MIN_LEN,
4163	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4164	idlen1 = sizeof(*t10id) + devidlen;
4165	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4166	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4167	if (scsiname != NULL) {
4168		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4169		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4170	}
4171	eui = ctl_get_opt(&be_lun->options, "eui");
4172	if (eui != NULL) {
4173		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4174	}
4175	naa = ctl_get_opt(&be_lun->options, "naa");
4176	if (naa != NULL) {
4177		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4178	}
4179	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4180	    M_CTL, M_WAITOK | M_ZERO);
4181	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4182	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4183	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4184	desc->length = idlen1;
4185	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4186	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4187	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4188		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4189	} else {
4190		strncpy(t10id->vendor, vendor,
4191		    min(sizeof(t10id->vendor), strlen(vendor)));
4192	}
4193	strncpy((char *)t10id->vendor_spec_id,
4194	    (char *)be_lun->device_id, devidlen);
4195	if (scsiname != NULL) {
4196		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4197		    desc->length);
4198		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4199		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4200		    SVPD_ID_TYPE_SCSI_NAME;
4201		desc->length = idlen2;
4202		strlcpy(desc->identifier, scsiname, idlen2);
4203	}
4204	if (eui != NULL) {
4205		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4206		    desc->length);
4207		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4208		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4209		    SVPD_ID_TYPE_EUI64;
4210		desc->length = hex2bin(eui, desc->identifier, 16);
4211		desc->length = desc->length > 12 ? 16 :
4212		    (desc->length > 8 ? 12 : 8);
4213		len -= 16 - desc->length;
4214	}
4215	if (naa != NULL) {
4216		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4217		    desc->length);
4218		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4219		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4220		    SVPD_ID_TYPE_NAA;
4221		desc->length = hex2bin(naa, desc->identifier, 16);
4222		desc->length = desc->length > 8 ? 16 : 8;
4223		len -= 16 - desc->length;
4224	}
4225	lun->lun_devid->len = len;
4226
4227	mtx_lock(&ctl_softc->ctl_lock);
4228	/*
4229	 * See if the caller requested a particular LUN number.  If so, see
4230	 * if it is available.  Otherwise, allocate the first available LUN.
4231	 */
4232	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4233		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4234		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4235			mtx_unlock(&ctl_softc->ctl_lock);
4236			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4237				printf("ctl: requested LUN ID %d is higher "
4238				       "than CTL_MAX_LUNS - 1 (%d)\n",
4239				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4240			} else {
4241				/*
4242				 * XXX KDM return an error, or just assign
4243				 * another LUN ID in this case??
4244				 */
4245				printf("ctl: requested LUN ID %d is already "
4246				       "in use\n", be_lun->req_lun_id);
4247			}
4248			if (lun->flags & CTL_LUN_MALLOCED)
4249				free(lun, M_CTL);
4250			be_lun->lun_config_status(be_lun->be_lun,
4251						  CTL_LUN_CONFIG_FAILURE);
4252			return (ENOSPC);
4253		}
4254		lun_number = be_lun->req_lun_id;
4255	} else {
4256		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4257		if (lun_number == -1) {
4258			mtx_unlock(&ctl_softc->ctl_lock);
4259			printf("ctl: can't allocate LUN, out of LUNs\n");
4260			if (lun->flags & CTL_LUN_MALLOCED)
4261				free(lun, M_CTL);
4262			be_lun->lun_config_status(be_lun->be_lun,
4263						  CTL_LUN_CONFIG_FAILURE);
4264			return (ENOSPC);
4265		}
4266	}
4267	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4268
4269	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4270	lun->lun = lun_number;
4271	lun->be_lun = be_lun;
4272	/*
4273	 * The processor LUN is always enabled.  Disk LUNs come on line
4274	 * disabled, and must be enabled by the backend.
4275	 */
4276	lun->flags |= CTL_LUN_DISABLED;
4277	lun->backend = be_lun->be;
4278	be_lun->ctl_lun = lun;
4279	be_lun->lun_id = lun_number;
4280	atomic_add_int(&be_lun->be->num_luns, 1);
4281	if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4282		lun->flags |= CTL_LUN_OFFLINE;
4283
4284	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4285		lun->flags |= CTL_LUN_STOPPED;
4286
4287	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4288		lun->flags |= CTL_LUN_INOPERABLE;
4289
4290	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4291		lun->flags |= CTL_LUN_PRIMARY_SC;
4292
4293	lun->ctl_softc = ctl_softc;
4294#ifdef CTL_TIME_IO
4295	lun->last_busy = getsbinuptime();
4296#endif
4297	TAILQ_INIT(&lun->ooa_queue);
4298	TAILQ_INIT(&lun->blocked_queue);
4299	STAILQ_INIT(&lun->error_list);
4300	ctl_tpc_lun_init(lun);
4301
4302	/*
4303	 * Initialize the mode and log page index.
4304	 */
4305	ctl_init_page_index(lun);
4306	ctl_init_log_page_index(lun);
4307
4308	/*
4309	 * Now, before we insert this lun on the lun list, set the lun
4310	 * inventory changed UA for all other luns.
4311	 */
4312	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4313		mtx_lock(&nlun->lun_lock);
4314		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4315		mtx_unlock(&nlun->lun_lock);
4316	}
4317
4318	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4319
4320	ctl_softc->ctl_luns[lun_number] = lun;
4321
4322	ctl_softc->num_luns++;
4323
4324	/* Setup statistics gathering */
4325	lun->stats.device_type = be_lun->lun_type;
4326	lun->stats.lun_number = lun_number;
4327	if (lun->stats.device_type == T_DIRECT)
4328		lun->stats.blocksize = be_lun->blocksize;
4329	else
4330		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4331	for (i = 0;i < CTL_MAX_PORTS;i++)
4332		lun->stats.ports[i].targ_port = i;
4333
4334	mtx_unlock(&ctl_softc->ctl_lock);
4335
4336	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4337	return (0);
4338}
4339
4340/*
4341 * Delete a LUN.
4342 * Assumptions:
4343 * - LUN has already been marked invalid and any pending I/O has been taken
4344 *   care of.
4345 */
4346static int
4347ctl_free_lun(struct ctl_lun *lun)
4348{
4349	struct ctl_softc *softc;
4350	struct ctl_lun *nlun;
4351	int i;
4352
4353	softc = lun->ctl_softc;
4354
4355	mtx_assert(&softc->ctl_lock, MA_OWNED);
4356
4357	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4358
4359	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4360
4361	softc->ctl_luns[lun->lun] = NULL;
4362
4363	if (!TAILQ_EMPTY(&lun->ooa_queue))
4364		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4365
4366	softc->num_luns--;
4367
4368	/*
4369	 * Tell the backend to free resources, if this LUN has a backend.
4370	 */
4371	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4372	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4373
4374	ctl_tpc_lun_shutdown(lun);
4375	mtx_destroy(&lun->lun_lock);
4376	free(lun->lun_devid, M_CTL);
4377	for (i = 0; i < CTL_MAX_PORTS; i++)
4378		free(lun->pending_ua[i], M_CTL);
4379	for (i = 0; i < CTL_MAX_PORTS; i++)
4380		free(lun->pr_keys[i], M_CTL);
4381	free(lun->write_buffer, M_CTL);
4382	if (lun->flags & CTL_LUN_MALLOCED)
4383		free(lun, M_CTL);
4384
4385	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4386		mtx_lock(&nlun->lun_lock);
4387		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4388		mtx_unlock(&nlun->lun_lock);
4389	}
4390
4391	return (0);
4392}
4393
4394static void
4395ctl_create_lun(struct ctl_be_lun *be_lun)
4396{
4397	struct ctl_softc *softc;
4398
4399	softc = control_softc;
4400
4401	/*
4402	 * ctl_alloc_lun() should handle all potential failure cases.
4403	 */
4404	ctl_alloc_lun(softc, NULL, be_lun);
4405}
4406
4407int
4408ctl_add_lun(struct ctl_be_lun *be_lun)
4409{
4410	struct ctl_softc *softc = control_softc;
4411
4412	mtx_lock(&softc->ctl_lock);
4413	STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4414	mtx_unlock(&softc->ctl_lock);
4415	wakeup(&softc->pending_lun_queue);
4416
4417	return (0);
4418}
4419
4420int
4421ctl_enable_lun(struct ctl_be_lun *be_lun)
4422{
4423	struct ctl_softc *softc;
4424	struct ctl_port *port, *nport;
4425	struct ctl_lun *lun;
4426	int retval;
4427
4428	lun = (struct ctl_lun *)be_lun->ctl_lun;
4429	softc = lun->ctl_softc;
4430
4431	mtx_lock(&softc->ctl_lock);
4432	mtx_lock(&lun->lun_lock);
4433	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4434		/*
4435		 * eh?  Why did we get called if the LUN is already
4436		 * enabled?
4437		 */
4438		mtx_unlock(&lun->lun_lock);
4439		mtx_unlock(&softc->ctl_lock);
4440		return (0);
4441	}
4442	lun->flags &= ~CTL_LUN_DISABLED;
4443	mtx_unlock(&lun->lun_lock);
4444
4445	for (port = STAILQ_FIRST(&softc->port_list); port != NULL; port = nport) {
4446		nport = STAILQ_NEXT(port, links);
4447		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4448		    port->lun_map != NULL || port->lun_enable == NULL)
4449			continue;
4450
4451		/*
4452		 * Drop the lock while we call the FETD's enable routine.
4453		 * This can lead to a callback into CTL (at least in the
4454		 * case of the internal initiator frontend.
4455		 */
4456		mtx_unlock(&softc->ctl_lock);
4457		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4458		mtx_lock(&softc->ctl_lock);
4459		if (retval != 0) {
4460			printf("%s: FETD %s port %d returned error "
4461			       "%d for lun_enable on lun %jd\n",
4462			       __func__, port->port_name, port->targ_port,
4463			       retval, (intmax_t)lun->lun);
4464		}
4465	}
4466
4467	mtx_unlock(&softc->ctl_lock);
4468	ctl_isc_announce_lun(lun);
4469
4470	return (0);
4471}
4472
4473int
4474ctl_disable_lun(struct ctl_be_lun *be_lun)
4475{
4476	struct ctl_softc *softc;
4477	struct ctl_port *port;
4478	struct ctl_lun *lun;
4479	int retval;
4480
4481	lun = (struct ctl_lun *)be_lun->ctl_lun;
4482	softc = lun->ctl_softc;
4483
4484	mtx_lock(&softc->ctl_lock);
4485	mtx_lock(&lun->lun_lock);
4486	if (lun->flags & CTL_LUN_DISABLED) {
4487		mtx_unlock(&lun->lun_lock);
4488		mtx_unlock(&softc->ctl_lock);
4489		return (0);
4490	}
4491	lun->flags |= CTL_LUN_DISABLED;
4492	mtx_unlock(&lun->lun_lock);
4493
4494	STAILQ_FOREACH(port, &softc->port_list, links) {
4495		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4496		    port->lun_map != NULL || port->lun_disable == NULL)
4497			continue;
4498
4499		/*
4500		 * Drop the lock before we call the frontend's disable
4501		 * routine, to avoid lock order reversals.
4502		 *
4503		 * XXX KDM what happens if the frontend list changes while
4504		 * we're traversing it?  It's unlikely, but should be handled.
4505		 */
4506		mtx_unlock(&softc->ctl_lock);
4507		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4508		mtx_lock(&softc->ctl_lock);
4509		if (retval != 0) {
4510			printf("%s: FETD %s port %d returned error "
4511			       "%d for lun_disable on lun %jd\n",
4512			       __func__, port->port_name, port->targ_port,
4513			       retval, (intmax_t)lun->lun);
4514		}
4515	}
4516
4517	mtx_unlock(&softc->ctl_lock);
4518	ctl_isc_announce_lun(lun);
4519
4520	return (0);
4521}
4522
4523int
4524ctl_start_lun(struct ctl_be_lun *be_lun)
4525{
4526	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4527
4528	mtx_lock(&lun->lun_lock);
4529	lun->flags &= ~CTL_LUN_STOPPED;
4530	mtx_unlock(&lun->lun_lock);
4531	return (0);
4532}
4533
4534int
4535ctl_stop_lun(struct ctl_be_lun *be_lun)
4536{
4537	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4538
4539	mtx_lock(&lun->lun_lock);
4540	lun->flags |= CTL_LUN_STOPPED;
4541	mtx_unlock(&lun->lun_lock);
4542	return (0);
4543}
4544
4545int
4546ctl_lun_offline(struct ctl_be_lun *be_lun)
4547{
4548	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4549
4550	mtx_lock(&lun->lun_lock);
4551	lun->flags |= CTL_LUN_OFFLINE;
4552	mtx_unlock(&lun->lun_lock);
4553	return (0);
4554}
4555
4556int
4557ctl_lun_online(struct ctl_be_lun *be_lun)
4558{
4559	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4560
4561	mtx_lock(&lun->lun_lock);
4562	lun->flags &= ~CTL_LUN_OFFLINE;
4563	mtx_unlock(&lun->lun_lock);
4564	return (0);
4565}
4566
4567int
4568ctl_lun_primary(struct ctl_be_lun *be_lun)
4569{
4570	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4571
4572	mtx_lock(&lun->lun_lock);
4573	lun->flags |= CTL_LUN_PRIMARY_SC;
4574	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4575	mtx_unlock(&lun->lun_lock);
4576	ctl_isc_announce_lun(lun);
4577	return (0);
4578}
4579
4580int
4581ctl_lun_secondary(struct ctl_be_lun *be_lun)
4582{
4583	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4584
4585	mtx_lock(&lun->lun_lock);
4586	lun->flags &= ~CTL_LUN_PRIMARY_SC;
4587	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4588	mtx_unlock(&lun->lun_lock);
4589	ctl_isc_announce_lun(lun);
4590	return (0);
4591}
4592
4593int
4594ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4595{
4596	struct ctl_softc *softc;
4597	struct ctl_lun *lun;
4598
4599	lun = (struct ctl_lun *)be_lun->ctl_lun;
4600	softc = lun->ctl_softc;
4601
4602	mtx_lock(&lun->lun_lock);
4603
4604	/*
4605	 * The LUN needs to be disabled before it can be marked invalid.
4606	 */
4607	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4608		mtx_unlock(&lun->lun_lock);
4609		return (-1);
4610	}
4611	/*
4612	 * Mark the LUN invalid.
4613	 */
4614	lun->flags |= CTL_LUN_INVALID;
4615
4616	/*
4617	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4618	 * If we have something in the OOA queue, we'll free it when the
4619	 * last I/O completes.
4620	 */
4621	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4622		mtx_unlock(&lun->lun_lock);
4623		mtx_lock(&softc->ctl_lock);
4624		ctl_free_lun(lun);
4625		mtx_unlock(&softc->ctl_lock);
4626	} else
4627		mtx_unlock(&lun->lun_lock);
4628
4629	return (0);
4630}
4631
4632int
4633ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4634{
4635	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4636
4637	mtx_lock(&lun->lun_lock);
4638	lun->flags |= CTL_LUN_INOPERABLE;
4639	mtx_unlock(&lun->lun_lock);
4640	return (0);
4641}
4642
4643int
4644ctl_lun_operable(struct ctl_be_lun *be_lun)
4645{
4646	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4647
4648	mtx_lock(&lun->lun_lock);
4649	lun->flags &= ~CTL_LUN_INOPERABLE;
4650	mtx_unlock(&lun->lun_lock);
4651	return (0);
4652}
4653
4654void
4655ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4656{
4657	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4658	union ctl_ha_msg msg;
4659
4660	mtx_lock(&lun->lun_lock);
4661	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGED);
4662	mtx_unlock(&lun->lun_lock);
4663	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4664		/* Send msg to other side. */
4665		bzero(&msg.ua, sizeof(msg.ua));
4666		msg.hdr.msg_type = CTL_MSG_UA;
4667		msg.hdr.nexus.initid = -1;
4668		msg.hdr.nexus.targ_port = -1;
4669		msg.hdr.nexus.targ_lun = lun->lun;
4670		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4671		msg.ua.ua_all = 1;
4672		msg.ua.ua_set = 1;
4673		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGED;
4674		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4675		    M_WAITOK);
4676	}
4677}
4678
4679/*
4680 * Backend "memory move is complete" callback for requests that never
4681 * make it down to say RAIDCore's configuration code.
4682 */
4683int
4684ctl_config_move_done(union ctl_io *io)
4685{
4686	int retval;
4687
4688	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4689	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4690	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
4691
4692	if ((io->io_hdr.port_status != 0) &&
4693	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4694	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4695		/*
4696		 * For hardware error sense keys, the sense key
4697		 * specific value is defined to be a retry count,
4698		 * but we use it to pass back an internal FETD
4699		 * error code.  XXX KDM  Hopefully the FETD is only
4700		 * using 16 bits for an error code, since that's
4701		 * all the space we have in the sks field.
4702		 */
4703		ctl_set_internal_failure(&io->scsiio,
4704					 /*sks_valid*/ 1,
4705					 /*retry_count*/
4706					 io->io_hdr.port_status);
4707	}
4708
4709	if (ctl_debug & CTL_DEBUG_CDB_DATA)
4710		ctl_data_print(io);
4711	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
4712	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4713	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
4714	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
4715		/*
4716		 * XXX KDM just assuming a single pointer here, and not a
4717		 * S/G list.  If we start using S/G lists for config data,
4718		 * we'll need to know how to clean them up here as well.
4719		 */
4720		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4721			free(io->scsiio.kern_data_ptr, M_CTL);
4722		ctl_done(io);
4723		retval = CTL_RETVAL_COMPLETE;
4724	} else {
4725		/*
4726		 * XXX KDM now we need to continue data movement.  Some
4727		 * options:
4728		 * - call ctl_scsiio() again?  We don't do this for data
4729		 *   writes, because for those at least we know ahead of
4730		 *   time where the write will go and how long it is.  For
4731		 *   config writes, though, that information is largely
4732		 *   contained within the write itself, thus we need to
4733		 *   parse out the data again.
4734		 *
4735		 * - Call some other function once the data is in?
4736		 */
4737
4738		/*
4739		 * XXX KDM call ctl_scsiio() again for now, and check flag
4740		 * bits to see whether we're allocated or not.
4741		 */
4742		retval = ctl_scsiio(&io->scsiio);
4743	}
4744	return (retval);
4745}
4746
4747/*
4748 * This gets called by a backend driver when it is done with a
4749 * data_submit method.
4750 */
4751void
4752ctl_data_submit_done(union ctl_io *io)
4753{
4754	/*
4755	 * If the IO_CONT flag is set, we need to call the supplied
4756	 * function to continue processing the I/O, instead of completing
4757	 * the I/O just yet.
4758	 *
4759	 * If there is an error, though, we don't want to keep processing.
4760	 * Instead, just send status back to the initiator.
4761	 */
4762	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
4763	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
4764	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4765	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4766		io->scsiio.io_cont(io);
4767		return;
4768	}
4769	ctl_done(io);
4770}
4771
4772/*
4773 * This gets called by a backend driver when it is done with a
4774 * configuration write.
4775 */
4776void
4777ctl_config_write_done(union ctl_io *io)
4778{
4779	uint8_t *buf;
4780
4781	/*
4782	 * If the IO_CONT flag is set, we need to call the supplied
4783	 * function to continue processing the I/O, instead of completing
4784	 * the I/O just yet.
4785	 *
4786	 * If there is an error, though, we don't want to keep processing.
4787	 * Instead, just send status back to the initiator.
4788	 */
4789	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
4790	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
4791	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4792	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4793		io->scsiio.io_cont(io);
4794		return;
4795	}
4796	/*
4797	 * Since a configuration write can be done for commands that actually
4798	 * have data allocated, like write buffer, and commands that have
4799	 * no data, like start/stop unit, we need to check here.
4800	 */
4801	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4802		buf = io->scsiio.kern_data_ptr;
4803	else
4804		buf = NULL;
4805	ctl_done(io);
4806	if (buf)
4807		free(buf, M_CTL);
4808}
4809
4810void
4811ctl_config_read_done(union ctl_io *io)
4812{
4813	uint8_t *buf;
4814
4815	/*
4816	 * If there is some error -- we are done, skip data transfer.
4817	 */
4818	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
4819	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4820	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
4821		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4822			buf = io->scsiio.kern_data_ptr;
4823		else
4824			buf = NULL;
4825		ctl_done(io);
4826		if (buf)
4827			free(buf, M_CTL);
4828		return;
4829	}
4830
4831	/*
4832	 * If the IO_CONT flag is set, we need to call the supplied
4833	 * function to continue processing the I/O, instead of completing
4834	 * the I/O just yet.
4835	 */
4836	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
4837		io->scsiio.io_cont(io);
4838		return;
4839	}
4840
4841	ctl_datamove(io);
4842}
4843
4844/*
4845 * SCSI release command.
4846 */
4847int
4848ctl_scsi_release(struct ctl_scsiio *ctsio)
4849{
4850	int length, longid, thirdparty_id, resv_id;
4851	struct ctl_lun *lun;
4852	uint32_t residx;
4853
4854	length = 0;
4855	resv_id = 0;
4856
4857	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
4858
4859	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
4860	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
4861
4862	switch (ctsio->cdb[0]) {
4863	case RELEASE_10: {
4864		struct scsi_release_10 *cdb;
4865
4866		cdb = (struct scsi_release_10 *)ctsio->cdb;
4867
4868		if (cdb->byte2 & SR10_LONGID)
4869			longid = 1;
4870		else
4871			thirdparty_id = cdb->thirdparty_id;
4872
4873		resv_id = cdb->resv_id;
4874		length = scsi_2btoul(cdb->length);
4875		break;
4876	}
4877	}
4878
4879
4880	/*
4881	 * XXX KDM right now, we only support LUN reservation.  We don't
4882	 * support 3rd party reservations, or extent reservations, which
4883	 * might actually need the parameter list.  If we've gotten this
4884	 * far, we've got a LUN reservation.  Anything else got kicked out
4885	 * above.  So, according to SPC, ignore the length.
4886	 */
4887	length = 0;
4888
4889	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
4890	 && (length > 0)) {
4891		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
4892		ctsio->kern_data_len = length;
4893		ctsio->kern_total_len = length;
4894		ctsio->kern_data_resid = 0;
4895		ctsio->kern_rel_offset = 0;
4896		ctsio->kern_sg_entries = 0;
4897		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
4898		ctsio->be_move_done = ctl_config_move_done;
4899		ctl_datamove((union ctl_io *)ctsio);
4900
4901		return (CTL_RETVAL_COMPLETE);
4902	}
4903
4904	if (length > 0)
4905		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
4906
4907	mtx_lock(&lun->lun_lock);
4908
4909	/*
4910	 * According to SPC, it is not an error for an intiator to attempt
4911	 * to release a reservation on a LUN that isn't reserved, or that
4912	 * is reserved by another initiator.  The reservation can only be
4913	 * released, though, by the initiator who made it or by one of
4914	 * several reset type events.
4915	 */
4916	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
4917			lun->flags &= ~CTL_LUN_RESERVED;
4918
4919	mtx_unlock(&lun->lun_lock);
4920
4921	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
4922		free(ctsio->kern_data_ptr, M_CTL);
4923		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
4924	}
4925
4926	ctl_set_success(ctsio);
4927	ctl_done((union ctl_io *)ctsio);
4928	return (CTL_RETVAL_COMPLETE);
4929}
4930
4931int
4932ctl_scsi_reserve(struct ctl_scsiio *ctsio)
4933{
4934	int extent, thirdparty, longid;
4935	int resv_id, length;
4936	uint64_t thirdparty_id;
4937	struct ctl_lun *lun;
4938	uint32_t residx;
4939
4940	extent = 0;
4941	thirdparty = 0;
4942	longid = 0;
4943	resv_id = 0;
4944	length = 0;
4945	thirdparty_id = 0;
4946
4947	CTL_DEBUG_PRINT(("ctl_reserve\n"));
4948
4949	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
4950	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
4951
4952	switch (ctsio->cdb[0]) {
4953	case RESERVE_10: {
4954		struct scsi_reserve_10 *cdb;
4955
4956		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
4957
4958		if (cdb->byte2 & SR10_LONGID)
4959			longid = 1;
4960		else
4961			thirdparty_id = cdb->thirdparty_id;
4962
4963		resv_id = cdb->resv_id;
4964		length = scsi_2btoul(cdb->length);
4965		break;
4966	}
4967	}
4968
4969	/*
4970	 * XXX KDM right now, we only support LUN reservation.  We don't
4971	 * support 3rd party reservations, or extent reservations, which
4972	 * might actually need the parameter list.  If we've gotten this
4973	 * far, we've got a LUN reservation.  Anything else got kicked out
4974	 * above.  So, according to SPC, ignore the length.
4975	 */
4976	length = 0;
4977
4978	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
4979	 && (length > 0)) {
4980		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
4981		ctsio->kern_data_len = length;
4982		ctsio->kern_total_len = length;
4983		ctsio->kern_data_resid = 0;
4984		ctsio->kern_rel_offset = 0;
4985		ctsio->kern_sg_entries = 0;
4986		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
4987		ctsio->be_move_done = ctl_config_move_done;
4988		ctl_datamove((union ctl_io *)ctsio);
4989
4990		return (CTL_RETVAL_COMPLETE);
4991	}
4992
4993	if (length > 0)
4994		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
4995
4996	mtx_lock(&lun->lun_lock);
4997	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
4998		ctl_set_reservation_conflict(ctsio);
4999		goto bailout;
5000	}
5001
5002	lun->flags |= CTL_LUN_RESERVED;
5003	lun->res_idx = residx;
5004
5005	ctl_set_success(ctsio);
5006
5007bailout:
5008	mtx_unlock(&lun->lun_lock);
5009
5010	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5011		free(ctsio->kern_data_ptr, M_CTL);
5012		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5013	}
5014
5015	ctl_done((union ctl_io *)ctsio);
5016	return (CTL_RETVAL_COMPLETE);
5017}
5018
5019int
5020ctl_start_stop(struct ctl_scsiio *ctsio)
5021{
5022	struct scsi_start_stop_unit *cdb;
5023	struct ctl_lun *lun;
5024	int retval;
5025
5026	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5027
5028	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5029	retval = 0;
5030
5031	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5032
5033	/*
5034	 * XXX KDM
5035	 * We don't support the immediate bit on a stop unit.  In order to
5036	 * do that, we would need to code up a way to know that a stop is
5037	 * pending, and hold off any new commands until it completes, one
5038	 * way or another.  Then we could accept or reject those commands
5039	 * depending on its status.  We would almost need to do the reverse
5040	 * of what we do below for an immediate start -- return the copy of
5041	 * the ctl_io to the FETD with status to send to the host (and to
5042	 * free the copy!) and then free the original I/O once the stop
5043	 * actually completes.  That way, the OOA queue mechanism can work
5044	 * to block commands that shouldn't proceed.  Another alternative
5045	 * would be to put the copy in the queue in place of the original,
5046	 * and return the original back to the caller.  That could be
5047	 * slightly safer..
5048	 */
5049	if ((cdb->byte2 & SSS_IMMED)
5050	 && ((cdb->how & SSS_START) == 0)) {
5051		ctl_set_invalid_field(ctsio,
5052				      /*sks_valid*/ 1,
5053				      /*command*/ 1,
5054				      /*field*/ 1,
5055				      /*bit_valid*/ 1,
5056				      /*bit*/ 0);
5057		ctl_done((union ctl_io *)ctsio);
5058		return (CTL_RETVAL_COMPLETE);
5059	}
5060
5061	if ((lun->flags & CTL_LUN_PR_RESERVED)
5062	 && ((cdb->how & SSS_START)==0)) {
5063		uint32_t residx;
5064
5065		residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5066		if (ctl_get_prkey(lun, residx) == 0
5067		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5068
5069			ctl_set_reservation_conflict(ctsio);
5070			ctl_done((union ctl_io *)ctsio);
5071			return (CTL_RETVAL_COMPLETE);
5072		}
5073	}
5074
5075	/*
5076	 * If there is no backend on this device, we can't start or stop
5077	 * it.  In theory we shouldn't get any start/stop commands in the
5078	 * first place at this level if the LUN doesn't have a backend.
5079	 * That should get stopped by the command decode code.
5080	 */
5081	if (lun->backend == NULL) {
5082		ctl_set_invalid_opcode(ctsio);
5083		ctl_done((union ctl_io *)ctsio);
5084		return (CTL_RETVAL_COMPLETE);
5085	}
5086
5087	/*
5088	 * XXX KDM Copan-specific offline behavior.
5089	 * Figure out a reasonable way to port this?
5090	 */
5091#ifdef NEEDTOPORT
5092	mtx_lock(&lun->lun_lock);
5093
5094	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5095	 && (lun->flags & CTL_LUN_OFFLINE)) {
5096		/*
5097		 * If the LUN is offline, and the on/offline bit isn't set,
5098		 * reject the start or stop.  Otherwise, let it through.
5099		 */
5100		mtx_unlock(&lun->lun_lock);
5101		ctl_set_lun_not_ready(ctsio);
5102		ctl_done((union ctl_io *)ctsio);
5103	} else {
5104		mtx_unlock(&lun->lun_lock);
5105#endif /* NEEDTOPORT */
5106		/*
5107		 * This could be a start or a stop when we're online,
5108		 * or a stop/offline or start/online.  A start or stop when
5109		 * we're offline is covered in the case above.
5110		 */
5111		/*
5112		 * In the non-immediate case, we send the request to
5113		 * the backend and return status to the user when
5114		 * it is done.
5115		 *
5116		 * In the immediate case, we allocate a new ctl_io
5117		 * to hold a copy of the request, and send that to
5118		 * the backend.  We then set good status on the
5119		 * user's request and return it immediately.
5120		 */
5121		if (cdb->byte2 & SSS_IMMED) {
5122			union ctl_io *new_io;
5123
5124			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5125			ctl_copy_io((union ctl_io *)ctsio, new_io);
5126			retval = lun->backend->config_write(new_io);
5127			ctl_set_success(ctsio);
5128			ctl_done((union ctl_io *)ctsio);
5129		} else {
5130			retval = lun->backend->config_write(
5131				(union ctl_io *)ctsio);
5132		}
5133#ifdef NEEDTOPORT
5134	}
5135#endif
5136	return (retval);
5137}
5138
5139/*
5140 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5141 * we don't really do anything with the LBA and length fields if the user
5142 * passes them in.  Instead we'll just flush out the cache for the entire
5143 * LUN.
5144 */
5145int
5146ctl_sync_cache(struct ctl_scsiio *ctsio)
5147{
5148	struct ctl_lun *lun;
5149	struct ctl_softc *softc;
5150	struct ctl_lba_len_flags *lbalen;
5151	uint64_t starting_lba;
5152	uint32_t block_count;
5153	int retval;
5154	uint8_t byte2;
5155
5156	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5157
5158	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5159	softc = lun->ctl_softc;
5160	retval = 0;
5161
5162	switch (ctsio->cdb[0]) {
5163	case SYNCHRONIZE_CACHE: {
5164		struct scsi_sync_cache *cdb;
5165		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5166
5167		starting_lba = scsi_4btoul(cdb->begin_lba);
5168		block_count = scsi_2btoul(cdb->lb_count);
5169		byte2 = cdb->byte2;
5170		break;
5171	}
5172	case SYNCHRONIZE_CACHE_16: {
5173		struct scsi_sync_cache_16 *cdb;
5174		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5175
5176		starting_lba = scsi_8btou64(cdb->begin_lba);
5177		block_count = scsi_4btoul(cdb->lb_count);
5178		byte2 = cdb->byte2;
5179		break;
5180	}
5181	default:
5182		ctl_set_invalid_opcode(ctsio);
5183		ctl_done((union ctl_io *)ctsio);
5184		goto bailout;
5185		break; /* NOTREACHED */
5186	}
5187
5188	/*
5189	 * We check the LBA and length, but don't do anything with them.
5190	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5191	 * get flushed.  This check will just help satisfy anyone who wants
5192	 * to see an error for an out of range LBA.
5193	 */
5194	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5195		ctl_set_lba_out_of_range(ctsio);
5196		ctl_done((union ctl_io *)ctsio);
5197		goto bailout;
5198	}
5199
5200	/*
5201	 * If this LUN has no backend, we can't flush the cache anyway.
5202	 */
5203	if (lun->backend == NULL) {
5204		ctl_set_invalid_opcode(ctsio);
5205		ctl_done((union ctl_io *)ctsio);
5206		goto bailout;
5207	}
5208
5209	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5210	lbalen->lba = starting_lba;
5211	lbalen->len = block_count;
5212	lbalen->flags = byte2;
5213
5214	/*
5215	 * Check to see whether we're configured to send the SYNCHRONIZE
5216	 * CACHE command directly to the back end.
5217	 */
5218	mtx_lock(&lun->lun_lock);
5219	if ((softc->flags & CTL_FLAG_REAL_SYNC)
5220	 && (++(lun->sync_count) >= lun->sync_interval)) {
5221		lun->sync_count = 0;
5222		mtx_unlock(&lun->lun_lock);
5223		retval = lun->backend->config_write((union ctl_io *)ctsio);
5224	} else {
5225		mtx_unlock(&lun->lun_lock);
5226		ctl_set_success(ctsio);
5227		ctl_done((union ctl_io *)ctsio);
5228	}
5229
5230bailout:
5231
5232	return (retval);
5233}
5234
5235int
5236ctl_format(struct ctl_scsiio *ctsio)
5237{
5238	struct scsi_format *cdb;
5239	struct ctl_lun *lun;
5240	int length, defect_list_len;
5241
5242	CTL_DEBUG_PRINT(("ctl_format\n"));
5243
5244	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5245
5246	cdb = (struct scsi_format *)ctsio->cdb;
5247
5248	length = 0;
5249	if (cdb->byte2 & SF_FMTDATA) {
5250		if (cdb->byte2 & SF_LONGLIST)
5251			length = sizeof(struct scsi_format_header_long);
5252		else
5253			length = sizeof(struct scsi_format_header_short);
5254	}
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	defect_list_len = 0;
5272
5273	if (cdb->byte2 & SF_FMTDATA) {
5274		if (cdb->byte2 & SF_LONGLIST) {
5275			struct scsi_format_header_long *header;
5276
5277			header = (struct scsi_format_header_long *)
5278				ctsio->kern_data_ptr;
5279
5280			defect_list_len = scsi_4btoul(header->defect_list_len);
5281			if (defect_list_len != 0) {
5282				ctl_set_invalid_field(ctsio,
5283						      /*sks_valid*/ 1,
5284						      /*command*/ 0,
5285						      /*field*/ 2,
5286						      /*bit_valid*/ 0,
5287						      /*bit*/ 0);
5288				goto bailout;
5289			}
5290		} else {
5291			struct scsi_format_header_short *header;
5292
5293			header = (struct scsi_format_header_short *)
5294				ctsio->kern_data_ptr;
5295
5296			defect_list_len = scsi_2btoul(header->defect_list_len);
5297			if (defect_list_len != 0) {
5298				ctl_set_invalid_field(ctsio,
5299						      /*sks_valid*/ 1,
5300						      /*command*/ 0,
5301						      /*field*/ 2,
5302						      /*bit_valid*/ 0,
5303						      /*bit*/ 0);
5304				goto bailout;
5305			}
5306		}
5307	}
5308
5309	/*
5310	 * The format command will clear out the "Medium format corrupted"
5311	 * status if set by the configuration code.  That status is really
5312	 * just a way to notify the host that we have lost the media, and
5313	 * get them to issue a command that will basically make them think
5314	 * they're blowing away the media.
5315	 */
5316	mtx_lock(&lun->lun_lock);
5317	lun->flags &= ~CTL_LUN_INOPERABLE;
5318	mtx_unlock(&lun->lun_lock);
5319
5320	ctl_set_success(ctsio);
5321bailout:
5322
5323	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5324		free(ctsio->kern_data_ptr, M_CTL);
5325		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5326	}
5327
5328	ctl_done((union ctl_io *)ctsio);
5329	return (CTL_RETVAL_COMPLETE);
5330}
5331
5332int
5333ctl_read_buffer(struct ctl_scsiio *ctsio)
5334{
5335	struct scsi_read_buffer *cdb;
5336	struct ctl_lun *lun;
5337	int buffer_offset, len;
5338	static uint8_t descr[4];
5339	static uint8_t echo_descr[4] = { 0 };
5340
5341	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5342
5343	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5344	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5345
5346	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5347	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5348	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5349		ctl_set_invalid_field(ctsio,
5350				      /*sks_valid*/ 1,
5351				      /*command*/ 1,
5352				      /*field*/ 1,
5353				      /*bit_valid*/ 1,
5354				      /*bit*/ 4);
5355		ctl_done((union ctl_io *)ctsio);
5356		return (CTL_RETVAL_COMPLETE);
5357	}
5358
5359	len = scsi_3btoul(cdb->length);
5360	buffer_offset = scsi_3btoul(cdb->offset);
5361
5362	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5363		ctl_set_invalid_field(ctsio,
5364				      /*sks_valid*/ 1,
5365				      /*command*/ 1,
5366				      /*field*/ 6,
5367				      /*bit_valid*/ 0,
5368				      /*bit*/ 0);
5369		ctl_done((union ctl_io *)ctsio);
5370		return (CTL_RETVAL_COMPLETE);
5371	}
5372
5373	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5374		descr[0] = 0;
5375		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5376		ctsio->kern_data_ptr = descr;
5377		len = min(len, sizeof(descr));
5378	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5379		ctsio->kern_data_ptr = echo_descr;
5380		len = min(len, sizeof(echo_descr));
5381	} else {
5382		if (lun->write_buffer == NULL) {
5383			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5384			    M_CTL, M_WAITOK);
5385		}
5386		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5387	}
5388	ctsio->kern_data_len = len;
5389	ctsio->kern_total_len = len;
5390	ctsio->kern_data_resid = 0;
5391	ctsio->kern_rel_offset = 0;
5392	ctsio->kern_sg_entries = 0;
5393	ctl_set_success(ctsio);
5394	ctsio->be_move_done = ctl_config_move_done;
5395	ctl_datamove((union ctl_io *)ctsio);
5396	return (CTL_RETVAL_COMPLETE);
5397}
5398
5399int
5400ctl_write_buffer(struct ctl_scsiio *ctsio)
5401{
5402	struct scsi_write_buffer *cdb;
5403	struct ctl_lun *lun;
5404	int buffer_offset, len;
5405
5406	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5407
5408	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5409	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5410
5411	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5412		ctl_set_invalid_field(ctsio,
5413				      /*sks_valid*/ 1,
5414				      /*command*/ 1,
5415				      /*field*/ 1,
5416				      /*bit_valid*/ 1,
5417				      /*bit*/ 4);
5418		ctl_done((union ctl_io *)ctsio);
5419		return (CTL_RETVAL_COMPLETE);
5420	}
5421
5422	len = scsi_3btoul(cdb->length);
5423	buffer_offset = scsi_3btoul(cdb->offset);
5424
5425	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5426		ctl_set_invalid_field(ctsio,
5427				      /*sks_valid*/ 1,
5428				      /*command*/ 1,
5429				      /*field*/ 6,
5430				      /*bit_valid*/ 0,
5431				      /*bit*/ 0);
5432		ctl_done((union ctl_io *)ctsio);
5433		return (CTL_RETVAL_COMPLETE);
5434	}
5435
5436	/*
5437	 * If we've got a kernel request that hasn't been malloced yet,
5438	 * malloc it and tell the caller the data buffer is here.
5439	 */
5440	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5441		if (lun->write_buffer == NULL) {
5442			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5443			    M_CTL, M_WAITOK);
5444		}
5445		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5446		ctsio->kern_data_len = len;
5447		ctsio->kern_total_len = len;
5448		ctsio->kern_data_resid = 0;
5449		ctsio->kern_rel_offset = 0;
5450		ctsio->kern_sg_entries = 0;
5451		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5452		ctsio->be_move_done = ctl_config_move_done;
5453		ctl_datamove((union ctl_io *)ctsio);
5454
5455		return (CTL_RETVAL_COMPLETE);
5456	}
5457
5458	ctl_set_success(ctsio);
5459	ctl_done((union ctl_io *)ctsio);
5460	return (CTL_RETVAL_COMPLETE);
5461}
5462
5463int
5464ctl_write_same(struct ctl_scsiio *ctsio)
5465{
5466	struct ctl_lun *lun;
5467	struct ctl_lba_len_flags *lbalen;
5468	uint64_t lba;
5469	uint32_t num_blocks;
5470	int len, retval;
5471	uint8_t byte2;
5472
5473	retval = CTL_RETVAL_COMPLETE;
5474
5475	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5476
5477	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5478
5479	switch (ctsio->cdb[0]) {
5480	case WRITE_SAME_10: {
5481		struct scsi_write_same_10 *cdb;
5482
5483		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5484
5485		lba = scsi_4btoul(cdb->addr);
5486		num_blocks = scsi_2btoul(cdb->length);
5487		byte2 = cdb->byte2;
5488		break;
5489	}
5490	case WRITE_SAME_16: {
5491		struct scsi_write_same_16 *cdb;
5492
5493		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5494
5495		lba = scsi_8btou64(cdb->addr);
5496		num_blocks = scsi_4btoul(cdb->length);
5497		byte2 = cdb->byte2;
5498		break;
5499	}
5500	default:
5501		/*
5502		 * We got a command we don't support.  This shouldn't
5503		 * happen, commands should be filtered out above us.
5504		 */
5505		ctl_set_invalid_opcode(ctsio);
5506		ctl_done((union ctl_io *)ctsio);
5507
5508		return (CTL_RETVAL_COMPLETE);
5509		break; /* NOTREACHED */
5510	}
5511
5512	/* NDOB and ANCHOR flags can be used only together with UNMAP */
5513	if ((byte2 & SWS_UNMAP) == 0 &&
5514	    (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5515		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5516		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5517		ctl_done((union ctl_io *)ctsio);
5518		return (CTL_RETVAL_COMPLETE);
5519	}
5520
5521	/*
5522	 * The first check is to make sure we're in bounds, the second
5523	 * check is to catch wrap-around problems.  If the lba + num blocks
5524	 * is less than the lba, then we've wrapped around and the block
5525	 * range is invalid anyway.
5526	 */
5527	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5528	 || ((lba + num_blocks) < lba)) {
5529		ctl_set_lba_out_of_range(ctsio);
5530		ctl_done((union ctl_io *)ctsio);
5531		return (CTL_RETVAL_COMPLETE);
5532	}
5533
5534	/* Zero number of blocks means "to the last logical block" */
5535	if (num_blocks == 0) {
5536		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5537			ctl_set_invalid_field(ctsio,
5538					      /*sks_valid*/ 0,
5539					      /*command*/ 1,
5540					      /*field*/ 0,
5541					      /*bit_valid*/ 0,
5542					      /*bit*/ 0);
5543			ctl_done((union ctl_io *)ctsio);
5544			return (CTL_RETVAL_COMPLETE);
5545		}
5546		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5547	}
5548
5549	len = lun->be_lun->blocksize;
5550
5551	/*
5552	 * If we've got a kernel request that hasn't been malloced yet,
5553	 * malloc it and tell the caller the data buffer is here.
5554	 */
5555	if ((byte2 & SWS_NDOB) == 0 &&
5556	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5557		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5558		ctsio->kern_data_len = len;
5559		ctsio->kern_total_len = len;
5560		ctsio->kern_data_resid = 0;
5561		ctsio->kern_rel_offset = 0;
5562		ctsio->kern_sg_entries = 0;
5563		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5564		ctsio->be_move_done = ctl_config_move_done;
5565		ctl_datamove((union ctl_io *)ctsio);
5566
5567		return (CTL_RETVAL_COMPLETE);
5568	}
5569
5570	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5571	lbalen->lba = lba;
5572	lbalen->len = num_blocks;
5573	lbalen->flags = byte2;
5574	retval = lun->backend->config_write((union ctl_io *)ctsio);
5575
5576	return (retval);
5577}
5578
5579int
5580ctl_unmap(struct ctl_scsiio *ctsio)
5581{
5582	struct ctl_lun *lun;
5583	struct scsi_unmap *cdb;
5584	struct ctl_ptr_len_flags *ptrlen;
5585	struct scsi_unmap_header *hdr;
5586	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5587	uint64_t lba;
5588	uint32_t num_blocks;
5589	int len, retval;
5590	uint8_t byte2;
5591
5592	retval = CTL_RETVAL_COMPLETE;
5593
5594	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5595
5596	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5597	cdb = (struct scsi_unmap *)ctsio->cdb;
5598
5599	len = scsi_2btoul(cdb->length);
5600	byte2 = cdb->byte2;
5601
5602	/*
5603	 * If we've got a kernel request that hasn't been malloced yet,
5604	 * malloc it and tell the caller the data buffer is here.
5605	 */
5606	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5607		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5608		ctsio->kern_data_len = len;
5609		ctsio->kern_total_len = len;
5610		ctsio->kern_data_resid = 0;
5611		ctsio->kern_rel_offset = 0;
5612		ctsio->kern_sg_entries = 0;
5613		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5614		ctsio->be_move_done = ctl_config_move_done;
5615		ctl_datamove((union ctl_io *)ctsio);
5616
5617		return (CTL_RETVAL_COMPLETE);
5618	}
5619
5620	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5621	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5622	if (len < sizeof (*hdr) ||
5623	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5624	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5625	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5626		ctl_set_invalid_field(ctsio,
5627				      /*sks_valid*/ 0,
5628				      /*command*/ 0,
5629				      /*field*/ 0,
5630				      /*bit_valid*/ 0,
5631				      /*bit*/ 0);
5632		goto done;
5633	}
5634	len = scsi_2btoul(hdr->desc_length);
5635	buf = (struct scsi_unmap_desc *)(hdr + 1);
5636	end = buf + len / sizeof(*buf);
5637
5638	endnz = buf;
5639	for (range = buf; range < end; range++) {
5640		lba = scsi_8btou64(range->lba);
5641		num_blocks = scsi_4btoul(range->length);
5642		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5643		 || ((lba + num_blocks) < lba)) {
5644			ctl_set_lba_out_of_range(ctsio);
5645			ctl_done((union ctl_io *)ctsio);
5646			return (CTL_RETVAL_COMPLETE);
5647		}
5648		if (num_blocks != 0)
5649			endnz = range + 1;
5650	}
5651
5652	/*
5653	 * Block backend can not handle zero last range.
5654	 * Filter it out and return if there is nothing left.
5655	 */
5656	len = (uint8_t *)endnz - (uint8_t *)buf;
5657	if (len == 0) {
5658		ctl_set_success(ctsio);
5659		goto done;
5660	}
5661
5662	mtx_lock(&lun->lun_lock);
5663	ptrlen = (struct ctl_ptr_len_flags *)
5664	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5665	ptrlen->ptr = (void *)buf;
5666	ptrlen->len = len;
5667	ptrlen->flags = byte2;
5668	ctl_check_blocked(lun);
5669	mtx_unlock(&lun->lun_lock);
5670
5671	retval = lun->backend->config_write((union ctl_io *)ctsio);
5672	return (retval);
5673
5674done:
5675	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5676		free(ctsio->kern_data_ptr, M_CTL);
5677		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5678	}
5679	ctl_done((union ctl_io *)ctsio);
5680	return (CTL_RETVAL_COMPLETE);
5681}
5682
5683/*
5684 * Note that this function currently doesn't actually do anything inside
5685 * CTL to enforce things if the DQue bit is turned on.
5686 *
5687 * Also note that this function can't be used in the default case, because
5688 * the DQue bit isn't set in the changeable mask for the control mode page
5689 * anyway.  This is just here as an example for how to implement a page
5690 * handler, and a placeholder in case we want to allow the user to turn
5691 * tagged queueing on and off.
5692 *
5693 * The D_SENSE bit handling is functional, however, and will turn
5694 * descriptor sense on and off for a given LUN.
5695 */
5696int
5697ctl_control_page_handler(struct ctl_scsiio *ctsio,
5698			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5699{
5700	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5701	struct ctl_lun *lun;
5702	int set_ua;
5703	uint32_t initidx;
5704
5705	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5706	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5707	set_ua = 0;
5708
5709	user_cp = (struct scsi_control_page *)page_ptr;
5710	current_cp = (struct scsi_control_page *)
5711		(page_index->page_data + (page_index->page_len *
5712		CTL_PAGE_CURRENT));
5713	saved_cp = (struct scsi_control_page *)
5714		(page_index->page_data + (page_index->page_len *
5715		CTL_PAGE_SAVED));
5716
5717	mtx_lock(&lun->lun_lock);
5718	if (((current_cp->rlec & SCP_DSENSE) == 0)
5719	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
5720		/*
5721		 * Descriptor sense is currently turned off and the user
5722		 * wants to turn it on.
5723		 */
5724		current_cp->rlec |= SCP_DSENSE;
5725		saved_cp->rlec |= SCP_DSENSE;
5726		lun->flags |= CTL_LUN_SENSE_DESC;
5727		set_ua = 1;
5728	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
5729		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
5730		/*
5731		 * Descriptor sense is currently turned on, and the user
5732		 * wants to turn it off.
5733		 */
5734		current_cp->rlec &= ~SCP_DSENSE;
5735		saved_cp->rlec &= ~SCP_DSENSE;
5736		lun->flags &= ~CTL_LUN_SENSE_DESC;
5737		set_ua = 1;
5738	}
5739	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
5740	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
5741		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5742		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5743		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5744		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5745		set_ua = 1;
5746	}
5747	if ((current_cp->eca_and_aen & SCP_SWP) !=
5748	    (user_cp->eca_and_aen & SCP_SWP)) {
5749		current_cp->eca_and_aen &= ~SCP_SWP;
5750		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5751		saved_cp->eca_and_aen &= ~SCP_SWP;
5752		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5753		set_ua = 1;
5754	}
5755	if (set_ua != 0)
5756		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5757	mtx_unlock(&lun->lun_lock);
5758
5759	return (0);
5760}
5761
5762int
5763ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
5764		     struct ctl_page_index *page_index, uint8_t *page_ptr)
5765{
5766	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
5767	struct ctl_lun *lun;
5768	int set_ua;
5769	uint32_t initidx;
5770
5771	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5772	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5773	set_ua = 0;
5774
5775	user_cp = (struct scsi_caching_page *)page_ptr;
5776	current_cp = (struct scsi_caching_page *)
5777		(page_index->page_data + (page_index->page_len *
5778		CTL_PAGE_CURRENT));
5779	saved_cp = (struct scsi_caching_page *)
5780		(page_index->page_data + (page_index->page_len *
5781		CTL_PAGE_SAVED));
5782
5783	mtx_lock(&lun->lun_lock);
5784	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
5785	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
5786		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5787		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5788		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5789		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5790		set_ua = 1;
5791	}
5792	if (set_ua != 0)
5793		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5794	mtx_unlock(&lun->lun_lock);
5795
5796	return (0);
5797}
5798
5799int
5800ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
5801				struct ctl_page_index *page_index,
5802				uint8_t *page_ptr)
5803{
5804	uint8_t *c;
5805	int i;
5806
5807	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
5808	ctl_time_io_secs =
5809		(c[0] << 8) |
5810		(c[1] << 0) |
5811		0;
5812	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
5813	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
5814	printf("page data:");
5815	for (i=0; i<8; i++)
5816		printf(" %.2x",page_ptr[i]);
5817	printf("\n");
5818	return (0);
5819}
5820
5821int
5822ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
5823			       struct ctl_page_index *page_index,
5824			       int pc)
5825{
5826	struct copan_debugconf_subpage *page;
5827
5828	page = (struct copan_debugconf_subpage *)page_index->page_data +
5829		(page_index->page_len * pc);
5830
5831	switch (pc) {
5832	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
5833	case SMS_PAGE_CTRL_DEFAULT >> 6:
5834	case SMS_PAGE_CTRL_SAVED >> 6:
5835		/*
5836		 * We don't update the changable or default bits for this page.
5837		 */
5838		break;
5839	case SMS_PAGE_CTRL_CURRENT >> 6:
5840		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
5841		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
5842		break;
5843	default:
5844#ifdef NEEDTOPORT
5845		EPRINT(0, "Invalid PC %d!!", pc);
5846#endif /* NEEDTOPORT */
5847		break;
5848	}
5849	return (0);
5850}
5851
5852
5853static int
5854ctl_do_mode_select(union ctl_io *io)
5855{
5856	struct scsi_mode_page_header *page_header;
5857	struct ctl_page_index *page_index;
5858	struct ctl_scsiio *ctsio;
5859	int control_dev, page_len;
5860	int page_len_offset, page_len_size;
5861	union ctl_modepage_info *modepage_info;
5862	struct ctl_lun *lun;
5863	int *len_left, *len_used;
5864	int retval, i;
5865
5866	ctsio = &io->scsiio;
5867	page_index = NULL;
5868	page_len = 0;
5869	retval = CTL_RETVAL_COMPLETE;
5870
5871	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5872
5873	if (lun->be_lun->lun_type != T_DIRECT)
5874		control_dev = 1;
5875	else
5876		control_dev = 0;
5877
5878	modepage_info = (union ctl_modepage_info *)
5879		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5880	len_left = &modepage_info->header.len_left;
5881	len_used = &modepage_info->header.len_used;
5882
5883do_next_page:
5884
5885	page_header = (struct scsi_mode_page_header *)
5886		(ctsio->kern_data_ptr + *len_used);
5887
5888	if (*len_left == 0) {
5889		free(ctsio->kern_data_ptr, M_CTL);
5890		ctl_set_success(ctsio);
5891		ctl_done((union ctl_io *)ctsio);
5892		return (CTL_RETVAL_COMPLETE);
5893	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
5894
5895		free(ctsio->kern_data_ptr, M_CTL);
5896		ctl_set_param_len_error(ctsio);
5897		ctl_done((union ctl_io *)ctsio);
5898		return (CTL_RETVAL_COMPLETE);
5899
5900	} else if ((page_header->page_code & SMPH_SPF)
5901		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
5902
5903		free(ctsio->kern_data_ptr, M_CTL);
5904		ctl_set_param_len_error(ctsio);
5905		ctl_done((union ctl_io *)ctsio);
5906		return (CTL_RETVAL_COMPLETE);
5907	}
5908
5909
5910	/*
5911	 * XXX KDM should we do something with the block descriptor?
5912	 */
5913	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5914
5915		if ((control_dev != 0)
5916		 && (lun->mode_pages.index[i].page_flags &
5917		     CTL_PAGE_FLAG_DISK_ONLY))
5918			continue;
5919
5920		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
5921		    (page_header->page_code & SMPH_PC_MASK))
5922			continue;
5923
5924		/*
5925		 * If neither page has a subpage code, then we've got a
5926		 * match.
5927		 */
5928		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
5929		 && ((page_header->page_code & SMPH_SPF) == 0)) {
5930			page_index = &lun->mode_pages.index[i];
5931			page_len = page_header->page_length;
5932			break;
5933		}
5934
5935		/*
5936		 * If both pages have subpages, then the subpage numbers
5937		 * have to match.
5938		 */
5939		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
5940		  && (page_header->page_code & SMPH_SPF)) {
5941			struct scsi_mode_page_header_sp *sph;
5942
5943			sph = (struct scsi_mode_page_header_sp *)page_header;
5944
5945			if (lun->mode_pages.index[i].subpage ==
5946			    sph->subpage) {
5947				page_index = &lun->mode_pages.index[i];
5948				page_len = scsi_2btoul(sph->page_length);
5949				break;
5950			}
5951		}
5952	}
5953
5954	/*
5955	 * If we couldn't find the page, or if we don't have a mode select
5956	 * handler for it, send back an error to the user.
5957	 */
5958	if ((page_index == NULL)
5959	 || (page_index->select_handler == NULL)) {
5960		ctl_set_invalid_field(ctsio,
5961				      /*sks_valid*/ 1,
5962				      /*command*/ 0,
5963				      /*field*/ *len_used,
5964				      /*bit_valid*/ 0,
5965				      /*bit*/ 0);
5966		free(ctsio->kern_data_ptr, M_CTL);
5967		ctl_done((union ctl_io *)ctsio);
5968		return (CTL_RETVAL_COMPLETE);
5969	}
5970
5971	if (page_index->page_code & SMPH_SPF) {
5972		page_len_offset = 2;
5973		page_len_size = 2;
5974	} else {
5975		page_len_size = 1;
5976		page_len_offset = 1;
5977	}
5978
5979	/*
5980	 * If the length the initiator gives us isn't the one we specify in
5981	 * the mode page header, or if they didn't specify enough data in
5982	 * the CDB to avoid truncating this page, kick out the request.
5983	 */
5984	if ((page_len != (page_index->page_len - page_len_offset -
5985			  page_len_size))
5986	 || (*len_left < page_index->page_len)) {
5987
5988
5989		ctl_set_invalid_field(ctsio,
5990				      /*sks_valid*/ 1,
5991				      /*command*/ 0,
5992				      /*field*/ *len_used + page_len_offset,
5993				      /*bit_valid*/ 0,
5994				      /*bit*/ 0);
5995		free(ctsio->kern_data_ptr, M_CTL);
5996		ctl_done((union ctl_io *)ctsio);
5997		return (CTL_RETVAL_COMPLETE);
5998	}
5999
6000	/*
6001	 * Run through the mode page, checking to make sure that the bits
6002	 * the user changed are actually legal for him to change.
6003	 */
6004	for (i = 0; i < page_index->page_len; i++) {
6005		uint8_t *user_byte, *change_mask, *current_byte;
6006		int bad_bit;
6007		int j;
6008
6009		user_byte = (uint8_t *)page_header + i;
6010		change_mask = page_index->page_data +
6011			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6012		current_byte = page_index->page_data +
6013			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6014
6015		/*
6016		 * Check to see whether the user set any bits in this byte
6017		 * that he is not allowed to set.
6018		 */
6019		if ((*user_byte & ~(*change_mask)) ==
6020		    (*current_byte & ~(*change_mask)))
6021			continue;
6022
6023		/*
6024		 * Go through bit by bit to determine which one is illegal.
6025		 */
6026		bad_bit = 0;
6027		for (j = 7; j >= 0; j--) {
6028			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6029			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6030				bad_bit = i;
6031				break;
6032			}
6033		}
6034		ctl_set_invalid_field(ctsio,
6035				      /*sks_valid*/ 1,
6036				      /*command*/ 0,
6037				      /*field*/ *len_used + i,
6038				      /*bit_valid*/ 1,
6039				      /*bit*/ bad_bit);
6040		free(ctsio->kern_data_ptr, M_CTL);
6041		ctl_done((union ctl_io *)ctsio);
6042		return (CTL_RETVAL_COMPLETE);
6043	}
6044
6045	/*
6046	 * Decrement these before we call the page handler, since we may
6047	 * end up getting called back one way or another before the handler
6048	 * returns to this context.
6049	 */
6050	*len_left -= page_index->page_len;
6051	*len_used += page_index->page_len;
6052
6053	retval = page_index->select_handler(ctsio, page_index,
6054					    (uint8_t *)page_header);
6055
6056	/*
6057	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6058	 * wait until this queued command completes to finish processing
6059	 * the mode page.  If it returns anything other than
6060	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6061	 * already set the sense information, freed the data pointer, and
6062	 * completed the io for us.
6063	 */
6064	if (retval != CTL_RETVAL_COMPLETE)
6065		goto bailout_no_done;
6066
6067	/*
6068	 * If the initiator sent us more than one page, parse the next one.
6069	 */
6070	if (*len_left > 0)
6071		goto do_next_page;
6072
6073	ctl_set_success(ctsio);
6074	free(ctsio->kern_data_ptr, M_CTL);
6075	ctl_done((union ctl_io *)ctsio);
6076
6077bailout_no_done:
6078
6079	return (CTL_RETVAL_COMPLETE);
6080
6081}
6082
6083int
6084ctl_mode_select(struct ctl_scsiio *ctsio)
6085{
6086	int param_len, pf, sp;
6087	int header_size, bd_len;
6088	int len_left, len_used;
6089	struct ctl_page_index *page_index;
6090	struct ctl_lun *lun;
6091	int control_dev, page_len;
6092	union ctl_modepage_info *modepage_info;
6093	int retval;
6094
6095	pf = 0;
6096	sp = 0;
6097	page_len = 0;
6098	len_used = 0;
6099	len_left = 0;
6100	retval = 0;
6101	bd_len = 0;
6102	page_index = NULL;
6103
6104	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6105
6106	if (lun->be_lun->lun_type != T_DIRECT)
6107		control_dev = 1;
6108	else
6109		control_dev = 0;
6110
6111	switch (ctsio->cdb[0]) {
6112	case MODE_SELECT_6: {
6113		struct scsi_mode_select_6 *cdb;
6114
6115		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6116
6117		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6118		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6119
6120		param_len = cdb->length;
6121		header_size = sizeof(struct scsi_mode_header_6);
6122		break;
6123	}
6124	case MODE_SELECT_10: {
6125		struct scsi_mode_select_10 *cdb;
6126
6127		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6128
6129		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6130		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6131
6132		param_len = scsi_2btoul(cdb->length);
6133		header_size = sizeof(struct scsi_mode_header_10);
6134		break;
6135	}
6136	default:
6137		ctl_set_invalid_opcode(ctsio);
6138		ctl_done((union ctl_io *)ctsio);
6139		return (CTL_RETVAL_COMPLETE);
6140		break; /* NOTREACHED */
6141	}
6142
6143	/*
6144	 * From SPC-3:
6145	 * "A parameter list length of zero indicates that the Data-Out Buffer
6146	 * shall be empty. This condition shall not be considered as an error."
6147	 */
6148	if (param_len == 0) {
6149		ctl_set_success(ctsio);
6150		ctl_done((union ctl_io *)ctsio);
6151		return (CTL_RETVAL_COMPLETE);
6152	}
6153
6154	/*
6155	 * Since we'll hit this the first time through, prior to
6156	 * allocation, we don't need to free a data buffer here.
6157	 */
6158	if (param_len < header_size) {
6159		ctl_set_param_len_error(ctsio);
6160		ctl_done((union ctl_io *)ctsio);
6161		return (CTL_RETVAL_COMPLETE);
6162	}
6163
6164	/*
6165	 * Allocate the data buffer and grab the user's data.  In theory,
6166	 * we shouldn't have to sanity check the parameter list length here
6167	 * because the maximum size is 64K.  We should be able to malloc
6168	 * that much without too many problems.
6169	 */
6170	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6171		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6172		ctsio->kern_data_len = param_len;
6173		ctsio->kern_total_len = param_len;
6174		ctsio->kern_data_resid = 0;
6175		ctsio->kern_rel_offset = 0;
6176		ctsio->kern_sg_entries = 0;
6177		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6178		ctsio->be_move_done = ctl_config_move_done;
6179		ctl_datamove((union ctl_io *)ctsio);
6180
6181		return (CTL_RETVAL_COMPLETE);
6182	}
6183
6184	switch (ctsio->cdb[0]) {
6185	case MODE_SELECT_6: {
6186		struct scsi_mode_header_6 *mh6;
6187
6188		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6189		bd_len = mh6->blk_desc_len;
6190		break;
6191	}
6192	case MODE_SELECT_10: {
6193		struct scsi_mode_header_10 *mh10;
6194
6195		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6196		bd_len = scsi_2btoul(mh10->blk_desc_len);
6197		break;
6198	}
6199	default:
6200		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6201		break;
6202	}
6203
6204	if (param_len < (header_size + bd_len)) {
6205		free(ctsio->kern_data_ptr, M_CTL);
6206		ctl_set_param_len_error(ctsio);
6207		ctl_done((union ctl_io *)ctsio);
6208		return (CTL_RETVAL_COMPLETE);
6209	}
6210
6211	/*
6212	 * Set the IO_CONT flag, so that if this I/O gets passed to
6213	 * ctl_config_write_done(), it'll get passed back to
6214	 * ctl_do_mode_select() for further processing, or completion if
6215	 * we're all done.
6216	 */
6217	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6218	ctsio->io_cont = ctl_do_mode_select;
6219
6220	modepage_info = (union ctl_modepage_info *)
6221		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6222
6223	memset(modepage_info, 0, sizeof(*modepage_info));
6224
6225	len_left = param_len - header_size - bd_len;
6226	len_used = header_size + bd_len;
6227
6228	modepage_info->header.len_left = len_left;
6229	modepage_info->header.len_used = len_used;
6230
6231	return (ctl_do_mode_select((union ctl_io *)ctsio));
6232}
6233
6234int
6235ctl_mode_sense(struct ctl_scsiio *ctsio)
6236{
6237	struct ctl_lun *lun;
6238	int pc, page_code, dbd, llba, subpage;
6239	int alloc_len, page_len, header_len, total_len;
6240	struct scsi_mode_block_descr *block_desc;
6241	struct ctl_page_index *page_index;
6242	int control_dev;
6243
6244	dbd = 0;
6245	llba = 0;
6246	block_desc = NULL;
6247	page_index = NULL;
6248
6249	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6250
6251	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6252
6253	if (lun->be_lun->lun_type != T_DIRECT)
6254		control_dev = 1;
6255	else
6256		control_dev = 0;
6257
6258	switch (ctsio->cdb[0]) {
6259	case MODE_SENSE_6: {
6260		struct scsi_mode_sense_6 *cdb;
6261
6262		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6263
6264		header_len = sizeof(struct scsi_mode_hdr_6);
6265		if (cdb->byte2 & SMS_DBD)
6266			dbd = 1;
6267		else
6268			header_len += sizeof(struct scsi_mode_block_descr);
6269
6270		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6271		page_code = cdb->page & SMS_PAGE_CODE;
6272		subpage = cdb->subpage;
6273		alloc_len = cdb->length;
6274		break;
6275	}
6276	case MODE_SENSE_10: {
6277		struct scsi_mode_sense_10 *cdb;
6278
6279		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6280
6281		header_len = sizeof(struct scsi_mode_hdr_10);
6282
6283		if (cdb->byte2 & SMS_DBD)
6284			dbd = 1;
6285		else
6286			header_len += sizeof(struct scsi_mode_block_descr);
6287		if (cdb->byte2 & SMS10_LLBAA)
6288			llba = 1;
6289		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6290		page_code = cdb->page & SMS_PAGE_CODE;
6291		subpage = cdb->subpage;
6292		alloc_len = scsi_2btoul(cdb->length);
6293		break;
6294	}
6295	default:
6296		ctl_set_invalid_opcode(ctsio);
6297		ctl_done((union ctl_io *)ctsio);
6298		return (CTL_RETVAL_COMPLETE);
6299		break; /* NOTREACHED */
6300	}
6301
6302	/*
6303	 * We have to make a first pass through to calculate the size of
6304	 * the pages that match the user's query.  Then we allocate enough
6305	 * memory to hold it, and actually copy the data into the buffer.
6306	 */
6307	switch (page_code) {
6308	case SMS_ALL_PAGES_PAGE: {
6309		int i;
6310
6311		page_len = 0;
6312
6313		/*
6314		 * At the moment, values other than 0 and 0xff here are
6315		 * reserved according to SPC-3.
6316		 */
6317		if ((subpage != SMS_SUBPAGE_PAGE_0)
6318		 && (subpage != SMS_SUBPAGE_ALL)) {
6319			ctl_set_invalid_field(ctsio,
6320					      /*sks_valid*/ 1,
6321					      /*command*/ 1,
6322					      /*field*/ 3,
6323					      /*bit_valid*/ 0,
6324					      /*bit*/ 0);
6325			ctl_done((union ctl_io *)ctsio);
6326			return (CTL_RETVAL_COMPLETE);
6327		}
6328
6329		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6330			if ((control_dev != 0)
6331			 && (lun->mode_pages.index[i].page_flags &
6332			     CTL_PAGE_FLAG_DISK_ONLY))
6333				continue;
6334
6335			/*
6336			 * We don't use this subpage if the user didn't
6337			 * request all subpages.
6338			 */
6339			if ((lun->mode_pages.index[i].subpage != 0)
6340			 && (subpage == SMS_SUBPAGE_PAGE_0))
6341				continue;
6342
6343#if 0
6344			printf("found page %#x len %d\n",
6345			       lun->mode_pages.index[i].page_code &
6346			       SMPH_PC_MASK,
6347			       lun->mode_pages.index[i].page_len);
6348#endif
6349			page_len += lun->mode_pages.index[i].page_len;
6350		}
6351		break;
6352	}
6353	default: {
6354		int i;
6355
6356		page_len = 0;
6357
6358		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6359			/* Look for the right page code */
6360			if ((lun->mode_pages.index[i].page_code &
6361			     SMPH_PC_MASK) != page_code)
6362				continue;
6363
6364			/* Look for the right subpage or the subpage wildcard*/
6365			if ((lun->mode_pages.index[i].subpage != subpage)
6366			 && (subpage != SMS_SUBPAGE_ALL))
6367				continue;
6368
6369			/* Make sure the page is supported for this dev type */
6370			if ((control_dev != 0)
6371			 && (lun->mode_pages.index[i].page_flags &
6372			     CTL_PAGE_FLAG_DISK_ONLY))
6373				continue;
6374
6375#if 0
6376			printf("found page %#x len %d\n",
6377			       lun->mode_pages.index[i].page_code &
6378			       SMPH_PC_MASK,
6379			       lun->mode_pages.index[i].page_len);
6380#endif
6381
6382			page_len += lun->mode_pages.index[i].page_len;
6383		}
6384
6385		if (page_len == 0) {
6386			ctl_set_invalid_field(ctsio,
6387					      /*sks_valid*/ 1,
6388					      /*command*/ 1,
6389					      /*field*/ 2,
6390					      /*bit_valid*/ 1,
6391					      /*bit*/ 5);
6392			ctl_done((union ctl_io *)ctsio);
6393			return (CTL_RETVAL_COMPLETE);
6394		}
6395		break;
6396	}
6397	}
6398
6399	total_len = header_len + page_len;
6400#if 0
6401	printf("header_len = %d, page_len = %d, total_len = %d\n",
6402	       header_len, page_len, total_len);
6403#endif
6404
6405	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6406	ctsio->kern_sg_entries = 0;
6407	ctsio->kern_data_resid = 0;
6408	ctsio->kern_rel_offset = 0;
6409	if (total_len < alloc_len) {
6410		ctsio->residual = alloc_len - total_len;
6411		ctsio->kern_data_len = total_len;
6412		ctsio->kern_total_len = total_len;
6413	} else {
6414		ctsio->residual = 0;
6415		ctsio->kern_data_len = alloc_len;
6416		ctsio->kern_total_len = alloc_len;
6417	}
6418
6419	switch (ctsio->cdb[0]) {
6420	case MODE_SENSE_6: {
6421		struct scsi_mode_hdr_6 *header;
6422
6423		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6424
6425		header->datalen = MIN(total_len - 1, 254);
6426		if (control_dev == 0) {
6427			header->dev_specific = 0x10; /* DPOFUA */
6428			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6429			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6430			    .eca_and_aen & SCP_SWP) != 0)
6431				    header->dev_specific |= 0x80; /* WP */
6432		}
6433		if (dbd)
6434			header->block_descr_len = 0;
6435		else
6436			header->block_descr_len =
6437				sizeof(struct scsi_mode_block_descr);
6438		block_desc = (struct scsi_mode_block_descr *)&header[1];
6439		break;
6440	}
6441	case MODE_SENSE_10: {
6442		struct scsi_mode_hdr_10 *header;
6443		int datalen;
6444
6445		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6446
6447		datalen = MIN(total_len - 2, 65533);
6448		scsi_ulto2b(datalen, header->datalen);
6449		if (control_dev == 0) {
6450			header->dev_specific = 0x10; /* DPOFUA */
6451			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6452			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6453			    .eca_and_aen & SCP_SWP) != 0)
6454				    header->dev_specific |= 0x80; /* WP */
6455		}
6456		if (dbd)
6457			scsi_ulto2b(0, header->block_descr_len);
6458		else
6459			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6460				    header->block_descr_len);
6461		block_desc = (struct scsi_mode_block_descr *)&header[1];
6462		break;
6463	}
6464	default:
6465		panic("invalid CDB type %#x", ctsio->cdb[0]);
6466		break; /* NOTREACHED */
6467	}
6468
6469	/*
6470	 * If we've got a disk, use its blocksize in the block
6471	 * descriptor.  Otherwise, just set it to 0.
6472	 */
6473	if (dbd == 0) {
6474		if (control_dev == 0)
6475			scsi_ulto3b(lun->be_lun->blocksize,
6476				    block_desc->block_len);
6477		else
6478			scsi_ulto3b(0, block_desc->block_len);
6479	}
6480
6481	switch (page_code) {
6482	case SMS_ALL_PAGES_PAGE: {
6483		int i, data_used;
6484
6485		data_used = header_len;
6486		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6487			struct ctl_page_index *page_index;
6488
6489			page_index = &lun->mode_pages.index[i];
6490
6491			if ((control_dev != 0)
6492			 && (page_index->page_flags &
6493			    CTL_PAGE_FLAG_DISK_ONLY))
6494				continue;
6495
6496			/*
6497			 * We don't use this subpage if the user didn't
6498			 * request all subpages.  We already checked (above)
6499			 * to make sure the user only specified a subpage
6500			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6501			 */
6502			if ((page_index->subpage != 0)
6503			 && (subpage == SMS_SUBPAGE_PAGE_0))
6504				continue;
6505
6506			/*
6507			 * Call the handler, if it exists, to update the
6508			 * page to the latest values.
6509			 */
6510			if (page_index->sense_handler != NULL)
6511				page_index->sense_handler(ctsio, page_index,pc);
6512
6513			memcpy(ctsio->kern_data_ptr + data_used,
6514			       page_index->page_data +
6515			       (page_index->page_len * pc),
6516			       page_index->page_len);
6517			data_used += page_index->page_len;
6518		}
6519		break;
6520	}
6521	default: {
6522		int i, data_used;
6523
6524		data_used = header_len;
6525
6526		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6527			struct ctl_page_index *page_index;
6528
6529			page_index = &lun->mode_pages.index[i];
6530
6531			/* Look for the right page code */
6532			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6533				continue;
6534
6535			/* Look for the right subpage or the subpage wildcard*/
6536			if ((page_index->subpage != subpage)
6537			 && (subpage != SMS_SUBPAGE_ALL))
6538				continue;
6539
6540			/* Make sure the page is supported for this dev type */
6541			if ((control_dev != 0)
6542			 && (page_index->page_flags &
6543			     CTL_PAGE_FLAG_DISK_ONLY))
6544				continue;
6545
6546			/*
6547			 * Call the handler, if it exists, to update the
6548			 * page to the latest values.
6549			 */
6550			if (page_index->sense_handler != NULL)
6551				page_index->sense_handler(ctsio, page_index,pc);
6552
6553			memcpy(ctsio->kern_data_ptr + data_used,
6554			       page_index->page_data +
6555			       (page_index->page_len * pc),
6556			       page_index->page_len);
6557			data_used += page_index->page_len;
6558		}
6559		break;
6560	}
6561	}
6562
6563	ctl_set_success(ctsio);
6564	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6565	ctsio->be_move_done = ctl_config_move_done;
6566	ctl_datamove((union ctl_io *)ctsio);
6567	return (CTL_RETVAL_COMPLETE);
6568}
6569
6570int
6571ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6572			       struct ctl_page_index *page_index,
6573			       int pc)
6574{
6575	struct ctl_lun *lun;
6576	struct scsi_log_param_header *phdr;
6577	uint8_t *data;
6578	uint64_t val;
6579
6580	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6581	data = page_index->page_data;
6582
6583	if (lun->backend->lun_attr != NULL &&
6584	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6585	     != UINT64_MAX) {
6586		phdr = (struct scsi_log_param_header *)data;
6587		scsi_ulto2b(0x0001, phdr->param_code);
6588		phdr->param_control = SLP_LBIN | SLP_LP;
6589		phdr->param_len = 8;
6590		data = (uint8_t *)(phdr + 1);
6591		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6592		data[4] = 0x02; /* per-pool */
6593		data += phdr->param_len;
6594	}
6595
6596	if (lun->backend->lun_attr != NULL &&
6597	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6598	     != UINT64_MAX) {
6599		phdr = (struct scsi_log_param_header *)data;
6600		scsi_ulto2b(0x0002, phdr->param_code);
6601		phdr->param_control = SLP_LBIN | SLP_LP;
6602		phdr->param_len = 8;
6603		data = (uint8_t *)(phdr + 1);
6604		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6605		data[4] = 0x01; /* per-LUN */
6606		data += phdr->param_len;
6607	}
6608
6609	if (lun->backend->lun_attr != NULL &&
6610	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6611	     != UINT64_MAX) {
6612		phdr = (struct scsi_log_param_header *)data;
6613		scsi_ulto2b(0x00f1, phdr->param_code);
6614		phdr->param_control = SLP_LBIN | SLP_LP;
6615		phdr->param_len = 8;
6616		data = (uint8_t *)(phdr + 1);
6617		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6618		data[4] = 0x02; /* per-pool */
6619		data += phdr->param_len;
6620	}
6621
6622	if (lun->backend->lun_attr != NULL &&
6623	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6624	     != UINT64_MAX) {
6625		phdr = (struct scsi_log_param_header *)data;
6626		scsi_ulto2b(0x00f2, phdr->param_code);
6627		phdr->param_control = SLP_LBIN | SLP_LP;
6628		phdr->param_len = 8;
6629		data = (uint8_t *)(phdr + 1);
6630		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6631		data[4] = 0x02; /* per-pool */
6632		data += phdr->param_len;
6633	}
6634
6635	page_index->page_len = data - page_index->page_data;
6636	return (0);
6637}
6638
6639int
6640ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6641			       struct ctl_page_index *page_index,
6642			       int pc)
6643{
6644	struct ctl_lun *lun;
6645	struct stat_page *data;
6646	uint64_t rn, wn, rb, wb;
6647	struct bintime rt, wt;
6648	int i;
6649
6650	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6651	data = (struct stat_page *)page_index->page_data;
6652
6653	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6654	data->sap.hdr.param_control = SLP_LBIN;
6655	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6656	    sizeof(struct scsi_log_param_header);
6657	rn = wn = rb = wb = 0;
6658	bintime_clear(&rt);
6659	bintime_clear(&wt);
6660	for (i = 0; i < CTL_MAX_PORTS; i++) {
6661		rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6662		wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6663		rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6664		wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6665		bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6666		bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6667	}
6668	scsi_u64to8b(rn, data->sap.read_num);
6669	scsi_u64to8b(wn, data->sap.write_num);
6670	if (lun->stats.blocksize > 0) {
6671		scsi_u64to8b(wb / lun->stats.blocksize,
6672		    data->sap.recvieved_lba);
6673		scsi_u64to8b(rb / lun->stats.blocksize,
6674		    data->sap.transmitted_lba);
6675	}
6676	scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6677	    data->sap.read_int);
6678	scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6679	    data->sap.write_int);
6680	scsi_u64to8b(0, data->sap.weighted_num);
6681	scsi_u64to8b(0, data->sap.weighted_int);
6682	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6683	data->it.hdr.param_control = SLP_LBIN;
6684	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6685	    sizeof(struct scsi_log_param_header);
6686#ifdef CTL_TIME_IO
6687	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6688#endif
6689	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6690	data->it.hdr.param_control = SLP_LBIN;
6691	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6692	    sizeof(struct scsi_log_param_header);
6693	scsi_ulto4b(3, data->ti.exponent);
6694	scsi_ulto4b(1, data->ti.integer);
6695
6696	page_index->page_len = sizeof(*data);
6697	return (0);
6698}
6699
6700int
6701ctl_log_sense(struct ctl_scsiio *ctsio)
6702{
6703	struct ctl_lun *lun;
6704	int i, pc, page_code, subpage;
6705	int alloc_len, total_len;
6706	struct ctl_page_index *page_index;
6707	struct scsi_log_sense *cdb;
6708	struct scsi_log_header *header;
6709
6710	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6711
6712	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6713	cdb = (struct scsi_log_sense *)ctsio->cdb;
6714	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6715	page_code = cdb->page & SLS_PAGE_CODE;
6716	subpage = cdb->subpage;
6717	alloc_len = scsi_2btoul(cdb->length);
6718
6719	page_index = NULL;
6720	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6721		page_index = &lun->log_pages.index[i];
6722
6723		/* Look for the right page code */
6724		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6725			continue;
6726
6727		/* Look for the right subpage or the subpage wildcard*/
6728		if (page_index->subpage != subpage)
6729			continue;
6730
6731		break;
6732	}
6733	if (i >= CTL_NUM_LOG_PAGES) {
6734		ctl_set_invalid_field(ctsio,
6735				      /*sks_valid*/ 1,
6736				      /*command*/ 1,
6737				      /*field*/ 2,
6738				      /*bit_valid*/ 0,
6739				      /*bit*/ 0);
6740		ctl_done((union ctl_io *)ctsio);
6741		return (CTL_RETVAL_COMPLETE);
6742	}
6743
6744	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6745
6746	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6747	ctsio->kern_sg_entries = 0;
6748	ctsio->kern_data_resid = 0;
6749	ctsio->kern_rel_offset = 0;
6750	if (total_len < alloc_len) {
6751		ctsio->residual = alloc_len - total_len;
6752		ctsio->kern_data_len = total_len;
6753		ctsio->kern_total_len = total_len;
6754	} else {
6755		ctsio->residual = 0;
6756		ctsio->kern_data_len = alloc_len;
6757		ctsio->kern_total_len = alloc_len;
6758	}
6759
6760	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6761	header->page = page_index->page_code;
6762	if (page_index->subpage) {
6763		header->page |= SL_SPF;
6764		header->subpage = page_index->subpage;
6765	}
6766	scsi_ulto2b(page_index->page_len, header->datalen);
6767
6768	/*
6769	 * Call the handler, if it exists, to update the
6770	 * page to the latest values.
6771	 */
6772	if (page_index->sense_handler != NULL)
6773		page_index->sense_handler(ctsio, page_index, pc);
6774
6775	memcpy(header + 1, page_index->page_data, page_index->page_len);
6776
6777	ctl_set_success(ctsio);
6778	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6779	ctsio->be_move_done = ctl_config_move_done;
6780	ctl_datamove((union ctl_io *)ctsio);
6781	return (CTL_RETVAL_COMPLETE);
6782}
6783
6784int
6785ctl_read_capacity(struct ctl_scsiio *ctsio)
6786{
6787	struct scsi_read_capacity *cdb;
6788	struct scsi_read_capacity_data *data;
6789	struct ctl_lun *lun;
6790	uint32_t lba;
6791
6792	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6793
6794	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6795
6796	lba = scsi_4btoul(cdb->addr);
6797	if (((cdb->pmi & SRC_PMI) == 0)
6798	 && (lba != 0)) {
6799		ctl_set_invalid_field(/*ctsio*/ ctsio,
6800				      /*sks_valid*/ 1,
6801				      /*command*/ 1,
6802				      /*field*/ 2,
6803				      /*bit_valid*/ 0,
6804				      /*bit*/ 0);
6805		ctl_done((union ctl_io *)ctsio);
6806		return (CTL_RETVAL_COMPLETE);
6807	}
6808
6809	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6810
6811	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6812	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6813	ctsio->residual = 0;
6814	ctsio->kern_data_len = sizeof(*data);
6815	ctsio->kern_total_len = sizeof(*data);
6816	ctsio->kern_data_resid = 0;
6817	ctsio->kern_rel_offset = 0;
6818	ctsio->kern_sg_entries = 0;
6819
6820	/*
6821	 * If the maximum LBA is greater than 0xfffffffe, the user must
6822	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6823	 * serivce action set.
6824	 */
6825	if (lun->be_lun->maxlba > 0xfffffffe)
6826		scsi_ulto4b(0xffffffff, data->addr);
6827	else
6828		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6829
6830	/*
6831	 * XXX KDM this may not be 512 bytes...
6832	 */
6833	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6834
6835	ctl_set_success(ctsio);
6836	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6837	ctsio->be_move_done = ctl_config_move_done;
6838	ctl_datamove((union ctl_io *)ctsio);
6839	return (CTL_RETVAL_COMPLETE);
6840}
6841
6842int
6843ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6844{
6845	struct scsi_read_capacity_16 *cdb;
6846	struct scsi_read_capacity_data_long *data;
6847	struct ctl_lun *lun;
6848	uint64_t lba;
6849	uint32_t alloc_len;
6850
6851	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6852
6853	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6854
6855	alloc_len = scsi_4btoul(cdb->alloc_len);
6856	lba = scsi_8btou64(cdb->addr);
6857
6858	if ((cdb->reladr & SRC16_PMI)
6859	 && (lba != 0)) {
6860		ctl_set_invalid_field(/*ctsio*/ ctsio,
6861				      /*sks_valid*/ 1,
6862				      /*command*/ 1,
6863				      /*field*/ 2,
6864				      /*bit_valid*/ 0,
6865				      /*bit*/ 0);
6866		ctl_done((union ctl_io *)ctsio);
6867		return (CTL_RETVAL_COMPLETE);
6868	}
6869
6870	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6871
6872	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6873	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6874
6875	if (sizeof(*data) < alloc_len) {
6876		ctsio->residual = alloc_len - sizeof(*data);
6877		ctsio->kern_data_len = sizeof(*data);
6878		ctsio->kern_total_len = sizeof(*data);
6879	} else {
6880		ctsio->residual = 0;
6881		ctsio->kern_data_len = alloc_len;
6882		ctsio->kern_total_len = alloc_len;
6883	}
6884	ctsio->kern_data_resid = 0;
6885	ctsio->kern_rel_offset = 0;
6886	ctsio->kern_sg_entries = 0;
6887
6888	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6889	/* XXX KDM this may not be 512 bytes... */
6890	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6891	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6892	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
6893	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
6894		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
6895
6896	ctl_set_success(ctsio);
6897	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6898	ctsio->be_move_done = ctl_config_move_done;
6899	ctl_datamove((union ctl_io *)ctsio);
6900	return (CTL_RETVAL_COMPLETE);
6901}
6902
6903int
6904ctl_get_lba_status(struct ctl_scsiio *ctsio)
6905{
6906	struct scsi_get_lba_status *cdb;
6907	struct scsi_get_lba_status_data *data;
6908	struct ctl_lun *lun;
6909	struct ctl_lba_len_flags *lbalen;
6910	uint64_t lba;
6911	uint32_t alloc_len, total_len;
6912	int retval;
6913
6914	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
6915
6916	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6917	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
6918	lba = scsi_8btou64(cdb->addr);
6919	alloc_len = scsi_4btoul(cdb->alloc_len);
6920
6921	if (lba > lun->be_lun->maxlba) {
6922		ctl_set_lba_out_of_range(ctsio);
6923		ctl_done((union ctl_io *)ctsio);
6924		return (CTL_RETVAL_COMPLETE);
6925	}
6926
6927	total_len = sizeof(*data) + sizeof(data->descr[0]);
6928	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6929	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
6930
6931	if (total_len < alloc_len) {
6932		ctsio->residual = alloc_len - total_len;
6933		ctsio->kern_data_len = total_len;
6934		ctsio->kern_total_len = total_len;
6935	} else {
6936		ctsio->residual = 0;
6937		ctsio->kern_data_len = alloc_len;
6938		ctsio->kern_total_len = alloc_len;
6939	}
6940	ctsio->kern_data_resid = 0;
6941	ctsio->kern_rel_offset = 0;
6942	ctsio->kern_sg_entries = 0;
6943
6944	/* Fill dummy data in case backend can't tell anything. */
6945	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
6946	scsi_u64to8b(lba, data->descr[0].addr);
6947	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
6948	    data->descr[0].length);
6949	data->descr[0].status = 0; /* Mapped or unknown. */
6950
6951	ctl_set_success(ctsio);
6952	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6953	ctsio->be_move_done = ctl_config_move_done;
6954
6955	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6956	lbalen->lba = lba;
6957	lbalen->len = total_len;
6958	lbalen->flags = 0;
6959	retval = lun->backend->config_read((union ctl_io *)ctsio);
6960	return (CTL_RETVAL_COMPLETE);
6961}
6962
6963int
6964ctl_read_defect(struct ctl_scsiio *ctsio)
6965{
6966	struct scsi_read_defect_data_10 *ccb10;
6967	struct scsi_read_defect_data_12 *ccb12;
6968	struct scsi_read_defect_data_hdr_10 *data10;
6969	struct scsi_read_defect_data_hdr_12 *data12;
6970	uint32_t alloc_len, data_len;
6971	uint8_t format;
6972
6973	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
6974
6975	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
6976		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
6977		format = ccb10->format;
6978		alloc_len = scsi_2btoul(ccb10->alloc_length);
6979		data_len = sizeof(*data10);
6980	} else {
6981		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
6982		format = ccb12->format;
6983		alloc_len = scsi_4btoul(ccb12->alloc_length);
6984		data_len = sizeof(*data12);
6985	}
6986	if (alloc_len == 0) {
6987		ctl_set_success(ctsio);
6988		ctl_done((union ctl_io *)ctsio);
6989		return (CTL_RETVAL_COMPLETE);
6990	}
6991
6992	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
6993	if (data_len < alloc_len) {
6994		ctsio->residual = alloc_len - data_len;
6995		ctsio->kern_data_len = data_len;
6996		ctsio->kern_total_len = data_len;
6997	} else {
6998		ctsio->residual = 0;
6999		ctsio->kern_data_len = alloc_len;
7000		ctsio->kern_total_len = alloc_len;
7001	}
7002	ctsio->kern_data_resid = 0;
7003	ctsio->kern_rel_offset = 0;
7004	ctsio->kern_sg_entries = 0;
7005
7006	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7007		data10 = (struct scsi_read_defect_data_hdr_10 *)
7008		    ctsio->kern_data_ptr;
7009		data10->format = format;
7010		scsi_ulto2b(0, data10->length);
7011	} else {
7012		data12 = (struct scsi_read_defect_data_hdr_12 *)
7013		    ctsio->kern_data_ptr;
7014		data12->format = format;
7015		scsi_ulto2b(0, data12->generation);
7016		scsi_ulto4b(0, data12->length);
7017	}
7018
7019	ctl_set_success(ctsio);
7020	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7021	ctsio->be_move_done = ctl_config_move_done;
7022	ctl_datamove((union ctl_io *)ctsio);
7023	return (CTL_RETVAL_COMPLETE);
7024}
7025
7026int
7027ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7028{
7029	struct scsi_maintenance_in *cdb;
7030	int retval;
7031	int alloc_len, ext, total_len = 0, g, pc, pg, gs, os;
7032	int num_target_port_groups, num_target_ports;
7033	struct ctl_lun *lun;
7034	struct ctl_softc *softc;
7035	struct ctl_port *port;
7036	struct scsi_target_group_data *rtg_ptr;
7037	struct scsi_target_group_data_extended *rtg_ext_ptr;
7038	struct scsi_target_port_group_descriptor *tpg_desc;
7039
7040	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7041
7042	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7043	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7044	softc = lun->ctl_softc;
7045
7046	retval = CTL_RETVAL_COMPLETE;
7047
7048	switch (cdb->byte2 & STG_PDF_MASK) {
7049	case STG_PDF_LENGTH:
7050		ext = 0;
7051		break;
7052	case STG_PDF_EXTENDED:
7053		ext = 1;
7054		break;
7055	default:
7056		ctl_set_invalid_field(/*ctsio*/ ctsio,
7057				      /*sks_valid*/ 1,
7058				      /*command*/ 1,
7059				      /*field*/ 2,
7060				      /*bit_valid*/ 1,
7061				      /*bit*/ 5);
7062		ctl_done((union ctl_io *)ctsio);
7063		return(retval);
7064	}
7065
7066	if (softc->is_single)
7067		num_target_port_groups = 1;
7068	else
7069		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7070	num_target_ports = 0;
7071	mtx_lock(&softc->ctl_lock);
7072	STAILQ_FOREACH(port, &softc->port_list, links) {
7073		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7074			continue;
7075		if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7076			continue;
7077		num_target_ports++;
7078	}
7079	mtx_unlock(&softc->ctl_lock);
7080
7081	if (ext)
7082		total_len = sizeof(struct scsi_target_group_data_extended);
7083	else
7084		total_len = sizeof(struct scsi_target_group_data);
7085	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7086		num_target_port_groups +
7087	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7088
7089	alloc_len = scsi_4btoul(cdb->length);
7090
7091	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7092
7093	ctsio->kern_sg_entries = 0;
7094
7095	if (total_len < alloc_len) {
7096		ctsio->residual = alloc_len - total_len;
7097		ctsio->kern_data_len = total_len;
7098		ctsio->kern_total_len = total_len;
7099	} else {
7100		ctsio->residual = 0;
7101		ctsio->kern_data_len = alloc_len;
7102		ctsio->kern_total_len = alloc_len;
7103	}
7104	ctsio->kern_data_resid = 0;
7105	ctsio->kern_rel_offset = 0;
7106
7107	if (ext) {
7108		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7109		    ctsio->kern_data_ptr;
7110		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7111		rtg_ext_ptr->format_type = 0x10;
7112		rtg_ext_ptr->implicit_transition_time = 0;
7113		tpg_desc = &rtg_ext_ptr->groups[0];
7114	} else {
7115		rtg_ptr = (struct scsi_target_group_data *)
7116		    ctsio->kern_data_ptr;
7117		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7118		tpg_desc = &rtg_ptr->groups[0];
7119	}
7120
7121	mtx_lock(&softc->ctl_lock);
7122	pg = softc->port_min / softc->port_cnt;
7123	if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7124		gs = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7125	else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7126		gs = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7127	else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7128		gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7129	else
7130		gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7131	if (lun->flags & CTL_LUN_PRIMARY_SC) {
7132		os = gs;
7133		gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7134	} else
7135		os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7136	for (g = 0; g < num_target_port_groups; g++) {
7137		tpg_desc->pref_state = (g == pg) ? gs : os;
7138		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7139		    TPG_U_SUP | TPG_T_SUP;
7140		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7141		tpg_desc->status = TPG_IMPLICIT;
7142		pc = 0;
7143		STAILQ_FOREACH(port, &softc->port_list, links) {
7144			if (port->targ_port < g * softc->port_cnt ||
7145			    port->targ_port >= (g + 1) * softc->port_cnt)
7146				continue;
7147			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7148				continue;
7149			if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7150				continue;
7151			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7152			    relative_target_port_identifier);
7153			pc++;
7154		}
7155		tpg_desc->target_port_count = pc;
7156		tpg_desc = (struct scsi_target_port_group_descriptor *)
7157		    &tpg_desc->descriptors[pc];
7158	}
7159	mtx_unlock(&softc->ctl_lock);
7160
7161	ctl_set_success(ctsio);
7162	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7163	ctsio->be_move_done = ctl_config_move_done;
7164	ctl_datamove((union ctl_io *)ctsio);
7165	return(retval);
7166}
7167
7168int
7169ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7170{
7171	struct ctl_lun *lun;
7172	struct scsi_report_supported_opcodes *cdb;
7173	const struct ctl_cmd_entry *entry, *sentry;
7174	struct scsi_report_supported_opcodes_all *all;
7175	struct scsi_report_supported_opcodes_descr *descr;
7176	struct scsi_report_supported_opcodes_one *one;
7177	int retval;
7178	int alloc_len, total_len;
7179	int opcode, service_action, i, j, num;
7180
7181	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7182
7183	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7184	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7185
7186	retval = CTL_RETVAL_COMPLETE;
7187
7188	opcode = cdb->requested_opcode;
7189	service_action = scsi_2btoul(cdb->requested_service_action);
7190	switch (cdb->options & RSO_OPTIONS_MASK) {
7191	case RSO_OPTIONS_ALL:
7192		num = 0;
7193		for (i = 0; i < 256; i++) {
7194			entry = &ctl_cmd_table[i];
7195			if (entry->flags & CTL_CMD_FLAG_SA5) {
7196				for (j = 0; j < 32; j++) {
7197					sentry = &((const struct ctl_cmd_entry *)
7198					    entry->execute)[j];
7199					if (ctl_cmd_applicable(
7200					    lun->be_lun->lun_type, sentry))
7201						num++;
7202				}
7203			} else {
7204				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7205				    entry))
7206					num++;
7207			}
7208		}
7209		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7210		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7211		break;
7212	case RSO_OPTIONS_OC:
7213		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7214			ctl_set_invalid_field(/*ctsio*/ ctsio,
7215					      /*sks_valid*/ 1,
7216					      /*command*/ 1,
7217					      /*field*/ 2,
7218					      /*bit_valid*/ 1,
7219					      /*bit*/ 2);
7220			ctl_done((union ctl_io *)ctsio);
7221			return (CTL_RETVAL_COMPLETE);
7222		}
7223		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7224		break;
7225	case RSO_OPTIONS_OC_SA:
7226		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7227		    service_action >= 32) {
7228			ctl_set_invalid_field(/*ctsio*/ ctsio,
7229					      /*sks_valid*/ 1,
7230					      /*command*/ 1,
7231					      /*field*/ 2,
7232					      /*bit_valid*/ 1,
7233					      /*bit*/ 2);
7234			ctl_done((union ctl_io *)ctsio);
7235			return (CTL_RETVAL_COMPLETE);
7236		}
7237		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7238		break;
7239	default:
7240		ctl_set_invalid_field(/*ctsio*/ ctsio,
7241				      /*sks_valid*/ 1,
7242				      /*command*/ 1,
7243				      /*field*/ 2,
7244				      /*bit_valid*/ 1,
7245				      /*bit*/ 2);
7246		ctl_done((union ctl_io *)ctsio);
7247		return (CTL_RETVAL_COMPLETE);
7248	}
7249
7250	alloc_len = scsi_4btoul(cdb->length);
7251
7252	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7253
7254	ctsio->kern_sg_entries = 0;
7255
7256	if (total_len < alloc_len) {
7257		ctsio->residual = alloc_len - total_len;
7258		ctsio->kern_data_len = total_len;
7259		ctsio->kern_total_len = total_len;
7260	} else {
7261		ctsio->residual = 0;
7262		ctsio->kern_data_len = alloc_len;
7263		ctsio->kern_total_len = alloc_len;
7264	}
7265	ctsio->kern_data_resid = 0;
7266	ctsio->kern_rel_offset = 0;
7267
7268	switch (cdb->options & RSO_OPTIONS_MASK) {
7269	case RSO_OPTIONS_ALL:
7270		all = (struct scsi_report_supported_opcodes_all *)
7271		    ctsio->kern_data_ptr;
7272		num = 0;
7273		for (i = 0; i < 256; i++) {
7274			entry = &ctl_cmd_table[i];
7275			if (entry->flags & CTL_CMD_FLAG_SA5) {
7276				for (j = 0; j < 32; j++) {
7277					sentry = &((const struct ctl_cmd_entry *)
7278					    entry->execute)[j];
7279					if (!ctl_cmd_applicable(
7280					    lun->be_lun->lun_type, sentry))
7281						continue;
7282					descr = &all->descr[num++];
7283					descr->opcode = i;
7284					scsi_ulto2b(j, descr->service_action);
7285					descr->flags = RSO_SERVACTV;
7286					scsi_ulto2b(sentry->length,
7287					    descr->cdb_length);
7288				}
7289			} else {
7290				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7291				    entry))
7292					continue;
7293				descr = &all->descr[num++];
7294				descr->opcode = i;
7295				scsi_ulto2b(0, descr->service_action);
7296				descr->flags = 0;
7297				scsi_ulto2b(entry->length, descr->cdb_length);
7298			}
7299		}
7300		scsi_ulto4b(
7301		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7302		    all->length);
7303		break;
7304	case RSO_OPTIONS_OC:
7305		one = (struct scsi_report_supported_opcodes_one *)
7306		    ctsio->kern_data_ptr;
7307		entry = &ctl_cmd_table[opcode];
7308		goto fill_one;
7309	case RSO_OPTIONS_OC_SA:
7310		one = (struct scsi_report_supported_opcodes_one *)
7311		    ctsio->kern_data_ptr;
7312		entry = &ctl_cmd_table[opcode];
7313		entry = &((const struct ctl_cmd_entry *)
7314		    entry->execute)[service_action];
7315fill_one:
7316		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7317			one->support = 3;
7318			scsi_ulto2b(entry->length, one->cdb_length);
7319			one->cdb_usage[0] = opcode;
7320			memcpy(&one->cdb_usage[1], entry->usage,
7321			    entry->length - 1);
7322		} else
7323			one->support = 1;
7324		break;
7325	}
7326
7327	ctl_set_success(ctsio);
7328	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7329	ctsio->be_move_done = ctl_config_move_done;
7330	ctl_datamove((union ctl_io *)ctsio);
7331	return(retval);
7332}
7333
7334int
7335ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7336{
7337	struct scsi_report_supported_tmf *cdb;
7338	struct scsi_report_supported_tmf_data *data;
7339	int retval;
7340	int alloc_len, total_len;
7341
7342	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7343
7344	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7345
7346	retval = CTL_RETVAL_COMPLETE;
7347
7348	total_len = sizeof(struct scsi_report_supported_tmf_data);
7349	alloc_len = scsi_4btoul(cdb->length);
7350
7351	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7352
7353	ctsio->kern_sg_entries = 0;
7354
7355	if (total_len < alloc_len) {
7356		ctsio->residual = alloc_len - total_len;
7357		ctsio->kern_data_len = total_len;
7358		ctsio->kern_total_len = total_len;
7359	} else {
7360		ctsio->residual = 0;
7361		ctsio->kern_data_len = alloc_len;
7362		ctsio->kern_total_len = alloc_len;
7363	}
7364	ctsio->kern_data_resid = 0;
7365	ctsio->kern_rel_offset = 0;
7366
7367	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7368	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7369	    RST_TRS;
7370	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7371
7372	ctl_set_success(ctsio);
7373	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7374	ctsio->be_move_done = ctl_config_move_done;
7375	ctl_datamove((union ctl_io *)ctsio);
7376	return (retval);
7377}
7378
7379int
7380ctl_report_timestamp(struct ctl_scsiio *ctsio)
7381{
7382	struct scsi_report_timestamp *cdb;
7383	struct scsi_report_timestamp_data *data;
7384	struct timeval tv;
7385	int64_t timestamp;
7386	int retval;
7387	int alloc_len, total_len;
7388
7389	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7390
7391	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7392
7393	retval = CTL_RETVAL_COMPLETE;
7394
7395	total_len = sizeof(struct scsi_report_timestamp_data);
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	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7415	scsi_ulto2b(sizeof(*data) - 2, data->length);
7416	data->origin = RTS_ORIG_OUTSIDE;
7417	getmicrotime(&tv);
7418	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7419	scsi_ulto4b(timestamp >> 16, data->timestamp);
7420	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7421
7422	ctl_set_success(ctsio);
7423	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7424	ctsio->be_move_done = ctl_config_move_done;
7425	ctl_datamove((union ctl_io *)ctsio);
7426	return (retval);
7427}
7428
7429int
7430ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7431{
7432	struct scsi_per_res_in *cdb;
7433	int alloc_len, total_len = 0;
7434	/* struct scsi_per_res_in_rsrv in_data; */
7435	struct ctl_lun *lun;
7436	struct ctl_softc *softc;
7437	uint64_t key;
7438
7439	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7440
7441	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7442
7443	alloc_len = scsi_2btoul(cdb->length);
7444
7445	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7446	softc = lun->ctl_softc;
7447
7448retry:
7449	mtx_lock(&lun->lun_lock);
7450	switch (cdb->action) {
7451	case SPRI_RK: /* read keys */
7452		total_len = sizeof(struct scsi_per_res_in_keys) +
7453			lun->pr_key_count *
7454			sizeof(struct scsi_per_res_key);
7455		break;
7456	case SPRI_RR: /* read reservation */
7457		if (lun->flags & CTL_LUN_PR_RESERVED)
7458			total_len = sizeof(struct scsi_per_res_in_rsrv);
7459		else
7460			total_len = sizeof(struct scsi_per_res_in_header);
7461		break;
7462	case SPRI_RC: /* report capabilities */
7463		total_len = sizeof(struct scsi_per_res_cap);
7464		break;
7465	case SPRI_RS: /* read full status */
7466		total_len = sizeof(struct scsi_per_res_in_header) +
7467		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7468		    lun->pr_key_count;
7469		break;
7470	default:
7471		panic("Invalid PR type %x", cdb->action);
7472	}
7473	mtx_unlock(&lun->lun_lock);
7474
7475	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7476
7477	if (total_len < alloc_len) {
7478		ctsio->residual = alloc_len - total_len;
7479		ctsio->kern_data_len = total_len;
7480		ctsio->kern_total_len = total_len;
7481	} else {
7482		ctsio->residual = 0;
7483		ctsio->kern_data_len = alloc_len;
7484		ctsio->kern_total_len = alloc_len;
7485	}
7486
7487	ctsio->kern_data_resid = 0;
7488	ctsio->kern_rel_offset = 0;
7489	ctsio->kern_sg_entries = 0;
7490
7491	mtx_lock(&lun->lun_lock);
7492	switch (cdb->action) {
7493	case SPRI_RK: { // read keys
7494        struct scsi_per_res_in_keys *res_keys;
7495		int i, key_count;
7496
7497		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7498
7499		/*
7500		 * We had to drop the lock to allocate our buffer, which
7501		 * leaves time for someone to come in with another
7502		 * persistent reservation.  (That is unlikely, though,
7503		 * since this should be the only persistent reservation
7504		 * command active right now.)
7505		 */
7506		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7507		    (lun->pr_key_count *
7508		     sizeof(struct scsi_per_res_key)))){
7509			mtx_unlock(&lun->lun_lock);
7510			free(ctsio->kern_data_ptr, M_CTL);
7511			printf("%s: reservation length changed, retrying\n",
7512			       __func__);
7513			goto retry;
7514		}
7515
7516		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7517
7518		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7519			     lun->pr_key_count, res_keys->header.length);
7520
7521		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7522			if ((key = ctl_get_prkey(lun, i)) == 0)
7523				continue;
7524
7525			/*
7526			 * We used lun->pr_key_count to calculate the
7527			 * size to allocate.  If it turns out the number of
7528			 * initiators with the registered flag set is
7529			 * larger than that (i.e. they haven't been kept in
7530			 * sync), we've got a problem.
7531			 */
7532			if (key_count >= lun->pr_key_count) {
7533#ifdef NEEDTOPORT
7534				csevent_log(CSC_CTL | CSC_SHELF_SW |
7535					    CTL_PR_ERROR,
7536					    csevent_LogType_Fault,
7537					    csevent_AlertLevel_Yellow,
7538					    csevent_FRU_ShelfController,
7539					    csevent_FRU_Firmware,
7540				        csevent_FRU_Unknown,
7541					    "registered keys %d >= key "
7542					    "count %d", key_count,
7543					    lun->pr_key_count);
7544#endif
7545				key_count++;
7546				continue;
7547			}
7548			scsi_u64to8b(key, res_keys->keys[key_count].key);
7549			key_count++;
7550		}
7551		break;
7552	}
7553	case SPRI_RR: { // read reservation
7554		struct scsi_per_res_in_rsrv *res;
7555		int tmp_len, header_only;
7556
7557		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7558
7559		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7560
7561		if (lun->flags & CTL_LUN_PR_RESERVED)
7562		{
7563			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7564			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7565				    res->header.length);
7566			header_only = 0;
7567		} else {
7568			tmp_len = sizeof(struct scsi_per_res_in_header);
7569			scsi_ulto4b(0, res->header.length);
7570			header_only = 1;
7571		}
7572
7573		/*
7574		 * We had to drop the lock to allocate our buffer, which
7575		 * leaves time for someone to come in with another
7576		 * persistent reservation.  (That is unlikely, though,
7577		 * since this should be the only persistent reservation
7578		 * command active right now.)
7579		 */
7580		if (tmp_len != total_len) {
7581			mtx_unlock(&lun->lun_lock);
7582			free(ctsio->kern_data_ptr, M_CTL);
7583			printf("%s: reservation status changed, retrying\n",
7584			       __func__);
7585			goto retry;
7586		}
7587
7588		/*
7589		 * No reservation held, so we're done.
7590		 */
7591		if (header_only != 0)
7592			break;
7593
7594		/*
7595		 * If the registration is an All Registrants type, the key
7596		 * is 0, since it doesn't really matter.
7597		 */
7598		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7599			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7600			    res->data.reservation);
7601		}
7602		res->data.scopetype = lun->res_type;
7603		break;
7604	}
7605	case SPRI_RC:     //report capabilities
7606	{
7607		struct scsi_per_res_cap *res_cap;
7608		uint16_t type_mask;
7609
7610		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7611		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7612		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7613		type_mask = SPRI_TM_WR_EX_AR |
7614			    SPRI_TM_EX_AC_RO |
7615			    SPRI_TM_WR_EX_RO |
7616			    SPRI_TM_EX_AC |
7617			    SPRI_TM_WR_EX |
7618			    SPRI_TM_EX_AC_AR;
7619		scsi_ulto2b(type_mask, res_cap->type_mask);
7620		break;
7621	}
7622	case SPRI_RS: { // read full status
7623		struct scsi_per_res_in_full *res_status;
7624		struct scsi_per_res_in_full_desc *res_desc;
7625		struct ctl_port *port;
7626		int i, len;
7627
7628		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7629
7630		/*
7631		 * We had to drop the lock to allocate our buffer, which
7632		 * leaves time for someone to come in with another
7633		 * persistent reservation.  (That is unlikely, though,
7634		 * since this should be the only persistent reservation
7635		 * command active right now.)
7636		 */
7637		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7638		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7639		     lun->pr_key_count)){
7640			mtx_unlock(&lun->lun_lock);
7641			free(ctsio->kern_data_ptr, M_CTL);
7642			printf("%s: reservation length changed, retrying\n",
7643			       __func__);
7644			goto retry;
7645		}
7646
7647		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7648
7649		res_desc = &res_status->desc[0];
7650		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7651			if ((key = ctl_get_prkey(lun, i)) == 0)
7652				continue;
7653
7654			scsi_u64to8b(key, res_desc->res_key.key);
7655			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7656			    (lun->pr_res_idx == i ||
7657			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7658				res_desc->flags = SPRI_FULL_R_HOLDER;
7659				res_desc->scopetype = lun->res_type;
7660			}
7661			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7662			    res_desc->rel_trgt_port_id);
7663			len = 0;
7664			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7665			if (port != NULL)
7666				len = ctl_create_iid(port,
7667				    i % CTL_MAX_INIT_PER_PORT,
7668				    res_desc->transport_id);
7669			scsi_ulto4b(len, res_desc->additional_length);
7670			res_desc = (struct scsi_per_res_in_full_desc *)
7671			    &res_desc->transport_id[len];
7672		}
7673		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7674		    res_status->header.length);
7675		break;
7676	}
7677	default:
7678		/*
7679		 * This is a bug, because we just checked for this above,
7680		 * and should have returned an error.
7681		 */
7682		panic("Invalid PR type %x", cdb->action);
7683		break; /* NOTREACHED */
7684	}
7685	mtx_unlock(&lun->lun_lock);
7686
7687	ctl_set_success(ctsio);
7688	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7689	ctsio->be_move_done = ctl_config_move_done;
7690	ctl_datamove((union ctl_io *)ctsio);
7691	return (CTL_RETVAL_COMPLETE);
7692}
7693
7694/*
7695 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7696 * it should return.
7697 */
7698static int
7699ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7700		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7701		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7702		struct scsi_per_res_out_parms* param)
7703{
7704	union ctl_ha_msg persis_io;
7705	int i;
7706
7707	mtx_lock(&lun->lun_lock);
7708	if (sa_res_key == 0) {
7709		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7710			/* validate scope and type */
7711			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7712			     SPR_LU_SCOPE) {
7713				mtx_unlock(&lun->lun_lock);
7714				ctl_set_invalid_field(/*ctsio*/ ctsio,
7715						      /*sks_valid*/ 1,
7716						      /*command*/ 1,
7717						      /*field*/ 2,
7718						      /*bit_valid*/ 1,
7719						      /*bit*/ 4);
7720				ctl_done((union ctl_io *)ctsio);
7721				return (1);
7722			}
7723
7724		        if (type>8 || type==2 || type==4 || type==0) {
7725				mtx_unlock(&lun->lun_lock);
7726				ctl_set_invalid_field(/*ctsio*/ ctsio,
7727       	           				      /*sks_valid*/ 1,
7728						      /*command*/ 1,
7729						      /*field*/ 2,
7730						      /*bit_valid*/ 1,
7731						      /*bit*/ 0);
7732				ctl_done((union ctl_io *)ctsio);
7733				return (1);
7734		        }
7735
7736			/*
7737			 * Unregister everybody else and build UA for
7738			 * them
7739			 */
7740			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7741				if (i == residx || ctl_get_prkey(lun, i) == 0)
7742					continue;
7743
7744				ctl_clr_prkey(lun, i);
7745				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7746			}
7747			lun->pr_key_count = 1;
7748			lun->res_type = type;
7749			if (lun->res_type != SPR_TYPE_WR_EX_AR
7750			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7751				lun->pr_res_idx = residx;
7752			lun->PRGeneration++;
7753			mtx_unlock(&lun->lun_lock);
7754
7755			/* send msg to other side */
7756			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7757			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7758			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7759			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7760			persis_io.pr.pr_info.res_type = type;
7761			memcpy(persis_io.pr.pr_info.sa_res_key,
7762			       param->serv_act_res_key,
7763			       sizeof(param->serv_act_res_key));
7764			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7765			    sizeof(persis_io.pr), M_WAITOK);
7766		} else {
7767			/* not all registrants */
7768			mtx_unlock(&lun->lun_lock);
7769			free(ctsio->kern_data_ptr, M_CTL);
7770			ctl_set_invalid_field(ctsio,
7771					      /*sks_valid*/ 1,
7772					      /*command*/ 0,
7773					      /*field*/ 8,
7774					      /*bit_valid*/ 0,
7775					      /*bit*/ 0);
7776			ctl_done((union ctl_io *)ctsio);
7777			return (1);
7778		}
7779	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7780		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7781		int found = 0;
7782
7783		if (res_key == sa_res_key) {
7784			/* special case */
7785			/*
7786			 * The spec implies this is not good but doesn't
7787			 * say what to do. There are two choices either
7788			 * generate a res conflict or check condition
7789			 * with illegal field in parameter data. Since
7790			 * that is what is done when the sa_res_key is
7791			 * zero I'll take that approach since this has
7792			 * to do with the sa_res_key.
7793			 */
7794			mtx_unlock(&lun->lun_lock);
7795			free(ctsio->kern_data_ptr, M_CTL);
7796			ctl_set_invalid_field(ctsio,
7797					      /*sks_valid*/ 1,
7798					      /*command*/ 0,
7799					      /*field*/ 8,
7800					      /*bit_valid*/ 0,
7801					      /*bit*/ 0);
7802			ctl_done((union ctl_io *)ctsio);
7803			return (1);
7804		}
7805
7806		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7807			if (ctl_get_prkey(lun, i) != sa_res_key)
7808				continue;
7809
7810			found = 1;
7811			ctl_clr_prkey(lun, i);
7812			lun->pr_key_count--;
7813			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7814		}
7815		if (!found) {
7816			mtx_unlock(&lun->lun_lock);
7817			free(ctsio->kern_data_ptr, M_CTL);
7818			ctl_set_reservation_conflict(ctsio);
7819			ctl_done((union ctl_io *)ctsio);
7820			return (CTL_RETVAL_COMPLETE);
7821		}
7822		lun->PRGeneration++;
7823		mtx_unlock(&lun->lun_lock);
7824
7825		/* send msg to other side */
7826		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7827		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7828		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7829		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7830		persis_io.pr.pr_info.res_type = type;
7831		memcpy(persis_io.pr.pr_info.sa_res_key,
7832		       param->serv_act_res_key,
7833		       sizeof(param->serv_act_res_key));
7834		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7835		    sizeof(persis_io.pr), M_WAITOK);
7836	} else {
7837		/* Reserved but not all registrants */
7838		/* sa_res_key is res holder */
7839		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7840			/* validate scope and type */
7841			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7842			     SPR_LU_SCOPE) {
7843				mtx_unlock(&lun->lun_lock);
7844				ctl_set_invalid_field(/*ctsio*/ ctsio,
7845						      /*sks_valid*/ 1,
7846						      /*command*/ 1,
7847						      /*field*/ 2,
7848						      /*bit_valid*/ 1,
7849						      /*bit*/ 4);
7850				ctl_done((union ctl_io *)ctsio);
7851				return (1);
7852			}
7853
7854			if (type>8 || type==2 || type==4 || type==0) {
7855				mtx_unlock(&lun->lun_lock);
7856				ctl_set_invalid_field(/*ctsio*/ ctsio,
7857						      /*sks_valid*/ 1,
7858						      /*command*/ 1,
7859						      /*field*/ 2,
7860						      /*bit_valid*/ 1,
7861						      /*bit*/ 0);
7862				ctl_done((union ctl_io *)ctsio);
7863				return (1);
7864			}
7865
7866			/*
7867			 * Do the following:
7868			 * if sa_res_key != res_key remove all
7869			 * registrants w/sa_res_key and generate UA
7870			 * for these registrants(Registrations
7871			 * Preempted) if it wasn't an exclusive
7872			 * reservation generate UA(Reservations
7873			 * Preempted) for all other registered nexuses
7874			 * if the type has changed. Establish the new
7875			 * reservation and holder. If res_key and
7876			 * sa_res_key are the same do the above
7877			 * except don't unregister the res holder.
7878			 */
7879
7880			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7881				if (i == residx || ctl_get_prkey(lun, i) == 0)
7882					continue;
7883
7884				if (sa_res_key == ctl_get_prkey(lun, i)) {
7885					ctl_clr_prkey(lun, i);
7886					lun->pr_key_count--;
7887					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7888				} else if (type != lun->res_type
7889					&& (lun->res_type == SPR_TYPE_WR_EX_RO
7890					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
7891					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
7892				}
7893			}
7894			lun->res_type = type;
7895			if (lun->res_type != SPR_TYPE_WR_EX_AR
7896			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7897				lun->pr_res_idx = residx;
7898			else
7899				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7900			lun->PRGeneration++;
7901			mtx_unlock(&lun->lun_lock);
7902
7903			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7904			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7905			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7906			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7907			persis_io.pr.pr_info.res_type = type;
7908			memcpy(persis_io.pr.pr_info.sa_res_key,
7909			       param->serv_act_res_key,
7910			       sizeof(param->serv_act_res_key));
7911			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7912			    sizeof(persis_io.pr), M_WAITOK);
7913		} else {
7914			/*
7915			 * sa_res_key is not the res holder just
7916			 * remove registrants
7917			 */
7918			int found=0;
7919
7920			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7921				if (sa_res_key != ctl_get_prkey(lun, i))
7922					continue;
7923
7924				found = 1;
7925				ctl_clr_prkey(lun, i);
7926				lun->pr_key_count--;
7927				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7928			}
7929
7930			if (!found) {
7931				mtx_unlock(&lun->lun_lock);
7932				free(ctsio->kern_data_ptr, M_CTL);
7933				ctl_set_reservation_conflict(ctsio);
7934				ctl_done((union ctl_io *)ctsio);
7935		        	return (1);
7936			}
7937			lun->PRGeneration++;
7938			mtx_unlock(&lun->lun_lock);
7939
7940			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7941			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7942			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7943			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7944			persis_io.pr.pr_info.res_type = type;
7945			memcpy(persis_io.pr.pr_info.sa_res_key,
7946			       param->serv_act_res_key,
7947			       sizeof(param->serv_act_res_key));
7948			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7949			    sizeof(persis_io.pr), M_WAITOK);
7950		}
7951	}
7952	return (0);
7953}
7954
7955static void
7956ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
7957{
7958	uint64_t sa_res_key;
7959	int i;
7960
7961	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
7962
7963	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7964	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
7965	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
7966		if (sa_res_key == 0) {
7967			/*
7968			 * Unregister everybody else and build UA for
7969			 * them
7970			 */
7971			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7972				if (i == msg->pr.pr_info.residx ||
7973				    ctl_get_prkey(lun, i) == 0)
7974					continue;
7975
7976				ctl_clr_prkey(lun, i);
7977				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7978			}
7979
7980			lun->pr_key_count = 1;
7981			lun->res_type = msg->pr.pr_info.res_type;
7982			if (lun->res_type != SPR_TYPE_WR_EX_AR
7983			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7984				lun->pr_res_idx = msg->pr.pr_info.residx;
7985		} else {
7986		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7987				if (sa_res_key == ctl_get_prkey(lun, i))
7988					continue;
7989
7990				ctl_clr_prkey(lun, i);
7991				lun->pr_key_count--;
7992				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7993			}
7994		}
7995	} else {
7996		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7997			if (i == msg->pr.pr_info.residx ||
7998			    ctl_get_prkey(lun, i) == 0)
7999				continue;
8000
8001			if (sa_res_key == ctl_get_prkey(lun, i)) {
8002				ctl_clr_prkey(lun, i);
8003				lun->pr_key_count--;
8004				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8005			} else if (msg->pr.pr_info.res_type != lun->res_type
8006				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8007				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8008				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8009			}
8010		}
8011		lun->res_type = msg->pr.pr_info.res_type;
8012		if (lun->res_type != SPR_TYPE_WR_EX_AR
8013		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8014			lun->pr_res_idx = msg->pr.pr_info.residx;
8015		else
8016			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8017	}
8018	lun->PRGeneration++;
8019
8020}
8021
8022
8023int
8024ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8025{
8026	int retval;
8027	u_int32_t param_len;
8028	struct scsi_per_res_out *cdb;
8029	struct ctl_lun *lun;
8030	struct scsi_per_res_out_parms* param;
8031	struct ctl_softc *softc;
8032	uint32_t residx;
8033	uint64_t res_key, sa_res_key, key;
8034	uint8_t type;
8035	union ctl_ha_msg persis_io;
8036	int    i;
8037
8038	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8039
8040	retval = CTL_RETVAL_COMPLETE;
8041
8042	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8043	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8044	softc = lun->ctl_softc;
8045
8046	/*
8047	 * We only support whole-LUN scope.  The scope & type are ignored for
8048	 * register, register and ignore existing key and clear.
8049	 * We sometimes ignore scope and type on preempts too!!
8050	 * Verify reservation type here as well.
8051	 */
8052	type = cdb->scope_type & SPR_TYPE_MASK;
8053	if ((cdb->action == SPRO_RESERVE)
8054	 || (cdb->action == SPRO_RELEASE)) {
8055		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8056			ctl_set_invalid_field(/*ctsio*/ ctsio,
8057					      /*sks_valid*/ 1,
8058					      /*command*/ 1,
8059					      /*field*/ 2,
8060					      /*bit_valid*/ 1,
8061					      /*bit*/ 4);
8062			ctl_done((union ctl_io *)ctsio);
8063			return (CTL_RETVAL_COMPLETE);
8064		}
8065
8066		if (type>8 || type==2 || type==4 || type==0) {
8067			ctl_set_invalid_field(/*ctsio*/ ctsio,
8068					      /*sks_valid*/ 1,
8069					      /*command*/ 1,
8070					      /*field*/ 2,
8071					      /*bit_valid*/ 1,
8072					      /*bit*/ 0);
8073			ctl_done((union ctl_io *)ctsio);
8074			return (CTL_RETVAL_COMPLETE);
8075		}
8076	}
8077
8078	param_len = scsi_4btoul(cdb->length);
8079
8080	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8081		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8082		ctsio->kern_data_len = param_len;
8083		ctsio->kern_total_len = param_len;
8084		ctsio->kern_data_resid = 0;
8085		ctsio->kern_rel_offset = 0;
8086		ctsio->kern_sg_entries = 0;
8087		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8088		ctsio->be_move_done = ctl_config_move_done;
8089		ctl_datamove((union ctl_io *)ctsio);
8090
8091		return (CTL_RETVAL_COMPLETE);
8092	}
8093
8094	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8095
8096	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8097	res_key = scsi_8btou64(param->res_key.key);
8098	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8099
8100	/*
8101	 * Validate the reservation key here except for SPRO_REG_IGNO
8102	 * This must be done for all other service actions
8103	 */
8104	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8105		mtx_lock(&lun->lun_lock);
8106		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8107			if (res_key != key) {
8108				/*
8109				 * The current key passed in doesn't match
8110				 * the one the initiator previously
8111				 * registered.
8112				 */
8113				mtx_unlock(&lun->lun_lock);
8114				free(ctsio->kern_data_ptr, M_CTL);
8115				ctl_set_reservation_conflict(ctsio);
8116				ctl_done((union ctl_io *)ctsio);
8117				return (CTL_RETVAL_COMPLETE);
8118			}
8119		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8120			/*
8121			 * We are not registered
8122			 */
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		} else if (res_key != 0) {
8129			/*
8130			 * We are not registered and trying to register but
8131			 * the register key isn't zero.
8132			 */
8133			mtx_unlock(&lun->lun_lock);
8134			free(ctsio->kern_data_ptr, M_CTL);
8135			ctl_set_reservation_conflict(ctsio);
8136			ctl_done((union ctl_io *)ctsio);
8137			return (CTL_RETVAL_COMPLETE);
8138		}
8139		mtx_unlock(&lun->lun_lock);
8140	}
8141
8142	switch (cdb->action & SPRO_ACTION_MASK) {
8143	case SPRO_REGISTER:
8144	case SPRO_REG_IGNO: {
8145
8146#if 0
8147		printf("Registration received\n");
8148#endif
8149
8150		/*
8151		 * We don't support any of these options, as we report in
8152		 * the read capabilities request (see
8153		 * ctl_persistent_reserve_in(), above).
8154		 */
8155		if ((param->flags & SPR_SPEC_I_PT)
8156		 || (param->flags & SPR_ALL_TG_PT)
8157		 || (param->flags & SPR_APTPL)) {
8158			int bit_ptr;
8159
8160			if (param->flags & SPR_APTPL)
8161				bit_ptr = 0;
8162			else if (param->flags & SPR_ALL_TG_PT)
8163				bit_ptr = 2;
8164			else /* SPR_SPEC_I_PT */
8165				bit_ptr = 3;
8166
8167			free(ctsio->kern_data_ptr, M_CTL);
8168			ctl_set_invalid_field(ctsio,
8169					      /*sks_valid*/ 1,
8170					      /*command*/ 0,
8171					      /*field*/ 20,
8172					      /*bit_valid*/ 1,
8173					      /*bit*/ bit_ptr);
8174			ctl_done((union ctl_io *)ctsio);
8175			return (CTL_RETVAL_COMPLETE);
8176		}
8177
8178		mtx_lock(&lun->lun_lock);
8179
8180		/*
8181		 * The initiator wants to clear the
8182		 * key/unregister.
8183		 */
8184		if (sa_res_key == 0) {
8185			if ((res_key == 0
8186			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8187			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8188			  && ctl_get_prkey(lun, residx) == 0)) {
8189				mtx_unlock(&lun->lun_lock);
8190				goto done;
8191			}
8192
8193			ctl_clr_prkey(lun, residx);
8194			lun->pr_key_count--;
8195
8196			if (residx == lun->pr_res_idx) {
8197				lun->flags &= ~CTL_LUN_PR_RESERVED;
8198				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8199
8200				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8201				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8202				 && lun->pr_key_count) {
8203					/*
8204					 * If the reservation is a registrants
8205					 * only type we need to generate a UA
8206					 * for other registered inits.  The
8207					 * sense code should be RESERVATIONS
8208					 * RELEASED
8209					 */
8210
8211					for (i = softc->init_min; i < softc->init_max; i++){
8212						if (ctl_get_prkey(lun, i) == 0)
8213							continue;
8214						ctl_est_ua(lun, i,
8215						    CTL_UA_RES_RELEASE);
8216					}
8217				}
8218				lun->res_type = 0;
8219			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8220				if (lun->pr_key_count==0) {
8221					lun->flags &= ~CTL_LUN_PR_RESERVED;
8222					lun->res_type = 0;
8223					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8224				}
8225			}
8226			lun->PRGeneration++;
8227			mtx_unlock(&lun->lun_lock);
8228
8229			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8230			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8231			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8232			persis_io.pr.pr_info.residx = residx;
8233			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8234			    sizeof(persis_io.pr), M_WAITOK);
8235		} else /* sa_res_key != 0 */ {
8236
8237			/*
8238			 * If we aren't registered currently then increment
8239			 * the key count and set the registered flag.
8240			 */
8241			ctl_alloc_prkey(lun, residx);
8242			if (ctl_get_prkey(lun, residx) == 0)
8243				lun->pr_key_count++;
8244			ctl_set_prkey(lun, residx, sa_res_key);
8245			lun->PRGeneration++;
8246			mtx_unlock(&lun->lun_lock);
8247
8248			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8249			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8250			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8251			persis_io.pr.pr_info.residx = residx;
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		break;
8260	}
8261	case SPRO_RESERVE:
8262#if 0
8263                printf("Reserve executed type %d\n", type);
8264#endif
8265		mtx_lock(&lun->lun_lock);
8266		if (lun->flags & CTL_LUN_PR_RESERVED) {
8267			/*
8268			 * if this isn't the reservation holder and it's
8269			 * not a "all registrants" type or if the type is
8270			 * different then we have a conflict
8271			 */
8272			if ((lun->pr_res_idx != residx
8273			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8274			 || lun->res_type != type) {
8275				mtx_unlock(&lun->lun_lock);
8276				free(ctsio->kern_data_ptr, M_CTL);
8277				ctl_set_reservation_conflict(ctsio);
8278				ctl_done((union ctl_io *)ctsio);
8279				return (CTL_RETVAL_COMPLETE);
8280			}
8281			mtx_unlock(&lun->lun_lock);
8282		} else /* create a reservation */ {
8283			/*
8284			 * If it's not an "all registrants" type record
8285			 * reservation holder
8286			 */
8287			if (type != SPR_TYPE_WR_EX_AR
8288			 && type != SPR_TYPE_EX_AC_AR)
8289				lun->pr_res_idx = residx; /* Res holder */
8290			else
8291				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8292
8293			lun->flags |= CTL_LUN_PR_RESERVED;
8294			lun->res_type = type;
8295
8296			mtx_unlock(&lun->lun_lock);
8297
8298			/* send msg to other side */
8299			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8300			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8301			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8302			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8303			persis_io.pr.pr_info.res_type = type;
8304			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8305			    sizeof(persis_io.pr), M_WAITOK);
8306		}
8307		break;
8308
8309	case SPRO_RELEASE:
8310		mtx_lock(&lun->lun_lock);
8311		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8312			/* No reservation exists return good status */
8313			mtx_unlock(&lun->lun_lock);
8314			goto done;
8315		}
8316		/*
8317		 * Is this nexus a reservation holder?
8318		 */
8319		if (lun->pr_res_idx != residx
8320		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8321			/*
8322			 * not a res holder return good status but
8323			 * do nothing
8324			 */
8325			mtx_unlock(&lun->lun_lock);
8326			goto done;
8327		}
8328
8329		if (lun->res_type != type) {
8330			mtx_unlock(&lun->lun_lock);
8331			free(ctsio->kern_data_ptr, M_CTL);
8332			ctl_set_illegal_pr_release(ctsio);
8333			ctl_done((union ctl_io *)ctsio);
8334			return (CTL_RETVAL_COMPLETE);
8335		}
8336
8337		/* okay to release */
8338		lun->flags &= ~CTL_LUN_PR_RESERVED;
8339		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8340		lun->res_type = 0;
8341
8342		/*
8343		 * if this isn't an exclusive access
8344		 * res generate UA for all other
8345		 * registrants.
8346		 */
8347		if (type != SPR_TYPE_EX_AC
8348		 && type != SPR_TYPE_WR_EX) {
8349			for (i = softc->init_min; i < softc->init_max; i++) {
8350				if (i == residx || ctl_get_prkey(lun, i) == 0)
8351					continue;
8352				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8353			}
8354		}
8355		mtx_unlock(&lun->lun_lock);
8356
8357		/* Send msg to other side */
8358		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8359		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8360		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8361		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8362		     sizeof(persis_io.pr), M_WAITOK);
8363		break;
8364
8365	case SPRO_CLEAR:
8366		/* send msg to other side */
8367
8368		mtx_lock(&lun->lun_lock);
8369		lun->flags &= ~CTL_LUN_PR_RESERVED;
8370		lun->res_type = 0;
8371		lun->pr_key_count = 0;
8372		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8373
8374		ctl_clr_prkey(lun, residx);
8375		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8376			if (ctl_get_prkey(lun, i) != 0) {
8377				ctl_clr_prkey(lun, i);
8378				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8379			}
8380		lun->PRGeneration++;
8381		mtx_unlock(&lun->lun_lock);
8382
8383		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8384		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8385		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8386		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8387		     sizeof(persis_io.pr), M_WAITOK);
8388		break;
8389
8390	case SPRO_PREEMPT:
8391	case SPRO_PRE_ABO: {
8392		int nretval;
8393
8394		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8395					  residx, ctsio, cdb, param);
8396		if (nretval != 0)
8397			return (CTL_RETVAL_COMPLETE);
8398		break;
8399	}
8400	default:
8401		panic("Invalid PR type %x", cdb->action);
8402	}
8403
8404done:
8405	free(ctsio->kern_data_ptr, M_CTL);
8406	ctl_set_success(ctsio);
8407	ctl_done((union ctl_io *)ctsio);
8408
8409	return (retval);
8410}
8411
8412/*
8413 * This routine is for handling a message from the other SC pertaining to
8414 * persistent reserve out. All the error checking will have been done
8415 * so only perorming the action need be done here to keep the two
8416 * in sync.
8417 */
8418static void
8419ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8420{
8421	struct ctl_lun *lun;
8422	struct ctl_softc *softc;
8423	int i;
8424	uint32_t residx, targ_lun;
8425
8426	softc = control_softc;
8427	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8428	mtx_lock(&softc->ctl_lock);
8429	if ((targ_lun >= CTL_MAX_LUNS) ||
8430	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
8431		mtx_unlock(&softc->ctl_lock);
8432		return;
8433	}
8434	mtx_lock(&lun->lun_lock);
8435	mtx_unlock(&softc->ctl_lock);
8436	if (lun->flags & CTL_LUN_DISABLED) {
8437		mtx_unlock(&lun->lun_lock);
8438		return;
8439	}
8440	residx = ctl_get_initindex(&msg->hdr.nexus);
8441	switch(msg->pr.pr_info.action) {
8442	case CTL_PR_REG_KEY:
8443		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8444		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8445			lun->pr_key_count++;
8446		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8447		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8448		lun->PRGeneration++;
8449		break;
8450
8451	case CTL_PR_UNREG_KEY:
8452		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8453		lun->pr_key_count--;
8454
8455		/* XXX Need to see if the reservation has been released */
8456		/* if so do we need to generate UA? */
8457		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8458			lun->flags &= ~CTL_LUN_PR_RESERVED;
8459			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8460
8461			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8462			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8463			 && lun->pr_key_count) {
8464				/*
8465				 * If the reservation is a registrants
8466				 * only type we need to generate a UA
8467				 * for other registered inits.  The
8468				 * sense code should be RESERVATIONS
8469				 * RELEASED
8470				 */
8471
8472				for (i = softc->init_min; i < softc->init_max; i++) {
8473					if (ctl_get_prkey(lun, i) == 0)
8474						continue;
8475
8476					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8477				}
8478			}
8479			lun->res_type = 0;
8480		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8481			if (lun->pr_key_count==0) {
8482				lun->flags &= ~CTL_LUN_PR_RESERVED;
8483				lun->res_type = 0;
8484				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8485			}
8486		}
8487		lun->PRGeneration++;
8488		break;
8489
8490	case CTL_PR_RESERVE:
8491		lun->flags |= CTL_LUN_PR_RESERVED;
8492		lun->res_type = msg->pr.pr_info.res_type;
8493		lun->pr_res_idx = msg->pr.pr_info.residx;
8494
8495		break;
8496
8497	case CTL_PR_RELEASE:
8498		/*
8499		 * if this isn't an exclusive access res generate UA for all
8500		 * other registrants.
8501		 */
8502		if (lun->res_type != SPR_TYPE_EX_AC
8503		 && lun->res_type != SPR_TYPE_WR_EX) {
8504			for (i = softc->init_min; i < softc->init_max; i++)
8505				if (i == residx || ctl_get_prkey(lun, i) == 0)
8506					continue;
8507				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8508		}
8509
8510		lun->flags &= ~CTL_LUN_PR_RESERVED;
8511		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8512		lun->res_type = 0;
8513		break;
8514
8515	case CTL_PR_PREEMPT:
8516		ctl_pro_preempt_other(lun, msg);
8517		break;
8518	case CTL_PR_CLEAR:
8519		lun->flags &= ~CTL_LUN_PR_RESERVED;
8520		lun->res_type = 0;
8521		lun->pr_key_count = 0;
8522		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8523
8524		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8525			if (ctl_get_prkey(lun, i) == 0)
8526				continue;
8527			ctl_clr_prkey(lun, i);
8528			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8529		}
8530		lun->PRGeneration++;
8531		break;
8532	}
8533
8534	mtx_unlock(&lun->lun_lock);
8535}
8536
8537int
8538ctl_read_write(struct ctl_scsiio *ctsio)
8539{
8540	struct ctl_lun *lun;
8541	struct ctl_lba_len_flags *lbalen;
8542	uint64_t lba;
8543	uint32_t num_blocks;
8544	int flags, retval;
8545	int isread;
8546
8547	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8548
8549	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8550
8551	flags = 0;
8552	retval = CTL_RETVAL_COMPLETE;
8553
8554	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8555	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8556	switch (ctsio->cdb[0]) {
8557	case READ_6:
8558	case WRITE_6: {
8559		struct scsi_rw_6 *cdb;
8560
8561		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8562
8563		lba = scsi_3btoul(cdb->addr);
8564		/* only 5 bits are valid in the most significant address byte */
8565		lba &= 0x1fffff;
8566		num_blocks = cdb->length;
8567		/*
8568		 * This is correct according to SBC-2.
8569		 */
8570		if (num_blocks == 0)
8571			num_blocks = 256;
8572		break;
8573	}
8574	case READ_10:
8575	case WRITE_10: {
8576		struct scsi_rw_10 *cdb;
8577
8578		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8579		if (cdb->byte2 & SRW10_FUA)
8580			flags |= CTL_LLF_FUA;
8581		if (cdb->byte2 & SRW10_DPO)
8582			flags |= CTL_LLF_DPO;
8583		lba = scsi_4btoul(cdb->addr);
8584		num_blocks = scsi_2btoul(cdb->length);
8585		break;
8586	}
8587	case WRITE_VERIFY_10: {
8588		struct scsi_write_verify_10 *cdb;
8589
8590		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8591		flags |= CTL_LLF_FUA;
8592		if (cdb->byte2 & SWV_DPO)
8593			flags |= CTL_LLF_DPO;
8594		lba = scsi_4btoul(cdb->addr);
8595		num_blocks = scsi_2btoul(cdb->length);
8596		break;
8597	}
8598	case READ_12:
8599	case WRITE_12: {
8600		struct scsi_rw_12 *cdb;
8601
8602		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8603		if (cdb->byte2 & SRW12_FUA)
8604			flags |= CTL_LLF_FUA;
8605		if (cdb->byte2 & SRW12_DPO)
8606			flags |= CTL_LLF_DPO;
8607		lba = scsi_4btoul(cdb->addr);
8608		num_blocks = scsi_4btoul(cdb->length);
8609		break;
8610	}
8611	case WRITE_VERIFY_12: {
8612		struct scsi_write_verify_12 *cdb;
8613
8614		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8615		flags |= CTL_LLF_FUA;
8616		if (cdb->byte2 & SWV_DPO)
8617			flags |= CTL_LLF_DPO;
8618		lba = scsi_4btoul(cdb->addr);
8619		num_blocks = scsi_4btoul(cdb->length);
8620		break;
8621	}
8622	case READ_16:
8623	case WRITE_16: {
8624		struct scsi_rw_16 *cdb;
8625
8626		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8627		if (cdb->byte2 & SRW12_FUA)
8628			flags |= CTL_LLF_FUA;
8629		if (cdb->byte2 & SRW12_DPO)
8630			flags |= CTL_LLF_DPO;
8631		lba = scsi_8btou64(cdb->addr);
8632		num_blocks = scsi_4btoul(cdb->length);
8633		break;
8634	}
8635	case WRITE_ATOMIC_16: {
8636		struct scsi_rw_16 *cdb;
8637
8638		if (lun->be_lun->atomicblock == 0) {
8639			ctl_set_invalid_opcode(ctsio);
8640			ctl_done((union ctl_io *)ctsio);
8641			return (CTL_RETVAL_COMPLETE);
8642		}
8643
8644		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8645		if (cdb->byte2 & SRW12_FUA)
8646			flags |= CTL_LLF_FUA;
8647		if (cdb->byte2 & SRW12_DPO)
8648			flags |= CTL_LLF_DPO;
8649		lba = scsi_8btou64(cdb->addr);
8650		num_blocks = scsi_4btoul(cdb->length);
8651		if (num_blocks > lun->be_lun->atomicblock) {
8652			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8653			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8654			    /*bit*/ 0);
8655			ctl_done((union ctl_io *)ctsio);
8656			return (CTL_RETVAL_COMPLETE);
8657		}
8658		break;
8659	}
8660	case WRITE_VERIFY_16: {
8661		struct scsi_write_verify_16 *cdb;
8662
8663		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8664		flags |= CTL_LLF_FUA;
8665		if (cdb->byte2 & SWV_DPO)
8666			flags |= CTL_LLF_DPO;
8667		lba = scsi_8btou64(cdb->addr);
8668		num_blocks = scsi_4btoul(cdb->length);
8669		break;
8670	}
8671	default:
8672		/*
8673		 * We got a command we don't support.  This shouldn't
8674		 * happen, commands should be filtered out above us.
8675		 */
8676		ctl_set_invalid_opcode(ctsio);
8677		ctl_done((union ctl_io *)ctsio);
8678
8679		return (CTL_RETVAL_COMPLETE);
8680		break; /* NOTREACHED */
8681	}
8682
8683	/*
8684	 * The first check is to make sure we're in bounds, the second
8685	 * check is to catch wrap-around problems.  If the lba + num blocks
8686	 * is less than the lba, then we've wrapped around and the block
8687	 * range is invalid anyway.
8688	 */
8689	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8690	 || ((lba + num_blocks) < lba)) {
8691		ctl_set_lba_out_of_range(ctsio);
8692		ctl_done((union ctl_io *)ctsio);
8693		return (CTL_RETVAL_COMPLETE);
8694	}
8695
8696	/*
8697	 * According to SBC-3, a transfer length of 0 is not an error.
8698	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8699	 * translates to 256 blocks for those commands.
8700	 */
8701	if (num_blocks == 0) {
8702		ctl_set_success(ctsio);
8703		ctl_done((union ctl_io *)ctsio);
8704		return (CTL_RETVAL_COMPLETE);
8705	}
8706
8707	/* Set FUA and/or DPO if caches are disabled. */
8708	if (isread) {
8709		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8710		    SCP_RCD) != 0)
8711			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8712	} else {
8713		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8714		    SCP_WCE) == 0)
8715			flags |= CTL_LLF_FUA;
8716	}
8717
8718	lbalen = (struct ctl_lba_len_flags *)
8719	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8720	lbalen->lba = lba;
8721	lbalen->len = num_blocks;
8722	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8723
8724	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8725	ctsio->kern_rel_offset = 0;
8726
8727	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8728
8729	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8730
8731	return (retval);
8732}
8733
8734static int
8735ctl_cnw_cont(union ctl_io *io)
8736{
8737	struct ctl_scsiio *ctsio;
8738	struct ctl_lun *lun;
8739	struct ctl_lba_len_flags *lbalen;
8740	int retval;
8741
8742	ctsio = &io->scsiio;
8743	ctsio->io_hdr.status = CTL_STATUS_NONE;
8744	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8745	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8746	lbalen = (struct ctl_lba_len_flags *)
8747	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8748	lbalen->flags &= ~CTL_LLF_COMPARE;
8749	lbalen->flags |= CTL_LLF_WRITE;
8750
8751	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8752	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8753	return (retval);
8754}
8755
8756int
8757ctl_cnw(struct ctl_scsiio *ctsio)
8758{
8759	struct ctl_lun *lun;
8760	struct ctl_lba_len_flags *lbalen;
8761	uint64_t lba;
8762	uint32_t num_blocks;
8763	int flags, retval;
8764
8765	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8766
8767	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8768
8769	flags = 0;
8770	retval = CTL_RETVAL_COMPLETE;
8771
8772	switch (ctsio->cdb[0]) {
8773	case COMPARE_AND_WRITE: {
8774		struct scsi_compare_and_write *cdb;
8775
8776		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8777		if (cdb->byte2 & SRW10_FUA)
8778			flags |= CTL_LLF_FUA;
8779		if (cdb->byte2 & SRW10_DPO)
8780			flags |= CTL_LLF_DPO;
8781		lba = scsi_8btou64(cdb->addr);
8782		num_blocks = cdb->length;
8783		break;
8784	}
8785	default:
8786		/*
8787		 * We got a command we don't support.  This shouldn't
8788		 * happen, commands should be filtered out above us.
8789		 */
8790		ctl_set_invalid_opcode(ctsio);
8791		ctl_done((union ctl_io *)ctsio);
8792
8793		return (CTL_RETVAL_COMPLETE);
8794		break; /* NOTREACHED */
8795	}
8796
8797	/*
8798	 * The first check is to make sure we're in bounds, the second
8799	 * check is to catch wrap-around problems.  If the lba + num blocks
8800	 * is less than the lba, then we've wrapped around and the block
8801	 * range is invalid anyway.
8802	 */
8803	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8804	 || ((lba + num_blocks) < lba)) {
8805		ctl_set_lba_out_of_range(ctsio);
8806		ctl_done((union ctl_io *)ctsio);
8807		return (CTL_RETVAL_COMPLETE);
8808	}
8809
8810	/*
8811	 * According to SBC-3, a transfer length of 0 is not an error.
8812	 */
8813	if (num_blocks == 0) {
8814		ctl_set_success(ctsio);
8815		ctl_done((union ctl_io *)ctsio);
8816		return (CTL_RETVAL_COMPLETE);
8817	}
8818
8819	/* Set FUA if write cache is disabled. */
8820	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8821	    SCP_WCE) == 0)
8822		flags |= CTL_LLF_FUA;
8823
8824	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8825	ctsio->kern_rel_offset = 0;
8826
8827	/*
8828	 * Set the IO_CONT flag, so that if this I/O gets passed to
8829	 * ctl_data_submit_done(), it'll get passed back to
8830	 * ctl_ctl_cnw_cont() for further processing.
8831	 */
8832	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8833	ctsio->io_cont = ctl_cnw_cont;
8834
8835	lbalen = (struct ctl_lba_len_flags *)
8836	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8837	lbalen->lba = lba;
8838	lbalen->len = num_blocks;
8839	lbalen->flags = CTL_LLF_COMPARE | flags;
8840
8841	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8842	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8843	return (retval);
8844}
8845
8846int
8847ctl_verify(struct ctl_scsiio *ctsio)
8848{
8849	struct ctl_lun *lun;
8850	struct ctl_lba_len_flags *lbalen;
8851	uint64_t lba;
8852	uint32_t num_blocks;
8853	int bytchk, flags;
8854	int retval;
8855
8856	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8857
8858	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8859
8860	bytchk = 0;
8861	flags = CTL_LLF_FUA;
8862	retval = CTL_RETVAL_COMPLETE;
8863
8864	switch (ctsio->cdb[0]) {
8865	case VERIFY_10: {
8866		struct scsi_verify_10 *cdb;
8867
8868		cdb = (struct scsi_verify_10 *)ctsio->cdb;
8869		if (cdb->byte2 & SVFY_BYTCHK)
8870			bytchk = 1;
8871		if (cdb->byte2 & SVFY_DPO)
8872			flags |= CTL_LLF_DPO;
8873		lba = scsi_4btoul(cdb->addr);
8874		num_blocks = scsi_2btoul(cdb->length);
8875		break;
8876	}
8877	case VERIFY_12: {
8878		struct scsi_verify_12 *cdb;
8879
8880		cdb = (struct scsi_verify_12 *)ctsio->cdb;
8881		if (cdb->byte2 & SVFY_BYTCHK)
8882			bytchk = 1;
8883		if (cdb->byte2 & SVFY_DPO)
8884			flags |= CTL_LLF_DPO;
8885		lba = scsi_4btoul(cdb->addr);
8886		num_blocks = scsi_4btoul(cdb->length);
8887		break;
8888	}
8889	case VERIFY_16: {
8890		struct scsi_rw_16 *cdb;
8891
8892		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8893		if (cdb->byte2 & SVFY_BYTCHK)
8894			bytchk = 1;
8895		if (cdb->byte2 & SVFY_DPO)
8896			flags |= CTL_LLF_DPO;
8897		lba = scsi_8btou64(cdb->addr);
8898		num_blocks = scsi_4btoul(cdb->length);
8899		break;
8900	}
8901	default:
8902		/*
8903		 * We got a command we don't support.  This shouldn't
8904		 * happen, commands should be filtered out above us.
8905		 */
8906		ctl_set_invalid_opcode(ctsio);
8907		ctl_done((union ctl_io *)ctsio);
8908		return (CTL_RETVAL_COMPLETE);
8909	}
8910
8911	/*
8912	 * The first check is to make sure we're in bounds, the second
8913	 * check is to catch wrap-around problems.  If the lba + num blocks
8914	 * is less than the lba, then we've wrapped around and the block
8915	 * range is invalid anyway.
8916	 */
8917	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8918	 || ((lba + num_blocks) < lba)) {
8919		ctl_set_lba_out_of_range(ctsio);
8920		ctl_done((union ctl_io *)ctsio);
8921		return (CTL_RETVAL_COMPLETE);
8922	}
8923
8924	/*
8925	 * According to SBC-3, a transfer length of 0 is not an error.
8926	 */
8927	if (num_blocks == 0) {
8928		ctl_set_success(ctsio);
8929		ctl_done((union ctl_io *)ctsio);
8930		return (CTL_RETVAL_COMPLETE);
8931	}
8932
8933	lbalen = (struct ctl_lba_len_flags *)
8934	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8935	lbalen->lba = lba;
8936	lbalen->len = num_blocks;
8937	if (bytchk) {
8938		lbalen->flags = CTL_LLF_COMPARE | flags;
8939		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8940	} else {
8941		lbalen->flags = CTL_LLF_VERIFY | flags;
8942		ctsio->kern_total_len = 0;
8943	}
8944	ctsio->kern_rel_offset = 0;
8945
8946	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
8947	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8948	return (retval);
8949}
8950
8951int
8952ctl_report_luns(struct ctl_scsiio *ctsio)
8953{
8954	struct ctl_softc *softc = control_softc;
8955	struct scsi_report_luns *cdb;
8956	struct scsi_report_luns_data *lun_data;
8957	struct ctl_lun *lun, *request_lun;
8958	struct ctl_port *port;
8959	int num_luns, retval;
8960	uint32_t alloc_len, lun_datalen;
8961	int num_filled, well_known;
8962	uint32_t initidx, targ_lun_id, lun_id;
8963
8964	retval = CTL_RETVAL_COMPLETE;
8965	well_known = 0;
8966
8967	cdb = (struct scsi_report_luns *)ctsio->cdb;
8968	port = ctl_io_port(&ctsio->io_hdr);
8969
8970	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
8971
8972	mtx_lock(&softc->ctl_lock);
8973	num_luns = 0;
8974	for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
8975		if (ctl_lun_map_from_port(port, targ_lun_id) < CTL_MAX_LUNS)
8976			num_luns++;
8977	}
8978	mtx_unlock(&softc->ctl_lock);
8979
8980	switch (cdb->select_report) {
8981	case RPL_REPORT_DEFAULT:
8982	case RPL_REPORT_ALL:
8983		break;
8984	case RPL_REPORT_WELLKNOWN:
8985		well_known = 1;
8986		num_luns = 0;
8987		break;
8988	default:
8989		ctl_set_invalid_field(ctsio,
8990				      /*sks_valid*/ 1,
8991				      /*command*/ 1,
8992				      /*field*/ 2,
8993				      /*bit_valid*/ 0,
8994				      /*bit*/ 0);
8995		ctl_done((union ctl_io *)ctsio);
8996		return (retval);
8997		break; /* NOTREACHED */
8998	}
8999
9000	alloc_len = scsi_4btoul(cdb->length);
9001	/*
9002	 * The initiator has to allocate at least 16 bytes for this request,
9003	 * so he can at least get the header and the first LUN.  Otherwise
9004	 * we reject the request (per SPC-3 rev 14, section 6.21).
9005	 */
9006	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9007	    sizeof(struct scsi_report_luns_lundata))) {
9008		ctl_set_invalid_field(ctsio,
9009				      /*sks_valid*/ 1,
9010				      /*command*/ 1,
9011				      /*field*/ 6,
9012				      /*bit_valid*/ 0,
9013				      /*bit*/ 0);
9014		ctl_done((union ctl_io *)ctsio);
9015		return (retval);
9016	}
9017
9018	request_lun = (struct ctl_lun *)
9019		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9020
9021	lun_datalen = sizeof(*lun_data) +
9022		(num_luns * sizeof(struct scsi_report_luns_lundata));
9023
9024	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9025	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9026	ctsio->kern_sg_entries = 0;
9027
9028	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9029
9030	mtx_lock(&softc->ctl_lock);
9031	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9032		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9033		if (lun_id >= CTL_MAX_LUNS)
9034			continue;
9035		lun = softc->ctl_luns[lun_id];
9036		if (lun == NULL)
9037			continue;
9038
9039		if (targ_lun_id <= 0xff) {
9040			/*
9041			 * Peripheral addressing method, bus number 0.
9042			 */
9043			lun_data->luns[num_filled].lundata[0] =
9044				RPL_LUNDATA_ATYP_PERIPH;
9045			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9046			num_filled++;
9047		} else if (targ_lun_id <= 0x3fff) {
9048			/*
9049			 * Flat addressing method.
9050			 */
9051			lun_data->luns[num_filled].lundata[0] =
9052				RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9053			lun_data->luns[num_filled].lundata[1] =
9054				(targ_lun_id & 0xff);
9055			num_filled++;
9056		} else if (targ_lun_id <= 0xffffff) {
9057			/*
9058			 * Extended flat addressing method.
9059			 */
9060			lun_data->luns[num_filled].lundata[0] =
9061			    RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9062			scsi_ulto3b(targ_lun_id,
9063			    &lun_data->luns[num_filled].lundata[1]);
9064			num_filled++;
9065		} else {
9066			printf("ctl_report_luns: bogus LUN number %jd, "
9067			       "skipping\n", (intmax_t)targ_lun_id);
9068		}
9069		/*
9070		 * According to SPC-3, rev 14 section 6.21:
9071		 *
9072		 * "The execution of a REPORT LUNS command to any valid and
9073		 * installed logical unit shall clear the REPORTED LUNS DATA
9074		 * HAS CHANGED unit attention condition for all logical
9075		 * units of that target with respect to the requesting
9076		 * initiator. A valid and installed logical unit is one
9077		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9078		 * INQUIRY data (see 6.4.2)."
9079		 *
9080		 * If request_lun is NULL, the LUN this report luns command
9081		 * was issued to is either disabled or doesn't exist. In that
9082		 * case, we shouldn't clear any pending lun change unit
9083		 * attention.
9084		 */
9085		if (request_lun != NULL) {
9086			mtx_lock(&lun->lun_lock);
9087			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9088			mtx_unlock(&lun->lun_lock);
9089		}
9090	}
9091	mtx_unlock(&softc->ctl_lock);
9092
9093	/*
9094	 * It's quite possible that we've returned fewer LUNs than we allocated
9095	 * space for.  Trim it.
9096	 */
9097	lun_datalen = sizeof(*lun_data) +
9098		(num_filled * sizeof(struct scsi_report_luns_lundata));
9099
9100	if (lun_datalen < alloc_len) {
9101		ctsio->residual = alloc_len - lun_datalen;
9102		ctsio->kern_data_len = lun_datalen;
9103		ctsio->kern_total_len = lun_datalen;
9104	} else {
9105		ctsio->residual = 0;
9106		ctsio->kern_data_len = alloc_len;
9107		ctsio->kern_total_len = alloc_len;
9108	}
9109	ctsio->kern_data_resid = 0;
9110	ctsio->kern_rel_offset = 0;
9111	ctsio->kern_sg_entries = 0;
9112
9113	/*
9114	 * We set this to the actual data length, regardless of how much
9115	 * space we actually have to return results.  If the user looks at
9116	 * this value, he'll know whether or not he allocated enough space
9117	 * and reissue the command if necessary.  We don't support well
9118	 * known logical units, so if the user asks for that, return none.
9119	 */
9120	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9121
9122	/*
9123	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9124	 * this request.
9125	 */
9126	ctl_set_success(ctsio);
9127	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9128	ctsio->be_move_done = ctl_config_move_done;
9129	ctl_datamove((union ctl_io *)ctsio);
9130	return (retval);
9131}
9132
9133int
9134ctl_request_sense(struct ctl_scsiio *ctsio)
9135{
9136	struct scsi_request_sense *cdb;
9137	struct scsi_sense_data *sense_ptr;
9138	struct ctl_softc *ctl_softc;
9139	struct ctl_lun *lun;
9140	uint32_t initidx;
9141	int have_error;
9142	scsi_sense_data_type sense_format;
9143	ctl_ua_type ua_type;
9144
9145	cdb = (struct scsi_request_sense *)ctsio->cdb;
9146
9147	ctl_softc = control_softc;
9148	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9149
9150	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9151
9152	/*
9153	 * Determine which sense format the user wants.
9154	 */
9155	if (cdb->byte2 & SRS_DESC)
9156		sense_format = SSD_TYPE_DESC;
9157	else
9158		sense_format = SSD_TYPE_FIXED;
9159
9160	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9161	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9162	ctsio->kern_sg_entries = 0;
9163
9164	/*
9165	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9166	 * larger than the largest allowed value for the length field in the
9167	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9168	 */
9169	ctsio->residual = 0;
9170	ctsio->kern_data_len = cdb->length;
9171	ctsio->kern_total_len = cdb->length;
9172
9173	ctsio->kern_data_resid = 0;
9174	ctsio->kern_rel_offset = 0;
9175	ctsio->kern_sg_entries = 0;
9176
9177	/*
9178	 * If we don't have a LUN, we don't have any pending sense.
9179	 */
9180	if (lun == NULL)
9181		goto no_sense;
9182
9183	have_error = 0;
9184	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9185	/*
9186	 * Check for pending sense, and then for pending unit attentions.
9187	 * Pending sense gets returned first, then pending unit attentions.
9188	 */
9189	mtx_lock(&lun->lun_lock);
9190#ifdef CTL_WITH_CA
9191	if (ctl_is_set(lun->have_ca, initidx)) {
9192		scsi_sense_data_type stored_format;
9193
9194		/*
9195		 * Check to see which sense format was used for the stored
9196		 * sense data.
9197		 */
9198		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9199
9200		/*
9201		 * If the user requested a different sense format than the
9202		 * one we stored, then we need to convert it to the other
9203		 * format.  If we're going from descriptor to fixed format
9204		 * sense data, we may lose things in translation, depending
9205		 * on what options were used.
9206		 *
9207		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9208		 * for some reason we'll just copy it out as-is.
9209		 */
9210		if ((stored_format == SSD_TYPE_FIXED)
9211		 && (sense_format == SSD_TYPE_DESC))
9212			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9213			    &lun->pending_sense[initidx],
9214			    (struct scsi_sense_data_desc *)sense_ptr);
9215		else if ((stored_format == SSD_TYPE_DESC)
9216		      && (sense_format == SSD_TYPE_FIXED))
9217			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9218			    &lun->pending_sense[initidx],
9219			    (struct scsi_sense_data_fixed *)sense_ptr);
9220		else
9221			memcpy(sense_ptr, &lun->pending_sense[initidx],
9222			       MIN(sizeof(*sense_ptr),
9223			       sizeof(lun->pending_sense[initidx])));
9224
9225		ctl_clear_mask(lun->have_ca, initidx);
9226		have_error = 1;
9227	} else
9228#endif
9229	{
9230		ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9231		if (ua_type != CTL_UA_NONE)
9232			have_error = 1;
9233		if (ua_type == CTL_UA_LUN_CHANGE) {
9234			mtx_unlock(&lun->lun_lock);
9235			mtx_lock(&ctl_softc->ctl_lock);
9236			ctl_clr_ua_allluns(ctl_softc, initidx, ua_type);
9237			mtx_unlock(&ctl_softc->ctl_lock);
9238			mtx_lock(&lun->lun_lock);
9239		}
9240
9241	}
9242	mtx_unlock(&lun->lun_lock);
9243
9244	/*
9245	 * We already have a pending error, return it.
9246	 */
9247	if (have_error != 0) {
9248		/*
9249		 * We report the SCSI status as OK, since the status of the
9250		 * request sense command itself is OK.
9251		 * We report 0 for the sense length, because we aren't doing
9252		 * autosense in this case.  We're reporting sense as
9253		 * parameter data.
9254		 */
9255		ctl_set_success(ctsio);
9256		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9257		ctsio->be_move_done = ctl_config_move_done;
9258		ctl_datamove((union ctl_io *)ctsio);
9259		return (CTL_RETVAL_COMPLETE);
9260	}
9261
9262no_sense:
9263
9264	/*
9265	 * No sense information to report, so we report that everything is
9266	 * okay.
9267	 */
9268	ctl_set_sense_data(sense_ptr,
9269			   lun,
9270			   sense_format,
9271			   /*current_error*/ 1,
9272			   /*sense_key*/ SSD_KEY_NO_SENSE,
9273			   /*asc*/ 0x00,
9274			   /*ascq*/ 0x00,
9275			   SSD_ELEM_NONE);
9276
9277	/*
9278	 * We report 0 for the sense length, because we aren't doing
9279	 * autosense in this case.  We're reporting sense as parameter data.
9280	 */
9281	ctl_set_success(ctsio);
9282	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9283	ctsio->be_move_done = ctl_config_move_done;
9284	ctl_datamove((union ctl_io *)ctsio);
9285	return (CTL_RETVAL_COMPLETE);
9286}
9287
9288int
9289ctl_tur(struct ctl_scsiio *ctsio)
9290{
9291
9292	CTL_DEBUG_PRINT(("ctl_tur\n"));
9293
9294	ctl_set_success(ctsio);
9295	ctl_done((union ctl_io *)ctsio);
9296
9297	return (CTL_RETVAL_COMPLETE);
9298}
9299
9300/*
9301 * SCSI VPD page 0x00, the Supported VPD Pages page.
9302 */
9303static int
9304ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9305{
9306	struct scsi_vpd_supported_pages *pages;
9307	int sup_page_size;
9308	struct ctl_lun *lun;
9309	int p;
9310
9311	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9312
9313	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9314	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9315	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9316	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9317	ctsio->kern_sg_entries = 0;
9318
9319	if (sup_page_size < alloc_len) {
9320		ctsio->residual = alloc_len - sup_page_size;
9321		ctsio->kern_data_len = sup_page_size;
9322		ctsio->kern_total_len = sup_page_size;
9323	} else {
9324		ctsio->residual = 0;
9325		ctsio->kern_data_len = alloc_len;
9326		ctsio->kern_total_len = alloc_len;
9327	}
9328	ctsio->kern_data_resid = 0;
9329	ctsio->kern_rel_offset = 0;
9330	ctsio->kern_sg_entries = 0;
9331
9332	/*
9333	 * The control device is always connected.  The disk device, on the
9334	 * other hand, may not be online all the time.  Need to change this
9335	 * to figure out whether the disk device is actually online or not.
9336	 */
9337	if (lun != NULL)
9338		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9339				lun->be_lun->lun_type;
9340	else
9341		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9342
9343	p = 0;
9344	/* Supported VPD pages */
9345	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9346	/* Serial Number */
9347	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9348	/* Device Identification */
9349	pages->page_list[p++] = SVPD_DEVICE_ID;
9350	/* Extended INQUIRY Data */
9351	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9352	/* Mode Page Policy */
9353	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9354	/* SCSI Ports */
9355	pages->page_list[p++] = SVPD_SCSI_PORTS;
9356	/* Third-party Copy */
9357	pages->page_list[p++] = SVPD_SCSI_TPC;
9358	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9359		/* Block limits */
9360		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9361		/* Block Device Characteristics */
9362		pages->page_list[p++] = SVPD_BDC;
9363		/* Logical Block Provisioning */
9364		pages->page_list[p++] = SVPD_LBP;
9365	}
9366	pages->length = p;
9367
9368	ctl_set_success(ctsio);
9369	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9370	ctsio->be_move_done = ctl_config_move_done;
9371	ctl_datamove((union ctl_io *)ctsio);
9372	return (CTL_RETVAL_COMPLETE);
9373}
9374
9375/*
9376 * SCSI VPD page 0x80, the Unit Serial Number page.
9377 */
9378static int
9379ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9380{
9381	struct scsi_vpd_unit_serial_number *sn_ptr;
9382	struct ctl_lun *lun;
9383	int data_len;
9384
9385	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9386
9387	data_len = 4 + CTL_SN_LEN;
9388	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9389	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9390	if (data_len < alloc_len) {
9391		ctsio->residual = alloc_len - data_len;
9392		ctsio->kern_data_len = data_len;
9393		ctsio->kern_total_len = data_len;
9394	} else {
9395		ctsio->residual = 0;
9396		ctsio->kern_data_len = alloc_len;
9397		ctsio->kern_total_len = alloc_len;
9398	}
9399	ctsio->kern_data_resid = 0;
9400	ctsio->kern_rel_offset = 0;
9401	ctsio->kern_sg_entries = 0;
9402
9403	/*
9404	 * The control device is always connected.  The disk device, on the
9405	 * other hand, may not be online all the time.  Need to change this
9406	 * to figure out whether the disk device is actually online or not.
9407	 */
9408	if (lun != NULL)
9409		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9410				  lun->be_lun->lun_type;
9411	else
9412		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9413
9414	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9415	sn_ptr->length = CTL_SN_LEN;
9416	/*
9417	 * If we don't have a LUN, we just leave the serial number as
9418	 * all spaces.
9419	 */
9420	if (lun != NULL) {
9421		strncpy((char *)sn_ptr->serial_num,
9422			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9423	} else
9424		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9425
9426	ctl_set_success(ctsio);
9427	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9428	ctsio->be_move_done = ctl_config_move_done;
9429	ctl_datamove((union ctl_io *)ctsio);
9430	return (CTL_RETVAL_COMPLETE);
9431}
9432
9433
9434/*
9435 * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9436 */
9437static int
9438ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9439{
9440	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9441	struct ctl_lun *lun;
9442	int data_len;
9443
9444	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9445
9446	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9447	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9448	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9449	ctsio->kern_sg_entries = 0;
9450
9451	if (data_len < alloc_len) {
9452		ctsio->residual = alloc_len - data_len;
9453		ctsio->kern_data_len = data_len;
9454		ctsio->kern_total_len = data_len;
9455	} else {
9456		ctsio->residual = 0;
9457		ctsio->kern_data_len = alloc_len;
9458		ctsio->kern_total_len = alloc_len;
9459	}
9460	ctsio->kern_data_resid = 0;
9461	ctsio->kern_rel_offset = 0;
9462	ctsio->kern_sg_entries = 0;
9463
9464	/*
9465	 * The control device is always connected.  The disk device, on the
9466	 * other hand, may not be online all the time.
9467	 */
9468	if (lun != NULL)
9469		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9470				     lun->be_lun->lun_type;
9471	else
9472		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9473	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9474	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9475	/*
9476	 * We support head of queue, ordered and simple tags.
9477	 */
9478	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9479	/*
9480	 * Volatile cache supported.
9481	 */
9482	eid_ptr->flags3 = SVPD_EID_V_SUP;
9483
9484	/*
9485	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9486	 * attention for a particular IT nexus on all LUNs once we report
9487	 * it to that nexus once.  This bit is required as of SPC-4.
9488	 */
9489	eid_ptr->flags4 = SVPD_EID_LUICLT;
9490
9491	/*
9492	 * XXX KDM in order to correctly answer this, we would need
9493	 * information from the SIM to determine how much sense data it
9494	 * can send.  So this would really be a path inquiry field, most
9495	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9496	 * but the hardware may or may not be able to support that much.
9497	 * 0 just means that the maximum sense data length is not reported.
9498	 */
9499	eid_ptr->max_sense_length = 0;
9500
9501	ctl_set_success(ctsio);
9502	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9503	ctsio->be_move_done = ctl_config_move_done;
9504	ctl_datamove((union ctl_io *)ctsio);
9505	return (CTL_RETVAL_COMPLETE);
9506}
9507
9508static int
9509ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9510{
9511	struct scsi_vpd_mode_page_policy *mpp_ptr;
9512	struct ctl_lun *lun;
9513	int data_len;
9514
9515	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9516
9517	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9518	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9519
9520	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9521	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9522	ctsio->kern_sg_entries = 0;
9523
9524	if (data_len < alloc_len) {
9525		ctsio->residual = alloc_len - data_len;
9526		ctsio->kern_data_len = data_len;
9527		ctsio->kern_total_len = data_len;
9528	} else {
9529		ctsio->residual = 0;
9530		ctsio->kern_data_len = alloc_len;
9531		ctsio->kern_total_len = alloc_len;
9532	}
9533	ctsio->kern_data_resid = 0;
9534	ctsio->kern_rel_offset = 0;
9535	ctsio->kern_sg_entries = 0;
9536
9537	/*
9538	 * The control device is always connected.  The disk device, on the
9539	 * other hand, may not be online all the time.
9540	 */
9541	if (lun != NULL)
9542		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9543				     lun->be_lun->lun_type;
9544	else
9545		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9546	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9547	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9548	mpp_ptr->descr[0].page_code = 0x3f;
9549	mpp_ptr->descr[0].subpage_code = 0xff;
9550	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9551
9552	ctl_set_success(ctsio);
9553	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9554	ctsio->be_move_done = ctl_config_move_done;
9555	ctl_datamove((union ctl_io *)ctsio);
9556	return (CTL_RETVAL_COMPLETE);
9557}
9558
9559/*
9560 * SCSI VPD page 0x83, the Device Identification page.
9561 */
9562static int
9563ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9564{
9565	struct scsi_vpd_device_id *devid_ptr;
9566	struct scsi_vpd_id_descriptor *desc;
9567	struct ctl_softc *softc;
9568	struct ctl_lun *lun;
9569	struct ctl_port *port;
9570	int data_len;
9571	uint8_t proto;
9572
9573	softc = control_softc;
9574
9575	port = ctl_io_port(&ctsio->io_hdr);
9576	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9577
9578	data_len = sizeof(struct scsi_vpd_device_id) +
9579	    sizeof(struct scsi_vpd_id_descriptor) +
9580		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9581	    sizeof(struct scsi_vpd_id_descriptor) +
9582		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9583	if (lun && lun->lun_devid)
9584		data_len += lun->lun_devid->len;
9585	if (port && port->port_devid)
9586		data_len += port->port_devid->len;
9587	if (port && port->target_devid)
9588		data_len += port->target_devid->len;
9589
9590	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9591	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9592	ctsio->kern_sg_entries = 0;
9593
9594	if (data_len < alloc_len) {
9595		ctsio->residual = alloc_len - data_len;
9596		ctsio->kern_data_len = data_len;
9597		ctsio->kern_total_len = data_len;
9598	} else {
9599		ctsio->residual = 0;
9600		ctsio->kern_data_len = alloc_len;
9601		ctsio->kern_total_len = alloc_len;
9602	}
9603	ctsio->kern_data_resid = 0;
9604	ctsio->kern_rel_offset = 0;
9605	ctsio->kern_sg_entries = 0;
9606
9607	/*
9608	 * The control device is always connected.  The disk device, on the
9609	 * other hand, may not be online all the time.
9610	 */
9611	if (lun != NULL)
9612		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9613				     lun->be_lun->lun_type;
9614	else
9615		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9616	devid_ptr->page_code = SVPD_DEVICE_ID;
9617	scsi_ulto2b(data_len - 4, devid_ptr->length);
9618
9619	if (port && port->port_type == CTL_PORT_FC)
9620		proto = SCSI_PROTO_FC << 4;
9621	else if (port && port->port_type == CTL_PORT_ISCSI)
9622		proto = SCSI_PROTO_ISCSI << 4;
9623	else
9624		proto = SCSI_PROTO_SPI << 4;
9625	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9626
9627	/*
9628	 * We're using a LUN association here.  i.e., this device ID is a
9629	 * per-LUN identifier.
9630	 */
9631	if (lun && lun->lun_devid) {
9632		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9633		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9634		    lun->lun_devid->len);
9635	}
9636
9637	/*
9638	 * This is for the WWPN which is a port association.
9639	 */
9640	if (port && port->port_devid) {
9641		memcpy(desc, port->port_devid->data, port->port_devid->len);
9642		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9643		    port->port_devid->len);
9644	}
9645
9646	/*
9647	 * This is for the Relative Target Port(type 4h) identifier
9648	 */
9649	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9650	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9651	    SVPD_ID_TYPE_RELTARG;
9652	desc->length = 4;
9653	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9654	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9655	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9656
9657	/*
9658	 * This is for the Target Port Group(type 5h) identifier
9659	 */
9660	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9661	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9662	    SVPD_ID_TYPE_TPORTGRP;
9663	desc->length = 4;
9664	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / softc->port_cnt + 1,
9665	    &desc->identifier[2]);
9666	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9667	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9668
9669	/*
9670	 * This is for the Target identifier
9671	 */
9672	if (port && port->target_devid) {
9673		memcpy(desc, port->target_devid->data, port->target_devid->len);
9674	}
9675
9676	ctl_set_success(ctsio);
9677	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9678	ctsio->be_move_done = ctl_config_move_done;
9679	ctl_datamove((union ctl_io *)ctsio);
9680	return (CTL_RETVAL_COMPLETE);
9681}
9682
9683static int
9684ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9685{
9686	struct ctl_softc *softc = control_softc;
9687	struct scsi_vpd_scsi_ports *sp;
9688	struct scsi_vpd_port_designation *pd;
9689	struct scsi_vpd_port_designation_cont *pdc;
9690	struct ctl_lun *lun;
9691	struct ctl_port *port;
9692	int data_len, num_target_ports, iid_len, id_len;
9693
9694	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9695
9696	num_target_ports = 0;
9697	iid_len = 0;
9698	id_len = 0;
9699	mtx_lock(&softc->ctl_lock);
9700	STAILQ_FOREACH(port, &softc->port_list, links) {
9701		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9702			continue;
9703		if (lun != NULL &&
9704		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9705			continue;
9706		num_target_ports++;
9707		if (port->init_devid)
9708			iid_len += port->init_devid->len;
9709		if (port->port_devid)
9710			id_len += port->port_devid->len;
9711	}
9712	mtx_unlock(&softc->ctl_lock);
9713
9714	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9715	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9716	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9717	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9718	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9719	ctsio->kern_sg_entries = 0;
9720
9721	if (data_len < alloc_len) {
9722		ctsio->residual = alloc_len - data_len;
9723		ctsio->kern_data_len = data_len;
9724		ctsio->kern_total_len = data_len;
9725	} else {
9726		ctsio->residual = 0;
9727		ctsio->kern_data_len = alloc_len;
9728		ctsio->kern_total_len = alloc_len;
9729	}
9730	ctsio->kern_data_resid = 0;
9731	ctsio->kern_rel_offset = 0;
9732	ctsio->kern_sg_entries = 0;
9733
9734	/*
9735	 * The control device is always connected.  The disk device, on the
9736	 * other hand, may not be online all the time.  Need to change this
9737	 * to figure out whether the disk device is actually online or not.
9738	 */
9739	if (lun != NULL)
9740		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9741				  lun->be_lun->lun_type;
9742	else
9743		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9744
9745	sp->page_code = SVPD_SCSI_PORTS;
9746	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9747	    sp->page_length);
9748	pd = &sp->design[0];
9749
9750	mtx_lock(&softc->ctl_lock);
9751	STAILQ_FOREACH(port, &softc->port_list, links) {
9752		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9753			continue;
9754		if (lun != NULL &&
9755		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9756			continue;
9757		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9758		if (port->init_devid) {
9759			iid_len = port->init_devid->len;
9760			memcpy(pd->initiator_transportid,
9761			    port->init_devid->data, port->init_devid->len);
9762		} else
9763			iid_len = 0;
9764		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9765		pdc = (struct scsi_vpd_port_designation_cont *)
9766		    (&pd->initiator_transportid[iid_len]);
9767		if (port->port_devid) {
9768			id_len = port->port_devid->len;
9769			memcpy(pdc->target_port_descriptors,
9770			    port->port_devid->data, port->port_devid->len);
9771		} else
9772			id_len = 0;
9773		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9774		pd = (struct scsi_vpd_port_designation *)
9775		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9776	}
9777	mtx_unlock(&softc->ctl_lock);
9778
9779	ctl_set_success(ctsio);
9780	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9781	ctsio->be_move_done = ctl_config_move_done;
9782	ctl_datamove((union ctl_io *)ctsio);
9783	return (CTL_RETVAL_COMPLETE);
9784}
9785
9786static int
9787ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9788{
9789	struct scsi_vpd_block_limits *bl_ptr;
9790	struct ctl_lun *lun;
9791	int bs;
9792
9793	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9794
9795	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9796	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9797	ctsio->kern_sg_entries = 0;
9798
9799	if (sizeof(*bl_ptr) < alloc_len) {
9800		ctsio->residual = alloc_len - sizeof(*bl_ptr);
9801		ctsio->kern_data_len = sizeof(*bl_ptr);
9802		ctsio->kern_total_len = sizeof(*bl_ptr);
9803	} else {
9804		ctsio->residual = 0;
9805		ctsio->kern_data_len = alloc_len;
9806		ctsio->kern_total_len = alloc_len;
9807	}
9808	ctsio->kern_data_resid = 0;
9809	ctsio->kern_rel_offset = 0;
9810	ctsio->kern_sg_entries = 0;
9811
9812	/*
9813	 * The control device is always connected.  The disk device, on the
9814	 * other hand, may not be online all the time.  Need to change this
9815	 * to figure out whether the disk device is actually online or not.
9816	 */
9817	if (lun != NULL)
9818		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9819				  lun->be_lun->lun_type;
9820	else
9821		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9822
9823	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9824	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9825	bl_ptr->max_cmp_write_len = 0xff;
9826	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9827	if (lun != NULL) {
9828		bs = lun->be_lun->blocksize;
9829		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9830		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9831			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
9832			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
9833			if (lun->be_lun->ublockexp != 0) {
9834				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9835				    bl_ptr->opt_unmap_grain);
9836				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9837				    bl_ptr->unmap_grain_align);
9838			}
9839		}
9840		scsi_ulto4b(lun->be_lun->atomicblock,
9841		    bl_ptr->max_atomic_transfer_length);
9842		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9843		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9844	}
9845	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
9846
9847	ctl_set_success(ctsio);
9848	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9849	ctsio->be_move_done = ctl_config_move_done;
9850	ctl_datamove((union ctl_io *)ctsio);
9851	return (CTL_RETVAL_COMPLETE);
9852}
9853
9854static int
9855ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9856{
9857	struct scsi_vpd_block_device_characteristics *bdc_ptr;
9858	struct ctl_lun *lun;
9859	const char *value;
9860	u_int i;
9861
9862	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9863
9864	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9865	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9866	ctsio->kern_sg_entries = 0;
9867
9868	if (sizeof(*bdc_ptr) < alloc_len) {
9869		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
9870		ctsio->kern_data_len = sizeof(*bdc_ptr);
9871		ctsio->kern_total_len = sizeof(*bdc_ptr);
9872	} else {
9873		ctsio->residual = 0;
9874		ctsio->kern_data_len = alloc_len;
9875		ctsio->kern_total_len = alloc_len;
9876	}
9877	ctsio->kern_data_resid = 0;
9878	ctsio->kern_rel_offset = 0;
9879	ctsio->kern_sg_entries = 0;
9880
9881	/*
9882	 * The control device is always connected.  The disk device, on the
9883	 * other hand, may not be online all the time.  Need to change this
9884	 * to figure out whether the disk device is actually online or not.
9885	 */
9886	if (lun != NULL)
9887		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9888				  lun->be_lun->lun_type;
9889	else
9890		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9891	bdc_ptr->page_code = SVPD_BDC;
9892	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9893	if (lun != NULL &&
9894	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
9895		i = strtol(value, NULL, 0);
9896	else
9897		i = CTL_DEFAULT_ROTATION_RATE;
9898	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9899	if (lun != NULL &&
9900	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
9901		i = strtol(value, NULL, 0);
9902	else
9903		i = 0;
9904	bdc_ptr->wab_wac_ff = (i & 0x0f);
9905	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9906
9907	ctl_set_success(ctsio);
9908	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9909	ctsio->be_move_done = ctl_config_move_done;
9910	ctl_datamove((union ctl_io *)ctsio);
9911	return (CTL_RETVAL_COMPLETE);
9912}
9913
9914static int
9915ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9916{
9917	struct scsi_vpd_logical_block_prov *lbp_ptr;
9918	struct ctl_lun *lun;
9919
9920	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9921
9922	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9923	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9924	ctsio->kern_sg_entries = 0;
9925
9926	if (sizeof(*lbp_ptr) < alloc_len) {
9927		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
9928		ctsio->kern_data_len = sizeof(*lbp_ptr);
9929		ctsio->kern_total_len = sizeof(*lbp_ptr);
9930	} else {
9931		ctsio->residual = 0;
9932		ctsio->kern_data_len = alloc_len;
9933		ctsio->kern_total_len = alloc_len;
9934	}
9935	ctsio->kern_data_resid = 0;
9936	ctsio->kern_rel_offset = 0;
9937	ctsio->kern_sg_entries = 0;
9938
9939	/*
9940	 * The control device is always connected.  The disk device, on the
9941	 * other hand, may not be online all the time.  Need to change this
9942	 * to figure out whether the disk device is actually online or not.
9943	 */
9944	if (lun != NULL)
9945		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9946				  lun->be_lun->lun_type;
9947	else
9948		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9949
9950	lbp_ptr->page_code = SVPD_LBP;
9951	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
9952	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
9953	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9954		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
9955		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
9956		lbp_ptr->prov_type = SVPD_LBP_THIN;
9957	}
9958
9959	ctl_set_success(ctsio);
9960	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9961	ctsio->be_move_done = ctl_config_move_done;
9962	ctl_datamove((union ctl_io *)ctsio);
9963	return (CTL_RETVAL_COMPLETE);
9964}
9965
9966/*
9967 * INQUIRY with the EVPD bit set.
9968 */
9969static int
9970ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
9971{
9972	struct ctl_lun *lun;
9973	struct scsi_inquiry *cdb;
9974	int alloc_len, retval;
9975
9976	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9977	cdb = (struct scsi_inquiry *)ctsio->cdb;
9978	alloc_len = scsi_2btoul(cdb->length);
9979
9980	switch (cdb->page_code) {
9981	case SVPD_SUPPORTED_PAGES:
9982		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
9983		break;
9984	case SVPD_UNIT_SERIAL_NUMBER:
9985		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
9986		break;
9987	case SVPD_DEVICE_ID:
9988		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
9989		break;
9990	case SVPD_EXTENDED_INQUIRY_DATA:
9991		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
9992		break;
9993	case SVPD_MODE_PAGE_POLICY:
9994		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
9995		break;
9996	case SVPD_SCSI_PORTS:
9997		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
9998		break;
9999	case SVPD_SCSI_TPC:
10000		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10001		break;
10002	case SVPD_BLOCK_LIMITS:
10003		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10004			goto err;
10005		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10006		break;
10007	case SVPD_BDC:
10008		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10009			goto err;
10010		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10011		break;
10012	case SVPD_LBP:
10013		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10014			goto err;
10015		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10016		break;
10017	default:
10018err:
10019		ctl_set_invalid_field(ctsio,
10020				      /*sks_valid*/ 1,
10021				      /*command*/ 1,
10022				      /*field*/ 2,
10023				      /*bit_valid*/ 0,
10024				      /*bit*/ 0);
10025		ctl_done((union ctl_io *)ctsio);
10026		retval = CTL_RETVAL_COMPLETE;
10027		break;
10028	}
10029
10030	return (retval);
10031}
10032
10033/*
10034 * Standard INQUIRY data.
10035 */
10036static int
10037ctl_inquiry_std(struct ctl_scsiio *ctsio)
10038{
10039	struct scsi_inquiry_data *inq_ptr;
10040	struct scsi_inquiry *cdb;
10041	struct ctl_softc *softc;
10042	struct ctl_port *port;
10043	struct ctl_lun *lun;
10044	char *val;
10045	uint32_t alloc_len, data_len;
10046	ctl_port_type port_type;
10047
10048	softc = control_softc;
10049
10050	/*
10051	 * Figure out whether we're talking to a Fibre Channel port or not.
10052	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10053	 * SCSI front ends.
10054	 */
10055	port = ctl_io_port(&ctsio->io_hdr);
10056	if (port != NULL)
10057		port_type = port->port_type;
10058	else
10059		port_type = CTL_PORT_SCSI;
10060	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10061		port_type = CTL_PORT_SCSI;
10062
10063	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10064	cdb = (struct scsi_inquiry *)ctsio->cdb;
10065	alloc_len = scsi_2btoul(cdb->length);
10066
10067	/*
10068	 * We malloc the full inquiry data size here and fill it
10069	 * in.  If the user only asks for less, we'll give him
10070	 * that much.
10071	 */
10072	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10073	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10074	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10075	ctsio->kern_sg_entries = 0;
10076	ctsio->kern_data_resid = 0;
10077	ctsio->kern_rel_offset = 0;
10078
10079	if (data_len < alloc_len) {
10080		ctsio->residual = alloc_len - data_len;
10081		ctsio->kern_data_len = data_len;
10082		ctsio->kern_total_len = data_len;
10083	} else {
10084		ctsio->residual = 0;
10085		ctsio->kern_data_len = alloc_len;
10086		ctsio->kern_total_len = alloc_len;
10087	}
10088
10089	if (lun != NULL) {
10090		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10091		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10092			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10093			    lun->be_lun->lun_type;
10094		} else {
10095			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10096			    lun->be_lun->lun_type;
10097		}
10098	} else
10099		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10100
10101	/* RMB in byte 2 is 0 */
10102	inq_ptr->version = SCSI_REV_SPC4;
10103
10104	/*
10105	 * According to SAM-3, even if a device only supports a single
10106	 * level of LUN addressing, it should still set the HISUP bit:
10107	 *
10108	 * 4.9.1 Logical unit numbers overview
10109	 *
10110	 * All logical unit number formats described in this standard are
10111	 * hierarchical in structure even when only a single level in that
10112	 * hierarchy is used. The HISUP bit shall be set to one in the
10113	 * standard INQUIRY data (see SPC-2) when any logical unit number
10114	 * format described in this standard is used.  Non-hierarchical
10115	 * formats are outside the scope of this standard.
10116	 *
10117	 * Therefore we set the HiSup bit here.
10118	 *
10119	 * The reponse format is 2, per SPC-3.
10120	 */
10121	inq_ptr->response_format = SID_HiSup | 2;
10122
10123	inq_ptr->additional_length = data_len -
10124	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10125	CTL_DEBUG_PRINT(("additional_length = %d\n",
10126			 inq_ptr->additional_length));
10127
10128	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10129	/* 16 bit addressing */
10130	if (port_type == CTL_PORT_SCSI)
10131		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10132	/* XXX set the SID_MultiP bit here if we're actually going to
10133	   respond on multiple ports */
10134	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10135
10136	/* 16 bit data bus, synchronous transfers */
10137	if (port_type == CTL_PORT_SCSI)
10138		inq_ptr->flags = SID_WBus16 | SID_Sync;
10139	/*
10140	 * XXX KDM do we want to support tagged queueing on the control
10141	 * device at all?
10142	 */
10143	if ((lun == NULL)
10144	 || (lun->be_lun->lun_type != T_PROCESSOR))
10145		inq_ptr->flags |= SID_CmdQue;
10146	/*
10147	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10148	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10149	 * name and 4 bytes for the revision.
10150	 */
10151	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10152	    "vendor")) == NULL) {
10153		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10154	} else {
10155		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10156		strncpy(inq_ptr->vendor, val,
10157		    min(sizeof(inq_ptr->vendor), strlen(val)));
10158	}
10159	if (lun == NULL) {
10160		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10161		    sizeof(inq_ptr->product));
10162	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10163		switch (lun->be_lun->lun_type) {
10164		case T_DIRECT:
10165			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10166			    sizeof(inq_ptr->product));
10167			break;
10168		case T_PROCESSOR:
10169			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10170			    sizeof(inq_ptr->product));
10171			break;
10172		default:
10173			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10174			    sizeof(inq_ptr->product));
10175			break;
10176		}
10177	} else {
10178		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10179		strncpy(inq_ptr->product, val,
10180		    min(sizeof(inq_ptr->product), strlen(val)));
10181	}
10182
10183	/*
10184	 * XXX make this a macro somewhere so it automatically gets
10185	 * incremented when we make changes.
10186	 */
10187	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10188	    "revision")) == NULL) {
10189		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10190	} else {
10191		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10192		strncpy(inq_ptr->revision, val,
10193		    min(sizeof(inq_ptr->revision), strlen(val)));
10194	}
10195
10196	/*
10197	 * For parallel SCSI, we support double transition and single
10198	 * transition clocking.  We also support QAS (Quick Arbitration
10199	 * and Selection) and Information Unit transfers on both the
10200	 * control and array devices.
10201	 */
10202	if (port_type == CTL_PORT_SCSI)
10203		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10204				    SID_SPI_IUS;
10205
10206	/* SAM-5 (no version claimed) */
10207	scsi_ulto2b(0x00A0, inq_ptr->version1);
10208	/* SPC-4 (no version claimed) */
10209	scsi_ulto2b(0x0460, inq_ptr->version2);
10210	if (port_type == CTL_PORT_FC) {
10211		/* FCP-2 ANSI INCITS.350:2003 */
10212		scsi_ulto2b(0x0917, inq_ptr->version3);
10213	} else if (port_type == CTL_PORT_SCSI) {
10214		/* SPI-4 ANSI INCITS.362:200x */
10215		scsi_ulto2b(0x0B56, inq_ptr->version3);
10216	} else if (port_type == CTL_PORT_ISCSI) {
10217		/* iSCSI (no version claimed) */
10218		scsi_ulto2b(0x0960, inq_ptr->version3);
10219	} else if (port_type == CTL_PORT_SAS) {
10220		/* SAS (no version claimed) */
10221		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10222	}
10223
10224	if (lun == NULL) {
10225		/* SBC-4 (no version claimed) */
10226		scsi_ulto2b(0x0600, inq_ptr->version4);
10227	} else {
10228		switch (lun->be_lun->lun_type) {
10229		case T_DIRECT:
10230			/* SBC-4 (no version claimed) */
10231			scsi_ulto2b(0x0600, inq_ptr->version4);
10232			break;
10233		case T_PROCESSOR:
10234		default:
10235			break;
10236		}
10237	}
10238
10239	ctl_set_success(ctsio);
10240	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10241	ctsio->be_move_done = ctl_config_move_done;
10242	ctl_datamove((union ctl_io *)ctsio);
10243	return (CTL_RETVAL_COMPLETE);
10244}
10245
10246int
10247ctl_inquiry(struct ctl_scsiio *ctsio)
10248{
10249	struct scsi_inquiry *cdb;
10250	int retval;
10251
10252	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10253
10254	cdb = (struct scsi_inquiry *)ctsio->cdb;
10255	if (cdb->byte2 & SI_EVPD)
10256		retval = ctl_inquiry_evpd(ctsio);
10257	else if (cdb->page_code == 0)
10258		retval = ctl_inquiry_std(ctsio);
10259	else {
10260		ctl_set_invalid_field(ctsio,
10261				      /*sks_valid*/ 1,
10262				      /*command*/ 1,
10263				      /*field*/ 2,
10264				      /*bit_valid*/ 0,
10265				      /*bit*/ 0);
10266		ctl_done((union ctl_io *)ctsio);
10267		return (CTL_RETVAL_COMPLETE);
10268	}
10269
10270	return (retval);
10271}
10272
10273/*
10274 * For known CDB types, parse the LBA and length.
10275 */
10276static int
10277ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10278{
10279	if (io->io_hdr.io_type != CTL_IO_SCSI)
10280		return (1);
10281
10282	switch (io->scsiio.cdb[0]) {
10283	case COMPARE_AND_WRITE: {
10284		struct scsi_compare_and_write *cdb;
10285
10286		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10287
10288		*lba = scsi_8btou64(cdb->addr);
10289		*len = cdb->length;
10290		break;
10291	}
10292	case READ_6:
10293	case WRITE_6: {
10294		struct scsi_rw_6 *cdb;
10295
10296		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10297
10298		*lba = scsi_3btoul(cdb->addr);
10299		/* only 5 bits are valid in the most significant address byte */
10300		*lba &= 0x1fffff;
10301		*len = cdb->length;
10302		break;
10303	}
10304	case READ_10:
10305	case WRITE_10: {
10306		struct scsi_rw_10 *cdb;
10307
10308		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10309
10310		*lba = scsi_4btoul(cdb->addr);
10311		*len = scsi_2btoul(cdb->length);
10312		break;
10313	}
10314	case WRITE_VERIFY_10: {
10315		struct scsi_write_verify_10 *cdb;
10316
10317		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10318
10319		*lba = scsi_4btoul(cdb->addr);
10320		*len = scsi_2btoul(cdb->length);
10321		break;
10322	}
10323	case READ_12:
10324	case WRITE_12: {
10325		struct scsi_rw_12 *cdb;
10326
10327		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10328
10329		*lba = scsi_4btoul(cdb->addr);
10330		*len = scsi_4btoul(cdb->length);
10331		break;
10332	}
10333	case WRITE_VERIFY_12: {
10334		struct scsi_write_verify_12 *cdb;
10335
10336		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10337
10338		*lba = scsi_4btoul(cdb->addr);
10339		*len = scsi_4btoul(cdb->length);
10340		break;
10341	}
10342	case READ_16:
10343	case WRITE_16:
10344	case WRITE_ATOMIC_16: {
10345		struct scsi_rw_16 *cdb;
10346
10347		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10348
10349		*lba = scsi_8btou64(cdb->addr);
10350		*len = scsi_4btoul(cdb->length);
10351		break;
10352	}
10353	case WRITE_VERIFY_16: {
10354		struct scsi_write_verify_16 *cdb;
10355
10356		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10357
10358		*lba = scsi_8btou64(cdb->addr);
10359		*len = scsi_4btoul(cdb->length);
10360		break;
10361	}
10362	case WRITE_SAME_10: {
10363		struct scsi_write_same_10 *cdb;
10364
10365		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10366
10367		*lba = scsi_4btoul(cdb->addr);
10368		*len = scsi_2btoul(cdb->length);
10369		break;
10370	}
10371	case WRITE_SAME_16: {
10372		struct scsi_write_same_16 *cdb;
10373
10374		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10375
10376		*lba = scsi_8btou64(cdb->addr);
10377		*len = scsi_4btoul(cdb->length);
10378		break;
10379	}
10380	case VERIFY_10: {
10381		struct scsi_verify_10 *cdb;
10382
10383		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10384
10385		*lba = scsi_4btoul(cdb->addr);
10386		*len = scsi_2btoul(cdb->length);
10387		break;
10388	}
10389	case VERIFY_12: {
10390		struct scsi_verify_12 *cdb;
10391
10392		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10393
10394		*lba = scsi_4btoul(cdb->addr);
10395		*len = scsi_4btoul(cdb->length);
10396		break;
10397	}
10398	case VERIFY_16: {
10399		struct scsi_verify_16 *cdb;
10400
10401		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10402
10403		*lba = scsi_8btou64(cdb->addr);
10404		*len = scsi_4btoul(cdb->length);
10405		break;
10406	}
10407	case UNMAP: {
10408		*lba = 0;
10409		*len = UINT64_MAX;
10410		break;
10411	}
10412	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10413		struct scsi_get_lba_status *cdb;
10414
10415		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10416		*lba = scsi_8btou64(cdb->addr);
10417		*len = UINT32_MAX;
10418		break;
10419	}
10420	default:
10421		return (1);
10422		break; /* NOTREACHED */
10423	}
10424
10425	return (0);
10426}
10427
10428static ctl_action
10429ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10430    bool seq)
10431{
10432	uint64_t endlba1, endlba2;
10433
10434	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10435	endlba2 = lba2 + len2 - 1;
10436
10437	if ((endlba1 < lba2) || (endlba2 < lba1))
10438		return (CTL_ACTION_PASS);
10439	else
10440		return (CTL_ACTION_BLOCK);
10441}
10442
10443static int
10444ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10445{
10446	struct ctl_ptr_len_flags *ptrlen;
10447	struct scsi_unmap_desc *buf, *end, *range;
10448	uint64_t lba;
10449	uint32_t len;
10450
10451	/* If not UNMAP -- go other way. */
10452	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10453	    io->scsiio.cdb[0] != UNMAP)
10454		return (CTL_ACTION_ERROR);
10455
10456	/* If UNMAP without data -- block and wait for data. */
10457	ptrlen = (struct ctl_ptr_len_flags *)
10458	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10459	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10460	    ptrlen->ptr == NULL)
10461		return (CTL_ACTION_BLOCK);
10462
10463	/* UNMAP with data -- check for collision. */
10464	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10465	end = buf + ptrlen->len / sizeof(*buf);
10466	for (range = buf; range < end; range++) {
10467		lba = scsi_8btou64(range->lba);
10468		len = scsi_4btoul(range->length);
10469		if ((lba < lba2 + len2) && (lba + len > lba2))
10470			return (CTL_ACTION_BLOCK);
10471	}
10472	return (CTL_ACTION_PASS);
10473}
10474
10475static ctl_action
10476ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10477{
10478	uint64_t lba1, lba2;
10479	uint64_t len1, len2;
10480	int retval;
10481
10482	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10483		return (CTL_ACTION_ERROR);
10484
10485	retval = ctl_extent_check_unmap(io1, lba2, len2);
10486	if (retval != CTL_ACTION_ERROR)
10487		return (retval);
10488
10489	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10490		return (CTL_ACTION_ERROR);
10491
10492	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10493}
10494
10495static ctl_action
10496ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10497{
10498	uint64_t lba1, lba2;
10499	uint64_t len1, len2;
10500
10501	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10502		return (CTL_ACTION_ERROR);
10503	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10504		return (CTL_ACTION_ERROR);
10505
10506	if (lba1 + len1 == lba2)
10507		return (CTL_ACTION_BLOCK);
10508	return (CTL_ACTION_PASS);
10509}
10510
10511static ctl_action
10512ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10513    union ctl_io *ooa_io)
10514{
10515	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10516	ctl_serialize_action *serialize_row;
10517
10518	/*
10519	 * The initiator attempted multiple untagged commands at the same
10520	 * time.  Can't do that.
10521	 */
10522	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10523	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10524	 && ((pending_io->io_hdr.nexus.targ_port ==
10525	      ooa_io->io_hdr.nexus.targ_port)
10526	  && (pending_io->io_hdr.nexus.initid ==
10527	      ooa_io->io_hdr.nexus.initid))
10528	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10529	      CTL_FLAG_STATUS_SENT)) == 0))
10530		return (CTL_ACTION_OVERLAP);
10531
10532	/*
10533	 * The initiator attempted to send multiple tagged commands with
10534	 * the same ID.  (It's fine if different initiators have the same
10535	 * tag ID.)
10536	 *
10537	 * Even if all of those conditions are true, we don't kill the I/O
10538	 * if the command ahead of us has been aborted.  We won't end up
10539	 * sending it to the FETD, and it's perfectly legal to resend a
10540	 * command with the same tag number as long as the previous
10541	 * instance of this tag number has been aborted somehow.
10542	 */
10543	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10544	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10545	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10546	 && ((pending_io->io_hdr.nexus.targ_port ==
10547	      ooa_io->io_hdr.nexus.targ_port)
10548	  && (pending_io->io_hdr.nexus.initid ==
10549	      ooa_io->io_hdr.nexus.initid))
10550	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10551	      CTL_FLAG_STATUS_SENT)) == 0))
10552		return (CTL_ACTION_OVERLAP_TAG);
10553
10554	/*
10555	 * If we get a head of queue tag, SAM-3 says that we should
10556	 * immediately execute it.
10557	 *
10558	 * What happens if this command would normally block for some other
10559	 * reason?  e.g. a request sense with a head of queue tag
10560	 * immediately after a write.  Normally that would block, but this
10561	 * will result in its getting executed immediately...
10562	 *
10563	 * We currently return "pass" instead of "skip", so we'll end up
10564	 * going through the rest of the queue to check for overlapped tags.
10565	 *
10566	 * XXX KDM check for other types of blockage first??
10567	 */
10568	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10569		return (CTL_ACTION_PASS);
10570
10571	/*
10572	 * Ordered tags have to block until all items ahead of them
10573	 * have completed.  If we get called with an ordered tag, we always
10574	 * block, if something else is ahead of us in the queue.
10575	 */
10576	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10577		return (CTL_ACTION_BLOCK);
10578
10579	/*
10580	 * Simple tags get blocked until all head of queue and ordered tags
10581	 * ahead of them have completed.  I'm lumping untagged commands in
10582	 * with simple tags here.  XXX KDM is that the right thing to do?
10583	 */
10584	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10585	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10586	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10587	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10588		return (CTL_ACTION_BLOCK);
10589
10590	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10591	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10592
10593	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10594
10595	switch (serialize_row[pending_entry->seridx]) {
10596	case CTL_SER_BLOCK:
10597		return (CTL_ACTION_BLOCK);
10598	case CTL_SER_EXTENT:
10599		return (ctl_extent_check(ooa_io, pending_io,
10600		    (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10601	case CTL_SER_EXTENTOPT:
10602		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10603		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10604			return (ctl_extent_check(ooa_io, pending_io,
10605			    (lun->be_lun &&
10606			     lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10607		return (CTL_ACTION_PASS);
10608	case CTL_SER_EXTENTSEQ:
10609		if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
10610			return (ctl_extent_check_seq(ooa_io, pending_io));
10611		return (CTL_ACTION_PASS);
10612	case CTL_SER_PASS:
10613		return (CTL_ACTION_PASS);
10614	case CTL_SER_BLOCKOPT:
10615		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10616		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10617			return (CTL_ACTION_BLOCK);
10618		return (CTL_ACTION_PASS);
10619	case CTL_SER_SKIP:
10620		return (CTL_ACTION_SKIP);
10621	default:
10622		panic("invalid serialization value %d",
10623		      serialize_row[pending_entry->seridx]);
10624	}
10625
10626	return (CTL_ACTION_ERROR);
10627}
10628
10629/*
10630 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10631 * Assumptions:
10632 * - pending_io is generally either incoming, or on the blocked queue
10633 * - starting I/O is the I/O we want to start the check with.
10634 */
10635static ctl_action
10636ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10637	      union ctl_io *starting_io)
10638{
10639	union ctl_io *ooa_io;
10640	ctl_action action;
10641
10642	mtx_assert(&lun->lun_lock, MA_OWNED);
10643
10644	/*
10645	 * Run back along the OOA queue, starting with the current
10646	 * blocked I/O and going through every I/O before it on the
10647	 * queue.  If starting_io is NULL, we'll just end up returning
10648	 * CTL_ACTION_PASS.
10649	 */
10650	for (ooa_io = starting_io; ooa_io != NULL;
10651	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10652	     ooa_links)){
10653
10654		/*
10655		 * This routine just checks to see whether
10656		 * cur_blocked is blocked by ooa_io, which is ahead
10657		 * of it in the queue.  It doesn't queue/dequeue
10658		 * cur_blocked.
10659		 */
10660		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10661		switch (action) {
10662		case CTL_ACTION_BLOCK:
10663		case CTL_ACTION_OVERLAP:
10664		case CTL_ACTION_OVERLAP_TAG:
10665		case CTL_ACTION_SKIP:
10666		case CTL_ACTION_ERROR:
10667			return (action);
10668			break; /* NOTREACHED */
10669		case CTL_ACTION_PASS:
10670			break;
10671		default:
10672			panic("invalid action %d", action);
10673			break;  /* NOTREACHED */
10674		}
10675	}
10676
10677	return (CTL_ACTION_PASS);
10678}
10679
10680/*
10681 * Assumptions:
10682 * - An I/O has just completed, and has been removed from the per-LUN OOA
10683 *   queue, so some items on the blocked queue may now be unblocked.
10684 */
10685static int
10686ctl_check_blocked(struct ctl_lun *lun)
10687{
10688	struct ctl_softc *softc = lun->ctl_softc;
10689	union ctl_io *cur_blocked, *next_blocked;
10690
10691	mtx_assert(&lun->lun_lock, MA_OWNED);
10692
10693	/*
10694	 * Run forward from the head of the blocked queue, checking each
10695	 * entry against the I/Os prior to it on the OOA queue to see if
10696	 * there is still any blockage.
10697	 *
10698	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10699	 * with our removing a variable on it while it is traversing the
10700	 * list.
10701	 */
10702	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10703	     cur_blocked != NULL; cur_blocked = next_blocked) {
10704		union ctl_io *prev_ooa;
10705		ctl_action action;
10706
10707		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10708							  blocked_links);
10709
10710		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10711						      ctl_ooaq, ooa_links);
10712
10713		/*
10714		 * If cur_blocked happens to be the first item in the OOA
10715		 * queue now, prev_ooa will be NULL, and the action
10716		 * returned will just be CTL_ACTION_PASS.
10717		 */
10718		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
10719
10720		switch (action) {
10721		case CTL_ACTION_BLOCK:
10722			/* Nothing to do here, still blocked */
10723			break;
10724		case CTL_ACTION_OVERLAP:
10725		case CTL_ACTION_OVERLAP_TAG:
10726			/*
10727			 * This shouldn't happen!  In theory we've already
10728			 * checked this command for overlap...
10729			 */
10730			break;
10731		case CTL_ACTION_PASS:
10732		case CTL_ACTION_SKIP: {
10733			const struct ctl_cmd_entry *entry;
10734
10735			/*
10736			 * The skip case shouldn't happen, this transaction
10737			 * should have never made it onto the blocked queue.
10738			 */
10739			/*
10740			 * This I/O is no longer blocked, we can remove it
10741			 * from the blocked queue.  Since this is a TAILQ
10742			 * (doubly linked list), we can do O(1) removals
10743			 * from any place on the list.
10744			 */
10745			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
10746				     blocked_links);
10747			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10748
10749			if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
10750			    (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
10751				/*
10752				 * Need to send IO back to original side to
10753				 * run
10754				 */
10755				union ctl_ha_msg msg_info;
10756
10757				cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
10758				msg_info.hdr.original_sc =
10759					cur_blocked->io_hdr.original_sc;
10760				msg_info.hdr.serializing_sc = cur_blocked;
10761				msg_info.hdr.msg_type = CTL_MSG_R2R;
10762				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
10763				    sizeof(msg_info.hdr), M_NOWAIT);
10764				break;
10765			}
10766			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
10767
10768			/*
10769			 * Check this I/O for LUN state changes that may
10770			 * have happened while this command was blocked.
10771			 * The LUN state may have been changed by a command
10772			 * ahead of us in the queue, so we need to re-check
10773			 * for any states that can be caused by SCSI
10774			 * commands.
10775			 */
10776			if (ctl_scsiio_lun_check(lun, entry,
10777						 &cur_blocked->scsiio) == 0) {
10778				cur_blocked->io_hdr.flags |=
10779				                      CTL_FLAG_IS_WAS_ON_RTR;
10780				ctl_enqueue_rtr(cur_blocked);
10781			} else
10782				ctl_done(cur_blocked);
10783			break;
10784		}
10785		default:
10786			/*
10787			 * This probably shouldn't happen -- we shouldn't
10788			 * get CTL_ACTION_ERROR, or anything else.
10789			 */
10790			break;
10791		}
10792	}
10793
10794	return (CTL_RETVAL_COMPLETE);
10795}
10796
10797/*
10798 * This routine (with one exception) checks LUN flags that can be set by
10799 * commands ahead of us in the OOA queue.  These flags have to be checked
10800 * when a command initially comes in, and when we pull a command off the
10801 * blocked queue and are preparing to execute it.  The reason we have to
10802 * check these flags for commands on the blocked queue is that the LUN
10803 * state may have been changed by a command ahead of us while we're on the
10804 * blocked queue.
10805 *
10806 * Ordering is somewhat important with these checks, so please pay
10807 * careful attention to the placement of any new checks.
10808 */
10809static int
10810ctl_scsiio_lun_check(struct ctl_lun *lun,
10811    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
10812{
10813	struct ctl_softc *softc = lun->ctl_softc;
10814	int retval;
10815	uint32_t residx;
10816
10817	retval = 0;
10818
10819	mtx_assert(&lun->lun_lock, MA_OWNED);
10820
10821	/*
10822	 * If this shelf is a secondary shelf controller, we may have to
10823	 * reject some commands disallowed by HA mode and link state.
10824	 */
10825	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
10826		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
10827		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
10828			ctl_set_lun_unavail(ctsio);
10829			retval = 1;
10830			goto bailout;
10831		}
10832		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
10833		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
10834			ctl_set_lun_transit(ctsio);
10835			retval = 1;
10836			goto bailout;
10837		}
10838		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
10839		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
10840			ctl_set_lun_standby(ctsio);
10841			retval = 1;
10842			goto bailout;
10843		}
10844
10845		/* The rest of checks are only done on executing side */
10846		if (softc->ha_mode == CTL_HA_MODE_XFER)
10847			goto bailout;
10848	}
10849
10850	if (entry->pattern & CTL_LUN_PAT_WRITE) {
10851		if (lun->be_lun &&
10852		    lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
10853			ctl_set_hw_write_protected(ctsio);
10854			retval = 1;
10855			goto bailout;
10856		}
10857		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
10858		    .eca_and_aen & SCP_SWP) != 0) {
10859			ctl_set_sense(ctsio, /*current_error*/ 1,
10860			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
10861			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
10862			retval = 1;
10863			goto bailout;
10864		}
10865	}
10866
10867	/*
10868	 * Check for a reservation conflict.  If this command isn't allowed
10869	 * even on reserved LUNs, and if this initiator isn't the one who
10870	 * reserved us, reject the command with a reservation conflict.
10871	 */
10872	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
10873	if ((lun->flags & CTL_LUN_RESERVED)
10874	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
10875		if (lun->res_idx != residx) {
10876			ctl_set_reservation_conflict(ctsio);
10877			retval = 1;
10878			goto bailout;
10879		}
10880	}
10881
10882	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
10883	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
10884		/* No reservation or command is allowed. */;
10885	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
10886	    (lun->res_type == SPR_TYPE_WR_EX ||
10887	     lun->res_type == SPR_TYPE_WR_EX_RO ||
10888	     lun->res_type == SPR_TYPE_WR_EX_AR)) {
10889		/* The command is allowed for Write Exclusive resv. */;
10890	} else {
10891		/*
10892		 * if we aren't registered or it's a res holder type
10893		 * reservation and this isn't the res holder then set a
10894		 * conflict.
10895		 */
10896		if (ctl_get_prkey(lun, residx) == 0
10897		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
10898			ctl_set_reservation_conflict(ctsio);
10899			retval = 1;
10900			goto bailout;
10901		}
10902	}
10903
10904	if ((lun->flags & CTL_LUN_OFFLINE)
10905	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0)) {
10906		ctl_set_lun_not_ready(ctsio);
10907		retval = 1;
10908		goto bailout;
10909	}
10910
10911	if ((lun->flags & CTL_LUN_STOPPED)
10912	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
10913		/* "Logical unit not ready, initializing cmd. required" */
10914		ctl_set_lun_stopped(ctsio);
10915		retval = 1;
10916		goto bailout;
10917	}
10918
10919	if ((lun->flags & CTL_LUN_INOPERABLE)
10920	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
10921		/* "Medium format corrupted" */
10922		ctl_set_medium_format_corrupted(ctsio);
10923		retval = 1;
10924		goto bailout;
10925	}
10926
10927bailout:
10928	return (retval);
10929}
10930
10931static void
10932ctl_failover_io(union ctl_io *io, int have_lock)
10933{
10934	ctl_set_busy(&io->scsiio);
10935	ctl_done(io);
10936}
10937
10938static void
10939ctl_failover_lun(struct ctl_lun *lun)
10940{
10941	struct ctl_softc *softc = lun->ctl_softc;
10942	struct ctl_io_hdr *io, *next_io;
10943
10944	CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", lun->lun));
10945	if (softc->ha_mode == CTL_HA_MODE_XFER) {
10946		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
10947			/* We are master */
10948			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
10949				if (io->flags & CTL_FLAG_IO_ACTIVE) {
10950					io->flags |= CTL_FLAG_ABORT;
10951				} else { /* This can be only due to DATAMOVE */
10952					io->msg_type = CTL_MSG_DATAMOVE_DONE;
10953					io->flags |= CTL_FLAG_IO_ACTIVE;
10954					io->port_status = 31340;
10955					ctl_enqueue_isc((union ctl_io *)io);
10956				}
10957			}
10958			/* We are slave */
10959			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
10960				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
10961				if (io->flags & CTL_FLAG_IO_ACTIVE) {
10962					io->flags |= CTL_FLAG_FAILOVER;
10963				} else {
10964					ctl_set_busy(&((union ctl_io *)io)->
10965					    scsiio);
10966					ctl_done((union ctl_io *)io);
10967				}
10968			}
10969		}
10970	} else { /* SERIALIZE modes */
10971		TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
10972		    next_io) {
10973			/* We are master */
10974			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
10975				TAILQ_REMOVE(&lun->blocked_queue, io,
10976				    blocked_links);
10977				io->flags &= ~CTL_FLAG_BLOCKED;
10978				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
10979				ctl_free_io((union ctl_io *)io);
10980			}
10981		}
10982		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
10983			/* We are master */
10984			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
10985				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
10986				ctl_free_io((union ctl_io *)io);
10987			}
10988			/* We are slave */
10989			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
10990				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
10991				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
10992					ctl_set_busy(&((union ctl_io *)io)->
10993					    scsiio);
10994					ctl_done((union ctl_io *)io);
10995				}
10996			}
10997		}
10998		ctl_check_blocked(lun);
10999	}
11000}
11001
11002static int
11003ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11004{
11005	struct ctl_lun *lun;
11006	const struct ctl_cmd_entry *entry;
11007	uint32_t initidx, targ_lun;
11008	int retval;
11009
11010	retval = 0;
11011
11012	lun = NULL;
11013
11014	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11015	if ((targ_lun < CTL_MAX_LUNS)
11016	 && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11017		/*
11018		 * If the LUN is invalid, pretend that it doesn't exist.
11019		 * It will go away as soon as all pending I/O has been
11020		 * completed.
11021		 */
11022		mtx_lock(&lun->lun_lock);
11023		if (lun->flags & CTL_LUN_DISABLED) {
11024			mtx_unlock(&lun->lun_lock);
11025			lun = NULL;
11026			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11027			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11028		} else {
11029			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11030			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11031				lun->be_lun;
11032
11033			/*
11034			 * Every I/O goes into the OOA queue for a
11035			 * particular LUN, and stays there until completion.
11036			 */
11037#ifdef CTL_TIME_IO
11038			if (TAILQ_EMPTY(&lun->ooa_queue)) {
11039				lun->idle_time += getsbinuptime() -
11040				    lun->last_busy;
11041			}
11042#endif
11043			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11044			    ooa_links);
11045		}
11046	} else {
11047		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11048		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11049	}
11050
11051	/* Get command entry and return error if it is unsuppotyed. */
11052	entry = ctl_validate_command(ctsio);
11053	if (entry == NULL) {
11054		if (lun)
11055			mtx_unlock(&lun->lun_lock);
11056		return (retval);
11057	}
11058
11059	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11060	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11061
11062	/*
11063	 * Check to see whether we can send this command to LUNs that don't
11064	 * exist.  This should pretty much only be the case for inquiry
11065	 * and request sense.  Further checks, below, really require having
11066	 * a LUN, so we can't really check the command anymore.  Just put
11067	 * it on the rtr queue.
11068	 */
11069	if (lun == NULL) {
11070		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11071			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11072			ctl_enqueue_rtr((union ctl_io *)ctsio);
11073			return (retval);
11074		}
11075
11076		ctl_set_unsupported_lun(ctsio);
11077		ctl_done((union ctl_io *)ctsio);
11078		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11079		return (retval);
11080	} else {
11081		/*
11082		 * Make sure we support this particular command on this LUN.
11083		 * e.g., we don't support writes to the control LUN.
11084		 */
11085		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11086			mtx_unlock(&lun->lun_lock);
11087			ctl_set_invalid_opcode(ctsio);
11088			ctl_done((union ctl_io *)ctsio);
11089			return (retval);
11090		}
11091	}
11092
11093	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11094
11095#ifdef CTL_WITH_CA
11096	/*
11097	 * If we've got a request sense, it'll clear the contingent
11098	 * allegiance condition.  Otherwise, if we have a CA condition for
11099	 * this initiator, clear it, because it sent down a command other
11100	 * than request sense.
11101	 */
11102	if ((ctsio->cdb[0] != REQUEST_SENSE)
11103	 && (ctl_is_set(lun->have_ca, initidx)))
11104		ctl_clear_mask(lun->have_ca, initidx);
11105#endif
11106
11107	/*
11108	 * If the command has this flag set, it handles its own unit
11109	 * attention reporting, we shouldn't do anything.  Otherwise we
11110	 * check for any pending unit attentions, and send them back to the
11111	 * initiator.  We only do this when a command initially comes in,
11112	 * not when we pull it off the blocked queue.
11113	 *
11114	 * According to SAM-3, section 5.3.2, the order that things get
11115	 * presented back to the host is basically unit attentions caused
11116	 * by some sort of reset event, busy status, reservation conflicts
11117	 * or task set full, and finally any other status.
11118	 *
11119	 * One issue here is that some of the unit attentions we report
11120	 * don't fall into the "reset" category (e.g. "reported luns data
11121	 * has changed").  So reporting it here, before the reservation
11122	 * check, may be technically wrong.  I guess the only thing to do
11123	 * would be to check for and report the reset events here, and then
11124	 * check for the other unit attention types after we check for a
11125	 * reservation conflict.
11126	 *
11127	 * XXX KDM need to fix this
11128	 */
11129	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11130		ctl_ua_type ua_type;
11131		scsi_sense_data_type sense_format;
11132
11133		if (lun->flags & CTL_LUN_SENSE_DESC)
11134			sense_format = SSD_TYPE_DESC;
11135		else
11136			sense_format = SSD_TYPE_FIXED;
11137
11138		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11139		    sense_format);
11140		if (ua_type != CTL_UA_NONE) {
11141			mtx_unlock(&lun->lun_lock);
11142			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11143			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11144			ctsio->sense_len = SSD_FULL_SIZE;
11145			ctl_done((union ctl_io *)ctsio);
11146			return (retval);
11147		}
11148	}
11149
11150
11151	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11152		mtx_unlock(&lun->lun_lock);
11153		ctl_done((union ctl_io *)ctsio);
11154		return (retval);
11155	}
11156
11157	/*
11158	 * XXX CHD this is where we want to send IO to other side if
11159	 * this LUN is secondary on this SC. We will need to make a copy
11160	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11161	 * the copy we send as FROM_OTHER.
11162	 * We also need to stuff the address of the original IO so we can
11163	 * find it easily. Something similar will need be done on the other
11164	 * side so when we are done we can find the copy.
11165	 */
11166	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11167	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0) {
11168		union ctl_ha_msg msg_info;
11169		int isc_retval;
11170
11171		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11172		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11173		mtx_unlock(&lun->lun_lock);
11174
11175		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11176		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11177		msg_info.hdr.serializing_sc = NULL;
11178		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11179		msg_info.scsi.tag_num = ctsio->tag_num;
11180		msg_info.scsi.tag_type = ctsio->tag_type;
11181		msg_info.scsi.cdb_len = ctsio->cdb_len;
11182		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11183
11184		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11185		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11186		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11187			ctl_set_busy(ctsio);
11188			ctl_done((union ctl_io *)ctsio);
11189			return (retval);
11190		}
11191		return (retval);
11192	}
11193
11194	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11195			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11196			      ctl_ooaq, ooa_links))) {
11197	case CTL_ACTION_BLOCK:
11198		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11199		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11200				  blocked_links);
11201		mtx_unlock(&lun->lun_lock);
11202		return (retval);
11203	case CTL_ACTION_PASS:
11204	case CTL_ACTION_SKIP:
11205		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11206		mtx_unlock(&lun->lun_lock);
11207		ctl_enqueue_rtr((union ctl_io *)ctsio);
11208		break;
11209	case CTL_ACTION_OVERLAP:
11210		mtx_unlock(&lun->lun_lock);
11211		ctl_set_overlapped_cmd(ctsio);
11212		ctl_done((union ctl_io *)ctsio);
11213		break;
11214	case CTL_ACTION_OVERLAP_TAG:
11215		mtx_unlock(&lun->lun_lock);
11216		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11217		ctl_done((union ctl_io *)ctsio);
11218		break;
11219	case CTL_ACTION_ERROR:
11220	default:
11221		mtx_unlock(&lun->lun_lock);
11222		ctl_set_internal_failure(ctsio,
11223					 /*sks_valid*/ 0,
11224					 /*retry_count*/ 0);
11225		ctl_done((union ctl_io *)ctsio);
11226		break;
11227	}
11228	return (retval);
11229}
11230
11231const struct ctl_cmd_entry *
11232ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11233{
11234	const struct ctl_cmd_entry *entry;
11235	int service_action;
11236
11237	entry = &ctl_cmd_table[ctsio->cdb[0]];
11238	if (sa)
11239		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11240	if (entry->flags & CTL_CMD_FLAG_SA5) {
11241		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11242		entry = &((const struct ctl_cmd_entry *)
11243		    entry->execute)[service_action];
11244	}
11245	return (entry);
11246}
11247
11248const struct ctl_cmd_entry *
11249ctl_validate_command(struct ctl_scsiio *ctsio)
11250{
11251	const struct ctl_cmd_entry *entry;
11252	int i, sa;
11253	uint8_t diff;
11254
11255	entry = ctl_get_cmd_entry(ctsio, &sa);
11256	if (entry->execute == NULL) {
11257		if (sa)
11258			ctl_set_invalid_field(ctsio,
11259					      /*sks_valid*/ 1,
11260					      /*command*/ 1,
11261					      /*field*/ 1,
11262					      /*bit_valid*/ 1,
11263					      /*bit*/ 4);
11264		else
11265			ctl_set_invalid_opcode(ctsio);
11266		ctl_done((union ctl_io *)ctsio);
11267		return (NULL);
11268	}
11269	KASSERT(entry->length > 0,
11270	    ("Not defined length for command 0x%02x/0x%02x",
11271	     ctsio->cdb[0], ctsio->cdb[1]));
11272	for (i = 1; i < entry->length; i++) {
11273		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11274		if (diff == 0)
11275			continue;
11276		ctl_set_invalid_field(ctsio,
11277				      /*sks_valid*/ 1,
11278				      /*command*/ 1,
11279				      /*field*/ i,
11280				      /*bit_valid*/ 1,
11281				      /*bit*/ fls(diff) - 1);
11282		ctl_done((union ctl_io *)ctsio);
11283		return (NULL);
11284	}
11285	return (entry);
11286}
11287
11288static int
11289ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11290{
11291
11292	switch (lun_type) {
11293	case T_PROCESSOR:
11294		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11295		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11296			return (0);
11297		break;
11298	case T_DIRECT:
11299		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11300		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11301			return (0);
11302		break;
11303	default:
11304		return (0);
11305	}
11306	return (1);
11307}
11308
11309static int
11310ctl_scsiio(struct ctl_scsiio *ctsio)
11311{
11312	int retval;
11313	const struct ctl_cmd_entry *entry;
11314
11315	retval = CTL_RETVAL_COMPLETE;
11316
11317	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11318
11319	entry = ctl_get_cmd_entry(ctsio, NULL);
11320
11321	/*
11322	 * If this I/O has been aborted, just send it straight to
11323	 * ctl_done() without executing it.
11324	 */
11325	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11326		ctl_done((union ctl_io *)ctsio);
11327		goto bailout;
11328	}
11329
11330	/*
11331	 * All the checks should have been handled by ctl_scsiio_precheck().
11332	 * We should be clear now to just execute the I/O.
11333	 */
11334	retval = entry->execute(ctsio);
11335
11336bailout:
11337	return (retval);
11338}
11339
11340/*
11341 * Since we only implement one target right now, a bus reset simply resets
11342 * our single target.
11343 */
11344static int
11345ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11346{
11347	return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11348}
11349
11350static int
11351ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11352		 ctl_ua_type ua_type)
11353{
11354	struct ctl_port *port;
11355	struct ctl_lun *lun;
11356	int retval;
11357
11358	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11359		union ctl_ha_msg msg_info;
11360
11361		msg_info.hdr.nexus = io->io_hdr.nexus;
11362		if (ua_type==CTL_UA_TARG_RESET)
11363			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11364		else
11365			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11366		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11367		msg_info.hdr.original_sc = NULL;
11368		msg_info.hdr.serializing_sc = NULL;
11369		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11370		    sizeof(msg_info.task), M_WAITOK);
11371	}
11372	retval = 0;
11373
11374	mtx_lock(&softc->ctl_lock);
11375	port = softc->ctl_ports[io->io_hdr.nexus.targ_port];
11376	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11377		if (port != NULL &&
11378		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
11379			continue;
11380		retval += ctl_do_lun_reset(lun, io, ua_type);
11381	}
11382	mtx_unlock(&softc->ctl_lock);
11383	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11384	return (retval);
11385}
11386
11387/*
11388 * The LUN should always be set.  The I/O is optional, and is used to
11389 * distinguish between I/Os sent by this initiator, and by other
11390 * initiators.  We set unit attention for initiators other than this one.
11391 * SAM-3 is vague on this point.  It does say that a unit attention should
11392 * be established for other initiators when a LUN is reset (see section
11393 * 5.7.3), but it doesn't specifically say that the unit attention should
11394 * be established for this particular initiator when a LUN is reset.  Here
11395 * is the relevant text, from SAM-3 rev 8:
11396 *
11397 * 5.7.2 When a SCSI initiator port aborts its own tasks
11398 *
11399 * When a SCSI initiator port causes its own task(s) to be aborted, no
11400 * notification that the task(s) have been aborted shall be returned to
11401 * the SCSI initiator port other than the completion response for the
11402 * command or task management function action that caused the task(s) to
11403 * be aborted and notification(s) associated with related effects of the
11404 * action (e.g., a reset unit attention condition).
11405 *
11406 * XXX KDM for now, we're setting unit attention for all initiators.
11407 */
11408static int
11409ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11410{
11411	union ctl_io *xio;
11412#if 0
11413	uint32_t initidx;
11414#endif
11415#ifdef CTL_WITH_CA
11416	int i;
11417#endif
11418
11419	mtx_lock(&lun->lun_lock);
11420	/*
11421	 * Run through the OOA queue and abort each I/O.
11422	 */
11423	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11424	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11425		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11426	}
11427
11428	/*
11429	 * This version sets unit attention for every
11430	 */
11431#if 0
11432	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11433	ctl_est_ua_all(lun, initidx, ua_type);
11434#else
11435	ctl_est_ua_all(lun, -1, ua_type);
11436#endif
11437
11438	/*
11439	 * A reset (any kind, really) clears reservations established with
11440	 * RESERVE/RELEASE.  It does not clear reservations established
11441	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11442	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11443	 * reservations made with the RESERVE/RELEASE commands, because
11444	 * those commands are obsolete in SPC-3.
11445	 */
11446	lun->flags &= ~CTL_LUN_RESERVED;
11447
11448#ifdef CTL_WITH_CA
11449	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11450		ctl_clear_mask(lun->have_ca, i);
11451#endif
11452	mtx_unlock(&lun->lun_lock);
11453
11454	return (0);
11455}
11456
11457static int
11458ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
11459{
11460	struct ctl_lun *lun;
11461	uint32_t targ_lun;
11462	int retval;
11463
11464	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11465	mtx_lock(&softc->ctl_lock);
11466	if ((targ_lun >= CTL_MAX_LUNS) ||
11467	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11468		mtx_unlock(&softc->ctl_lock);
11469		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11470		return (1);
11471	}
11472	retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
11473	mtx_unlock(&softc->ctl_lock);
11474	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11475
11476	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11477		union ctl_ha_msg msg_info;
11478
11479		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11480		msg_info.hdr.nexus = io->io_hdr.nexus;
11481		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11482		msg_info.hdr.original_sc = NULL;
11483		msg_info.hdr.serializing_sc = NULL;
11484		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11485		    sizeof(msg_info.task), M_WAITOK);
11486	}
11487	return (retval);
11488}
11489
11490static void
11491ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11492    int other_sc)
11493{
11494	union ctl_io *xio;
11495
11496	mtx_assert(&lun->lun_lock, MA_OWNED);
11497
11498	/*
11499	 * Run through the OOA queue and attempt to find the given I/O.
11500	 * The target port, initiator ID, tag type and tag number have to
11501	 * match the values that we got from the initiator.  If we have an
11502	 * untagged command to abort, simply abort the first untagged command
11503	 * we come to.  We only allow one untagged command at a time of course.
11504	 */
11505	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11506	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11507
11508		if ((targ_port == UINT32_MAX ||
11509		     targ_port == xio->io_hdr.nexus.targ_port) &&
11510		    (init_id == UINT32_MAX ||
11511		     init_id == xio->io_hdr.nexus.initid)) {
11512			if (targ_port != xio->io_hdr.nexus.targ_port ||
11513			    init_id != xio->io_hdr.nexus.initid)
11514				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11515			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11516			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11517				union ctl_ha_msg msg_info;
11518
11519				msg_info.hdr.nexus = xio->io_hdr.nexus;
11520				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11521				msg_info.task.tag_num = xio->scsiio.tag_num;
11522				msg_info.task.tag_type = xio->scsiio.tag_type;
11523				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11524				msg_info.hdr.original_sc = NULL;
11525				msg_info.hdr.serializing_sc = NULL;
11526				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11527				    sizeof(msg_info.task), M_NOWAIT);
11528			}
11529		}
11530	}
11531}
11532
11533static int
11534ctl_abort_task_set(union ctl_io *io)
11535{
11536	struct ctl_softc *softc = control_softc;
11537	struct ctl_lun *lun;
11538	uint32_t targ_lun;
11539
11540	/*
11541	 * Look up the LUN.
11542	 */
11543	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11544	mtx_lock(&softc->ctl_lock);
11545	if ((targ_lun >= CTL_MAX_LUNS) ||
11546	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11547		mtx_unlock(&softc->ctl_lock);
11548		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11549		return (1);
11550	}
11551
11552	mtx_lock(&lun->lun_lock);
11553	mtx_unlock(&softc->ctl_lock);
11554	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11555		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11556		    io->io_hdr.nexus.initid,
11557		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11558	} else { /* CTL_TASK_CLEAR_TASK_SET */
11559		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11560		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11561	}
11562	mtx_unlock(&lun->lun_lock);
11563	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11564	return (0);
11565}
11566
11567static int
11568ctl_i_t_nexus_reset(union ctl_io *io)
11569{
11570	struct ctl_softc *softc = control_softc;
11571	struct ctl_lun *lun;
11572	uint32_t initidx;
11573
11574	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11575		union ctl_ha_msg msg_info;
11576
11577		msg_info.hdr.nexus = io->io_hdr.nexus;
11578		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
11579		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11580		msg_info.hdr.original_sc = NULL;
11581		msg_info.hdr.serializing_sc = NULL;
11582		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11583		    sizeof(msg_info.task), M_WAITOK);
11584	}
11585
11586	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11587	mtx_lock(&softc->ctl_lock);
11588	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11589		mtx_lock(&lun->lun_lock);
11590		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11591		    io->io_hdr.nexus.initid, 1);
11592#ifdef CTL_WITH_CA
11593		ctl_clear_mask(lun->have_ca, initidx);
11594#endif
11595		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
11596			lun->flags &= ~CTL_LUN_RESERVED;
11597		ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
11598		mtx_unlock(&lun->lun_lock);
11599	}
11600	mtx_unlock(&softc->ctl_lock);
11601	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11602	return (0);
11603}
11604
11605static int
11606ctl_abort_task(union ctl_io *io)
11607{
11608	union ctl_io *xio;
11609	struct ctl_lun *lun;
11610	struct ctl_softc *softc;
11611#if 0
11612	struct sbuf sb;
11613	char printbuf[128];
11614#endif
11615	int found;
11616	uint32_t targ_lun;
11617
11618	softc = control_softc;
11619	found = 0;
11620
11621	/*
11622	 * Look up the LUN.
11623	 */
11624	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11625	mtx_lock(&softc->ctl_lock);
11626	if ((targ_lun >= CTL_MAX_LUNS) ||
11627	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11628		mtx_unlock(&softc->ctl_lock);
11629		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11630		return (1);
11631	}
11632
11633#if 0
11634	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11635	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11636#endif
11637
11638	mtx_lock(&lun->lun_lock);
11639	mtx_unlock(&softc->ctl_lock);
11640	/*
11641	 * Run through the OOA queue and attempt to find the given I/O.
11642	 * The target port, initiator ID, tag type and tag number have to
11643	 * match the values that we got from the initiator.  If we have an
11644	 * untagged command to abort, simply abort the first untagged command
11645	 * we come to.  We only allow one untagged command at a time of course.
11646	 */
11647	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11648	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11649#if 0
11650		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
11651
11652		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
11653			    lun->lun, xio->scsiio.tag_num,
11654			    xio->scsiio.tag_type,
11655			    (xio->io_hdr.blocked_links.tqe_prev
11656			    == NULL) ? "" : " BLOCKED",
11657			    (xio->io_hdr.flags &
11658			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
11659			    (xio->io_hdr.flags &
11660			    CTL_FLAG_ABORT) ? " ABORT" : "",
11661			    (xio->io_hdr.flags &
11662			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
11663		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
11664		sbuf_finish(&sb);
11665		printf("%s\n", sbuf_data(&sb));
11666#endif
11667
11668		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
11669		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
11670		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
11671			continue;
11672
11673		/*
11674		 * If the abort says that the task is untagged, the
11675		 * task in the queue must be untagged.  Otherwise,
11676		 * we just check to see whether the tag numbers
11677		 * match.  This is because the QLogic firmware
11678		 * doesn't pass back the tag type in an abort
11679		 * request.
11680		 */
11681#if 0
11682		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
11683		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
11684		 || (xio->scsiio.tag_num == io->taskio.tag_num))
11685#endif
11686		/*
11687		 * XXX KDM we've got problems with FC, because it
11688		 * doesn't send down a tag type with aborts.  So we
11689		 * can only really go by the tag number...
11690		 * This may cause problems with parallel SCSI.
11691		 * Need to figure that out!!
11692		 */
11693		if (xio->scsiio.tag_num == io->taskio.tag_num) {
11694			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11695			found = 1;
11696			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
11697			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11698				union ctl_ha_msg msg_info;
11699
11700				msg_info.hdr.nexus = io->io_hdr.nexus;
11701				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11702				msg_info.task.tag_num = io->taskio.tag_num;
11703				msg_info.task.tag_type = io->taskio.tag_type;
11704				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11705				msg_info.hdr.original_sc = NULL;
11706				msg_info.hdr.serializing_sc = NULL;
11707#if 0
11708				printf("Sent Abort to other side\n");
11709#endif
11710				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11711				    sizeof(msg_info.task), M_NOWAIT);
11712			}
11713#if 0
11714			printf("ctl_abort_task: found I/O to abort\n");
11715#endif
11716		}
11717	}
11718	mtx_unlock(&lun->lun_lock);
11719
11720	if (found == 0) {
11721		/*
11722		 * This isn't really an error.  It's entirely possible for
11723		 * the abort and command completion to cross on the wire.
11724		 * This is more of an informative/diagnostic error.
11725		 */
11726#if 0
11727		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
11728		       "%u:%u:%u tag %d type %d\n",
11729		       io->io_hdr.nexus.initid,
11730		       io->io_hdr.nexus.targ_port,
11731		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
11732		       io->taskio.tag_type);
11733#endif
11734	}
11735	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11736	return (0);
11737}
11738
11739static int
11740ctl_query_task(union ctl_io *io, int task_set)
11741{
11742	union ctl_io *xio;
11743	struct ctl_lun *lun;
11744	struct ctl_softc *softc;
11745	int found = 0;
11746	uint32_t targ_lun;
11747
11748	softc = control_softc;
11749	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11750	mtx_lock(&softc->ctl_lock);
11751	if ((targ_lun >= CTL_MAX_LUNS) ||
11752	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11753		mtx_unlock(&softc->ctl_lock);
11754		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11755		return (1);
11756	}
11757	mtx_lock(&lun->lun_lock);
11758	mtx_unlock(&softc->ctl_lock);
11759	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11760	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11761
11762		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
11763		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
11764		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
11765			continue;
11766
11767		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
11768			found = 1;
11769			break;
11770		}
11771	}
11772	mtx_unlock(&lun->lun_lock);
11773	if (found)
11774		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
11775	else
11776		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11777	return (0);
11778}
11779
11780static int
11781ctl_query_async_event(union ctl_io *io)
11782{
11783	struct ctl_lun *lun;
11784	struct ctl_softc *softc;
11785	ctl_ua_type ua;
11786	uint32_t targ_lun, initidx;
11787
11788	softc = control_softc;
11789	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11790	mtx_lock(&softc->ctl_lock);
11791	if ((targ_lun >= CTL_MAX_LUNS) ||
11792	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11793		mtx_unlock(&softc->ctl_lock);
11794		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11795		return (1);
11796	}
11797	mtx_lock(&lun->lun_lock);
11798	mtx_unlock(&softc->ctl_lock);
11799	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11800	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
11801	mtx_unlock(&lun->lun_lock);
11802	if (ua != CTL_UA_NONE)
11803		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
11804	else
11805		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11806	return (0);
11807}
11808
11809static void
11810ctl_run_task(union ctl_io *io)
11811{
11812	struct ctl_softc *softc = control_softc;
11813	int retval = 1;
11814
11815	CTL_DEBUG_PRINT(("ctl_run_task\n"));
11816	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
11817	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
11818	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
11819	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
11820	switch (io->taskio.task_action) {
11821	case CTL_TASK_ABORT_TASK:
11822		retval = ctl_abort_task(io);
11823		break;
11824	case CTL_TASK_ABORT_TASK_SET:
11825	case CTL_TASK_CLEAR_TASK_SET:
11826		retval = ctl_abort_task_set(io);
11827		break;
11828	case CTL_TASK_CLEAR_ACA:
11829		break;
11830	case CTL_TASK_I_T_NEXUS_RESET:
11831		retval = ctl_i_t_nexus_reset(io);
11832		break;
11833	case CTL_TASK_LUN_RESET:
11834		retval = ctl_lun_reset(softc, io);
11835		break;
11836	case CTL_TASK_TARGET_RESET:
11837		retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
11838		break;
11839	case CTL_TASK_BUS_RESET:
11840		retval = ctl_bus_reset(softc, io);
11841		break;
11842	case CTL_TASK_PORT_LOGIN:
11843		break;
11844	case CTL_TASK_PORT_LOGOUT:
11845		break;
11846	case CTL_TASK_QUERY_TASK:
11847		retval = ctl_query_task(io, 0);
11848		break;
11849	case CTL_TASK_QUERY_TASK_SET:
11850		retval = ctl_query_task(io, 1);
11851		break;
11852	case CTL_TASK_QUERY_ASYNC_EVENT:
11853		retval = ctl_query_async_event(io);
11854		break;
11855	default:
11856		printf("%s: got unknown task management event %d\n",
11857		       __func__, io->taskio.task_action);
11858		break;
11859	}
11860	if (retval == 0)
11861		io->io_hdr.status = CTL_SUCCESS;
11862	else
11863		io->io_hdr.status = CTL_ERROR;
11864	ctl_done(io);
11865}
11866
11867/*
11868 * For HA operation.  Handle commands that come in from the other
11869 * controller.
11870 */
11871static void
11872ctl_handle_isc(union ctl_io *io)
11873{
11874	int free_io;
11875	struct ctl_lun *lun;
11876	struct ctl_softc *softc;
11877	uint32_t targ_lun;
11878
11879	softc = control_softc;
11880
11881	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11882	lun = softc->ctl_luns[targ_lun];
11883
11884	switch (io->io_hdr.msg_type) {
11885	case CTL_MSG_SERIALIZE:
11886		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
11887		break;
11888	case CTL_MSG_R2R: {
11889		const struct ctl_cmd_entry *entry;
11890
11891		/*
11892		 * This is only used in SER_ONLY mode.
11893		 */
11894		free_io = 0;
11895		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
11896		mtx_lock(&lun->lun_lock);
11897		if (ctl_scsiio_lun_check(lun,
11898		    entry, (struct ctl_scsiio *)io) != 0) {
11899			mtx_unlock(&lun->lun_lock);
11900			ctl_done(io);
11901			break;
11902		}
11903		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11904		mtx_unlock(&lun->lun_lock);
11905		ctl_enqueue_rtr(io);
11906		break;
11907	}
11908	case CTL_MSG_FINISH_IO:
11909		if (softc->ha_mode == CTL_HA_MODE_XFER) {
11910			free_io = 0;
11911			ctl_done(io);
11912		} else {
11913			free_io = 1;
11914			mtx_lock(&lun->lun_lock);
11915			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
11916				     ooa_links);
11917			ctl_check_blocked(lun);
11918			mtx_unlock(&lun->lun_lock);
11919		}
11920		break;
11921	case CTL_MSG_PERS_ACTION:
11922		ctl_hndl_per_res_out_on_other_sc(
11923			(union ctl_ha_msg *)&io->presio.pr_msg);
11924		free_io = 1;
11925		break;
11926	case CTL_MSG_BAD_JUJU:
11927		free_io = 0;
11928		ctl_done(io);
11929		break;
11930	case CTL_MSG_DATAMOVE:
11931		/* Only used in XFER mode */
11932		free_io = 0;
11933		ctl_datamove_remote(io);
11934		break;
11935	case CTL_MSG_DATAMOVE_DONE:
11936		/* Only used in XFER mode */
11937		free_io = 0;
11938		io->scsiio.be_move_done(io);
11939		break;
11940	case CTL_MSG_FAILOVER:
11941		mtx_lock(&lun->lun_lock);
11942		ctl_failover_lun(lun);
11943		mtx_unlock(&lun->lun_lock);
11944		free_io = 1;
11945		break;
11946	default:
11947		free_io = 1;
11948		printf("%s: Invalid message type %d\n",
11949		       __func__, io->io_hdr.msg_type);
11950		break;
11951	}
11952	if (free_io)
11953		ctl_free_io(io);
11954
11955}
11956
11957
11958/*
11959 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
11960 * there is no match.
11961 */
11962static ctl_lun_error_pattern
11963ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
11964{
11965	const struct ctl_cmd_entry *entry;
11966	ctl_lun_error_pattern filtered_pattern, pattern;
11967
11968	pattern = desc->error_pattern;
11969
11970	/*
11971	 * XXX KDM we need more data passed into this function to match a
11972	 * custom pattern, and we actually need to implement custom pattern
11973	 * matching.
11974	 */
11975	if (pattern & CTL_LUN_PAT_CMD)
11976		return (CTL_LUN_PAT_CMD);
11977
11978	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
11979		return (CTL_LUN_PAT_ANY);
11980
11981	entry = ctl_get_cmd_entry(ctsio, NULL);
11982
11983	filtered_pattern = entry->pattern & pattern;
11984
11985	/*
11986	 * If the user requested specific flags in the pattern (e.g.
11987	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
11988	 * flags.
11989	 *
11990	 * If the user did not specify any flags, it doesn't matter whether
11991	 * or not the command supports the flags.
11992	 */
11993	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
11994	     (pattern & ~CTL_LUN_PAT_MASK))
11995		return (CTL_LUN_PAT_NONE);
11996
11997	/*
11998	 * If the user asked for a range check, see if the requested LBA
11999	 * range overlaps with this command's LBA range.
12000	 */
12001	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12002		uint64_t lba1;
12003		uint64_t len1;
12004		ctl_action action;
12005		int retval;
12006
12007		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12008		if (retval != 0)
12009			return (CTL_LUN_PAT_NONE);
12010
12011		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12012					      desc->lba_range.len, FALSE);
12013		/*
12014		 * A "pass" means that the LBA ranges don't overlap, so
12015		 * this doesn't match the user's range criteria.
12016		 */
12017		if (action == CTL_ACTION_PASS)
12018			return (CTL_LUN_PAT_NONE);
12019	}
12020
12021	return (filtered_pattern);
12022}
12023
12024static void
12025ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12026{
12027	struct ctl_error_desc *desc, *desc2;
12028
12029	mtx_assert(&lun->lun_lock, MA_OWNED);
12030
12031	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12032		ctl_lun_error_pattern pattern;
12033		/*
12034		 * Check to see whether this particular command matches
12035		 * the pattern in the descriptor.
12036		 */
12037		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12038		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12039			continue;
12040
12041		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12042		case CTL_LUN_INJ_ABORTED:
12043			ctl_set_aborted(&io->scsiio);
12044			break;
12045		case CTL_LUN_INJ_MEDIUM_ERR:
12046			ctl_set_medium_error(&io->scsiio);
12047			break;
12048		case CTL_LUN_INJ_UA:
12049			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12050			 * OCCURRED */
12051			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12052			break;
12053		case CTL_LUN_INJ_CUSTOM:
12054			/*
12055			 * We're assuming the user knows what he is doing.
12056			 * Just copy the sense information without doing
12057			 * checks.
12058			 */
12059			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12060			      MIN(sizeof(desc->custom_sense),
12061				  sizeof(io->scsiio.sense_data)));
12062			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12063			io->scsiio.sense_len = SSD_FULL_SIZE;
12064			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12065			break;
12066		case CTL_LUN_INJ_NONE:
12067		default:
12068			/*
12069			 * If this is an error injection type we don't know
12070			 * about, clear the continuous flag (if it is set)
12071			 * so it will get deleted below.
12072			 */
12073			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12074			break;
12075		}
12076		/*
12077		 * By default, each error injection action is a one-shot
12078		 */
12079		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12080			continue;
12081
12082		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12083
12084		free(desc, M_CTL);
12085	}
12086}
12087
12088#ifdef CTL_IO_DELAY
12089static void
12090ctl_datamove_timer_wakeup(void *arg)
12091{
12092	union ctl_io *io;
12093
12094	io = (union ctl_io *)arg;
12095
12096	ctl_datamove(io);
12097}
12098#endif /* CTL_IO_DELAY */
12099
12100void
12101ctl_datamove(union ctl_io *io)
12102{
12103	void (*fe_datamove)(union ctl_io *io);
12104
12105	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12106
12107	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12108
12109#ifdef CTL_TIME_IO
12110	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12111		char str[256];
12112		char path_str[64];
12113		struct sbuf sb;
12114
12115		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12116		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12117
12118		sbuf_cat(&sb, path_str);
12119		switch (io->io_hdr.io_type) {
12120		case CTL_IO_SCSI:
12121			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12122			sbuf_printf(&sb, "\n");
12123			sbuf_cat(&sb, path_str);
12124			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12125				    io->scsiio.tag_num, io->scsiio.tag_type);
12126			break;
12127		case CTL_IO_TASK:
12128			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12129				    "Tag Type: %d\n", io->taskio.task_action,
12130				    io->taskio.tag_num, io->taskio.tag_type);
12131			break;
12132		default:
12133			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12134			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12135			break;
12136		}
12137		sbuf_cat(&sb, path_str);
12138		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12139			    (intmax_t)time_uptime - io->io_hdr.start_time);
12140		sbuf_finish(&sb);
12141		printf("%s", sbuf_data(&sb));
12142	}
12143#endif /* CTL_TIME_IO */
12144
12145#ifdef CTL_IO_DELAY
12146	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12147		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12148	} else {
12149		struct ctl_lun *lun;
12150
12151		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12152		if ((lun != NULL)
12153		 && (lun->delay_info.datamove_delay > 0)) {
12154
12155			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12156			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12157			callout_reset(&io->io_hdr.delay_callout,
12158				      lun->delay_info.datamove_delay * hz,
12159				      ctl_datamove_timer_wakeup, io);
12160			if (lun->delay_info.datamove_type ==
12161			    CTL_DELAY_TYPE_ONESHOT)
12162				lun->delay_info.datamove_delay = 0;
12163			return;
12164		}
12165	}
12166#endif
12167
12168	/*
12169	 * This command has been aborted.  Set the port status, so we fail
12170	 * the data move.
12171	 */
12172	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12173		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12174		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12175		       io->io_hdr.nexus.targ_port,
12176		       io->io_hdr.nexus.targ_lun);
12177		io->io_hdr.port_status = 31337;
12178		/*
12179		 * Note that the backend, in this case, will get the
12180		 * callback in its context.  In other cases it may get
12181		 * called in the frontend's interrupt thread context.
12182		 */
12183		io->scsiio.be_move_done(io);
12184		return;
12185	}
12186
12187	/* Don't confuse frontend with zero length data move. */
12188	if (io->scsiio.kern_data_len == 0) {
12189		io->scsiio.be_move_done(io);
12190		return;
12191	}
12192
12193	/*
12194	 * If we're in XFER mode and this I/O is from the other shelf
12195	 * controller, we need to send the DMA to the other side to
12196	 * actually transfer the data to/from the host.  In serialize only
12197	 * mode the transfer happens below CTL and ctl_datamove() is only
12198	 * called on the machine that originally received the I/O.
12199	 */
12200	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12201	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12202		union ctl_ha_msg msg;
12203		uint32_t sg_entries_sent;
12204		int do_sg_copy;
12205		int i;
12206
12207		memset(&msg, 0, sizeof(msg));
12208		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12209		msg.hdr.original_sc = io->io_hdr.original_sc;
12210		msg.hdr.serializing_sc = io;
12211		msg.hdr.nexus = io->io_hdr.nexus;
12212		msg.dt.flags = io->io_hdr.flags;
12213		/*
12214		 * We convert everything into a S/G list here.  We can't
12215		 * pass by reference, only by value between controllers.
12216		 * So we can't pass a pointer to the S/G list, only as many
12217		 * S/G entries as we can fit in here.  If it's possible for
12218		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12219		 * then we need to break this up into multiple transfers.
12220		 */
12221		if (io->scsiio.kern_sg_entries == 0) {
12222			msg.dt.kern_sg_entries = 1;
12223#if 0
12224			/*
12225			 * Convert to a physical address if this is a
12226			 * virtual address.
12227			 */
12228			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12229				msg.dt.sg_list[0].addr =
12230					io->scsiio.kern_data_ptr;
12231			} else {
12232				/*
12233				 * XXX KDM use busdma here!
12234				 */
12235				msg.dt.sg_list[0].addr = (void *)
12236					vtophys(io->scsiio.kern_data_ptr);
12237			}
12238#else
12239			KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12240			    ("HA does not support BUS_ADDR"));
12241			msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
12242#endif
12243
12244			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12245			do_sg_copy = 0;
12246		} else {
12247			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12248			do_sg_copy = 1;
12249		}
12250
12251		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12252		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12253		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12254		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12255		msg.dt.sg_sequence = 0;
12256
12257		/*
12258		 * Loop until we've sent all of the S/G entries.  On the
12259		 * other end, we'll recompose these S/G entries into one
12260		 * contiguous list before passing it to the
12261		 */
12262		for (sg_entries_sent = 0; sg_entries_sent <
12263		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12264			msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list)/
12265				sizeof(msg.dt.sg_list[0])),
12266				msg.dt.kern_sg_entries - sg_entries_sent);
12267
12268			if (do_sg_copy != 0) {
12269				struct ctl_sg_entry *sgl;
12270				int j;
12271
12272				sgl = (struct ctl_sg_entry *)
12273					io->scsiio.kern_data_ptr;
12274				/*
12275				 * If this is in cached memory, flush the cache
12276				 * before we send the DMA request to the other
12277				 * controller.  We want to do this in either
12278				 * the * read or the write case.  The read
12279				 * case is straightforward.  In the write
12280				 * case, we want to make sure nothing is
12281				 * in the local cache that could overwrite
12282				 * the DMAed data.
12283				 */
12284
12285				for (i = sg_entries_sent, j = 0;
12286				     i < msg.dt.cur_sg_entries; i++, j++) {
12287#if 0
12288					if ((io->io_hdr.flags &
12289					     CTL_FLAG_BUS_ADDR) == 0) {
12290						/*
12291						 * XXX KDM use busdma.
12292						 */
12293						msg.dt.sg_list[j].addr =(void *)
12294						       vtophys(sgl[i].addr);
12295					} else {
12296						msg.dt.sg_list[j].addr =
12297							sgl[i].addr;
12298					}
12299#else
12300					KASSERT((io->io_hdr.flags &
12301					    CTL_FLAG_BUS_ADDR) == 0,
12302					    ("HA does not support BUS_ADDR"));
12303					msg.dt.sg_list[j].addr = sgl[i].addr;
12304#endif
12305					msg.dt.sg_list[j].len = sgl[i].len;
12306				}
12307			}
12308
12309			sg_entries_sent += msg.dt.cur_sg_entries;
12310			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12311				msg.dt.sg_last = 1;
12312			else
12313				msg.dt.sg_last = 0;
12314
12315			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12316			    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
12317			    sizeof(struct ctl_sg_entry)*msg.dt.cur_sg_entries,
12318			    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
12319				io->io_hdr.port_status = 31341;
12320				io->scsiio.be_move_done(io);
12321				return;
12322			}
12323
12324			msg.dt.sent_sg_entries = sg_entries_sent;
12325		}
12326		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12327	} else {
12328
12329		/*
12330		 * Lookup the fe_datamove() function for this particular
12331		 * front end.
12332		 */
12333		fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12334
12335		fe_datamove(io);
12336	}
12337}
12338
12339static void
12340ctl_send_datamove_done(union ctl_io *io, int have_lock)
12341{
12342	union ctl_ha_msg msg;
12343
12344	memset(&msg, 0, sizeof(msg));
12345
12346	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12347	msg.hdr.original_sc = io;
12348	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12349	msg.hdr.nexus = io->io_hdr.nexus;
12350	msg.hdr.status = io->io_hdr.status;
12351	msg.scsi.tag_num = io->scsiio.tag_num;
12352	msg.scsi.tag_type = io->scsiio.tag_type;
12353	msg.scsi.scsi_status = io->scsiio.scsi_status;
12354	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12355	       io->scsiio.sense_len);
12356	msg.scsi.sense_len = io->scsiio.sense_len;
12357	msg.scsi.sense_residual = io->scsiio.sense_residual;
12358	msg.scsi.fetd_status = io->io_hdr.port_status;
12359	msg.scsi.residual = io->scsiio.residual;
12360	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12361
12362	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12363		ctl_failover_io(io, /*have_lock*/ have_lock);
12364		return;
12365	}
12366
12367	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12368	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12369	    msg.scsi.sense_len, M_WAITOK);
12370}
12371
12372/*
12373 * The DMA to the remote side is done, now we need to tell the other side
12374 * we're done so it can continue with its data movement.
12375 */
12376static void
12377ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12378{
12379	union ctl_io *io;
12380	int i;
12381
12382	io = rq->context;
12383
12384	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12385		printf("%s: ISC DMA write failed with error %d", __func__,
12386		       rq->ret);
12387		ctl_set_internal_failure(&io->scsiio,
12388					 /*sks_valid*/ 1,
12389					 /*retry_count*/ rq->ret);
12390	}
12391
12392	ctl_dt_req_free(rq);
12393
12394	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12395		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12396	free(io->io_hdr.remote_sglist, M_CTL);
12397	io->io_hdr.remote_sglist = NULL;
12398	io->io_hdr.local_sglist = NULL;
12399
12400	/*
12401	 * The data is in local and remote memory, so now we need to send
12402	 * status (good or back) back to the other side.
12403	 */
12404	ctl_send_datamove_done(io, /*have_lock*/ 0);
12405}
12406
12407/*
12408 * We've moved the data from the host/controller into local memory.  Now we
12409 * need to push it over to the remote controller's memory.
12410 */
12411static int
12412ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12413{
12414	int retval;
12415
12416	retval = 0;
12417
12418	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12419					  ctl_datamove_remote_write_cb);
12420
12421	return (retval);
12422}
12423
12424static void
12425ctl_datamove_remote_write(union ctl_io *io)
12426{
12427	int retval;
12428	void (*fe_datamove)(union ctl_io *io);
12429
12430	/*
12431	 * - Get the data from the host/HBA into local memory.
12432	 * - DMA memory from the local controller to the remote controller.
12433	 * - Send status back to the remote controller.
12434	 */
12435
12436	retval = ctl_datamove_remote_sgl_setup(io);
12437	if (retval != 0)
12438		return;
12439
12440	/* Switch the pointer over so the FETD knows what to do */
12441	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12442
12443	/*
12444	 * Use a custom move done callback, since we need to send completion
12445	 * back to the other controller, not to the backend on this side.
12446	 */
12447	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12448
12449	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12450
12451	fe_datamove(io);
12452
12453	return;
12454
12455}
12456
12457static int
12458ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12459{
12460#if 0
12461	char str[256];
12462	char path_str[64];
12463	struct sbuf sb;
12464#endif
12465	int i;
12466
12467	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12468		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12469	free(io->io_hdr.remote_sglist, M_CTL);
12470	io->io_hdr.remote_sglist = NULL;
12471	io->io_hdr.local_sglist = NULL;
12472
12473#if 0
12474	scsi_path_string(io, path_str, sizeof(path_str));
12475	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12476	sbuf_cat(&sb, path_str);
12477	scsi_command_string(&io->scsiio, NULL, &sb);
12478	sbuf_printf(&sb, "\n");
12479	sbuf_cat(&sb, path_str);
12480	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12481		    io->scsiio.tag_num, io->scsiio.tag_type);
12482	sbuf_cat(&sb, path_str);
12483	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12484		    io->io_hdr.flags, io->io_hdr.status);
12485	sbuf_finish(&sb);
12486	printk("%s", sbuf_data(&sb));
12487#endif
12488
12489
12490	/*
12491	 * The read is done, now we need to send status (good or bad) back
12492	 * to the other side.
12493	 */
12494	ctl_send_datamove_done(io, /*have_lock*/ 0);
12495
12496	return (0);
12497}
12498
12499static void
12500ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12501{
12502	union ctl_io *io;
12503	void (*fe_datamove)(union ctl_io *io);
12504
12505	io = rq->context;
12506
12507	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12508		printf("%s: ISC DMA read failed with error %d\n", __func__,
12509		       rq->ret);
12510		ctl_set_internal_failure(&io->scsiio,
12511					 /*sks_valid*/ 1,
12512					 /*retry_count*/ rq->ret);
12513	}
12514
12515	ctl_dt_req_free(rq);
12516
12517	/* Switch the pointer over so the FETD knows what to do */
12518	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12519
12520	/*
12521	 * Use a custom move done callback, since we need to send completion
12522	 * back to the other controller, not to the backend on this side.
12523	 */
12524	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12525
12526	/* XXX KDM add checks like the ones in ctl_datamove? */
12527
12528	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12529
12530	fe_datamove(io);
12531}
12532
12533static int
12534ctl_datamove_remote_sgl_setup(union ctl_io *io)
12535{
12536	struct ctl_sg_entry *local_sglist, *remote_sglist;
12537	struct ctl_softc *softc;
12538	uint32_t len_to_go;
12539	int retval;
12540	int i;
12541
12542	retval = 0;
12543	softc = control_softc;
12544	local_sglist = io->io_hdr.local_sglist;
12545	remote_sglist = io->io_hdr.remote_sglist;
12546	len_to_go = io->scsiio.kern_data_len;
12547
12548	/*
12549	 * The difficult thing here is that the size of the various
12550	 * S/G segments may be different than the size from the
12551	 * remote controller.  That'll make it harder when DMAing
12552	 * the data back to the other side.
12553	 */
12554	for (i = 0; len_to_go > 0; i++) {
12555		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12556		local_sglist[i].addr =
12557		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12558
12559		len_to_go -= local_sglist[i].len;
12560	}
12561	/*
12562	 * Reset the number of S/G entries accordingly.  The original
12563	 * number of S/G entries is available in rem_sg_entries.
12564	 */
12565	io->scsiio.kern_sg_entries = i;
12566
12567#if 0
12568	printf("%s: kern_sg_entries = %d\n", __func__,
12569	       io->scsiio.kern_sg_entries);
12570	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12571		printf("%s: sg[%d] = %p, %d\n", __func__, i,
12572		       local_sglist[i].addr, local_sglist[i].len);
12573#endif
12574
12575	return (retval);
12576}
12577
12578static int
12579ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12580			 ctl_ha_dt_cb callback)
12581{
12582	struct ctl_ha_dt_req *rq;
12583	struct ctl_sg_entry *remote_sglist, *local_sglist;
12584	uint32_t local_used, remote_used, total_used;
12585	int i, j, isc_ret;
12586
12587	rq = ctl_dt_req_alloc();
12588
12589	/*
12590	 * If we failed to allocate the request, and if the DMA didn't fail
12591	 * anyway, set busy status.  This is just a resource allocation
12592	 * failure.
12593	 */
12594	if ((rq == NULL)
12595	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
12596		ctl_set_busy(&io->scsiio);
12597
12598	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
12599
12600		if (rq != NULL)
12601			ctl_dt_req_free(rq);
12602
12603		/*
12604		 * The data move failed.  We need to return status back
12605		 * to the other controller.  No point in trying to DMA
12606		 * data to the remote controller.
12607		 */
12608
12609		ctl_send_datamove_done(io, /*have_lock*/ 0);
12610
12611		return (1);
12612	}
12613
12614	local_sglist = io->io_hdr.local_sglist;
12615	remote_sglist = io->io_hdr.remote_sglist;
12616	local_used = 0;
12617	remote_used = 0;
12618	total_used = 0;
12619
12620	/*
12621	 * Pull/push the data over the wire from/to the other controller.
12622	 * This takes into account the possibility that the local and
12623	 * remote sglists may not be identical in terms of the size of
12624	 * the elements and the number of elements.
12625	 *
12626	 * One fundamental assumption here is that the length allocated for
12627	 * both the local and remote sglists is identical.  Otherwise, we've
12628	 * essentially got a coding error of some sort.
12629	 */
12630	isc_ret = CTL_HA_STATUS_SUCCESS;
12631	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12632		uint32_t cur_len;
12633		uint8_t *tmp_ptr;
12634
12635		rq->command = command;
12636		rq->context = io;
12637
12638		/*
12639		 * Both pointers should be aligned.  But it is possible
12640		 * that the allocation length is not.  They should both
12641		 * also have enough slack left over at the end, though,
12642		 * to round up to the next 8 byte boundary.
12643		 */
12644		cur_len = MIN(local_sglist[i].len - local_used,
12645			      remote_sglist[j].len - remote_used);
12646		rq->size = cur_len;
12647
12648		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12649		tmp_ptr += local_used;
12650
12651#if 0
12652		/* Use physical addresses when talking to ISC hardware */
12653		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12654			/* XXX KDM use busdma */
12655			rq->local = vtophys(tmp_ptr);
12656		} else
12657			rq->local = tmp_ptr;
12658#else
12659		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12660		    ("HA does not support BUS_ADDR"));
12661		rq->local = tmp_ptr;
12662#endif
12663
12664		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12665		tmp_ptr += remote_used;
12666		rq->remote = tmp_ptr;
12667
12668		rq->callback = NULL;
12669
12670		local_used += cur_len;
12671		if (local_used >= local_sglist[i].len) {
12672			i++;
12673			local_used = 0;
12674		}
12675
12676		remote_used += cur_len;
12677		if (remote_used >= remote_sglist[j].len) {
12678			j++;
12679			remote_used = 0;
12680		}
12681		total_used += cur_len;
12682
12683		if (total_used >= io->scsiio.kern_data_len)
12684			rq->callback = callback;
12685
12686#if 0
12687		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
12688		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
12689		       rq->local, rq->remote, rq->size);
12690#endif
12691
12692		isc_ret = ctl_dt_single(rq);
12693		if (isc_ret > CTL_HA_STATUS_SUCCESS)
12694			break;
12695	}
12696	if (isc_ret != CTL_HA_STATUS_WAIT) {
12697		rq->ret = isc_ret;
12698		callback(rq);
12699	}
12700
12701	return (0);
12702}
12703
12704static void
12705ctl_datamove_remote_read(union ctl_io *io)
12706{
12707	int retval;
12708	int i;
12709
12710	/*
12711	 * This will send an error to the other controller in the case of a
12712	 * failure.
12713	 */
12714	retval = ctl_datamove_remote_sgl_setup(io);
12715	if (retval != 0)
12716		return;
12717
12718	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12719					  ctl_datamove_remote_read_cb);
12720	if (retval != 0) {
12721		/*
12722		 * Make sure we free memory if there was an error..  The
12723		 * ctl_datamove_remote_xfer() function will send the
12724		 * datamove done message, or call the callback with an
12725		 * error if there is a problem.
12726		 */
12727		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12728			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12729		free(io->io_hdr.remote_sglist, M_CTL);
12730		io->io_hdr.remote_sglist = NULL;
12731		io->io_hdr.local_sglist = NULL;
12732	}
12733
12734	return;
12735}
12736
12737/*
12738 * Process a datamove request from the other controller.  This is used for
12739 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12740 * first.  Once that is complete, the data gets DMAed into the remote
12741 * controller's memory.  For reads, we DMA from the remote controller's
12742 * memory into our memory first, and then move it out to the FETD.
12743 */
12744static void
12745ctl_datamove_remote(union ctl_io *io)
12746{
12747
12748	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12749
12750	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12751		ctl_failover_io(io, /*have_lock*/ 0);
12752		return;
12753	}
12754
12755	/*
12756	 * Note that we look for an aborted I/O here, but don't do some of
12757	 * the other checks that ctl_datamove() normally does.
12758	 * We don't need to run the datamove delay code, since that should
12759	 * have been done if need be on the other controller.
12760	 */
12761	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12762		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
12763		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12764		       io->io_hdr.nexus.targ_port,
12765		       io->io_hdr.nexus.targ_lun);
12766		io->io_hdr.port_status = 31338;
12767		ctl_send_datamove_done(io, /*have_lock*/ 0);
12768		return;
12769	}
12770
12771	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
12772		ctl_datamove_remote_write(io);
12773	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
12774		ctl_datamove_remote_read(io);
12775	else {
12776		io->io_hdr.port_status = 31339;
12777		ctl_send_datamove_done(io, /*have_lock*/ 0);
12778	}
12779}
12780
12781static int
12782ctl_process_done(union ctl_io *io)
12783{
12784	struct ctl_lun *lun;
12785	struct ctl_softc *softc = control_softc;
12786	void (*fe_done)(union ctl_io *io);
12787	union ctl_ha_msg msg;
12788	uint32_t targ_port = io->io_hdr.nexus.targ_port;
12789
12790	CTL_DEBUG_PRINT(("ctl_process_done\n"));
12791
12792	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0)
12793		fe_done = softc->ctl_ports[targ_port]->fe_done;
12794	else
12795		fe_done = NULL;
12796
12797#ifdef CTL_TIME_IO
12798	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12799		char str[256];
12800		char path_str[64];
12801		struct sbuf sb;
12802
12803		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12804		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12805
12806		sbuf_cat(&sb, path_str);
12807		switch (io->io_hdr.io_type) {
12808		case CTL_IO_SCSI:
12809			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12810			sbuf_printf(&sb, "\n");
12811			sbuf_cat(&sb, path_str);
12812			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12813				    io->scsiio.tag_num, io->scsiio.tag_type);
12814			break;
12815		case CTL_IO_TASK:
12816			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12817				    "Tag Type: %d\n", io->taskio.task_action,
12818				    io->taskio.tag_num, io->taskio.tag_type);
12819			break;
12820		default:
12821			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12822			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12823			break;
12824		}
12825		sbuf_cat(&sb, path_str);
12826		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
12827			    (intmax_t)time_uptime - io->io_hdr.start_time);
12828		sbuf_finish(&sb);
12829		printf("%s", sbuf_data(&sb));
12830	}
12831#endif /* CTL_TIME_IO */
12832
12833	switch (io->io_hdr.io_type) {
12834	case CTL_IO_SCSI:
12835		break;
12836	case CTL_IO_TASK:
12837		if (ctl_debug & CTL_DEBUG_INFO)
12838			ctl_io_error_print(io, NULL);
12839		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
12840			ctl_free_io(io);
12841		else
12842			fe_done(io);
12843		return (CTL_RETVAL_COMPLETE);
12844	default:
12845		panic("ctl_process_done: invalid io type %d\n",
12846		      io->io_hdr.io_type);
12847		break; /* NOTREACHED */
12848	}
12849
12850	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12851	if (lun == NULL) {
12852		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
12853				 io->io_hdr.nexus.targ_mapped_lun));
12854		goto bailout;
12855	}
12856
12857	mtx_lock(&lun->lun_lock);
12858
12859	/*
12860	 * Check to see if we have any errors to inject here.  We only
12861	 * inject errors for commands that don't already have errors set.
12862	 */
12863	if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
12864	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
12865	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
12866		ctl_inject_error(lun, io);
12867
12868	/*
12869	 * XXX KDM how do we treat commands that aren't completed
12870	 * successfully?
12871	 *
12872	 * XXX KDM should we also track I/O latency?
12873	 */
12874	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
12875	    io->io_hdr.io_type == CTL_IO_SCSI) {
12876#ifdef CTL_TIME_IO
12877		struct bintime cur_bt;
12878#endif
12879		int type;
12880
12881		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12882		    CTL_FLAG_DATA_IN)
12883			type = CTL_STATS_READ;
12884		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12885		    CTL_FLAG_DATA_OUT)
12886			type = CTL_STATS_WRITE;
12887		else
12888			type = CTL_STATS_NO_IO;
12889
12890		lun->stats.ports[targ_port].bytes[type] +=
12891		    io->scsiio.kern_total_len;
12892		lun->stats.ports[targ_port].operations[type]++;
12893#ifdef CTL_TIME_IO
12894		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
12895		   &io->io_hdr.dma_bt);
12896		lun->stats.ports[targ_port].num_dmas[type] +=
12897		    io->io_hdr.num_dmas;
12898		getbintime(&cur_bt);
12899		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
12900		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
12901#endif
12902	}
12903
12904	/*
12905	 * Remove this from the OOA queue.
12906	 */
12907	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
12908#ifdef CTL_TIME_IO
12909	if (TAILQ_EMPTY(&lun->ooa_queue))
12910		lun->last_busy = getsbinuptime();
12911#endif
12912
12913	/*
12914	 * Run through the blocked queue on this LUN and see if anything
12915	 * has become unblocked, now that this transaction is done.
12916	 */
12917	ctl_check_blocked(lun);
12918
12919	/*
12920	 * If the LUN has been invalidated, free it if there is nothing
12921	 * left on its OOA queue.
12922	 */
12923	if ((lun->flags & CTL_LUN_INVALID)
12924	 && TAILQ_EMPTY(&lun->ooa_queue)) {
12925		mtx_unlock(&lun->lun_lock);
12926		mtx_lock(&softc->ctl_lock);
12927		ctl_free_lun(lun);
12928		mtx_unlock(&softc->ctl_lock);
12929	} else
12930		mtx_unlock(&lun->lun_lock);
12931
12932bailout:
12933
12934	/*
12935	 * If this command has been aborted, make sure we set the status
12936	 * properly.  The FETD is responsible for freeing the I/O and doing
12937	 * whatever it needs to do to clean up its state.
12938	 */
12939	if (io->io_hdr.flags & CTL_FLAG_ABORT)
12940		ctl_set_task_aborted(&io->scsiio);
12941
12942	/*
12943	 * If enabled, print command error status.
12944	 */
12945	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
12946	    (ctl_debug & CTL_DEBUG_INFO) != 0)
12947		ctl_io_error_print(io, NULL);
12948
12949	/*
12950	 * Tell the FETD or the other shelf controller we're done with this
12951	 * command.  Note that only SCSI commands get to this point.  Task
12952	 * management commands are completed above.
12953	 */
12954	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
12955	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
12956		memset(&msg, 0, sizeof(msg));
12957		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
12958		msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12959		msg.hdr.nexus = io->io_hdr.nexus;
12960		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12961		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
12962		    M_WAITOK);
12963	}
12964	if ((softc->ha_mode == CTL_HA_MODE_XFER)
12965	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12966		memset(&msg, 0, sizeof(msg));
12967		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
12968		msg.hdr.original_sc = io->io_hdr.original_sc;
12969		msg.hdr.nexus = io->io_hdr.nexus;
12970		msg.hdr.status = io->io_hdr.status;
12971		msg.scsi.scsi_status = io->scsiio.scsi_status;
12972		msg.scsi.tag_num = io->scsiio.tag_num;
12973		msg.scsi.tag_type = io->scsiio.tag_type;
12974		msg.scsi.sense_len = io->scsiio.sense_len;
12975		msg.scsi.sense_residual = io->scsiio.sense_residual;
12976		msg.scsi.residual = io->scsiio.residual;
12977		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12978		       io->scsiio.sense_len);
12979		/*
12980		 * We copy this whether or not this is an I/O-related
12981		 * command.  Otherwise, we'd have to go and check to see
12982		 * whether it's a read/write command, and it really isn't
12983		 * worth it.
12984		 */
12985		memcpy(&msg.scsi.lbalen,
12986		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
12987		       sizeof(msg.scsi.lbalen));
12988
12989		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12990		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12991		    msg.scsi.sense_len, M_WAITOK);
12992		ctl_free_io(io);
12993	} else
12994		fe_done(io);
12995
12996	return (CTL_RETVAL_COMPLETE);
12997}
12998
12999#ifdef CTL_WITH_CA
13000/*
13001 * Front end should call this if it doesn't do autosense.  When the request
13002 * sense comes back in from the initiator, we'll dequeue this and send it.
13003 */
13004int
13005ctl_queue_sense(union ctl_io *io)
13006{
13007	struct ctl_lun *lun;
13008	struct ctl_port *port;
13009	struct ctl_softc *softc;
13010	uint32_t initidx, targ_lun;
13011
13012	softc = control_softc;
13013
13014	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13015
13016	/*
13017	 * LUN lookup will likely move to the ctl_work_thread() once we
13018	 * have our new queueing infrastructure (that doesn't put things on
13019	 * a per-LUN queue initially).  That is so that we can handle
13020	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13021	 * can't deal with that right now.
13022	 */
13023	mtx_lock(&softc->ctl_lock);
13024
13025	/*
13026	 * If we don't have a LUN for this, just toss the sense
13027	 * information.
13028	 */
13029	port = ctl_io_port(&ctsio->io_hdr);
13030	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13031	if ((targ_lun < CTL_MAX_LUNS)
13032	 && (softc->ctl_luns[targ_lun] != NULL))
13033		lun = softc->ctl_luns[targ_lun];
13034	else
13035		goto bailout;
13036
13037	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13038
13039	mtx_lock(&lun->lun_lock);
13040	/*
13041	 * Already have CA set for this LUN...toss the sense information.
13042	 */
13043	if (ctl_is_set(lun->have_ca, initidx)) {
13044		mtx_unlock(&lun->lun_lock);
13045		goto bailout;
13046	}
13047
13048	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13049	       MIN(sizeof(lun->pending_sense[initidx]),
13050	       sizeof(io->scsiio.sense_data)));
13051	ctl_set_mask(lun->have_ca, initidx);
13052	mtx_unlock(&lun->lun_lock);
13053
13054bailout:
13055	mtx_unlock(&softc->ctl_lock);
13056
13057	ctl_free_io(io);
13058
13059	return (CTL_RETVAL_COMPLETE);
13060}
13061#endif
13062
13063/*
13064 * Primary command inlet from frontend ports.  All SCSI and task I/O
13065 * requests must go through this function.
13066 */
13067int
13068ctl_queue(union ctl_io *io)
13069{
13070	struct ctl_port *port;
13071
13072	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13073
13074#ifdef CTL_TIME_IO
13075	io->io_hdr.start_time = time_uptime;
13076	getbintime(&io->io_hdr.start_bt);
13077#endif /* CTL_TIME_IO */
13078
13079	/* Map FE-specific LUN ID into global one. */
13080	port = ctl_io_port(&io->io_hdr);
13081	io->io_hdr.nexus.targ_mapped_lun =
13082	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13083
13084	switch (io->io_hdr.io_type) {
13085	case CTL_IO_SCSI:
13086	case CTL_IO_TASK:
13087		if (ctl_debug & CTL_DEBUG_CDB)
13088			ctl_io_print(io);
13089		ctl_enqueue_incoming(io);
13090		break;
13091	default:
13092		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13093		return (EINVAL);
13094	}
13095
13096	return (CTL_RETVAL_COMPLETE);
13097}
13098
13099#ifdef CTL_IO_DELAY
13100static void
13101ctl_done_timer_wakeup(void *arg)
13102{
13103	union ctl_io *io;
13104
13105	io = (union ctl_io *)arg;
13106	ctl_done(io);
13107}
13108#endif /* CTL_IO_DELAY */
13109
13110void
13111ctl_done(union ctl_io *io)
13112{
13113
13114	/*
13115	 * Enable this to catch duplicate completion issues.
13116	 */
13117#if 0
13118	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13119		printf("%s: type %d msg %d cdb %x iptl: "
13120		       "%u:%u:%u tag 0x%04x "
13121		       "flag %#x status %x\n",
13122			__func__,
13123			io->io_hdr.io_type,
13124			io->io_hdr.msg_type,
13125			io->scsiio.cdb[0],
13126			io->io_hdr.nexus.initid,
13127			io->io_hdr.nexus.targ_port,
13128			io->io_hdr.nexus.targ_lun,
13129			(io->io_hdr.io_type ==
13130			CTL_IO_TASK) ?
13131			io->taskio.tag_num :
13132			io->scsiio.tag_num,
13133		        io->io_hdr.flags,
13134			io->io_hdr.status);
13135	} else
13136		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13137#endif
13138
13139	/*
13140	 * This is an internal copy of an I/O, and should not go through
13141	 * the normal done processing logic.
13142	 */
13143	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13144		return;
13145
13146#ifdef CTL_IO_DELAY
13147	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13148		struct ctl_lun *lun;
13149
13150		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13151
13152		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13153	} else {
13154		struct ctl_lun *lun;
13155
13156		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13157
13158		if ((lun != NULL)
13159		 && (lun->delay_info.done_delay > 0)) {
13160
13161			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13162			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13163			callout_reset(&io->io_hdr.delay_callout,
13164				      lun->delay_info.done_delay * hz,
13165				      ctl_done_timer_wakeup, io);
13166			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13167				lun->delay_info.done_delay = 0;
13168			return;
13169		}
13170	}
13171#endif /* CTL_IO_DELAY */
13172
13173	ctl_enqueue_done(io);
13174}
13175
13176static void
13177ctl_work_thread(void *arg)
13178{
13179	struct ctl_thread *thr = (struct ctl_thread *)arg;
13180	struct ctl_softc *softc = thr->ctl_softc;
13181	union ctl_io *io;
13182	int retval;
13183
13184	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13185
13186	for (;;) {
13187		retval = 0;
13188
13189		/*
13190		 * We handle the queues in this order:
13191		 * - ISC
13192		 * - done queue (to free up resources, unblock other commands)
13193		 * - RtR queue
13194		 * - incoming queue
13195		 *
13196		 * If those queues are empty, we break out of the loop and
13197		 * go to sleep.
13198		 */
13199		mtx_lock(&thr->queue_lock);
13200		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13201		if (io != NULL) {
13202			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13203			mtx_unlock(&thr->queue_lock);
13204			ctl_handle_isc(io);
13205			continue;
13206		}
13207		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13208		if (io != NULL) {
13209			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13210			/* clear any blocked commands, call fe_done */
13211			mtx_unlock(&thr->queue_lock);
13212			retval = ctl_process_done(io);
13213			continue;
13214		}
13215		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13216		if (io != NULL) {
13217			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13218			mtx_unlock(&thr->queue_lock);
13219			if (io->io_hdr.io_type == CTL_IO_TASK)
13220				ctl_run_task(io);
13221			else
13222				ctl_scsiio_precheck(softc, &io->scsiio);
13223			continue;
13224		}
13225		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13226		if (io != NULL) {
13227			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13228			mtx_unlock(&thr->queue_lock);
13229			retval = ctl_scsiio(&io->scsiio);
13230			if (retval != CTL_RETVAL_COMPLETE)
13231				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13232			continue;
13233		}
13234
13235		/* Sleep until we have something to do. */
13236		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13237	}
13238}
13239
13240static void
13241ctl_lun_thread(void *arg)
13242{
13243	struct ctl_softc *softc = (struct ctl_softc *)arg;
13244	struct ctl_be_lun *be_lun;
13245	int retval;
13246
13247	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13248
13249	for (;;) {
13250		retval = 0;
13251		mtx_lock(&softc->ctl_lock);
13252		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13253		if (be_lun != NULL) {
13254			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13255			mtx_unlock(&softc->ctl_lock);
13256			ctl_create_lun(be_lun);
13257			continue;
13258		}
13259
13260		/* Sleep until we have something to do. */
13261		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13262		    PDROP | PRIBIO, "-", 0);
13263	}
13264}
13265
13266static void
13267ctl_thresh_thread(void *arg)
13268{
13269	struct ctl_softc *softc = (struct ctl_softc *)arg;
13270	struct ctl_lun *lun;
13271	struct ctl_be_lun *be_lun;
13272	struct scsi_da_rw_recovery_page *rwpage;
13273	struct ctl_logical_block_provisioning_page *page;
13274	const char *attr;
13275	union ctl_ha_msg msg;
13276	uint64_t thres, val;
13277	int i, e, set;
13278
13279	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13280
13281	for (;;) {
13282		mtx_lock(&softc->ctl_lock);
13283		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13284			be_lun = lun->be_lun;
13285			if ((lun->flags & CTL_LUN_DISABLED) ||
13286			    (lun->flags & CTL_LUN_OFFLINE) ||
13287			    lun->backend->lun_attr == NULL)
13288				continue;
13289			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13290			    softc->ha_mode == CTL_HA_MODE_XFER)
13291				continue;
13292			rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13293			if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13294				continue;
13295			e = 0;
13296			page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13297			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13298				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13299					continue;
13300				thres = scsi_4btoul(page->descr[i].count);
13301				thres <<= CTL_LBP_EXPONENT;
13302				switch (page->descr[i].resource) {
13303				case 0x01:
13304					attr = "blocksavail";
13305					break;
13306				case 0x02:
13307					attr = "blocksused";
13308					break;
13309				case 0xf1:
13310					attr = "poolblocksavail";
13311					break;
13312				case 0xf2:
13313					attr = "poolblocksused";
13314					break;
13315				default:
13316					continue;
13317				}
13318				mtx_unlock(&softc->ctl_lock); // XXX
13319				val = lun->backend->lun_attr(
13320				    lun->be_lun->be_lun, attr);
13321				mtx_lock(&softc->ctl_lock);
13322				if (val == UINT64_MAX)
13323					continue;
13324				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13325				    == SLBPPD_ARMING_INC)
13326					e |= (val >= thres);
13327				else
13328					e |= (val <= thres);
13329			}
13330			mtx_lock(&lun->lun_lock);
13331			if (e) {
13332				if (lun->lasttpt == 0 ||
13333				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13334					lun->lasttpt = time_uptime;
13335					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13336					set = 1;
13337				} else
13338					set = 0;
13339			} else {
13340				lun->lasttpt = 0;
13341				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13342				set = -1;
13343			}
13344			mtx_unlock(&lun->lun_lock);
13345			if (set != 0 &&
13346			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13347				/* Send msg to other side. */
13348				bzero(&msg.ua, sizeof(msg.ua));
13349				msg.hdr.msg_type = CTL_MSG_UA;
13350				msg.hdr.nexus.initid = -1;
13351				msg.hdr.nexus.targ_port = -1;
13352				msg.hdr.nexus.targ_lun = lun->lun;
13353				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13354				msg.ua.ua_all = 1;
13355				msg.ua.ua_set = (set > 0);
13356				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13357				mtx_unlock(&softc->ctl_lock); // XXX
13358				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13359				    sizeof(msg.ua), M_WAITOK);
13360				mtx_lock(&softc->ctl_lock);
13361			}
13362		}
13363		mtx_unlock(&softc->ctl_lock);
13364		pause("-", CTL_LBP_PERIOD * hz);
13365	}
13366}
13367
13368static void
13369ctl_enqueue_incoming(union ctl_io *io)
13370{
13371	struct ctl_softc *softc = control_softc;
13372	struct ctl_thread *thr;
13373	u_int idx;
13374
13375	idx = (io->io_hdr.nexus.targ_port * 127 +
13376	       io->io_hdr.nexus.initid) % worker_threads;
13377	thr = &softc->threads[idx];
13378	mtx_lock(&thr->queue_lock);
13379	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13380	mtx_unlock(&thr->queue_lock);
13381	wakeup(thr);
13382}
13383
13384static void
13385ctl_enqueue_rtr(union ctl_io *io)
13386{
13387	struct ctl_softc *softc = control_softc;
13388	struct ctl_thread *thr;
13389
13390	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13391	mtx_lock(&thr->queue_lock);
13392	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13393	mtx_unlock(&thr->queue_lock);
13394	wakeup(thr);
13395}
13396
13397static void
13398ctl_enqueue_done(union ctl_io *io)
13399{
13400	struct ctl_softc *softc = control_softc;
13401	struct ctl_thread *thr;
13402
13403	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13404	mtx_lock(&thr->queue_lock);
13405	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13406	mtx_unlock(&thr->queue_lock);
13407	wakeup(thr);
13408}
13409
13410static void
13411ctl_enqueue_isc(union ctl_io *io)
13412{
13413	struct ctl_softc *softc = control_softc;
13414	struct ctl_thread *thr;
13415
13416	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13417	mtx_lock(&thr->queue_lock);
13418	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13419	mtx_unlock(&thr->queue_lock);
13420	wakeup(thr);
13421}
13422
13423/*
13424 *  vim: ts=8
13425 */
13426