ctl.c revision 287778
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 287778 2015-09-14 09:56:01Z 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	ctl_enqueue_isc((union ctl_io *)ctsio);
520}
521
522static void
523ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
524				union ctl_ha_msg *msg_info)
525{
526	struct ctl_scsiio *ctsio;
527
528	if (msg_info->hdr.serializing_sc == NULL) {
529		printf("%s: serializing_sc == NULL!\n", __func__);
530		/* XXX KDM now what? */
531		return;
532	}
533
534	ctsio = &msg_info->hdr.serializing_sc->scsiio;
535	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
536	ctl_enqueue_isc((union ctl_io *)ctsio);
537}
538
539void
540ctl_isc_announce_lun(struct ctl_lun *lun)
541{
542	struct ctl_softc *softc = lun->ctl_softc;
543	union ctl_ha_msg *msg;
544	struct ctl_ha_msg_lun_pr_key pr_key;
545	int i, k;
546
547	if (softc->ha_link != CTL_HA_LINK_ONLINE)
548		return;
549	mtx_lock(&lun->lun_lock);
550	i = sizeof(msg->lun);
551	if (lun->lun_devid)
552		i += lun->lun_devid->len;
553	i += sizeof(pr_key) * lun->pr_key_count;
554alloc:
555	mtx_unlock(&lun->lun_lock);
556	msg = malloc(i, M_CTL, M_WAITOK);
557	mtx_lock(&lun->lun_lock);
558	k = sizeof(msg->lun);
559	if (lun->lun_devid)
560		k += lun->lun_devid->len;
561	k += sizeof(pr_key) * lun->pr_key_count;
562	if (i < k) {
563		free(msg, M_CTL);
564		i = k;
565		goto alloc;
566	}
567	bzero(&msg->lun, sizeof(msg->lun));
568	msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
569	msg->hdr.nexus.targ_lun = lun->lun;
570	msg->hdr.nexus.targ_mapped_lun = lun->lun;
571	msg->lun.flags = lun->flags;
572	msg->lun.pr_generation = lun->PRGeneration;
573	msg->lun.pr_res_idx = lun->pr_res_idx;
574	msg->lun.pr_res_type = lun->res_type;
575	msg->lun.pr_key_count = lun->pr_key_count;
576	i = 0;
577	if (lun->lun_devid) {
578		msg->lun.lun_devid_len = lun->lun_devid->len;
579		memcpy(&msg->lun.data[i], lun->lun_devid->data,
580		    msg->lun.lun_devid_len);
581		i += msg->lun.lun_devid_len;
582	}
583	for (k = 0; k < CTL_MAX_INITIATORS; k++) {
584		if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
585			continue;
586		pr_key.pr_iid = k;
587		memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
588		i += sizeof(pr_key);
589	}
590	mtx_unlock(&lun->lun_lock);
591	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
592	    M_WAITOK);
593	free(msg, M_CTL);
594}
595
596void
597ctl_isc_announce_port(struct ctl_port *port)
598{
599	struct ctl_softc *softc = control_softc;
600	union ctl_ha_msg *msg;
601	int i;
602
603	if (port->targ_port < softc->port_min ||
604	    port->targ_port >= softc->port_max ||
605	    softc->ha_link != CTL_HA_LINK_ONLINE)
606		return;
607	i = sizeof(msg->port) + strlen(port->port_name) + 1;
608	if (port->lun_map)
609		i += sizeof(uint32_t) * CTL_MAX_LUNS;
610	if (port->port_devid)
611		i += port->port_devid->len;
612	if (port->target_devid)
613		i += port->target_devid->len;
614	msg = malloc(i, M_CTL, M_WAITOK);
615	bzero(&msg->port, sizeof(msg->port));
616	msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
617	msg->hdr.nexus.targ_port = port->targ_port;
618	msg->port.port_type = port->port_type;
619	msg->port.physical_port = port->physical_port;
620	msg->port.virtual_port = port->virtual_port;
621	msg->port.status = port->status;
622	i = 0;
623	msg->port.name_len = sprintf(&msg->port.data[i],
624	    "%d:%s", softc->ha_id, port->port_name) + 1;
625	i += msg->port.name_len;
626	if (port->lun_map) {
627		msg->port.lun_map_len = sizeof(uint32_t) * CTL_MAX_LUNS;
628		memcpy(&msg->port.data[i], port->lun_map,
629		    msg->port.lun_map_len);
630		i += msg->port.lun_map_len;
631	}
632	if (port->port_devid) {
633		msg->port.port_devid_len = port->port_devid->len;
634		memcpy(&msg->port.data[i], port->port_devid->data,
635		    msg->port.port_devid_len);
636		i += msg->port.port_devid_len;
637	}
638	if (port->target_devid) {
639		msg->port.target_devid_len = port->target_devid->len;
640		memcpy(&msg->port.data[i], port->target_devid->data,
641		    msg->port.target_devid_len);
642		i += msg->port.target_devid_len;
643	}
644	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
645	    M_WAITOK);
646	free(msg, M_CTL);
647}
648
649static void
650ctl_isc_ha_link_up(struct ctl_softc *softc)
651{
652	struct ctl_port *port;
653	struct ctl_lun *lun;
654
655	STAILQ_FOREACH(port, &softc->port_list, links)
656		ctl_isc_announce_port(port);
657	STAILQ_FOREACH(lun, &softc->lun_list, links)
658		ctl_isc_announce_lun(lun);
659}
660
661static void
662ctl_isc_ha_link_down(struct ctl_softc *softc)
663{
664	struct ctl_port *port;
665	struct ctl_lun *lun;
666	union ctl_io *io;
667
668	mtx_lock(&softc->ctl_lock);
669	STAILQ_FOREACH(lun, &softc->lun_list, links) {
670		mtx_lock(&lun->lun_lock);
671		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
672			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
673			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
674		}
675		mtx_unlock(&lun->lun_lock);
676
677		mtx_unlock(&softc->ctl_lock);
678		io = ctl_alloc_io(softc->othersc_pool);
679		mtx_lock(&softc->ctl_lock);
680		ctl_zero_io(io);
681		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
682		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
683		ctl_enqueue_isc(io);
684	}
685
686	STAILQ_FOREACH(port, &softc->port_list, links) {
687		if (port->targ_port >= softc->port_min &&
688		    port->targ_port < softc->port_max)
689			continue;
690		port->status &= ~CTL_PORT_STATUS_ONLINE;
691	}
692	mtx_unlock(&softc->ctl_lock);
693}
694
695static void
696ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
697{
698	struct ctl_lun *lun;
699	uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
700
701	mtx_lock(&softc->ctl_lock);
702	if (msg->hdr.nexus.targ_lun < CTL_MAX_LUNS &&
703	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) != NULL) {
704		mtx_lock(&lun->lun_lock);
705		mtx_unlock(&softc->ctl_lock);
706		if (msg->ua.ua_all) {
707			if (msg->ua.ua_set)
708				ctl_est_ua_all(lun, iid, msg->ua.ua_type);
709			else
710				ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
711		} else {
712			if (msg->ua.ua_set)
713				ctl_est_ua(lun, iid, msg->ua.ua_type);
714			else
715				ctl_clr_ua(lun, iid, msg->ua.ua_type);
716		}
717		mtx_unlock(&lun->lun_lock);
718	} else
719		mtx_unlock(&softc->ctl_lock);
720}
721
722static void
723ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
724{
725	struct ctl_lun *lun;
726	struct ctl_ha_msg_lun_pr_key pr_key;
727	int i, k;
728	ctl_lun_flags oflags;
729	uint32_t targ_lun;
730
731	targ_lun = msg->hdr.nexus.targ_mapped_lun;
732	mtx_lock(&softc->ctl_lock);
733	if ((targ_lun >= CTL_MAX_LUNS) ||
734	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
735		mtx_unlock(&softc->ctl_lock);
736		return;
737	}
738	mtx_lock(&lun->lun_lock);
739	mtx_unlock(&softc->ctl_lock);
740	if (lun->flags & CTL_LUN_DISABLED) {
741		mtx_unlock(&lun->lun_lock);
742		return;
743	}
744	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
745	if (msg->lun.lun_devid_len != i || (i > 0 &&
746	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
747		mtx_unlock(&lun->lun_lock);
748		printf("%s: Received conflicting HA LUN %d\n",
749		    __func__, msg->hdr.nexus.targ_lun);
750		return;
751	} else {
752		/* Record whether peer is primary. */
753		oflags = lun->flags;
754		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
755		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
756			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
757		else
758			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
759		if (oflags != lun->flags)
760			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
761
762		/* If peer is primary and we are not -- use data */
763		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
764		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
765			lun->PRGeneration = msg->lun.pr_generation;
766			lun->pr_res_idx = msg->lun.pr_res_idx;
767			lun->res_type = msg->lun.pr_res_type;
768			lun->pr_key_count = msg->lun.pr_key_count;
769			for (k = 0; k < CTL_MAX_INITIATORS; k++)
770				ctl_clr_prkey(lun, k);
771			for (k = 0; k < msg->lun.pr_key_count; k++) {
772				memcpy(&pr_key, &msg->lun.data[i],
773				    sizeof(pr_key));
774				ctl_alloc_prkey(lun, pr_key.pr_iid);
775				ctl_set_prkey(lun, pr_key.pr_iid,
776				    pr_key.pr_key);
777				i += sizeof(pr_key);
778			}
779		}
780
781		mtx_unlock(&lun->lun_lock);
782		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
783		    __func__, msg->hdr.nexus.targ_lun,
784		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
785		    "primary" : "secondary"));
786
787		/* If we are primary but peer doesn't know -- notify */
788		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
789		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
790			ctl_isc_announce_lun(lun);
791	}
792}
793
794static void
795ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
796{
797	struct ctl_port *port;
798	struct ctl_lun *lun;
799	int i, new;
800
801	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
802	if (port == NULL) {
803		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
804		    msg->hdr.nexus.targ_port));
805		new = 1;
806		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
807		port->frontend = &ha_frontend;
808		port->targ_port = msg->hdr.nexus.targ_port;
809	} else if (port->frontend == &ha_frontend) {
810		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
811		    msg->hdr.nexus.targ_port));
812		new = 0;
813	} else {
814		printf("%s: Received conflicting HA port %d\n",
815		    __func__, msg->hdr.nexus.targ_port);
816		return;
817	}
818	port->port_type = msg->port.port_type;
819	port->physical_port = msg->port.physical_port;
820	port->virtual_port = msg->port.virtual_port;
821	port->status = msg->port.status;
822	i = 0;
823	free(port->port_name, M_CTL);
824	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
825	    M_CTL);
826	i += msg->port.name_len;
827	if (msg->port.lun_map_len != 0) {
828		if (port->lun_map == NULL)
829			port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
830			    M_CTL, M_WAITOK);
831		memcpy(port->lun_map, &msg->port.data[i],
832		    sizeof(uint32_t) * CTL_MAX_LUNS);
833		i += msg->port.lun_map_len;
834	} else {
835		free(port->lun_map, M_CTL);
836		port->lun_map = NULL;
837	}
838	if (msg->port.port_devid_len != 0) {
839		if (port->port_devid == NULL ||
840		    port->port_devid->len != msg->port.port_devid_len) {
841			free(port->port_devid, M_CTL);
842			port->port_devid = malloc(sizeof(struct ctl_devid) +
843			    msg->port.port_devid_len, M_CTL, M_WAITOK);
844		}
845		memcpy(port->port_devid->data, &msg->port.data[i],
846		    msg->port.port_devid_len);
847		port->port_devid->len = msg->port.port_devid_len;
848		i += msg->port.port_devid_len;
849	} else {
850		free(port->port_devid, M_CTL);
851		port->port_devid = NULL;
852	}
853	if (msg->port.target_devid_len != 0) {
854		if (port->target_devid == NULL ||
855		    port->target_devid->len != msg->port.target_devid_len) {
856			free(port->target_devid, M_CTL);
857			port->target_devid = malloc(sizeof(struct ctl_devid) +
858			    msg->port.target_devid_len, M_CTL, M_WAITOK);
859		}
860		memcpy(port->target_devid->data, &msg->port.data[i],
861		    msg->port.target_devid_len);
862		port->target_devid->len = msg->port.target_devid_len;
863		i += msg->port.target_devid_len;
864	} else {
865		free(port->port_devid, M_CTL);
866		port->port_devid = NULL;
867	}
868	if (new) {
869		if (ctl_port_register(port) != 0) {
870			printf("%s: ctl_port_register() failed with error\n",
871			    __func__);
872		}
873	}
874	mtx_lock(&softc->ctl_lock);
875	STAILQ_FOREACH(lun, &softc->lun_list, links) {
876		if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
877			continue;
878		mtx_lock(&lun->lun_lock);
879		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
880		mtx_unlock(&lun->lun_lock);
881	}
882	mtx_unlock(&softc->ctl_lock);
883}
884
885/*
886 * ISC (Inter Shelf Communication) event handler.  Events from the HA
887 * subsystem come in here.
888 */
889static void
890ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
891{
892	struct ctl_softc *softc;
893	union ctl_io *io;
894	struct ctl_prio *presio;
895	ctl_ha_status isc_status;
896
897	softc = control_softc;
898	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
899	if (event == CTL_HA_EVT_MSG_RECV) {
900		union ctl_ha_msg *msg, msgbuf;
901
902		if (param > sizeof(msgbuf))
903			msg = malloc(param, M_CTL, M_WAITOK);
904		else
905			msg = &msgbuf;
906		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
907		    M_WAITOK);
908		if (isc_status != CTL_HA_STATUS_SUCCESS) {
909			printf("%s: Error receiving message: %d\n",
910			    __func__, isc_status);
911			if (msg != &msgbuf)
912				free(msg, M_CTL);
913			return;
914		}
915
916		CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
917		switch (msg->hdr.msg_type) {
918		case CTL_MSG_SERIALIZE:
919			io = ctl_alloc_io(softc->othersc_pool);
920			ctl_zero_io(io);
921			// populate ctsio from msg
922			io->io_hdr.io_type = CTL_IO_SCSI;
923			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
924			io->io_hdr.original_sc = msg->hdr.original_sc;
925			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
926					    CTL_FLAG_IO_ACTIVE;
927			/*
928			 * If we're in serialization-only mode, we don't
929			 * want to go through full done processing.  Thus
930			 * the COPY flag.
931			 *
932			 * XXX KDM add another flag that is more specific.
933			 */
934			if (softc->ha_mode != CTL_HA_MODE_XFER)
935				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
936			io->io_hdr.nexus = msg->hdr.nexus;
937#if 0
938			printf("port %u, iid %u, lun %u\n",
939			       io->io_hdr.nexus.targ_port,
940			       io->io_hdr.nexus.initid,
941			       io->io_hdr.nexus.targ_lun);
942#endif
943			io->scsiio.tag_num = msg->scsi.tag_num;
944			io->scsiio.tag_type = msg->scsi.tag_type;
945#ifdef CTL_TIME_IO
946			io->io_hdr.start_time = time_uptime;
947			getbintime(&io->io_hdr.start_bt);
948#endif /* CTL_TIME_IO */
949			io->scsiio.cdb_len = msg->scsi.cdb_len;
950			memcpy(io->scsiio.cdb, msg->scsi.cdb,
951			       CTL_MAX_CDBLEN);
952			if (softc->ha_mode == CTL_HA_MODE_XFER) {
953				const struct ctl_cmd_entry *entry;
954
955				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
956				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
957				io->io_hdr.flags |=
958					entry->flags & CTL_FLAG_DATA_MASK;
959			}
960			ctl_enqueue_isc(io);
961			break;
962
963		/* Performed on the Originating SC, XFER mode only */
964		case CTL_MSG_DATAMOVE: {
965			struct ctl_sg_entry *sgl;
966			int i, j;
967
968			io = msg->hdr.original_sc;
969			if (io == NULL) {
970				printf("%s: original_sc == NULL!\n", __func__);
971				/* XXX KDM do something here */
972				break;
973			}
974			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
975			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
976			/*
977			 * Keep track of this, we need to send it back over
978			 * when the datamove is complete.
979			 */
980			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
981
982			if (msg->dt.sg_sequence == 0) {
983				i = msg->dt.kern_sg_entries +
984				    io->scsiio.kern_data_len /
985				    CTL_HA_DATAMOVE_SEGMENT + 1;
986				sgl = malloc(sizeof(*sgl) * i, M_CTL,
987				    M_WAITOK | M_ZERO);
988				io->io_hdr.remote_sglist = sgl;
989				io->io_hdr.local_sglist =
990				    &sgl[msg->dt.kern_sg_entries];
991
992				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
993
994				io->scsiio.kern_sg_entries =
995					msg->dt.kern_sg_entries;
996				io->scsiio.rem_sg_entries =
997					msg->dt.kern_sg_entries;
998				io->scsiio.kern_data_len =
999					msg->dt.kern_data_len;
1000				io->scsiio.kern_total_len =
1001					msg->dt.kern_total_len;
1002				io->scsiio.kern_data_resid =
1003					msg->dt.kern_data_resid;
1004				io->scsiio.kern_rel_offset =
1005					msg->dt.kern_rel_offset;
1006				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1007				io->io_hdr.flags |= msg->dt.flags &
1008				    CTL_FLAG_BUS_ADDR;
1009			} else
1010				sgl = (struct ctl_sg_entry *)
1011					io->scsiio.kern_data_ptr;
1012
1013			for (i = msg->dt.sent_sg_entries, j = 0;
1014			     i < (msg->dt.sent_sg_entries +
1015			     msg->dt.cur_sg_entries); i++, j++) {
1016				sgl[i].addr = msg->dt.sg_list[j].addr;
1017				sgl[i].len = msg->dt.sg_list[j].len;
1018
1019#if 0
1020				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
1021				       __func__,
1022				       msg->dt.sg_list[j].addr,
1023				       msg->dt.sg_list[j].len,
1024				       sgl[i].addr, sgl[i].len, j, i);
1025#endif
1026			}
1027
1028			/*
1029			 * If this is the last piece of the I/O, we've got
1030			 * the full S/G list.  Queue processing in the thread.
1031			 * Otherwise wait for the next piece.
1032			 */
1033			if (msg->dt.sg_last != 0)
1034				ctl_enqueue_isc(io);
1035			break;
1036		}
1037		/* Performed on the Serializing (primary) SC, XFER mode only */
1038		case CTL_MSG_DATAMOVE_DONE: {
1039			if (msg->hdr.serializing_sc == NULL) {
1040				printf("%s: serializing_sc == NULL!\n",
1041				       __func__);
1042				/* XXX KDM now what? */
1043				break;
1044			}
1045			/*
1046			 * We grab the sense information here in case
1047			 * there was a failure, so we can return status
1048			 * back to the initiator.
1049			 */
1050			io = msg->hdr.serializing_sc;
1051			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1052			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1053			io->io_hdr.port_status = msg->scsi.fetd_status;
1054			io->scsiio.residual = msg->scsi.residual;
1055			if (msg->hdr.status != CTL_STATUS_NONE) {
1056				io->io_hdr.status = msg->hdr.status;
1057				io->scsiio.scsi_status = msg->scsi.scsi_status;
1058				io->scsiio.sense_len = msg->scsi.sense_len;
1059				io->scsiio.sense_residual =msg->scsi.sense_residual;
1060				memcpy(&io->scsiio.sense_data,
1061				    &msg->scsi.sense_data,
1062				    msg->scsi.sense_len);
1063			}
1064			ctl_enqueue_isc(io);
1065			break;
1066		}
1067
1068		/* Preformed on Originating SC, SER_ONLY mode */
1069		case CTL_MSG_R2R:
1070			io = msg->hdr.original_sc;
1071			if (io == NULL) {
1072				printf("%s: original_sc == NULL!\n",
1073				    __func__);
1074				break;
1075			}
1076			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1077			io->io_hdr.msg_type = CTL_MSG_R2R;
1078			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1079			ctl_enqueue_isc(io);
1080			break;
1081
1082		/*
1083		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1084		 * mode.
1085		 * Performed on the Originating (i.e. secondary) SC in XFER
1086		 * mode
1087		 */
1088		case CTL_MSG_FINISH_IO:
1089			if (softc->ha_mode == CTL_HA_MODE_XFER)
1090				ctl_isc_handler_finish_xfer(softc, msg);
1091			else
1092				ctl_isc_handler_finish_ser_only(softc, msg);
1093			break;
1094
1095		/* Preformed on Originating SC */
1096		case CTL_MSG_BAD_JUJU:
1097			io = msg->hdr.original_sc;
1098			if (io == NULL) {
1099				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1100				       __func__);
1101				break;
1102			}
1103			ctl_copy_sense_data(msg, io);
1104			/*
1105			 * IO should have already been cleaned up on other
1106			 * SC so clear this flag so we won't send a message
1107			 * back to finish the IO there.
1108			 */
1109			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1110			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1111
1112			/* io = msg->hdr.serializing_sc; */
1113			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1114			ctl_enqueue_isc(io);
1115			break;
1116
1117		/* Handle resets sent from the other side */
1118		case CTL_MSG_MANAGE_TASKS: {
1119			struct ctl_taskio *taskio;
1120			taskio = (struct ctl_taskio *)ctl_alloc_io(
1121			    softc->othersc_pool);
1122			ctl_zero_io((union ctl_io *)taskio);
1123			taskio->io_hdr.io_type = CTL_IO_TASK;
1124			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1125			taskio->io_hdr.nexus = msg->hdr.nexus;
1126			taskio->task_action = msg->task.task_action;
1127			taskio->tag_num = msg->task.tag_num;
1128			taskio->tag_type = msg->task.tag_type;
1129#ifdef CTL_TIME_IO
1130			taskio->io_hdr.start_time = time_uptime;
1131			getbintime(&taskio->io_hdr.start_bt);
1132#endif /* CTL_TIME_IO */
1133			ctl_run_task((union ctl_io *)taskio);
1134			break;
1135		}
1136		/* Persistent Reserve action which needs attention */
1137		case CTL_MSG_PERS_ACTION:
1138			presio = (struct ctl_prio *)ctl_alloc_io(
1139			    softc->othersc_pool);
1140			ctl_zero_io((union ctl_io *)presio);
1141			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1142			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1143			presio->io_hdr.nexus = msg->hdr.nexus;
1144			presio->pr_msg = msg->pr;
1145			ctl_enqueue_isc((union ctl_io *)presio);
1146			break;
1147		case CTL_MSG_UA:
1148			ctl_isc_ua(softc, msg, param);
1149			break;
1150		case CTL_MSG_PORT_SYNC:
1151			ctl_isc_port_sync(softc, msg, param);
1152			break;
1153		case CTL_MSG_LUN_SYNC:
1154			ctl_isc_lun_sync(softc, msg, param);
1155			break;
1156		default:
1157			printf("Received HA message of unknown type %d\n",
1158			    msg->hdr.msg_type);
1159			break;
1160		}
1161		if (msg != &msgbuf)
1162			free(msg, M_CTL);
1163	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1164		printf("CTL: HA link status changed from %d to %d\n",
1165		    softc->ha_link, param);
1166		if (param == softc->ha_link)
1167			return;
1168		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1169			softc->ha_link = param;
1170			ctl_isc_ha_link_down(softc);
1171		} else {
1172			softc->ha_link = param;
1173			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1174				ctl_isc_ha_link_up(softc);
1175		}
1176		return;
1177	} else {
1178		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1179		return;
1180	}
1181}
1182
1183static void
1184ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1185{
1186
1187	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1188	    src->scsi.sense_len);
1189	dest->scsiio.scsi_status = src->scsi.scsi_status;
1190	dest->scsiio.sense_len = src->scsi.sense_len;
1191	dest->io_hdr.status = src->hdr.status;
1192}
1193
1194static void
1195ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1196{
1197
1198	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1199	    src->scsiio.sense_len);
1200	dest->scsi.scsi_status = src->scsiio.scsi_status;
1201	dest->scsi.sense_len = src->scsiio.sense_len;
1202	dest->hdr.status = src->io_hdr.status;
1203}
1204
1205void
1206ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1207{
1208	struct ctl_softc *softc = lun->ctl_softc;
1209	ctl_ua_type *pu;
1210
1211	if (initidx < softc->init_min || initidx >= softc->init_max)
1212		return;
1213	mtx_assert(&lun->lun_lock, MA_OWNED);
1214	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1215	if (pu == NULL)
1216		return;
1217	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1218}
1219
1220void
1221ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1222{
1223	int i;
1224
1225	mtx_assert(&lun->lun_lock, MA_OWNED);
1226	if (lun->pending_ua[port] == NULL)
1227		return;
1228	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1229		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1230			continue;
1231		lun->pending_ua[port][i] |= ua;
1232	}
1233}
1234
1235void
1236ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1237{
1238	struct ctl_softc *softc = lun->ctl_softc;
1239	int i;
1240
1241	mtx_assert(&lun->lun_lock, MA_OWNED);
1242	for (i = softc->port_min; i < softc->port_max; i++)
1243		ctl_est_ua_port(lun, i, except, ua);
1244}
1245
1246void
1247ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1248{
1249	struct ctl_softc *softc = lun->ctl_softc;
1250	ctl_ua_type *pu;
1251
1252	if (initidx < softc->init_min || initidx >= softc->init_max)
1253		return;
1254	mtx_assert(&lun->lun_lock, MA_OWNED);
1255	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1256	if (pu == NULL)
1257		return;
1258	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1259}
1260
1261void
1262ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1263{
1264	struct ctl_softc *softc = lun->ctl_softc;
1265	int i, j;
1266
1267	mtx_assert(&lun->lun_lock, MA_OWNED);
1268	for (i = softc->port_min; i < softc->port_max; i++) {
1269		if (lun->pending_ua[i] == NULL)
1270			continue;
1271		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1272			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1273				continue;
1274			lun->pending_ua[i][j] &= ~ua;
1275		}
1276	}
1277}
1278
1279void
1280ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1281    ctl_ua_type ua_type)
1282{
1283	struct ctl_lun *lun;
1284
1285	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1286	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1287		mtx_lock(&lun->lun_lock);
1288		ctl_clr_ua(lun, initidx, ua_type);
1289		mtx_unlock(&lun->lun_lock);
1290	}
1291}
1292
1293static int
1294ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1295{
1296	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1297	struct ctl_lun *lun;
1298	struct ctl_lun_req ireq;
1299	int error, value;
1300
1301	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1302	error = sysctl_handle_int(oidp, &value, 0, req);
1303	if ((error != 0) || (req->newptr == NULL))
1304		return (error);
1305
1306	mtx_lock(&softc->ctl_lock);
1307	if (value == 0)
1308		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1309	else
1310		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1311	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1312		mtx_unlock(&softc->ctl_lock);
1313		bzero(&ireq, sizeof(ireq));
1314		ireq.reqtype = CTL_LUNREQ_MODIFY;
1315		ireq.reqdata.modify.lun_id = lun->lun;
1316		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1317		    curthread);
1318		if (ireq.status != CTL_LUN_OK) {
1319			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1320			    __func__, ireq.status, ireq.error_str);
1321		}
1322		mtx_lock(&softc->ctl_lock);
1323	}
1324	mtx_unlock(&softc->ctl_lock);
1325	return (0);
1326}
1327
1328static int
1329ctl_init(void)
1330{
1331	struct ctl_softc *softc;
1332	void *other_pool;
1333	int i, error, retval;
1334
1335	retval = 0;
1336	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1337			       M_WAITOK | M_ZERO);
1338	softc = control_softc;
1339
1340	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1341			      "cam/ctl");
1342
1343	softc->dev->si_drv1 = softc;
1344
1345	sysctl_ctx_init(&softc->sysctl_ctx);
1346	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1347		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1348		CTLFLAG_RD, 0, "CAM Target Layer");
1349
1350	if (softc->sysctl_tree == NULL) {
1351		printf("%s: unable to allocate sysctl tree\n", __func__);
1352		destroy_dev(softc->dev);
1353		free(control_softc, M_DEVBUF);
1354		control_softc = NULL;
1355		return (ENOMEM);
1356	}
1357
1358	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1359	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1360	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1361	softc->open_count = 0;
1362
1363	/*
1364	 * Default to actually sending a SYNCHRONIZE CACHE command down to
1365	 * the drive.
1366	 */
1367	softc->flags = CTL_FLAG_REAL_SYNC;
1368
1369	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1370	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1371	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1372
1373	/*
1374	 * In Copan's HA scheme, the "master" and "slave" roles are
1375	 * figured out through the slot the controller is in.  Although it
1376	 * is an active/active system, someone has to be in charge.
1377	 */
1378	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1379	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1380	    "HA head ID (0 - no HA)");
1381	if (softc->ha_id == 0 || softc->ha_id > NUM_TARGET_PORT_GROUPS) {
1382		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1383		softc->is_single = 1;
1384		softc->port_cnt = CTL_MAX_PORTS;
1385		softc->port_min = 0;
1386	} else {
1387		softc->port_cnt = CTL_MAX_PORTS / NUM_TARGET_PORT_GROUPS;
1388		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1389	}
1390	softc->port_max = softc->port_min + softc->port_cnt;
1391	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1392	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1393
1394	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1395	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1396	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
1397
1398	STAILQ_INIT(&softc->lun_list);
1399	STAILQ_INIT(&softc->pending_lun_queue);
1400	STAILQ_INIT(&softc->fe_list);
1401	STAILQ_INIT(&softc->port_list);
1402	STAILQ_INIT(&softc->be_list);
1403	ctl_tpc_init(softc);
1404
1405	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1406	                    &other_pool) != 0)
1407	{
1408		printf("ctl: can't allocate %d entry other SC pool, "
1409		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1410		return (ENOMEM);
1411	}
1412	softc->othersc_pool = other_pool;
1413
1414	if (worker_threads <= 0)
1415		worker_threads = max(1, mp_ncpus / 4);
1416	if (worker_threads > CTL_MAX_THREADS)
1417		worker_threads = CTL_MAX_THREADS;
1418
1419	for (i = 0; i < worker_threads; i++) {
1420		struct ctl_thread *thr = &softc->threads[i];
1421
1422		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1423		thr->ctl_softc = softc;
1424		STAILQ_INIT(&thr->incoming_queue);
1425		STAILQ_INIT(&thr->rtr_queue);
1426		STAILQ_INIT(&thr->done_queue);
1427		STAILQ_INIT(&thr->isc_queue);
1428
1429		error = kproc_kthread_add(ctl_work_thread, thr,
1430		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1431		if (error != 0) {
1432			printf("error creating CTL work thread!\n");
1433			ctl_pool_free(other_pool);
1434			return (error);
1435		}
1436	}
1437	error = kproc_kthread_add(ctl_lun_thread, softc,
1438	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1439	if (error != 0) {
1440		printf("error creating CTL lun thread!\n");
1441		ctl_pool_free(other_pool);
1442		return (error);
1443	}
1444	error = kproc_kthread_add(ctl_thresh_thread, softc,
1445	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1446	if (error != 0) {
1447		printf("error creating CTL threshold thread!\n");
1448		ctl_pool_free(other_pool);
1449		return (error);
1450	}
1451
1452	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1453	    OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1454	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1455
1456	if (softc->is_single == 0) {
1457		ctl_frontend_register(&ha_frontend);
1458		if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
1459			printf("ctl_init: ctl_ha_msg_init failed.\n");
1460			softc->is_single = 1;
1461		} else
1462		if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
1463		    != CTL_HA_STATUS_SUCCESS) {
1464			printf("ctl_init: ctl_ha_msg_register failed.\n");
1465			softc->is_single = 1;
1466		}
1467	}
1468	return (0);
1469}
1470
1471void
1472ctl_shutdown(void)
1473{
1474	struct ctl_softc *softc;
1475	struct ctl_lun *lun, *next_lun;
1476
1477	softc = (struct ctl_softc *)control_softc;
1478
1479	if (softc->is_single == 0) {
1480		if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL)
1481		    != CTL_HA_STATUS_SUCCESS) {
1482			printf("ctl_shutdown: ctl_ha_msg_deregister failed.\n");
1483		}
1484		if (ctl_ha_msg_shutdown(softc) != CTL_HA_STATUS_SUCCESS) {
1485			printf("ctl_shutdown: ctl_ha_msg_shutdown failed.\n");
1486		}
1487		ctl_frontend_deregister(&ha_frontend);
1488	}
1489
1490	mtx_lock(&softc->ctl_lock);
1491
1492	/*
1493	 * Free up each LUN.
1494	 */
1495	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1496		next_lun = STAILQ_NEXT(lun, links);
1497		ctl_free_lun(lun);
1498	}
1499
1500	mtx_unlock(&softc->ctl_lock);
1501
1502#if 0
1503	ctl_shutdown_thread(softc->work_thread);
1504	mtx_destroy(&softc->queue_lock);
1505#endif
1506
1507	ctl_tpc_shutdown(softc);
1508	uma_zdestroy(softc->io_zone);
1509	mtx_destroy(&softc->ctl_lock);
1510
1511	destroy_dev(softc->dev);
1512
1513	sysctl_ctx_free(&softc->sysctl_ctx);
1514
1515	free(control_softc, M_DEVBUF);
1516	control_softc = NULL;
1517}
1518
1519static int
1520ctl_module_event_handler(module_t mod, int what, void *arg)
1521{
1522
1523	switch (what) {
1524	case MOD_LOAD:
1525		return (ctl_init());
1526	case MOD_UNLOAD:
1527		return (EBUSY);
1528	default:
1529		return (EOPNOTSUPP);
1530	}
1531}
1532
1533/*
1534 * XXX KDM should we do some access checks here?  Bump a reference count to
1535 * prevent a CTL module from being unloaded while someone has it open?
1536 */
1537static int
1538ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1539{
1540	return (0);
1541}
1542
1543static int
1544ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1545{
1546	return (0);
1547}
1548
1549/*
1550 * Remove an initiator by port number and initiator ID.
1551 * Returns 0 for success, -1 for failure.
1552 */
1553int
1554ctl_remove_initiator(struct ctl_port *port, int iid)
1555{
1556	struct ctl_softc *softc = control_softc;
1557
1558	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1559
1560	if (iid > CTL_MAX_INIT_PER_PORT) {
1561		printf("%s: initiator ID %u > maximun %u!\n",
1562		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1563		return (-1);
1564	}
1565
1566	mtx_lock(&softc->ctl_lock);
1567	port->wwpn_iid[iid].in_use--;
1568	port->wwpn_iid[iid].last_use = time_uptime;
1569	mtx_unlock(&softc->ctl_lock);
1570
1571	return (0);
1572}
1573
1574/*
1575 * Add an initiator to the initiator map.
1576 * Returns iid for success, < 0 for failure.
1577 */
1578int
1579ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1580{
1581	struct ctl_softc *softc = control_softc;
1582	time_t best_time;
1583	int i, best;
1584
1585	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1586
1587	if (iid >= CTL_MAX_INIT_PER_PORT) {
1588		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1589		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1590		free(name, M_CTL);
1591		return (-1);
1592	}
1593
1594	mtx_lock(&softc->ctl_lock);
1595
1596	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1597		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1598			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1599				iid = i;
1600				break;
1601			}
1602			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1603			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1604				iid = i;
1605				break;
1606			}
1607		}
1608	}
1609
1610	if (iid < 0) {
1611		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1612			if (port->wwpn_iid[i].in_use == 0 &&
1613			    port->wwpn_iid[i].wwpn == 0 &&
1614			    port->wwpn_iid[i].name == NULL) {
1615				iid = i;
1616				break;
1617			}
1618		}
1619	}
1620
1621	if (iid < 0) {
1622		best = -1;
1623		best_time = INT32_MAX;
1624		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1625			if (port->wwpn_iid[i].in_use == 0) {
1626				if (port->wwpn_iid[i].last_use < best_time) {
1627					best = i;
1628					best_time = port->wwpn_iid[i].last_use;
1629				}
1630			}
1631		}
1632		iid = best;
1633	}
1634
1635	if (iid < 0) {
1636		mtx_unlock(&softc->ctl_lock);
1637		free(name, M_CTL);
1638		return (-2);
1639	}
1640
1641	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1642		/*
1643		 * This is not an error yet.
1644		 */
1645		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1646#if 0
1647			printf("%s: port %d iid %u WWPN %#jx arrived"
1648			    " again\n", __func__, port->targ_port,
1649			    iid, (uintmax_t)wwpn);
1650#endif
1651			goto take;
1652		}
1653		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1654		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1655#if 0
1656			printf("%s: port %d iid %u name '%s' arrived"
1657			    " again\n", __func__, port->targ_port,
1658			    iid, name);
1659#endif
1660			goto take;
1661		}
1662
1663		/*
1664		 * This is an error, but what do we do about it?  The
1665		 * driver is telling us we have a new WWPN for this
1666		 * initiator ID, so we pretty much need to use it.
1667		 */
1668		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1669		    " but WWPN %#jx '%s' is still at that address\n",
1670		    __func__, port->targ_port, iid, wwpn, name,
1671		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1672		    port->wwpn_iid[iid].name);
1673
1674		/*
1675		 * XXX KDM clear have_ca and ua_pending on each LUN for
1676		 * this initiator.
1677		 */
1678	}
1679take:
1680	free(port->wwpn_iid[iid].name, M_CTL);
1681	port->wwpn_iid[iid].name = name;
1682	port->wwpn_iid[iid].wwpn = wwpn;
1683	port->wwpn_iid[iid].in_use++;
1684	mtx_unlock(&softc->ctl_lock);
1685
1686	return (iid);
1687}
1688
1689static int
1690ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1691{
1692	int len;
1693
1694	switch (port->port_type) {
1695	case CTL_PORT_FC:
1696	{
1697		struct scsi_transportid_fcp *id =
1698		    (struct scsi_transportid_fcp *)buf;
1699		if (port->wwpn_iid[iid].wwpn == 0)
1700			return (0);
1701		memset(id, 0, sizeof(*id));
1702		id->format_protocol = SCSI_PROTO_FC;
1703		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1704		return (sizeof(*id));
1705	}
1706	case CTL_PORT_ISCSI:
1707	{
1708		struct scsi_transportid_iscsi_port *id =
1709		    (struct scsi_transportid_iscsi_port *)buf;
1710		if (port->wwpn_iid[iid].name == NULL)
1711			return (0);
1712		memset(id, 0, 256);
1713		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1714		    SCSI_PROTO_ISCSI;
1715		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1716		len = roundup2(min(len, 252), 4);
1717		scsi_ulto2b(len, id->additional_length);
1718		return (sizeof(*id) + len);
1719	}
1720	case CTL_PORT_SAS:
1721	{
1722		struct scsi_transportid_sas *id =
1723		    (struct scsi_transportid_sas *)buf;
1724		if (port->wwpn_iid[iid].wwpn == 0)
1725			return (0);
1726		memset(id, 0, sizeof(*id));
1727		id->format_protocol = SCSI_PROTO_SAS;
1728		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1729		return (sizeof(*id));
1730	}
1731	default:
1732	{
1733		struct scsi_transportid_spi *id =
1734		    (struct scsi_transportid_spi *)buf;
1735		memset(id, 0, sizeof(*id));
1736		id->format_protocol = SCSI_PROTO_SPI;
1737		scsi_ulto2b(iid, id->scsi_addr);
1738		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1739		return (sizeof(*id));
1740	}
1741	}
1742}
1743
1744/*
1745 * Serialize a command that went down the "wrong" side, and so was sent to
1746 * this controller for execution.  The logic is a little different than the
1747 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1748 * sent back to the other side, but in the success case, we execute the
1749 * command on this side (XFER mode) or tell the other side to execute it
1750 * (SER_ONLY mode).
1751 */
1752static int
1753ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1754{
1755	struct ctl_softc *softc;
1756	union ctl_ha_msg msg_info;
1757	struct ctl_lun *lun;
1758	const struct ctl_cmd_entry *entry;
1759	int retval = 0;
1760	uint32_t targ_lun;
1761
1762	softc = control_softc;
1763
1764	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1765	mtx_lock(&softc->ctl_lock);
1766	if ((targ_lun < CTL_MAX_LUNS) &&
1767	    ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
1768		mtx_lock(&lun->lun_lock);
1769		mtx_unlock(&softc->ctl_lock);
1770		/*
1771		 * If the LUN is invalid, pretend that it doesn't exist.
1772		 * It will go away as soon as all pending I/O has been
1773		 * completed.
1774		 */
1775		if (lun->flags & CTL_LUN_DISABLED) {
1776			mtx_unlock(&lun->lun_lock);
1777			lun = NULL;
1778		}
1779	} else {
1780		mtx_unlock(&softc->ctl_lock);
1781		lun = NULL;
1782	}
1783	if (lun == NULL) {
1784		/*
1785		 * The other node would not send this request to us unless
1786		 * received announce that we are primary node for this LUN.
1787		 * If this LUN does not exist now, it is probably result of
1788		 * a race, so respond to initiator in the most opaque way.
1789		 */
1790		ctl_set_busy(ctsio);
1791		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
1792		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1793		msg_info.hdr.serializing_sc = NULL;
1794		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1795		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1796		    sizeof(msg_info.scsi), M_WAITOK);
1797		return(1);
1798	}
1799
1800	entry = ctl_get_cmd_entry(ctsio, NULL);
1801	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
1802		mtx_unlock(&lun->lun_lock);
1803		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
1804		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1805		msg_info.hdr.serializing_sc = NULL;
1806		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1807		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1808		    sizeof(msg_info.scsi), M_WAITOK);
1809		return(1);
1810	}
1811
1812	ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
1813	ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = lun->be_lun;
1814
1815	/*
1816	 * Every I/O goes into the OOA queue for a
1817	 * particular LUN, and stays there until completion.
1818	 */
1819#ifdef CTL_TIME_IO
1820	if (TAILQ_EMPTY(&lun->ooa_queue))
1821		lun->idle_time += getsbinuptime() - lun->last_busy;
1822#endif
1823	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1824
1825	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1826		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1827		 ooa_links))) {
1828	case CTL_ACTION_BLOCK:
1829		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1830		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1831				  blocked_links);
1832		mtx_unlock(&lun->lun_lock);
1833		break;
1834	case CTL_ACTION_PASS:
1835	case CTL_ACTION_SKIP:
1836		if (softc->ha_mode == CTL_HA_MODE_XFER) {
1837			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1838			ctl_enqueue_rtr((union ctl_io *)ctsio);
1839			mtx_unlock(&lun->lun_lock);
1840		} else {
1841			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
1842			mtx_unlock(&lun->lun_lock);
1843
1844			/* send msg back to other side */
1845			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1846			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1847			msg_info.hdr.msg_type = CTL_MSG_R2R;
1848			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1849			    sizeof(msg_info.hdr), M_WAITOK);
1850		}
1851		break;
1852	case CTL_ACTION_OVERLAP:
1853		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1854		mtx_unlock(&lun->lun_lock);
1855		retval = 1;
1856
1857		ctl_set_overlapped_cmd(ctsio);
1858		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
1859		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1860		msg_info.hdr.serializing_sc = NULL;
1861		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1862		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1863		    sizeof(msg_info.scsi), M_WAITOK);
1864		break;
1865	case CTL_ACTION_OVERLAP_TAG:
1866		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1867		mtx_unlock(&lun->lun_lock);
1868		retval = 1;
1869		ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
1870		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
1871		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1872		msg_info.hdr.serializing_sc = NULL;
1873		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1874		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1875		    sizeof(msg_info.scsi), M_WAITOK);
1876		break;
1877	case CTL_ACTION_ERROR:
1878	default:
1879		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1880		mtx_unlock(&lun->lun_lock);
1881		retval = 1;
1882
1883		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
1884					 /*retry_count*/ 0);
1885		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
1886		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1887		msg_info.hdr.serializing_sc = NULL;
1888		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1889		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1890		    sizeof(msg_info.scsi), M_WAITOK);
1891		break;
1892	}
1893	return (retval);
1894}
1895
1896/*
1897 * Returns 0 for success, errno for failure.
1898 */
1899static int
1900ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
1901		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
1902{
1903	union ctl_io *io;
1904	int retval;
1905
1906	retval = 0;
1907
1908	mtx_lock(&lun->lun_lock);
1909	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
1910	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
1911	     ooa_links)) {
1912		struct ctl_ooa_entry *entry;
1913
1914		/*
1915		 * If we've got more than we can fit, just count the
1916		 * remaining entries.
1917		 */
1918		if (*cur_fill_num >= ooa_hdr->alloc_num)
1919			continue;
1920
1921		entry = &kern_entries[*cur_fill_num];
1922
1923		entry->tag_num = io->scsiio.tag_num;
1924		entry->lun_num = lun->lun;
1925#ifdef CTL_TIME_IO
1926		entry->start_bt = io->io_hdr.start_bt;
1927#endif
1928		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
1929		entry->cdb_len = io->scsiio.cdb_len;
1930		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
1931			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
1932
1933		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
1934			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
1935
1936		if (io->io_hdr.flags & CTL_FLAG_ABORT)
1937			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
1938
1939		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
1940			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
1941
1942		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
1943			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
1944	}
1945	mtx_unlock(&lun->lun_lock);
1946
1947	return (retval);
1948}
1949
1950static void *
1951ctl_copyin_alloc(void *user_addr, int len, char *error_str,
1952		 size_t error_str_len)
1953{
1954	void *kptr;
1955
1956	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
1957
1958	if (copyin(user_addr, kptr, len) != 0) {
1959		snprintf(error_str, error_str_len, "Error copying %d bytes "
1960			 "from user address %p to kernel address %p", len,
1961			 user_addr, kptr);
1962		free(kptr, M_CTL);
1963		return (NULL);
1964	}
1965
1966	return (kptr);
1967}
1968
1969static void
1970ctl_free_args(int num_args, struct ctl_be_arg *args)
1971{
1972	int i;
1973
1974	if (args == NULL)
1975		return;
1976
1977	for (i = 0; i < num_args; i++) {
1978		free(args[i].kname, M_CTL);
1979		free(args[i].kvalue, M_CTL);
1980	}
1981
1982	free(args, M_CTL);
1983}
1984
1985static struct ctl_be_arg *
1986ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
1987		char *error_str, size_t error_str_len)
1988{
1989	struct ctl_be_arg *args;
1990	int i;
1991
1992	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
1993				error_str, error_str_len);
1994
1995	if (args == NULL)
1996		goto bailout;
1997
1998	for (i = 0; i < num_args; i++) {
1999		args[i].kname = NULL;
2000		args[i].kvalue = NULL;
2001	}
2002
2003	for (i = 0; i < num_args; i++) {
2004		uint8_t *tmpptr;
2005
2006		args[i].kname = ctl_copyin_alloc(args[i].name,
2007			args[i].namelen, error_str, error_str_len);
2008		if (args[i].kname == NULL)
2009			goto bailout;
2010
2011		if (args[i].kname[args[i].namelen - 1] != '\0') {
2012			snprintf(error_str, error_str_len, "Argument %d "
2013				 "name is not NUL-terminated", i);
2014			goto bailout;
2015		}
2016
2017		if (args[i].flags & CTL_BEARG_RD) {
2018			tmpptr = ctl_copyin_alloc(args[i].value,
2019				args[i].vallen, error_str, error_str_len);
2020			if (tmpptr == NULL)
2021				goto bailout;
2022			if ((args[i].flags & CTL_BEARG_ASCII)
2023			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2024				snprintf(error_str, error_str_len, "Argument "
2025				    "%d value is not NUL-terminated", i);
2026				goto bailout;
2027			}
2028			args[i].kvalue = tmpptr;
2029		} else {
2030			args[i].kvalue = malloc(args[i].vallen,
2031			    M_CTL, M_WAITOK | M_ZERO);
2032		}
2033	}
2034
2035	return (args);
2036bailout:
2037
2038	ctl_free_args(num_args, args);
2039
2040	return (NULL);
2041}
2042
2043static void
2044ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2045{
2046	int i;
2047
2048	for (i = 0; i < num_args; i++) {
2049		if (args[i].flags & CTL_BEARG_WR)
2050			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2051	}
2052}
2053
2054/*
2055 * Escape characters that are illegal or not recommended in XML.
2056 */
2057int
2058ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2059{
2060	char *end = str + size;
2061	int retval;
2062
2063	retval = 0;
2064
2065	for (; *str && str < end; str++) {
2066		switch (*str) {
2067		case '&':
2068			retval = sbuf_printf(sb, "&amp;");
2069			break;
2070		case '>':
2071			retval = sbuf_printf(sb, "&gt;");
2072			break;
2073		case '<':
2074			retval = sbuf_printf(sb, "&lt;");
2075			break;
2076		default:
2077			retval = sbuf_putc(sb, *str);
2078			break;
2079		}
2080
2081		if (retval != 0)
2082			break;
2083
2084	}
2085
2086	return (retval);
2087}
2088
2089static void
2090ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2091{
2092	struct scsi_vpd_id_descriptor *desc;
2093	int i;
2094
2095	if (id == NULL || id->len < 4)
2096		return;
2097	desc = (struct scsi_vpd_id_descriptor *)id->data;
2098	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2099	case SVPD_ID_TYPE_T10:
2100		sbuf_printf(sb, "t10.");
2101		break;
2102	case SVPD_ID_TYPE_EUI64:
2103		sbuf_printf(sb, "eui.");
2104		break;
2105	case SVPD_ID_TYPE_NAA:
2106		sbuf_printf(sb, "naa.");
2107		break;
2108	case SVPD_ID_TYPE_SCSI_NAME:
2109		break;
2110	}
2111	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2112	case SVPD_ID_CODESET_BINARY:
2113		for (i = 0; i < desc->length; i++)
2114			sbuf_printf(sb, "%02x", desc->identifier[i]);
2115		break;
2116	case SVPD_ID_CODESET_ASCII:
2117		sbuf_printf(sb, "%.*s", (int)desc->length,
2118		    (char *)desc->identifier);
2119		break;
2120	case SVPD_ID_CODESET_UTF8:
2121		sbuf_printf(sb, "%s", (char *)desc->identifier);
2122		break;
2123	}
2124}
2125
2126static int
2127ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2128	  struct thread *td)
2129{
2130	struct ctl_softc *softc;
2131	struct ctl_lun *lun;
2132	int retval;
2133
2134	softc = control_softc;
2135
2136	retval = 0;
2137
2138	switch (cmd) {
2139	case CTL_IO:
2140		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2141		break;
2142	case CTL_ENABLE_PORT:
2143	case CTL_DISABLE_PORT:
2144	case CTL_SET_PORT_WWNS: {
2145		struct ctl_port *port;
2146		struct ctl_port_entry *entry;
2147
2148		entry = (struct ctl_port_entry *)addr;
2149
2150		mtx_lock(&softc->ctl_lock);
2151		STAILQ_FOREACH(port, &softc->port_list, links) {
2152			int action, done;
2153
2154			if (port->targ_port < softc->port_min ||
2155			    port->targ_port >= softc->port_max)
2156				continue;
2157
2158			action = 0;
2159			done = 0;
2160			if ((entry->port_type == CTL_PORT_NONE)
2161			 && (entry->targ_port == port->targ_port)) {
2162				/*
2163				 * If the user only wants to enable or
2164				 * disable or set WWNs on a specific port,
2165				 * do the operation and we're done.
2166				 */
2167				action = 1;
2168				done = 1;
2169			} else if (entry->port_type & port->port_type) {
2170				/*
2171				 * Compare the user's type mask with the
2172				 * particular frontend type to see if we
2173				 * have a match.
2174				 */
2175				action = 1;
2176				done = 0;
2177
2178				/*
2179				 * Make sure the user isn't trying to set
2180				 * WWNs on multiple ports at the same time.
2181				 */
2182				if (cmd == CTL_SET_PORT_WWNS) {
2183					printf("%s: Can't set WWNs on "
2184					       "multiple ports\n", __func__);
2185					retval = EINVAL;
2186					break;
2187				}
2188			}
2189			if (action == 0)
2190				continue;
2191
2192			/*
2193			 * XXX KDM we have to drop the lock here, because
2194			 * the online/offline operations can potentially
2195			 * block.  We need to reference count the frontends
2196			 * so they can't go away,
2197			 */
2198			if (cmd == CTL_ENABLE_PORT) {
2199				mtx_unlock(&softc->ctl_lock);
2200				ctl_port_online(port);
2201				mtx_lock(&softc->ctl_lock);
2202			} else if (cmd == CTL_DISABLE_PORT) {
2203				mtx_unlock(&softc->ctl_lock);
2204				ctl_port_offline(port);
2205				mtx_lock(&softc->ctl_lock);
2206			} else if (cmd == CTL_SET_PORT_WWNS) {
2207				ctl_port_set_wwns(port,
2208				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2209				    1 : 0, entry->wwnn,
2210				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2211				    1 : 0, entry->wwpn);
2212			}
2213			if (done != 0)
2214				break;
2215		}
2216		mtx_unlock(&softc->ctl_lock);
2217		break;
2218	}
2219	case CTL_GET_PORT_LIST: {
2220		struct ctl_port *port;
2221		struct ctl_port_list *list;
2222		int i;
2223
2224		list = (struct ctl_port_list *)addr;
2225
2226		if (list->alloc_len != (list->alloc_num *
2227		    sizeof(struct ctl_port_entry))) {
2228			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2229			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2230			       "%zu\n", __func__, list->alloc_len,
2231			       list->alloc_num, sizeof(struct ctl_port_entry));
2232			retval = EINVAL;
2233			break;
2234		}
2235		list->fill_len = 0;
2236		list->fill_num = 0;
2237		list->dropped_num = 0;
2238		i = 0;
2239		mtx_lock(&softc->ctl_lock);
2240		STAILQ_FOREACH(port, &softc->port_list, links) {
2241			struct ctl_port_entry entry, *list_entry;
2242
2243			if (list->fill_num >= list->alloc_num) {
2244				list->dropped_num++;
2245				continue;
2246			}
2247
2248			entry.port_type = port->port_type;
2249			strlcpy(entry.port_name, port->port_name,
2250				sizeof(entry.port_name));
2251			entry.targ_port = port->targ_port;
2252			entry.physical_port = port->physical_port;
2253			entry.virtual_port = port->virtual_port;
2254			entry.wwnn = port->wwnn;
2255			entry.wwpn = port->wwpn;
2256			if (port->status & CTL_PORT_STATUS_ONLINE)
2257				entry.online = 1;
2258			else
2259				entry.online = 0;
2260
2261			list_entry = &list->entries[i];
2262
2263			retval = copyout(&entry, list_entry, sizeof(entry));
2264			if (retval != 0) {
2265				printf("%s: CTL_GET_PORT_LIST: copyout "
2266				       "returned %d\n", __func__, retval);
2267				break;
2268			}
2269			i++;
2270			list->fill_num++;
2271			list->fill_len += sizeof(entry);
2272		}
2273		mtx_unlock(&softc->ctl_lock);
2274
2275		/*
2276		 * If this is non-zero, we had a copyout fault, so there's
2277		 * probably no point in attempting to set the status inside
2278		 * the structure.
2279		 */
2280		if (retval != 0)
2281			break;
2282
2283		if (list->dropped_num > 0)
2284			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2285		else
2286			list->status = CTL_PORT_LIST_OK;
2287		break;
2288	}
2289	case CTL_DUMP_OOA: {
2290		union ctl_io *io;
2291		char printbuf[128];
2292		struct sbuf sb;
2293
2294		mtx_lock(&softc->ctl_lock);
2295		printf("Dumping OOA queues:\n");
2296		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2297			mtx_lock(&lun->lun_lock);
2298			for (io = (union ctl_io *)TAILQ_FIRST(
2299			     &lun->ooa_queue); io != NULL;
2300			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2301			     ooa_links)) {
2302				sbuf_new(&sb, printbuf, sizeof(printbuf),
2303					 SBUF_FIXEDLEN);
2304				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2305					    (intmax_t)lun->lun,
2306					    io->scsiio.tag_num,
2307					    (io->io_hdr.flags &
2308					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2309					    (io->io_hdr.flags &
2310					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2311					    (io->io_hdr.flags &
2312					    CTL_FLAG_ABORT) ? " ABORT" : "",
2313			                    (io->io_hdr.flags &
2314		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2315				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2316				sbuf_finish(&sb);
2317				printf("%s\n", sbuf_data(&sb));
2318			}
2319			mtx_unlock(&lun->lun_lock);
2320		}
2321		printf("OOA queues dump done\n");
2322		mtx_unlock(&softc->ctl_lock);
2323		break;
2324	}
2325	case CTL_GET_OOA: {
2326		struct ctl_ooa *ooa_hdr;
2327		struct ctl_ooa_entry *entries;
2328		uint32_t cur_fill_num;
2329
2330		ooa_hdr = (struct ctl_ooa *)addr;
2331
2332		if ((ooa_hdr->alloc_len == 0)
2333		 || (ooa_hdr->alloc_num == 0)) {
2334			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2335			       "must be non-zero\n", __func__,
2336			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2337			retval = EINVAL;
2338			break;
2339		}
2340
2341		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2342		    sizeof(struct ctl_ooa_entry))) {
2343			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2344			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2345			       __func__, ooa_hdr->alloc_len,
2346			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2347			retval = EINVAL;
2348			break;
2349		}
2350
2351		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2352		if (entries == NULL) {
2353			printf("%s: could not allocate %d bytes for OOA "
2354			       "dump\n", __func__, ooa_hdr->alloc_len);
2355			retval = ENOMEM;
2356			break;
2357		}
2358
2359		mtx_lock(&softc->ctl_lock);
2360		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2361		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2362		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2363			mtx_unlock(&softc->ctl_lock);
2364			free(entries, M_CTL);
2365			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2366			       __func__, (uintmax_t)ooa_hdr->lun_num);
2367			retval = EINVAL;
2368			break;
2369		}
2370
2371		cur_fill_num = 0;
2372
2373		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2374			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2375				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2376					ooa_hdr, entries);
2377				if (retval != 0)
2378					break;
2379			}
2380			if (retval != 0) {
2381				mtx_unlock(&softc->ctl_lock);
2382				free(entries, M_CTL);
2383				break;
2384			}
2385		} else {
2386			lun = softc->ctl_luns[ooa_hdr->lun_num];
2387
2388			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2389						    entries);
2390		}
2391		mtx_unlock(&softc->ctl_lock);
2392
2393		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2394		ooa_hdr->fill_len = ooa_hdr->fill_num *
2395			sizeof(struct ctl_ooa_entry);
2396		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2397		if (retval != 0) {
2398			printf("%s: error copying out %d bytes for OOA dump\n",
2399			       __func__, ooa_hdr->fill_len);
2400		}
2401
2402		getbintime(&ooa_hdr->cur_bt);
2403
2404		if (cur_fill_num > ooa_hdr->alloc_num) {
2405			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2406			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2407		} else {
2408			ooa_hdr->dropped_num = 0;
2409			ooa_hdr->status = CTL_OOA_OK;
2410		}
2411
2412		free(entries, M_CTL);
2413		break;
2414	}
2415	case CTL_CHECK_OOA: {
2416		union ctl_io *io;
2417		struct ctl_ooa_info *ooa_info;
2418
2419
2420		ooa_info = (struct ctl_ooa_info *)addr;
2421
2422		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2423			ooa_info->status = CTL_OOA_INVALID_LUN;
2424			break;
2425		}
2426		mtx_lock(&softc->ctl_lock);
2427		lun = softc->ctl_luns[ooa_info->lun_id];
2428		if (lun == NULL) {
2429			mtx_unlock(&softc->ctl_lock);
2430			ooa_info->status = CTL_OOA_INVALID_LUN;
2431			break;
2432		}
2433		mtx_lock(&lun->lun_lock);
2434		mtx_unlock(&softc->ctl_lock);
2435		ooa_info->num_entries = 0;
2436		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2437		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2438		     &io->io_hdr, ooa_links)) {
2439			ooa_info->num_entries++;
2440		}
2441		mtx_unlock(&lun->lun_lock);
2442
2443		ooa_info->status = CTL_OOA_SUCCESS;
2444
2445		break;
2446	}
2447	case CTL_DELAY_IO: {
2448		struct ctl_io_delay_info *delay_info;
2449
2450		delay_info = (struct ctl_io_delay_info *)addr;
2451
2452#ifdef CTL_IO_DELAY
2453		mtx_lock(&softc->ctl_lock);
2454
2455		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2456		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2457			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2458		} else {
2459			lun = softc->ctl_luns[delay_info->lun_id];
2460			mtx_lock(&lun->lun_lock);
2461
2462			delay_info->status = CTL_DELAY_STATUS_OK;
2463
2464			switch (delay_info->delay_type) {
2465			case CTL_DELAY_TYPE_CONT:
2466				break;
2467			case CTL_DELAY_TYPE_ONESHOT:
2468				break;
2469			default:
2470				delay_info->status =
2471					CTL_DELAY_STATUS_INVALID_TYPE;
2472				break;
2473			}
2474
2475			switch (delay_info->delay_loc) {
2476			case CTL_DELAY_LOC_DATAMOVE:
2477				lun->delay_info.datamove_type =
2478					delay_info->delay_type;
2479				lun->delay_info.datamove_delay =
2480					delay_info->delay_secs;
2481				break;
2482			case CTL_DELAY_LOC_DONE:
2483				lun->delay_info.done_type =
2484					delay_info->delay_type;
2485				lun->delay_info.done_delay =
2486					delay_info->delay_secs;
2487				break;
2488			default:
2489				delay_info->status =
2490					CTL_DELAY_STATUS_INVALID_LOC;
2491				break;
2492			}
2493			mtx_unlock(&lun->lun_lock);
2494		}
2495
2496		mtx_unlock(&softc->ctl_lock);
2497#else
2498		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2499#endif /* CTL_IO_DELAY */
2500		break;
2501	}
2502	case CTL_REALSYNC_SET: {
2503		int *syncstate;
2504
2505		syncstate = (int *)addr;
2506
2507		mtx_lock(&softc->ctl_lock);
2508		switch (*syncstate) {
2509		case 0:
2510			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2511			break;
2512		case 1:
2513			softc->flags |= CTL_FLAG_REAL_SYNC;
2514			break;
2515		default:
2516			retval = EINVAL;
2517			break;
2518		}
2519		mtx_unlock(&softc->ctl_lock);
2520		break;
2521	}
2522	case CTL_REALSYNC_GET: {
2523		int *syncstate;
2524
2525		syncstate = (int*)addr;
2526
2527		mtx_lock(&softc->ctl_lock);
2528		if (softc->flags & CTL_FLAG_REAL_SYNC)
2529			*syncstate = 1;
2530		else
2531			*syncstate = 0;
2532		mtx_unlock(&softc->ctl_lock);
2533
2534		break;
2535	}
2536	case CTL_SETSYNC:
2537	case CTL_GETSYNC: {
2538		struct ctl_sync_info *sync_info;
2539
2540		sync_info = (struct ctl_sync_info *)addr;
2541
2542		mtx_lock(&softc->ctl_lock);
2543		lun = softc->ctl_luns[sync_info->lun_id];
2544		if (lun == NULL) {
2545			mtx_unlock(&softc->ctl_lock);
2546			sync_info->status = CTL_GS_SYNC_NO_LUN;
2547			break;
2548		}
2549		/*
2550		 * Get or set the sync interval.  We're not bounds checking
2551		 * in the set case, hopefully the user won't do something
2552		 * silly.
2553		 */
2554		mtx_lock(&lun->lun_lock);
2555		mtx_unlock(&softc->ctl_lock);
2556		if (cmd == CTL_GETSYNC)
2557			sync_info->sync_interval = lun->sync_interval;
2558		else
2559			lun->sync_interval = sync_info->sync_interval;
2560		mtx_unlock(&lun->lun_lock);
2561
2562		sync_info->status = CTL_GS_SYNC_OK;
2563
2564		break;
2565	}
2566	case CTL_GETSTATS: {
2567		struct ctl_stats *stats;
2568		int i;
2569
2570		stats = (struct ctl_stats *)addr;
2571
2572		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2573		     stats->alloc_len) {
2574			stats->status = CTL_SS_NEED_MORE_SPACE;
2575			stats->num_luns = softc->num_luns;
2576			break;
2577		}
2578		/*
2579		 * XXX KDM no locking here.  If the LUN list changes,
2580		 * things can blow up.
2581		 */
2582		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2583		     i++, lun = STAILQ_NEXT(lun, links)) {
2584			retval = copyout(&lun->stats, &stats->lun_stats[i],
2585					 sizeof(lun->stats));
2586			if (retval != 0)
2587				break;
2588		}
2589		stats->num_luns = softc->num_luns;
2590		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2591				 softc->num_luns;
2592		stats->status = CTL_SS_OK;
2593#ifdef CTL_TIME_IO
2594		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2595#else
2596		stats->flags = CTL_STATS_FLAG_NONE;
2597#endif
2598		getnanouptime(&stats->timestamp);
2599		break;
2600	}
2601	case CTL_ERROR_INJECT: {
2602		struct ctl_error_desc *err_desc, *new_err_desc;
2603
2604		err_desc = (struct ctl_error_desc *)addr;
2605
2606		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2607				      M_WAITOK | M_ZERO);
2608		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2609
2610		mtx_lock(&softc->ctl_lock);
2611		lun = softc->ctl_luns[err_desc->lun_id];
2612		if (lun == NULL) {
2613			mtx_unlock(&softc->ctl_lock);
2614			free(new_err_desc, M_CTL);
2615			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2616			       __func__, (uintmax_t)err_desc->lun_id);
2617			retval = EINVAL;
2618			break;
2619		}
2620		mtx_lock(&lun->lun_lock);
2621		mtx_unlock(&softc->ctl_lock);
2622
2623		/*
2624		 * We could do some checking here to verify the validity
2625		 * of the request, but given the complexity of error
2626		 * injection requests, the checking logic would be fairly
2627		 * complex.
2628		 *
2629		 * For now, if the request is invalid, it just won't get
2630		 * executed and might get deleted.
2631		 */
2632		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2633
2634		/*
2635		 * XXX KDM check to make sure the serial number is unique,
2636		 * in case we somehow manage to wrap.  That shouldn't
2637		 * happen for a very long time, but it's the right thing to
2638		 * do.
2639		 */
2640		new_err_desc->serial = lun->error_serial;
2641		err_desc->serial = lun->error_serial;
2642		lun->error_serial++;
2643
2644		mtx_unlock(&lun->lun_lock);
2645		break;
2646	}
2647	case CTL_ERROR_INJECT_DELETE: {
2648		struct ctl_error_desc *delete_desc, *desc, *desc2;
2649		int delete_done;
2650
2651		delete_desc = (struct ctl_error_desc *)addr;
2652		delete_done = 0;
2653
2654		mtx_lock(&softc->ctl_lock);
2655		lun = softc->ctl_luns[delete_desc->lun_id];
2656		if (lun == NULL) {
2657			mtx_unlock(&softc->ctl_lock);
2658			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2659			       __func__, (uintmax_t)delete_desc->lun_id);
2660			retval = EINVAL;
2661			break;
2662		}
2663		mtx_lock(&lun->lun_lock);
2664		mtx_unlock(&softc->ctl_lock);
2665		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2666			if (desc->serial != delete_desc->serial)
2667				continue;
2668
2669			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2670				      links);
2671			free(desc, M_CTL);
2672			delete_done = 1;
2673		}
2674		mtx_unlock(&lun->lun_lock);
2675		if (delete_done == 0) {
2676			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2677			       "error serial %ju on LUN %u\n", __func__,
2678			       delete_desc->serial, delete_desc->lun_id);
2679			retval = EINVAL;
2680			break;
2681		}
2682		break;
2683	}
2684	case CTL_DUMP_STRUCTS: {
2685		int i, j, k;
2686		struct ctl_port *port;
2687		struct ctl_frontend *fe;
2688
2689		mtx_lock(&softc->ctl_lock);
2690		printf("CTL Persistent Reservation information start:\n");
2691		for (i = 0; i < CTL_MAX_LUNS; i++) {
2692			lun = softc->ctl_luns[i];
2693
2694			if ((lun == NULL)
2695			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
2696				continue;
2697
2698			for (j = 0; j < CTL_MAX_PORTS; j++) {
2699				if (lun->pr_keys[j] == NULL)
2700					continue;
2701				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2702					if (lun->pr_keys[j][k] == 0)
2703						continue;
2704					printf("  LUN %d port %d iid %d key "
2705					       "%#jx\n", i, j, k,
2706					       (uintmax_t)lun->pr_keys[j][k]);
2707				}
2708			}
2709		}
2710		printf("CTL Persistent Reservation information end\n");
2711		printf("CTL Ports:\n");
2712		STAILQ_FOREACH(port, &softc->port_list, links) {
2713			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2714			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2715			       port->frontend->name, port->port_type,
2716			       port->physical_port, port->virtual_port,
2717			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2718			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2719				if (port->wwpn_iid[j].in_use == 0 &&
2720				    port->wwpn_iid[j].wwpn == 0 &&
2721				    port->wwpn_iid[j].name == NULL)
2722					continue;
2723
2724				printf("    iid %u use %d WWPN %#jx '%s'\n",
2725				    j, port->wwpn_iid[j].in_use,
2726				    (uintmax_t)port->wwpn_iid[j].wwpn,
2727				    port->wwpn_iid[j].name);
2728			}
2729		}
2730		printf("CTL Port information end\n");
2731		mtx_unlock(&softc->ctl_lock);
2732		/*
2733		 * XXX KDM calling this without a lock.  We'd likely want
2734		 * to drop the lock before calling the frontend's dump
2735		 * routine anyway.
2736		 */
2737		printf("CTL Frontends:\n");
2738		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2739			printf("  Frontend '%s'\n", fe->name);
2740			if (fe->fe_dump != NULL)
2741				fe->fe_dump();
2742		}
2743		printf("CTL Frontend information end\n");
2744		break;
2745	}
2746	case CTL_LUN_REQ: {
2747		struct ctl_lun_req *lun_req;
2748		struct ctl_backend_driver *backend;
2749
2750		lun_req = (struct ctl_lun_req *)addr;
2751
2752		backend = ctl_backend_find(lun_req->backend);
2753		if (backend == NULL) {
2754			lun_req->status = CTL_LUN_ERROR;
2755			snprintf(lun_req->error_str,
2756				 sizeof(lun_req->error_str),
2757				 "Backend \"%s\" not found.",
2758				 lun_req->backend);
2759			break;
2760		}
2761		if (lun_req->num_be_args > 0) {
2762			lun_req->kern_be_args = ctl_copyin_args(
2763				lun_req->num_be_args,
2764				lun_req->be_args,
2765				lun_req->error_str,
2766				sizeof(lun_req->error_str));
2767			if (lun_req->kern_be_args == NULL) {
2768				lun_req->status = CTL_LUN_ERROR;
2769				break;
2770			}
2771		}
2772
2773		retval = backend->ioctl(dev, cmd, addr, flag, td);
2774
2775		if (lun_req->num_be_args > 0) {
2776			ctl_copyout_args(lun_req->num_be_args,
2777				      lun_req->kern_be_args);
2778			ctl_free_args(lun_req->num_be_args,
2779				      lun_req->kern_be_args);
2780		}
2781		break;
2782	}
2783	case CTL_LUN_LIST: {
2784		struct sbuf *sb;
2785		struct ctl_lun_list *list;
2786		struct ctl_option *opt;
2787
2788		list = (struct ctl_lun_list *)addr;
2789
2790		/*
2791		 * Allocate a fixed length sbuf here, based on the length
2792		 * of the user's buffer.  We could allocate an auto-extending
2793		 * buffer, and then tell the user how much larger our
2794		 * amount of data is than his buffer, but that presents
2795		 * some problems:
2796		 *
2797		 * 1.  The sbuf(9) routines use a blocking malloc, and so
2798		 *     we can't hold a lock while calling them with an
2799		 *     auto-extending buffer.
2800 		 *
2801		 * 2.  There is not currently a LUN reference counting
2802		 *     mechanism, outside of outstanding transactions on
2803		 *     the LUN's OOA queue.  So a LUN could go away on us
2804		 *     while we're getting the LUN number, backend-specific
2805		 *     information, etc.  Thus, given the way things
2806		 *     currently work, we need to hold the CTL lock while
2807		 *     grabbing LUN information.
2808		 *
2809		 * So, from the user's standpoint, the best thing to do is
2810		 * allocate what he thinks is a reasonable buffer length,
2811		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
2812		 * double the buffer length and try again.  (And repeat
2813		 * that until he succeeds.)
2814		 */
2815		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
2816		if (sb == NULL) {
2817			list->status = CTL_LUN_LIST_ERROR;
2818			snprintf(list->error_str, sizeof(list->error_str),
2819				 "Unable to allocate %d bytes for LUN list",
2820				 list->alloc_len);
2821			break;
2822		}
2823
2824		sbuf_printf(sb, "<ctllunlist>\n");
2825
2826		mtx_lock(&softc->ctl_lock);
2827		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2828			mtx_lock(&lun->lun_lock);
2829			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
2830					     (uintmax_t)lun->lun);
2831
2832			/*
2833			 * Bail out as soon as we see that we've overfilled
2834			 * the buffer.
2835			 */
2836			if (retval != 0)
2837				break;
2838
2839			retval = sbuf_printf(sb, "\t<backend_type>%s"
2840					     "</backend_type>\n",
2841					     (lun->backend == NULL) ?  "none" :
2842					     lun->backend->name);
2843
2844			if (retval != 0)
2845				break;
2846
2847			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
2848					     lun->be_lun->lun_type);
2849
2850			if (retval != 0)
2851				break;
2852
2853			if (lun->backend == NULL) {
2854				retval = sbuf_printf(sb, "</lun>\n");
2855				if (retval != 0)
2856					break;
2857				continue;
2858			}
2859
2860			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
2861					     (lun->be_lun->maxlba > 0) ?
2862					     lun->be_lun->maxlba + 1 : 0);
2863
2864			if (retval != 0)
2865				break;
2866
2867			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
2868					     lun->be_lun->blocksize);
2869
2870			if (retval != 0)
2871				break;
2872
2873			retval = sbuf_printf(sb, "\t<serial_number>");
2874
2875			if (retval != 0)
2876				break;
2877
2878			retval = ctl_sbuf_printf_esc(sb,
2879			    lun->be_lun->serial_num,
2880			    sizeof(lun->be_lun->serial_num));
2881
2882			if (retval != 0)
2883				break;
2884
2885			retval = sbuf_printf(sb, "</serial_number>\n");
2886
2887			if (retval != 0)
2888				break;
2889
2890			retval = sbuf_printf(sb, "\t<device_id>");
2891
2892			if (retval != 0)
2893				break;
2894
2895			retval = ctl_sbuf_printf_esc(sb,
2896			    lun->be_lun->device_id,
2897			    sizeof(lun->be_lun->device_id));
2898
2899			if (retval != 0)
2900				break;
2901
2902			retval = sbuf_printf(sb, "</device_id>\n");
2903
2904			if (retval != 0)
2905				break;
2906
2907			if (lun->backend->lun_info != NULL) {
2908				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
2909				if (retval != 0)
2910					break;
2911			}
2912			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
2913				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
2914				    opt->name, opt->value, opt->name);
2915				if (retval != 0)
2916					break;
2917			}
2918
2919			retval = sbuf_printf(sb, "</lun>\n");
2920
2921			if (retval != 0)
2922				break;
2923			mtx_unlock(&lun->lun_lock);
2924		}
2925		if (lun != NULL)
2926			mtx_unlock(&lun->lun_lock);
2927		mtx_unlock(&softc->ctl_lock);
2928
2929		if ((retval != 0)
2930		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
2931			retval = 0;
2932			sbuf_delete(sb);
2933			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
2934			snprintf(list->error_str, sizeof(list->error_str),
2935				 "Out of space, %d bytes is too small",
2936				 list->alloc_len);
2937			break;
2938		}
2939
2940		sbuf_finish(sb);
2941
2942		retval = copyout(sbuf_data(sb), list->lun_xml,
2943				 sbuf_len(sb) + 1);
2944
2945		list->fill_len = sbuf_len(sb) + 1;
2946		list->status = CTL_LUN_LIST_OK;
2947		sbuf_delete(sb);
2948		break;
2949	}
2950	case CTL_ISCSI: {
2951		struct ctl_iscsi *ci;
2952		struct ctl_frontend *fe;
2953
2954		ci = (struct ctl_iscsi *)addr;
2955
2956		fe = ctl_frontend_find("iscsi");
2957		if (fe == NULL) {
2958			ci->status = CTL_ISCSI_ERROR;
2959			snprintf(ci->error_str, sizeof(ci->error_str),
2960			    "Frontend \"iscsi\" not found.");
2961			break;
2962		}
2963
2964		retval = fe->ioctl(dev, cmd, addr, flag, td);
2965		break;
2966	}
2967	case CTL_PORT_REQ: {
2968		struct ctl_req *req;
2969		struct ctl_frontend *fe;
2970
2971		req = (struct ctl_req *)addr;
2972
2973		fe = ctl_frontend_find(req->driver);
2974		if (fe == NULL) {
2975			req->status = CTL_LUN_ERROR;
2976			snprintf(req->error_str, sizeof(req->error_str),
2977			    "Frontend \"%s\" not found.", req->driver);
2978			break;
2979		}
2980		if (req->num_args > 0) {
2981			req->kern_args = ctl_copyin_args(req->num_args,
2982			    req->args, req->error_str, sizeof(req->error_str));
2983			if (req->kern_args == NULL) {
2984				req->status = CTL_LUN_ERROR;
2985				break;
2986			}
2987		}
2988
2989		if (fe->ioctl)
2990			retval = fe->ioctl(dev, cmd, addr, flag, td);
2991		else
2992			retval = ENODEV;
2993
2994		if (req->num_args > 0) {
2995			ctl_copyout_args(req->num_args, req->kern_args);
2996			ctl_free_args(req->num_args, req->kern_args);
2997		}
2998		break;
2999	}
3000	case CTL_PORT_LIST: {
3001		struct sbuf *sb;
3002		struct ctl_port *port;
3003		struct ctl_lun_list *list;
3004		struct ctl_option *opt;
3005		int j;
3006		uint32_t plun;
3007
3008		list = (struct ctl_lun_list *)addr;
3009
3010		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3011		if (sb == NULL) {
3012			list->status = CTL_LUN_LIST_ERROR;
3013			snprintf(list->error_str, sizeof(list->error_str),
3014				 "Unable to allocate %d bytes for LUN list",
3015				 list->alloc_len);
3016			break;
3017		}
3018
3019		sbuf_printf(sb, "<ctlportlist>\n");
3020
3021		mtx_lock(&softc->ctl_lock);
3022		STAILQ_FOREACH(port, &softc->port_list, links) {
3023			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3024					     (uintmax_t)port->targ_port);
3025
3026			/*
3027			 * Bail out as soon as we see that we've overfilled
3028			 * the buffer.
3029			 */
3030			if (retval != 0)
3031				break;
3032
3033			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3034			    "</frontend_type>\n", port->frontend->name);
3035			if (retval != 0)
3036				break;
3037
3038			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3039					     port->port_type);
3040			if (retval != 0)
3041				break;
3042
3043			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3044			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3045			if (retval != 0)
3046				break;
3047
3048			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3049			    port->port_name);
3050			if (retval != 0)
3051				break;
3052
3053			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3054			    port->physical_port);
3055			if (retval != 0)
3056				break;
3057
3058			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3059			    port->virtual_port);
3060			if (retval != 0)
3061				break;
3062
3063			if (port->target_devid != NULL) {
3064				sbuf_printf(sb, "\t<target>");
3065				ctl_id_sbuf(port->target_devid, sb);
3066				sbuf_printf(sb, "</target>\n");
3067			}
3068
3069			if (port->port_devid != NULL) {
3070				sbuf_printf(sb, "\t<port>");
3071				ctl_id_sbuf(port->port_devid, sb);
3072				sbuf_printf(sb, "</port>\n");
3073			}
3074
3075			if (port->port_info != NULL) {
3076				retval = port->port_info(port->onoff_arg, sb);
3077				if (retval != 0)
3078					break;
3079			}
3080			STAILQ_FOREACH(opt, &port->options, links) {
3081				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3082				    opt->name, opt->value, opt->name);
3083				if (retval != 0)
3084					break;
3085			}
3086
3087			if (port->lun_map != NULL) {
3088				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3089				for (j = 0; j < CTL_MAX_LUNS; j++) {
3090					plun = ctl_lun_map_from_port(port, j);
3091					if (plun >= CTL_MAX_LUNS)
3092						continue;
3093					sbuf_printf(sb,
3094					    "\t<lun id=\"%u\">%u</lun>\n",
3095					    j, plun);
3096				}
3097			}
3098
3099			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3100				if (port->wwpn_iid[j].in_use == 0 ||
3101				    (port->wwpn_iid[j].wwpn == 0 &&
3102				     port->wwpn_iid[j].name == NULL))
3103					continue;
3104
3105				if (port->wwpn_iid[j].name != NULL)
3106					retval = sbuf_printf(sb,
3107					    "\t<initiator id=\"%u\">%s</initiator>\n",
3108					    j, port->wwpn_iid[j].name);
3109				else
3110					retval = sbuf_printf(sb,
3111					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3112					    j, port->wwpn_iid[j].wwpn);
3113				if (retval != 0)
3114					break;
3115			}
3116			if (retval != 0)
3117				break;
3118
3119			retval = sbuf_printf(sb, "</targ_port>\n");
3120			if (retval != 0)
3121				break;
3122		}
3123		mtx_unlock(&softc->ctl_lock);
3124
3125		if ((retval != 0)
3126		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3127			retval = 0;
3128			sbuf_delete(sb);
3129			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3130			snprintf(list->error_str, sizeof(list->error_str),
3131				 "Out of space, %d bytes is too small",
3132				 list->alloc_len);
3133			break;
3134		}
3135
3136		sbuf_finish(sb);
3137
3138		retval = copyout(sbuf_data(sb), list->lun_xml,
3139				 sbuf_len(sb) + 1);
3140
3141		list->fill_len = sbuf_len(sb) + 1;
3142		list->status = CTL_LUN_LIST_OK;
3143		sbuf_delete(sb);
3144		break;
3145	}
3146	case CTL_LUN_MAP: {
3147		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3148		struct ctl_port *port;
3149
3150		mtx_lock(&softc->ctl_lock);
3151		if (lm->port < softc->port_min ||
3152		    lm->port >= softc->port_max ||
3153		    (port = softc->ctl_ports[lm->port]) == NULL) {
3154			mtx_unlock(&softc->ctl_lock);
3155			return (ENXIO);
3156		}
3157		if (port->status & CTL_PORT_STATUS_ONLINE) {
3158			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3159				if (ctl_lun_map_to_port(port, lun->lun) >=
3160				    CTL_MAX_LUNS)
3161					continue;
3162				mtx_lock(&lun->lun_lock);
3163				ctl_est_ua_port(lun, lm->port, -1,
3164				    CTL_UA_LUN_CHANGE);
3165				mtx_unlock(&lun->lun_lock);
3166			}
3167		}
3168		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3169		if (lm->plun < CTL_MAX_LUNS) {
3170			if (lm->lun == UINT32_MAX)
3171				retval = ctl_lun_map_unset(port, lm->plun);
3172			else if (lm->lun < CTL_MAX_LUNS &&
3173			    softc->ctl_luns[lm->lun] != NULL)
3174				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3175			else
3176				return (ENXIO);
3177		} else if (lm->plun == UINT32_MAX) {
3178			if (lm->lun == UINT32_MAX)
3179				retval = ctl_lun_map_deinit(port);
3180			else
3181				retval = ctl_lun_map_init(port);
3182		} else
3183			return (ENXIO);
3184		if (port->status & CTL_PORT_STATUS_ONLINE)
3185			ctl_isc_announce_port(port);
3186		break;
3187	}
3188	default: {
3189		/* XXX KDM should we fix this? */
3190#if 0
3191		struct ctl_backend_driver *backend;
3192		unsigned int type;
3193		int found;
3194
3195		found = 0;
3196
3197		/*
3198		 * We encode the backend type as the ioctl type for backend
3199		 * ioctls.  So parse it out here, and then search for a
3200		 * backend of this type.
3201		 */
3202		type = _IOC_TYPE(cmd);
3203
3204		STAILQ_FOREACH(backend, &softc->be_list, links) {
3205			if (backend->type == type) {
3206				found = 1;
3207				break;
3208			}
3209		}
3210		if (found == 0) {
3211			printf("ctl: unknown ioctl command %#lx or backend "
3212			       "%d\n", cmd, type);
3213			retval = EINVAL;
3214			break;
3215		}
3216		retval = backend->ioctl(dev, cmd, addr, flag, td);
3217#endif
3218		retval = ENOTTY;
3219		break;
3220	}
3221	}
3222	return (retval);
3223}
3224
3225uint32_t
3226ctl_get_initindex(struct ctl_nexus *nexus)
3227{
3228	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3229}
3230
3231int
3232ctl_lun_map_init(struct ctl_port *port)
3233{
3234	struct ctl_softc *softc = control_softc;
3235	struct ctl_lun *lun;
3236	uint32_t i;
3237
3238	if (port->lun_map == NULL)
3239		port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3240		    M_CTL, M_NOWAIT);
3241	if (port->lun_map == NULL)
3242		return (ENOMEM);
3243	for (i = 0; i < CTL_MAX_LUNS; i++)
3244		port->lun_map[i] = UINT32_MAX;
3245	if (port->status & CTL_PORT_STATUS_ONLINE) {
3246		if (port->lun_disable != NULL) {
3247			STAILQ_FOREACH(lun, &softc->lun_list, links)
3248				port->lun_disable(port->targ_lun_arg, lun->lun);
3249		}
3250		ctl_isc_announce_port(port);
3251	}
3252	return (0);
3253}
3254
3255int
3256ctl_lun_map_deinit(struct ctl_port *port)
3257{
3258	struct ctl_softc *softc = control_softc;
3259	struct ctl_lun *lun;
3260
3261	if (port->lun_map == NULL)
3262		return (0);
3263	free(port->lun_map, M_CTL);
3264	port->lun_map = NULL;
3265	if (port->status & CTL_PORT_STATUS_ONLINE) {
3266		if (port->lun_enable != NULL) {
3267			STAILQ_FOREACH(lun, &softc->lun_list, links)
3268				port->lun_enable(port->targ_lun_arg, lun->lun);
3269		}
3270		ctl_isc_announce_port(port);
3271	}
3272	return (0);
3273}
3274
3275int
3276ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3277{
3278	int status;
3279	uint32_t old;
3280
3281	if (port->lun_map == NULL) {
3282		status = ctl_lun_map_init(port);
3283		if (status != 0)
3284			return (status);
3285	}
3286	old = port->lun_map[plun];
3287	port->lun_map[plun] = glun;
3288	if ((port->status & CTL_PORT_STATUS_ONLINE) && old >= CTL_MAX_LUNS) {
3289		if (port->lun_enable != NULL)
3290			port->lun_enable(port->targ_lun_arg, plun);
3291		ctl_isc_announce_port(port);
3292	}
3293	return (0);
3294}
3295
3296int
3297ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3298{
3299	uint32_t old;
3300
3301	if (port->lun_map == NULL)
3302		return (0);
3303	old = port->lun_map[plun];
3304	port->lun_map[plun] = UINT32_MAX;
3305	if ((port->status & CTL_PORT_STATUS_ONLINE) && old < CTL_MAX_LUNS) {
3306		if (port->lun_disable != NULL)
3307			port->lun_disable(port->targ_lun_arg, plun);
3308		ctl_isc_announce_port(port);
3309	}
3310	return (0);
3311}
3312
3313uint32_t
3314ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3315{
3316
3317	if (port == NULL)
3318		return (UINT32_MAX);
3319	if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3320		return (lun_id);
3321	return (port->lun_map[lun_id]);
3322}
3323
3324uint32_t
3325ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3326{
3327	uint32_t i;
3328
3329	if (port == NULL)
3330		return (UINT32_MAX);
3331	if (port->lun_map == NULL)
3332		return (lun_id);
3333	for (i = 0; i < CTL_MAX_LUNS; i++) {
3334		if (port->lun_map[i] == lun_id)
3335			return (i);
3336	}
3337	return (UINT32_MAX);
3338}
3339
3340static struct ctl_port *
3341ctl_io_port(struct ctl_io_hdr *io_hdr)
3342{
3343
3344	return (control_softc->ctl_ports[io_hdr->nexus.targ_port]);
3345}
3346
3347int
3348ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3349{
3350	int i;
3351
3352	for (i = first; i < last; i++) {
3353		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3354			return (i);
3355	}
3356	return (-1);
3357}
3358
3359int
3360ctl_set_mask(uint32_t *mask, uint32_t bit)
3361{
3362	uint32_t chunk, piece;
3363
3364	chunk = bit >> 5;
3365	piece = bit % (sizeof(uint32_t) * 8);
3366
3367	if ((mask[chunk] & (1 << piece)) != 0)
3368		return (-1);
3369	else
3370		mask[chunk] |= (1 << piece);
3371
3372	return (0);
3373}
3374
3375int
3376ctl_clear_mask(uint32_t *mask, uint32_t bit)
3377{
3378	uint32_t chunk, piece;
3379
3380	chunk = bit >> 5;
3381	piece = bit % (sizeof(uint32_t) * 8);
3382
3383	if ((mask[chunk] & (1 << piece)) == 0)
3384		return (-1);
3385	else
3386		mask[chunk] &= ~(1 << piece);
3387
3388	return (0);
3389}
3390
3391int
3392ctl_is_set(uint32_t *mask, uint32_t bit)
3393{
3394	uint32_t chunk, piece;
3395
3396	chunk = bit >> 5;
3397	piece = bit % (sizeof(uint32_t) * 8);
3398
3399	if ((mask[chunk] & (1 << piece)) == 0)
3400		return (0);
3401	else
3402		return (1);
3403}
3404
3405static uint64_t
3406ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3407{
3408	uint64_t *t;
3409
3410	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3411	if (t == NULL)
3412		return (0);
3413	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3414}
3415
3416static void
3417ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3418{
3419	uint64_t *t;
3420
3421	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3422	if (t == NULL)
3423		return;
3424	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3425}
3426
3427static void
3428ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3429{
3430	uint64_t *p;
3431	u_int i;
3432
3433	i = residx/CTL_MAX_INIT_PER_PORT;
3434	if (lun->pr_keys[i] != NULL)
3435		return;
3436	mtx_unlock(&lun->lun_lock);
3437	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3438	    M_WAITOK | M_ZERO);
3439	mtx_lock(&lun->lun_lock);
3440	if (lun->pr_keys[i] == NULL)
3441		lun->pr_keys[i] = p;
3442	else
3443		free(p, M_CTL);
3444}
3445
3446static void
3447ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3448{
3449	uint64_t *t;
3450
3451	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3452	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3453	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3454}
3455
3456/*
3457 * ctl_softc, pool_name, total_ctl_io are passed in.
3458 * npool is passed out.
3459 */
3460int
3461ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3462		uint32_t total_ctl_io, void **npool)
3463{
3464#ifdef IO_POOLS
3465	struct ctl_io_pool *pool;
3466
3467	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3468					    M_NOWAIT | M_ZERO);
3469	if (pool == NULL)
3470		return (ENOMEM);
3471
3472	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3473	pool->ctl_softc = ctl_softc;
3474	pool->zone = uma_zsecond_create(pool->name, NULL,
3475	    NULL, NULL, NULL, ctl_softc->io_zone);
3476	/* uma_prealloc(pool->zone, total_ctl_io); */
3477
3478	*npool = pool;
3479#else
3480	*npool = ctl_softc->io_zone;
3481#endif
3482	return (0);
3483}
3484
3485void
3486ctl_pool_free(struct ctl_io_pool *pool)
3487{
3488
3489	if (pool == NULL)
3490		return;
3491
3492#ifdef IO_POOLS
3493	uma_zdestroy(pool->zone);
3494	free(pool, M_CTL);
3495#endif
3496}
3497
3498union ctl_io *
3499ctl_alloc_io(void *pool_ref)
3500{
3501	union ctl_io *io;
3502#ifdef IO_POOLS
3503	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3504
3505	io = uma_zalloc(pool->zone, M_WAITOK);
3506#else
3507	io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3508#endif
3509	if (io != NULL)
3510		io->io_hdr.pool = pool_ref;
3511	return (io);
3512}
3513
3514union ctl_io *
3515ctl_alloc_io_nowait(void *pool_ref)
3516{
3517	union ctl_io *io;
3518#ifdef IO_POOLS
3519	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3520
3521	io = uma_zalloc(pool->zone, M_NOWAIT);
3522#else
3523	io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3524#endif
3525	if (io != NULL)
3526		io->io_hdr.pool = pool_ref;
3527	return (io);
3528}
3529
3530void
3531ctl_free_io(union ctl_io *io)
3532{
3533#ifdef IO_POOLS
3534	struct ctl_io_pool *pool;
3535#endif
3536
3537	if (io == NULL)
3538		return;
3539
3540#ifdef IO_POOLS
3541	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3542	uma_zfree(pool->zone, io);
3543#else
3544	uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3545#endif
3546}
3547
3548void
3549ctl_zero_io(union ctl_io *io)
3550{
3551	void *pool_ref;
3552
3553	if (io == NULL)
3554		return;
3555
3556	/*
3557	 * May need to preserve linked list pointers at some point too.
3558	 */
3559	pool_ref = io->io_hdr.pool;
3560	memset(io, 0, sizeof(*io));
3561	io->io_hdr.pool = pool_ref;
3562}
3563
3564/*
3565 * This routine is currently used for internal copies of ctl_ios that need
3566 * to persist for some reason after we've already returned status to the
3567 * FETD.  (Thus the flag set.)
3568 *
3569 * XXX XXX
3570 * Note that this makes a blind copy of all fields in the ctl_io, except
3571 * for the pool reference.  This includes any memory that has been
3572 * allocated!  That memory will no longer be valid after done has been
3573 * called, so this would be VERY DANGEROUS for command that actually does
3574 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3575 * start and stop commands, which don't transfer any data, so this is not a
3576 * problem.  If it is used for anything else, the caller would also need to
3577 * allocate data buffer space and this routine would need to be modified to
3578 * copy the data buffer(s) as well.
3579 */
3580void
3581ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3582{
3583	void *pool_ref;
3584
3585	if ((src == NULL)
3586	 || (dest == NULL))
3587		return;
3588
3589	/*
3590	 * May need to preserve linked list pointers at some point too.
3591	 */
3592	pool_ref = dest->io_hdr.pool;
3593
3594	memcpy(dest, src, MIN(sizeof(*src), sizeof(*dest)));
3595
3596	dest->io_hdr.pool = pool_ref;
3597	/*
3598	 * We need to know that this is an internal copy, and doesn't need
3599	 * to get passed back to the FETD that allocated it.
3600	 */
3601	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3602}
3603
3604int
3605ctl_expand_number(const char *buf, uint64_t *num)
3606{
3607	char *endptr;
3608	uint64_t number;
3609	unsigned shift;
3610
3611	number = strtoq(buf, &endptr, 0);
3612
3613	switch (tolower((unsigned char)*endptr)) {
3614	case 'e':
3615		shift = 60;
3616		break;
3617	case 'p':
3618		shift = 50;
3619		break;
3620	case 't':
3621		shift = 40;
3622		break;
3623	case 'g':
3624		shift = 30;
3625		break;
3626	case 'm':
3627		shift = 20;
3628		break;
3629	case 'k':
3630		shift = 10;
3631		break;
3632	case 'b':
3633	case '\0': /* No unit. */
3634		*num = number;
3635		return (0);
3636	default:
3637		/* Unrecognized unit. */
3638		return (-1);
3639	}
3640
3641	if ((number << shift) >> shift != number) {
3642		/* Overflow */
3643		return (-1);
3644	}
3645	*num = number << shift;
3646	return (0);
3647}
3648
3649
3650/*
3651 * This routine could be used in the future to load default and/or saved
3652 * mode page parameters for a particuar lun.
3653 */
3654static int
3655ctl_init_page_index(struct ctl_lun *lun)
3656{
3657	int i;
3658	struct ctl_page_index *page_index;
3659	const char *value;
3660	uint64_t ival;
3661
3662	memcpy(&lun->mode_pages.index, page_index_template,
3663	       sizeof(page_index_template));
3664
3665	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3666
3667		page_index = &lun->mode_pages.index[i];
3668		/*
3669		 * If this is a disk-only mode page, there's no point in
3670		 * setting it up.  For some pages, we have to have some
3671		 * basic information about the disk in order to calculate the
3672		 * mode page data.
3673		 */
3674		if ((lun->be_lun->lun_type != T_DIRECT)
3675		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3676			continue;
3677
3678		switch (page_index->page_code & SMPH_PC_MASK) {
3679		case SMS_RW_ERROR_RECOVERY_PAGE: {
3680			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3681				panic("subpage is incorrect!");
3682			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3683			       &rw_er_page_default,
3684			       sizeof(rw_er_page_default));
3685			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3686			       &rw_er_page_changeable,
3687			       sizeof(rw_er_page_changeable));
3688			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3689			       &rw_er_page_default,
3690			       sizeof(rw_er_page_default));
3691			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3692			       &rw_er_page_default,
3693			       sizeof(rw_er_page_default));
3694			page_index->page_data =
3695				(uint8_t *)lun->mode_pages.rw_er_page;
3696			break;
3697		}
3698		case SMS_FORMAT_DEVICE_PAGE: {
3699			struct scsi_format_page *format_page;
3700
3701			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3702				panic("subpage is incorrect!");
3703
3704			/*
3705			 * Sectors per track are set above.  Bytes per
3706			 * sector need to be set here on a per-LUN basis.
3707			 */
3708			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3709			       &format_page_default,
3710			       sizeof(format_page_default));
3711			memcpy(&lun->mode_pages.format_page[
3712			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
3713			       sizeof(format_page_changeable));
3714			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3715			       &format_page_default,
3716			       sizeof(format_page_default));
3717			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3718			       &format_page_default,
3719			       sizeof(format_page_default));
3720
3721			format_page = &lun->mode_pages.format_page[
3722				CTL_PAGE_CURRENT];
3723			scsi_ulto2b(lun->be_lun->blocksize,
3724				    format_page->bytes_per_sector);
3725
3726			format_page = &lun->mode_pages.format_page[
3727				CTL_PAGE_DEFAULT];
3728			scsi_ulto2b(lun->be_lun->blocksize,
3729				    format_page->bytes_per_sector);
3730
3731			format_page = &lun->mode_pages.format_page[
3732				CTL_PAGE_SAVED];
3733			scsi_ulto2b(lun->be_lun->blocksize,
3734				    format_page->bytes_per_sector);
3735
3736			page_index->page_data =
3737				(uint8_t *)lun->mode_pages.format_page;
3738			break;
3739		}
3740		case SMS_RIGID_DISK_PAGE: {
3741			struct scsi_rigid_disk_page *rigid_disk_page;
3742			uint32_t sectors_per_cylinder;
3743			uint64_t cylinders;
3744#ifndef	__XSCALE__
3745			int shift;
3746#endif /* !__XSCALE__ */
3747
3748			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3749				panic("invalid subpage value %d",
3750				      page_index->subpage);
3751
3752			/*
3753			 * Rotation rate and sectors per track are set
3754			 * above.  We calculate the cylinders here based on
3755			 * capacity.  Due to the number of heads and
3756			 * sectors per track we're using, smaller arrays
3757			 * may turn out to have 0 cylinders.  Linux and
3758			 * FreeBSD don't pay attention to these mode pages
3759			 * to figure out capacity, but Solaris does.  It
3760			 * seems to deal with 0 cylinders just fine, and
3761			 * works out a fake geometry based on the capacity.
3762			 */
3763			memcpy(&lun->mode_pages.rigid_disk_page[
3764			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
3765			       sizeof(rigid_disk_page_default));
3766			memcpy(&lun->mode_pages.rigid_disk_page[
3767			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
3768			       sizeof(rigid_disk_page_changeable));
3769
3770			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
3771				CTL_DEFAULT_HEADS;
3772
3773			/*
3774			 * The divide method here will be more accurate,
3775			 * probably, but results in floating point being
3776			 * used in the kernel on i386 (__udivdi3()).  On the
3777			 * XScale, though, __udivdi3() is implemented in
3778			 * software.
3779			 *
3780			 * The shift method for cylinder calculation is
3781			 * accurate if sectors_per_cylinder is a power of
3782			 * 2.  Otherwise it might be slightly off -- you
3783			 * might have a bit of a truncation problem.
3784			 */
3785#ifdef	__XSCALE__
3786			cylinders = (lun->be_lun->maxlba + 1) /
3787				sectors_per_cylinder;
3788#else
3789			for (shift = 31; shift > 0; shift--) {
3790				if (sectors_per_cylinder & (1 << shift))
3791					break;
3792			}
3793			cylinders = (lun->be_lun->maxlba + 1) >> shift;
3794#endif
3795
3796			/*
3797			 * We've basically got 3 bytes, or 24 bits for the
3798			 * cylinder size in the mode page.  If we're over,
3799			 * just round down to 2^24.
3800			 */
3801			if (cylinders > 0xffffff)
3802				cylinders = 0xffffff;
3803
3804			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
3805				CTL_PAGE_DEFAULT];
3806			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
3807
3808			if ((value = ctl_get_opt(&lun->be_lun->options,
3809			    "rpm")) != NULL) {
3810				scsi_ulto2b(strtol(value, NULL, 0),
3811				     rigid_disk_page->rotation_rate);
3812			}
3813
3814			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
3815			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
3816			       sizeof(rigid_disk_page_default));
3817			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
3818			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
3819			       sizeof(rigid_disk_page_default));
3820
3821			page_index->page_data =
3822				(uint8_t *)lun->mode_pages.rigid_disk_page;
3823			break;
3824		}
3825		case SMS_CACHING_PAGE: {
3826			struct scsi_caching_page *caching_page;
3827
3828			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3829				panic("invalid subpage value %d",
3830				      page_index->subpage);
3831			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
3832			       &caching_page_default,
3833			       sizeof(caching_page_default));
3834			memcpy(&lun->mode_pages.caching_page[
3835			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
3836			       sizeof(caching_page_changeable));
3837			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
3838			       &caching_page_default,
3839			       sizeof(caching_page_default));
3840			caching_page = &lun->mode_pages.caching_page[
3841			    CTL_PAGE_SAVED];
3842			value = ctl_get_opt(&lun->be_lun->options, "writecache");
3843			if (value != NULL && strcmp(value, "off") == 0)
3844				caching_page->flags1 &= ~SCP_WCE;
3845			value = ctl_get_opt(&lun->be_lun->options, "readcache");
3846			if (value != NULL && strcmp(value, "off") == 0)
3847				caching_page->flags1 |= SCP_RCD;
3848			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
3849			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
3850			       sizeof(caching_page_default));
3851			page_index->page_data =
3852				(uint8_t *)lun->mode_pages.caching_page;
3853			break;
3854		}
3855		case SMS_CONTROL_MODE_PAGE: {
3856			struct scsi_control_page *control_page;
3857
3858			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3859				panic("invalid subpage value %d",
3860				      page_index->subpage);
3861
3862			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
3863			       &control_page_default,
3864			       sizeof(control_page_default));
3865			memcpy(&lun->mode_pages.control_page[
3866			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
3867			       sizeof(control_page_changeable));
3868			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
3869			       &control_page_default,
3870			       sizeof(control_page_default));
3871			control_page = &lun->mode_pages.control_page[
3872			    CTL_PAGE_SAVED];
3873			value = ctl_get_opt(&lun->be_lun->options, "reordering");
3874			if (value != NULL && strcmp(value, "unrestricted") == 0) {
3875				control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
3876				control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
3877			}
3878			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
3879			       &lun->mode_pages.control_page[CTL_PAGE_SAVED],
3880			       sizeof(control_page_default));
3881			page_index->page_data =
3882				(uint8_t *)lun->mode_pages.control_page;
3883			break;
3884
3885		}
3886		case SMS_INFO_EXCEPTIONS_PAGE: {
3887			switch (page_index->subpage) {
3888			case SMS_SUBPAGE_PAGE_0:
3889				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
3890				       &ie_page_default,
3891				       sizeof(ie_page_default));
3892				memcpy(&lun->mode_pages.ie_page[
3893				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
3894				       sizeof(ie_page_changeable));
3895				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
3896				       &ie_page_default,
3897				       sizeof(ie_page_default));
3898				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
3899				       &ie_page_default,
3900				       sizeof(ie_page_default));
3901				page_index->page_data =
3902					(uint8_t *)lun->mode_pages.ie_page;
3903				break;
3904			case 0x02: {
3905				struct ctl_logical_block_provisioning_page *page;
3906
3907				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
3908				       &lbp_page_default,
3909				       sizeof(lbp_page_default));
3910				memcpy(&lun->mode_pages.lbp_page[
3911				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
3912				       sizeof(lbp_page_changeable));
3913				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
3914				       &lbp_page_default,
3915				       sizeof(lbp_page_default));
3916				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
3917				value = ctl_get_opt(&lun->be_lun->options,
3918				    "avail-threshold");
3919				if (value != NULL &&
3920				    ctl_expand_number(value, &ival) == 0) {
3921					page->descr[0].flags |= SLBPPD_ENABLED |
3922					    SLBPPD_ARMING_DEC;
3923					if (lun->be_lun->blocksize)
3924						ival /= lun->be_lun->blocksize;
3925					else
3926						ival /= 512;
3927					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
3928					    page->descr[0].count);
3929				}
3930				value = ctl_get_opt(&lun->be_lun->options,
3931				    "used-threshold");
3932				if (value != NULL &&
3933				    ctl_expand_number(value, &ival) == 0) {
3934					page->descr[1].flags |= SLBPPD_ENABLED |
3935					    SLBPPD_ARMING_INC;
3936					if (lun->be_lun->blocksize)
3937						ival /= lun->be_lun->blocksize;
3938					else
3939						ival /= 512;
3940					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
3941					    page->descr[1].count);
3942				}
3943				value = ctl_get_opt(&lun->be_lun->options,
3944				    "pool-avail-threshold");
3945				if (value != NULL &&
3946				    ctl_expand_number(value, &ival) == 0) {
3947					page->descr[2].flags |= SLBPPD_ENABLED |
3948					    SLBPPD_ARMING_DEC;
3949					if (lun->be_lun->blocksize)
3950						ival /= lun->be_lun->blocksize;
3951					else
3952						ival /= 512;
3953					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
3954					    page->descr[2].count);
3955				}
3956				value = ctl_get_opt(&lun->be_lun->options,
3957				    "pool-used-threshold");
3958				if (value != NULL &&
3959				    ctl_expand_number(value, &ival) == 0) {
3960					page->descr[3].flags |= SLBPPD_ENABLED |
3961					    SLBPPD_ARMING_INC;
3962					if (lun->be_lun->blocksize)
3963						ival /= lun->be_lun->blocksize;
3964					else
3965						ival /= 512;
3966					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
3967					    page->descr[3].count);
3968				}
3969				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
3970				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
3971				       sizeof(lbp_page_default));
3972				page_index->page_data =
3973					(uint8_t *)lun->mode_pages.lbp_page;
3974			}}
3975			break;
3976		}
3977		case SMS_VENDOR_SPECIFIC_PAGE:{
3978			switch (page_index->subpage) {
3979			case DBGCNF_SUBPAGE_CODE: {
3980				struct copan_debugconf_subpage *current_page,
3981							       *saved_page;
3982
3983				memcpy(&lun->mode_pages.debugconf_subpage[
3984				       CTL_PAGE_CURRENT],
3985				       &debugconf_page_default,
3986				       sizeof(debugconf_page_default));
3987				memcpy(&lun->mode_pages.debugconf_subpage[
3988				       CTL_PAGE_CHANGEABLE],
3989				       &debugconf_page_changeable,
3990				       sizeof(debugconf_page_changeable));
3991				memcpy(&lun->mode_pages.debugconf_subpage[
3992				       CTL_PAGE_DEFAULT],
3993				       &debugconf_page_default,
3994				       sizeof(debugconf_page_default));
3995				memcpy(&lun->mode_pages.debugconf_subpage[
3996				       CTL_PAGE_SAVED],
3997				       &debugconf_page_default,
3998				       sizeof(debugconf_page_default));
3999				page_index->page_data =
4000					(uint8_t *)lun->mode_pages.debugconf_subpage;
4001
4002				current_page = (struct copan_debugconf_subpage *)
4003					(page_index->page_data +
4004					 (page_index->page_len *
4005					  CTL_PAGE_CURRENT));
4006				saved_page = (struct copan_debugconf_subpage *)
4007					(page_index->page_data +
4008					 (page_index->page_len *
4009					  CTL_PAGE_SAVED));
4010				break;
4011			}
4012			default:
4013				panic("invalid subpage value %d",
4014				      page_index->subpage);
4015				break;
4016			}
4017   			break;
4018		}
4019		default:
4020			panic("invalid page value %d",
4021			      page_index->page_code & SMPH_PC_MASK);
4022			break;
4023    	}
4024	}
4025
4026	return (CTL_RETVAL_COMPLETE);
4027}
4028
4029static int
4030ctl_init_log_page_index(struct ctl_lun *lun)
4031{
4032	struct ctl_page_index *page_index;
4033	int i, j, k, prev;
4034
4035	memcpy(&lun->log_pages.index, log_page_index_template,
4036	       sizeof(log_page_index_template));
4037
4038	prev = -1;
4039	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4040
4041		page_index = &lun->log_pages.index[i];
4042		/*
4043		 * If this is a disk-only mode page, there's no point in
4044		 * setting it up.  For some pages, we have to have some
4045		 * basic information about the disk in order to calculate the
4046		 * mode page data.
4047		 */
4048		if ((lun->be_lun->lun_type != T_DIRECT)
4049		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4050			continue;
4051
4052		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4053		     lun->backend->lun_attr == NULL)
4054			continue;
4055
4056		if (page_index->page_code != prev) {
4057			lun->log_pages.pages_page[j] = page_index->page_code;
4058			prev = page_index->page_code;
4059			j++;
4060		}
4061		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4062		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4063		k++;
4064	}
4065	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4066	lun->log_pages.index[0].page_len = j;
4067	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4068	lun->log_pages.index[1].page_len = k * 2;
4069	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4070	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4071	lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4072	lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4073
4074	return (CTL_RETVAL_COMPLETE);
4075}
4076
4077static int
4078hex2bin(const char *str, uint8_t *buf, int buf_size)
4079{
4080	int i;
4081	u_char c;
4082
4083	memset(buf, 0, buf_size);
4084	while (isspace(str[0]))
4085		str++;
4086	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4087		str += 2;
4088	buf_size *= 2;
4089	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4090		c = str[i];
4091		if (isdigit(c))
4092			c -= '0';
4093		else if (isalpha(c))
4094			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4095		else
4096			break;
4097		if (c >= 16)
4098			break;
4099		if ((i & 1) == 0)
4100			buf[i / 2] |= (c << 4);
4101		else
4102			buf[i / 2] |= c;
4103	}
4104	return ((i + 1) / 2);
4105}
4106
4107/*
4108 * LUN allocation.
4109 *
4110 * Requirements:
4111 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4112 *   wants us to allocate the LUN and he can block.
4113 * - ctl_softc is always set
4114 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4115 *
4116 * Returns 0 for success, non-zero (errno) for failure.
4117 */
4118static int
4119ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4120	      struct ctl_be_lun *const be_lun)
4121{
4122	struct ctl_lun *nlun, *lun;
4123	struct scsi_vpd_id_descriptor *desc;
4124	struct scsi_vpd_id_t10 *t10id;
4125	const char *eui, *naa, *scsiname, *vendor;
4126	int lun_number, i, lun_malloced;
4127	int devidlen, idlen1, idlen2 = 0, len;
4128
4129	if (be_lun == NULL)
4130		return (EINVAL);
4131
4132	/*
4133	 * We currently only support Direct Access or Processor LUN types.
4134	 */
4135	switch (be_lun->lun_type) {
4136	case T_DIRECT:
4137		break;
4138	case T_PROCESSOR:
4139		break;
4140	case T_SEQUENTIAL:
4141	case T_CHANGER:
4142	default:
4143		be_lun->lun_config_status(be_lun->be_lun,
4144					  CTL_LUN_CONFIG_FAILURE);
4145		break;
4146	}
4147	if (ctl_lun == NULL) {
4148		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4149		lun_malloced = 1;
4150	} else {
4151		lun_malloced = 0;
4152		lun = ctl_lun;
4153	}
4154
4155	memset(lun, 0, sizeof(*lun));
4156	if (lun_malloced)
4157		lun->flags = CTL_LUN_MALLOCED;
4158
4159	/* Generate LUN ID. */
4160	devidlen = max(CTL_DEVID_MIN_LEN,
4161	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4162	idlen1 = sizeof(*t10id) + devidlen;
4163	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4164	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4165	if (scsiname != NULL) {
4166		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4167		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4168	}
4169	eui = ctl_get_opt(&be_lun->options, "eui");
4170	if (eui != NULL) {
4171		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4172	}
4173	naa = ctl_get_opt(&be_lun->options, "naa");
4174	if (naa != NULL) {
4175		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4176	}
4177	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4178	    M_CTL, M_WAITOK | M_ZERO);
4179	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4180	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4181	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4182	desc->length = idlen1;
4183	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4184	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4185	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4186		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4187	} else {
4188		strncpy(t10id->vendor, vendor,
4189		    min(sizeof(t10id->vendor), strlen(vendor)));
4190	}
4191	strncpy((char *)t10id->vendor_spec_id,
4192	    (char *)be_lun->device_id, devidlen);
4193	if (scsiname != NULL) {
4194		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4195		    desc->length);
4196		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4197		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4198		    SVPD_ID_TYPE_SCSI_NAME;
4199		desc->length = idlen2;
4200		strlcpy(desc->identifier, scsiname, idlen2);
4201	}
4202	if (eui != NULL) {
4203		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4204		    desc->length);
4205		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4206		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4207		    SVPD_ID_TYPE_EUI64;
4208		desc->length = hex2bin(eui, desc->identifier, 16);
4209		desc->length = desc->length > 12 ? 16 :
4210		    (desc->length > 8 ? 12 : 8);
4211		len -= 16 - desc->length;
4212	}
4213	if (naa != NULL) {
4214		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4215		    desc->length);
4216		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4217		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4218		    SVPD_ID_TYPE_NAA;
4219		desc->length = hex2bin(naa, desc->identifier, 16);
4220		desc->length = desc->length > 8 ? 16 : 8;
4221		len -= 16 - desc->length;
4222	}
4223	lun->lun_devid->len = len;
4224
4225	mtx_lock(&ctl_softc->ctl_lock);
4226	/*
4227	 * See if the caller requested a particular LUN number.  If so, see
4228	 * if it is available.  Otherwise, allocate the first available LUN.
4229	 */
4230	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4231		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4232		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4233			mtx_unlock(&ctl_softc->ctl_lock);
4234			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4235				printf("ctl: requested LUN ID %d is higher "
4236				       "than CTL_MAX_LUNS - 1 (%d)\n",
4237				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4238			} else {
4239				/*
4240				 * XXX KDM return an error, or just assign
4241				 * another LUN ID in this case??
4242				 */
4243				printf("ctl: requested LUN ID %d is already "
4244				       "in use\n", be_lun->req_lun_id);
4245			}
4246			if (lun->flags & CTL_LUN_MALLOCED)
4247				free(lun, M_CTL);
4248			be_lun->lun_config_status(be_lun->be_lun,
4249						  CTL_LUN_CONFIG_FAILURE);
4250			return (ENOSPC);
4251		}
4252		lun_number = be_lun->req_lun_id;
4253	} else {
4254		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4255		if (lun_number == -1) {
4256			mtx_unlock(&ctl_softc->ctl_lock);
4257			printf("ctl: can't allocate LUN, out of LUNs\n");
4258			if (lun->flags & CTL_LUN_MALLOCED)
4259				free(lun, M_CTL);
4260			be_lun->lun_config_status(be_lun->be_lun,
4261						  CTL_LUN_CONFIG_FAILURE);
4262			return (ENOSPC);
4263		}
4264	}
4265	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4266
4267	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4268	lun->lun = lun_number;
4269	lun->be_lun = be_lun;
4270	/*
4271	 * The processor LUN is always enabled.  Disk LUNs come on line
4272	 * disabled, and must be enabled by the backend.
4273	 */
4274	lun->flags |= CTL_LUN_DISABLED;
4275	lun->backend = be_lun->be;
4276	be_lun->ctl_lun = lun;
4277	be_lun->lun_id = lun_number;
4278	atomic_add_int(&be_lun->be->num_luns, 1);
4279	if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4280		lun->flags |= CTL_LUN_OFFLINE;
4281
4282	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4283		lun->flags |= CTL_LUN_STOPPED;
4284
4285	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4286		lun->flags |= CTL_LUN_INOPERABLE;
4287
4288	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4289		lun->flags |= CTL_LUN_PRIMARY_SC;
4290
4291	lun->ctl_softc = ctl_softc;
4292#ifdef CTL_TIME_IO
4293	lun->last_busy = getsbinuptime();
4294#endif
4295	TAILQ_INIT(&lun->ooa_queue);
4296	TAILQ_INIT(&lun->blocked_queue);
4297	STAILQ_INIT(&lun->error_list);
4298	ctl_tpc_lun_init(lun);
4299
4300	/*
4301	 * Initialize the mode and log page index.
4302	 */
4303	ctl_init_page_index(lun);
4304	ctl_init_log_page_index(lun);
4305
4306	/*
4307	 * Now, before we insert this lun on the lun list, set the lun
4308	 * inventory changed UA for all other luns.
4309	 */
4310	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4311		mtx_lock(&nlun->lun_lock);
4312		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4313		mtx_unlock(&nlun->lun_lock);
4314	}
4315
4316	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4317
4318	ctl_softc->ctl_luns[lun_number] = lun;
4319
4320	ctl_softc->num_luns++;
4321
4322	/* Setup statistics gathering */
4323	lun->stats.device_type = be_lun->lun_type;
4324	lun->stats.lun_number = lun_number;
4325	if (lun->stats.device_type == T_DIRECT)
4326		lun->stats.blocksize = be_lun->blocksize;
4327	else
4328		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4329	for (i = 0;i < CTL_MAX_PORTS;i++)
4330		lun->stats.ports[i].targ_port = i;
4331
4332	mtx_unlock(&ctl_softc->ctl_lock);
4333
4334	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4335	return (0);
4336}
4337
4338/*
4339 * Delete a LUN.
4340 * Assumptions:
4341 * - LUN has already been marked invalid and any pending I/O has been taken
4342 *   care of.
4343 */
4344static int
4345ctl_free_lun(struct ctl_lun *lun)
4346{
4347	struct ctl_softc *softc;
4348	struct ctl_lun *nlun;
4349	int i;
4350
4351	softc = lun->ctl_softc;
4352
4353	mtx_assert(&softc->ctl_lock, MA_OWNED);
4354
4355	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4356
4357	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4358
4359	softc->ctl_luns[lun->lun] = NULL;
4360
4361	if (!TAILQ_EMPTY(&lun->ooa_queue))
4362		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4363
4364	softc->num_luns--;
4365
4366	/*
4367	 * Tell the backend to free resources, if this LUN has a backend.
4368	 */
4369	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4370	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4371
4372	ctl_tpc_lun_shutdown(lun);
4373	mtx_destroy(&lun->lun_lock);
4374	free(lun->lun_devid, M_CTL);
4375	for (i = 0; i < CTL_MAX_PORTS; i++)
4376		free(lun->pending_ua[i], M_CTL);
4377	for (i = 0; i < CTL_MAX_PORTS; i++)
4378		free(lun->pr_keys[i], M_CTL);
4379	free(lun->write_buffer, M_CTL);
4380	if (lun->flags & CTL_LUN_MALLOCED)
4381		free(lun, M_CTL);
4382
4383	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4384		mtx_lock(&nlun->lun_lock);
4385		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4386		mtx_unlock(&nlun->lun_lock);
4387	}
4388
4389	return (0);
4390}
4391
4392static void
4393ctl_create_lun(struct ctl_be_lun *be_lun)
4394{
4395	struct ctl_softc *softc;
4396
4397	softc = control_softc;
4398
4399	/*
4400	 * ctl_alloc_lun() should handle all potential failure cases.
4401	 */
4402	ctl_alloc_lun(softc, NULL, be_lun);
4403}
4404
4405int
4406ctl_add_lun(struct ctl_be_lun *be_lun)
4407{
4408	struct ctl_softc *softc = control_softc;
4409
4410	mtx_lock(&softc->ctl_lock);
4411	STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4412	mtx_unlock(&softc->ctl_lock);
4413	wakeup(&softc->pending_lun_queue);
4414
4415	return (0);
4416}
4417
4418int
4419ctl_enable_lun(struct ctl_be_lun *be_lun)
4420{
4421	struct ctl_softc *softc;
4422	struct ctl_port *port, *nport;
4423	struct ctl_lun *lun;
4424	int retval;
4425
4426	lun = (struct ctl_lun *)be_lun->ctl_lun;
4427	softc = lun->ctl_softc;
4428
4429	mtx_lock(&softc->ctl_lock);
4430	mtx_lock(&lun->lun_lock);
4431	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4432		/*
4433		 * eh?  Why did we get called if the LUN is already
4434		 * enabled?
4435		 */
4436		mtx_unlock(&lun->lun_lock);
4437		mtx_unlock(&softc->ctl_lock);
4438		return (0);
4439	}
4440	lun->flags &= ~CTL_LUN_DISABLED;
4441	mtx_unlock(&lun->lun_lock);
4442
4443	for (port = STAILQ_FIRST(&softc->port_list); port != NULL; port = nport) {
4444		nport = STAILQ_NEXT(port, links);
4445		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4446		    port->lun_map != NULL || port->lun_enable == NULL)
4447			continue;
4448
4449		/*
4450		 * Drop the lock while we call the FETD's enable routine.
4451		 * This can lead to a callback into CTL (at least in the
4452		 * case of the internal initiator frontend.
4453		 */
4454		mtx_unlock(&softc->ctl_lock);
4455		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4456		mtx_lock(&softc->ctl_lock);
4457		if (retval != 0) {
4458			printf("%s: FETD %s port %d returned error "
4459			       "%d for lun_enable on lun %jd\n",
4460			       __func__, port->port_name, port->targ_port,
4461			       retval, (intmax_t)lun->lun);
4462		}
4463	}
4464
4465	mtx_unlock(&softc->ctl_lock);
4466	ctl_isc_announce_lun(lun);
4467
4468	return (0);
4469}
4470
4471int
4472ctl_disable_lun(struct ctl_be_lun *be_lun)
4473{
4474	struct ctl_softc *softc;
4475	struct ctl_port *port;
4476	struct ctl_lun *lun;
4477	int retval;
4478
4479	lun = (struct ctl_lun *)be_lun->ctl_lun;
4480	softc = lun->ctl_softc;
4481
4482	mtx_lock(&softc->ctl_lock);
4483	mtx_lock(&lun->lun_lock);
4484	if (lun->flags & CTL_LUN_DISABLED) {
4485		mtx_unlock(&lun->lun_lock);
4486		mtx_unlock(&softc->ctl_lock);
4487		return (0);
4488	}
4489	lun->flags |= CTL_LUN_DISABLED;
4490	mtx_unlock(&lun->lun_lock);
4491
4492	STAILQ_FOREACH(port, &softc->port_list, links) {
4493		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4494		    port->lun_map != NULL || port->lun_disable == NULL)
4495			continue;
4496
4497		/*
4498		 * Drop the lock before we call the frontend's disable
4499		 * routine, to avoid lock order reversals.
4500		 *
4501		 * XXX KDM what happens if the frontend list changes while
4502		 * we're traversing it?  It's unlikely, but should be handled.
4503		 */
4504		mtx_unlock(&softc->ctl_lock);
4505		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4506		mtx_lock(&softc->ctl_lock);
4507		if (retval != 0) {
4508			printf("%s: FETD %s port %d returned error "
4509			       "%d for lun_disable on lun %jd\n",
4510			       __func__, port->port_name, port->targ_port,
4511			       retval, (intmax_t)lun->lun);
4512		}
4513	}
4514
4515	mtx_unlock(&softc->ctl_lock);
4516	ctl_isc_announce_lun(lun);
4517
4518	return (0);
4519}
4520
4521int
4522ctl_start_lun(struct ctl_be_lun *be_lun)
4523{
4524	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4525
4526	mtx_lock(&lun->lun_lock);
4527	lun->flags &= ~CTL_LUN_STOPPED;
4528	mtx_unlock(&lun->lun_lock);
4529	return (0);
4530}
4531
4532int
4533ctl_stop_lun(struct ctl_be_lun *be_lun)
4534{
4535	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4536
4537	mtx_lock(&lun->lun_lock);
4538	lun->flags |= CTL_LUN_STOPPED;
4539	mtx_unlock(&lun->lun_lock);
4540	return (0);
4541}
4542
4543int
4544ctl_lun_offline(struct ctl_be_lun *be_lun)
4545{
4546	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4547
4548	mtx_lock(&lun->lun_lock);
4549	lun->flags |= CTL_LUN_OFFLINE;
4550	mtx_unlock(&lun->lun_lock);
4551	return (0);
4552}
4553
4554int
4555ctl_lun_online(struct ctl_be_lun *be_lun)
4556{
4557	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4558
4559	mtx_lock(&lun->lun_lock);
4560	lun->flags &= ~CTL_LUN_OFFLINE;
4561	mtx_unlock(&lun->lun_lock);
4562	return (0);
4563}
4564
4565int
4566ctl_lun_primary(struct ctl_be_lun *be_lun)
4567{
4568	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4569
4570	mtx_lock(&lun->lun_lock);
4571	lun->flags |= CTL_LUN_PRIMARY_SC;
4572	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4573	mtx_unlock(&lun->lun_lock);
4574	ctl_isc_announce_lun(lun);
4575	return (0);
4576}
4577
4578int
4579ctl_lun_secondary(struct ctl_be_lun *be_lun)
4580{
4581	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4582
4583	mtx_lock(&lun->lun_lock);
4584	lun->flags &= ~CTL_LUN_PRIMARY_SC;
4585	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4586	mtx_unlock(&lun->lun_lock);
4587	ctl_isc_announce_lun(lun);
4588	return (0);
4589}
4590
4591int
4592ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4593{
4594	struct ctl_softc *softc;
4595	struct ctl_lun *lun;
4596
4597	lun = (struct ctl_lun *)be_lun->ctl_lun;
4598	softc = lun->ctl_softc;
4599
4600	mtx_lock(&lun->lun_lock);
4601
4602	/*
4603	 * The LUN needs to be disabled before it can be marked invalid.
4604	 */
4605	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4606		mtx_unlock(&lun->lun_lock);
4607		return (-1);
4608	}
4609	/*
4610	 * Mark the LUN invalid.
4611	 */
4612	lun->flags |= CTL_LUN_INVALID;
4613
4614	/*
4615	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4616	 * If we have something in the OOA queue, we'll free it when the
4617	 * last I/O completes.
4618	 */
4619	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4620		mtx_unlock(&lun->lun_lock);
4621		mtx_lock(&softc->ctl_lock);
4622		ctl_free_lun(lun);
4623		mtx_unlock(&softc->ctl_lock);
4624	} else
4625		mtx_unlock(&lun->lun_lock);
4626
4627	return (0);
4628}
4629
4630int
4631ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4632{
4633	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4634
4635	mtx_lock(&lun->lun_lock);
4636	lun->flags |= CTL_LUN_INOPERABLE;
4637	mtx_unlock(&lun->lun_lock);
4638	return (0);
4639}
4640
4641int
4642ctl_lun_operable(struct ctl_be_lun *be_lun)
4643{
4644	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4645
4646	mtx_lock(&lun->lun_lock);
4647	lun->flags &= ~CTL_LUN_INOPERABLE;
4648	mtx_unlock(&lun->lun_lock);
4649	return (0);
4650}
4651
4652void
4653ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4654{
4655	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4656	union ctl_ha_msg msg;
4657
4658	mtx_lock(&lun->lun_lock);
4659	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGED);
4660	mtx_unlock(&lun->lun_lock);
4661	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4662		/* Send msg to other side. */
4663		bzero(&msg.ua, sizeof(msg.ua));
4664		msg.hdr.msg_type = CTL_MSG_UA;
4665		msg.hdr.nexus.initid = -1;
4666		msg.hdr.nexus.targ_port = -1;
4667		msg.hdr.nexus.targ_lun = lun->lun;
4668		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4669		msg.ua.ua_all = 1;
4670		msg.ua.ua_set = 1;
4671		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGED;
4672		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4673		    M_WAITOK);
4674	}
4675}
4676
4677/*
4678 * Backend "memory move is complete" callback for requests that never
4679 * make it down to say RAIDCore's configuration code.
4680 */
4681int
4682ctl_config_move_done(union ctl_io *io)
4683{
4684	int retval;
4685
4686	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4687	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4688	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
4689
4690	if ((io->io_hdr.port_status != 0) &&
4691	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4692	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4693		/*
4694		 * For hardware error sense keys, the sense key
4695		 * specific value is defined to be a retry count,
4696		 * but we use it to pass back an internal FETD
4697		 * error code.  XXX KDM  Hopefully the FETD is only
4698		 * using 16 bits for an error code, since that's
4699		 * all the space we have in the sks field.
4700		 */
4701		ctl_set_internal_failure(&io->scsiio,
4702					 /*sks_valid*/ 1,
4703					 /*retry_count*/
4704					 io->io_hdr.port_status);
4705	}
4706
4707	if (ctl_debug & CTL_DEBUG_CDB_DATA)
4708		ctl_data_print(io);
4709	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
4710	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4711	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
4712	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
4713		/*
4714		 * XXX KDM just assuming a single pointer here, and not a
4715		 * S/G list.  If we start using S/G lists for config data,
4716		 * we'll need to know how to clean them up here as well.
4717		 */
4718		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4719			free(io->scsiio.kern_data_ptr, M_CTL);
4720		ctl_done(io);
4721		retval = CTL_RETVAL_COMPLETE;
4722	} else {
4723		/*
4724		 * XXX KDM now we need to continue data movement.  Some
4725		 * options:
4726		 * - call ctl_scsiio() again?  We don't do this for data
4727		 *   writes, because for those at least we know ahead of
4728		 *   time where the write will go and how long it is.  For
4729		 *   config writes, though, that information is largely
4730		 *   contained within the write itself, thus we need to
4731		 *   parse out the data again.
4732		 *
4733		 * - Call some other function once the data is in?
4734		 */
4735
4736		/*
4737		 * XXX KDM call ctl_scsiio() again for now, and check flag
4738		 * bits to see whether we're allocated or not.
4739		 */
4740		retval = ctl_scsiio(&io->scsiio);
4741	}
4742	return (retval);
4743}
4744
4745/*
4746 * This gets called by a backend driver when it is done with a
4747 * data_submit method.
4748 */
4749void
4750ctl_data_submit_done(union ctl_io *io)
4751{
4752	/*
4753	 * If the IO_CONT flag is set, we need to call the supplied
4754	 * function to continue processing the I/O, instead of completing
4755	 * the I/O just yet.
4756	 *
4757	 * If there is an error, though, we don't want to keep processing.
4758	 * Instead, just send status back to the initiator.
4759	 */
4760	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
4761	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
4762	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4763	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4764		io->scsiio.io_cont(io);
4765		return;
4766	}
4767	ctl_done(io);
4768}
4769
4770/*
4771 * This gets called by a backend driver when it is done with a
4772 * configuration write.
4773 */
4774void
4775ctl_config_write_done(union ctl_io *io)
4776{
4777	uint8_t *buf;
4778
4779	/*
4780	 * If the IO_CONT flag is set, we need to call the supplied
4781	 * function to continue processing the I/O, instead of completing
4782	 * the I/O just yet.
4783	 *
4784	 * If there is an error, though, we don't want to keep processing.
4785	 * Instead, just send status back to the initiator.
4786	 */
4787	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
4788	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
4789	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4790	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4791		io->scsiio.io_cont(io);
4792		return;
4793	}
4794	/*
4795	 * Since a configuration write can be done for commands that actually
4796	 * have data allocated, like write buffer, and commands that have
4797	 * no data, like start/stop unit, we need to check here.
4798	 */
4799	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4800		buf = io->scsiio.kern_data_ptr;
4801	else
4802		buf = NULL;
4803	ctl_done(io);
4804	if (buf)
4805		free(buf, M_CTL);
4806}
4807
4808void
4809ctl_config_read_done(union ctl_io *io)
4810{
4811	uint8_t *buf;
4812
4813	/*
4814	 * If there is some error -- we are done, skip data transfer.
4815	 */
4816	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
4817	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4818	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
4819		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4820			buf = io->scsiio.kern_data_ptr;
4821		else
4822			buf = NULL;
4823		ctl_done(io);
4824		if (buf)
4825			free(buf, M_CTL);
4826		return;
4827	}
4828
4829	/*
4830	 * If the IO_CONT flag is set, we need to call the supplied
4831	 * function to continue processing the I/O, instead of completing
4832	 * the I/O just yet.
4833	 */
4834	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
4835		io->scsiio.io_cont(io);
4836		return;
4837	}
4838
4839	ctl_datamove(io);
4840}
4841
4842/*
4843 * SCSI release command.
4844 */
4845int
4846ctl_scsi_release(struct ctl_scsiio *ctsio)
4847{
4848	int length, longid, thirdparty_id, resv_id;
4849	struct ctl_lun *lun;
4850	uint32_t residx;
4851
4852	length = 0;
4853	resv_id = 0;
4854
4855	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
4856
4857	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
4858	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
4859
4860	switch (ctsio->cdb[0]) {
4861	case RELEASE_10: {
4862		struct scsi_release_10 *cdb;
4863
4864		cdb = (struct scsi_release_10 *)ctsio->cdb;
4865
4866		if (cdb->byte2 & SR10_LONGID)
4867			longid = 1;
4868		else
4869			thirdparty_id = cdb->thirdparty_id;
4870
4871		resv_id = cdb->resv_id;
4872		length = scsi_2btoul(cdb->length);
4873		break;
4874	}
4875	}
4876
4877
4878	/*
4879	 * XXX KDM right now, we only support LUN reservation.  We don't
4880	 * support 3rd party reservations, or extent reservations, which
4881	 * might actually need the parameter list.  If we've gotten this
4882	 * far, we've got a LUN reservation.  Anything else got kicked out
4883	 * above.  So, according to SPC, ignore the length.
4884	 */
4885	length = 0;
4886
4887	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
4888	 && (length > 0)) {
4889		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
4890		ctsio->kern_data_len = length;
4891		ctsio->kern_total_len = length;
4892		ctsio->kern_data_resid = 0;
4893		ctsio->kern_rel_offset = 0;
4894		ctsio->kern_sg_entries = 0;
4895		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
4896		ctsio->be_move_done = ctl_config_move_done;
4897		ctl_datamove((union ctl_io *)ctsio);
4898
4899		return (CTL_RETVAL_COMPLETE);
4900	}
4901
4902	if (length > 0)
4903		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
4904
4905	mtx_lock(&lun->lun_lock);
4906
4907	/*
4908	 * According to SPC, it is not an error for an intiator to attempt
4909	 * to release a reservation on a LUN that isn't reserved, or that
4910	 * is reserved by another initiator.  The reservation can only be
4911	 * released, though, by the initiator who made it or by one of
4912	 * several reset type events.
4913	 */
4914	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
4915			lun->flags &= ~CTL_LUN_RESERVED;
4916
4917	mtx_unlock(&lun->lun_lock);
4918
4919	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
4920		free(ctsio->kern_data_ptr, M_CTL);
4921		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
4922	}
4923
4924	ctl_set_success(ctsio);
4925	ctl_done((union ctl_io *)ctsio);
4926	return (CTL_RETVAL_COMPLETE);
4927}
4928
4929int
4930ctl_scsi_reserve(struct ctl_scsiio *ctsio)
4931{
4932	int extent, thirdparty, longid;
4933	int resv_id, length;
4934	uint64_t thirdparty_id;
4935	struct ctl_lun *lun;
4936	uint32_t residx;
4937
4938	extent = 0;
4939	thirdparty = 0;
4940	longid = 0;
4941	resv_id = 0;
4942	length = 0;
4943	thirdparty_id = 0;
4944
4945	CTL_DEBUG_PRINT(("ctl_reserve\n"));
4946
4947	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
4948	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
4949
4950	switch (ctsio->cdb[0]) {
4951	case RESERVE_10: {
4952		struct scsi_reserve_10 *cdb;
4953
4954		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
4955
4956		if (cdb->byte2 & SR10_LONGID)
4957			longid = 1;
4958		else
4959			thirdparty_id = cdb->thirdparty_id;
4960
4961		resv_id = cdb->resv_id;
4962		length = scsi_2btoul(cdb->length);
4963		break;
4964	}
4965	}
4966
4967	/*
4968	 * XXX KDM right now, we only support LUN reservation.  We don't
4969	 * support 3rd party reservations, or extent reservations, which
4970	 * might actually need the parameter list.  If we've gotten this
4971	 * far, we've got a LUN reservation.  Anything else got kicked out
4972	 * above.  So, according to SPC, ignore the length.
4973	 */
4974	length = 0;
4975
4976	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
4977	 && (length > 0)) {
4978		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
4979		ctsio->kern_data_len = length;
4980		ctsio->kern_total_len = length;
4981		ctsio->kern_data_resid = 0;
4982		ctsio->kern_rel_offset = 0;
4983		ctsio->kern_sg_entries = 0;
4984		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
4985		ctsio->be_move_done = ctl_config_move_done;
4986		ctl_datamove((union ctl_io *)ctsio);
4987
4988		return (CTL_RETVAL_COMPLETE);
4989	}
4990
4991	if (length > 0)
4992		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
4993
4994	mtx_lock(&lun->lun_lock);
4995	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
4996		ctl_set_reservation_conflict(ctsio);
4997		goto bailout;
4998	}
4999
5000	lun->flags |= CTL_LUN_RESERVED;
5001	lun->res_idx = residx;
5002
5003	ctl_set_success(ctsio);
5004
5005bailout:
5006	mtx_unlock(&lun->lun_lock);
5007
5008	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5009		free(ctsio->kern_data_ptr, M_CTL);
5010		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5011	}
5012
5013	ctl_done((union ctl_io *)ctsio);
5014	return (CTL_RETVAL_COMPLETE);
5015}
5016
5017int
5018ctl_start_stop(struct ctl_scsiio *ctsio)
5019{
5020	struct scsi_start_stop_unit *cdb;
5021	struct ctl_lun *lun;
5022	int retval;
5023
5024	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5025
5026	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5027	retval = 0;
5028
5029	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5030
5031	/*
5032	 * XXX KDM
5033	 * We don't support the immediate bit on a stop unit.  In order to
5034	 * do that, we would need to code up a way to know that a stop is
5035	 * pending, and hold off any new commands until it completes, one
5036	 * way or another.  Then we could accept or reject those commands
5037	 * depending on its status.  We would almost need to do the reverse
5038	 * of what we do below for an immediate start -- return the copy of
5039	 * the ctl_io to the FETD with status to send to the host (and to
5040	 * free the copy!) and then free the original I/O once the stop
5041	 * actually completes.  That way, the OOA queue mechanism can work
5042	 * to block commands that shouldn't proceed.  Another alternative
5043	 * would be to put the copy in the queue in place of the original,
5044	 * and return the original back to the caller.  That could be
5045	 * slightly safer..
5046	 */
5047	if ((cdb->byte2 & SSS_IMMED)
5048	 && ((cdb->how & SSS_START) == 0)) {
5049		ctl_set_invalid_field(ctsio,
5050				      /*sks_valid*/ 1,
5051				      /*command*/ 1,
5052				      /*field*/ 1,
5053				      /*bit_valid*/ 1,
5054				      /*bit*/ 0);
5055		ctl_done((union ctl_io *)ctsio);
5056		return (CTL_RETVAL_COMPLETE);
5057	}
5058
5059	if ((lun->flags & CTL_LUN_PR_RESERVED)
5060	 && ((cdb->how & SSS_START)==0)) {
5061		uint32_t residx;
5062
5063		residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5064		if (ctl_get_prkey(lun, residx) == 0
5065		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5066
5067			ctl_set_reservation_conflict(ctsio);
5068			ctl_done((union ctl_io *)ctsio);
5069			return (CTL_RETVAL_COMPLETE);
5070		}
5071	}
5072
5073	/*
5074	 * If there is no backend on this device, we can't start or stop
5075	 * it.  In theory we shouldn't get any start/stop commands in the
5076	 * first place at this level if the LUN doesn't have a backend.
5077	 * That should get stopped by the command decode code.
5078	 */
5079	if (lun->backend == NULL) {
5080		ctl_set_invalid_opcode(ctsio);
5081		ctl_done((union ctl_io *)ctsio);
5082		return (CTL_RETVAL_COMPLETE);
5083	}
5084
5085	/*
5086	 * XXX KDM Copan-specific offline behavior.
5087	 * Figure out a reasonable way to port this?
5088	 */
5089#ifdef NEEDTOPORT
5090	mtx_lock(&lun->lun_lock);
5091
5092	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5093	 && (lun->flags & CTL_LUN_OFFLINE)) {
5094		/*
5095		 * If the LUN is offline, and the on/offline bit isn't set,
5096		 * reject the start or stop.  Otherwise, let it through.
5097		 */
5098		mtx_unlock(&lun->lun_lock);
5099		ctl_set_lun_not_ready(ctsio);
5100		ctl_done((union ctl_io *)ctsio);
5101	} else {
5102		mtx_unlock(&lun->lun_lock);
5103#endif /* NEEDTOPORT */
5104		/*
5105		 * This could be a start or a stop when we're online,
5106		 * or a stop/offline or start/online.  A start or stop when
5107		 * we're offline is covered in the case above.
5108		 */
5109		/*
5110		 * In the non-immediate case, we send the request to
5111		 * the backend and return status to the user when
5112		 * it is done.
5113		 *
5114		 * In the immediate case, we allocate a new ctl_io
5115		 * to hold a copy of the request, and send that to
5116		 * the backend.  We then set good status on the
5117		 * user's request and return it immediately.
5118		 */
5119		if (cdb->byte2 & SSS_IMMED) {
5120			union ctl_io *new_io;
5121
5122			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5123			ctl_copy_io((union ctl_io *)ctsio, new_io);
5124			retval = lun->backend->config_write(new_io);
5125			ctl_set_success(ctsio);
5126			ctl_done((union ctl_io *)ctsio);
5127		} else {
5128			retval = lun->backend->config_write(
5129				(union ctl_io *)ctsio);
5130		}
5131#ifdef NEEDTOPORT
5132	}
5133#endif
5134	return (retval);
5135}
5136
5137/*
5138 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5139 * we don't really do anything with the LBA and length fields if the user
5140 * passes them in.  Instead we'll just flush out the cache for the entire
5141 * LUN.
5142 */
5143int
5144ctl_sync_cache(struct ctl_scsiio *ctsio)
5145{
5146	struct ctl_lun *lun;
5147	struct ctl_softc *softc;
5148	struct ctl_lba_len_flags *lbalen;
5149	uint64_t starting_lba;
5150	uint32_t block_count;
5151	int retval;
5152	uint8_t byte2;
5153
5154	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5155
5156	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5157	softc = lun->ctl_softc;
5158	retval = 0;
5159
5160	switch (ctsio->cdb[0]) {
5161	case SYNCHRONIZE_CACHE: {
5162		struct scsi_sync_cache *cdb;
5163		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5164
5165		starting_lba = scsi_4btoul(cdb->begin_lba);
5166		block_count = scsi_2btoul(cdb->lb_count);
5167		byte2 = cdb->byte2;
5168		break;
5169	}
5170	case SYNCHRONIZE_CACHE_16: {
5171		struct scsi_sync_cache_16 *cdb;
5172		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5173
5174		starting_lba = scsi_8btou64(cdb->begin_lba);
5175		block_count = scsi_4btoul(cdb->lb_count);
5176		byte2 = cdb->byte2;
5177		break;
5178	}
5179	default:
5180		ctl_set_invalid_opcode(ctsio);
5181		ctl_done((union ctl_io *)ctsio);
5182		goto bailout;
5183		break; /* NOTREACHED */
5184	}
5185
5186	/*
5187	 * We check the LBA and length, but don't do anything with them.
5188	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5189	 * get flushed.  This check will just help satisfy anyone who wants
5190	 * to see an error for an out of range LBA.
5191	 */
5192	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5193		ctl_set_lba_out_of_range(ctsio);
5194		ctl_done((union ctl_io *)ctsio);
5195		goto bailout;
5196	}
5197
5198	/*
5199	 * If this LUN has no backend, we can't flush the cache anyway.
5200	 */
5201	if (lun->backend == NULL) {
5202		ctl_set_invalid_opcode(ctsio);
5203		ctl_done((union ctl_io *)ctsio);
5204		goto bailout;
5205	}
5206
5207	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5208	lbalen->lba = starting_lba;
5209	lbalen->len = block_count;
5210	lbalen->flags = byte2;
5211
5212	/*
5213	 * Check to see whether we're configured to send the SYNCHRONIZE
5214	 * CACHE command directly to the back end.
5215	 */
5216	mtx_lock(&lun->lun_lock);
5217	if ((softc->flags & CTL_FLAG_REAL_SYNC)
5218	 && (++(lun->sync_count) >= lun->sync_interval)) {
5219		lun->sync_count = 0;
5220		mtx_unlock(&lun->lun_lock);
5221		retval = lun->backend->config_write((union ctl_io *)ctsio);
5222	} else {
5223		mtx_unlock(&lun->lun_lock);
5224		ctl_set_success(ctsio);
5225		ctl_done((union ctl_io *)ctsio);
5226	}
5227
5228bailout:
5229
5230	return (retval);
5231}
5232
5233int
5234ctl_format(struct ctl_scsiio *ctsio)
5235{
5236	struct scsi_format *cdb;
5237	struct ctl_lun *lun;
5238	int length, defect_list_len;
5239
5240	CTL_DEBUG_PRINT(("ctl_format\n"));
5241
5242	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5243
5244	cdb = (struct scsi_format *)ctsio->cdb;
5245
5246	length = 0;
5247	if (cdb->byte2 & SF_FMTDATA) {
5248		if (cdb->byte2 & SF_LONGLIST)
5249			length = sizeof(struct scsi_format_header_long);
5250		else
5251			length = sizeof(struct scsi_format_header_short);
5252	}
5253
5254	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5255	 && (length > 0)) {
5256		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5257		ctsio->kern_data_len = length;
5258		ctsio->kern_total_len = length;
5259		ctsio->kern_data_resid = 0;
5260		ctsio->kern_rel_offset = 0;
5261		ctsio->kern_sg_entries = 0;
5262		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5263		ctsio->be_move_done = ctl_config_move_done;
5264		ctl_datamove((union ctl_io *)ctsio);
5265
5266		return (CTL_RETVAL_COMPLETE);
5267	}
5268
5269	defect_list_len = 0;
5270
5271	if (cdb->byte2 & SF_FMTDATA) {
5272		if (cdb->byte2 & SF_LONGLIST) {
5273			struct scsi_format_header_long *header;
5274
5275			header = (struct scsi_format_header_long *)
5276				ctsio->kern_data_ptr;
5277
5278			defect_list_len = scsi_4btoul(header->defect_list_len);
5279			if (defect_list_len != 0) {
5280				ctl_set_invalid_field(ctsio,
5281						      /*sks_valid*/ 1,
5282						      /*command*/ 0,
5283						      /*field*/ 2,
5284						      /*bit_valid*/ 0,
5285						      /*bit*/ 0);
5286				goto bailout;
5287			}
5288		} else {
5289			struct scsi_format_header_short *header;
5290
5291			header = (struct scsi_format_header_short *)
5292				ctsio->kern_data_ptr;
5293
5294			defect_list_len = scsi_2btoul(header->defect_list_len);
5295			if (defect_list_len != 0) {
5296				ctl_set_invalid_field(ctsio,
5297						      /*sks_valid*/ 1,
5298						      /*command*/ 0,
5299						      /*field*/ 2,
5300						      /*bit_valid*/ 0,
5301						      /*bit*/ 0);
5302				goto bailout;
5303			}
5304		}
5305	}
5306
5307	/*
5308	 * The format command will clear out the "Medium format corrupted"
5309	 * status if set by the configuration code.  That status is really
5310	 * just a way to notify the host that we have lost the media, and
5311	 * get them to issue a command that will basically make them think
5312	 * they're blowing away the media.
5313	 */
5314	mtx_lock(&lun->lun_lock);
5315	lun->flags &= ~CTL_LUN_INOPERABLE;
5316	mtx_unlock(&lun->lun_lock);
5317
5318	ctl_set_success(ctsio);
5319bailout:
5320
5321	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5322		free(ctsio->kern_data_ptr, M_CTL);
5323		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5324	}
5325
5326	ctl_done((union ctl_io *)ctsio);
5327	return (CTL_RETVAL_COMPLETE);
5328}
5329
5330int
5331ctl_read_buffer(struct ctl_scsiio *ctsio)
5332{
5333	struct scsi_read_buffer *cdb;
5334	struct ctl_lun *lun;
5335	int buffer_offset, len;
5336	static uint8_t descr[4];
5337	static uint8_t echo_descr[4] = { 0 };
5338
5339	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5340
5341	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5342	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5343
5344	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5345	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5346	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5347		ctl_set_invalid_field(ctsio,
5348				      /*sks_valid*/ 1,
5349				      /*command*/ 1,
5350				      /*field*/ 1,
5351				      /*bit_valid*/ 1,
5352				      /*bit*/ 4);
5353		ctl_done((union ctl_io *)ctsio);
5354		return (CTL_RETVAL_COMPLETE);
5355	}
5356
5357	len = scsi_3btoul(cdb->length);
5358	buffer_offset = scsi_3btoul(cdb->offset);
5359
5360	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5361		ctl_set_invalid_field(ctsio,
5362				      /*sks_valid*/ 1,
5363				      /*command*/ 1,
5364				      /*field*/ 6,
5365				      /*bit_valid*/ 0,
5366				      /*bit*/ 0);
5367		ctl_done((union ctl_io *)ctsio);
5368		return (CTL_RETVAL_COMPLETE);
5369	}
5370
5371	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5372		descr[0] = 0;
5373		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5374		ctsio->kern_data_ptr = descr;
5375		len = min(len, sizeof(descr));
5376	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5377		ctsio->kern_data_ptr = echo_descr;
5378		len = min(len, sizeof(echo_descr));
5379	} else {
5380		if (lun->write_buffer == NULL) {
5381			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5382			    M_CTL, M_WAITOK);
5383		}
5384		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5385	}
5386	ctsio->kern_data_len = len;
5387	ctsio->kern_total_len = len;
5388	ctsio->kern_data_resid = 0;
5389	ctsio->kern_rel_offset = 0;
5390	ctsio->kern_sg_entries = 0;
5391	ctl_set_success(ctsio);
5392	ctsio->be_move_done = ctl_config_move_done;
5393	ctl_datamove((union ctl_io *)ctsio);
5394	return (CTL_RETVAL_COMPLETE);
5395}
5396
5397int
5398ctl_write_buffer(struct ctl_scsiio *ctsio)
5399{
5400	struct scsi_write_buffer *cdb;
5401	struct ctl_lun *lun;
5402	int buffer_offset, len;
5403
5404	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5405
5406	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5407	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5408
5409	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5410		ctl_set_invalid_field(ctsio,
5411				      /*sks_valid*/ 1,
5412				      /*command*/ 1,
5413				      /*field*/ 1,
5414				      /*bit_valid*/ 1,
5415				      /*bit*/ 4);
5416		ctl_done((union ctl_io *)ctsio);
5417		return (CTL_RETVAL_COMPLETE);
5418	}
5419
5420	len = scsi_3btoul(cdb->length);
5421	buffer_offset = scsi_3btoul(cdb->offset);
5422
5423	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5424		ctl_set_invalid_field(ctsio,
5425				      /*sks_valid*/ 1,
5426				      /*command*/ 1,
5427				      /*field*/ 6,
5428				      /*bit_valid*/ 0,
5429				      /*bit*/ 0);
5430		ctl_done((union ctl_io *)ctsio);
5431		return (CTL_RETVAL_COMPLETE);
5432	}
5433
5434	/*
5435	 * If we've got a kernel request that hasn't been malloced yet,
5436	 * malloc it and tell the caller the data buffer is here.
5437	 */
5438	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5439		if (lun->write_buffer == NULL) {
5440			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5441			    M_CTL, M_WAITOK);
5442		}
5443		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5444		ctsio->kern_data_len = len;
5445		ctsio->kern_total_len = len;
5446		ctsio->kern_data_resid = 0;
5447		ctsio->kern_rel_offset = 0;
5448		ctsio->kern_sg_entries = 0;
5449		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5450		ctsio->be_move_done = ctl_config_move_done;
5451		ctl_datamove((union ctl_io *)ctsio);
5452
5453		return (CTL_RETVAL_COMPLETE);
5454	}
5455
5456	ctl_set_success(ctsio);
5457	ctl_done((union ctl_io *)ctsio);
5458	return (CTL_RETVAL_COMPLETE);
5459}
5460
5461int
5462ctl_write_same(struct ctl_scsiio *ctsio)
5463{
5464	struct ctl_lun *lun;
5465	struct ctl_lba_len_flags *lbalen;
5466	uint64_t lba;
5467	uint32_t num_blocks;
5468	int len, retval;
5469	uint8_t byte2;
5470
5471	retval = CTL_RETVAL_COMPLETE;
5472
5473	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5474
5475	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5476
5477	switch (ctsio->cdb[0]) {
5478	case WRITE_SAME_10: {
5479		struct scsi_write_same_10 *cdb;
5480
5481		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5482
5483		lba = scsi_4btoul(cdb->addr);
5484		num_blocks = scsi_2btoul(cdb->length);
5485		byte2 = cdb->byte2;
5486		break;
5487	}
5488	case WRITE_SAME_16: {
5489		struct scsi_write_same_16 *cdb;
5490
5491		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5492
5493		lba = scsi_8btou64(cdb->addr);
5494		num_blocks = scsi_4btoul(cdb->length);
5495		byte2 = cdb->byte2;
5496		break;
5497	}
5498	default:
5499		/*
5500		 * We got a command we don't support.  This shouldn't
5501		 * happen, commands should be filtered out above us.
5502		 */
5503		ctl_set_invalid_opcode(ctsio);
5504		ctl_done((union ctl_io *)ctsio);
5505
5506		return (CTL_RETVAL_COMPLETE);
5507		break; /* NOTREACHED */
5508	}
5509
5510	/* NDOB and ANCHOR flags can be used only together with UNMAP */
5511	if ((byte2 & SWS_UNMAP) == 0 &&
5512	    (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5513		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5514		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5515		ctl_done((union ctl_io *)ctsio);
5516		return (CTL_RETVAL_COMPLETE);
5517	}
5518
5519	/*
5520	 * The first check is to make sure we're in bounds, the second
5521	 * check is to catch wrap-around problems.  If the lba + num blocks
5522	 * is less than the lba, then we've wrapped around and the block
5523	 * range is invalid anyway.
5524	 */
5525	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5526	 || ((lba + num_blocks) < lba)) {
5527		ctl_set_lba_out_of_range(ctsio);
5528		ctl_done((union ctl_io *)ctsio);
5529		return (CTL_RETVAL_COMPLETE);
5530	}
5531
5532	/* Zero number of blocks means "to the last logical block" */
5533	if (num_blocks == 0) {
5534		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5535			ctl_set_invalid_field(ctsio,
5536					      /*sks_valid*/ 0,
5537					      /*command*/ 1,
5538					      /*field*/ 0,
5539					      /*bit_valid*/ 0,
5540					      /*bit*/ 0);
5541			ctl_done((union ctl_io *)ctsio);
5542			return (CTL_RETVAL_COMPLETE);
5543		}
5544		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5545	}
5546
5547	len = lun->be_lun->blocksize;
5548
5549	/*
5550	 * If we've got a kernel request that hasn't been malloced yet,
5551	 * malloc it and tell the caller the data buffer is here.
5552	 */
5553	if ((byte2 & SWS_NDOB) == 0 &&
5554	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5555		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5556		ctsio->kern_data_len = len;
5557		ctsio->kern_total_len = len;
5558		ctsio->kern_data_resid = 0;
5559		ctsio->kern_rel_offset = 0;
5560		ctsio->kern_sg_entries = 0;
5561		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5562		ctsio->be_move_done = ctl_config_move_done;
5563		ctl_datamove((union ctl_io *)ctsio);
5564
5565		return (CTL_RETVAL_COMPLETE);
5566	}
5567
5568	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5569	lbalen->lba = lba;
5570	lbalen->len = num_blocks;
5571	lbalen->flags = byte2;
5572	retval = lun->backend->config_write((union ctl_io *)ctsio);
5573
5574	return (retval);
5575}
5576
5577int
5578ctl_unmap(struct ctl_scsiio *ctsio)
5579{
5580	struct ctl_lun *lun;
5581	struct scsi_unmap *cdb;
5582	struct ctl_ptr_len_flags *ptrlen;
5583	struct scsi_unmap_header *hdr;
5584	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5585	uint64_t lba;
5586	uint32_t num_blocks;
5587	int len, retval;
5588	uint8_t byte2;
5589
5590	retval = CTL_RETVAL_COMPLETE;
5591
5592	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5593
5594	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5595	cdb = (struct scsi_unmap *)ctsio->cdb;
5596
5597	len = scsi_2btoul(cdb->length);
5598	byte2 = cdb->byte2;
5599
5600	/*
5601	 * If we've got a kernel request that hasn't been malloced yet,
5602	 * malloc it and tell the caller the data buffer is here.
5603	 */
5604	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5605		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5606		ctsio->kern_data_len = len;
5607		ctsio->kern_total_len = len;
5608		ctsio->kern_data_resid = 0;
5609		ctsio->kern_rel_offset = 0;
5610		ctsio->kern_sg_entries = 0;
5611		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5612		ctsio->be_move_done = ctl_config_move_done;
5613		ctl_datamove((union ctl_io *)ctsio);
5614
5615		return (CTL_RETVAL_COMPLETE);
5616	}
5617
5618	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5619	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5620	if (len < sizeof (*hdr) ||
5621	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5622	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5623	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5624		ctl_set_invalid_field(ctsio,
5625				      /*sks_valid*/ 0,
5626				      /*command*/ 0,
5627				      /*field*/ 0,
5628				      /*bit_valid*/ 0,
5629				      /*bit*/ 0);
5630		goto done;
5631	}
5632	len = scsi_2btoul(hdr->desc_length);
5633	buf = (struct scsi_unmap_desc *)(hdr + 1);
5634	end = buf + len / sizeof(*buf);
5635
5636	endnz = buf;
5637	for (range = buf; range < end; range++) {
5638		lba = scsi_8btou64(range->lba);
5639		num_blocks = scsi_4btoul(range->length);
5640		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5641		 || ((lba + num_blocks) < lba)) {
5642			ctl_set_lba_out_of_range(ctsio);
5643			ctl_done((union ctl_io *)ctsio);
5644			return (CTL_RETVAL_COMPLETE);
5645		}
5646		if (num_blocks != 0)
5647			endnz = range + 1;
5648	}
5649
5650	/*
5651	 * Block backend can not handle zero last range.
5652	 * Filter it out and return if there is nothing left.
5653	 */
5654	len = (uint8_t *)endnz - (uint8_t *)buf;
5655	if (len == 0) {
5656		ctl_set_success(ctsio);
5657		goto done;
5658	}
5659
5660	mtx_lock(&lun->lun_lock);
5661	ptrlen = (struct ctl_ptr_len_flags *)
5662	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5663	ptrlen->ptr = (void *)buf;
5664	ptrlen->len = len;
5665	ptrlen->flags = byte2;
5666	ctl_check_blocked(lun);
5667	mtx_unlock(&lun->lun_lock);
5668
5669	retval = lun->backend->config_write((union ctl_io *)ctsio);
5670	return (retval);
5671
5672done:
5673	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5674		free(ctsio->kern_data_ptr, M_CTL);
5675		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5676	}
5677	ctl_done((union ctl_io *)ctsio);
5678	return (CTL_RETVAL_COMPLETE);
5679}
5680
5681/*
5682 * Note that this function currently doesn't actually do anything inside
5683 * CTL to enforce things if the DQue bit is turned on.
5684 *
5685 * Also note that this function can't be used in the default case, because
5686 * the DQue bit isn't set in the changeable mask for the control mode page
5687 * anyway.  This is just here as an example for how to implement a page
5688 * handler, and a placeholder in case we want to allow the user to turn
5689 * tagged queueing on and off.
5690 *
5691 * The D_SENSE bit handling is functional, however, and will turn
5692 * descriptor sense on and off for a given LUN.
5693 */
5694int
5695ctl_control_page_handler(struct ctl_scsiio *ctsio,
5696			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5697{
5698	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5699	struct ctl_lun *lun;
5700	int set_ua;
5701	uint32_t initidx;
5702
5703	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5704	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5705	set_ua = 0;
5706
5707	user_cp = (struct scsi_control_page *)page_ptr;
5708	current_cp = (struct scsi_control_page *)
5709		(page_index->page_data + (page_index->page_len *
5710		CTL_PAGE_CURRENT));
5711	saved_cp = (struct scsi_control_page *)
5712		(page_index->page_data + (page_index->page_len *
5713		CTL_PAGE_SAVED));
5714
5715	mtx_lock(&lun->lun_lock);
5716	if (((current_cp->rlec & SCP_DSENSE) == 0)
5717	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
5718		/*
5719		 * Descriptor sense is currently turned off and the user
5720		 * wants to turn it on.
5721		 */
5722		current_cp->rlec |= SCP_DSENSE;
5723		saved_cp->rlec |= SCP_DSENSE;
5724		lun->flags |= CTL_LUN_SENSE_DESC;
5725		set_ua = 1;
5726	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
5727		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
5728		/*
5729		 * Descriptor sense is currently turned on, and the user
5730		 * wants to turn it off.
5731		 */
5732		current_cp->rlec &= ~SCP_DSENSE;
5733		saved_cp->rlec &= ~SCP_DSENSE;
5734		lun->flags &= ~CTL_LUN_SENSE_DESC;
5735		set_ua = 1;
5736	}
5737	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
5738	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
5739		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5740		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5741		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5742		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5743		set_ua = 1;
5744	}
5745	if ((current_cp->eca_and_aen & SCP_SWP) !=
5746	    (user_cp->eca_and_aen & SCP_SWP)) {
5747		current_cp->eca_and_aen &= ~SCP_SWP;
5748		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5749		saved_cp->eca_and_aen &= ~SCP_SWP;
5750		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5751		set_ua = 1;
5752	}
5753	if (set_ua != 0)
5754		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5755	mtx_unlock(&lun->lun_lock);
5756
5757	return (0);
5758}
5759
5760int
5761ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
5762		     struct ctl_page_index *page_index, uint8_t *page_ptr)
5763{
5764	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
5765	struct ctl_lun *lun;
5766	int set_ua;
5767	uint32_t initidx;
5768
5769	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5770	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5771	set_ua = 0;
5772
5773	user_cp = (struct scsi_caching_page *)page_ptr;
5774	current_cp = (struct scsi_caching_page *)
5775		(page_index->page_data + (page_index->page_len *
5776		CTL_PAGE_CURRENT));
5777	saved_cp = (struct scsi_caching_page *)
5778		(page_index->page_data + (page_index->page_len *
5779		CTL_PAGE_SAVED));
5780
5781	mtx_lock(&lun->lun_lock);
5782	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
5783	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
5784		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5785		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5786		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5787		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5788		set_ua = 1;
5789	}
5790	if (set_ua != 0)
5791		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5792	mtx_unlock(&lun->lun_lock);
5793
5794	return (0);
5795}
5796
5797int
5798ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
5799				struct ctl_page_index *page_index,
5800				uint8_t *page_ptr)
5801{
5802	uint8_t *c;
5803	int i;
5804
5805	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
5806	ctl_time_io_secs =
5807		(c[0] << 8) |
5808		(c[1] << 0) |
5809		0;
5810	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
5811	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
5812	printf("page data:");
5813	for (i=0; i<8; i++)
5814		printf(" %.2x",page_ptr[i]);
5815	printf("\n");
5816	return (0);
5817}
5818
5819int
5820ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
5821			       struct ctl_page_index *page_index,
5822			       int pc)
5823{
5824	struct copan_debugconf_subpage *page;
5825
5826	page = (struct copan_debugconf_subpage *)page_index->page_data +
5827		(page_index->page_len * pc);
5828
5829	switch (pc) {
5830	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
5831	case SMS_PAGE_CTRL_DEFAULT >> 6:
5832	case SMS_PAGE_CTRL_SAVED >> 6:
5833		/*
5834		 * We don't update the changable or default bits for this page.
5835		 */
5836		break;
5837	case SMS_PAGE_CTRL_CURRENT >> 6:
5838		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
5839		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
5840		break;
5841	default:
5842#ifdef NEEDTOPORT
5843		EPRINT(0, "Invalid PC %d!!", pc);
5844#endif /* NEEDTOPORT */
5845		break;
5846	}
5847	return (0);
5848}
5849
5850
5851static int
5852ctl_do_mode_select(union ctl_io *io)
5853{
5854	struct scsi_mode_page_header *page_header;
5855	struct ctl_page_index *page_index;
5856	struct ctl_scsiio *ctsio;
5857	int control_dev, page_len;
5858	int page_len_offset, page_len_size;
5859	union ctl_modepage_info *modepage_info;
5860	struct ctl_lun *lun;
5861	int *len_left, *len_used;
5862	int retval, i;
5863
5864	ctsio = &io->scsiio;
5865	page_index = NULL;
5866	page_len = 0;
5867	retval = CTL_RETVAL_COMPLETE;
5868
5869	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5870
5871	if (lun->be_lun->lun_type != T_DIRECT)
5872		control_dev = 1;
5873	else
5874		control_dev = 0;
5875
5876	modepage_info = (union ctl_modepage_info *)
5877		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5878	len_left = &modepage_info->header.len_left;
5879	len_used = &modepage_info->header.len_used;
5880
5881do_next_page:
5882
5883	page_header = (struct scsi_mode_page_header *)
5884		(ctsio->kern_data_ptr + *len_used);
5885
5886	if (*len_left == 0) {
5887		free(ctsio->kern_data_ptr, M_CTL);
5888		ctl_set_success(ctsio);
5889		ctl_done((union ctl_io *)ctsio);
5890		return (CTL_RETVAL_COMPLETE);
5891	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
5892
5893		free(ctsio->kern_data_ptr, M_CTL);
5894		ctl_set_param_len_error(ctsio);
5895		ctl_done((union ctl_io *)ctsio);
5896		return (CTL_RETVAL_COMPLETE);
5897
5898	} else if ((page_header->page_code & SMPH_SPF)
5899		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
5900
5901		free(ctsio->kern_data_ptr, M_CTL);
5902		ctl_set_param_len_error(ctsio);
5903		ctl_done((union ctl_io *)ctsio);
5904		return (CTL_RETVAL_COMPLETE);
5905	}
5906
5907
5908	/*
5909	 * XXX KDM should we do something with the block descriptor?
5910	 */
5911	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5912
5913		if ((control_dev != 0)
5914		 && (lun->mode_pages.index[i].page_flags &
5915		     CTL_PAGE_FLAG_DISK_ONLY))
5916			continue;
5917
5918		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
5919		    (page_header->page_code & SMPH_PC_MASK))
5920			continue;
5921
5922		/*
5923		 * If neither page has a subpage code, then we've got a
5924		 * match.
5925		 */
5926		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
5927		 && ((page_header->page_code & SMPH_SPF) == 0)) {
5928			page_index = &lun->mode_pages.index[i];
5929			page_len = page_header->page_length;
5930			break;
5931		}
5932
5933		/*
5934		 * If both pages have subpages, then the subpage numbers
5935		 * have to match.
5936		 */
5937		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
5938		  && (page_header->page_code & SMPH_SPF)) {
5939			struct scsi_mode_page_header_sp *sph;
5940
5941			sph = (struct scsi_mode_page_header_sp *)page_header;
5942
5943			if (lun->mode_pages.index[i].subpage ==
5944			    sph->subpage) {
5945				page_index = &lun->mode_pages.index[i];
5946				page_len = scsi_2btoul(sph->page_length);
5947				break;
5948			}
5949		}
5950	}
5951
5952	/*
5953	 * If we couldn't find the page, or if we don't have a mode select
5954	 * handler for it, send back an error to the user.
5955	 */
5956	if ((page_index == NULL)
5957	 || (page_index->select_handler == NULL)) {
5958		ctl_set_invalid_field(ctsio,
5959				      /*sks_valid*/ 1,
5960				      /*command*/ 0,
5961				      /*field*/ *len_used,
5962				      /*bit_valid*/ 0,
5963				      /*bit*/ 0);
5964		free(ctsio->kern_data_ptr, M_CTL);
5965		ctl_done((union ctl_io *)ctsio);
5966		return (CTL_RETVAL_COMPLETE);
5967	}
5968
5969	if (page_index->page_code & SMPH_SPF) {
5970		page_len_offset = 2;
5971		page_len_size = 2;
5972	} else {
5973		page_len_size = 1;
5974		page_len_offset = 1;
5975	}
5976
5977	/*
5978	 * If the length the initiator gives us isn't the one we specify in
5979	 * the mode page header, or if they didn't specify enough data in
5980	 * the CDB to avoid truncating this page, kick out the request.
5981	 */
5982	if ((page_len != (page_index->page_len - page_len_offset -
5983			  page_len_size))
5984	 || (*len_left < page_index->page_len)) {
5985
5986
5987		ctl_set_invalid_field(ctsio,
5988				      /*sks_valid*/ 1,
5989				      /*command*/ 0,
5990				      /*field*/ *len_used + page_len_offset,
5991				      /*bit_valid*/ 0,
5992				      /*bit*/ 0);
5993		free(ctsio->kern_data_ptr, M_CTL);
5994		ctl_done((union ctl_io *)ctsio);
5995		return (CTL_RETVAL_COMPLETE);
5996	}
5997
5998	/*
5999	 * Run through the mode page, checking to make sure that the bits
6000	 * the user changed are actually legal for him to change.
6001	 */
6002	for (i = 0; i < page_index->page_len; i++) {
6003		uint8_t *user_byte, *change_mask, *current_byte;
6004		int bad_bit;
6005		int j;
6006
6007		user_byte = (uint8_t *)page_header + i;
6008		change_mask = page_index->page_data +
6009			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6010		current_byte = page_index->page_data +
6011			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6012
6013		/*
6014		 * Check to see whether the user set any bits in this byte
6015		 * that he is not allowed to set.
6016		 */
6017		if ((*user_byte & ~(*change_mask)) ==
6018		    (*current_byte & ~(*change_mask)))
6019			continue;
6020
6021		/*
6022		 * Go through bit by bit to determine which one is illegal.
6023		 */
6024		bad_bit = 0;
6025		for (j = 7; j >= 0; j--) {
6026			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6027			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6028				bad_bit = i;
6029				break;
6030			}
6031		}
6032		ctl_set_invalid_field(ctsio,
6033				      /*sks_valid*/ 1,
6034				      /*command*/ 0,
6035				      /*field*/ *len_used + i,
6036				      /*bit_valid*/ 1,
6037				      /*bit*/ bad_bit);
6038		free(ctsio->kern_data_ptr, M_CTL);
6039		ctl_done((union ctl_io *)ctsio);
6040		return (CTL_RETVAL_COMPLETE);
6041	}
6042
6043	/*
6044	 * Decrement these before we call the page handler, since we may
6045	 * end up getting called back one way or another before the handler
6046	 * returns to this context.
6047	 */
6048	*len_left -= page_index->page_len;
6049	*len_used += page_index->page_len;
6050
6051	retval = page_index->select_handler(ctsio, page_index,
6052					    (uint8_t *)page_header);
6053
6054	/*
6055	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6056	 * wait until this queued command completes to finish processing
6057	 * the mode page.  If it returns anything other than
6058	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6059	 * already set the sense information, freed the data pointer, and
6060	 * completed the io for us.
6061	 */
6062	if (retval != CTL_RETVAL_COMPLETE)
6063		goto bailout_no_done;
6064
6065	/*
6066	 * If the initiator sent us more than one page, parse the next one.
6067	 */
6068	if (*len_left > 0)
6069		goto do_next_page;
6070
6071	ctl_set_success(ctsio);
6072	free(ctsio->kern_data_ptr, M_CTL);
6073	ctl_done((union ctl_io *)ctsio);
6074
6075bailout_no_done:
6076
6077	return (CTL_RETVAL_COMPLETE);
6078
6079}
6080
6081int
6082ctl_mode_select(struct ctl_scsiio *ctsio)
6083{
6084	int param_len, pf, sp;
6085	int header_size, bd_len;
6086	int len_left, len_used;
6087	struct ctl_page_index *page_index;
6088	struct ctl_lun *lun;
6089	int control_dev, page_len;
6090	union ctl_modepage_info *modepage_info;
6091	int retval;
6092
6093	pf = 0;
6094	sp = 0;
6095	page_len = 0;
6096	len_used = 0;
6097	len_left = 0;
6098	retval = 0;
6099	bd_len = 0;
6100	page_index = NULL;
6101
6102	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6103
6104	if (lun->be_lun->lun_type != T_DIRECT)
6105		control_dev = 1;
6106	else
6107		control_dev = 0;
6108
6109	switch (ctsio->cdb[0]) {
6110	case MODE_SELECT_6: {
6111		struct scsi_mode_select_6 *cdb;
6112
6113		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6114
6115		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6116		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6117
6118		param_len = cdb->length;
6119		header_size = sizeof(struct scsi_mode_header_6);
6120		break;
6121	}
6122	case MODE_SELECT_10: {
6123		struct scsi_mode_select_10 *cdb;
6124
6125		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6126
6127		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6128		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6129
6130		param_len = scsi_2btoul(cdb->length);
6131		header_size = sizeof(struct scsi_mode_header_10);
6132		break;
6133	}
6134	default:
6135		ctl_set_invalid_opcode(ctsio);
6136		ctl_done((union ctl_io *)ctsio);
6137		return (CTL_RETVAL_COMPLETE);
6138		break; /* NOTREACHED */
6139	}
6140
6141	/*
6142	 * From SPC-3:
6143	 * "A parameter list length of zero indicates that the Data-Out Buffer
6144	 * shall be empty. This condition shall not be considered as an error."
6145	 */
6146	if (param_len == 0) {
6147		ctl_set_success(ctsio);
6148		ctl_done((union ctl_io *)ctsio);
6149		return (CTL_RETVAL_COMPLETE);
6150	}
6151
6152	/*
6153	 * Since we'll hit this the first time through, prior to
6154	 * allocation, we don't need to free a data buffer here.
6155	 */
6156	if (param_len < header_size) {
6157		ctl_set_param_len_error(ctsio);
6158		ctl_done((union ctl_io *)ctsio);
6159		return (CTL_RETVAL_COMPLETE);
6160	}
6161
6162	/*
6163	 * Allocate the data buffer and grab the user's data.  In theory,
6164	 * we shouldn't have to sanity check the parameter list length here
6165	 * because the maximum size is 64K.  We should be able to malloc
6166	 * that much without too many problems.
6167	 */
6168	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6169		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6170		ctsio->kern_data_len = param_len;
6171		ctsio->kern_total_len = param_len;
6172		ctsio->kern_data_resid = 0;
6173		ctsio->kern_rel_offset = 0;
6174		ctsio->kern_sg_entries = 0;
6175		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6176		ctsio->be_move_done = ctl_config_move_done;
6177		ctl_datamove((union ctl_io *)ctsio);
6178
6179		return (CTL_RETVAL_COMPLETE);
6180	}
6181
6182	switch (ctsio->cdb[0]) {
6183	case MODE_SELECT_6: {
6184		struct scsi_mode_header_6 *mh6;
6185
6186		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6187		bd_len = mh6->blk_desc_len;
6188		break;
6189	}
6190	case MODE_SELECT_10: {
6191		struct scsi_mode_header_10 *mh10;
6192
6193		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6194		bd_len = scsi_2btoul(mh10->blk_desc_len);
6195		break;
6196	}
6197	default:
6198		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6199		break;
6200	}
6201
6202	if (param_len < (header_size + bd_len)) {
6203		free(ctsio->kern_data_ptr, M_CTL);
6204		ctl_set_param_len_error(ctsio);
6205		ctl_done((union ctl_io *)ctsio);
6206		return (CTL_RETVAL_COMPLETE);
6207	}
6208
6209	/*
6210	 * Set the IO_CONT flag, so that if this I/O gets passed to
6211	 * ctl_config_write_done(), it'll get passed back to
6212	 * ctl_do_mode_select() for further processing, or completion if
6213	 * we're all done.
6214	 */
6215	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6216	ctsio->io_cont = ctl_do_mode_select;
6217
6218	modepage_info = (union ctl_modepage_info *)
6219		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6220
6221	memset(modepage_info, 0, sizeof(*modepage_info));
6222
6223	len_left = param_len - header_size - bd_len;
6224	len_used = header_size + bd_len;
6225
6226	modepage_info->header.len_left = len_left;
6227	modepage_info->header.len_used = len_used;
6228
6229	return (ctl_do_mode_select((union ctl_io *)ctsio));
6230}
6231
6232int
6233ctl_mode_sense(struct ctl_scsiio *ctsio)
6234{
6235	struct ctl_lun *lun;
6236	int pc, page_code, dbd, llba, subpage;
6237	int alloc_len, page_len, header_len, total_len;
6238	struct scsi_mode_block_descr *block_desc;
6239	struct ctl_page_index *page_index;
6240	int control_dev;
6241
6242	dbd = 0;
6243	llba = 0;
6244	block_desc = NULL;
6245	page_index = NULL;
6246
6247	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6248
6249	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6250
6251	if (lun->be_lun->lun_type != T_DIRECT)
6252		control_dev = 1;
6253	else
6254		control_dev = 0;
6255
6256	switch (ctsio->cdb[0]) {
6257	case MODE_SENSE_6: {
6258		struct scsi_mode_sense_6 *cdb;
6259
6260		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6261
6262		header_len = sizeof(struct scsi_mode_hdr_6);
6263		if (cdb->byte2 & SMS_DBD)
6264			dbd = 1;
6265		else
6266			header_len += sizeof(struct scsi_mode_block_descr);
6267
6268		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6269		page_code = cdb->page & SMS_PAGE_CODE;
6270		subpage = cdb->subpage;
6271		alloc_len = cdb->length;
6272		break;
6273	}
6274	case MODE_SENSE_10: {
6275		struct scsi_mode_sense_10 *cdb;
6276
6277		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6278
6279		header_len = sizeof(struct scsi_mode_hdr_10);
6280
6281		if (cdb->byte2 & SMS_DBD)
6282			dbd = 1;
6283		else
6284			header_len += sizeof(struct scsi_mode_block_descr);
6285		if (cdb->byte2 & SMS10_LLBAA)
6286			llba = 1;
6287		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6288		page_code = cdb->page & SMS_PAGE_CODE;
6289		subpage = cdb->subpage;
6290		alloc_len = scsi_2btoul(cdb->length);
6291		break;
6292	}
6293	default:
6294		ctl_set_invalid_opcode(ctsio);
6295		ctl_done((union ctl_io *)ctsio);
6296		return (CTL_RETVAL_COMPLETE);
6297		break; /* NOTREACHED */
6298	}
6299
6300	/*
6301	 * We have to make a first pass through to calculate the size of
6302	 * the pages that match the user's query.  Then we allocate enough
6303	 * memory to hold it, and actually copy the data into the buffer.
6304	 */
6305	switch (page_code) {
6306	case SMS_ALL_PAGES_PAGE: {
6307		int i;
6308
6309		page_len = 0;
6310
6311		/*
6312		 * At the moment, values other than 0 and 0xff here are
6313		 * reserved according to SPC-3.
6314		 */
6315		if ((subpage != SMS_SUBPAGE_PAGE_0)
6316		 && (subpage != SMS_SUBPAGE_ALL)) {
6317			ctl_set_invalid_field(ctsio,
6318					      /*sks_valid*/ 1,
6319					      /*command*/ 1,
6320					      /*field*/ 3,
6321					      /*bit_valid*/ 0,
6322					      /*bit*/ 0);
6323			ctl_done((union ctl_io *)ctsio);
6324			return (CTL_RETVAL_COMPLETE);
6325		}
6326
6327		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6328			if ((control_dev != 0)
6329			 && (lun->mode_pages.index[i].page_flags &
6330			     CTL_PAGE_FLAG_DISK_ONLY))
6331				continue;
6332
6333			/*
6334			 * We don't use this subpage if the user didn't
6335			 * request all subpages.
6336			 */
6337			if ((lun->mode_pages.index[i].subpage != 0)
6338			 && (subpage == SMS_SUBPAGE_PAGE_0))
6339				continue;
6340
6341#if 0
6342			printf("found page %#x len %d\n",
6343			       lun->mode_pages.index[i].page_code &
6344			       SMPH_PC_MASK,
6345			       lun->mode_pages.index[i].page_len);
6346#endif
6347			page_len += lun->mode_pages.index[i].page_len;
6348		}
6349		break;
6350	}
6351	default: {
6352		int i;
6353
6354		page_len = 0;
6355
6356		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6357			/* Look for the right page code */
6358			if ((lun->mode_pages.index[i].page_code &
6359			     SMPH_PC_MASK) != page_code)
6360				continue;
6361
6362			/* Look for the right subpage or the subpage wildcard*/
6363			if ((lun->mode_pages.index[i].subpage != subpage)
6364			 && (subpage != SMS_SUBPAGE_ALL))
6365				continue;
6366
6367			/* Make sure the page is supported for this dev type */
6368			if ((control_dev != 0)
6369			 && (lun->mode_pages.index[i].page_flags &
6370			     CTL_PAGE_FLAG_DISK_ONLY))
6371				continue;
6372
6373#if 0
6374			printf("found page %#x len %d\n",
6375			       lun->mode_pages.index[i].page_code &
6376			       SMPH_PC_MASK,
6377			       lun->mode_pages.index[i].page_len);
6378#endif
6379
6380			page_len += lun->mode_pages.index[i].page_len;
6381		}
6382
6383		if (page_len == 0) {
6384			ctl_set_invalid_field(ctsio,
6385					      /*sks_valid*/ 1,
6386					      /*command*/ 1,
6387					      /*field*/ 2,
6388					      /*bit_valid*/ 1,
6389					      /*bit*/ 5);
6390			ctl_done((union ctl_io *)ctsio);
6391			return (CTL_RETVAL_COMPLETE);
6392		}
6393		break;
6394	}
6395	}
6396
6397	total_len = header_len + page_len;
6398#if 0
6399	printf("header_len = %d, page_len = %d, total_len = %d\n",
6400	       header_len, page_len, total_len);
6401#endif
6402
6403	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6404	ctsio->kern_sg_entries = 0;
6405	ctsio->kern_data_resid = 0;
6406	ctsio->kern_rel_offset = 0;
6407	if (total_len < alloc_len) {
6408		ctsio->residual = alloc_len - total_len;
6409		ctsio->kern_data_len = total_len;
6410		ctsio->kern_total_len = total_len;
6411	} else {
6412		ctsio->residual = 0;
6413		ctsio->kern_data_len = alloc_len;
6414		ctsio->kern_total_len = alloc_len;
6415	}
6416
6417	switch (ctsio->cdb[0]) {
6418	case MODE_SENSE_6: {
6419		struct scsi_mode_hdr_6 *header;
6420
6421		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6422
6423		header->datalen = MIN(total_len - 1, 254);
6424		if (control_dev == 0) {
6425			header->dev_specific = 0x10; /* DPOFUA */
6426			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6427			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6428			    .eca_and_aen & SCP_SWP) != 0)
6429				    header->dev_specific |= 0x80; /* WP */
6430		}
6431		if (dbd)
6432			header->block_descr_len = 0;
6433		else
6434			header->block_descr_len =
6435				sizeof(struct scsi_mode_block_descr);
6436		block_desc = (struct scsi_mode_block_descr *)&header[1];
6437		break;
6438	}
6439	case MODE_SENSE_10: {
6440		struct scsi_mode_hdr_10 *header;
6441		int datalen;
6442
6443		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6444
6445		datalen = MIN(total_len - 2, 65533);
6446		scsi_ulto2b(datalen, header->datalen);
6447		if (control_dev == 0) {
6448			header->dev_specific = 0x10; /* DPOFUA */
6449			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6450			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6451			    .eca_and_aen & SCP_SWP) != 0)
6452				    header->dev_specific |= 0x80; /* WP */
6453		}
6454		if (dbd)
6455			scsi_ulto2b(0, header->block_descr_len);
6456		else
6457			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6458				    header->block_descr_len);
6459		block_desc = (struct scsi_mode_block_descr *)&header[1];
6460		break;
6461	}
6462	default:
6463		panic("invalid CDB type %#x", ctsio->cdb[0]);
6464		break; /* NOTREACHED */
6465	}
6466
6467	/*
6468	 * If we've got a disk, use its blocksize in the block
6469	 * descriptor.  Otherwise, just set it to 0.
6470	 */
6471	if (dbd == 0) {
6472		if (control_dev == 0)
6473			scsi_ulto3b(lun->be_lun->blocksize,
6474				    block_desc->block_len);
6475		else
6476			scsi_ulto3b(0, block_desc->block_len);
6477	}
6478
6479	switch (page_code) {
6480	case SMS_ALL_PAGES_PAGE: {
6481		int i, data_used;
6482
6483		data_used = header_len;
6484		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6485			struct ctl_page_index *page_index;
6486
6487			page_index = &lun->mode_pages.index[i];
6488
6489			if ((control_dev != 0)
6490			 && (page_index->page_flags &
6491			    CTL_PAGE_FLAG_DISK_ONLY))
6492				continue;
6493
6494			/*
6495			 * We don't use this subpage if the user didn't
6496			 * request all subpages.  We already checked (above)
6497			 * to make sure the user only specified a subpage
6498			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6499			 */
6500			if ((page_index->subpage != 0)
6501			 && (subpage == SMS_SUBPAGE_PAGE_0))
6502				continue;
6503
6504			/*
6505			 * Call the handler, if it exists, to update the
6506			 * page to the latest values.
6507			 */
6508			if (page_index->sense_handler != NULL)
6509				page_index->sense_handler(ctsio, page_index,pc);
6510
6511			memcpy(ctsio->kern_data_ptr + data_used,
6512			       page_index->page_data +
6513			       (page_index->page_len * pc),
6514			       page_index->page_len);
6515			data_used += page_index->page_len;
6516		}
6517		break;
6518	}
6519	default: {
6520		int i, data_used;
6521
6522		data_used = header_len;
6523
6524		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6525			struct ctl_page_index *page_index;
6526
6527			page_index = &lun->mode_pages.index[i];
6528
6529			/* Look for the right page code */
6530			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6531				continue;
6532
6533			/* Look for the right subpage or the subpage wildcard*/
6534			if ((page_index->subpage != subpage)
6535			 && (subpage != SMS_SUBPAGE_ALL))
6536				continue;
6537
6538			/* Make sure the page is supported for this dev type */
6539			if ((control_dev != 0)
6540			 && (page_index->page_flags &
6541			     CTL_PAGE_FLAG_DISK_ONLY))
6542				continue;
6543
6544			/*
6545			 * Call the handler, if it exists, to update the
6546			 * page to the latest values.
6547			 */
6548			if (page_index->sense_handler != NULL)
6549				page_index->sense_handler(ctsio, page_index,pc);
6550
6551			memcpy(ctsio->kern_data_ptr + data_used,
6552			       page_index->page_data +
6553			       (page_index->page_len * pc),
6554			       page_index->page_len);
6555			data_used += page_index->page_len;
6556		}
6557		break;
6558	}
6559	}
6560
6561	ctl_set_success(ctsio);
6562	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6563	ctsio->be_move_done = ctl_config_move_done;
6564	ctl_datamove((union ctl_io *)ctsio);
6565	return (CTL_RETVAL_COMPLETE);
6566}
6567
6568int
6569ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6570			       struct ctl_page_index *page_index,
6571			       int pc)
6572{
6573	struct ctl_lun *lun;
6574	struct scsi_log_param_header *phdr;
6575	uint8_t *data;
6576	uint64_t val;
6577
6578	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6579	data = page_index->page_data;
6580
6581	if (lun->backend->lun_attr != NULL &&
6582	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6583	     != UINT64_MAX) {
6584		phdr = (struct scsi_log_param_header *)data;
6585		scsi_ulto2b(0x0001, phdr->param_code);
6586		phdr->param_control = SLP_LBIN | SLP_LP;
6587		phdr->param_len = 8;
6588		data = (uint8_t *)(phdr + 1);
6589		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6590		data[4] = 0x02; /* per-pool */
6591		data += phdr->param_len;
6592	}
6593
6594	if (lun->backend->lun_attr != NULL &&
6595	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6596	     != UINT64_MAX) {
6597		phdr = (struct scsi_log_param_header *)data;
6598		scsi_ulto2b(0x0002, phdr->param_code);
6599		phdr->param_control = SLP_LBIN | SLP_LP;
6600		phdr->param_len = 8;
6601		data = (uint8_t *)(phdr + 1);
6602		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6603		data[4] = 0x01; /* per-LUN */
6604		data += phdr->param_len;
6605	}
6606
6607	if (lun->backend->lun_attr != NULL &&
6608	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6609	     != UINT64_MAX) {
6610		phdr = (struct scsi_log_param_header *)data;
6611		scsi_ulto2b(0x00f1, phdr->param_code);
6612		phdr->param_control = SLP_LBIN | SLP_LP;
6613		phdr->param_len = 8;
6614		data = (uint8_t *)(phdr + 1);
6615		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6616		data[4] = 0x02; /* per-pool */
6617		data += phdr->param_len;
6618	}
6619
6620	if (lun->backend->lun_attr != NULL &&
6621	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6622	     != UINT64_MAX) {
6623		phdr = (struct scsi_log_param_header *)data;
6624		scsi_ulto2b(0x00f2, phdr->param_code);
6625		phdr->param_control = SLP_LBIN | SLP_LP;
6626		phdr->param_len = 8;
6627		data = (uint8_t *)(phdr + 1);
6628		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6629		data[4] = 0x02; /* per-pool */
6630		data += phdr->param_len;
6631	}
6632
6633	page_index->page_len = data - page_index->page_data;
6634	return (0);
6635}
6636
6637int
6638ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6639			       struct ctl_page_index *page_index,
6640			       int pc)
6641{
6642	struct ctl_lun *lun;
6643	struct stat_page *data;
6644	uint64_t rn, wn, rb, wb;
6645	struct bintime rt, wt;
6646	int i;
6647
6648	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6649	data = (struct stat_page *)page_index->page_data;
6650
6651	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6652	data->sap.hdr.param_control = SLP_LBIN;
6653	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6654	    sizeof(struct scsi_log_param_header);
6655	rn = wn = rb = wb = 0;
6656	bintime_clear(&rt);
6657	bintime_clear(&wt);
6658	for (i = 0; i < CTL_MAX_PORTS; i++) {
6659		rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6660		wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6661		rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6662		wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6663		bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6664		bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6665	}
6666	scsi_u64to8b(rn, data->sap.read_num);
6667	scsi_u64to8b(wn, data->sap.write_num);
6668	if (lun->stats.blocksize > 0) {
6669		scsi_u64to8b(wb / lun->stats.blocksize,
6670		    data->sap.recvieved_lba);
6671		scsi_u64to8b(rb / lun->stats.blocksize,
6672		    data->sap.transmitted_lba);
6673	}
6674	scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6675	    data->sap.read_int);
6676	scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6677	    data->sap.write_int);
6678	scsi_u64to8b(0, data->sap.weighted_num);
6679	scsi_u64to8b(0, data->sap.weighted_int);
6680	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6681	data->it.hdr.param_control = SLP_LBIN;
6682	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6683	    sizeof(struct scsi_log_param_header);
6684#ifdef CTL_TIME_IO
6685	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6686#endif
6687	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6688	data->it.hdr.param_control = SLP_LBIN;
6689	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6690	    sizeof(struct scsi_log_param_header);
6691	scsi_ulto4b(3, data->ti.exponent);
6692	scsi_ulto4b(1, data->ti.integer);
6693
6694	page_index->page_len = sizeof(*data);
6695	return (0);
6696}
6697
6698int
6699ctl_log_sense(struct ctl_scsiio *ctsio)
6700{
6701	struct ctl_lun *lun;
6702	int i, pc, page_code, subpage;
6703	int alloc_len, total_len;
6704	struct ctl_page_index *page_index;
6705	struct scsi_log_sense *cdb;
6706	struct scsi_log_header *header;
6707
6708	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6709
6710	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6711	cdb = (struct scsi_log_sense *)ctsio->cdb;
6712	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6713	page_code = cdb->page & SLS_PAGE_CODE;
6714	subpage = cdb->subpage;
6715	alloc_len = scsi_2btoul(cdb->length);
6716
6717	page_index = NULL;
6718	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6719		page_index = &lun->log_pages.index[i];
6720
6721		/* Look for the right page code */
6722		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6723			continue;
6724
6725		/* Look for the right subpage or the subpage wildcard*/
6726		if (page_index->subpage != subpage)
6727			continue;
6728
6729		break;
6730	}
6731	if (i >= CTL_NUM_LOG_PAGES) {
6732		ctl_set_invalid_field(ctsio,
6733				      /*sks_valid*/ 1,
6734				      /*command*/ 1,
6735				      /*field*/ 2,
6736				      /*bit_valid*/ 0,
6737				      /*bit*/ 0);
6738		ctl_done((union ctl_io *)ctsio);
6739		return (CTL_RETVAL_COMPLETE);
6740	}
6741
6742	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6743
6744	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6745	ctsio->kern_sg_entries = 0;
6746	ctsio->kern_data_resid = 0;
6747	ctsio->kern_rel_offset = 0;
6748	if (total_len < alloc_len) {
6749		ctsio->residual = alloc_len - total_len;
6750		ctsio->kern_data_len = total_len;
6751		ctsio->kern_total_len = total_len;
6752	} else {
6753		ctsio->residual = 0;
6754		ctsio->kern_data_len = alloc_len;
6755		ctsio->kern_total_len = alloc_len;
6756	}
6757
6758	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6759	header->page = page_index->page_code;
6760	if (page_index->subpage) {
6761		header->page |= SL_SPF;
6762		header->subpage = page_index->subpage;
6763	}
6764	scsi_ulto2b(page_index->page_len, header->datalen);
6765
6766	/*
6767	 * Call the handler, if it exists, to update the
6768	 * page to the latest values.
6769	 */
6770	if (page_index->sense_handler != NULL)
6771		page_index->sense_handler(ctsio, page_index, pc);
6772
6773	memcpy(header + 1, page_index->page_data, page_index->page_len);
6774
6775	ctl_set_success(ctsio);
6776	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6777	ctsio->be_move_done = ctl_config_move_done;
6778	ctl_datamove((union ctl_io *)ctsio);
6779	return (CTL_RETVAL_COMPLETE);
6780}
6781
6782int
6783ctl_read_capacity(struct ctl_scsiio *ctsio)
6784{
6785	struct scsi_read_capacity *cdb;
6786	struct scsi_read_capacity_data *data;
6787	struct ctl_lun *lun;
6788	uint32_t lba;
6789
6790	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6791
6792	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6793
6794	lba = scsi_4btoul(cdb->addr);
6795	if (((cdb->pmi & SRC_PMI) == 0)
6796	 && (lba != 0)) {
6797		ctl_set_invalid_field(/*ctsio*/ ctsio,
6798				      /*sks_valid*/ 1,
6799				      /*command*/ 1,
6800				      /*field*/ 2,
6801				      /*bit_valid*/ 0,
6802				      /*bit*/ 0);
6803		ctl_done((union ctl_io *)ctsio);
6804		return (CTL_RETVAL_COMPLETE);
6805	}
6806
6807	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6808
6809	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6810	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6811	ctsio->residual = 0;
6812	ctsio->kern_data_len = sizeof(*data);
6813	ctsio->kern_total_len = sizeof(*data);
6814	ctsio->kern_data_resid = 0;
6815	ctsio->kern_rel_offset = 0;
6816	ctsio->kern_sg_entries = 0;
6817
6818	/*
6819	 * If the maximum LBA is greater than 0xfffffffe, the user must
6820	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6821	 * serivce action set.
6822	 */
6823	if (lun->be_lun->maxlba > 0xfffffffe)
6824		scsi_ulto4b(0xffffffff, data->addr);
6825	else
6826		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6827
6828	/*
6829	 * XXX KDM this may not be 512 bytes...
6830	 */
6831	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6832
6833	ctl_set_success(ctsio);
6834	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6835	ctsio->be_move_done = ctl_config_move_done;
6836	ctl_datamove((union ctl_io *)ctsio);
6837	return (CTL_RETVAL_COMPLETE);
6838}
6839
6840int
6841ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6842{
6843	struct scsi_read_capacity_16 *cdb;
6844	struct scsi_read_capacity_data_long *data;
6845	struct ctl_lun *lun;
6846	uint64_t lba;
6847	uint32_t alloc_len;
6848
6849	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6850
6851	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6852
6853	alloc_len = scsi_4btoul(cdb->alloc_len);
6854	lba = scsi_8btou64(cdb->addr);
6855
6856	if ((cdb->reladr & SRC16_PMI)
6857	 && (lba != 0)) {
6858		ctl_set_invalid_field(/*ctsio*/ ctsio,
6859				      /*sks_valid*/ 1,
6860				      /*command*/ 1,
6861				      /*field*/ 2,
6862				      /*bit_valid*/ 0,
6863				      /*bit*/ 0);
6864		ctl_done((union ctl_io *)ctsio);
6865		return (CTL_RETVAL_COMPLETE);
6866	}
6867
6868	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6869
6870	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6871	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6872
6873	if (sizeof(*data) < alloc_len) {
6874		ctsio->residual = alloc_len - sizeof(*data);
6875		ctsio->kern_data_len = sizeof(*data);
6876		ctsio->kern_total_len = sizeof(*data);
6877	} else {
6878		ctsio->residual = 0;
6879		ctsio->kern_data_len = alloc_len;
6880		ctsio->kern_total_len = alloc_len;
6881	}
6882	ctsio->kern_data_resid = 0;
6883	ctsio->kern_rel_offset = 0;
6884	ctsio->kern_sg_entries = 0;
6885
6886	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6887	/* XXX KDM this may not be 512 bytes... */
6888	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6889	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6890	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
6891	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
6892		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
6893
6894	ctl_set_success(ctsio);
6895	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6896	ctsio->be_move_done = ctl_config_move_done;
6897	ctl_datamove((union ctl_io *)ctsio);
6898	return (CTL_RETVAL_COMPLETE);
6899}
6900
6901int
6902ctl_get_lba_status(struct ctl_scsiio *ctsio)
6903{
6904	struct scsi_get_lba_status *cdb;
6905	struct scsi_get_lba_status_data *data;
6906	struct ctl_lun *lun;
6907	struct ctl_lba_len_flags *lbalen;
6908	uint64_t lba;
6909	uint32_t alloc_len, total_len;
6910	int retval;
6911
6912	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
6913
6914	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6915	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
6916	lba = scsi_8btou64(cdb->addr);
6917	alloc_len = scsi_4btoul(cdb->alloc_len);
6918
6919	if (lba > lun->be_lun->maxlba) {
6920		ctl_set_lba_out_of_range(ctsio);
6921		ctl_done((union ctl_io *)ctsio);
6922		return (CTL_RETVAL_COMPLETE);
6923	}
6924
6925	total_len = sizeof(*data) + sizeof(data->descr[0]);
6926	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6927	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
6928
6929	if (total_len < alloc_len) {
6930		ctsio->residual = alloc_len - total_len;
6931		ctsio->kern_data_len = total_len;
6932		ctsio->kern_total_len = total_len;
6933	} else {
6934		ctsio->residual = 0;
6935		ctsio->kern_data_len = alloc_len;
6936		ctsio->kern_total_len = alloc_len;
6937	}
6938	ctsio->kern_data_resid = 0;
6939	ctsio->kern_rel_offset = 0;
6940	ctsio->kern_sg_entries = 0;
6941
6942	/* Fill dummy data in case backend can't tell anything. */
6943	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
6944	scsi_u64to8b(lba, data->descr[0].addr);
6945	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
6946	    data->descr[0].length);
6947	data->descr[0].status = 0; /* Mapped or unknown. */
6948
6949	ctl_set_success(ctsio);
6950	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6951	ctsio->be_move_done = ctl_config_move_done;
6952
6953	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6954	lbalen->lba = lba;
6955	lbalen->len = total_len;
6956	lbalen->flags = 0;
6957	retval = lun->backend->config_read((union ctl_io *)ctsio);
6958	return (CTL_RETVAL_COMPLETE);
6959}
6960
6961int
6962ctl_read_defect(struct ctl_scsiio *ctsio)
6963{
6964	struct scsi_read_defect_data_10 *ccb10;
6965	struct scsi_read_defect_data_12 *ccb12;
6966	struct scsi_read_defect_data_hdr_10 *data10;
6967	struct scsi_read_defect_data_hdr_12 *data12;
6968	uint32_t alloc_len, data_len;
6969	uint8_t format;
6970
6971	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
6972
6973	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
6974		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
6975		format = ccb10->format;
6976		alloc_len = scsi_2btoul(ccb10->alloc_length);
6977		data_len = sizeof(*data10);
6978	} else {
6979		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
6980		format = ccb12->format;
6981		alloc_len = scsi_4btoul(ccb12->alloc_length);
6982		data_len = sizeof(*data12);
6983	}
6984	if (alloc_len == 0) {
6985		ctl_set_success(ctsio);
6986		ctl_done((union ctl_io *)ctsio);
6987		return (CTL_RETVAL_COMPLETE);
6988	}
6989
6990	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
6991	if (data_len < alloc_len) {
6992		ctsio->residual = alloc_len - data_len;
6993		ctsio->kern_data_len = data_len;
6994		ctsio->kern_total_len = data_len;
6995	} else {
6996		ctsio->residual = 0;
6997		ctsio->kern_data_len = alloc_len;
6998		ctsio->kern_total_len = alloc_len;
6999	}
7000	ctsio->kern_data_resid = 0;
7001	ctsio->kern_rel_offset = 0;
7002	ctsio->kern_sg_entries = 0;
7003
7004	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7005		data10 = (struct scsi_read_defect_data_hdr_10 *)
7006		    ctsio->kern_data_ptr;
7007		data10->format = format;
7008		scsi_ulto2b(0, data10->length);
7009	} else {
7010		data12 = (struct scsi_read_defect_data_hdr_12 *)
7011		    ctsio->kern_data_ptr;
7012		data12->format = format;
7013		scsi_ulto2b(0, data12->generation);
7014		scsi_ulto4b(0, data12->length);
7015	}
7016
7017	ctl_set_success(ctsio);
7018	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7019	ctsio->be_move_done = ctl_config_move_done;
7020	ctl_datamove((union ctl_io *)ctsio);
7021	return (CTL_RETVAL_COMPLETE);
7022}
7023
7024int
7025ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7026{
7027	struct scsi_maintenance_in *cdb;
7028	int retval;
7029	int alloc_len, ext, total_len = 0, g, pc, pg, gs, os;
7030	int num_target_port_groups, num_target_ports;
7031	struct ctl_lun *lun;
7032	struct ctl_softc *softc;
7033	struct ctl_port *port;
7034	struct scsi_target_group_data *rtg_ptr;
7035	struct scsi_target_group_data_extended *rtg_ext_ptr;
7036	struct scsi_target_port_group_descriptor *tpg_desc;
7037
7038	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7039
7040	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7041	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7042	softc = lun->ctl_softc;
7043
7044	retval = CTL_RETVAL_COMPLETE;
7045
7046	switch (cdb->byte2 & STG_PDF_MASK) {
7047	case STG_PDF_LENGTH:
7048		ext = 0;
7049		break;
7050	case STG_PDF_EXTENDED:
7051		ext = 1;
7052		break;
7053	default:
7054		ctl_set_invalid_field(/*ctsio*/ ctsio,
7055				      /*sks_valid*/ 1,
7056				      /*command*/ 1,
7057				      /*field*/ 2,
7058				      /*bit_valid*/ 1,
7059				      /*bit*/ 5);
7060		ctl_done((union ctl_io *)ctsio);
7061		return(retval);
7062	}
7063
7064	if (softc->is_single)
7065		num_target_port_groups = 1;
7066	else
7067		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7068	num_target_ports = 0;
7069	mtx_lock(&softc->ctl_lock);
7070	STAILQ_FOREACH(port, &softc->port_list, links) {
7071		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7072			continue;
7073		if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7074			continue;
7075		num_target_ports++;
7076	}
7077	mtx_unlock(&softc->ctl_lock);
7078
7079	if (ext)
7080		total_len = sizeof(struct scsi_target_group_data_extended);
7081	else
7082		total_len = sizeof(struct scsi_target_group_data);
7083	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7084		num_target_port_groups +
7085	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7086
7087	alloc_len = scsi_4btoul(cdb->length);
7088
7089	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7090
7091	ctsio->kern_sg_entries = 0;
7092
7093	if (total_len < alloc_len) {
7094		ctsio->residual = alloc_len - total_len;
7095		ctsio->kern_data_len = total_len;
7096		ctsio->kern_total_len = total_len;
7097	} else {
7098		ctsio->residual = 0;
7099		ctsio->kern_data_len = alloc_len;
7100		ctsio->kern_total_len = alloc_len;
7101	}
7102	ctsio->kern_data_resid = 0;
7103	ctsio->kern_rel_offset = 0;
7104
7105	if (ext) {
7106		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7107		    ctsio->kern_data_ptr;
7108		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7109		rtg_ext_ptr->format_type = 0x10;
7110		rtg_ext_ptr->implicit_transition_time = 0;
7111		tpg_desc = &rtg_ext_ptr->groups[0];
7112	} else {
7113		rtg_ptr = (struct scsi_target_group_data *)
7114		    ctsio->kern_data_ptr;
7115		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7116		tpg_desc = &rtg_ptr->groups[0];
7117	}
7118
7119	mtx_lock(&softc->ctl_lock);
7120	pg = softc->port_min / softc->port_cnt;
7121	if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7122		gs = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7123	else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7124		gs = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7125	else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7126		gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7127	else
7128		gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7129	if (lun->flags & CTL_LUN_PRIMARY_SC) {
7130		os = gs;
7131		gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7132	} else
7133		os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7134	for (g = 0; g < num_target_port_groups; g++) {
7135		tpg_desc->pref_state = (g == pg) ? gs : os;
7136		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7137		    TPG_U_SUP | TPG_T_SUP;
7138		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7139		tpg_desc->status = TPG_IMPLICIT;
7140		pc = 0;
7141		STAILQ_FOREACH(port, &softc->port_list, links) {
7142			if (port->targ_port < g * softc->port_cnt ||
7143			    port->targ_port >= (g + 1) * softc->port_cnt)
7144				continue;
7145			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7146				continue;
7147			if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7148				continue;
7149			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7150			    relative_target_port_identifier);
7151			pc++;
7152		}
7153		tpg_desc->target_port_count = pc;
7154		tpg_desc = (struct scsi_target_port_group_descriptor *)
7155		    &tpg_desc->descriptors[pc];
7156	}
7157	mtx_unlock(&softc->ctl_lock);
7158
7159	ctl_set_success(ctsio);
7160	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7161	ctsio->be_move_done = ctl_config_move_done;
7162	ctl_datamove((union ctl_io *)ctsio);
7163	return(retval);
7164}
7165
7166int
7167ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7168{
7169	struct ctl_lun *lun;
7170	struct scsi_report_supported_opcodes *cdb;
7171	const struct ctl_cmd_entry *entry, *sentry;
7172	struct scsi_report_supported_opcodes_all *all;
7173	struct scsi_report_supported_opcodes_descr *descr;
7174	struct scsi_report_supported_opcodes_one *one;
7175	int retval;
7176	int alloc_len, total_len;
7177	int opcode, service_action, i, j, num;
7178
7179	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7180
7181	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7182	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7183
7184	retval = CTL_RETVAL_COMPLETE;
7185
7186	opcode = cdb->requested_opcode;
7187	service_action = scsi_2btoul(cdb->requested_service_action);
7188	switch (cdb->options & RSO_OPTIONS_MASK) {
7189	case RSO_OPTIONS_ALL:
7190		num = 0;
7191		for (i = 0; i < 256; i++) {
7192			entry = &ctl_cmd_table[i];
7193			if (entry->flags & CTL_CMD_FLAG_SA5) {
7194				for (j = 0; j < 32; j++) {
7195					sentry = &((const struct ctl_cmd_entry *)
7196					    entry->execute)[j];
7197					if (ctl_cmd_applicable(
7198					    lun->be_lun->lun_type, sentry))
7199						num++;
7200				}
7201			} else {
7202				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7203				    entry))
7204					num++;
7205			}
7206		}
7207		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7208		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7209		break;
7210	case RSO_OPTIONS_OC:
7211		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7212			ctl_set_invalid_field(/*ctsio*/ ctsio,
7213					      /*sks_valid*/ 1,
7214					      /*command*/ 1,
7215					      /*field*/ 2,
7216					      /*bit_valid*/ 1,
7217					      /*bit*/ 2);
7218			ctl_done((union ctl_io *)ctsio);
7219			return (CTL_RETVAL_COMPLETE);
7220		}
7221		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7222		break;
7223	case RSO_OPTIONS_OC_SA:
7224		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7225		    service_action >= 32) {
7226			ctl_set_invalid_field(/*ctsio*/ ctsio,
7227					      /*sks_valid*/ 1,
7228					      /*command*/ 1,
7229					      /*field*/ 2,
7230					      /*bit_valid*/ 1,
7231					      /*bit*/ 2);
7232			ctl_done((union ctl_io *)ctsio);
7233			return (CTL_RETVAL_COMPLETE);
7234		}
7235		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7236		break;
7237	default:
7238		ctl_set_invalid_field(/*ctsio*/ ctsio,
7239				      /*sks_valid*/ 1,
7240				      /*command*/ 1,
7241				      /*field*/ 2,
7242				      /*bit_valid*/ 1,
7243				      /*bit*/ 2);
7244		ctl_done((union ctl_io *)ctsio);
7245		return (CTL_RETVAL_COMPLETE);
7246	}
7247
7248	alloc_len = scsi_4btoul(cdb->length);
7249
7250	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7251
7252	ctsio->kern_sg_entries = 0;
7253
7254	if (total_len < alloc_len) {
7255		ctsio->residual = alloc_len - total_len;
7256		ctsio->kern_data_len = total_len;
7257		ctsio->kern_total_len = total_len;
7258	} else {
7259		ctsio->residual = 0;
7260		ctsio->kern_data_len = alloc_len;
7261		ctsio->kern_total_len = alloc_len;
7262	}
7263	ctsio->kern_data_resid = 0;
7264	ctsio->kern_rel_offset = 0;
7265
7266	switch (cdb->options & RSO_OPTIONS_MASK) {
7267	case RSO_OPTIONS_ALL:
7268		all = (struct scsi_report_supported_opcodes_all *)
7269		    ctsio->kern_data_ptr;
7270		num = 0;
7271		for (i = 0; i < 256; i++) {
7272			entry = &ctl_cmd_table[i];
7273			if (entry->flags & CTL_CMD_FLAG_SA5) {
7274				for (j = 0; j < 32; j++) {
7275					sentry = &((const struct ctl_cmd_entry *)
7276					    entry->execute)[j];
7277					if (!ctl_cmd_applicable(
7278					    lun->be_lun->lun_type, sentry))
7279						continue;
7280					descr = &all->descr[num++];
7281					descr->opcode = i;
7282					scsi_ulto2b(j, descr->service_action);
7283					descr->flags = RSO_SERVACTV;
7284					scsi_ulto2b(sentry->length,
7285					    descr->cdb_length);
7286				}
7287			} else {
7288				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7289				    entry))
7290					continue;
7291				descr = &all->descr[num++];
7292				descr->opcode = i;
7293				scsi_ulto2b(0, descr->service_action);
7294				descr->flags = 0;
7295				scsi_ulto2b(entry->length, descr->cdb_length);
7296			}
7297		}
7298		scsi_ulto4b(
7299		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7300		    all->length);
7301		break;
7302	case RSO_OPTIONS_OC:
7303		one = (struct scsi_report_supported_opcodes_one *)
7304		    ctsio->kern_data_ptr;
7305		entry = &ctl_cmd_table[opcode];
7306		goto fill_one;
7307	case RSO_OPTIONS_OC_SA:
7308		one = (struct scsi_report_supported_opcodes_one *)
7309		    ctsio->kern_data_ptr;
7310		entry = &ctl_cmd_table[opcode];
7311		entry = &((const struct ctl_cmd_entry *)
7312		    entry->execute)[service_action];
7313fill_one:
7314		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7315			one->support = 3;
7316			scsi_ulto2b(entry->length, one->cdb_length);
7317			one->cdb_usage[0] = opcode;
7318			memcpy(&one->cdb_usage[1], entry->usage,
7319			    entry->length - 1);
7320		} else
7321			one->support = 1;
7322		break;
7323	}
7324
7325	ctl_set_success(ctsio);
7326	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7327	ctsio->be_move_done = ctl_config_move_done;
7328	ctl_datamove((union ctl_io *)ctsio);
7329	return(retval);
7330}
7331
7332int
7333ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7334{
7335	struct scsi_report_supported_tmf *cdb;
7336	struct scsi_report_supported_tmf_data *data;
7337	int retval;
7338	int alloc_len, total_len;
7339
7340	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7341
7342	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7343
7344	retval = CTL_RETVAL_COMPLETE;
7345
7346	total_len = sizeof(struct scsi_report_supported_tmf_data);
7347	alloc_len = scsi_4btoul(cdb->length);
7348
7349	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7350
7351	ctsio->kern_sg_entries = 0;
7352
7353	if (total_len < alloc_len) {
7354		ctsio->residual = alloc_len - total_len;
7355		ctsio->kern_data_len = total_len;
7356		ctsio->kern_total_len = total_len;
7357	} else {
7358		ctsio->residual = 0;
7359		ctsio->kern_data_len = alloc_len;
7360		ctsio->kern_total_len = alloc_len;
7361	}
7362	ctsio->kern_data_resid = 0;
7363	ctsio->kern_rel_offset = 0;
7364
7365	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7366	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7367	    RST_TRS;
7368	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7369
7370	ctl_set_success(ctsio);
7371	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7372	ctsio->be_move_done = ctl_config_move_done;
7373	ctl_datamove((union ctl_io *)ctsio);
7374	return (retval);
7375}
7376
7377int
7378ctl_report_timestamp(struct ctl_scsiio *ctsio)
7379{
7380	struct scsi_report_timestamp *cdb;
7381	struct scsi_report_timestamp_data *data;
7382	struct timeval tv;
7383	int64_t timestamp;
7384	int retval;
7385	int alloc_len, total_len;
7386
7387	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7388
7389	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7390
7391	retval = CTL_RETVAL_COMPLETE;
7392
7393	total_len = sizeof(struct scsi_report_timestamp_data);
7394	alloc_len = scsi_4btoul(cdb->length);
7395
7396	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7397
7398	ctsio->kern_sg_entries = 0;
7399
7400	if (total_len < alloc_len) {
7401		ctsio->residual = alloc_len - total_len;
7402		ctsio->kern_data_len = total_len;
7403		ctsio->kern_total_len = total_len;
7404	} else {
7405		ctsio->residual = 0;
7406		ctsio->kern_data_len = alloc_len;
7407		ctsio->kern_total_len = alloc_len;
7408	}
7409	ctsio->kern_data_resid = 0;
7410	ctsio->kern_rel_offset = 0;
7411
7412	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7413	scsi_ulto2b(sizeof(*data) - 2, data->length);
7414	data->origin = RTS_ORIG_OUTSIDE;
7415	getmicrotime(&tv);
7416	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7417	scsi_ulto4b(timestamp >> 16, data->timestamp);
7418	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7419
7420	ctl_set_success(ctsio);
7421	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7422	ctsio->be_move_done = ctl_config_move_done;
7423	ctl_datamove((union ctl_io *)ctsio);
7424	return (retval);
7425}
7426
7427int
7428ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7429{
7430	struct scsi_per_res_in *cdb;
7431	int alloc_len, total_len = 0;
7432	/* struct scsi_per_res_in_rsrv in_data; */
7433	struct ctl_lun *lun;
7434	struct ctl_softc *softc;
7435	uint64_t key;
7436
7437	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7438
7439	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7440
7441	alloc_len = scsi_2btoul(cdb->length);
7442
7443	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7444	softc = lun->ctl_softc;
7445
7446retry:
7447	mtx_lock(&lun->lun_lock);
7448	switch (cdb->action) {
7449	case SPRI_RK: /* read keys */
7450		total_len = sizeof(struct scsi_per_res_in_keys) +
7451			lun->pr_key_count *
7452			sizeof(struct scsi_per_res_key);
7453		break;
7454	case SPRI_RR: /* read reservation */
7455		if (lun->flags & CTL_LUN_PR_RESERVED)
7456			total_len = sizeof(struct scsi_per_res_in_rsrv);
7457		else
7458			total_len = sizeof(struct scsi_per_res_in_header);
7459		break;
7460	case SPRI_RC: /* report capabilities */
7461		total_len = sizeof(struct scsi_per_res_cap);
7462		break;
7463	case SPRI_RS: /* read full status */
7464		total_len = sizeof(struct scsi_per_res_in_header) +
7465		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7466		    lun->pr_key_count;
7467		break;
7468	default:
7469		panic("Invalid PR type %x", cdb->action);
7470	}
7471	mtx_unlock(&lun->lun_lock);
7472
7473	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7474
7475	if (total_len < alloc_len) {
7476		ctsio->residual = alloc_len - total_len;
7477		ctsio->kern_data_len = total_len;
7478		ctsio->kern_total_len = total_len;
7479	} else {
7480		ctsio->residual = 0;
7481		ctsio->kern_data_len = alloc_len;
7482		ctsio->kern_total_len = alloc_len;
7483	}
7484
7485	ctsio->kern_data_resid = 0;
7486	ctsio->kern_rel_offset = 0;
7487	ctsio->kern_sg_entries = 0;
7488
7489	mtx_lock(&lun->lun_lock);
7490	switch (cdb->action) {
7491	case SPRI_RK: { // read keys
7492        struct scsi_per_res_in_keys *res_keys;
7493		int i, key_count;
7494
7495		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7496
7497		/*
7498		 * We had to drop the lock to allocate our buffer, which
7499		 * leaves time for someone to come in with another
7500		 * persistent reservation.  (That is unlikely, though,
7501		 * since this should be the only persistent reservation
7502		 * command active right now.)
7503		 */
7504		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7505		    (lun->pr_key_count *
7506		     sizeof(struct scsi_per_res_key)))){
7507			mtx_unlock(&lun->lun_lock);
7508			free(ctsio->kern_data_ptr, M_CTL);
7509			printf("%s: reservation length changed, retrying\n",
7510			       __func__);
7511			goto retry;
7512		}
7513
7514		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7515
7516		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7517			     lun->pr_key_count, res_keys->header.length);
7518
7519		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7520			if ((key = ctl_get_prkey(lun, i)) == 0)
7521				continue;
7522
7523			/*
7524			 * We used lun->pr_key_count to calculate the
7525			 * size to allocate.  If it turns out the number of
7526			 * initiators with the registered flag set is
7527			 * larger than that (i.e. they haven't been kept in
7528			 * sync), we've got a problem.
7529			 */
7530			if (key_count >= lun->pr_key_count) {
7531#ifdef NEEDTOPORT
7532				csevent_log(CSC_CTL | CSC_SHELF_SW |
7533					    CTL_PR_ERROR,
7534					    csevent_LogType_Fault,
7535					    csevent_AlertLevel_Yellow,
7536					    csevent_FRU_ShelfController,
7537					    csevent_FRU_Firmware,
7538				        csevent_FRU_Unknown,
7539					    "registered keys %d >= key "
7540					    "count %d", key_count,
7541					    lun->pr_key_count);
7542#endif
7543				key_count++;
7544				continue;
7545			}
7546			scsi_u64to8b(key, res_keys->keys[key_count].key);
7547			key_count++;
7548		}
7549		break;
7550	}
7551	case SPRI_RR: { // read reservation
7552		struct scsi_per_res_in_rsrv *res;
7553		int tmp_len, header_only;
7554
7555		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7556
7557		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7558
7559		if (lun->flags & CTL_LUN_PR_RESERVED)
7560		{
7561			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7562			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7563				    res->header.length);
7564			header_only = 0;
7565		} else {
7566			tmp_len = sizeof(struct scsi_per_res_in_header);
7567			scsi_ulto4b(0, res->header.length);
7568			header_only = 1;
7569		}
7570
7571		/*
7572		 * We had to drop the lock to allocate our buffer, which
7573		 * leaves time for someone to come in with another
7574		 * persistent reservation.  (That is unlikely, though,
7575		 * since this should be the only persistent reservation
7576		 * command active right now.)
7577		 */
7578		if (tmp_len != total_len) {
7579			mtx_unlock(&lun->lun_lock);
7580			free(ctsio->kern_data_ptr, M_CTL);
7581			printf("%s: reservation status changed, retrying\n",
7582			       __func__);
7583			goto retry;
7584		}
7585
7586		/*
7587		 * No reservation held, so we're done.
7588		 */
7589		if (header_only != 0)
7590			break;
7591
7592		/*
7593		 * If the registration is an All Registrants type, the key
7594		 * is 0, since it doesn't really matter.
7595		 */
7596		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7597			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7598			    res->data.reservation);
7599		}
7600		res->data.scopetype = lun->res_type;
7601		break;
7602	}
7603	case SPRI_RC:     //report capabilities
7604	{
7605		struct scsi_per_res_cap *res_cap;
7606		uint16_t type_mask;
7607
7608		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7609		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7610		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7611		type_mask = SPRI_TM_WR_EX_AR |
7612			    SPRI_TM_EX_AC_RO |
7613			    SPRI_TM_WR_EX_RO |
7614			    SPRI_TM_EX_AC |
7615			    SPRI_TM_WR_EX |
7616			    SPRI_TM_EX_AC_AR;
7617		scsi_ulto2b(type_mask, res_cap->type_mask);
7618		break;
7619	}
7620	case SPRI_RS: { // read full status
7621		struct scsi_per_res_in_full *res_status;
7622		struct scsi_per_res_in_full_desc *res_desc;
7623		struct ctl_port *port;
7624		int i, len;
7625
7626		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7627
7628		/*
7629		 * We had to drop the lock to allocate our buffer, which
7630		 * leaves time for someone to come in with another
7631		 * persistent reservation.  (That is unlikely, though,
7632		 * since this should be the only persistent reservation
7633		 * command active right now.)
7634		 */
7635		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7636		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7637		     lun->pr_key_count)){
7638			mtx_unlock(&lun->lun_lock);
7639			free(ctsio->kern_data_ptr, M_CTL);
7640			printf("%s: reservation length changed, retrying\n",
7641			       __func__);
7642			goto retry;
7643		}
7644
7645		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7646
7647		res_desc = &res_status->desc[0];
7648		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7649			if ((key = ctl_get_prkey(lun, i)) == 0)
7650				continue;
7651
7652			scsi_u64to8b(key, res_desc->res_key.key);
7653			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7654			    (lun->pr_res_idx == i ||
7655			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7656				res_desc->flags = SPRI_FULL_R_HOLDER;
7657				res_desc->scopetype = lun->res_type;
7658			}
7659			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7660			    res_desc->rel_trgt_port_id);
7661			len = 0;
7662			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7663			if (port != NULL)
7664				len = ctl_create_iid(port,
7665				    i % CTL_MAX_INIT_PER_PORT,
7666				    res_desc->transport_id);
7667			scsi_ulto4b(len, res_desc->additional_length);
7668			res_desc = (struct scsi_per_res_in_full_desc *)
7669			    &res_desc->transport_id[len];
7670		}
7671		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7672		    res_status->header.length);
7673		break;
7674	}
7675	default:
7676		/*
7677		 * This is a bug, because we just checked for this above,
7678		 * and should have returned an error.
7679		 */
7680		panic("Invalid PR type %x", cdb->action);
7681		break; /* NOTREACHED */
7682	}
7683	mtx_unlock(&lun->lun_lock);
7684
7685	ctl_set_success(ctsio);
7686	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7687	ctsio->be_move_done = ctl_config_move_done;
7688	ctl_datamove((union ctl_io *)ctsio);
7689	return (CTL_RETVAL_COMPLETE);
7690}
7691
7692/*
7693 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7694 * it should return.
7695 */
7696static int
7697ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7698		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7699		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7700		struct scsi_per_res_out_parms* param)
7701{
7702	union ctl_ha_msg persis_io;
7703	int i;
7704
7705	mtx_lock(&lun->lun_lock);
7706	if (sa_res_key == 0) {
7707		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7708			/* validate scope and type */
7709			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7710			     SPR_LU_SCOPE) {
7711				mtx_unlock(&lun->lun_lock);
7712				ctl_set_invalid_field(/*ctsio*/ ctsio,
7713						      /*sks_valid*/ 1,
7714						      /*command*/ 1,
7715						      /*field*/ 2,
7716						      /*bit_valid*/ 1,
7717						      /*bit*/ 4);
7718				ctl_done((union ctl_io *)ctsio);
7719				return (1);
7720			}
7721
7722		        if (type>8 || type==2 || type==4 || type==0) {
7723				mtx_unlock(&lun->lun_lock);
7724				ctl_set_invalid_field(/*ctsio*/ ctsio,
7725       	           				      /*sks_valid*/ 1,
7726						      /*command*/ 1,
7727						      /*field*/ 2,
7728						      /*bit_valid*/ 1,
7729						      /*bit*/ 0);
7730				ctl_done((union ctl_io *)ctsio);
7731				return (1);
7732		        }
7733
7734			/*
7735			 * Unregister everybody else and build UA for
7736			 * them
7737			 */
7738			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7739				if (i == residx || ctl_get_prkey(lun, i) == 0)
7740					continue;
7741
7742				ctl_clr_prkey(lun, i);
7743				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7744			}
7745			lun->pr_key_count = 1;
7746			lun->res_type = type;
7747			if (lun->res_type != SPR_TYPE_WR_EX_AR
7748			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7749				lun->pr_res_idx = residx;
7750			lun->PRGeneration++;
7751			mtx_unlock(&lun->lun_lock);
7752
7753			/* send msg to other side */
7754			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7755			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7756			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7757			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7758			persis_io.pr.pr_info.res_type = type;
7759			memcpy(persis_io.pr.pr_info.sa_res_key,
7760			       param->serv_act_res_key,
7761			       sizeof(param->serv_act_res_key));
7762			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7763			    sizeof(persis_io.pr), M_WAITOK);
7764		} else {
7765			/* not all registrants */
7766			mtx_unlock(&lun->lun_lock);
7767			free(ctsio->kern_data_ptr, M_CTL);
7768			ctl_set_invalid_field(ctsio,
7769					      /*sks_valid*/ 1,
7770					      /*command*/ 0,
7771					      /*field*/ 8,
7772					      /*bit_valid*/ 0,
7773					      /*bit*/ 0);
7774			ctl_done((union ctl_io *)ctsio);
7775			return (1);
7776		}
7777	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7778		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7779		int found = 0;
7780
7781		if (res_key == sa_res_key) {
7782			/* special case */
7783			/*
7784			 * The spec implies this is not good but doesn't
7785			 * say what to do. There are two choices either
7786			 * generate a res conflict or check condition
7787			 * with illegal field in parameter data. Since
7788			 * that is what is done when the sa_res_key is
7789			 * zero I'll take that approach since this has
7790			 * to do with the sa_res_key.
7791			 */
7792			mtx_unlock(&lun->lun_lock);
7793			free(ctsio->kern_data_ptr, M_CTL);
7794			ctl_set_invalid_field(ctsio,
7795					      /*sks_valid*/ 1,
7796					      /*command*/ 0,
7797					      /*field*/ 8,
7798					      /*bit_valid*/ 0,
7799					      /*bit*/ 0);
7800			ctl_done((union ctl_io *)ctsio);
7801			return (1);
7802		}
7803
7804		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7805			if (ctl_get_prkey(lun, i) != sa_res_key)
7806				continue;
7807
7808			found = 1;
7809			ctl_clr_prkey(lun, i);
7810			lun->pr_key_count--;
7811			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7812		}
7813		if (!found) {
7814			mtx_unlock(&lun->lun_lock);
7815			free(ctsio->kern_data_ptr, M_CTL);
7816			ctl_set_reservation_conflict(ctsio);
7817			ctl_done((union ctl_io *)ctsio);
7818			return (CTL_RETVAL_COMPLETE);
7819		}
7820		lun->PRGeneration++;
7821		mtx_unlock(&lun->lun_lock);
7822
7823		/* send msg to other side */
7824		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7825		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7826		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7827		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7828		persis_io.pr.pr_info.res_type = type;
7829		memcpy(persis_io.pr.pr_info.sa_res_key,
7830		       param->serv_act_res_key,
7831		       sizeof(param->serv_act_res_key));
7832		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7833		    sizeof(persis_io.pr), M_WAITOK);
7834	} else {
7835		/* Reserved but not all registrants */
7836		/* sa_res_key is res holder */
7837		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7838			/* validate scope and type */
7839			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7840			     SPR_LU_SCOPE) {
7841				mtx_unlock(&lun->lun_lock);
7842				ctl_set_invalid_field(/*ctsio*/ ctsio,
7843						      /*sks_valid*/ 1,
7844						      /*command*/ 1,
7845						      /*field*/ 2,
7846						      /*bit_valid*/ 1,
7847						      /*bit*/ 4);
7848				ctl_done((union ctl_io *)ctsio);
7849				return (1);
7850			}
7851
7852			if (type>8 || type==2 || type==4 || type==0) {
7853				mtx_unlock(&lun->lun_lock);
7854				ctl_set_invalid_field(/*ctsio*/ ctsio,
7855						      /*sks_valid*/ 1,
7856						      /*command*/ 1,
7857						      /*field*/ 2,
7858						      /*bit_valid*/ 1,
7859						      /*bit*/ 0);
7860				ctl_done((union ctl_io *)ctsio);
7861				return (1);
7862			}
7863
7864			/*
7865			 * Do the following:
7866			 * if sa_res_key != res_key remove all
7867			 * registrants w/sa_res_key and generate UA
7868			 * for these registrants(Registrations
7869			 * Preempted) if it wasn't an exclusive
7870			 * reservation generate UA(Reservations
7871			 * Preempted) for all other registered nexuses
7872			 * if the type has changed. Establish the new
7873			 * reservation and holder. If res_key and
7874			 * sa_res_key are the same do the above
7875			 * except don't unregister the res holder.
7876			 */
7877
7878			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7879				if (i == residx || ctl_get_prkey(lun, i) == 0)
7880					continue;
7881
7882				if (sa_res_key == ctl_get_prkey(lun, i)) {
7883					ctl_clr_prkey(lun, i);
7884					lun->pr_key_count--;
7885					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7886				} else if (type != lun->res_type
7887					&& (lun->res_type == SPR_TYPE_WR_EX_RO
7888					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
7889					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
7890				}
7891			}
7892			lun->res_type = type;
7893			if (lun->res_type != SPR_TYPE_WR_EX_AR
7894			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7895				lun->pr_res_idx = residx;
7896			else
7897				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7898			lun->PRGeneration++;
7899			mtx_unlock(&lun->lun_lock);
7900
7901			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7902			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7903			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7904			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7905			persis_io.pr.pr_info.res_type = type;
7906			memcpy(persis_io.pr.pr_info.sa_res_key,
7907			       param->serv_act_res_key,
7908			       sizeof(param->serv_act_res_key));
7909			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7910			    sizeof(persis_io.pr), M_WAITOK);
7911		} else {
7912			/*
7913			 * sa_res_key is not the res holder just
7914			 * remove registrants
7915			 */
7916			int found=0;
7917
7918			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7919				if (sa_res_key != ctl_get_prkey(lun, i))
7920					continue;
7921
7922				found = 1;
7923				ctl_clr_prkey(lun, i);
7924				lun->pr_key_count--;
7925				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7926			}
7927
7928			if (!found) {
7929				mtx_unlock(&lun->lun_lock);
7930				free(ctsio->kern_data_ptr, M_CTL);
7931				ctl_set_reservation_conflict(ctsio);
7932				ctl_done((union ctl_io *)ctsio);
7933		        	return (1);
7934			}
7935			lun->PRGeneration++;
7936			mtx_unlock(&lun->lun_lock);
7937
7938			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7939			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7940			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7941			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7942			persis_io.pr.pr_info.res_type = type;
7943			memcpy(persis_io.pr.pr_info.sa_res_key,
7944			       param->serv_act_res_key,
7945			       sizeof(param->serv_act_res_key));
7946			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7947			    sizeof(persis_io.pr), M_WAITOK);
7948		}
7949	}
7950	return (0);
7951}
7952
7953static void
7954ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
7955{
7956	uint64_t sa_res_key;
7957	int i;
7958
7959	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
7960
7961	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7962	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
7963	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
7964		if (sa_res_key == 0) {
7965			/*
7966			 * Unregister everybody else and build UA for
7967			 * them
7968			 */
7969			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7970				if (i == msg->pr.pr_info.residx ||
7971				    ctl_get_prkey(lun, i) == 0)
7972					continue;
7973
7974				ctl_clr_prkey(lun, i);
7975				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7976			}
7977
7978			lun->pr_key_count = 1;
7979			lun->res_type = msg->pr.pr_info.res_type;
7980			if (lun->res_type != SPR_TYPE_WR_EX_AR
7981			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7982				lun->pr_res_idx = msg->pr.pr_info.residx;
7983		} else {
7984		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7985				if (sa_res_key == ctl_get_prkey(lun, i))
7986					continue;
7987
7988				ctl_clr_prkey(lun, i);
7989				lun->pr_key_count--;
7990				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7991			}
7992		}
7993	} else {
7994		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7995			if (i == msg->pr.pr_info.residx ||
7996			    ctl_get_prkey(lun, i) == 0)
7997				continue;
7998
7999			if (sa_res_key == ctl_get_prkey(lun, i)) {
8000				ctl_clr_prkey(lun, i);
8001				lun->pr_key_count--;
8002				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8003			} else if (msg->pr.pr_info.res_type != lun->res_type
8004				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8005				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8006				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8007			}
8008		}
8009		lun->res_type = msg->pr.pr_info.res_type;
8010		if (lun->res_type != SPR_TYPE_WR_EX_AR
8011		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8012			lun->pr_res_idx = msg->pr.pr_info.residx;
8013		else
8014			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8015	}
8016	lun->PRGeneration++;
8017
8018}
8019
8020
8021int
8022ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8023{
8024	int retval;
8025	u_int32_t param_len;
8026	struct scsi_per_res_out *cdb;
8027	struct ctl_lun *lun;
8028	struct scsi_per_res_out_parms* param;
8029	struct ctl_softc *softc;
8030	uint32_t residx;
8031	uint64_t res_key, sa_res_key, key;
8032	uint8_t type;
8033	union ctl_ha_msg persis_io;
8034	int    i;
8035
8036	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8037
8038	retval = CTL_RETVAL_COMPLETE;
8039
8040	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8041	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8042	softc = lun->ctl_softc;
8043
8044	/*
8045	 * We only support whole-LUN scope.  The scope & type are ignored for
8046	 * register, register and ignore existing key and clear.
8047	 * We sometimes ignore scope and type on preempts too!!
8048	 * Verify reservation type here as well.
8049	 */
8050	type = cdb->scope_type & SPR_TYPE_MASK;
8051	if ((cdb->action == SPRO_RESERVE)
8052	 || (cdb->action == SPRO_RELEASE)) {
8053		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8054			ctl_set_invalid_field(/*ctsio*/ ctsio,
8055					      /*sks_valid*/ 1,
8056					      /*command*/ 1,
8057					      /*field*/ 2,
8058					      /*bit_valid*/ 1,
8059					      /*bit*/ 4);
8060			ctl_done((union ctl_io *)ctsio);
8061			return (CTL_RETVAL_COMPLETE);
8062		}
8063
8064		if (type>8 || type==2 || type==4 || type==0) {
8065			ctl_set_invalid_field(/*ctsio*/ ctsio,
8066					      /*sks_valid*/ 1,
8067					      /*command*/ 1,
8068					      /*field*/ 2,
8069					      /*bit_valid*/ 1,
8070					      /*bit*/ 0);
8071			ctl_done((union ctl_io *)ctsio);
8072			return (CTL_RETVAL_COMPLETE);
8073		}
8074	}
8075
8076	param_len = scsi_4btoul(cdb->length);
8077
8078	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8079		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8080		ctsio->kern_data_len = param_len;
8081		ctsio->kern_total_len = param_len;
8082		ctsio->kern_data_resid = 0;
8083		ctsio->kern_rel_offset = 0;
8084		ctsio->kern_sg_entries = 0;
8085		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8086		ctsio->be_move_done = ctl_config_move_done;
8087		ctl_datamove((union ctl_io *)ctsio);
8088
8089		return (CTL_RETVAL_COMPLETE);
8090	}
8091
8092	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8093
8094	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8095	res_key = scsi_8btou64(param->res_key.key);
8096	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8097
8098	/*
8099	 * Validate the reservation key here except for SPRO_REG_IGNO
8100	 * This must be done for all other service actions
8101	 */
8102	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8103		mtx_lock(&lun->lun_lock);
8104		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8105			if (res_key != key) {
8106				/*
8107				 * The current key passed in doesn't match
8108				 * the one the initiator previously
8109				 * registered.
8110				 */
8111				mtx_unlock(&lun->lun_lock);
8112				free(ctsio->kern_data_ptr, M_CTL);
8113				ctl_set_reservation_conflict(ctsio);
8114				ctl_done((union ctl_io *)ctsio);
8115				return (CTL_RETVAL_COMPLETE);
8116			}
8117		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8118			/*
8119			 * We are not registered
8120			 */
8121			mtx_unlock(&lun->lun_lock);
8122			free(ctsio->kern_data_ptr, M_CTL);
8123			ctl_set_reservation_conflict(ctsio);
8124			ctl_done((union ctl_io *)ctsio);
8125			return (CTL_RETVAL_COMPLETE);
8126		} else if (res_key != 0) {
8127			/*
8128			 * We are not registered and trying to register but
8129			 * the register key isn't zero.
8130			 */
8131			mtx_unlock(&lun->lun_lock);
8132			free(ctsio->kern_data_ptr, M_CTL);
8133			ctl_set_reservation_conflict(ctsio);
8134			ctl_done((union ctl_io *)ctsio);
8135			return (CTL_RETVAL_COMPLETE);
8136		}
8137		mtx_unlock(&lun->lun_lock);
8138	}
8139
8140	switch (cdb->action & SPRO_ACTION_MASK) {
8141	case SPRO_REGISTER:
8142	case SPRO_REG_IGNO: {
8143
8144#if 0
8145		printf("Registration received\n");
8146#endif
8147
8148		/*
8149		 * We don't support any of these options, as we report in
8150		 * the read capabilities request (see
8151		 * ctl_persistent_reserve_in(), above).
8152		 */
8153		if ((param->flags & SPR_SPEC_I_PT)
8154		 || (param->flags & SPR_ALL_TG_PT)
8155		 || (param->flags & SPR_APTPL)) {
8156			int bit_ptr;
8157
8158			if (param->flags & SPR_APTPL)
8159				bit_ptr = 0;
8160			else if (param->flags & SPR_ALL_TG_PT)
8161				bit_ptr = 2;
8162			else /* SPR_SPEC_I_PT */
8163				bit_ptr = 3;
8164
8165			free(ctsio->kern_data_ptr, M_CTL);
8166			ctl_set_invalid_field(ctsio,
8167					      /*sks_valid*/ 1,
8168					      /*command*/ 0,
8169					      /*field*/ 20,
8170					      /*bit_valid*/ 1,
8171					      /*bit*/ bit_ptr);
8172			ctl_done((union ctl_io *)ctsio);
8173			return (CTL_RETVAL_COMPLETE);
8174		}
8175
8176		mtx_lock(&lun->lun_lock);
8177
8178		/*
8179		 * The initiator wants to clear the
8180		 * key/unregister.
8181		 */
8182		if (sa_res_key == 0) {
8183			if ((res_key == 0
8184			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8185			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8186			  && ctl_get_prkey(lun, residx) == 0)) {
8187				mtx_unlock(&lun->lun_lock);
8188				goto done;
8189			}
8190
8191			ctl_clr_prkey(lun, residx);
8192			lun->pr_key_count--;
8193
8194			if (residx == lun->pr_res_idx) {
8195				lun->flags &= ~CTL_LUN_PR_RESERVED;
8196				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8197
8198				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8199				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8200				 && lun->pr_key_count) {
8201					/*
8202					 * If the reservation is a registrants
8203					 * only type we need to generate a UA
8204					 * for other registered inits.  The
8205					 * sense code should be RESERVATIONS
8206					 * RELEASED
8207					 */
8208
8209					for (i = softc->init_min; i < softc->init_max; i++){
8210						if (ctl_get_prkey(lun, i) == 0)
8211							continue;
8212						ctl_est_ua(lun, i,
8213						    CTL_UA_RES_RELEASE);
8214					}
8215				}
8216				lun->res_type = 0;
8217			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8218				if (lun->pr_key_count==0) {
8219					lun->flags &= ~CTL_LUN_PR_RESERVED;
8220					lun->res_type = 0;
8221					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8222				}
8223			}
8224			lun->PRGeneration++;
8225			mtx_unlock(&lun->lun_lock);
8226
8227			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8228			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8229			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8230			persis_io.pr.pr_info.residx = residx;
8231			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8232			    sizeof(persis_io.pr), M_WAITOK);
8233		} else /* sa_res_key != 0 */ {
8234
8235			/*
8236			 * If we aren't registered currently then increment
8237			 * the key count and set the registered flag.
8238			 */
8239			ctl_alloc_prkey(lun, residx);
8240			if (ctl_get_prkey(lun, residx) == 0)
8241				lun->pr_key_count++;
8242			ctl_set_prkey(lun, residx, sa_res_key);
8243			lun->PRGeneration++;
8244			mtx_unlock(&lun->lun_lock);
8245
8246			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8247			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8248			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8249			persis_io.pr.pr_info.residx = residx;
8250			memcpy(persis_io.pr.pr_info.sa_res_key,
8251			       param->serv_act_res_key,
8252			       sizeof(param->serv_act_res_key));
8253			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8254			    sizeof(persis_io.pr), M_WAITOK);
8255		}
8256
8257		break;
8258	}
8259	case SPRO_RESERVE:
8260#if 0
8261                printf("Reserve executed type %d\n", type);
8262#endif
8263		mtx_lock(&lun->lun_lock);
8264		if (lun->flags & CTL_LUN_PR_RESERVED) {
8265			/*
8266			 * if this isn't the reservation holder and it's
8267			 * not a "all registrants" type or if the type is
8268			 * different then we have a conflict
8269			 */
8270			if ((lun->pr_res_idx != residx
8271			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8272			 || lun->res_type != type) {
8273				mtx_unlock(&lun->lun_lock);
8274				free(ctsio->kern_data_ptr, M_CTL);
8275				ctl_set_reservation_conflict(ctsio);
8276				ctl_done((union ctl_io *)ctsio);
8277				return (CTL_RETVAL_COMPLETE);
8278			}
8279			mtx_unlock(&lun->lun_lock);
8280		} else /* create a reservation */ {
8281			/*
8282			 * If it's not an "all registrants" type record
8283			 * reservation holder
8284			 */
8285			if (type != SPR_TYPE_WR_EX_AR
8286			 && type != SPR_TYPE_EX_AC_AR)
8287				lun->pr_res_idx = residx; /* Res holder */
8288			else
8289				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8290
8291			lun->flags |= CTL_LUN_PR_RESERVED;
8292			lun->res_type = type;
8293
8294			mtx_unlock(&lun->lun_lock);
8295
8296			/* send msg to other side */
8297			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8298			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8299			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8300			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8301			persis_io.pr.pr_info.res_type = type;
8302			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8303			    sizeof(persis_io.pr), M_WAITOK);
8304		}
8305		break;
8306
8307	case SPRO_RELEASE:
8308		mtx_lock(&lun->lun_lock);
8309		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8310			/* No reservation exists return good status */
8311			mtx_unlock(&lun->lun_lock);
8312			goto done;
8313		}
8314		/*
8315		 * Is this nexus a reservation holder?
8316		 */
8317		if (lun->pr_res_idx != residx
8318		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8319			/*
8320			 * not a res holder return good status but
8321			 * do nothing
8322			 */
8323			mtx_unlock(&lun->lun_lock);
8324			goto done;
8325		}
8326
8327		if (lun->res_type != type) {
8328			mtx_unlock(&lun->lun_lock);
8329			free(ctsio->kern_data_ptr, M_CTL);
8330			ctl_set_illegal_pr_release(ctsio);
8331			ctl_done((union ctl_io *)ctsio);
8332			return (CTL_RETVAL_COMPLETE);
8333		}
8334
8335		/* okay to release */
8336		lun->flags &= ~CTL_LUN_PR_RESERVED;
8337		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8338		lun->res_type = 0;
8339
8340		/*
8341		 * if this isn't an exclusive access
8342		 * res generate UA for all other
8343		 * registrants.
8344		 */
8345		if (type != SPR_TYPE_EX_AC
8346		 && type != SPR_TYPE_WR_EX) {
8347			for (i = softc->init_min; i < softc->init_max; i++) {
8348				if (i == residx || ctl_get_prkey(lun, i) == 0)
8349					continue;
8350				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8351			}
8352		}
8353		mtx_unlock(&lun->lun_lock);
8354
8355		/* Send msg to other side */
8356		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8357		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8358		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8359		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8360		     sizeof(persis_io.pr), M_WAITOK);
8361		break;
8362
8363	case SPRO_CLEAR:
8364		/* send msg to other side */
8365
8366		mtx_lock(&lun->lun_lock);
8367		lun->flags &= ~CTL_LUN_PR_RESERVED;
8368		lun->res_type = 0;
8369		lun->pr_key_count = 0;
8370		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8371
8372		ctl_clr_prkey(lun, residx);
8373		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8374			if (ctl_get_prkey(lun, i) != 0) {
8375				ctl_clr_prkey(lun, i);
8376				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8377			}
8378		lun->PRGeneration++;
8379		mtx_unlock(&lun->lun_lock);
8380
8381		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8382		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8383		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8384		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8385		     sizeof(persis_io.pr), M_WAITOK);
8386		break;
8387
8388	case SPRO_PREEMPT:
8389	case SPRO_PRE_ABO: {
8390		int nretval;
8391
8392		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8393					  residx, ctsio, cdb, param);
8394		if (nretval != 0)
8395			return (CTL_RETVAL_COMPLETE);
8396		break;
8397	}
8398	default:
8399		panic("Invalid PR type %x", cdb->action);
8400	}
8401
8402done:
8403	free(ctsio->kern_data_ptr, M_CTL);
8404	ctl_set_success(ctsio);
8405	ctl_done((union ctl_io *)ctsio);
8406
8407	return (retval);
8408}
8409
8410/*
8411 * This routine is for handling a message from the other SC pertaining to
8412 * persistent reserve out. All the error checking will have been done
8413 * so only perorming the action need be done here to keep the two
8414 * in sync.
8415 */
8416static void
8417ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8418{
8419	struct ctl_lun *lun;
8420	struct ctl_softc *softc;
8421	int i;
8422	uint32_t residx, targ_lun;
8423
8424	softc = control_softc;
8425	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8426	mtx_lock(&softc->ctl_lock);
8427	if ((targ_lun >= CTL_MAX_LUNS) ||
8428	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
8429		mtx_unlock(&softc->ctl_lock);
8430		return;
8431	}
8432	mtx_lock(&lun->lun_lock);
8433	mtx_unlock(&softc->ctl_lock);
8434	if (lun->flags & CTL_LUN_DISABLED) {
8435		mtx_unlock(&lun->lun_lock);
8436		return;
8437	}
8438	residx = ctl_get_initindex(&msg->hdr.nexus);
8439	switch(msg->pr.pr_info.action) {
8440	case CTL_PR_REG_KEY:
8441		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8442		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8443			lun->pr_key_count++;
8444		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8445		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8446		lun->PRGeneration++;
8447		break;
8448
8449	case CTL_PR_UNREG_KEY:
8450		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8451		lun->pr_key_count--;
8452
8453		/* XXX Need to see if the reservation has been released */
8454		/* if so do we need to generate UA? */
8455		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8456			lun->flags &= ~CTL_LUN_PR_RESERVED;
8457			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8458
8459			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8460			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8461			 && lun->pr_key_count) {
8462				/*
8463				 * If the reservation is a registrants
8464				 * only type we need to generate a UA
8465				 * for other registered inits.  The
8466				 * sense code should be RESERVATIONS
8467				 * RELEASED
8468				 */
8469
8470				for (i = softc->init_min; i < softc->init_max; i++) {
8471					if (ctl_get_prkey(lun, i) == 0)
8472						continue;
8473
8474					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8475				}
8476			}
8477			lun->res_type = 0;
8478		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8479			if (lun->pr_key_count==0) {
8480				lun->flags &= ~CTL_LUN_PR_RESERVED;
8481				lun->res_type = 0;
8482				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8483			}
8484		}
8485		lun->PRGeneration++;
8486		break;
8487
8488	case CTL_PR_RESERVE:
8489		lun->flags |= CTL_LUN_PR_RESERVED;
8490		lun->res_type = msg->pr.pr_info.res_type;
8491		lun->pr_res_idx = msg->pr.pr_info.residx;
8492
8493		break;
8494
8495	case CTL_PR_RELEASE:
8496		/*
8497		 * if this isn't an exclusive access res generate UA for all
8498		 * other registrants.
8499		 */
8500		if (lun->res_type != SPR_TYPE_EX_AC
8501		 && lun->res_type != SPR_TYPE_WR_EX) {
8502			for (i = softc->init_min; i < softc->init_max; i++)
8503				if (i == residx || ctl_get_prkey(lun, i) == 0)
8504					continue;
8505				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8506		}
8507
8508		lun->flags &= ~CTL_LUN_PR_RESERVED;
8509		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8510		lun->res_type = 0;
8511		break;
8512
8513	case CTL_PR_PREEMPT:
8514		ctl_pro_preempt_other(lun, msg);
8515		break;
8516	case CTL_PR_CLEAR:
8517		lun->flags &= ~CTL_LUN_PR_RESERVED;
8518		lun->res_type = 0;
8519		lun->pr_key_count = 0;
8520		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8521
8522		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8523			if (ctl_get_prkey(lun, i) == 0)
8524				continue;
8525			ctl_clr_prkey(lun, i);
8526			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8527		}
8528		lun->PRGeneration++;
8529		break;
8530	}
8531
8532	mtx_unlock(&lun->lun_lock);
8533}
8534
8535int
8536ctl_read_write(struct ctl_scsiio *ctsio)
8537{
8538	struct ctl_lun *lun;
8539	struct ctl_lba_len_flags *lbalen;
8540	uint64_t lba;
8541	uint32_t num_blocks;
8542	int flags, retval;
8543	int isread;
8544
8545	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8546
8547	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8548
8549	flags = 0;
8550	retval = CTL_RETVAL_COMPLETE;
8551
8552	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8553	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8554	switch (ctsio->cdb[0]) {
8555	case READ_6:
8556	case WRITE_6: {
8557		struct scsi_rw_6 *cdb;
8558
8559		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8560
8561		lba = scsi_3btoul(cdb->addr);
8562		/* only 5 bits are valid in the most significant address byte */
8563		lba &= 0x1fffff;
8564		num_blocks = cdb->length;
8565		/*
8566		 * This is correct according to SBC-2.
8567		 */
8568		if (num_blocks == 0)
8569			num_blocks = 256;
8570		break;
8571	}
8572	case READ_10:
8573	case WRITE_10: {
8574		struct scsi_rw_10 *cdb;
8575
8576		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8577		if (cdb->byte2 & SRW10_FUA)
8578			flags |= CTL_LLF_FUA;
8579		if (cdb->byte2 & SRW10_DPO)
8580			flags |= CTL_LLF_DPO;
8581		lba = scsi_4btoul(cdb->addr);
8582		num_blocks = scsi_2btoul(cdb->length);
8583		break;
8584	}
8585	case WRITE_VERIFY_10: {
8586		struct scsi_write_verify_10 *cdb;
8587
8588		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8589		flags |= CTL_LLF_FUA;
8590		if (cdb->byte2 & SWV_DPO)
8591			flags |= CTL_LLF_DPO;
8592		lba = scsi_4btoul(cdb->addr);
8593		num_blocks = scsi_2btoul(cdb->length);
8594		break;
8595	}
8596	case READ_12:
8597	case WRITE_12: {
8598		struct scsi_rw_12 *cdb;
8599
8600		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8601		if (cdb->byte2 & SRW12_FUA)
8602			flags |= CTL_LLF_FUA;
8603		if (cdb->byte2 & SRW12_DPO)
8604			flags |= CTL_LLF_DPO;
8605		lba = scsi_4btoul(cdb->addr);
8606		num_blocks = scsi_4btoul(cdb->length);
8607		break;
8608	}
8609	case WRITE_VERIFY_12: {
8610		struct scsi_write_verify_12 *cdb;
8611
8612		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8613		flags |= CTL_LLF_FUA;
8614		if (cdb->byte2 & SWV_DPO)
8615			flags |= CTL_LLF_DPO;
8616		lba = scsi_4btoul(cdb->addr);
8617		num_blocks = scsi_4btoul(cdb->length);
8618		break;
8619	}
8620	case READ_16:
8621	case WRITE_16: {
8622		struct scsi_rw_16 *cdb;
8623
8624		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8625		if (cdb->byte2 & SRW12_FUA)
8626			flags |= CTL_LLF_FUA;
8627		if (cdb->byte2 & SRW12_DPO)
8628			flags |= CTL_LLF_DPO;
8629		lba = scsi_8btou64(cdb->addr);
8630		num_blocks = scsi_4btoul(cdb->length);
8631		break;
8632	}
8633	case WRITE_ATOMIC_16: {
8634		struct scsi_rw_16 *cdb;
8635
8636		if (lun->be_lun->atomicblock == 0) {
8637			ctl_set_invalid_opcode(ctsio);
8638			ctl_done((union ctl_io *)ctsio);
8639			return (CTL_RETVAL_COMPLETE);
8640		}
8641
8642		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8643		if (cdb->byte2 & SRW12_FUA)
8644			flags |= CTL_LLF_FUA;
8645		if (cdb->byte2 & SRW12_DPO)
8646			flags |= CTL_LLF_DPO;
8647		lba = scsi_8btou64(cdb->addr);
8648		num_blocks = scsi_4btoul(cdb->length);
8649		if (num_blocks > lun->be_lun->atomicblock) {
8650			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8651			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8652			    /*bit*/ 0);
8653			ctl_done((union ctl_io *)ctsio);
8654			return (CTL_RETVAL_COMPLETE);
8655		}
8656		break;
8657	}
8658	case WRITE_VERIFY_16: {
8659		struct scsi_write_verify_16 *cdb;
8660
8661		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8662		flags |= CTL_LLF_FUA;
8663		if (cdb->byte2 & SWV_DPO)
8664			flags |= CTL_LLF_DPO;
8665		lba = scsi_8btou64(cdb->addr);
8666		num_blocks = scsi_4btoul(cdb->length);
8667		break;
8668	}
8669	default:
8670		/*
8671		 * We got a command we don't support.  This shouldn't
8672		 * happen, commands should be filtered out above us.
8673		 */
8674		ctl_set_invalid_opcode(ctsio);
8675		ctl_done((union ctl_io *)ctsio);
8676
8677		return (CTL_RETVAL_COMPLETE);
8678		break; /* NOTREACHED */
8679	}
8680
8681	/*
8682	 * The first check is to make sure we're in bounds, the second
8683	 * check is to catch wrap-around problems.  If the lba + num blocks
8684	 * is less than the lba, then we've wrapped around and the block
8685	 * range is invalid anyway.
8686	 */
8687	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8688	 || ((lba + num_blocks) < lba)) {
8689		ctl_set_lba_out_of_range(ctsio);
8690		ctl_done((union ctl_io *)ctsio);
8691		return (CTL_RETVAL_COMPLETE);
8692	}
8693
8694	/*
8695	 * According to SBC-3, a transfer length of 0 is not an error.
8696	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8697	 * translates to 256 blocks for those commands.
8698	 */
8699	if (num_blocks == 0) {
8700		ctl_set_success(ctsio);
8701		ctl_done((union ctl_io *)ctsio);
8702		return (CTL_RETVAL_COMPLETE);
8703	}
8704
8705	/* Set FUA and/or DPO if caches are disabled. */
8706	if (isread) {
8707		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8708		    SCP_RCD) != 0)
8709			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8710	} else {
8711		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8712		    SCP_WCE) == 0)
8713			flags |= CTL_LLF_FUA;
8714	}
8715
8716	lbalen = (struct ctl_lba_len_flags *)
8717	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8718	lbalen->lba = lba;
8719	lbalen->len = num_blocks;
8720	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8721
8722	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8723	ctsio->kern_rel_offset = 0;
8724
8725	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8726
8727	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8728
8729	return (retval);
8730}
8731
8732static int
8733ctl_cnw_cont(union ctl_io *io)
8734{
8735	struct ctl_scsiio *ctsio;
8736	struct ctl_lun *lun;
8737	struct ctl_lba_len_flags *lbalen;
8738	int retval;
8739
8740	ctsio = &io->scsiio;
8741	ctsio->io_hdr.status = CTL_STATUS_NONE;
8742	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8743	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8744	lbalen = (struct ctl_lba_len_flags *)
8745	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8746	lbalen->flags &= ~CTL_LLF_COMPARE;
8747	lbalen->flags |= CTL_LLF_WRITE;
8748
8749	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8750	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8751	return (retval);
8752}
8753
8754int
8755ctl_cnw(struct ctl_scsiio *ctsio)
8756{
8757	struct ctl_lun *lun;
8758	struct ctl_lba_len_flags *lbalen;
8759	uint64_t lba;
8760	uint32_t num_blocks;
8761	int flags, retval;
8762
8763	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8764
8765	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8766
8767	flags = 0;
8768	retval = CTL_RETVAL_COMPLETE;
8769
8770	switch (ctsio->cdb[0]) {
8771	case COMPARE_AND_WRITE: {
8772		struct scsi_compare_and_write *cdb;
8773
8774		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8775		if (cdb->byte2 & SRW10_FUA)
8776			flags |= CTL_LLF_FUA;
8777		if (cdb->byte2 & SRW10_DPO)
8778			flags |= CTL_LLF_DPO;
8779		lba = scsi_8btou64(cdb->addr);
8780		num_blocks = cdb->length;
8781		break;
8782	}
8783	default:
8784		/*
8785		 * We got a command we don't support.  This shouldn't
8786		 * happen, commands should be filtered out above us.
8787		 */
8788		ctl_set_invalid_opcode(ctsio);
8789		ctl_done((union ctl_io *)ctsio);
8790
8791		return (CTL_RETVAL_COMPLETE);
8792		break; /* NOTREACHED */
8793	}
8794
8795	/*
8796	 * The first check is to make sure we're in bounds, the second
8797	 * check is to catch wrap-around problems.  If the lba + num blocks
8798	 * is less than the lba, then we've wrapped around and the block
8799	 * range is invalid anyway.
8800	 */
8801	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8802	 || ((lba + num_blocks) < lba)) {
8803		ctl_set_lba_out_of_range(ctsio);
8804		ctl_done((union ctl_io *)ctsio);
8805		return (CTL_RETVAL_COMPLETE);
8806	}
8807
8808	/*
8809	 * According to SBC-3, a transfer length of 0 is not an error.
8810	 */
8811	if (num_blocks == 0) {
8812		ctl_set_success(ctsio);
8813		ctl_done((union ctl_io *)ctsio);
8814		return (CTL_RETVAL_COMPLETE);
8815	}
8816
8817	/* Set FUA if write cache is disabled. */
8818	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8819	    SCP_WCE) == 0)
8820		flags |= CTL_LLF_FUA;
8821
8822	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8823	ctsio->kern_rel_offset = 0;
8824
8825	/*
8826	 * Set the IO_CONT flag, so that if this I/O gets passed to
8827	 * ctl_data_submit_done(), it'll get passed back to
8828	 * ctl_ctl_cnw_cont() for further processing.
8829	 */
8830	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8831	ctsio->io_cont = ctl_cnw_cont;
8832
8833	lbalen = (struct ctl_lba_len_flags *)
8834	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8835	lbalen->lba = lba;
8836	lbalen->len = num_blocks;
8837	lbalen->flags = CTL_LLF_COMPARE | flags;
8838
8839	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8840	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8841	return (retval);
8842}
8843
8844int
8845ctl_verify(struct ctl_scsiio *ctsio)
8846{
8847	struct ctl_lun *lun;
8848	struct ctl_lba_len_flags *lbalen;
8849	uint64_t lba;
8850	uint32_t num_blocks;
8851	int bytchk, flags;
8852	int retval;
8853
8854	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8855
8856	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8857
8858	bytchk = 0;
8859	flags = CTL_LLF_FUA;
8860	retval = CTL_RETVAL_COMPLETE;
8861
8862	switch (ctsio->cdb[0]) {
8863	case VERIFY_10: {
8864		struct scsi_verify_10 *cdb;
8865
8866		cdb = (struct scsi_verify_10 *)ctsio->cdb;
8867		if (cdb->byte2 & SVFY_BYTCHK)
8868			bytchk = 1;
8869		if (cdb->byte2 & SVFY_DPO)
8870			flags |= CTL_LLF_DPO;
8871		lba = scsi_4btoul(cdb->addr);
8872		num_blocks = scsi_2btoul(cdb->length);
8873		break;
8874	}
8875	case VERIFY_12: {
8876		struct scsi_verify_12 *cdb;
8877
8878		cdb = (struct scsi_verify_12 *)ctsio->cdb;
8879		if (cdb->byte2 & SVFY_BYTCHK)
8880			bytchk = 1;
8881		if (cdb->byte2 & SVFY_DPO)
8882			flags |= CTL_LLF_DPO;
8883		lba = scsi_4btoul(cdb->addr);
8884		num_blocks = scsi_4btoul(cdb->length);
8885		break;
8886	}
8887	case VERIFY_16: {
8888		struct scsi_rw_16 *cdb;
8889
8890		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8891		if (cdb->byte2 & SVFY_BYTCHK)
8892			bytchk = 1;
8893		if (cdb->byte2 & SVFY_DPO)
8894			flags |= CTL_LLF_DPO;
8895		lba = scsi_8btou64(cdb->addr);
8896		num_blocks = scsi_4btoul(cdb->length);
8897		break;
8898	}
8899	default:
8900		/*
8901		 * We got a command we don't support.  This shouldn't
8902		 * happen, commands should be filtered out above us.
8903		 */
8904		ctl_set_invalid_opcode(ctsio);
8905		ctl_done((union ctl_io *)ctsio);
8906		return (CTL_RETVAL_COMPLETE);
8907	}
8908
8909	/*
8910	 * The first check is to make sure we're in bounds, the second
8911	 * check is to catch wrap-around problems.  If the lba + num blocks
8912	 * is less than the lba, then we've wrapped around and the block
8913	 * range is invalid anyway.
8914	 */
8915	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8916	 || ((lba + num_blocks) < lba)) {
8917		ctl_set_lba_out_of_range(ctsio);
8918		ctl_done((union ctl_io *)ctsio);
8919		return (CTL_RETVAL_COMPLETE);
8920	}
8921
8922	/*
8923	 * According to SBC-3, a transfer length of 0 is not an error.
8924	 */
8925	if (num_blocks == 0) {
8926		ctl_set_success(ctsio);
8927		ctl_done((union ctl_io *)ctsio);
8928		return (CTL_RETVAL_COMPLETE);
8929	}
8930
8931	lbalen = (struct ctl_lba_len_flags *)
8932	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8933	lbalen->lba = lba;
8934	lbalen->len = num_blocks;
8935	if (bytchk) {
8936		lbalen->flags = CTL_LLF_COMPARE | flags;
8937		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8938	} else {
8939		lbalen->flags = CTL_LLF_VERIFY | flags;
8940		ctsio->kern_total_len = 0;
8941	}
8942	ctsio->kern_rel_offset = 0;
8943
8944	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
8945	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8946	return (retval);
8947}
8948
8949int
8950ctl_report_luns(struct ctl_scsiio *ctsio)
8951{
8952	struct ctl_softc *softc = control_softc;
8953	struct scsi_report_luns *cdb;
8954	struct scsi_report_luns_data *lun_data;
8955	struct ctl_lun *lun, *request_lun;
8956	struct ctl_port *port;
8957	int num_luns, retval;
8958	uint32_t alloc_len, lun_datalen;
8959	int num_filled, well_known;
8960	uint32_t initidx, targ_lun_id, lun_id;
8961
8962	retval = CTL_RETVAL_COMPLETE;
8963	well_known = 0;
8964
8965	cdb = (struct scsi_report_luns *)ctsio->cdb;
8966	port = ctl_io_port(&ctsio->io_hdr);
8967
8968	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
8969
8970	mtx_lock(&softc->ctl_lock);
8971	num_luns = 0;
8972	for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
8973		if (ctl_lun_map_from_port(port, targ_lun_id) < CTL_MAX_LUNS)
8974			num_luns++;
8975	}
8976	mtx_unlock(&softc->ctl_lock);
8977
8978	switch (cdb->select_report) {
8979	case RPL_REPORT_DEFAULT:
8980	case RPL_REPORT_ALL:
8981		break;
8982	case RPL_REPORT_WELLKNOWN:
8983		well_known = 1;
8984		num_luns = 0;
8985		break;
8986	default:
8987		ctl_set_invalid_field(ctsio,
8988				      /*sks_valid*/ 1,
8989				      /*command*/ 1,
8990				      /*field*/ 2,
8991				      /*bit_valid*/ 0,
8992				      /*bit*/ 0);
8993		ctl_done((union ctl_io *)ctsio);
8994		return (retval);
8995		break; /* NOTREACHED */
8996	}
8997
8998	alloc_len = scsi_4btoul(cdb->length);
8999	/*
9000	 * The initiator has to allocate at least 16 bytes for this request,
9001	 * so he can at least get the header and the first LUN.  Otherwise
9002	 * we reject the request (per SPC-3 rev 14, section 6.21).
9003	 */
9004	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9005	    sizeof(struct scsi_report_luns_lundata))) {
9006		ctl_set_invalid_field(ctsio,
9007				      /*sks_valid*/ 1,
9008				      /*command*/ 1,
9009				      /*field*/ 6,
9010				      /*bit_valid*/ 0,
9011				      /*bit*/ 0);
9012		ctl_done((union ctl_io *)ctsio);
9013		return (retval);
9014	}
9015
9016	request_lun = (struct ctl_lun *)
9017		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9018
9019	lun_datalen = sizeof(*lun_data) +
9020		(num_luns * sizeof(struct scsi_report_luns_lundata));
9021
9022	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9023	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9024	ctsio->kern_sg_entries = 0;
9025
9026	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9027
9028	mtx_lock(&softc->ctl_lock);
9029	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9030		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9031		if (lun_id >= CTL_MAX_LUNS)
9032			continue;
9033		lun = softc->ctl_luns[lun_id];
9034		if (lun == NULL)
9035			continue;
9036
9037		if (targ_lun_id <= 0xff) {
9038			/*
9039			 * Peripheral addressing method, bus number 0.
9040			 */
9041			lun_data->luns[num_filled].lundata[0] =
9042				RPL_LUNDATA_ATYP_PERIPH;
9043			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9044			num_filled++;
9045		} else if (targ_lun_id <= 0x3fff) {
9046			/*
9047			 * Flat addressing method.
9048			 */
9049			lun_data->luns[num_filled].lundata[0] =
9050				RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9051			lun_data->luns[num_filled].lundata[1] =
9052				(targ_lun_id & 0xff);
9053			num_filled++;
9054		} else if (targ_lun_id <= 0xffffff) {
9055			/*
9056			 * Extended flat addressing method.
9057			 */
9058			lun_data->luns[num_filled].lundata[0] =
9059			    RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9060			scsi_ulto3b(targ_lun_id,
9061			    &lun_data->luns[num_filled].lundata[1]);
9062			num_filled++;
9063		} else {
9064			printf("ctl_report_luns: bogus LUN number %jd, "
9065			       "skipping\n", (intmax_t)targ_lun_id);
9066		}
9067		/*
9068		 * According to SPC-3, rev 14 section 6.21:
9069		 *
9070		 * "The execution of a REPORT LUNS command to any valid and
9071		 * installed logical unit shall clear the REPORTED LUNS DATA
9072		 * HAS CHANGED unit attention condition for all logical
9073		 * units of that target with respect to the requesting
9074		 * initiator. A valid and installed logical unit is one
9075		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9076		 * INQUIRY data (see 6.4.2)."
9077		 *
9078		 * If request_lun is NULL, the LUN this report luns command
9079		 * was issued to is either disabled or doesn't exist. In that
9080		 * case, we shouldn't clear any pending lun change unit
9081		 * attention.
9082		 */
9083		if (request_lun != NULL) {
9084			mtx_lock(&lun->lun_lock);
9085			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9086			mtx_unlock(&lun->lun_lock);
9087		}
9088	}
9089	mtx_unlock(&softc->ctl_lock);
9090
9091	/*
9092	 * It's quite possible that we've returned fewer LUNs than we allocated
9093	 * space for.  Trim it.
9094	 */
9095	lun_datalen = sizeof(*lun_data) +
9096		(num_filled * sizeof(struct scsi_report_luns_lundata));
9097
9098	if (lun_datalen < alloc_len) {
9099		ctsio->residual = alloc_len - lun_datalen;
9100		ctsio->kern_data_len = lun_datalen;
9101		ctsio->kern_total_len = lun_datalen;
9102	} else {
9103		ctsio->residual = 0;
9104		ctsio->kern_data_len = alloc_len;
9105		ctsio->kern_total_len = alloc_len;
9106	}
9107	ctsio->kern_data_resid = 0;
9108	ctsio->kern_rel_offset = 0;
9109	ctsio->kern_sg_entries = 0;
9110
9111	/*
9112	 * We set this to the actual data length, regardless of how much
9113	 * space we actually have to return results.  If the user looks at
9114	 * this value, he'll know whether or not he allocated enough space
9115	 * and reissue the command if necessary.  We don't support well
9116	 * known logical units, so if the user asks for that, return none.
9117	 */
9118	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9119
9120	/*
9121	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9122	 * this request.
9123	 */
9124	ctl_set_success(ctsio);
9125	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9126	ctsio->be_move_done = ctl_config_move_done;
9127	ctl_datamove((union ctl_io *)ctsio);
9128	return (retval);
9129}
9130
9131int
9132ctl_request_sense(struct ctl_scsiio *ctsio)
9133{
9134	struct scsi_request_sense *cdb;
9135	struct scsi_sense_data *sense_ptr;
9136	struct ctl_softc *ctl_softc;
9137	struct ctl_lun *lun;
9138	uint32_t initidx;
9139	int have_error;
9140	scsi_sense_data_type sense_format;
9141	ctl_ua_type ua_type;
9142
9143	cdb = (struct scsi_request_sense *)ctsio->cdb;
9144
9145	ctl_softc = control_softc;
9146	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9147
9148	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9149
9150	/*
9151	 * Determine which sense format the user wants.
9152	 */
9153	if (cdb->byte2 & SRS_DESC)
9154		sense_format = SSD_TYPE_DESC;
9155	else
9156		sense_format = SSD_TYPE_FIXED;
9157
9158	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9159	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9160	ctsio->kern_sg_entries = 0;
9161
9162	/*
9163	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9164	 * larger than the largest allowed value for the length field in the
9165	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9166	 */
9167	ctsio->residual = 0;
9168	ctsio->kern_data_len = cdb->length;
9169	ctsio->kern_total_len = cdb->length;
9170
9171	ctsio->kern_data_resid = 0;
9172	ctsio->kern_rel_offset = 0;
9173	ctsio->kern_sg_entries = 0;
9174
9175	/*
9176	 * If we don't have a LUN, we don't have any pending sense.
9177	 */
9178	if (lun == NULL)
9179		goto no_sense;
9180
9181	have_error = 0;
9182	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9183	/*
9184	 * Check for pending sense, and then for pending unit attentions.
9185	 * Pending sense gets returned first, then pending unit attentions.
9186	 */
9187	mtx_lock(&lun->lun_lock);
9188#ifdef CTL_WITH_CA
9189	if (ctl_is_set(lun->have_ca, initidx)) {
9190		scsi_sense_data_type stored_format;
9191
9192		/*
9193		 * Check to see which sense format was used for the stored
9194		 * sense data.
9195		 */
9196		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9197
9198		/*
9199		 * If the user requested a different sense format than the
9200		 * one we stored, then we need to convert it to the other
9201		 * format.  If we're going from descriptor to fixed format
9202		 * sense data, we may lose things in translation, depending
9203		 * on what options were used.
9204		 *
9205		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9206		 * for some reason we'll just copy it out as-is.
9207		 */
9208		if ((stored_format == SSD_TYPE_FIXED)
9209		 && (sense_format == SSD_TYPE_DESC))
9210			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9211			    &lun->pending_sense[initidx],
9212			    (struct scsi_sense_data_desc *)sense_ptr);
9213		else if ((stored_format == SSD_TYPE_DESC)
9214		      && (sense_format == SSD_TYPE_FIXED))
9215			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9216			    &lun->pending_sense[initidx],
9217			    (struct scsi_sense_data_fixed *)sense_ptr);
9218		else
9219			memcpy(sense_ptr, &lun->pending_sense[initidx],
9220			       MIN(sizeof(*sense_ptr),
9221			       sizeof(lun->pending_sense[initidx])));
9222
9223		ctl_clear_mask(lun->have_ca, initidx);
9224		have_error = 1;
9225	} else
9226#endif
9227	{
9228		ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9229		if (ua_type != CTL_UA_NONE)
9230			have_error = 1;
9231		if (ua_type == CTL_UA_LUN_CHANGE) {
9232			mtx_unlock(&lun->lun_lock);
9233			mtx_lock(&ctl_softc->ctl_lock);
9234			ctl_clr_ua_allluns(ctl_softc, initidx, ua_type);
9235			mtx_unlock(&ctl_softc->ctl_lock);
9236			mtx_lock(&lun->lun_lock);
9237		}
9238
9239	}
9240	mtx_unlock(&lun->lun_lock);
9241
9242	/*
9243	 * We already have a pending error, return it.
9244	 */
9245	if (have_error != 0) {
9246		/*
9247		 * We report the SCSI status as OK, since the status of the
9248		 * request sense command itself is OK.
9249		 * We report 0 for the sense length, because we aren't doing
9250		 * autosense in this case.  We're reporting sense as
9251		 * parameter data.
9252		 */
9253		ctl_set_success(ctsio);
9254		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9255		ctsio->be_move_done = ctl_config_move_done;
9256		ctl_datamove((union ctl_io *)ctsio);
9257		return (CTL_RETVAL_COMPLETE);
9258	}
9259
9260no_sense:
9261
9262	/*
9263	 * No sense information to report, so we report that everything is
9264	 * okay.
9265	 */
9266	ctl_set_sense_data(sense_ptr,
9267			   lun,
9268			   sense_format,
9269			   /*current_error*/ 1,
9270			   /*sense_key*/ SSD_KEY_NO_SENSE,
9271			   /*asc*/ 0x00,
9272			   /*ascq*/ 0x00,
9273			   SSD_ELEM_NONE);
9274
9275	/*
9276	 * We report 0 for the sense length, because we aren't doing
9277	 * autosense in this case.  We're reporting sense as parameter data.
9278	 */
9279	ctl_set_success(ctsio);
9280	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9281	ctsio->be_move_done = ctl_config_move_done;
9282	ctl_datamove((union ctl_io *)ctsio);
9283	return (CTL_RETVAL_COMPLETE);
9284}
9285
9286int
9287ctl_tur(struct ctl_scsiio *ctsio)
9288{
9289
9290	CTL_DEBUG_PRINT(("ctl_tur\n"));
9291
9292	ctl_set_success(ctsio);
9293	ctl_done((union ctl_io *)ctsio);
9294
9295	return (CTL_RETVAL_COMPLETE);
9296}
9297
9298/*
9299 * SCSI VPD page 0x00, the Supported VPD Pages page.
9300 */
9301static int
9302ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9303{
9304	struct scsi_vpd_supported_pages *pages;
9305	int sup_page_size;
9306	struct ctl_lun *lun;
9307	int p;
9308
9309	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9310
9311	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9312	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9313	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9314	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9315	ctsio->kern_sg_entries = 0;
9316
9317	if (sup_page_size < alloc_len) {
9318		ctsio->residual = alloc_len - sup_page_size;
9319		ctsio->kern_data_len = sup_page_size;
9320		ctsio->kern_total_len = sup_page_size;
9321	} else {
9322		ctsio->residual = 0;
9323		ctsio->kern_data_len = alloc_len;
9324		ctsio->kern_total_len = alloc_len;
9325	}
9326	ctsio->kern_data_resid = 0;
9327	ctsio->kern_rel_offset = 0;
9328	ctsio->kern_sg_entries = 0;
9329
9330	/*
9331	 * The control device is always connected.  The disk device, on the
9332	 * other hand, may not be online all the time.  Need to change this
9333	 * to figure out whether the disk device is actually online or not.
9334	 */
9335	if (lun != NULL)
9336		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9337				lun->be_lun->lun_type;
9338	else
9339		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9340
9341	p = 0;
9342	/* Supported VPD pages */
9343	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9344	/* Serial Number */
9345	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9346	/* Device Identification */
9347	pages->page_list[p++] = SVPD_DEVICE_ID;
9348	/* Extended INQUIRY Data */
9349	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9350	/* Mode Page Policy */
9351	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9352	/* SCSI Ports */
9353	pages->page_list[p++] = SVPD_SCSI_PORTS;
9354	/* Third-party Copy */
9355	pages->page_list[p++] = SVPD_SCSI_TPC;
9356	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9357		/* Block limits */
9358		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9359		/* Block Device Characteristics */
9360		pages->page_list[p++] = SVPD_BDC;
9361		/* Logical Block Provisioning */
9362		pages->page_list[p++] = SVPD_LBP;
9363	}
9364	pages->length = p;
9365
9366	ctl_set_success(ctsio);
9367	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9368	ctsio->be_move_done = ctl_config_move_done;
9369	ctl_datamove((union ctl_io *)ctsio);
9370	return (CTL_RETVAL_COMPLETE);
9371}
9372
9373/*
9374 * SCSI VPD page 0x80, the Unit Serial Number page.
9375 */
9376static int
9377ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9378{
9379	struct scsi_vpd_unit_serial_number *sn_ptr;
9380	struct ctl_lun *lun;
9381	int data_len;
9382
9383	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9384
9385	data_len = 4 + CTL_SN_LEN;
9386	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9387	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9388	if (data_len < alloc_len) {
9389		ctsio->residual = alloc_len - data_len;
9390		ctsio->kern_data_len = data_len;
9391		ctsio->kern_total_len = data_len;
9392	} else {
9393		ctsio->residual = 0;
9394		ctsio->kern_data_len = alloc_len;
9395		ctsio->kern_total_len = alloc_len;
9396	}
9397	ctsio->kern_data_resid = 0;
9398	ctsio->kern_rel_offset = 0;
9399	ctsio->kern_sg_entries = 0;
9400
9401	/*
9402	 * The control device is always connected.  The disk device, on the
9403	 * other hand, may not be online all the time.  Need to change this
9404	 * to figure out whether the disk device is actually online or not.
9405	 */
9406	if (lun != NULL)
9407		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9408				  lun->be_lun->lun_type;
9409	else
9410		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9411
9412	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9413	sn_ptr->length = CTL_SN_LEN;
9414	/*
9415	 * If we don't have a LUN, we just leave the serial number as
9416	 * all spaces.
9417	 */
9418	if (lun != NULL) {
9419		strncpy((char *)sn_ptr->serial_num,
9420			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9421	} else
9422		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9423
9424	ctl_set_success(ctsio);
9425	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9426	ctsio->be_move_done = ctl_config_move_done;
9427	ctl_datamove((union ctl_io *)ctsio);
9428	return (CTL_RETVAL_COMPLETE);
9429}
9430
9431
9432/*
9433 * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9434 */
9435static int
9436ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9437{
9438	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9439	struct ctl_lun *lun;
9440	int data_len;
9441
9442	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9443
9444	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9445	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9446	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9447	ctsio->kern_sg_entries = 0;
9448
9449	if (data_len < alloc_len) {
9450		ctsio->residual = alloc_len - data_len;
9451		ctsio->kern_data_len = data_len;
9452		ctsio->kern_total_len = data_len;
9453	} else {
9454		ctsio->residual = 0;
9455		ctsio->kern_data_len = alloc_len;
9456		ctsio->kern_total_len = alloc_len;
9457	}
9458	ctsio->kern_data_resid = 0;
9459	ctsio->kern_rel_offset = 0;
9460	ctsio->kern_sg_entries = 0;
9461
9462	/*
9463	 * The control device is always connected.  The disk device, on the
9464	 * other hand, may not be online all the time.
9465	 */
9466	if (lun != NULL)
9467		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9468				     lun->be_lun->lun_type;
9469	else
9470		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9471	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9472	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9473	/*
9474	 * We support head of queue, ordered and simple tags.
9475	 */
9476	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9477	/*
9478	 * Volatile cache supported.
9479	 */
9480	eid_ptr->flags3 = SVPD_EID_V_SUP;
9481
9482	/*
9483	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9484	 * attention for a particular IT nexus on all LUNs once we report
9485	 * it to that nexus once.  This bit is required as of SPC-4.
9486	 */
9487	eid_ptr->flags4 = SVPD_EID_LUICLT;
9488
9489	/*
9490	 * XXX KDM in order to correctly answer this, we would need
9491	 * information from the SIM to determine how much sense data it
9492	 * can send.  So this would really be a path inquiry field, most
9493	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9494	 * but the hardware may or may not be able to support that much.
9495	 * 0 just means that the maximum sense data length is not reported.
9496	 */
9497	eid_ptr->max_sense_length = 0;
9498
9499	ctl_set_success(ctsio);
9500	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9501	ctsio->be_move_done = ctl_config_move_done;
9502	ctl_datamove((union ctl_io *)ctsio);
9503	return (CTL_RETVAL_COMPLETE);
9504}
9505
9506static int
9507ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9508{
9509	struct scsi_vpd_mode_page_policy *mpp_ptr;
9510	struct ctl_lun *lun;
9511	int data_len;
9512
9513	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9514
9515	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9516	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9517
9518	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9519	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9520	ctsio->kern_sg_entries = 0;
9521
9522	if (data_len < alloc_len) {
9523		ctsio->residual = alloc_len - data_len;
9524		ctsio->kern_data_len = data_len;
9525		ctsio->kern_total_len = data_len;
9526	} else {
9527		ctsio->residual = 0;
9528		ctsio->kern_data_len = alloc_len;
9529		ctsio->kern_total_len = alloc_len;
9530	}
9531	ctsio->kern_data_resid = 0;
9532	ctsio->kern_rel_offset = 0;
9533	ctsio->kern_sg_entries = 0;
9534
9535	/*
9536	 * The control device is always connected.  The disk device, on the
9537	 * other hand, may not be online all the time.
9538	 */
9539	if (lun != NULL)
9540		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9541				     lun->be_lun->lun_type;
9542	else
9543		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9544	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9545	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9546	mpp_ptr->descr[0].page_code = 0x3f;
9547	mpp_ptr->descr[0].subpage_code = 0xff;
9548	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9549
9550	ctl_set_success(ctsio);
9551	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9552	ctsio->be_move_done = ctl_config_move_done;
9553	ctl_datamove((union ctl_io *)ctsio);
9554	return (CTL_RETVAL_COMPLETE);
9555}
9556
9557/*
9558 * SCSI VPD page 0x83, the Device Identification page.
9559 */
9560static int
9561ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9562{
9563	struct scsi_vpd_device_id *devid_ptr;
9564	struct scsi_vpd_id_descriptor *desc;
9565	struct ctl_softc *softc;
9566	struct ctl_lun *lun;
9567	struct ctl_port *port;
9568	int data_len;
9569	uint8_t proto;
9570
9571	softc = control_softc;
9572
9573	port = ctl_io_port(&ctsio->io_hdr);
9574	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9575
9576	data_len = sizeof(struct scsi_vpd_device_id) +
9577	    sizeof(struct scsi_vpd_id_descriptor) +
9578		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9579	    sizeof(struct scsi_vpd_id_descriptor) +
9580		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9581	if (lun && lun->lun_devid)
9582		data_len += lun->lun_devid->len;
9583	if (port && port->port_devid)
9584		data_len += port->port_devid->len;
9585	if (port && port->target_devid)
9586		data_len += port->target_devid->len;
9587
9588	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9589	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9590	ctsio->kern_sg_entries = 0;
9591
9592	if (data_len < alloc_len) {
9593		ctsio->residual = alloc_len - data_len;
9594		ctsio->kern_data_len = data_len;
9595		ctsio->kern_total_len = data_len;
9596	} else {
9597		ctsio->residual = 0;
9598		ctsio->kern_data_len = alloc_len;
9599		ctsio->kern_total_len = alloc_len;
9600	}
9601	ctsio->kern_data_resid = 0;
9602	ctsio->kern_rel_offset = 0;
9603	ctsio->kern_sg_entries = 0;
9604
9605	/*
9606	 * The control device is always connected.  The disk device, on the
9607	 * other hand, may not be online all the time.
9608	 */
9609	if (lun != NULL)
9610		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9611				     lun->be_lun->lun_type;
9612	else
9613		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9614	devid_ptr->page_code = SVPD_DEVICE_ID;
9615	scsi_ulto2b(data_len - 4, devid_ptr->length);
9616
9617	if (port && port->port_type == CTL_PORT_FC)
9618		proto = SCSI_PROTO_FC << 4;
9619	else if (port && port->port_type == CTL_PORT_ISCSI)
9620		proto = SCSI_PROTO_ISCSI << 4;
9621	else
9622		proto = SCSI_PROTO_SPI << 4;
9623	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9624
9625	/*
9626	 * We're using a LUN association here.  i.e., this device ID is a
9627	 * per-LUN identifier.
9628	 */
9629	if (lun && lun->lun_devid) {
9630		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9631		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9632		    lun->lun_devid->len);
9633	}
9634
9635	/*
9636	 * This is for the WWPN which is a port association.
9637	 */
9638	if (port && port->port_devid) {
9639		memcpy(desc, port->port_devid->data, port->port_devid->len);
9640		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9641		    port->port_devid->len);
9642	}
9643
9644	/*
9645	 * This is for the Relative Target Port(type 4h) identifier
9646	 */
9647	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9648	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9649	    SVPD_ID_TYPE_RELTARG;
9650	desc->length = 4;
9651	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9652	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9653	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9654
9655	/*
9656	 * This is for the Target Port Group(type 5h) identifier
9657	 */
9658	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9659	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9660	    SVPD_ID_TYPE_TPORTGRP;
9661	desc->length = 4;
9662	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / softc->port_cnt + 1,
9663	    &desc->identifier[2]);
9664	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9665	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9666
9667	/*
9668	 * This is for the Target identifier
9669	 */
9670	if (port && port->target_devid) {
9671		memcpy(desc, port->target_devid->data, port->target_devid->len);
9672	}
9673
9674	ctl_set_success(ctsio);
9675	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9676	ctsio->be_move_done = ctl_config_move_done;
9677	ctl_datamove((union ctl_io *)ctsio);
9678	return (CTL_RETVAL_COMPLETE);
9679}
9680
9681static int
9682ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9683{
9684	struct ctl_softc *softc = control_softc;
9685	struct scsi_vpd_scsi_ports *sp;
9686	struct scsi_vpd_port_designation *pd;
9687	struct scsi_vpd_port_designation_cont *pdc;
9688	struct ctl_lun *lun;
9689	struct ctl_port *port;
9690	int data_len, num_target_ports, iid_len, id_len;
9691
9692	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9693
9694	num_target_ports = 0;
9695	iid_len = 0;
9696	id_len = 0;
9697	mtx_lock(&softc->ctl_lock);
9698	STAILQ_FOREACH(port, &softc->port_list, links) {
9699		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9700			continue;
9701		if (lun != NULL &&
9702		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9703			continue;
9704		num_target_ports++;
9705		if (port->init_devid)
9706			iid_len += port->init_devid->len;
9707		if (port->port_devid)
9708			id_len += port->port_devid->len;
9709	}
9710	mtx_unlock(&softc->ctl_lock);
9711
9712	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9713	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9714	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9715	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9716	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9717	ctsio->kern_sg_entries = 0;
9718
9719	if (data_len < alloc_len) {
9720		ctsio->residual = alloc_len - data_len;
9721		ctsio->kern_data_len = data_len;
9722		ctsio->kern_total_len = data_len;
9723	} else {
9724		ctsio->residual = 0;
9725		ctsio->kern_data_len = alloc_len;
9726		ctsio->kern_total_len = alloc_len;
9727	}
9728	ctsio->kern_data_resid = 0;
9729	ctsio->kern_rel_offset = 0;
9730	ctsio->kern_sg_entries = 0;
9731
9732	/*
9733	 * The control device is always connected.  The disk device, on the
9734	 * other hand, may not be online all the time.  Need to change this
9735	 * to figure out whether the disk device is actually online or not.
9736	 */
9737	if (lun != NULL)
9738		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9739				  lun->be_lun->lun_type;
9740	else
9741		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9742
9743	sp->page_code = SVPD_SCSI_PORTS;
9744	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9745	    sp->page_length);
9746	pd = &sp->design[0];
9747
9748	mtx_lock(&softc->ctl_lock);
9749	STAILQ_FOREACH(port, &softc->port_list, links) {
9750		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9751			continue;
9752		if (lun != NULL &&
9753		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9754			continue;
9755		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9756		if (port->init_devid) {
9757			iid_len = port->init_devid->len;
9758			memcpy(pd->initiator_transportid,
9759			    port->init_devid->data, port->init_devid->len);
9760		} else
9761			iid_len = 0;
9762		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9763		pdc = (struct scsi_vpd_port_designation_cont *)
9764		    (&pd->initiator_transportid[iid_len]);
9765		if (port->port_devid) {
9766			id_len = port->port_devid->len;
9767			memcpy(pdc->target_port_descriptors,
9768			    port->port_devid->data, port->port_devid->len);
9769		} else
9770			id_len = 0;
9771		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9772		pd = (struct scsi_vpd_port_designation *)
9773		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9774	}
9775	mtx_unlock(&softc->ctl_lock);
9776
9777	ctl_set_success(ctsio);
9778	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9779	ctsio->be_move_done = ctl_config_move_done;
9780	ctl_datamove((union ctl_io *)ctsio);
9781	return (CTL_RETVAL_COMPLETE);
9782}
9783
9784static int
9785ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9786{
9787	struct scsi_vpd_block_limits *bl_ptr;
9788	struct ctl_lun *lun;
9789	int bs;
9790
9791	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9792
9793	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9794	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9795	ctsio->kern_sg_entries = 0;
9796
9797	if (sizeof(*bl_ptr) < alloc_len) {
9798		ctsio->residual = alloc_len - sizeof(*bl_ptr);
9799		ctsio->kern_data_len = sizeof(*bl_ptr);
9800		ctsio->kern_total_len = sizeof(*bl_ptr);
9801	} else {
9802		ctsio->residual = 0;
9803		ctsio->kern_data_len = alloc_len;
9804		ctsio->kern_total_len = alloc_len;
9805	}
9806	ctsio->kern_data_resid = 0;
9807	ctsio->kern_rel_offset = 0;
9808	ctsio->kern_sg_entries = 0;
9809
9810	/*
9811	 * The control device is always connected.  The disk device, on the
9812	 * other hand, may not be online all the time.  Need to change this
9813	 * to figure out whether the disk device is actually online or not.
9814	 */
9815	if (lun != NULL)
9816		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9817				  lun->be_lun->lun_type;
9818	else
9819		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9820
9821	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9822	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9823	bl_ptr->max_cmp_write_len = 0xff;
9824	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9825	if (lun != NULL) {
9826		bs = lun->be_lun->blocksize;
9827		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9828		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9829			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
9830			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
9831			if (lun->be_lun->ublockexp != 0) {
9832				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9833				    bl_ptr->opt_unmap_grain);
9834				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9835				    bl_ptr->unmap_grain_align);
9836			}
9837		}
9838		scsi_ulto4b(lun->be_lun->atomicblock,
9839		    bl_ptr->max_atomic_transfer_length);
9840		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9841		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9842	}
9843	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
9844
9845	ctl_set_success(ctsio);
9846	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9847	ctsio->be_move_done = ctl_config_move_done;
9848	ctl_datamove((union ctl_io *)ctsio);
9849	return (CTL_RETVAL_COMPLETE);
9850}
9851
9852static int
9853ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9854{
9855	struct scsi_vpd_block_device_characteristics *bdc_ptr;
9856	struct ctl_lun *lun;
9857	const char *value;
9858	u_int i;
9859
9860	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9861
9862	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9863	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9864	ctsio->kern_sg_entries = 0;
9865
9866	if (sizeof(*bdc_ptr) < alloc_len) {
9867		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
9868		ctsio->kern_data_len = sizeof(*bdc_ptr);
9869		ctsio->kern_total_len = sizeof(*bdc_ptr);
9870	} else {
9871		ctsio->residual = 0;
9872		ctsio->kern_data_len = alloc_len;
9873		ctsio->kern_total_len = alloc_len;
9874	}
9875	ctsio->kern_data_resid = 0;
9876	ctsio->kern_rel_offset = 0;
9877	ctsio->kern_sg_entries = 0;
9878
9879	/*
9880	 * The control device is always connected.  The disk device, on the
9881	 * other hand, may not be online all the time.  Need to change this
9882	 * to figure out whether the disk device is actually online or not.
9883	 */
9884	if (lun != NULL)
9885		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9886				  lun->be_lun->lun_type;
9887	else
9888		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9889	bdc_ptr->page_code = SVPD_BDC;
9890	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9891	if (lun != NULL &&
9892	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
9893		i = strtol(value, NULL, 0);
9894	else
9895		i = CTL_DEFAULT_ROTATION_RATE;
9896	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9897	if (lun != NULL &&
9898	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
9899		i = strtol(value, NULL, 0);
9900	else
9901		i = 0;
9902	bdc_ptr->wab_wac_ff = (i & 0x0f);
9903	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9904
9905	ctl_set_success(ctsio);
9906	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9907	ctsio->be_move_done = ctl_config_move_done;
9908	ctl_datamove((union ctl_io *)ctsio);
9909	return (CTL_RETVAL_COMPLETE);
9910}
9911
9912static int
9913ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9914{
9915	struct scsi_vpd_logical_block_prov *lbp_ptr;
9916	struct ctl_lun *lun;
9917
9918	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9919
9920	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9921	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9922	ctsio->kern_sg_entries = 0;
9923
9924	if (sizeof(*lbp_ptr) < alloc_len) {
9925		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
9926		ctsio->kern_data_len = sizeof(*lbp_ptr);
9927		ctsio->kern_total_len = sizeof(*lbp_ptr);
9928	} else {
9929		ctsio->residual = 0;
9930		ctsio->kern_data_len = alloc_len;
9931		ctsio->kern_total_len = alloc_len;
9932	}
9933	ctsio->kern_data_resid = 0;
9934	ctsio->kern_rel_offset = 0;
9935	ctsio->kern_sg_entries = 0;
9936
9937	/*
9938	 * The control device is always connected.  The disk device, on the
9939	 * other hand, may not be online all the time.  Need to change this
9940	 * to figure out whether the disk device is actually online or not.
9941	 */
9942	if (lun != NULL)
9943		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9944				  lun->be_lun->lun_type;
9945	else
9946		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9947
9948	lbp_ptr->page_code = SVPD_LBP;
9949	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
9950	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
9951	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9952		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
9953		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
9954		lbp_ptr->prov_type = SVPD_LBP_THIN;
9955	}
9956
9957	ctl_set_success(ctsio);
9958	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9959	ctsio->be_move_done = ctl_config_move_done;
9960	ctl_datamove((union ctl_io *)ctsio);
9961	return (CTL_RETVAL_COMPLETE);
9962}
9963
9964/*
9965 * INQUIRY with the EVPD bit set.
9966 */
9967static int
9968ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
9969{
9970	struct ctl_lun *lun;
9971	struct scsi_inquiry *cdb;
9972	int alloc_len, retval;
9973
9974	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9975	cdb = (struct scsi_inquiry *)ctsio->cdb;
9976	alloc_len = scsi_2btoul(cdb->length);
9977
9978	switch (cdb->page_code) {
9979	case SVPD_SUPPORTED_PAGES:
9980		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
9981		break;
9982	case SVPD_UNIT_SERIAL_NUMBER:
9983		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
9984		break;
9985	case SVPD_DEVICE_ID:
9986		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
9987		break;
9988	case SVPD_EXTENDED_INQUIRY_DATA:
9989		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
9990		break;
9991	case SVPD_MODE_PAGE_POLICY:
9992		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
9993		break;
9994	case SVPD_SCSI_PORTS:
9995		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
9996		break;
9997	case SVPD_SCSI_TPC:
9998		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
9999		break;
10000	case SVPD_BLOCK_LIMITS:
10001		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10002			goto err;
10003		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10004		break;
10005	case SVPD_BDC:
10006		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10007			goto err;
10008		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10009		break;
10010	case SVPD_LBP:
10011		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10012			goto err;
10013		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10014		break;
10015	default:
10016err:
10017		ctl_set_invalid_field(ctsio,
10018				      /*sks_valid*/ 1,
10019				      /*command*/ 1,
10020				      /*field*/ 2,
10021				      /*bit_valid*/ 0,
10022				      /*bit*/ 0);
10023		ctl_done((union ctl_io *)ctsio);
10024		retval = CTL_RETVAL_COMPLETE;
10025		break;
10026	}
10027
10028	return (retval);
10029}
10030
10031/*
10032 * Standard INQUIRY data.
10033 */
10034static int
10035ctl_inquiry_std(struct ctl_scsiio *ctsio)
10036{
10037	struct scsi_inquiry_data *inq_ptr;
10038	struct scsi_inquiry *cdb;
10039	struct ctl_softc *softc;
10040	struct ctl_port *port;
10041	struct ctl_lun *lun;
10042	char *val;
10043	uint32_t alloc_len, data_len;
10044	ctl_port_type port_type;
10045
10046	softc = control_softc;
10047
10048	/*
10049	 * Figure out whether we're talking to a Fibre Channel port or not.
10050	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10051	 * SCSI front ends.
10052	 */
10053	port = ctl_io_port(&ctsio->io_hdr);
10054	if (port != NULL)
10055		port_type = port->port_type;
10056	else
10057		port_type = CTL_PORT_SCSI;
10058	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10059		port_type = CTL_PORT_SCSI;
10060
10061	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10062	cdb = (struct scsi_inquiry *)ctsio->cdb;
10063	alloc_len = scsi_2btoul(cdb->length);
10064
10065	/*
10066	 * We malloc the full inquiry data size here and fill it
10067	 * in.  If the user only asks for less, we'll give him
10068	 * that much.
10069	 */
10070	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10071	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10072	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10073	ctsio->kern_sg_entries = 0;
10074	ctsio->kern_data_resid = 0;
10075	ctsio->kern_rel_offset = 0;
10076
10077	if (data_len < alloc_len) {
10078		ctsio->residual = alloc_len - data_len;
10079		ctsio->kern_data_len = data_len;
10080		ctsio->kern_total_len = data_len;
10081	} else {
10082		ctsio->residual = 0;
10083		ctsio->kern_data_len = alloc_len;
10084		ctsio->kern_total_len = alloc_len;
10085	}
10086
10087	if (lun != NULL) {
10088		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10089		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10090			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10091			    lun->be_lun->lun_type;
10092		} else {
10093			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10094			    lun->be_lun->lun_type;
10095		}
10096	} else
10097		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10098
10099	/* RMB in byte 2 is 0 */
10100	inq_ptr->version = SCSI_REV_SPC4;
10101
10102	/*
10103	 * According to SAM-3, even if a device only supports a single
10104	 * level of LUN addressing, it should still set the HISUP bit:
10105	 *
10106	 * 4.9.1 Logical unit numbers overview
10107	 *
10108	 * All logical unit number formats described in this standard are
10109	 * hierarchical in structure even when only a single level in that
10110	 * hierarchy is used. The HISUP bit shall be set to one in the
10111	 * standard INQUIRY data (see SPC-2) when any logical unit number
10112	 * format described in this standard is used.  Non-hierarchical
10113	 * formats are outside the scope of this standard.
10114	 *
10115	 * Therefore we set the HiSup bit here.
10116	 *
10117	 * The reponse format is 2, per SPC-3.
10118	 */
10119	inq_ptr->response_format = SID_HiSup | 2;
10120
10121	inq_ptr->additional_length = data_len -
10122	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10123	CTL_DEBUG_PRINT(("additional_length = %d\n",
10124			 inq_ptr->additional_length));
10125
10126	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10127	/* 16 bit addressing */
10128	if (port_type == CTL_PORT_SCSI)
10129		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10130	/* XXX set the SID_MultiP bit here if we're actually going to
10131	   respond on multiple ports */
10132	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10133
10134	/* 16 bit data bus, synchronous transfers */
10135	if (port_type == CTL_PORT_SCSI)
10136		inq_ptr->flags = SID_WBus16 | SID_Sync;
10137	/*
10138	 * XXX KDM do we want to support tagged queueing on the control
10139	 * device at all?
10140	 */
10141	if ((lun == NULL)
10142	 || (lun->be_lun->lun_type != T_PROCESSOR))
10143		inq_ptr->flags |= SID_CmdQue;
10144	/*
10145	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10146	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10147	 * name and 4 bytes for the revision.
10148	 */
10149	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10150	    "vendor")) == NULL) {
10151		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10152	} else {
10153		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10154		strncpy(inq_ptr->vendor, val,
10155		    min(sizeof(inq_ptr->vendor), strlen(val)));
10156	}
10157	if (lun == NULL) {
10158		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10159		    sizeof(inq_ptr->product));
10160	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10161		switch (lun->be_lun->lun_type) {
10162		case T_DIRECT:
10163			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10164			    sizeof(inq_ptr->product));
10165			break;
10166		case T_PROCESSOR:
10167			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10168			    sizeof(inq_ptr->product));
10169			break;
10170		default:
10171			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10172			    sizeof(inq_ptr->product));
10173			break;
10174		}
10175	} else {
10176		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10177		strncpy(inq_ptr->product, val,
10178		    min(sizeof(inq_ptr->product), strlen(val)));
10179	}
10180
10181	/*
10182	 * XXX make this a macro somewhere so it automatically gets
10183	 * incremented when we make changes.
10184	 */
10185	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10186	    "revision")) == NULL) {
10187		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10188	} else {
10189		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10190		strncpy(inq_ptr->revision, val,
10191		    min(sizeof(inq_ptr->revision), strlen(val)));
10192	}
10193
10194	/*
10195	 * For parallel SCSI, we support double transition and single
10196	 * transition clocking.  We also support QAS (Quick Arbitration
10197	 * and Selection) and Information Unit transfers on both the
10198	 * control and array devices.
10199	 */
10200	if (port_type == CTL_PORT_SCSI)
10201		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10202				    SID_SPI_IUS;
10203
10204	/* SAM-5 (no version claimed) */
10205	scsi_ulto2b(0x00A0, inq_ptr->version1);
10206	/* SPC-4 (no version claimed) */
10207	scsi_ulto2b(0x0460, inq_ptr->version2);
10208	if (port_type == CTL_PORT_FC) {
10209		/* FCP-2 ANSI INCITS.350:2003 */
10210		scsi_ulto2b(0x0917, inq_ptr->version3);
10211	} else if (port_type == CTL_PORT_SCSI) {
10212		/* SPI-4 ANSI INCITS.362:200x */
10213		scsi_ulto2b(0x0B56, inq_ptr->version3);
10214	} else if (port_type == CTL_PORT_ISCSI) {
10215		/* iSCSI (no version claimed) */
10216		scsi_ulto2b(0x0960, inq_ptr->version3);
10217	} else if (port_type == CTL_PORT_SAS) {
10218		/* SAS (no version claimed) */
10219		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10220	}
10221
10222	if (lun == NULL) {
10223		/* SBC-4 (no version claimed) */
10224		scsi_ulto2b(0x0600, inq_ptr->version4);
10225	} else {
10226		switch (lun->be_lun->lun_type) {
10227		case T_DIRECT:
10228			/* SBC-4 (no version claimed) */
10229			scsi_ulto2b(0x0600, inq_ptr->version4);
10230			break;
10231		case T_PROCESSOR:
10232		default:
10233			break;
10234		}
10235	}
10236
10237	ctl_set_success(ctsio);
10238	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10239	ctsio->be_move_done = ctl_config_move_done;
10240	ctl_datamove((union ctl_io *)ctsio);
10241	return (CTL_RETVAL_COMPLETE);
10242}
10243
10244int
10245ctl_inquiry(struct ctl_scsiio *ctsio)
10246{
10247	struct scsi_inquiry *cdb;
10248	int retval;
10249
10250	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10251
10252	cdb = (struct scsi_inquiry *)ctsio->cdb;
10253	if (cdb->byte2 & SI_EVPD)
10254		retval = ctl_inquiry_evpd(ctsio);
10255	else if (cdb->page_code == 0)
10256		retval = ctl_inquiry_std(ctsio);
10257	else {
10258		ctl_set_invalid_field(ctsio,
10259				      /*sks_valid*/ 1,
10260				      /*command*/ 1,
10261				      /*field*/ 2,
10262				      /*bit_valid*/ 0,
10263				      /*bit*/ 0);
10264		ctl_done((union ctl_io *)ctsio);
10265		return (CTL_RETVAL_COMPLETE);
10266	}
10267
10268	return (retval);
10269}
10270
10271/*
10272 * For known CDB types, parse the LBA and length.
10273 */
10274static int
10275ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10276{
10277	if (io->io_hdr.io_type != CTL_IO_SCSI)
10278		return (1);
10279
10280	switch (io->scsiio.cdb[0]) {
10281	case COMPARE_AND_WRITE: {
10282		struct scsi_compare_and_write *cdb;
10283
10284		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10285
10286		*lba = scsi_8btou64(cdb->addr);
10287		*len = cdb->length;
10288		break;
10289	}
10290	case READ_6:
10291	case WRITE_6: {
10292		struct scsi_rw_6 *cdb;
10293
10294		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10295
10296		*lba = scsi_3btoul(cdb->addr);
10297		/* only 5 bits are valid in the most significant address byte */
10298		*lba &= 0x1fffff;
10299		*len = cdb->length;
10300		break;
10301	}
10302	case READ_10:
10303	case WRITE_10: {
10304		struct scsi_rw_10 *cdb;
10305
10306		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10307
10308		*lba = scsi_4btoul(cdb->addr);
10309		*len = scsi_2btoul(cdb->length);
10310		break;
10311	}
10312	case WRITE_VERIFY_10: {
10313		struct scsi_write_verify_10 *cdb;
10314
10315		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10316
10317		*lba = scsi_4btoul(cdb->addr);
10318		*len = scsi_2btoul(cdb->length);
10319		break;
10320	}
10321	case READ_12:
10322	case WRITE_12: {
10323		struct scsi_rw_12 *cdb;
10324
10325		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10326
10327		*lba = scsi_4btoul(cdb->addr);
10328		*len = scsi_4btoul(cdb->length);
10329		break;
10330	}
10331	case WRITE_VERIFY_12: {
10332		struct scsi_write_verify_12 *cdb;
10333
10334		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10335
10336		*lba = scsi_4btoul(cdb->addr);
10337		*len = scsi_4btoul(cdb->length);
10338		break;
10339	}
10340	case READ_16:
10341	case WRITE_16:
10342	case WRITE_ATOMIC_16: {
10343		struct scsi_rw_16 *cdb;
10344
10345		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10346
10347		*lba = scsi_8btou64(cdb->addr);
10348		*len = scsi_4btoul(cdb->length);
10349		break;
10350	}
10351	case WRITE_VERIFY_16: {
10352		struct scsi_write_verify_16 *cdb;
10353
10354		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10355
10356		*lba = scsi_8btou64(cdb->addr);
10357		*len = scsi_4btoul(cdb->length);
10358		break;
10359	}
10360	case WRITE_SAME_10: {
10361		struct scsi_write_same_10 *cdb;
10362
10363		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10364
10365		*lba = scsi_4btoul(cdb->addr);
10366		*len = scsi_2btoul(cdb->length);
10367		break;
10368	}
10369	case WRITE_SAME_16: {
10370		struct scsi_write_same_16 *cdb;
10371
10372		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10373
10374		*lba = scsi_8btou64(cdb->addr);
10375		*len = scsi_4btoul(cdb->length);
10376		break;
10377	}
10378	case VERIFY_10: {
10379		struct scsi_verify_10 *cdb;
10380
10381		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10382
10383		*lba = scsi_4btoul(cdb->addr);
10384		*len = scsi_2btoul(cdb->length);
10385		break;
10386	}
10387	case VERIFY_12: {
10388		struct scsi_verify_12 *cdb;
10389
10390		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10391
10392		*lba = scsi_4btoul(cdb->addr);
10393		*len = scsi_4btoul(cdb->length);
10394		break;
10395	}
10396	case VERIFY_16: {
10397		struct scsi_verify_16 *cdb;
10398
10399		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10400
10401		*lba = scsi_8btou64(cdb->addr);
10402		*len = scsi_4btoul(cdb->length);
10403		break;
10404	}
10405	case UNMAP: {
10406		*lba = 0;
10407		*len = UINT64_MAX;
10408		break;
10409	}
10410	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10411		struct scsi_get_lba_status *cdb;
10412
10413		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10414		*lba = scsi_8btou64(cdb->addr);
10415		*len = UINT32_MAX;
10416		break;
10417	}
10418	default:
10419		return (1);
10420		break; /* NOTREACHED */
10421	}
10422
10423	return (0);
10424}
10425
10426static ctl_action
10427ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10428    bool seq)
10429{
10430	uint64_t endlba1, endlba2;
10431
10432	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10433	endlba2 = lba2 + len2 - 1;
10434
10435	if ((endlba1 < lba2) || (endlba2 < lba1))
10436		return (CTL_ACTION_PASS);
10437	else
10438		return (CTL_ACTION_BLOCK);
10439}
10440
10441static int
10442ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10443{
10444	struct ctl_ptr_len_flags *ptrlen;
10445	struct scsi_unmap_desc *buf, *end, *range;
10446	uint64_t lba;
10447	uint32_t len;
10448
10449	/* If not UNMAP -- go other way. */
10450	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10451	    io->scsiio.cdb[0] != UNMAP)
10452		return (CTL_ACTION_ERROR);
10453
10454	/* If UNMAP without data -- block and wait for data. */
10455	ptrlen = (struct ctl_ptr_len_flags *)
10456	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10457	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10458	    ptrlen->ptr == NULL)
10459		return (CTL_ACTION_BLOCK);
10460
10461	/* UNMAP with data -- check for collision. */
10462	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10463	end = buf + ptrlen->len / sizeof(*buf);
10464	for (range = buf; range < end; range++) {
10465		lba = scsi_8btou64(range->lba);
10466		len = scsi_4btoul(range->length);
10467		if ((lba < lba2 + len2) && (lba + len > lba2))
10468			return (CTL_ACTION_BLOCK);
10469	}
10470	return (CTL_ACTION_PASS);
10471}
10472
10473static ctl_action
10474ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10475{
10476	uint64_t lba1, lba2;
10477	uint64_t len1, len2;
10478	int retval;
10479
10480	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10481		return (CTL_ACTION_ERROR);
10482
10483	retval = ctl_extent_check_unmap(io1, lba2, len2);
10484	if (retval != CTL_ACTION_ERROR)
10485		return (retval);
10486
10487	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10488		return (CTL_ACTION_ERROR);
10489
10490	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10491}
10492
10493static ctl_action
10494ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10495{
10496	uint64_t lba1, lba2;
10497	uint64_t len1, len2;
10498
10499	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10500		return (CTL_ACTION_ERROR);
10501	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10502		return (CTL_ACTION_ERROR);
10503
10504	if (lba1 + len1 == lba2)
10505		return (CTL_ACTION_BLOCK);
10506	return (CTL_ACTION_PASS);
10507}
10508
10509static ctl_action
10510ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10511    union ctl_io *ooa_io)
10512{
10513	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10514	ctl_serialize_action *serialize_row;
10515
10516	/*
10517	 * The initiator attempted multiple untagged commands at the same
10518	 * time.  Can't do that.
10519	 */
10520	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10521	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10522	 && ((pending_io->io_hdr.nexus.targ_port ==
10523	      ooa_io->io_hdr.nexus.targ_port)
10524	  && (pending_io->io_hdr.nexus.initid ==
10525	      ooa_io->io_hdr.nexus.initid))
10526	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10527	      CTL_FLAG_STATUS_SENT)) == 0))
10528		return (CTL_ACTION_OVERLAP);
10529
10530	/*
10531	 * The initiator attempted to send multiple tagged commands with
10532	 * the same ID.  (It's fine if different initiators have the same
10533	 * tag ID.)
10534	 *
10535	 * Even if all of those conditions are true, we don't kill the I/O
10536	 * if the command ahead of us has been aborted.  We won't end up
10537	 * sending it to the FETD, and it's perfectly legal to resend a
10538	 * command with the same tag number as long as the previous
10539	 * instance of this tag number has been aborted somehow.
10540	 */
10541	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10542	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10543	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10544	 && ((pending_io->io_hdr.nexus.targ_port ==
10545	      ooa_io->io_hdr.nexus.targ_port)
10546	  && (pending_io->io_hdr.nexus.initid ==
10547	      ooa_io->io_hdr.nexus.initid))
10548	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10549	      CTL_FLAG_STATUS_SENT)) == 0))
10550		return (CTL_ACTION_OVERLAP_TAG);
10551
10552	/*
10553	 * If we get a head of queue tag, SAM-3 says that we should
10554	 * immediately execute it.
10555	 *
10556	 * What happens if this command would normally block for some other
10557	 * reason?  e.g. a request sense with a head of queue tag
10558	 * immediately after a write.  Normally that would block, but this
10559	 * will result in its getting executed immediately...
10560	 *
10561	 * We currently return "pass" instead of "skip", so we'll end up
10562	 * going through the rest of the queue to check for overlapped tags.
10563	 *
10564	 * XXX KDM check for other types of blockage first??
10565	 */
10566	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10567		return (CTL_ACTION_PASS);
10568
10569	/*
10570	 * Ordered tags have to block until all items ahead of them
10571	 * have completed.  If we get called with an ordered tag, we always
10572	 * block, if something else is ahead of us in the queue.
10573	 */
10574	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10575		return (CTL_ACTION_BLOCK);
10576
10577	/*
10578	 * Simple tags get blocked until all head of queue and ordered tags
10579	 * ahead of them have completed.  I'm lumping untagged commands in
10580	 * with simple tags here.  XXX KDM is that the right thing to do?
10581	 */
10582	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10583	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10584	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10585	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10586		return (CTL_ACTION_BLOCK);
10587
10588	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10589	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10590
10591	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10592
10593	switch (serialize_row[pending_entry->seridx]) {
10594	case CTL_SER_BLOCK:
10595		return (CTL_ACTION_BLOCK);
10596	case CTL_SER_EXTENT:
10597		return (ctl_extent_check(ooa_io, pending_io,
10598		    (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10599	case CTL_SER_EXTENTOPT:
10600		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10601		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10602			return (ctl_extent_check(ooa_io, pending_io,
10603			    (lun->be_lun &&
10604			     lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10605		return (CTL_ACTION_PASS);
10606	case CTL_SER_EXTENTSEQ:
10607		if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
10608			return (ctl_extent_check_seq(ooa_io, pending_io));
10609		return (CTL_ACTION_PASS);
10610	case CTL_SER_PASS:
10611		return (CTL_ACTION_PASS);
10612	case CTL_SER_BLOCKOPT:
10613		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10614		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10615			return (CTL_ACTION_BLOCK);
10616		return (CTL_ACTION_PASS);
10617	case CTL_SER_SKIP:
10618		return (CTL_ACTION_SKIP);
10619	default:
10620		panic("invalid serialization value %d",
10621		      serialize_row[pending_entry->seridx]);
10622	}
10623
10624	return (CTL_ACTION_ERROR);
10625}
10626
10627/*
10628 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10629 * Assumptions:
10630 * - pending_io is generally either incoming, or on the blocked queue
10631 * - starting I/O is the I/O we want to start the check with.
10632 */
10633static ctl_action
10634ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10635	      union ctl_io *starting_io)
10636{
10637	union ctl_io *ooa_io;
10638	ctl_action action;
10639
10640	mtx_assert(&lun->lun_lock, MA_OWNED);
10641
10642	/*
10643	 * Run back along the OOA queue, starting with the current
10644	 * blocked I/O and going through every I/O before it on the
10645	 * queue.  If starting_io is NULL, we'll just end up returning
10646	 * CTL_ACTION_PASS.
10647	 */
10648	for (ooa_io = starting_io; ooa_io != NULL;
10649	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10650	     ooa_links)){
10651
10652		/*
10653		 * This routine just checks to see whether
10654		 * cur_blocked is blocked by ooa_io, which is ahead
10655		 * of it in the queue.  It doesn't queue/dequeue
10656		 * cur_blocked.
10657		 */
10658		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10659		switch (action) {
10660		case CTL_ACTION_BLOCK:
10661		case CTL_ACTION_OVERLAP:
10662		case CTL_ACTION_OVERLAP_TAG:
10663		case CTL_ACTION_SKIP:
10664		case CTL_ACTION_ERROR:
10665			return (action);
10666			break; /* NOTREACHED */
10667		case CTL_ACTION_PASS:
10668			break;
10669		default:
10670			panic("invalid action %d", action);
10671			break;  /* NOTREACHED */
10672		}
10673	}
10674
10675	return (CTL_ACTION_PASS);
10676}
10677
10678/*
10679 * Assumptions:
10680 * - An I/O has just completed, and has been removed from the per-LUN OOA
10681 *   queue, so some items on the blocked queue may now be unblocked.
10682 */
10683static int
10684ctl_check_blocked(struct ctl_lun *lun)
10685{
10686	struct ctl_softc *softc = lun->ctl_softc;
10687	union ctl_io *cur_blocked, *next_blocked;
10688
10689	mtx_assert(&lun->lun_lock, MA_OWNED);
10690
10691	/*
10692	 * Run forward from the head of the blocked queue, checking each
10693	 * entry against the I/Os prior to it on the OOA queue to see if
10694	 * there is still any blockage.
10695	 *
10696	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10697	 * with our removing a variable on it while it is traversing the
10698	 * list.
10699	 */
10700	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10701	     cur_blocked != NULL; cur_blocked = next_blocked) {
10702		union ctl_io *prev_ooa;
10703		ctl_action action;
10704
10705		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10706							  blocked_links);
10707
10708		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10709						      ctl_ooaq, ooa_links);
10710
10711		/*
10712		 * If cur_blocked happens to be the first item in the OOA
10713		 * queue now, prev_ooa will be NULL, and the action
10714		 * returned will just be CTL_ACTION_PASS.
10715		 */
10716		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
10717
10718		switch (action) {
10719		case CTL_ACTION_BLOCK:
10720			/* Nothing to do here, still blocked */
10721			break;
10722		case CTL_ACTION_OVERLAP:
10723		case CTL_ACTION_OVERLAP_TAG:
10724			/*
10725			 * This shouldn't happen!  In theory we've already
10726			 * checked this command for overlap...
10727			 */
10728			break;
10729		case CTL_ACTION_PASS:
10730		case CTL_ACTION_SKIP: {
10731			const struct ctl_cmd_entry *entry;
10732
10733			/*
10734			 * The skip case shouldn't happen, this transaction
10735			 * should have never made it onto the blocked queue.
10736			 */
10737			/*
10738			 * This I/O is no longer blocked, we can remove it
10739			 * from the blocked queue.  Since this is a TAILQ
10740			 * (doubly linked list), we can do O(1) removals
10741			 * from any place on the list.
10742			 */
10743			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
10744				     blocked_links);
10745			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10746
10747			if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
10748			    (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
10749				/*
10750				 * Need to send IO back to original side to
10751				 * run
10752				 */
10753				union ctl_ha_msg msg_info;
10754
10755				cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
10756				msg_info.hdr.original_sc =
10757					cur_blocked->io_hdr.original_sc;
10758				msg_info.hdr.serializing_sc = cur_blocked;
10759				msg_info.hdr.msg_type = CTL_MSG_R2R;
10760				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
10761				    sizeof(msg_info.hdr), M_NOWAIT);
10762				break;
10763			}
10764			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
10765
10766			/*
10767			 * Check this I/O for LUN state changes that may
10768			 * have happened while this command was blocked.
10769			 * The LUN state may have been changed by a command
10770			 * ahead of us in the queue, so we need to re-check
10771			 * for any states that can be caused by SCSI
10772			 * commands.
10773			 */
10774			if (ctl_scsiio_lun_check(lun, entry,
10775						 &cur_blocked->scsiio) == 0) {
10776				cur_blocked->io_hdr.flags |=
10777				                      CTL_FLAG_IS_WAS_ON_RTR;
10778				ctl_enqueue_rtr(cur_blocked);
10779			} else
10780				ctl_done(cur_blocked);
10781			break;
10782		}
10783		default:
10784			/*
10785			 * This probably shouldn't happen -- we shouldn't
10786			 * get CTL_ACTION_ERROR, or anything else.
10787			 */
10788			break;
10789		}
10790	}
10791
10792	return (CTL_RETVAL_COMPLETE);
10793}
10794
10795/*
10796 * This routine (with one exception) checks LUN flags that can be set by
10797 * commands ahead of us in the OOA queue.  These flags have to be checked
10798 * when a command initially comes in, and when we pull a command off the
10799 * blocked queue and are preparing to execute it.  The reason we have to
10800 * check these flags for commands on the blocked queue is that the LUN
10801 * state may have been changed by a command ahead of us while we're on the
10802 * blocked queue.
10803 *
10804 * Ordering is somewhat important with these checks, so please pay
10805 * careful attention to the placement of any new checks.
10806 */
10807static int
10808ctl_scsiio_lun_check(struct ctl_lun *lun,
10809    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
10810{
10811	struct ctl_softc *softc = lun->ctl_softc;
10812	int retval;
10813	uint32_t residx;
10814
10815	retval = 0;
10816
10817	mtx_assert(&lun->lun_lock, MA_OWNED);
10818
10819	/*
10820	 * If this shelf is a secondary shelf controller, we may have to
10821	 * reject some commands disallowed by HA mode and link state.
10822	 */
10823	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
10824		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
10825		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
10826			ctl_set_lun_unavail(ctsio);
10827			retval = 1;
10828			goto bailout;
10829		}
10830		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
10831		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
10832			ctl_set_lun_transit(ctsio);
10833			retval = 1;
10834			goto bailout;
10835		}
10836		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
10837		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
10838			ctl_set_lun_standby(ctsio);
10839			retval = 1;
10840			goto bailout;
10841		}
10842
10843		/* The rest of checks are only done on executing side */
10844		if (softc->ha_mode == CTL_HA_MODE_XFER)
10845			goto bailout;
10846	}
10847
10848	if (entry->pattern & CTL_LUN_PAT_WRITE) {
10849		if (lun->be_lun &&
10850		    lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
10851			ctl_set_hw_write_protected(ctsio);
10852			retval = 1;
10853			goto bailout;
10854		}
10855		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
10856		    .eca_and_aen & SCP_SWP) != 0) {
10857			ctl_set_sense(ctsio, /*current_error*/ 1,
10858			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
10859			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
10860			retval = 1;
10861			goto bailout;
10862		}
10863	}
10864
10865	/*
10866	 * Check for a reservation conflict.  If this command isn't allowed
10867	 * even on reserved LUNs, and if this initiator isn't the one who
10868	 * reserved us, reject the command with a reservation conflict.
10869	 */
10870	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
10871	if ((lun->flags & CTL_LUN_RESERVED)
10872	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
10873		if (lun->res_idx != residx) {
10874			ctl_set_reservation_conflict(ctsio);
10875			retval = 1;
10876			goto bailout;
10877		}
10878	}
10879
10880	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
10881	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
10882		/* No reservation or command is allowed. */;
10883	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
10884	    (lun->res_type == SPR_TYPE_WR_EX ||
10885	     lun->res_type == SPR_TYPE_WR_EX_RO ||
10886	     lun->res_type == SPR_TYPE_WR_EX_AR)) {
10887		/* The command is allowed for Write Exclusive resv. */;
10888	} else {
10889		/*
10890		 * if we aren't registered or it's a res holder type
10891		 * reservation and this isn't the res holder then set a
10892		 * conflict.
10893		 */
10894		if (ctl_get_prkey(lun, residx) == 0
10895		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
10896			ctl_set_reservation_conflict(ctsio);
10897			retval = 1;
10898			goto bailout;
10899		}
10900	}
10901
10902	if ((lun->flags & CTL_LUN_OFFLINE)
10903	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0)) {
10904		ctl_set_lun_not_ready(ctsio);
10905		retval = 1;
10906		goto bailout;
10907	}
10908
10909	if ((lun->flags & CTL_LUN_STOPPED)
10910	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
10911		/* "Logical unit not ready, initializing cmd. required" */
10912		ctl_set_lun_stopped(ctsio);
10913		retval = 1;
10914		goto bailout;
10915	}
10916
10917	if ((lun->flags & CTL_LUN_INOPERABLE)
10918	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
10919		/* "Medium format corrupted" */
10920		ctl_set_medium_format_corrupted(ctsio);
10921		retval = 1;
10922		goto bailout;
10923	}
10924
10925bailout:
10926	return (retval);
10927}
10928
10929static void
10930ctl_failover_io(union ctl_io *io, int have_lock)
10931{
10932	ctl_set_busy(&io->scsiio);
10933	ctl_done(io);
10934}
10935
10936static void
10937ctl_failover_lun(struct ctl_lun *lun)
10938{
10939	struct ctl_softc *softc = lun->ctl_softc;
10940	struct ctl_io_hdr *io, *next_io;
10941
10942	CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", lun->lun));
10943	if (softc->ha_mode == CTL_HA_MODE_XFER) {
10944		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
10945			/* We are master */
10946			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
10947				if (io->flags & CTL_FLAG_IO_ACTIVE) {
10948					io->flags |= CTL_FLAG_ABORT;
10949				} else { /* This can be only due to DATAMOVE */
10950					io->msg_type = CTL_MSG_DATAMOVE_DONE;
10951					io->flags |= CTL_FLAG_IO_ACTIVE;
10952					io->port_status = 31340;
10953					ctl_enqueue_isc((union ctl_io *)io);
10954				}
10955			}
10956			/* We are slave */
10957			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
10958				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
10959				if (io->flags & CTL_FLAG_IO_ACTIVE) {
10960					io->flags |= CTL_FLAG_FAILOVER;
10961				} else {
10962					ctl_set_busy(&((union ctl_io *)io)->
10963					    scsiio);
10964					ctl_done((union ctl_io *)io);
10965				}
10966			}
10967		}
10968	} else { /* SERIALIZE modes */
10969		TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
10970		    next_io) {
10971			/* We are master */
10972			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
10973				TAILQ_REMOVE(&lun->blocked_queue, io,
10974				    blocked_links);
10975				io->flags &= ~CTL_FLAG_BLOCKED;
10976				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
10977				ctl_free_io((union ctl_io *)io);
10978			}
10979		}
10980		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
10981			/* We are master */
10982			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
10983				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
10984				ctl_free_io((union ctl_io *)io);
10985			}
10986			/* We are slave */
10987			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
10988				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
10989				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
10990					ctl_set_busy(&((union ctl_io *)io)->
10991					    scsiio);
10992					ctl_done((union ctl_io *)io);
10993				}
10994			}
10995		}
10996		ctl_check_blocked(lun);
10997	}
10998}
10999
11000static int
11001ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11002{
11003	struct ctl_lun *lun;
11004	const struct ctl_cmd_entry *entry;
11005	uint32_t initidx, targ_lun;
11006	int retval;
11007
11008	retval = 0;
11009
11010	lun = NULL;
11011
11012	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11013	if ((targ_lun < CTL_MAX_LUNS)
11014	 && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11015		/*
11016		 * If the LUN is invalid, pretend that it doesn't exist.
11017		 * It will go away as soon as all pending I/O has been
11018		 * completed.
11019		 */
11020		mtx_lock(&lun->lun_lock);
11021		if (lun->flags & CTL_LUN_DISABLED) {
11022			mtx_unlock(&lun->lun_lock);
11023			lun = NULL;
11024			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11025			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11026		} else {
11027			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11028			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11029				lun->be_lun;
11030
11031			/*
11032			 * Every I/O goes into the OOA queue for a
11033			 * particular LUN, and stays there until completion.
11034			 */
11035#ifdef CTL_TIME_IO
11036			if (TAILQ_EMPTY(&lun->ooa_queue)) {
11037				lun->idle_time += getsbinuptime() -
11038				    lun->last_busy;
11039			}
11040#endif
11041			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11042			    ooa_links);
11043		}
11044	} else {
11045		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11046		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11047	}
11048
11049	/* Get command entry and return error if it is unsuppotyed. */
11050	entry = ctl_validate_command(ctsio);
11051	if (entry == NULL) {
11052		if (lun)
11053			mtx_unlock(&lun->lun_lock);
11054		return (retval);
11055	}
11056
11057	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11058	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11059
11060	/*
11061	 * Check to see whether we can send this command to LUNs that don't
11062	 * exist.  This should pretty much only be the case for inquiry
11063	 * and request sense.  Further checks, below, really require having
11064	 * a LUN, so we can't really check the command anymore.  Just put
11065	 * it on the rtr queue.
11066	 */
11067	if (lun == NULL) {
11068		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11069			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11070			ctl_enqueue_rtr((union ctl_io *)ctsio);
11071			return (retval);
11072		}
11073
11074		ctl_set_unsupported_lun(ctsio);
11075		ctl_done((union ctl_io *)ctsio);
11076		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11077		return (retval);
11078	} else {
11079		/*
11080		 * Make sure we support this particular command on this LUN.
11081		 * e.g., we don't support writes to the control LUN.
11082		 */
11083		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11084			mtx_unlock(&lun->lun_lock);
11085			ctl_set_invalid_opcode(ctsio);
11086			ctl_done((union ctl_io *)ctsio);
11087			return (retval);
11088		}
11089	}
11090
11091	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11092
11093#ifdef CTL_WITH_CA
11094	/*
11095	 * If we've got a request sense, it'll clear the contingent
11096	 * allegiance condition.  Otherwise, if we have a CA condition for
11097	 * this initiator, clear it, because it sent down a command other
11098	 * than request sense.
11099	 */
11100	if ((ctsio->cdb[0] != REQUEST_SENSE)
11101	 && (ctl_is_set(lun->have_ca, initidx)))
11102		ctl_clear_mask(lun->have_ca, initidx);
11103#endif
11104
11105	/*
11106	 * If the command has this flag set, it handles its own unit
11107	 * attention reporting, we shouldn't do anything.  Otherwise we
11108	 * check for any pending unit attentions, and send them back to the
11109	 * initiator.  We only do this when a command initially comes in,
11110	 * not when we pull it off the blocked queue.
11111	 *
11112	 * According to SAM-3, section 5.3.2, the order that things get
11113	 * presented back to the host is basically unit attentions caused
11114	 * by some sort of reset event, busy status, reservation conflicts
11115	 * or task set full, and finally any other status.
11116	 *
11117	 * One issue here is that some of the unit attentions we report
11118	 * don't fall into the "reset" category (e.g. "reported luns data
11119	 * has changed").  So reporting it here, before the reservation
11120	 * check, may be technically wrong.  I guess the only thing to do
11121	 * would be to check for and report the reset events here, and then
11122	 * check for the other unit attention types after we check for a
11123	 * reservation conflict.
11124	 *
11125	 * XXX KDM need to fix this
11126	 */
11127	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11128		ctl_ua_type ua_type;
11129		scsi_sense_data_type sense_format;
11130
11131		if (lun->flags & CTL_LUN_SENSE_DESC)
11132			sense_format = SSD_TYPE_DESC;
11133		else
11134			sense_format = SSD_TYPE_FIXED;
11135
11136		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11137		    sense_format);
11138		if (ua_type != CTL_UA_NONE) {
11139			mtx_unlock(&lun->lun_lock);
11140			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11141			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11142			ctsio->sense_len = SSD_FULL_SIZE;
11143			ctl_done((union ctl_io *)ctsio);
11144			return (retval);
11145		}
11146	}
11147
11148
11149	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11150		mtx_unlock(&lun->lun_lock);
11151		ctl_done((union ctl_io *)ctsio);
11152		return (retval);
11153	}
11154
11155	/*
11156	 * XXX CHD this is where we want to send IO to other side if
11157	 * this LUN is secondary on this SC. We will need to make a copy
11158	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11159	 * the copy we send as FROM_OTHER.
11160	 * We also need to stuff the address of the original IO so we can
11161	 * find it easily. Something similar will need be done on the other
11162	 * side so when we are done we can find the copy.
11163	 */
11164	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11165	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0) {
11166		union ctl_ha_msg msg_info;
11167		int isc_retval;
11168
11169		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11170		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11171		mtx_unlock(&lun->lun_lock);
11172
11173		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11174		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11175		msg_info.hdr.serializing_sc = NULL;
11176		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11177		msg_info.scsi.tag_num = ctsio->tag_num;
11178		msg_info.scsi.tag_type = ctsio->tag_type;
11179		msg_info.scsi.cdb_len = ctsio->cdb_len;
11180		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11181
11182		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11183		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11184		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11185			ctl_set_busy(ctsio);
11186			ctl_done((union ctl_io *)ctsio);
11187			return (retval);
11188		}
11189		return (retval);
11190	}
11191
11192	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11193			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11194			      ctl_ooaq, ooa_links))) {
11195	case CTL_ACTION_BLOCK:
11196		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11197		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11198				  blocked_links);
11199		mtx_unlock(&lun->lun_lock);
11200		return (retval);
11201	case CTL_ACTION_PASS:
11202	case CTL_ACTION_SKIP:
11203		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11204		mtx_unlock(&lun->lun_lock);
11205		ctl_enqueue_rtr((union ctl_io *)ctsio);
11206		break;
11207	case CTL_ACTION_OVERLAP:
11208		mtx_unlock(&lun->lun_lock);
11209		ctl_set_overlapped_cmd(ctsio);
11210		ctl_done((union ctl_io *)ctsio);
11211		break;
11212	case CTL_ACTION_OVERLAP_TAG:
11213		mtx_unlock(&lun->lun_lock);
11214		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11215		ctl_done((union ctl_io *)ctsio);
11216		break;
11217	case CTL_ACTION_ERROR:
11218	default:
11219		mtx_unlock(&lun->lun_lock);
11220		ctl_set_internal_failure(ctsio,
11221					 /*sks_valid*/ 0,
11222					 /*retry_count*/ 0);
11223		ctl_done((union ctl_io *)ctsio);
11224		break;
11225	}
11226	return (retval);
11227}
11228
11229const struct ctl_cmd_entry *
11230ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11231{
11232	const struct ctl_cmd_entry *entry;
11233	int service_action;
11234
11235	entry = &ctl_cmd_table[ctsio->cdb[0]];
11236	if (sa)
11237		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11238	if (entry->flags & CTL_CMD_FLAG_SA5) {
11239		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11240		entry = &((const struct ctl_cmd_entry *)
11241		    entry->execute)[service_action];
11242	}
11243	return (entry);
11244}
11245
11246const struct ctl_cmd_entry *
11247ctl_validate_command(struct ctl_scsiio *ctsio)
11248{
11249	const struct ctl_cmd_entry *entry;
11250	int i, sa;
11251	uint8_t diff;
11252
11253	entry = ctl_get_cmd_entry(ctsio, &sa);
11254	if (entry->execute == NULL) {
11255		if (sa)
11256			ctl_set_invalid_field(ctsio,
11257					      /*sks_valid*/ 1,
11258					      /*command*/ 1,
11259					      /*field*/ 1,
11260					      /*bit_valid*/ 1,
11261					      /*bit*/ 4);
11262		else
11263			ctl_set_invalid_opcode(ctsio);
11264		ctl_done((union ctl_io *)ctsio);
11265		return (NULL);
11266	}
11267	KASSERT(entry->length > 0,
11268	    ("Not defined length for command 0x%02x/0x%02x",
11269	     ctsio->cdb[0], ctsio->cdb[1]));
11270	for (i = 1; i < entry->length; i++) {
11271		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11272		if (diff == 0)
11273			continue;
11274		ctl_set_invalid_field(ctsio,
11275				      /*sks_valid*/ 1,
11276				      /*command*/ 1,
11277				      /*field*/ i,
11278				      /*bit_valid*/ 1,
11279				      /*bit*/ fls(diff) - 1);
11280		ctl_done((union ctl_io *)ctsio);
11281		return (NULL);
11282	}
11283	return (entry);
11284}
11285
11286static int
11287ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11288{
11289
11290	switch (lun_type) {
11291	case T_PROCESSOR:
11292		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11293		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11294			return (0);
11295		break;
11296	case T_DIRECT:
11297		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11298		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11299			return (0);
11300		break;
11301	default:
11302		return (0);
11303	}
11304	return (1);
11305}
11306
11307static int
11308ctl_scsiio(struct ctl_scsiio *ctsio)
11309{
11310	int retval;
11311	const struct ctl_cmd_entry *entry;
11312
11313	retval = CTL_RETVAL_COMPLETE;
11314
11315	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11316
11317	entry = ctl_get_cmd_entry(ctsio, NULL);
11318
11319	/*
11320	 * If this I/O has been aborted, just send it straight to
11321	 * ctl_done() without executing it.
11322	 */
11323	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11324		ctl_done((union ctl_io *)ctsio);
11325		goto bailout;
11326	}
11327
11328	/*
11329	 * All the checks should have been handled by ctl_scsiio_precheck().
11330	 * We should be clear now to just execute the I/O.
11331	 */
11332	retval = entry->execute(ctsio);
11333
11334bailout:
11335	return (retval);
11336}
11337
11338/*
11339 * Since we only implement one target right now, a bus reset simply resets
11340 * our single target.
11341 */
11342static int
11343ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11344{
11345	return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11346}
11347
11348static int
11349ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11350		 ctl_ua_type ua_type)
11351{
11352	struct ctl_port *port;
11353	struct ctl_lun *lun;
11354	int retval;
11355
11356	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11357		union ctl_ha_msg msg_info;
11358
11359		msg_info.hdr.nexus = io->io_hdr.nexus;
11360		if (ua_type==CTL_UA_TARG_RESET)
11361			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11362		else
11363			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11364		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11365		msg_info.hdr.original_sc = NULL;
11366		msg_info.hdr.serializing_sc = NULL;
11367		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11368		    sizeof(msg_info.task), M_WAITOK);
11369	}
11370	retval = 0;
11371
11372	mtx_lock(&softc->ctl_lock);
11373	port = softc->ctl_ports[io->io_hdr.nexus.targ_port];
11374	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11375		if (port != NULL &&
11376		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
11377			continue;
11378		retval += ctl_do_lun_reset(lun, io, ua_type);
11379	}
11380	mtx_unlock(&softc->ctl_lock);
11381	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11382	return (retval);
11383}
11384
11385/*
11386 * The LUN should always be set.  The I/O is optional, and is used to
11387 * distinguish between I/Os sent by this initiator, and by other
11388 * initiators.  We set unit attention for initiators other than this one.
11389 * SAM-3 is vague on this point.  It does say that a unit attention should
11390 * be established for other initiators when a LUN is reset (see section
11391 * 5.7.3), but it doesn't specifically say that the unit attention should
11392 * be established for this particular initiator when a LUN is reset.  Here
11393 * is the relevant text, from SAM-3 rev 8:
11394 *
11395 * 5.7.2 When a SCSI initiator port aborts its own tasks
11396 *
11397 * When a SCSI initiator port causes its own task(s) to be aborted, no
11398 * notification that the task(s) have been aborted shall be returned to
11399 * the SCSI initiator port other than the completion response for the
11400 * command or task management function action that caused the task(s) to
11401 * be aborted and notification(s) associated with related effects of the
11402 * action (e.g., a reset unit attention condition).
11403 *
11404 * XXX KDM for now, we're setting unit attention for all initiators.
11405 */
11406static int
11407ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11408{
11409	union ctl_io *xio;
11410#if 0
11411	uint32_t initidx;
11412#endif
11413#ifdef CTL_WITH_CA
11414	int i;
11415#endif
11416
11417	mtx_lock(&lun->lun_lock);
11418	/*
11419	 * Run through the OOA queue and abort each I/O.
11420	 */
11421	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11422	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11423		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11424	}
11425
11426	/*
11427	 * This version sets unit attention for every
11428	 */
11429#if 0
11430	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11431	ctl_est_ua_all(lun, initidx, ua_type);
11432#else
11433	ctl_est_ua_all(lun, -1, ua_type);
11434#endif
11435
11436	/*
11437	 * A reset (any kind, really) clears reservations established with
11438	 * RESERVE/RELEASE.  It does not clear reservations established
11439	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11440	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11441	 * reservations made with the RESERVE/RELEASE commands, because
11442	 * those commands are obsolete in SPC-3.
11443	 */
11444	lun->flags &= ~CTL_LUN_RESERVED;
11445
11446#ifdef CTL_WITH_CA
11447	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11448		ctl_clear_mask(lun->have_ca, i);
11449#endif
11450	mtx_unlock(&lun->lun_lock);
11451
11452	return (0);
11453}
11454
11455static int
11456ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
11457{
11458	struct ctl_lun *lun;
11459	uint32_t targ_lun;
11460	int retval;
11461
11462	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11463	mtx_lock(&softc->ctl_lock);
11464	if ((targ_lun >= CTL_MAX_LUNS) ||
11465	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11466		mtx_unlock(&softc->ctl_lock);
11467		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11468		return (1);
11469	}
11470	retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
11471	mtx_unlock(&softc->ctl_lock);
11472	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11473
11474	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11475		union ctl_ha_msg msg_info;
11476
11477		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11478		msg_info.hdr.nexus = io->io_hdr.nexus;
11479		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11480		msg_info.hdr.original_sc = NULL;
11481		msg_info.hdr.serializing_sc = NULL;
11482		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11483		    sizeof(msg_info.task), M_WAITOK);
11484	}
11485	return (retval);
11486}
11487
11488static void
11489ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11490    int other_sc)
11491{
11492	union ctl_io *xio;
11493
11494	mtx_assert(&lun->lun_lock, MA_OWNED);
11495
11496	/*
11497	 * Run through the OOA queue and attempt to find the given I/O.
11498	 * The target port, initiator ID, tag type and tag number have to
11499	 * match the values that we got from the initiator.  If we have an
11500	 * untagged command to abort, simply abort the first untagged command
11501	 * we come to.  We only allow one untagged command at a time of course.
11502	 */
11503	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11504	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11505
11506		if ((targ_port == UINT32_MAX ||
11507		     targ_port == xio->io_hdr.nexus.targ_port) &&
11508		    (init_id == UINT32_MAX ||
11509		     init_id == xio->io_hdr.nexus.initid)) {
11510			if (targ_port != xio->io_hdr.nexus.targ_port ||
11511			    init_id != xio->io_hdr.nexus.initid)
11512				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11513			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11514			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11515				union ctl_ha_msg msg_info;
11516
11517				msg_info.hdr.nexus = xio->io_hdr.nexus;
11518				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11519				msg_info.task.tag_num = xio->scsiio.tag_num;
11520				msg_info.task.tag_type = xio->scsiio.tag_type;
11521				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11522				msg_info.hdr.original_sc = NULL;
11523				msg_info.hdr.serializing_sc = NULL;
11524				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11525				    sizeof(msg_info.task), M_NOWAIT);
11526			}
11527		}
11528	}
11529}
11530
11531static int
11532ctl_abort_task_set(union ctl_io *io)
11533{
11534	struct ctl_softc *softc = control_softc;
11535	struct ctl_lun *lun;
11536	uint32_t targ_lun;
11537
11538	/*
11539	 * Look up the LUN.
11540	 */
11541	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11542	mtx_lock(&softc->ctl_lock);
11543	if ((targ_lun >= CTL_MAX_LUNS) ||
11544	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11545		mtx_unlock(&softc->ctl_lock);
11546		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11547		return (1);
11548	}
11549
11550	mtx_lock(&lun->lun_lock);
11551	mtx_unlock(&softc->ctl_lock);
11552	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11553		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11554		    io->io_hdr.nexus.initid,
11555		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11556	} else { /* CTL_TASK_CLEAR_TASK_SET */
11557		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11558		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11559	}
11560	mtx_unlock(&lun->lun_lock);
11561	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11562	return (0);
11563}
11564
11565static int
11566ctl_i_t_nexus_reset(union ctl_io *io)
11567{
11568	struct ctl_softc *softc = control_softc;
11569	struct ctl_lun *lun;
11570	uint32_t initidx;
11571
11572	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11573		union ctl_ha_msg msg_info;
11574
11575		msg_info.hdr.nexus = io->io_hdr.nexus;
11576		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
11577		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11578		msg_info.hdr.original_sc = NULL;
11579		msg_info.hdr.serializing_sc = NULL;
11580		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11581		    sizeof(msg_info.task), M_WAITOK);
11582	}
11583
11584	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11585	mtx_lock(&softc->ctl_lock);
11586	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11587		mtx_lock(&lun->lun_lock);
11588		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11589		    io->io_hdr.nexus.initid, 1);
11590#ifdef CTL_WITH_CA
11591		ctl_clear_mask(lun->have_ca, initidx);
11592#endif
11593		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
11594			lun->flags &= ~CTL_LUN_RESERVED;
11595		ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
11596		mtx_unlock(&lun->lun_lock);
11597	}
11598	mtx_unlock(&softc->ctl_lock);
11599	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11600	return (0);
11601}
11602
11603static int
11604ctl_abort_task(union ctl_io *io)
11605{
11606	union ctl_io *xio;
11607	struct ctl_lun *lun;
11608	struct ctl_softc *softc;
11609#if 0
11610	struct sbuf sb;
11611	char printbuf[128];
11612#endif
11613	int found;
11614	uint32_t targ_lun;
11615
11616	softc = control_softc;
11617	found = 0;
11618
11619	/*
11620	 * Look up the LUN.
11621	 */
11622	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11623	mtx_lock(&softc->ctl_lock);
11624	if ((targ_lun >= CTL_MAX_LUNS) ||
11625	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11626		mtx_unlock(&softc->ctl_lock);
11627		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11628		return (1);
11629	}
11630
11631#if 0
11632	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11633	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11634#endif
11635
11636	mtx_lock(&lun->lun_lock);
11637	mtx_unlock(&softc->ctl_lock);
11638	/*
11639	 * Run through the OOA queue and attempt to find the given I/O.
11640	 * The target port, initiator ID, tag type and tag number have to
11641	 * match the values that we got from the initiator.  If we have an
11642	 * untagged command to abort, simply abort the first untagged command
11643	 * we come to.  We only allow one untagged command at a time of course.
11644	 */
11645	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11646	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11647#if 0
11648		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
11649
11650		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
11651			    lun->lun, xio->scsiio.tag_num,
11652			    xio->scsiio.tag_type,
11653			    (xio->io_hdr.blocked_links.tqe_prev
11654			    == NULL) ? "" : " BLOCKED",
11655			    (xio->io_hdr.flags &
11656			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
11657			    (xio->io_hdr.flags &
11658			    CTL_FLAG_ABORT) ? " ABORT" : "",
11659			    (xio->io_hdr.flags &
11660			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
11661		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
11662		sbuf_finish(&sb);
11663		printf("%s\n", sbuf_data(&sb));
11664#endif
11665
11666		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
11667		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
11668		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
11669			continue;
11670
11671		/*
11672		 * If the abort says that the task is untagged, the
11673		 * task in the queue must be untagged.  Otherwise,
11674		 * we just check to see whether the tag numbers
11675		 * match.  This is because the QLogic firmware
11676		 * doesn't pass back the tag type in an abort
11677		 * request.
11678		 */
11679#if 0
11680		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
11681		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
11682		 || (xio->scsiio.tag_num == io->taskio.tag_num))
11683#endif
11684		/*
11685		 * XXX KDM we've got problems with FC, because it
11686		 * doesn't send down a tag type with aborts.  So we
11687		 * can only really go by the tag number...
11688		 * This may cause problems with parallel SCSI.
11689		 * Need to figure that out!!
11690		 */
11691		if (xio->scsiio.tag_num == io->taskio.tag_num) {
11692			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11693			found = 1;
11694			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
11695			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11696				union ctl_ha_msg msg_info;
11697
11698				msg_info.hdr.nexus = io->io_hdr.nexus;
11699				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11700				msg_info.task.tag_num = io->taskio.tag_num;
11701				msg_info.task.tag_type = io->taskio.tag_type;
11702				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11703				msg_info.hdr.original_sc = NULL;
11704				msg_info.hdr.serializing_sc = NULL;
11705#if 0
11706				printf("Sent Abort to other side\n");
11707#endif
11708				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11709				    sizeof(msg_info.task), M_NOWAIT);
11710			}
11711#if 0
11712			printf("ctl_abort_task: found I/O to abort\n");
11713#endif
11714		}
11715	}
11716	mtx_unlock(&lun->lun_lock);
11717
11718	if (found == 0) {
11719		/*
11720		 * This isn't really an error.  It's entirely possible for
11721		 * the abort and command completion to cross on the wire.
11722		 * This is more of an informative/diagnostic error.
11723		 */
11724#if 0
11725		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
11726		       "%u:%u:%u tag %d type %d\n",
11727		       io->io_hdr.nexus.initid,
11728		       io->io_hdr.nexus.targ_port,
11729		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
11730		       io->taskio.tag_type);
11731#endif
11732	}
11733	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11734	return (0);
11735}
11736
11737static int
11738ctl_query_task(union ctl_io *io, int task_set)
11739{
11740	union ctl_io *xio;
11741	struct ctl_lun *lun;
11742	struct ctl_softc *softc;
11743	int found = 0;
11744	uint32_t targ_lun;
11745
11746	softc = control_softc;
11747	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11748	mtx_lock(&softc->ctl_lock);
11749	if ((targ_lun >= CTL_MAX_LUNS) ||
11750	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11751		mtx_unlock(&softc->ctl_lock);
11752		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11753		return (1);
11754	}
11755	mtx_lock(&lun->lun_lock);
11756	mtx_unlock(&softc->ctl_lock);
11757	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11758	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11759
11760		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
11761		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
11762		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
11763			continue;
11764
11765		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
11766			found = 1;
11767			break;
11768		}
11769	}
11770	mtx_unlock(&lun->lun_lock);
11771	if (found)
11772		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
11773	else
11774		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11775	return (0);
11776}
11777
11778static int
11779ctl_query_async_event(union ctl_io *io)
11780{
11781	struct ctl_lun *lun;
11782	struct ctl_softc *softc;
11783	ctl_ua_type ua;
11784	uint32_t targ_lun, initidx;
11785
11786	softc = control_softc;
11787	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11788	mtx_lock(&softc->ctl_lock);
11789	if ((targ_lun >= CTL_MAX_LUNS) ||
11790	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11791		mtx_unlock(&softc->ctl_lock);
11792		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11793		return (1);
11794	}
11795	mtx_lock(&lun->lun_lock);
11796	mtx_unlock(&softc->ctl_lock);
11797	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11798	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
11799	mtx_unlock(&lun->lun_lock);
11800	if (ua != CTL_UA_NONE)
11801		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
11802	else
11803		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11804	return (0);
11805}
11806
11807static void
11808ctl_run_task(union ctl_io *io)
11809{
11810	struct ctl_softc *softc = control_softc;
11811	int retval = 1;
11812
11813	CTL_DEBUG_PRINT(("ctl_run_task\n"));
11814	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
11815	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
11816	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
11817	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
11818	switch (io->taskio.task_action) {
11819	case CTL_TASK_ABORT_TASK:
11820		retval = ctl_abort_task(io);
11821		break;
11822	case CTL_TASK_ABORT_TASK_SET:
11823	case CTL_TASK_CLEAR_TASK_SET:
11824		retval = ctl_abort_task_set(io);
11825		break;
11826	case CTL_TASK_CLEAR_ACA:
11827		break;
11828	case CTL_TASK_I_T_NEXUS_RESET:
11829		retval = ctl_i_t_nexus_reset(io);
11830		break;
11831	case CTL_TASK_LUN_RESET:
11832		retval = ctl_lun_reset(softc, io);
11833		break;
11834	case CTL_TASK_TARGET_RESET:
11835		retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
11836		break;
11837	case CTL_TASK_BUS_RESET:
11838		retval = ctl_bus_reset(softc, io);
11839		break;
11840	case CTL_TASK_PORT_LOGIN:
11841		break;
11842	case CTL_TASK_PORT_LOGOUT:
11843		break;
11844	case CTL_TASK_QUERY_TASK:
11845		retval = ctl_query_task(io, 0);
11846		break;
11847	case CTL_TASK_QUERY_TASK_SET:
11848		retval = ctl_query_task(io, 1);
11849		break;
11850	case CTL_TASK_QUERY_ASYNC_EVENT:
11851		retval = ctl_query_async_event(io);
11852		break;
11853	default:
11854		printf("%s: got unknown task management event %d\n",
11855		       __func__, io->taskio.task_action);
11856		break;
11857	}
11858	if (retval == 0)
11859		io->io_hdr.status = CTL_SUCCESS;
11860	else
11861		io->io_hdr.status = CTL_ERROR;
11862	ctl_done(io);
11863}
11864
11865/*
11866 * For HA operation.  Handle commands that come in from the other
11867 * controller.
11868 */
11869static void
11870ctl_handle_isc(union ctl_io *io)
11871{
11872	int free_io;
11873	struct ctl_lun *lun;
11874	struct ctl_softc *softc;
11875	uint32_t targ_lun;
11876
11877	softc = control_softc;
11878
11879	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11880	lun = softc->ctl_luns[targ_lun];
11881
11882	switch (io->io_hdr.msg_type) {
11883	case CTL_MSG_SERIALIZE:
11884		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
11885		break;
11886	case CTL_MSG_R2R: {
11887		const struct ctl_cmd_entry *entry;
11888
11889		/*
11890		 * This is only used in SER_ONLY mode.
11891		 */
11892		free_io = 0;
11893		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
11894		mtx_lock(&lun->lun_lock);
11895		if (ctl_scsiio_lun_check(lun,
11896		    entry, (struct ctl_scsiio *)io) != 0) {
11897			mtx_unlock(&lun->lun_lock);
11898			ctl_done(io);
11899			break;
11900		}
11901		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11902		mtx_unlock(&lun->lun_lock);
11903		ctl_enqueue_rtr(io);
11904		break;
11905	}
11906	case CTL_MSG_FINISH_IO:
11907		if (softc->ha_mode == CTL_HA_MODE_XFER) {
11908			free_io = 0;
11909			ctl_done(io);
11910		} else {
11911			free_io = 1;
11912			mtx_lock(&lun->lun_lock);
11913			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
11914				     ooa_links);
11915			ctl_check_blocked(lun);
11916			mtx_unlock(&lun->lun_lock);
11917		}
11918		break;
11919	case CTL_MSG_PERS_ACTION:
11920		ctl_hndl_per_res_out_on_other_sc(
11921			(union ctl_ha_msg *)&io->presio.pr_msg);
11922		free_io = 1;
11923		break;
11924	case CTL_MSG_BAD_JUJU:
11925		free_io = 0;
11926		ctl_done(io);
11927		break;
11928	case CTL_MSG_DATAMOVE:
11929		/* Only used in XFER mode */
11930		free_io = 0;
11931		ctl_datamove_remote(io);
11932		break;
11933	case CTL_MSG_DATAMOVE_DONE:
11934		/* Only used in XFER mode */
11935		free_io = 0;
11936		io->scsiio.be_move_done(io);
11937		break;
11938	case CTL_MSG_FAILOVER:
11939		mtx_lock(&lun->lun_lock);
11940		ctl_failover_lun(lun);
11941		mtx_unlock(&lun->lun_lock);
11942		free_io = 1;
11943		break;
11944	default:
11945		free_io = 1;
11946		printf("%s: Invalid message type %d\n",
11947		       __func__, io->io_hdr.msg_type);
11948		break;
11949	}
11950	if (free_io)
11951		ctl_free_io(io);
11952
11953}
11954
11955
11956/*
11957 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
11958 * there is no match.
11959 */
11960static ctl_lun_error_pattern
11961ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
11962{
11963	const struct ctl_cmd_entry *entry;
11964	ctl_lun_error_pattern filtered_pattern, pattern;
11965
11966	pattern = desc->error_pattern;
11967
11968	/*
11969	 * XXX KDM we need more data passed into this function to match a
11970	 * custom pattern, and we actually need to implement custom pattern
11971	 * matching.
11972	 */
11973	if (pattern & CTL_LUN_PAT_CMD)
11974		return (CTL_LUN_PAT_CMD);
11975
11976	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
11977		return (CTL_LUN_PAT_ANY);
11978
11979	entry = ctl_get_cmd_entry(ctsio, NULL);
11980
11981	filtered_pattern = entry->pattern & pattern;
11982
11983	/*
11984	 * If the user requested specific flags in the pattern (e.g.
11985	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
11986	 * flags.
11987	 *
11988	 * If the user did not specify any flags, it doesn't matter whether
11989	 * or not the command supports the flags.
11990	 */
11991	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
11992	     (pattern & ~CTL_LUN_PAT_MASK))
11993		return (CTL_LUN_PAT_NONE);
11994
11995	/*
11996	 * If the user asked for a range check, see if the requested LBA
11997	 * range overlaps with this command's LBA range.
11998	 */
11999	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12000		uint64_t lba1;
12001		uint64_t len1;
12002		ctl_action action;
12003		int retval;
12004
12005		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12006		if (retval != 0)
12007			return (CTL_LUN_PAT_NONE);
12008
12009		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12010					      desc->lba_range.len, FALSE);
12011		/*
12012		 * A "pass" means that the LBA ranges don't overlap, so
12013		 * this doesn't match the user's range criteria.
12014		 */
12015		if (action == CTL_ACTION_PASS)
12016			return (CTL_LUN_PAT_NONE);
12017	}
12018
12019	return (filtered_pattern);
12020}
12021
12022static void
12023ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12024{
12025	struct ctl_error_desc *desc, *desc2;
12026
12027	mtx_assert(&lun->lun_lock, MA_OWNED);
12028
12029	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12030		ctl_lun_error_pattern pattern;
12031		/*
12032		 * Check to see whether this particular command matches
12033		 * the pattern in the descriptor.
12034		 */
12035		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12036		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12037			continue;
12038
12039		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12040		case CTL_LUN_INJ_ABORTED:
12041			ctl_set_aborted(&io->scsiio);
12042			break;
12043		case CTL_LUN_INJ_MEDIUM_ERR:
12044			ctl_set_medium_error(&io->scsiio);
12045			break;
12046		case CTL_LUN_INJ_UA:
12047			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12048			 * OCCURRED */
12049			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12050			break;
12051		case CTL_LUN_INJ_CUSTOM:
12052			/*
12053			 * We're assuming the user knows what he is doing.
12054			 * Just copy the sense information without doing
12055			 * checks.
12056			 */
12057			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12058			      MIN(sizeof(desc->custom_sense),
12059				  sizeof(io->scsiio.sense_data)));
12060			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12061			io->scsiio.sense_len = SSD_FULL_SIZE;
12062			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12063			break;
12064		case CTL_LUN_INJ_NONE:
12065		default:
12066			/*
12067			 * If this is an error injection type we don't know
12068			 * about, clear the continuous flag (if it is set)
12069			 * so it will get deleted below.
12070			 */
12071			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12072			break;
12073		}
12074		/*
12075		 * By default, each error injection action is a one-shot
12076		 */
12077		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12078			continue;
12079
12080		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12081
12082		free(desc, M_CTL);
12083	}
12084}
12085
12086#ifdef CTL_IO_DELAY
12087static void
12088ctl_datamove_timer_wakeup(void *arg)
12089{
12090	union ctl_io *io;
12091
12092	io = (union ctl_io *)arg;
12093
12094	ctl_datamove(io);
12095}
12096#endif /* CTL_IO_DELAY */
12097
12098void
12099ctl_datamove(union ctl_io *io)
12100{
12101	void (*fe_datamove)(union ctl_io *io);
12102
12103	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12104
12105	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12106
12107#ifdef CTL_TIME_IO
12108	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12109		char str[256];
12110		char path_str[64];
12111		struct sbuf sb;
12112
12113		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12114		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12115
12116		sbuf_cat(&sb, path_str);
12117		switch (io->io_hdr.io_type) {
12118		case CTL_IO_SCSI:
12119			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12120			sbuf_printf(&sb, "\n");
12121			sbuf_cat(&sb, path_str);
12122			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12123				    io->scsiio.tag_num, io->scsiio.tag_type);
12124			break;
12125		case CTL_IO_TASK:
12126			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12127				    "Tag Type: %d\n", io->taskio.task_action,
12128				    io->taskio.tag_num, io->taskio.tag_type);
12129			break;
12130		default:
12131			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12132			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12133			break;
12134		}
12135		sbuf_cat(&sb, path_str);
12136		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12137			    (intmax_t)time_uptime - io->io_hdr.start_time);
12138		sbuf_finish(&sb);
12139		printf("%s", sbuf_data(&sb));
12140	}
12141#endif /* CTL_TIME_IO */
12142
12143#ifdef CTL_IO_DELAY
12144	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12145		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12146	} else {
12147		struct ctl_lun *lun;
12148
12149		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12150		if ((lun != NULL)
12151		 && (lun->delay_info.datamove_delay > 0)) {
12152
12153			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12154			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12155			callout_reset(&io->io_hdr.delay_callout,
12156				      lun->delay_info.datamove_delay * hz,
12157				      ctl_datamove_timer_wakeup, io);
12158			if (lun->delay_info.datamove_type ==
12159			    CTL_DELAY_TYPE_ONESHOT)
12160				lun->delay_info.datamove_delay = 0;
12161			return;
12162		}
12163	}
12164#endif
12165
12166	/*
12167	 * This command has been aborted.  Set the port status, so we fail
12168	 * the data move.
12169	 */
12170	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12171		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12172		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12173		       io->io_hdr.nexus.targ_port,
12174		       io->io_hdr.nexus.targ_lun);
12175		io->io_hdr.port_status = 31337;
12176		/*
12177		 * Note that the backend, in this case, will get the
12178		 * callback in its context.  In other cases it may get
12179		 * called in the frontend's interrupt thread context.
12180		 */
12181		io->scsiio.be_move_done(io);
12182		return;
12183	}
12184
12185	/* Don't confuse frontend with zero length data move. */
12186	if (io->scsiio.kern_data_len == 0) {
12187		io->scsiio.be_move_done(io);
12188		return;
12189	}
12190
12191	/*
12192	 * If we're in XFER mode and this I/O is from the other shelf
12193	 * controller, we need to send the DMA to the other side to
12194	 * actually transfer the data to/from the host.  In serialize only
12195	 * mode the transfer happens below CTL and ctl_datamove() is only
12196	 * called on the machine that originally received the I/O.
12197	 */
12198	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12199	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12200		union ctl_ha_msg msg;
12201		uint32_t sg_entries_sent;
12202		int do_sg_copy;
12203		int i;
12204
12205		memset(&msg, 0, sizeof(msg));
12206		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12207		msg.hdr.original_sc = io->io_hdr.original_sc;
12208		msg.hdr.serializing_sc = io;
12209		msg.hdr.nexus = io->io_hdr.nexus;
12210		msg.dt.flags = io->io_hdr.flags;
12211		/*
12212		 * We convert everything into a S/G list here.  We can't
12213		 * pass by reference, only by value between controllers.
12214		 * So we can't pass a pointer to the S/G list, only as many
12215		 * S/G entries as we can fit in here.  If it's possible for
12216		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12217		 * then we need to break this up into multiple transfers.
12218		 */
12219		if (io->scsiio.kern_sg_entries == 0) {
12220			msg.dt.kern_sg_entries = 1;
12221#if 0
12222			/*
12223			 * Convert to a physical address if this is a
12224			 * virtual address.
12225			 */
12226			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12227				msg.dt.sg_list[0].addr =
12228					io->scsiio.kern_data_ptr;
12229			} else {
12230				/*
12231				 * XXX KDM use busdma here!
12232				 */
12233				msg.dt.sg_list[0].addr = (void *)
12234					vtophys(io->scsiio.kern_data_ptr);
12235			}
12236#else
12237			KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12238			    ("HA does not support BUS_ADDR"));
12239			msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
12240#endif
12241
12242			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12243			do_sg_copy = 0;
12244		} else {
12245			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12246			do_sg_copy = 1;
12247		}
12248
12249		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12250		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12251		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12252		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12253		msg.dt.sg_sequence = 0;
12254
12255		/*
12256		 * Loop until we've sent all of the S/G entries.  On the
12257		 * other end, we'll recompose these S/G entries into one
12258		 * contiguous list before passing it to the
12259		 */
12260		for (sg_entries_sent = 0; sg_entries_sent <
12261		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12262			msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list)/
12263				sizeof(msg.dt.sg_list[0])),
12264				msg.dt.kern_sg_entries - sg_entries_sent);
12265
12266			if (do_sg_copy != 0) {
12267				struct ctl_sg_entry *sgl;
12268				int j;
12269
12270				sgl = (struct ctl_sg_entry *)
12271					io->scsiio.kern_data_ptr;
12272				/*
12273				 * If this is in cached memory, flush the cache
12274				 * before we send the DMA request to the other
12275				 * controller.  We want to do this in either
12276				 * the * read or the write case.  The read
12277				 * case is straightforward.  In the write
12278				 * case, we want to make sure nothing is
12279				 * in the local cache that could overwrite
12280				 * the DMAed data.
12281				 */
12282
12283				for (i = sg_entries_sent, j = 0;
12284				     i < msg.dt.cur_sg_entries; i++, j++) {
12285#if 0
12286					if ((io->io_hdr.flags &
12287					     CTL_FLAG_BUS_ADDR) == 0) {
12288						/*
12289						 * XXX KDM use busdma.
12290						 */
12291						msg.dt.sg_list[j].addr =(void *)
12292						       vtophys(sgl[i].addr);
12293					} else {
12294						msg.dt.sg_list[j].addr =
12295							sgl[i].addr;
12296					}
12297#else
12298					KASSERT((io->io_hdr.flags &
12299					    CTL_FLAG_BUS_ADDR) == 0,
12300					    ("HA does not support BUS_ADDR"));
12301					msg.dt.sg_list[j].addr = sgl[i].addr;
12302#endif
12303					msg.dt.sg_list[j].len = sgl[i].len;
12304				}
12305			}
12306
12307			sg_entries_sent += msg.dt.cur_sg_entries;
12308			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12309				msg.dt.sg_last = 1;
12310			else
12311				msg.dt.sg_last = 0;
12312
12313			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12314			    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
12315			    sizeof(struct ctl_sg_entry)*msg.dt.cur_sg_entries,
12316			    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
12317				io->io_hdr.port_status = 31341;
12318				io->scsiio.be_move_done(io);
12319				return;
12320			}
12321
12322			msg.dt.sent_sg_entries = sg_entries_sent;
12323		}
12324		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12325	} else {
12326
12327		/*
12328		 * Lookup the fe_datamove() function for this particular
12329		 * front end.
12330		 */
12331		fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12332
12333		fe_datamove(io);
12334	}
12335}
12336
12337static void
12338ctl_send_datamove_done(union ctl_io *io, int have_lock)
12339{
12340	union ctl_ha_msg msg;
12341
12342	memset(&msg, 0, sizeof(msg));
12343
12344	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12345	msg.hdr.original_sc = io;
12346	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12347	msg.hdr.nexus = io->io_hdr.nexus;
12348	msg.hdr.status = io->io_hdr.status;
12349	msg.scsi.tag_num = io->scsiio.tag_num;
12350	msg.scsi.tag_type = io->scsiio.tag_type;
12351	msg.scsi.scsi_status = io->scsiio.scsi_status;
12352	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12353	       io->scsiio.sense_len);
12354	msg.scsi.sense_len = io->scsiio.sense_len;
12355	msg.scsi.sense_residual = io->scsiio.sense_residual;
12356	msg.scsi.fetd_status = io->io_hdr.port_status;
12357	msg.scsi.residual = io->scsiio.residual;
12358	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12359
12360	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12361		ctl_failover_io(io, /*have_lock*/ have_lock);
12362		return;
12363	}
12364
12365	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12366	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12367	    msg.scsi.sense_len, M_WAITOK);
12368}
12369
12370/*
12371 * The DMA to the remote side is done, now we need to tell the other side
12372 * we're done so it can continue with its data movement.
12373 */
12374static void
12375ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12376{
12377	union ctl_io *io;
12378	int i;
12379
12380	io = rq->context;
12381
12382	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12383		printf("%s: ISC DMA write failed with error %d", __func__,
12384		       rq->ret);
12385		ctl_set_internal_failure(&io->scsiio,
12386					 /*sks_valid*/ 1,
12387					 /*retry_count*/ rq->ret);
12388	}
12389
12390	ctl_dt_req_free(rq);
12391
12392	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12393		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12394	free(io->io_hdr.remote_sglist, M_CTL);
12395	io->io_hdr.remote_sglist = NULL;
12396	io->io_hdr.local_sglist = NULL;
12397
12398	/*
12399	 * The data is in local and remote memory, so now we need to send
12400	 * status (good or back) back to the other side.
12401	 */
12402	ctl_send_datamove_done(io, /*have_lock*/ 0);
12403}
12404
12405/*
12406 * We've moved the data from the host/controller into local memory.  Now we
12407 * need to push it over to the remote controller's memory.
12408 */
12409static int
12410ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12411{
12412	int retval;
12413
12414	retval = 0;
12415
12416	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12417					  ctl_datamove_remote_write_cb);
12418
12419	return (retval);
12420}
12421
12422static void
12423ctl_datamove_remote_write(union ctl_io *io)
12424{
12425	int retval;
12426	void (*fe_datamove)(union ctl_io *io);
12427
12428	/*
12429	 * - Get the data from the host/HBA into local memory.
12430	 * - DMA memory from the local controller to the remote controller.
12431	 * - Send status back to the remote controller.
12432	 */
12433
12434	retval = ctl_datamove_remote_sgl_setup(io);
12435	if (retval != 0)
12436		return;
12437
12438	/* Switch the pointer over so the FETD knows what to do */
12439	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12440
12441	/*
12442	 * Use a custom move done callback, since we need to send completion
12443	 * back to the other controller, not to the backend on this side.
12444	 */
12445	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12446
12447	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12448
12449	fe_datamove(io);
12450
12451	return;
12452
12453}
12454
12455static int
12456ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12457{
12458#if 0
12459	char str[256];
12460	char path_str[64];
12461	struct sbuf sb;
12462#endif
12463	int i;
12464
12465	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12466		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12467	free(io->io_hdr.remote_sglist, M_CTL);
12468	io->io_hdr.remote_sglist = NULL;
12469	io->io_hdr.local_sglist = NULL;
12470
12471#if 0
12472	scsi_path_string(io, path_str, sizeof(path_str));
12473	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12474	sbuf_cat(&sb, path_str);
12475	scsi_command_string(&io->scsiio, NULL, &sb);
12476	sbuf_printf(&sb, "\n");
12477	sbuf_cat(&sb, path_str);
12478	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12479		    io->scsiio.tag_num, io->scsiio.tag_type);
12480	sbuf_cat(&sb, path_str);
12481	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12482		    io->io_hdr.flags, io->io_hdr.status);
12483	sbuf_finish(&sb);
12484	printk("%s", sbuf_data(&sb));
12485#endif
12486
12487
12488	/*
12489	 * The read is done, now we need to send status (good or bad) back
12490	 * to the other side.
12491	 */
12492	ctl_send_datamove_done(io, /*have_lock*/ 0);
12493
12494	return (0);
12495}
12496
12497static void
12498ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12499{
12500	union ctl_io *io;
12501	void (*fe_datamove)(union ctl_io *io);
12502
12503	io = rq->context;
12504
12505	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12506		printf("%s: ISC DMA read failed with error %d\n", __func__,
12507		       rq->ret);
12508		ctl_set_internal_failure(&io->scsiio,
12509					 /*sks_valid*/ 1,
12510					 /*retry_count*/ rq->ret);
12511	}
12512
12513	ctl_dt_req_free(rq);
12514
12515	/* Switch the pointer over so the FETD knows what to do */
12516	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12517
12518	/*
12519	 * Use a custom move done callback, since we need to send completion
12520	 * back to the other controller, not to the backend on this side.
12521	 */
12522	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12523
12524	/* XXX KDM add checks like the ones in ctl_datamove? */
12525
12526	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12527
12528	fe_datamove(io);
12529}
12530
12531static int
12532ctl_datamove_remote_sgl_setup(union ctl_io *io)
12533{
12534	struct ctl_sg_entry *local_sglist, *remote_sglist;
12535	struct ctl_softc *softc;
12536	uint32_t len_to_go;
12537	int retval;
12538	int i;
12539
12540	retval = 0;
12541	softc = control_softc;
12542	local_sglist = io->io_hdr.local_sglist;
12543	remote_sglist = io->io_hdr.remote_sglist;
12544	len_to_go = io->scsiio.kern_data_len;
12545
12546	/*
12547	 * The difficult thing here is that the size of the various
12548	 * S/G segments may be different than the size from the
12549	 * remote controller.  That'll make it harder when DMAing
12550	 * the data back to the other side.
12551	 */
12552	for (i = 0; len_to_go > 0; i++) {
12553		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12554		local_sglist[i].addr =
12555		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12556
12557		len_to_go -= local_sglist[i].len;
12558	}
12559	/*
12560	 * Reset the number of S/G entries accordingly.  The original
12561	 * number of S/G entries is available in rem_sg_entries.
12562	 */
12563	io->scsiio.kern_sg_entries = i;
12564
12565#if 0
12566	printf("%s: kern_sg_entries = %d\n", __func__,
12567	       io->scsiio.kern_sg_entries);
12568	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12569		printf("%s: sg[%d] = %p, %d\n", __func__, i,
12570		       local_sglist[i].addr, local_sglist[i].len);
12571#endif
12572
12573	return (retval);
12574}
12575
12576static int
12577ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12578			 ctl_ha_dt_cb callback)
12579{
12580	struct ctl_ha_dt_req *rq;
12581	struct ctl_sg_entry *remote_sglist, *local_sglist;
12582	uint32_t local_used, remote_used, total_used;
12583	int i, j, isc_ret;
12584
12585	rq = ctl_dt_req_alloc();
12586
12587	/*
12588	 * If we failed to allocate the request, and if the DMA didn't fail
12589	 * anyway, set busy status.  This is just a resource allocation
12590	 * failure.
12591	 */
12592	if ((rq == NULL)
12593	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
12594		ctl_set_busy(&io->scsiio);
12595
12596	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
12597
12598		if (rq != NULL)
12599			ctl_dt_req_free(rq);
12600
12601		/*
12602		 * The data move failed.  We need to return status back
12603		 * to the other controller.  No point in trying to DMA
12604		 * data to the remote controller.
12605		 */
12606
12607		ctl_send_datamove_done(io, /*have_lock*/ 0);
12608
12609		return (1);
12610	}
12611
12612	local_sglist = io->io_hdr.local_sglist;
12613	remote_sglist = io->io_hdr.remote_sglist;
12614	local_used = 0;
12615	remote_used = 0;
12616	total_used = 0;
12617
12618	/*
12619	 * Pull/push the data over the wire from/to the other controller.
12620	 * This takes into account the possibility that the local and
12621	 * remote sglists may not be identical in terms of the size of
12622	 * the elements and the number of elements.
12623	 *
12624	 * One fundamental assumption here is that the length allocated for
12625	 * both the local and remote sglists is identical.  Otherwise, we've
12626	 * essentially got a coding error of some sort.
12627	 */
12628	isc_ret = CTL_HA_STATUS_SUCCESS;
12629	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12630		uint32_t cur_len;
12631		uint8_t *tmp_ptr;
12632
12633		rq->command = command;
12634		rq->context = io;
12635
12636		/*
12637		 * Both pointers should be aligned.  But it is possible
12638		 * that the allocation length is not.  They should both
12639		 * also have enough slack left over at the end, though,
12640		 * to round up to the next 8 byte boundary.
12641		 */
12642		cur_len = MIN(local_sglist[i].len - local_used,
12643			      remote_sglist[j].len - remote_used);
12644		rq->size = cur_len;
12645
12646		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12647		tmp_ptr += local_used;
12648
12649#if 0
12650		/* Use physical addresses when talking to ISC hardware */
12651		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12652			/* XXX KDM use busdma */
12653			rq->local = vtophys(tmp_ptr);
12654		} else
12655			rq->local = tmp_ptr;
12656#else
12657		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12658		    ("HA does not support BUS_ADDR"));
12659		rq->local = tmp_ptr;
12660#endif
12661
12662		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12663		tmp_ptr += remote_used;
12664		rq->remote = tmp_ptr;
12665
12666		rq->callback = NULL;
12667
12668		local_used += cur_len;
12669		if (local_used >= local_sglist[i].len) {
12670			i++;
12671			local_used = 0;
12672		}
12673
12674		remote_used += cur_len;
12675		if (remote_used >= remote_sglist[j].len) {
12676			j++;
12677			remote_used = 0;
12678		}
12679		total_used += cur_len;
12680
12681		if (total_used >= io->scsiio.kern_data_len)
12682			rq->callback = callback;
12683
12684#if 0
12685		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
12686		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
12687		       rq->local, rq->remote, rq->size);
12688#endif
12689
12690		isc_ret = ctl_dt_single(rq);
12691		if (isc_ret > CTL_HA_STATUS_SUCCESS)
12692			break;
12693	}
12694	if (isc_ret != CTL_HA_STATUS_WAIT) {
12695		rq->ret = isc_ret;
12696		callback(rq);
12697	}
12698
12699	return (0);
12700}
12701
12702static void
12703ctl_datamove_remote_read(union ctl_io *io)
12704{
12705	int retval;
12706	int i;
12707
12708	/*
12709	 * This will send an error to the other controller in the case of a
12710	 * failure.
12711	 */
12712	retval = ctl_datamove_remote_sgl_setup(io);
12713	if (retval != 0)
12714		return;
12715
12716	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12717					  ctl_datamove_remote_read_cb);
12718	if (retval != 0) {
12719		/*
12720		 * Make sure we free memory if there was an error..  The
12721		 * ctl_datamove_remote_xfer() function will send the
12722		 * datamove done message, or call the callback with an
12723		 * error if there is a problem.
12724		 */
12725		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12726			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12727		free(io->io_hdr.remote_sglist, M_CTL);
12728		io->io_hdr.remote_sglist = NULL;
12729		io->io_hdr.local_sglist = NULL;
12730	}
12731
12732	return;
12733}
12734
12735/*
12736 * Process a datamove request from the other controller.  This is used for
12737 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12738 * first.  Once that is complete, the data gets DMAed into the remote
12739 * controller's memory.  For reads, we DMA from the remote controller's
12740 * memory into our memory first, and then move it out to the FETD.
12741 */
12742static void
12743ctl_datamove_remote(union ctl_io *io)
12744{
12745
12746	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12747
12748	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12749		ctl_failover_io(io, /*have_lock*/ 0);
12750		return;
12751	}
12752
12753	/*
12754	 * Note that we look for an aborted I/O here, but don't do some of
12755	 * the other checks that ctl_datamove() normally does.
12756	 * We don't need to run the datamove delay code, since that should
12757	 * have been done if need be on the other controller.
12758	 */
12759	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12760		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
12761		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12762		       io->io_hdr.nexus.targ_port,
12763		       io->io_hdr.nexus.targ_lun);
12764		io->io_hdr.port_status = 31338;
12765		ctl_send_datamove_done(io, /*have_lock*/ 0);
12766		return;
12767	}
12768
12769	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
12770		ctl_datamove_remote_write(io);
12771	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
12772		ctl_datamove_remote_read(io);
12773	else {
12774		io->io_hdr.port_status = 31339;
12775		ctl_send_datamove_done(io, /*have_lock*/ 0);
12776	}
12777}
12778
12779static int
12780ctl_process_done(union ctl_io *io)
12781{
12782	struct ctl_lun *lun;
12783	struct ctl_softc *softc = control_softc;
12784	void (*fe_done)(union ctl_io *io);
12785	union ctl_ha_msg msg;
12786	uint32_t targ_port = io->io_hdr.nexus.targ_port;
12787
12788	CTL_DEBUG_PRINT(("ctl_process_done\n"));
12789
12790	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0)
12791		fe_done = softc->ctl_ports[targ_port]->fe_done;
12792	else
12793		fe_done = NULL;
12794
12795#ifdef CTL_TIME_IO
12796	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12797		char str[256];
12798		char path_str[64];
12799		struct sbuf sb;
12800
12801		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12802		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12803
12804		sbuf_cat(&sb, path_str);
12805		switch (io->io_hdr.io_type) {
12806		case CTL_IO_SCSI:
12807			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12808			sbuf_printf(&sb, "\n");
12809			sbuf_cat(&sb, path_str);
12810			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12811				    io->scsiio.tag_num, io->scsiio.tag_type);
12812			break;
12813		case CTL_IO_TASK:
12814			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12815				    "Tag Type: %d\n", io->taskio.task_action,
12816				    io->taskio.tag_num, io->taskio.tag_type);
12817			break;
12818		default:
12819			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12820			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12821			break;
12822		}
12823		sbuf_cat(&sb, path_str);
12824		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
12825			    (intmax_t)time_uptime - io->io_hdr.start_time);
12826		sbuf_finish(&sb);
12827		printf("%s", sbuf_data(&sb));
12828	}
12829#endif /* CTL_TIME_IO */
12830
12831	switch (io->io_hdr.io_type) {
12832	case CTL_IO_SCSI:
12833		break;
12834	case CTL_IO_TASK:
12835		if (ctl_debug & CTL_DEBUG_INFO)
12836			ctl_io_error_print(io, NULL);
12837		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
12838			ctl_free_io(io);
12839		else
12840			fe_done(io);
12841		return (CTL_RETVAL_COMPLETE);
12842	default:
12843		panic("ctl_process_done: invalid io type %d\n",
12844		      io->io_hdr.io_type);
12845		break; /* NOTREACHED */
12846	}
12847
12848	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12849	if (lun == NULL) {
12850		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
12851				 io->io_hdr.nexus.targ_mapped_lun));
12852		goto bailout;
12853	}
12854
12855	mtx_lock(&lun->lun_lock);
12856
12857	/*
12858	 * Check to see if we have any errors to inject here.  We only
12859	 * inject errors for commands that don't already have errors set.
12860	 */
12861	if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
12862	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
12863	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
12864		ctl_inject_error(lun, io);
12865
12866	/*
12867	 * XXX KDM how do we treat commands that aren't completed
12868	 * successfully?
12869	 *
12870	 * XXX KDM should we also track I/O latency?
12871	 */
12872	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
12873	    io->io_hdr.io_type == CTL_IO_SCSI) {
12874#ifdef CTL_TIME_IO
12875		struct bintime cur_bt;
12876#endif
12877		int type;
12878
12879		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12880		    CTL_FLAG_DATA_IN)
12881			type = CTL_STATS_READ;
12882		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12883		    CTL_FLAG_DATA_OUT)
12884			type = CTL_STATS_WRITE;
12885		else
12886			type = CTL_STATS_NO_IO;
12887
12888		lun->stats.ports[targ_port].bytes[type] +=
12889		    io->scsiio.kern_total_len;
12890		lun->stats.ports[targ_port].operations[type]++;
12891#ifdef CTL_TIME_IO
12892		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
12893		   &io->io_hdr.dma_bt);
12894		lun->stats.ports[targ_port].num_dmas[type] +=
12895		    io->io_hdr.num_dmas;
12896		getbintime(&cur_bt);
12897		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
12898		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
12899#endif
12900	}
12901
12902	/*
12903	 * Remove this from the OOA queue.
12904	 */
12905	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
12906#ifdef CTL_TIME_IO
12907	if (TAILQ_EMPTY(&lun->ooa_queue))
12908		lun->last_busy = getsbinuptime();
12909#endif
12910
12911	/*
12912	 * Run through the blocked queue on this LUN and see if anything
12913	 * has become unblocked, now that this transaction is done.
12914	 */
12915	ctl_check_blocked(lun);
12916
12917	/*
12918	 * If the LUN has been invalidated, free it if there is nothing
12919	 * left on its OOA queue.
12920	 */
12921	if ((lun->flags & CTL_LUN_INVALID)
12922	 && TAILQ_EMPTY(&lun->ooa_queue)) {
12923		mtx_unlock(&lun->lun_lock);
12924		mtx_lock(&softc->ctl_lock);
12925		ctl_free_lun(lun);
12926		mtx_unlock(&softc->ctl_lock);
12927	} else
12928		mtx_unlock(&lun->lun_lock);
12929
12930bailout:
12931
12932	/*
12933	 * If this command has been aborted, make sure we set the status
12934	 * properly.  The FETD is responsible for freeing the I/O and doing
12935	 * whatever it needs to do to clean up its state.
12936	 */
12937	if (io->io_hdr.flags & CTL_FLAG_ABORT)
12938		ctl_set_task_aborted(&io->scsiio);
12939
12940	/*
12941	 * If enabled, print command error status.
12942	 */
12943	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
12944	    (ctl_debug & CTL_DEBUG_INFO) != 0)
12945		ctl_io_error_print(io, NULL);
12946
12947	/*
12948	 * Tell the FETD or the other shelf controller we're done with this
12949	 * command.  Note that only SCSI commands get to this point.  Task
12950	 * management commands are completed above.
12951	 */
12952	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
12953	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
12954		memset(&msg, 0, sizeof(msg));
12955		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
12956		msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12957		msg.hdr.nexus = io->io_hdr.nexus;
12958		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12959		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
12960		    M_WAITOK);
12961	}
12962	if ((softc->ha_mode == CTL_HA_MODE_XFER)
12963	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12964		memset(&msg, 0, sizeof(msg));
12965		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
12966		msg.hdr.original_sc = io->io_hdr.original_sc;
12967		msg.hdr.nexus = io->io_hdr.nexus;
12968		msg.hdr.status = io->io_hdr.status;
12969		msg.scsi.scsi_status = io->scsiio.scsi_status;
12970		msg.scsi.tag_num = io->scsiio.tag_num;
12971		msg.scsi.tag_type = io->scsiio.tag_type;
12972		msg.scsi.sense_len = io->scsiio.sense_len;
12973		msg.scsi.sense_residual = io->scsiio.sense_residual;
12974		msg.scsi.residual = io->scsiio.residual;
12975		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12976		       io->scsiio.sense_len);
12977
12978		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12979		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12980		    msg.scsi.sense_len, M_WAITOK);
12981		ctl_free_io(io);
12982	} else
12983		fe_done(io);
12984
12985	return (CTL_RETVAL_COMPLETE);
12986}
12987
12988#ifdef CTL_WITH_CA
12989/*
12990 * Front end should call this if it doesn't do autosense.  When the request
12991 * sense comes back in from the initiator, we'll dequeue this and send it.
12992 */
12993int
12994ctl_queue_sense(union ctl_io *io)
12995{
12996	struct ctl_lun *lun;
12997	struct ctl_port *port;
12998	struct ctl_softc *softc;
12999	uint32_t initidx, targ_lun;
13000
13001	softc = control_softc;
13002
13003	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13004
13005	/*
13006	 * LUN lookup will likely move to the ctl_work_thread() once we
13007	 * have our new queueing infrastructure (that doesn't put things on
13008	 * a per-LUN queue initially).  That is so that we can handle
13009	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13010	 * can't deal with that right now.
13011	 */
13012	mtx_lock(&softc->ctl_lock);
13013
13014	/*
13015	 * If we don't have a LUN for this, just toss the sense
13016	 * information.
13017	 */
13018	port = ctl_io_port(&ctsio->io_hdr);
13019	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13020	if ((targ_lun < CTL_MAX_LUNS)
13021	 && (softc->ctl_luns[targ_lun] != NULL))
13022		lun = softc->ctl_luns[targ_lun];
13023	else
13024		goto bailout;
13025
13026	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13027
13028	mtx_lock(&lun->lun_lock);
13029	/*
13030	 * Already have CA set for this LUN...toss the sense information.
13031	 */
13032	if (ctl_is_set(lun->have_ca, initidx)) {
13033		mtx_unlock(&lun->lun_lock);
13034		goto bailout;
13035	}
13036
13037	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13038	       MIN(sizeof(lun->pending_sense[initidx]),
13039	       sizeof(io->scsiio.sense_data)));
13040	ctl_set_mask(lun->have_ca, initidx);
13041	mtx_unlock(&lun->lun_lock);
13042
13043bailout:
13044	mtx_unlock(&softc->ctl_lock);
13045
13046	ctl_free_io(io);
13047
13048	return (CTL_RETVAL_COMPLETE);
13049}
13050#endif
13051
13052/*
13053 * Primary command inlet from frontend ports.  All SCSI and task I/O
13054 * requests must go through this function.
13055 */
13056int
13057ctl_queue(union ctl_io *io)
13058{
13059	struct ctl_port *port;
13060
13061	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13062
13063#ifdef CTL_TIME_IO
13064	io->io_hdr.start_time = time_uptime;
13065	getbintime(&io->io_hdr.start_bt);
13066#endif /* CTL_TIME_IO */
13067
13068	/* Map FE-specific LUN ID into global one. */
13069	port = ctl_io_port(&io->io_hdr);
13070	io->io_hdr.nexus.targ_mapped_lun =
13071	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13072
13073	switch (io->io_hdr.io_type) {
13074	case CTL_IO_SCSI:
13075	case CTL_IO_TASK:
13076		if (ctl_debug & CTL_DEBUG_CDB)
13077			ctl_io_print(io);
13078		ctl_enqueue_incoming(io);
13079		break;
13080	default:
13081		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13082		return (EINVAL);
13083	}
13084
13085	return (CTL_RETVAL_COMPLETE);
13086}
13087
13088#ifdef CTL_IO_DELAY
13089static void
13090ctl_done_timer_wakeup(void *arg)
13091{
13092	union ctl_io *io;
13093
13094	io = (union ctl_io *)arg;
13095	ctl_done(io);
13096}
13097#endif /* CTL_IO_DELAY */
13098
13099void
13100ctl_done(union ctl_io *io)
13101{
13102
13103	/*
13104	 * Enable this to catch duplicate completion issues.
13105	 */
13106#if 0
13107	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13108		printf("%s: type %d msg %d cdb %x iptl: "
13109		       "%u:%u:%u tag 0x%04x "
13110		       "flag %#x status %x\n",
13111			__func__,
13112			io->io_hdr.io_type,
13113			io->io_hdr.msg_type,
13114			io->scsiio.cdb[0],
13115			io->io_hdr.nexus.initid,
13116			io->io_hdr.nexus.targ_port,
13117			io->io_hdr.nexus.targ_lun,
13118			(io->io_hdr.io_type ==
13119			CTL_IO_TASK) ?
13120			io->taskio.tag_num :
13121			io->scsiio.tag_num,
13122		        io->io_hdr.flags,
13123			io->io_hdr.status);
13124	} else
13125		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13126#endif
13127
13128	/*
13129	 * This is an internal copy of an I/O, and should not go through
13130	 * the normal done processing logic.
13131	 */
13132	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13133		return;
13134
13135#ifdef CTL_IO_DELAY
13136	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13137		struct ctl_lun *lun;
13138
13139		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13140
13141		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13142	} else {
13143		struct ctl_lun *lun;
13144
13145		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13146
13147		if ((lun != NULL)
13148		 && (lun->delay_info.done_delay > 0)) {
13149
13150			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13151			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13152			callout_reset(&io->io_hdr.delay_callout,
13153				      lun->delay_info.done_delay * hz,
13154				      ctl_done_timer_wakeup, io);
13155			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13156				lun->delay_info.done_delay = 0;
13157			return;
13158		}
13159	}
13160#endif /* CTL_IO_DELAY */
13161
13162	ctl_enqueue_done(io);
13163}
13164
13165static void
13166ctl_work_thread(void *arg)
13167{
13168	struct ctl_thread *thr = (struct ctl_thread *)arg;
13169	struct ctl_softc *softc = thr->ctl_softc;
13170	union ctl_io *io;
13171	int retval;
13172
13173	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13174
13175	for (;;) {
13176		retval = 0;
13177
13178		/*
13179		 * We handle the queues in this order:
13180		 * - ISC
13181		 * - done queue (to free up resources, unblock other commands)
13182		 * - RtR queue
13183		 * - incoming queue
13184		 *
13185		 * If those queues are empty, we break out of the loop and
13186		 * go to sleep.
13187		 */
13188		mtx_lock(&thr->queue_lock);
13189		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13190		if (io != NULL) {
13191			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13192			mtx_unlock(&thr->queue_lock);
13193			ctl_handle_isc(io);
13194			continue;
13195		}
13196		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13197		if (io != NULL) {
13198			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13199			/* clear any blocked commands, call fe_done */
13200			mtx_unlock(&thr->queue_lock);
13201			retval = ctl_process_done(io);
13202			continue;
13203		}
13204		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13205		if (io != NULL) {
13206			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13207			mtx_unlock(&thr->queue_lock);
13208			if (io->io_hdr.io_type == CTL_IO_TASK)
13209				ctl_run_task(io);
13210			else
13211				ctl_scsiio_precheck(softc, &io->scsiio);
13212			continue;
13213		}
13214		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13215		if (io != NULL) {
13216			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13217			mtx_unlock(&thr->queue_lock);
13218			retval = ctl_scsiio(&io->scsiio);
13219			if (retval != CTL_RETVAL_COMPLETE)
13220				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13221			continue;
13222		}
13223
13224		/* Sleep until we have something to do. */
13225		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13226	}
13227}
13228
13229static void
13230ctl_lun_thread(void *arg)
13231{
13232	struct ctl_softc *softc = (struct ctl_softc *)arg;
13233	struct ctl_be_lun *be_lun;
13234	int retval;
13235
13236	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13237
13238	for (;;) {
13239		retval = 0;
13240		mtx_lock(&softc->ctl_lock);
13241		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13242		if (be_lun != NULL) {
13243			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13244			mtx_unlock(&softc->ctl_lock);
13245			ctl_create_lun(be_lun);
13246			continue;
13247		}
13248
13249		/* Sleep until we have something to do. */
13250		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13251		    PDROP | PRIBIO, "-", 0);
13252	}
13253}
13254
13255static void
13256ctl_thresh_thread(void *arg)
13257{
13258	struct ctl_softc *softc = (struct ctl_softc *)arg;
13259	struct ctl_lun *lun;
13260	struct ctl_be_lun *be_lun;
13261	struct scsi_da_rw_recovery_page *rwpage;
13262	struct ctl_logical_block_provisioning_page *page;
13263	const char *attr;
13264	union ctl_ha_msg msg;
13265	uint64_t thres, val;
13266	int i, e, set;
13267
13268	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13269
13270	for (;;) {
13271		mtx_lock(&softc->ctl_lock);
13272		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13273			be_lun = lun->be_lun;
13274			if ((lun->flags & CTL_LUN_DISABLED) ||
13275			    (lun->flags & CTL_LUN_OFFLINE) ||
13276			    lun->backend->lun_attr == NULL)
13277				continue;
13278			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13279			    softc->ha_mode == CTL_HA_MODE_XFER)
13280				continue;
13281			rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13282			if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13283				continue;
13284			e = 0;
13285			page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13286			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13287				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13288					continue;
13289				thres = scsi_4btoul(page->descr[i].count);
13290				thres <<= CTL_LBP_EXPONENT;
13291				switch (page->descr[i].resource) {
13292				case 0x01:
13293					attr = "blocksavail";
13294					break;
13295				case 0x02:
13296					attr = "blocksused";
13297					break;
13298				case 0xf1:
13299					attr = "poolblocksavail";
13300					break;
13301				case 0xf2:
13302					attr = "poolblocksused";
13303					break;
13304				default:
13305					continue;
13306				}
13307				mtx_unlock(&softc->ctl_lock); // XXX
13308				val = lun->backend->lun_attr(
13309				    lun->be_lun->be_lun, attr);
13310				mtx_lock(&softc->ctl_lock);
13311				if (val == UINT64_MAX)
13312					continue;
13313				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13314				    == SLBPPD_ARMING_INC)
13315					e |= (val >= thres);
13316				else
13317					e |= (val <= thres);
13318			}
13319			mtx_lock(&lun->lun_lock);
13320			if (e) {
13321				if (lun->lasttpt == 0 ||
13322				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13323					lun->lasttpt = time_uptime;
13324					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13325					set = 1;
13326				} else
13327					set = 0;
13328			} else {
13329				lun->lasttpt = 0;
13330				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13331				set = -1;
13332			}
13333			mtx_unlock(&lun->lun_lock);
13334			if (set != 0 &&
13335			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13336				/* Send msg to other side. */
13337				bzero(&msg.ua, sizeof(msg.ua));
13338				msg.hdr.msg_type = CTL_MSG_UA;
13339				msg.hdr.nexus.initid = -1;
13340				msg.hdr.nexus.targ_port = -1;
13341				msg.hdr.nexus.targ_lun = lun->lun;
13342				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13343				msg.ua.ua_all = 1;
13344				msg.ua.ua_set = (set > 0);
13345				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13346				mtx_unlock(&softc->ctl_lock); // XXX
13347				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13348				    sizeof(msg.ua), M_WAITOK);
13349				mtx_lock(&softc->ctl_lock);
13350			}
13351		}
13352		mtx_unlock(&softc->ctl_lock);
13353		pause("-", CTL_LBP_PERIOD * hz);
13354	}
13355}
13356
13357static void
13358ctl_enqueue_incoming(union ctl_io *io)
13359{
13360	struct ctl_softc *softc = control_softc;
13361	struct ctl_thread *thr;
13362	u_int idx;
13363
13364	idx = (io->io_hdr.nexus.targ_port * 127 +
13365	       io->io_hdr.nexus.initid) % worker_threads;
13366	thr = &softc->threads[idx];
13367	mtx_lock(&thr->queue_lock);
13368	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13369	mtx_unlock(&thr->queue_lock);
13370	wakeup(thr);
13371}
13372
13373static void
13374ctl_enqueue_rtr(union ctl_io *io)
13375{
13376	struct ctl_softc *softc = control_softc;
13377	struct ctl_thread *thr;
13378
13379	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13380	mtx_lock(&thr->queue_lock);
13381	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13382	mtx_unlock(&thr->queue_lock);
13383	wakeup(thr);
13384}
13385
13386static void
13387ctl_enqueue_done(union ctl_io *io)
13388{
13389	struct ctl_softc *softc = control_softc;
13390	struct ctl_thread *thr;
13391
13392	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13393	mtx_lock(&thr->queue_lock);
13394	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13395	mtx_unlock(&thr->queue_lock);
13396	wakeup(thr);
13397}
13398
13399static void
13400ctl_enqueue_isc(union ctl_io *io)
13401{
13402	struct ctl_softc *softc = control_softc;
13403	struct ctl_thread *thr;
13404
13405	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13406	mtx_lock(&thr->queue_lock);
13407	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13408	mtx_unlock(&thr->queue_lock);
13409	wakeup(thr);
13410}
13411
13412/*
13413 *  vim: ts=8
13414 */
13415