ctl.c revision 275455
1/*-
2 * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3 * Copyright (c) 2012 The FreeBSD Foundation
4 * All rights reserved.
5 *
6 * Portions of this software were developed by Edward Tomasz Napierala
7 * under sponsorship from the FreeBSD Foundation.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions, and the following disclaimer,
14 *    without modification.
15 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
16 *    substantially similar to the "NO WARRANTY" disclaimer below
17 *    ("Disclaimer") and any redistribution must be conditioned upon
18 *    including a substantially similar Disclaimer requirement for further
19 *    binary redistribution.
20 *
21 * NO WARRANTY
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
25 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
31 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGES.
33 *
34 * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/ctl.c#8 $
35 */
36/*
37 * CAM Target Layer, a SCSI device emulation subsystem.
38 *
39 * Author: Ken Merry <ken@FreeBSD.org>
40 */
41
42#define _CTL_C
43
44#include <sys/cdefs.h>
45__FBSDID("$FreeBSD: head/sys/cam/ctl/ctl.c 275455 2014-12-03 10:39:47Z mav $");
46
47#include <sys/param.h>
48#include <sys/systm.h>
49#include <sys/ctype.h>
50#include <sys/kernel.h>
51#include <sys/types.h>
52#include <sys/kthread.h>
53#include <sys/bio.h>
54#include <sys/fcntl.h>
55#include <sys/lock.h>
56#include <sys/module.h>
57#include <sys/mutex.h>
58#include <sys/condvar.h>
59#include <sys/malloc.h>
60#include <sys/conf.h>
61#include <sys/ioccom.h>
62#include <sys/queue.h>
63#include <sys/sbuf.h>
64#include <sys/smp.h>
65#include <sys/endian.h>
66#include <sys/sysctl.h>
67#include <vm/uma.h>
68
69#include <cam/cam.h>
70#include <cam/scsi/scsi_all.h>
71#include <cam/scsi/scsi_da.h>
72#include <cam/ctl/ctl_io.h>
73#include <cam/ctl/ctl.h>
74#include <cam/ctl/ctl_frontend.h>
75#include <cam/ctl/ctl_frontend_internal.h>
76#include <cam/ctl/ctl_util.h>
77#include <cam/ctl/ctl_backend.h>
78#include <cam/ctl/ctl_ioctl.h>
79#include <cam/ctl/ctl_ha.h>
80#include <cam/ctl/ctl_private.h>
81#include <cam/ctl/ctl_debug.h>
82#include <cam/ctl/ctl_scsi_all.h>
83#include <cam/ctl/ctl_error.h>
84
85struct ctl_softc *control_softc = NULL;
86
87/*
88 * Size and alignment macros needed for Copan-specific HA hardware.  These
89 * can go away when the HA code is re-written, and uses busdma for any
90 * hardware.
91 */
92#define	CTL_ALIGN_8B(target, source, type)				\
93	if (((uint32_t)source & 0x7) != 0)				\
94		target = (type)(source + (0x8 - ((uint32_t)source & 0x7)));\
95	else								\
96		target = (type)source;
97
98#define	CTL_SIZE_8B(target, size)					\
99	if ((size & 0x7) != 0)						\
100		target = size + (0x8 - (size & 0x7));			\
101	else								\
102		target = size;
103
104#define CTL_ALIGN_8B_MARGIN	16
105
106/*
107 * Template mode pages.
108 */
109
110/*
111 * Note that these are default values only.  The actual values will be
112 * filled in when the user does a mode sense.
113 */
114static struct copan_debugconf_subpage debugconf_page_default = {
115	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
116	DBGCNF_SUBPAGE_CODE,		/* subpage */
117	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
118	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
119	DBGCNF_VERSION,			/* page_version */
120	{CTL_TIME_IO_DEFAULT_SECS>>8,
121	 CTL_TIME_IO_DEFAULT_SECS>>0},	/* ctl_time_io_secs */
122};
123
124static struct copan_debugconf_subpage debugconf_page_changeable = {
125	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
126	DBGCNF_SUBPAGE_CODE,		/* subpage */
127	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
128	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
129	0,				/* page_version */
130	{0xff,0xff},			/* ctl_time_io_secs */
131};
132
133static struct scsi_da_rw_recovery_page rw_er_page_default = {
134	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
135	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
136	/*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
137	/*read_retry_count*/0,
138	/*correction_span*/0,
139	/*head_offset_count*/0,
140	/*data_strobe_offset_cnt*/0,
141	/*byte8*/SMS_RWER_LBPERE,
142	/*write_retry_count*/0,
143	/*reserved2*/0,
144	/*recovery_time_limit*/{0, 0},
145};
146
147static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
148	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
149	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
150	/*byte3*/0,
151	/*read_retry_count*/0,
152	/*correction_span*/0,
153	/*head_offset_count*/0,
154	/*data_strobe_offset_cnt*/0,
155	/*byte8*/0,
156	/*write_retry_count*/0,
157	/*reserved2*/0,
158	/*recovery_time_limit*/{0, 0},
159};
160
161static struct scsi_format_page format_page_default = {
162	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
163	/*page_length*/sizeof(struct scsi_format_page) - 2,
164	/*tracks_per_zone*/ {0, 0},
165	/*alt_sectors_per_zone*/ {0, 0},
166	/*alt_tracks_per_zone*/ {0, 0},
167	/*alt_tracks_per_lun*/ {0, 0},
168	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
169			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
170	/*bytes_per_sector*/ {0, 0},
171	/*interleave*/ {0, 0},
172	/*track_skew*/ {0, 0},
173	/*cylinder_skew*/ {0, 0},
174	/*flags*/ SFP_HSEC,
175	/*reserved*/ {0, 0, 0}
176};
177
178static struct scsi_format_page format_page_changeable = {
179	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
180	/*page_length*/sizeof(struct scsi_format_page) - 2,
181	/*tracks_per_zone*/ {0, 0},
182	/*alt_sectors_per_zone*/ {0, 0},
183	/*alt_tracks_per_zone*/ {0, 0},
184	/*alt_tracks_per_lun*/ {0, 0},
185	/*sectors_per_track*/ {0, 0},
186	/*bytes_per_sector*/ {0, 0},
187	/*interleave*/ {0, 0},
188	/*track_skew*/ {0, 0},
189	/*cylinder_skew*/ {0, 0},
190	/*flags*/ 0,
191	/*reserved*/ {0, 0, 0}
192};
193
194static struct scsi_rigid_disk_page rigid_disk_page_default = {
195	/*page_code*/SMS_RIGID_DISK_PAGE,
196	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
197	/*cylinders*/ {0, 0, 0},
198	/*heads*/ CTL_DEFAULT_HEADS,
199	/*start_write_precomp*/ {0, 0, 0},
200	/*start_reduced_current*/ {0, 0, 0},
201	/*step_rate*/ {0, 0},
202	/*landing_zone_cylinder*/ {0, 0, 0},
203	/*rpl*/ SRDP_RPL_DISABLED,
204	/*rotational_offset*/ 0,
205	/*reserved1*/ 0,
206	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
207			   CTL_DEFAULT_ROTATION_RATE & 0xff},
208	/*reserved2*/ {0, 0}
209};
210
211static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
212	/*page_code*/SMS_RIGID_DISK_PAGE,
213	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
214	/*cylinders*/ {0, 0, 0},
215	/*heads*/ 0,
216	/*start_write_precomp*/ {0, 0, 0},
217	/*start_reduced_current*/ {0, 0, 0},
218	/*step_rate*/ {0, 0},
219	/*landing_zone_cylinder*/ {0, 0, 0},
220	/*rpl*/ 0,
221	/*rotational_offset*/ 0,
222	/*reserved1*/ 0,
223	/*rotation_rate*/ {0, 0},
224	/*reserved2*/ {0, 0}
225};
226
227static struct scsi_caching_page caching_page_default = {
228	/*page_code*/SMS_CACHING_PAGE,
229	/*page_length*/sizeof(struct scsi_caching_page) - 2,
230	/*flags1*/ SCP_DISC | SCP_WCE,
231	/*ret_priority*/ 0,
232	/*disable_pf_transfer_len*/ {0xff, 0xff},
233	/*min_prefetch*/ {0, 0},
234	/*max_prefetch*/ {0xff, 0xff},
235	/*max_pf_ceiling*/ {0xff, 0xff},
236	/*flags2*/ 0,
237	/*cache_segments*/ 0,
238	/*cache_seg_size*/ {0, 0},
239	/*reserved*/ 0,
240	/*non_cache_seg_size*/ {0, 0, 0}
241};
242
243static struct scsi_caching_page caching_page_changeable = {
244	/*page_code*/SMS_CACHING_PAGE,
245	/*page_length*/sizeof(struct scsi_caching_page) - 2,
246	/*flags1*/ SCP_WCE | SCP_RCD,
247	/*ret_priority*/ 0,
248	/*disable_pf_transfer_len*/ {0, 0},
249	/*min_prefetch*/ {0, 0},
250	/*max_prefetch*/ {0, 0},
251	/*max_pf_ceiling*/ {0, 0},
252	/*flags2*/ 0,
253	/*cache_segments*/ 0,
254	/*cache_seg_size*/ {0, 0},
255	/*reserved*/ 0,
256	/*non_cache_seg_size*/ {0, 0, 0}
257};
258
259static struct scsi_control_page control_page_default = {
260	/*page_code*/SMS_CONTROL_MODE_PAGE,
261	/*page_length*/sizeof(struct scsi_control_page) - 2,
262	/*rlec*/0,
263	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
264	/*eca_and_aen*/0,
265	/*flags4*/SCP_TAS,
266	/*aen_holdoff_period*/{0, 0},
267	/*busy_timeout_period*/{0, 0},
268	/*extended_selftest_completion_time*/{0, 0}
269};
270
271static struct scsi_control_page control_page_changeable = {
272	/*page_code*/SMS_CONTROL_MODE_PAGE,
273	/*page_length*/sizeof(struct scsi_control_page) - 2,
274	/*rlec*/SCP_DSENSE,
275	/*queue_flags*/SCP_QUEUE_ALG_MASK,
276	/*eca_and_aen*/SCP_SWP,
277	/*flags4*/0,
278	/*aen_holdoff_period*/{0, 0},
279	/*busy_timeout_period*/{0, 0},
280	/*extended_selftest_completion_time*/{0, 0}
281};
282
283static struct scsi_info_exceptions_page ie_page_default = {
284	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
285	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
286	/*info_flags*/SIEP_FLAGS_DEXCPT,
287	/*mrie*/0,
288	/*interval_timer*/{0, 0, 0, 0},
289	/*report_count*/{0, 0, 0, 0}
290};
291
292static struct scsi_info_exceptions_page ie_page_changeable = {
293	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
294	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
295	/*info_flags*/0,
296	/*mrie*/0,
297	/*interval_timer*/{0, 0, 0, 0},
298	/*report_count*/{0, 0, 0, 0}
299};
300
301#define CTL_LBPM_LEN	(sizeof(struct ctl_logical_block_provisioning_page) - 4)
302
303static struct ctl_logical_block_provisioning_page lbp_page_default = {{
304	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
305	/*subpage_code*/0x02,
306	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
307	/*flags*/0,
308	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
309	/*descr*/{}},
310	{{/*flags*/0,
311	  /*resource*/0x01,
312	  /*reserved*/{0, 0},
313	  /*count*/{0, 0, 0, 0}},
314	 {/*flags*/0,
315	  /*resource*/0x02,
316	  /*reserved*/{0, 0},
317	  /*count*/{0, 0, 0, 0}},
318	 {/*flags*/0,
319	  /*resource*/0xf1,
320	  /*reserved*/{0, 0},
321	  /*count*/{0, 0, 0, 0}},
322	 {/*flags*/0,
323	  /*resource*/0xf2,
324	  /*reserved*/{0, 0},
325	  /*count*/{0, 0, 0, 0}}
326	}
327};
328
329static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
330	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
331	/*subpage_code*/0x02,
332	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
333	/*flags*/0,
334	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
335	/*descr*/{}},
336	{{/*flags*/0,
337	  /*resource*/0,
338	  /*reserved*/{0, 0},
339	  /*count*/{0, 0, 0, 0}},
340	 {/*flags*/0,
341	  /*resource*/0,
342	  /*reserved*/{0, 0},
343	  /*count*/{0, 0, 0, 0}},
344	 {/*flags*/0,
345	  /*resource*/0,
346	  /*reserved*/{0, 0},
347	  /*count*/{0, 0, 0, 0}},
348	 {/*flags*/0,
349	  /*resource*/0,
350	  /*reserved*/{0, 0},
351	  /*count*/{0, 0, 0, 0}}
352	}
353};
354
355/*
356 * XXX KDM move these into the softc.
357 */
358static int rcv_sync_msg;
359static uint8_t ctl_pause_rtr;
360
361SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
362static int worker_threads = -1;
363SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
364    &worker_threads, 1, "Number of worker threads");
365static int ctl_debug = CTL_DEBUG_NONE;
366SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
367    &ctl_debug, 0, "Enabled debug flags");
368
369/*
370 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
371 * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
372 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
373 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
374 */
375#define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
376
377static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
378				  int param);
379static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
380static int ctl_init(void);
381void ctl_shutdown(void);
382static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
383static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
384static void ctl_ioctl_online(void *arg);
385static void ctl_ioctl_offline(void *arg);
386static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
387static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
388static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
389static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
390static int ctl_ioctl_submit_wait(union ctl_io *io);
391static void ctl_ioctl_datamove(union ctl_io *io);
392static void ctl_ioctl_done(union ctl_io *io);
393static void ctl_ioctl_hard_startstop_callback(void *arg,
394					      struct cfi_metatask *metatask);
395static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
396static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
397			      struct ctl_ooa *ooa_hdr,
398			      struct ctl_ooa_entry *kern_entries);
399static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
400		     struct thread *td);
401static uint32_t ctl_map_lun(int port_num, uint32_t lun);
402static uint32_t ctl_map_lun_back(int port_num, uint32_t lun);
403static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
404			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
405static int ctl_free_lun(struct ctl_lun *lun);
406static void ctl_create_lun(struct ctl_be_lun *be_lun);
407/**
408static void ctl_failover_change_pages(struct ctl_softc *softc,
409				      struct ctl_scsiio *ctsio, int master);
410**/
411
412static int ctl_do_mode_select(union ctl_io *io);
413static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
414			   uint64_t res_key, uint64_t sa_res_key,
415			   uint8_t type, uint32_t residx,
416			   struct ctl_scsiio *ctsio,
417			   struct scsi_per_res_out *cdb,
418			   struct scsi_per_res_out_parms* param);
419static void ctl_pro_preempt_other(struct ctl_lun *lun,
420				  union ctl_ha_msg *msg);
421static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
422static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
423static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
424static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
425static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
426static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
427static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
428					 int alloc_len);
429static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
430					 int alloc_len);
431static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
432static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
433static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
434static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
435static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
436static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
437static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
438    union ctl_io *pending_io, union ctl_io *ooa_io);
439static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
440				union ctl_io *starting_io);
441static int ctl_check_blocked(struct ctl_lun *lun);
442static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
443				struct ctl_lun *lun,
444				const struct ctl_cmd_entry *entry,
445				struct ctl_scsiio *ctsio);
446//static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
447static void ctl_failover(void);
448static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
449			       struct ctl_scsiio *ctsio);
450static int ctl_scsiio(struct ctl_scsiio *ctsio);
451
452static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
453static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
454			    ctl_ua_type ua_type);
455static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
456			 ctl_ua_type ua_type);
457static int ctl_abort_task(union ctl_io *io);
458static int ctl_abort_task_set(union ctl_io *io);
459static int ctl_i_t_nexus_reset(union ctl_io *io);
460static void ctl_run_task(union ctl_io *io);
461#ifdef CTL_IO_DELAY
462static void ctl_datamove_timer_wakeup(void *arg);
463static void ctl_done_timer_wakeup(void *arg);
464#endif /* CTL_IO_DELAY */
465
466static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
467static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
468static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
469static void ctl_datamove_remote_write(union ctl_io *io);
470static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
471static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
472static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
473static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
474				    ctl_ha_dt_cb callback);
475static void ctl_datamove_remote_read(union ctl_io *io);
476static void ctl_datamove_remote(union ctl_io *io);
477static int ctl_process_done(union ctl_io *io);
478static void ctl_lun_thread(void *arg);
479static void ctl_thresh_thread(void *arg);
480static void ctl_work_thread(void *arg);
481static void ctl_enqueue_incoming(union ctl_io *io);
482static void ctl_enqueue_rtr(union ctl_io *io);
483static void ctl_enqueue_done(union ctl_io *io);
484static void ctl_enqueue_isc(union ctl_io *io);
485static const struct ctl_cmd_entry *
486    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
487static const struct ctl_cmd_entry *
488    ctl_validate_command(struct ctl_scsiio *ctsio);
489static int ctl_cmd_applicable(uint8_t lun_type,
490    const struct ctl_cmd_entry *entry);
491
492/*
493 * Load the serialization table.  This isn't very pretty, but is probably
494 * the easiest way to do it.
495 */
496#include "ctl_ser_table.c"
497
498/*
499 * We only need to define open, close and ioctl routines for this driver.
500 */
501static struct cdevsw ctl_cdevsw = {
502	.d_version =	D_VERSION,
503	.d_flags =	0,
504	.d_open =	ctl_open,
505	.d_close =	ctl_close,
506	.d_ioctl =	ctl_ioctl,
507	.d_name =	"ctl",
508};
509
510
511MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
512MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
513
514static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
515
516static moduledata_t ctl_moduledata = {
517	"ctl",
518	ctl_module_event_handler,
519	NULL
520};
521
522DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
523MODULE_VERSION(ctl, 1);
524
525static struct ctl_frontend ioctl_frontend =
526{
527	.name = "ioctl",
528};
529
530static void
531ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
532			    union ctl_ha_msg *msg_info)
533{
534	struct ctl_scsiio *ctsio;
535
536	if (msg_info->hdr.original_sc == NULL) {
537		printf("%s: original_sc == NULL!\n", __func__);
538		/* XXX KDM now what? */
539		return;
540	}
541
542	ctsio = &msg_info->hdr.original_sc->scsiio;
543	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
544	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
545	ctsio->io_hdr.status = msg_info->hdr.status;
546	ctsio->scsi_status = msg_info->scsi.scsi_status;
547	ctsio->sense_len = msg_info->scsi.sense_len;
548	ctsio->sense_residual = msg_info->scsi.sense_residual;
549	ctsio->residual = msg_info->scsi.residual;
550	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
551	       sizeof(ctsio->sense_data));
552	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
553	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
554	ctl_enqueue_isc((union ctl_io *)ctsio);
555}
556
557static void
558ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
559				union ctl_ha_msg *msg_info)
560{
561	struct ctl_scsiio *ctsio;
562
563	if (msg_info->hdr.serializing_sc == NULL) {
564		printf("%s: serializing_sc == NULL!\n", __func__);
565		/* XXX KDM now what? */
566		return;
567	}
568
569	ctsio = &msg_info->hdr.serializing_sc->scsiio;
570#if 0
571	/*
572	 * Attempt to catch the situation where an I/O has
573	 * been freed, and we're using it again.
574	 */
575	if (ctsio->io_hdr.io_type == 0xff) {
576		union ctl_io *tmp_io;
577		tmp_io = (union ctl_io *)ctsio;
578		printf("%s: %p use after free!\n", __func__,
579		       ctsio);
580		printf("%s: type %d msg %d cdb %x iptl: "
581		       "%d:%d:%d:%d tag 0x%04x "
582		       "flag %#x status %x\n",
583			__func__,
584			tmp_io->io_hdr.io_type,
585			tmp_io->io_hdr.msg_type,
586			tmp_io->scsiio.cdb[0],
587			tmp_io->io_hdr.nexus.initid.id,
588			tmp_io->io_hdr.nexus.targ_port,
589			tmp_io->io_hdr.nexus.targ_target.id,
590			tmp_io->io_hdr.nexus.targ_lun,
591			(tmp_io->io_hdr.io_type ==
592			CTL_IO_TASK) ?
593			tmp_io->taskio.tag_num :
594			tmp_io->scsiio.tag_num,
595		        tmp_io->io_hdr.flags,
596			tmp_io->io_hdr.status);
597	}
598#endif
599	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
600	ctl_enqueue_isc((union ctl_io *)ctsio);
601}
602
603/*
604 * ISC (Inter Shelf Communication) event handler.  Events from the HA
605 * subsystem come in here.
606 */
607static void
608ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
609{
610	struct ctl_softc *ctl_softc;
611	union ctl_io *io;
612	struct ctl_prio *presio;
613	ctl_ha_status isc_status;
614
615	ctl_softc = control_softc;
616	io = NULL;
617
618
619#if 0
620	printf("CTL: Isc Msg event %d\n", event);
621#endif
622	if (event == CTL_HA_EVT_MSG_RECV) {
623		union ctl_ha_msg msg_info;
624
625		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
626					     sizeof(msg_info), /*wait*/ 0);
627#if 0
628		printf("CTL: msg_type %d\n", msg_info.msg_type);
629#endif
630		if (isc_status != 0) {
631			printf("Error receiving message, status = %d\n",
632			       isc_status);
633			return;
634		}
635
636		switch (msg_info.hdr.msg_type) {
637		case CTL_MSG_SERIALIZE:
638#if 0
639			printf("Serialize\n");
640#endif
641			io = ctl_alloc_io_nowait(ctl_softc->othersc_pool);
642			if (io == NULL) {
643				printf("ctl_isc_event_handler: can't allocate "
644				       "ctl_io!\n");
645				/* Bad Juju */
646				/* Need to set busy and send msg back */
647				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
648				msg_info.hdr.status = CTL_SCSI_ERROR;
649				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
650				msg_info.scsi.sense_len = 0;
651			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
652				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
653				}
654				goto bailout;
655			}
656			ctl_zero_io(io);
657			// populate ctsio from msg_info
658			io->io_hdr.io_type = CTL_IO_SCSI;
659			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
660			io->io_hdr.original_sc = msg_info.hdr.original_sc;
661#if 0
662			printf("pOrig %x\n", (int)msg_info.original_sc);
663#endif
664			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
665					    CTL_FLAG_IO_ACTIVE;
666			/*
667			 * If we're in serialization-only mode, we don't
668			 * want to go through full done processing.  Thus
669			 * the COPY flag.
670			 *
671			 * XXX KDM add another flag that is more specific.
672			 */
673			if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
674				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
675			io->io_hdr.nexus = msg_info.hdr.nexus;
676#if 0
677			printf("targ %d, port %d, iid %d, lun %d\n",
678			       io->io_hdr.nexus.targ_target.id,
679			       io->io_hdr.nexus.targ_port,
680			       io->io_hdr.nexus.initid.id,
681			       io->io_hdr.nexus.targ_lun);
682#endif
683			io->scsiio.tag_num = msg_info.scsi.tag_num;
684			io->scsiio.tag_type = msg_info.scsi.tag_type;
685			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
686			       CTL_MAX_CDBLEN);
687			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
688				const struct ctl_cmd_entry *entry;
689
690				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
691				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
692				io->io_hdr.flags |=
693					entry->flags & CTL_FLAG_DATA_MASK;
694			}
695			ctl_enqueue_isc(io);
696			break;
697
698		/* Performed on the Originating SC, XFER mode only */
699		case CTL_MSG_DATAMOVE: {
700			struct ctl_sg_entry *sgl;
701			int i, j;
702
703			io = msg_info.hdr.original_sc;
704			if (io == NULL) {
705				printf("%s: original_sc == NULL!\n", __func__);
706				/* XXX KDM do something here */
707				break;
708			}
709			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
710			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
711			/*
712			 * Keep track of this, we need to send it back over
713			 * when the datamove is complete.
714			 */
715			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
716
717			if (msg_info.dt.sg_sequence == 0) {
718				/*
719				 * XXX KDM we use the preallocated S/G list
720				 * here, but we'll need to change this to
721				 * dynamic allocation if we need larger S/G
722				 * lists.
723				 */
724				if (msg_info.dt.kern_sg_entries >
725				    sizeof(io->io_hdr.remote_sglist) /
726				    sizeof(io->io_hdr.remote_sglist[0])) {
727					printf("%s: number of S/G entries "
728					    "needed %u > allocated num %zd\n",
729					    __func__,
730					    msg_info.dt.kern_sg_entries,
731					    sizeof(io->io_hdr.remote_sglist)/
732					    sizeof(io->io_hdr.remote_sglist[0]));
733
734					/*
735					 * XXX KDM send a message back to
736					 * the other side to shut down the
737					 * DMA.  The error will come back
738					 * through via the normal channel.
739					 */
740					break;
741				}
742				sgl = io->io_hdr.remote_sglist;
743				memset(sgl, 0,
744				       sizeof(io->io_hdr.remote_sglist));
745
746				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
747
748				io->scsiio.kern_sg_entries =
749					msg_info.dt.kern_sg_entries;
750				io->scsiio.rem_sg_entries =
751					msg_info.dt.kern_sg_entries;
752				io->scsiio.kern_data_len =
753					msg_info.dt.kern_data_len;
754				io->scsiio.kern_total_len =
755					msg_info.dt.kern_total_len;
756				io->scsiio.kern_data_resid =
757					msg_info.dt.kern_data_resid;
758				io->scsiio.kern_rel_offset =
759					msg_info.dt.kern_rel_offset;
760				/*
761				 * Clear out per-DMA flags.
762				 */
763				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
764				/*
765				 * Add per-DMA flags that are set for this
766				 * particular DMA request.
767				 */
768				io->io_hdr.flags |= msg_info.dt.flags &
769						    CTL_FLAG_RDMA_MASK;
770			} else
771				sgl = (struct ctl_sg_entry *)
772					io->scsiio.kern_data_ptr;
773
774			for (i = msg_info.dt.sent_sg_entries, j = 0;
775			     i < (msg_info.dt.sent_sg_entries +
776			     msg_info.dt.cur_sg_entries); i++, j++) {
777				sgl[i].addr = msg_info.dt.sg_list[j].addr;
778				sgl[i].len = msg_info.dt.sg_list[j].len;
779
780#if 0
781				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
782				       __func__,
783				       msg_info.dt.sg_list[j].addr,
784				       msg_info.dt.sg_list[j].len,
785				       sgl[i].addr, sgl[i].len, j, i);
786#endif
787			}
788#if 0
789			memcpy(&sgl[msg_info.dt.sent_sg_entries],
790			       msg_info.dt.sg_list,
791			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
792#endif
793
794			/*
795			 * If this is the last piece of the I/O, we've got
796			 * the full S/G list.  Queue processing in the thread.
797			 * Otherwise wait for the next piece.
798			 */
799			if (msg_info.dt.sg_last != 0)
800				ctl_enqueue_isc(io);
801			break;
802		}
803		/* Performed on the Serializing (primary) SC, XFER mode only */
804		case CTL_MSG_DATAMOVE_DONE: {
805			if (msg_info.hdr.serializing_sc == NULL) {
806				printf("%s: serializing_sc == NULL!\n",
807				       __func__);
808				/* XXX KDM now what? */
809				break;
810			}
811			/*
812			 * We grab the sense information here in case
813			 * there was a failure, so we can return status
814			 * back to the initiator.
815			 */
816			io = msg_info.hdr.serializing_sc;
817			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
818			io->io_hdr.status = msg_info.hdr.status;
819			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
820			io->scsiio.sense_len = msg_info.scsi.sense_len;
821			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
822			io->io_hdr.port_status = msg_info.scsi.fetd_status;
823			io->scsiio.residual = msg_info.scsi.residual;
824			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
825			       sizeof(io->scsiio.sense_data));
826			ctl_enqueue_isc(io);
827			break;
828		}
829
830		/* Preformed on Originating SC, SER_ONLY mode */
831		case CTL_MSG_R2R:
832			io = msg_info.hdr.original_sc;
833			if (io == NULL) {
834				printf("%s: Major Bummer\n", __func__);
835				return;
836			} else {
837#if 0
838				printf("pOrig %x\n",(int) ctsio);
839#endif
840			}
841			io->io_hdr.msg_type = CTL_MSG_R2R;
842			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
843			ctl_enqueue_isc(io);
844			break;
845
846		/*
847		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
848		 * mode.
849		 * Performed on the Originating (i.e. secondary) SC in XFER
850		 * mode
851		 */
852		case CTL_MSG_FINISH_IO:
853			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
854				ctl_isc_handler_finish_xfer(ctl_softc,
855							    &msg_info);
856			else
857				ctl_isc_handler_finish_ser_only(ctl_softc,
858								&msg_info);
859			break;
860
861		/* Preformed on Originating SC */
862		case CTL_MSG_BAD_JUJU:
863			io = msg_info.hdr.original_sc;
864			if (io == NULL) {
865				printf("%s: Bad JUJU!, original_sc is NULL!\n",
866				       __func__);
867				break;
868			}
869			ctl_copy_sense_data(&msg_info, io);
870			/*
871			 * IO should have already been cleaned up on other
872			 * SC so clear this flag so we won't send a message
873			 * back to finish the IO there.
874			 */
875			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
876			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
877
878			/* io = msg_info.hdr.serializing_sc; */
879			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
880			ctl_enqueue_isc(io);
881			break;
882
883		/* Handle resets sent from the other side */
884		case CTL_MSG_MANAGE_TASKS: {
885			struct ctl_taskio *taskio;
886			taskio = (struct ctl_taskio *)ctl_alloc_io_nowait(
887			    ctl_softc->othersc_pool);
888			if (taskio == NULL) {
889				printf("ctl_isc_event_handler: can't allocate "
890				       "ctl_io!\n");
891				/* Bad Juju */
892				/* should I just call the proper reset func
893				   here??? */
894				goto bailout;
895			}
896			ctl_zero_io((union ctl_io *)taskio);
897			taskio->io_hdr.io_type = CTL_IO_TASK;
898			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
899			taskio->io_hdr.nexus = msg_info.hdr.nexus;
900			taskio->task_action = msg_info.task.task_action;
901			taskio->tag_num = msg_info.task.tag_num;
902			taskio->tag_type = msg_info.task.tag_type;
903#ifdef CTL_TIME_IO
904			taskio->io_hdr.start_time = time_uptime;
905			getbintime(&taskio->io_hdr.start_bt);
906#if 0
907			cs_prof_gettime(&taskio->io_hdr.start_ticks);
908#endif
909#endif /* CTL_TIME_IO */
910			ctl_run_task((union ctl_io *)taskio);
911			break;
912		}
913		/* Persistent Reserve action which needs attention */
914		case CTL_MSG_PERS_ACTION:
915			presio = (struct ctl_prio *)ctl_alloc_io_nowait(
916			    ctl_softc->othersc_pool);
917			if (presio == NULL) {
918				printf("ctl_isc_event_handler: can't allocate "
919				       "ctl_io!\n");
920				/* Bad Juju */
921				/* Need to set busy and send msg back */
922				goto bailout;
923			}
924			ctl_zero_io((union ctl_io *)presio);
925			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
926			presio->pr_msg = msg_info.pr;
927			ctl_enqueue_isc((union ctl_io *)presio);
928			break;
929		case CTL_MSG_SYNC_FE:
930			rcv_sync_msg = 1;
931			break;
932		default:
933		        printf("How did I get here?\n");
934		}
935	} else if (event == CTL_HA_EVT_MSG_SENT) {
936		if (param != CTL_HA_STATUS_SUCCESS) {
937			printf("Bad status from ctl_ha_msg_send status %d\n",
938			       param);
939		}
940		return;
941	} else if (event == CTL_HA_EVT_DISCONNECT) {
942		printf("CTL: Got a disconnect from Isc\n");
943		return;
944	} else {
945		printf("ctl_isc_event_handler: Unknown event %d\n", event);
946		return;
947	}
948
949bailout:
950	return;
951}
952
953static void
954ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
955{
956	struct scsi_sense_data *sense;
957
958	sense = &dest->scsiio.sense_data;
959	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
960	dest->scsiio.scsi_status = src->scsi.scsi_status;
961	dest->scsiio.sense_len = src->scsi.sense_len;
962	dest->io_hdr.status = src->hdr.status;
963}
964
965static int
966ctl_ha_state_sysctl(SYSCTL_HANDLER_ARGS)
967{
968	struct ctl_softc *softc = (struct ctl_softc *)arg1;
969	struct ctl_lun *lun;
970	int error, value, i;
971
972	if (softc->flags & CTL_FLAG_ACTIVE_SHELF)
973		value = 0;
974	else
975		value = 1;
976
977	error = sysctl_handle_int(oidp, &value, 0, req);
978	if ((error != 0) || (req->newptr == NULL))
979		return (error);
980
981	mtx_lock(&softc->ctl_lock);
982	if (value == 0)
983		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
984	else
985		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
986	STAILQ_FOREACH(lun, &softc->lun_list, links) {
987		mtx_lock(&lun->lun_lock);
988		for (i = 0; i < CTL_MAX_INITIATORS; i++)
989			lun->pending_ua[i] |= CTL_UA_ASYM_ACC_CHANGE;
990		mtx_unlock(&lun->lun_lock);
991	}
992	mtx_unlock(&softc->ctl_lock);
993	return (0);
994}
995
996static int
997ctl_init(void)
998{
999	struct ctl_softc *softc;
1000	void *other_pool;
1001	struct ctl_port *port;
1002	int i, error, retval;
1003	//int isc_retval;
1004
1005	retval = 0;
1006	ctl_pause_rtr = 0;
1007        rcv_sync_msg = 0;
1008
1009	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1010			       M_WAITOK | M_ZERO);
1011	softc = control_softc;
1012
1013	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1014			      "cam/ctl");
1015
1016	softc->dev->si_drv1 = softc;
1017
1018	/*
1019	 * By default, return a "bad LUN" peripheral qualifier for unknown
1020	 * LUNs.  The user can override this default using the tunable or
1021	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
1022	 */
1023	softc->inquiry_pq_no_lun = 1;
1024	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
1025			  &softc->inquiry_pq_no_lun);
1026	sysctl_ctx_init(&softc->sysctl_ctx);
1027	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1028		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1029		CTLFLAG_RD, 0, "CAM Target Layer");
1030
1031	if (softc->sysctl_tree == NULL) {
1032		printf("%s: unable to allocate sysctl tree\n", __func__);
1033		destroy_dev(softc->dev);
1034		free(control_softc, M_DEVBUF);
1035		control_softc = NULL;
1036		return (ENOMEM);
1037	}
1038
1039	SYSCTL_ADD_INT(&softc->sysctl_ctx,
1040		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1041		       "inquiry_pq_no_lun", CTLFLAG_RW,
1042		       &softc->inquiry_pq_no_lun, 0,
1043		       "Report no lun possible for invalid LUNs");
1044
1045	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1046	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1047	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1048	softc->open_count = 0;
1049
1050	/*
1051	 * Default to actually sending a SYNCHRONIZE CACHE command down to
1052	 * the drive.
1053	 */
1054	softc->flags = CTL_FLAG_REAL_SYNC;
1055
1056	/*
1057	 * In Copan's HA scheme, the "master" and "slave" roles are
1058	 * figured out through the slot the controller is in.  Although it
1059	 * is an active/active system, someone has to be in charge.
1060	 */
1061	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1062	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1063	    "HA head ID (0 - no HA)");
1064	if (softc->ha_id == 0) {
1065		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1066		softc->is_single = 1;
1067		softc->port_offset = 0;
1068	} else
1069		softc->port_offset = (softc->ha_id - 1) * CTL_MAX_PORTS;
1070	softc->persis_offset = softc->port_offset * CTL_MAX_INIT_PER_PORT;
1071
1072	/*
1073	 * XXX KDM need to figure out where we want to get our target ID
1074	 * and WWID.  Is it different on each port?
1075	 */
1076	softc->target.id = 0;
1077	softc->target.wwid[0] = 0x12345678;
1078	softc->target.wwid[1] = 0x87654321;
1079	STAILQ_INIT(&softc->lun_list);
1080	STAILQ_INIT(&softc->pending_lun_queue);
1081	STAILQ_INIT(&softc->fe_list);
1082	STAILQ_INIT(&softc->port_list);
1083	STAILQ_INIT(&softc->be_list);
1084	ctl_tpc_init(softc);
1085
1086	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1087	                    &other_pool) != 0)
1088	{
1089		printf("ctl: can't allocate %d entry other SC pool, "
1090		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1091		return (ENOMEM);
1092	}
1093	softc->othersc_pool = other_pool;
1094
1095	if (worker_threads <= 0)
1096		worker_threads = max(1, mp_ncpus / 4);
1097	if (worker_threads > CTL_MAX_THREADS)
1098		worker_threads = CTL_MAX_THREADS;
1099
1100	for (i = 0; i < worker_threads; i++) {
1101		struct ctl_thread *thr = &softc->threads[i];
1102
1103		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1104		thr->ctl_softc = softc;
1105		STAILQ_INIT(&thr->incoming_queue);
1106		STAILQ_INIT(&thr->rtr_queue);
1107		STAILQ_INIT(&thr->done_queue);
1108		STAILQ_INIT(&thr->isc_queue);
1109
1110		error = kproc_kthread_add(ctl_work_thread, thr,
1111		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1112		if (error != 0) {
1113			printf("error creating CTL work thread!\n");
1114			ctl_pool_free(other_pool);
1115			return (error);
1116		}
1117	}
1118	error = kproc_kthread_add(ctl_lun_thread, softc,
1119	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1120	if (error != 0) {
1121		printf("error creating CTL lun thread!\n");
1122		ctl_pool_free(other_pool);
1123		return (error);
1124	}
1125	error = kproc_kthread_add(ctl_thresh_thread, softc,
1126	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1127	if (error != 0) {
1128		printf("error creating CTL threshold thread!\n");
1129		ctl_pool_free(other_pool);
1130		return (error);
1131	}
1132	if (bootverbose)
1133		printf("ctl: CAM Target Layer loaded\n");
1134
1135	/*
1136	 * Initialize the ioctl front end.
1137	 */
1138	ctl_frontend_register(&ioctl_frontend);
1139	port = &softc->ioctl_info.port;
1140	port->frontend = &ioctl_frontend;
1141	sprintf(softc->ioctl_info.port_name, "ioctl");
1142	port->port_type = CTL_PORT_IOCTL;
1143	port->num_requested_ctl_io = 100;
1144	port->port_name = softc->ioctl_info.port_name;
1145	port->port_online = ctl_ioctl_online;
1146	port->port_offline = ctl_ioctl_offline;
1147	port->onoff_arg = &softc->ioctl_info;
1148	port->lun_enable = ctl_ioctl_lun_enable;
1149	port->lun_disable = ctl_ioctl_lun_disable;
1150	port->targ_lun_arg = &softc->ioctl_info;
1151	port->fe_datamove = ctl_ioctl_datamove;
1152	port->fe_done = ctl_ioctl_done;
1153	port->max_targets = 15;
1154	port->max_target_id = 15;
1155
1156	if (ctl_port_register(&softc->ioctl_info.port) != 0) {
1157		printf("ctl: ioctl front end registration failed, will "
1158		       "continue anyway\n");
1159	}
1160
1161	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1162	    OID_AUTO, "ha_state", CTLTYPE_INT | CTLFLAG_RWTUN,
1163	    softc, 0, ctl_ha_state_sysctl, "I", "HA state for this head");
1164
1165#ifdef CTL_IO_DELAY
1166	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1167		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1168		       sizeof(struct callout), CTL_TIMER_BYTES);
1169		return (EINVAL);
1170	}
1171#endif /* CTL_IO_DELAY */
1172
1173	return (0);
1174}
1175
1176void
1177ctl_shutdown(void)
1178{
1179	struct ctl_softc *softc;
1180	struct ctl_lun *lun, *next_lun;
1181
1182	softc = (struct ctl_softc *)control_softc;
1183
1184	if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1185		printf("ctl: ioctl front end deregistration failed\n");
1186
1187	mtx_lock(&softc->ctl_lock);
1188
1189	/*
1190	 * Free up each LUN.
1191	 */
1192	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1193		next_lun = STAILQ_NEXT(lun, links);
1194		ctl_free_lun(lun);
1195	}
1196
1197	mtx_unlock(&softc->ctl_lock);
1198
1199	ctl_frontend_deregister(&ioctl_frontend);
1200
1201#if 0
1202	ctl_shutdown_thread(softc->work_thread);
1203	mtx_destroy(&softc->queue_lock);
1204#endif
1205
1206	ctl_tpc_shutdown(softc);
1207	uma_zdestroy(softc->io_zone);
1208	mtx_destroy(&softc->ctl_lock);
1209
1210	destroy_dev(softc->dev);
1211
1212	sysctl_ctx_free(&softc->sysctl_ctx);
1213
1214	free(control_softc, M_DEVBUF);
1215	control_softc = NULL;
1216
1217	if (bootverbose)
1218		printf("ctl: CAM Target Layer unloaded\n");
1219}
1220
1221static int
1222ctl_module_event_handler(module_t mod, int what, void *arg)
1223{
1224
1225	switch (what) {
1226	case MOD_LOAD:
1227		return (ctl_init());
1228	case MOD_UNLOAD:
1229		return (EBUSY);
1230	default:
1231		return (EOPNOTSUPP);
1232	}
1233}
1234
1235/*
1236 * XXX KDM should we do some access checks here?  Bump a reference count to
1237 * prevent a CTL module from being unloaded while someone has it open?
1238 */
1239static int
1240ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1241{
1242	return (0);
1243}
1244
1245static int
1246ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1247{
1248	return (0);
1249}
1250
1251int
1252ctl_port_enable(ctl_port_type port_type)
1253{
1254	struct ctl_softc *softc = control_softc;
1255	struct ctl_port *port;
1256
1257	if (softc->is_single == 0) {
1258		union ctl_ha_msg msg_info;
1259		int isc_retval;
1260
1261#if 0
1262		printf("%s: HA mode, synchronizing frontend enable\n",
1263		        __func__);
1264#endif
1265		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1266	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1267		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1268			printf("Sync msg send error retval %d\n", isc_retval);
1269		}
1270		if (!rcv_sync_msg) {
1271			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1272			        sizeof(msg_info), 1);
1273		}
1274#if 0
1275        	printf("CTL:Frontend Enable\n");
1276	} else {
1277		printf("%s: single mode, skipping frontend synchronization\n",
1278		        __func__);
1279#endif
1280	}
1281
1282	STAILQ_FOREACH(port, &softc->port_list, links) {
1283		if (port_type & port->port_type)
1284		{
1285#if 0
1286			printf("port %d\n", port->targ_port);
1287#endif
1288			ctl_port_online(port);
1289		}
1290	}
1291
1292	return (0);
1293}
1294
1295int
1296ctl_port_disable(ctl_port_type port_type)
1297{
1298	struct ctl_softc *softc;
1299	struct ctl_port *port;
1300
1301	softc = control_softc;
1302
1303	STAILQ_FOREACH(port, &softc->port_list, links) {
1304		if (port_type & port->port_type)
1305			ctl_port_offline(port);
1306	}
1307
1308	return (0);
1309}
1310
1311/*
1312 * Returns 0 for success, 1 for failure.
1313 * Currently the only failure mode is if there aren't enough entries
1314 * allocated.  So, in case of a failure, look at num_entries_dropped,
1315 * reallocate and try again.
1316 */
1317int
1318ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1319	      int *num_entries_filled, int *num_entries_dropped,
1320	      ctl_port_type port_type, int no_virtual)
1321{
1322	struct ctl_softc *softc;
1323	struct ctl_port *port;
1324	int entries_dropped, entries_filled;
1325	int retval;
1326	int i;
1327
1328	softc = control_softc;
1329
1330	retval = 0;
1331	entries_filled = 0;
1332	entries_dropped = 0;
1333
1334	i = 0;
1335	mtx_lock(&softc->ctl_lock);
1336	STAILQ_FOREACH(port, &softc->port_list, links) {
1337		struct ctl_port_entry *entry;
1338
1339		if ((port->port_type & port_type) == 0)
1340			continue;
1341
1342		if ((no_virtual != 0)
1343		 && (port->virtual_port != 0))
1344			continue;
1345
1346		if (entries_filled >= num_entries_alloced) {
1347			entries_dropped++;
1348			continue;
1349		}
1350		entry = &entries[i];
1351
1352		entry->port_type = port->port_type;
1353		strlcpy(entry->port_name, port->port_name,
1354			sizeof(entry->port_name));
1355		entry->physical_port = port->physical_port;
1356		entry->virtual_port = port->virtual_port;
1357		entry->wwnn = port->wwnn;
1358		entry->wwpn = port->wwpn;
1359
1360		i++;
1361		entries_filled++;
1362	}
1363
1364	mtx_unlock(&softc->ctl_lock);
1365
1366	if (entries_dropped > 0)
1367		retval = 1;
1368
1369	*num_entries_dropped = entries_dropped;
1370	*num_entries_filled = entries_filled;
1371
1372	return (retval);
1373}
1374
1375static void
1376ctl_ioctl_online(void *arg)
1377{
1378	struct ctl_ioctl_info *ioctl_info;
1379
1380	ioctl_info = (struct ctl_ioctl_info *)arg;
1381
1382	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1383}
1384
1385static void
1386ctl_ioctl_offline(void *arg)
1387{
1388	struct ctl_ioctl_info *ioctl_info;
1389
1390	ioctl_info = (struct ctl_ioctl_info *)arg;
1391
1392	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1393}
1394
1395/*
1396 * Remove an initiator by port number and initiator ID.
1397 * Returns 0 for success, -1 for failure.
1398 */
1399int
1400ctl_remove_initiator(struct ctl_port *port, int iid)
1401{
1402	struct ctl_softc *softc = control_softc;
1403
1404	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1405
1406	if (iid > CTL_MAX_INIT_PER_PORT) {
1407		printf("%s: initiator ID %u > maximun %u!\n",
1408		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1409		return (-1);
1410	}
1411
1412	mtx_lock(&softc->ctl_lock);
1413	port->wwpn_iid[iid].in_use--;
1414	port->wwpn_iid[iid].last_use = time_uptime;
1415	mtx_unlock(&softc->ctl_lock);
1416
1417	return (0);
1418}
1419
1420/*
1421 * Add an initiator to the initiator map.
1422 * Returns iid for success, < 0 for failure.
1423 */
1424int
1425ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1426{
1427	struct ctl_softc *softc = control_softc;
1428	time_t best_time;
1429	int i, best;
1430
1431	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1432
1433	if (iid >= CTL_MAX_INIT_PER_PORT) {
1434		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1435		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1436		free(name, M_CTL);
1437		return (-1);
1438	}
1439
1440	mtx_lock(&softc->ctl_lock);
1441
1442	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1443		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1444			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1445				iid = i;
1446				break;
1447			}
1448			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1449			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1450				iid = i;
1451				break;
1452			}
1453		}
1454	}
1455
1456	if (iid < 0) {
1457		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1458			if (port->wwpn_iid[i].in_use == 0 &&
1459			    port->wwpn_iid[i].wwpn == 0 &&
1460			    port->wwpn_iid[i].name == NULL) {
1461				iid = i;
1462				break;
1463			}
1464		}
1465	}
1466
1467	if (iid < 0) {
1468		best = -1;
1469		best_time = INT32_MAX;
1470		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1471			if (port->wwpn_iid[i].in_use == 0) {
1472				if (port->wwpn_iid[i].last_use < best_time) {
1473					best = i;
1474					best_time = port->wwpn_iid[i].last_use;
1475				}
1476			}
1477		}
1478		iid = best;
1479	}
1480
1481	if (iid < 0) {
1482		mtx_unlock(&softc->ctl_lock);
1483		free(name, M_CTL);
1484		return (-2);
1485	}
1486
1487	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1488		/*
1489		 * This is not an error yet.
1490		 */
1491		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1492#if 0
1493			printf("%s: port %d iid %u WWPN %#jx arrived"
1494			    " again\n", __func__, port->targ_port,
1495			    iid, (uintmax_t)wwpn);
1496#endif
1497			goto take;
1498		}
1499		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1500		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1501#if 0
1502			printf("%s: port %d iid %u name '%s' arrived"
1503			    " again\n", __func__, port->targ_port,
1504			    iid, name);
1505#endif
1506			goto take;
1507		}
1508
1509		/*
1510		 * This is an error, but what do we do about it?  The
1511		 * driver is telling us we have a new WWPN for this
1512		 * initiator ID, so we pretty much need to use it.
1513		 */
1514		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1515		    " but WWPN %#jx '%s' is still at that address\n",
1516		    __func__, port->targ_port, iid, wwpn, name,
1517		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1518		    port->wwpn_iid[iid].name);
1519
1520		/*
1521		 * XXX KDM clear have_ca and ua_pending on each LUN for
1522		 * this initiator.
1523		 */
1524	}
1525take:
1526	free(port->wwpn_iid[iid].name, M_CTL);
1527	port->wwpn_iid[iid].name = name;
1528	port->wwpn_iid[iid].wwpn = wwpn;
1529	port->wwpn_iid[iid].in_use++;
1530	mtx_unlock(&softc->ctl_lock);
1531
1532	return (iid);
1533}
1534
1535static int
1536ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1537{
1538	int len;
1539
1540	switch (port->port_type) {
1541	case CTL_PORT_FC:
1542	{
1543		struct scsi_transportid_fcp *id =
1544		    (struct scsi_transportid_fcp *)buf;
1545		if (port->wwpn_iid[iid].wwpn == 0)
1546			return (0);
1547		memset(id, 0, sizeof(*id));
1548		id->format_protocol = SCSI_PROTO_FC;
1549		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1550		return (sizeof(*id));
1551	}
1552	case CTL_PORT_ISCSI:
1553	{
1554		struct scsi_transportid_iscsi_port *id =
1555		    (struct scsi_transportid_iscsi_port *)buf;
1556		if (port->wwpn_iid[iid].name == NULL)
1557			return (0);
1558		memset(id, 0, 256);
1559		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1560		    SCSI_PROTO_ISCSI;
1561		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1562		len = roundup2(min(len, 252), 4);
1563		scsi_ulto2b(len, id->additional_length);
1564		return (sizeof(*id) + len);
1565	}
1566	case CTL_PORT_SAS:
1567	{
1568		struct scsi_transportid_sas *id =
1569		    (struct scsi_transportid_sas *)buf;
1570		if (port->wwpn_iid[iid].wwpn == 0)
1571			return (0);
1572		memset(id, 0, sizeof(*id));
1573		id->format_protocol = SCSI_PROTO_SAS;
1574		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1575		return (sizeof(*id));
1576	}
1577	default:
1578	{
1579		struct scsi_transportid_spi *id =
1580		    (struct scsi_transportid_spi *)buf;
1581		memset(id, 0, sizeof(*id));
1582		id->format_protocol = SCSI_PROTO_SPI;
1583		scsi_ulto2b(iid, id->scsi_addr);
1584		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1585		return (sizeof(*id));
1586	}
1587	}
1588}
1589
1590static int
1591ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1592{
1593	return (0);
1594}
1595
1596static int
1597ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1598{
1599	return (0);
1600}
1601
1602/*
1603 * Data movement routine for the CTL ioctl frontend port.
1604 */
1605static int
1606ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1607{
1608	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1609	struct ctl_sg_entry ext_entry, kern_entry;
1610	int ext_sglen, ext_sg_entries, kern_sg_entries;
1611	int ext_sg_start, ext_offset;
1612	int len_to_copy, len_copied;
1613	int kern_watermark, ext_watermark;
1614	int ext_sglist_malloced;
1615	int i, j;
1616
1617	ext_sglist_malloced = 0;
1618	ext_sg_start = 0;
1619	ext_offset = 0;
1620
1621	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1622
1623	/*
1624	 * If this flag is set, fake the data transfer.
1625	 */
1626	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1627		ctsio->ext_data_filled = ctsio->ext_data_len;
1628		goto bailout;
1629	}
1630
1631	/*
1632	 * To simplify things here, if we have a single buffer, stick it in
1633	 * a S/G entry and just make it a single entry S/G list.
1634	 */
1635	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1636		int len_seen;
1637
1638		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1639
1640		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1641							   M_WAITOK);
1642		ext_sglist_malloced = 1;
1643		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1644				   ext_sglen) != 0) {
1645			ctl_set_internal_failure(ctsio,
1646						 /*sks_valid*/ 0,
1647						 /*retry_count*/ 0);
1648			goto bailout;
1649		}
1650		ext_sg_entries = ctsio->ext_sg_entries;
1651		len_seen = 0;
1652		for (i = 0; i < ext_sg_entries; i++) {
1653			if ((len_seen + ext_sglist[i].len) >=
1654			     ctsio->ext_data_filled) {
1655				ext_sg_start = i;
1656				ext_offset = ctsio->ext_data_filled - len_seen;
1657				break;
1658			}
1659			len_seen += ext_sglist[i].len;
1660		}
1661	} else {
1662		ext_sglist = &ext_entry;
1663		ext_sglist->addr = ctsio->ext_data_ptr;
1664		ext_sglist->len = ctsio->ext_data_len;
1665		ext_sg_entries = 1;
1666		ext_sg_start = 0;
1667		ext_offset = ctsio->ext_data_filled;
1668	}
1669
1670	if (ctsio->kern_sg_entries > 0) {
1671		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1672		kern_sg_entries = ctsio->kern_sg_entries;
1673	} else {
1674		kern_sglist = &kern_entry;
1675		kern_sglist->addr = ctsio->kern_data_ptr;
1676		kern_sglist->len = ctsio->kern_data_len;
1677		kern_sg_entries = 1;
1678	}
1679
1680
1681	kern_watermark = 0;
1682	ext_watermark = ext_offset;
1683	len_copied = 0;
1684	for (i = ext_sg_start, j = 0;
1685	     i < ext_sg_entries && j < kern_sg_entries;) {
1686		uint8_t *ext_ptr, *kern_ptr;
1687
1688		len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1689				      kern_sglist[j].len - kern_watermark);
1690
1691		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1692		ext_ptr = ext_ptr + ext_watermark;
1693		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1694			/*
1695			 * XXX KDM fix this!
1696			 */
1697			panic("need to implement bus address support");
1698#if 0
1699			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1700#endif
1701		} else
1702			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1703		kern_ptr = kern_ptr + kern_watermark;
1704
1705		kern_watermark += len_to_copy;
1706		ext_watermark += len_to_copy;
1707
1708		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1709		     CTL_FLAG_DATA_IN) {
1710			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1711					 "bytes to user\n", len_to_copy));
1712			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1713					 "to %p\n", kern_ptr, ext_ptr));
1714			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1715				ctl_set_internal_failure(ctsio,
1716							 /*sks_valid*/ 0,
1717							 /*retry_count*/ 0);
1718				goto bailout;
1719			}
1720		} else {
1721			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1722					 "bytes from user\n", len_to_copy));
1723			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1724					 "to %p\n", ext_ptr, kern_ptr));
1725			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1726				ctl_set_internal_failure(ctsio,
1727							 /*sks_valid*/ 0,
1728							 /*retry_count*/0);
1729				goto bailout;
1730			}
1731		}
1732
1733		len_copied += len_to_copy;
1734
1735		if (ext_sglist[i].len == ext_watermark) {
1736			i++;
1737			ext_watermark = 0;
1738		}
1739
1740		if (kern_sglist[j].len == kern_watermark) {
1741			j++;
1742			kern_watermark = 0;
1743		}
1744	}
1745
1746	ctsio->ext_data_filled += len_copied;
1747
1748	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1749			 "kern_sg_entries: %d\n", ext_sg_entries,
1750			 kern_sg_entries));
1751	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1752			 "kern_data_len = %d\n", ctsio->ext_data_len,
1753			 ctsio->kern_data_len));
1754
1755
1756	/* XXX KDM set residual?? */
1757bailout:
1758
1759	if (ext_sglist_malloced != 0)
1760		free(ext_sglist, M_CTL);
1761
1762	return (CTL_RETVAL_COMPLETE);
1763}
1764
1765/*
1766 * Serialize a command that went down the "wrong" side, and so was sent to
1767 * this controller for execution.  The logic is a little different than the
1768 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1769 * sent back to the other side, but in the success case, we execute the
1770 * command on this side (XFER mode) or tell the other side to execute it
1771 * (SER_ONLY mode).
1772 */
1773static int
1774ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1775{
1776	struct ctl_softc *ctl_softc;
1777	union ctl_ha_msg msg_info;
1778	struct ctl_lun *lun;
1779	int retval = 0;
1780	uint32_t targ_lun;
1781
1782	ctl_softc = control_softc;
1783
1784	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1785	lun = ctl_softc->ctl_luns[targ_lun];
1786	if (lun==NULL)
1787	{
1788		/*
1789		 * Why isn't LUN defined? The other side wouldn't
1790		 * send a cmd if the LUN is undefined.
1791		 */
1792		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1793
1794		/* "Logical unit not supported" */
1795		ctl_set_sense_data(&msg_info.scsi.sense_data,
1796				   lun,
1797				   /*sense_format*/SSD_TYPE_NONE,
1798				   /*current_error*/ 1,
1799				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1800				   /*asc*/ 0x25,
1801				   /*ascq*/ 0x00,
1802				   SSD_ELEM_NONE);
1803
1804		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1805		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1806		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1807		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1808		msg_info.hdr.serializing_sc = NULL;
1809		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1810	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1811				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1812		}
1813		return(1);
1814
1815	}
1816
1817	mtx_lock(&lun->lun_lock);
1818    	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1819
1820	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1821		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1822		 ooa_links))) {
1823	case CTL_ACTION_BLOCK:
1824		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1825		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1826				  blocked_links);
1827		break;
1828	case CTL_ACTION_PASS:
1829	case CTL_ACTION_SKIP:
1830		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1831			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1832			ctl_enqueue_rtr((union ctl_io *)ctsio);
1833		} else {
1834
1835			/* send msg back to other side */
1836			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1837			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1838			msg_info.hdr.msg_type = CTL_MSG_R2R;
1839#if 0
1840			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1841#endif
1842		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1843			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1844			}
1845		}
1846		break;
1847	case CTL_ACTION_OVERLAP:
1848		/* OVERLAPPED COMMANDS ATTEMPTED */
1849		ctl_set_sense_data(&msg_info.scsi.sense_data,
1850				   lun,
1851				   /*sense_format*/SSD_TYPE_NONE,
1852				   /*current_error*/ 1,
1853				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1854				   /*asc*/ 0x4E,
1855				   /*ascq*/ 0x00,
1856				   SSD_ELEM_NONE);
1857
1858		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1859		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1860		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1861		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1862		msg_info.hdr.serializing_sc = NULL;
1863		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1864#if 0
1865		printf("BAD JUJU:Major Bummer Overlap\n");
1866#endif
1867		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1868		retval = 1;
1869		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1870		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1871		}
1872		break;
1873	case CTL_ACTION_OVERLAP_TAG:
1874		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1875		ctl_set_sense_data(&msg_info.scsi.sense_data,
1876				   lun,
1877				   /*sense_format*/SSD_TYPE_NONE,
1878				   /*current_error*/ 1,
1879				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1880				   /*asc*/ 0x4D,
1881				   /*ascq*/ ctsio->tag_num & 0xff,
1882				   SSD_ELEM_NONE);
1883
1884		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1885		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1886		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1887		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1888		msg_info.hdr.serializing_sc = NULL;
1889		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1890#if 0
1891		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1892#endif
1893		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1894		retval = 1;
1895		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1896		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1897		}
1898		break;
1899	case CTL_ACTION_ERROR:
1900	default:
1901		/* "Internal target failure" */
1902		ctl_set_sense_data(&msg_info.scsi.sense_data,
1903				   lun,
1904				   /*sense_format*/SSD_TYPE_NONE,
1905				   /*current_error*/ 1,
1906				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1907				   /*asc*/ 0x44,
1908				   /*ascq*/ 0x00,
1909				   SSD_ELEM_NONE);
1910
1911		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1912		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1913		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1914		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1915		msg_info.hdr.serializing_sc = NULL;
1916		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1917#if 0
1918		printf("BAD JUJU:Major Bummer HW Error\n");
1919#endif
1920		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1921		retval = 1;
1922		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1923		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1924		}
1925		break;
1926	}
1927	mtx_unlock(&lun->lun_lock);
1928	return (retval);
1929}
1930
1931static int
1932ctl_ioctl_submit_wait(union ctl_io *io)
1933{
1934	struct ctl_fe_ioctl_params params;
1935	ctl_fe_ioctl_state last_state;
1936	int done, retval;
1937
1938	retval = 0;
1939
1940	bzero(&params, sizeof(params));
1941
1942	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1943	cv_init(&params.sem, "ctlioccv");
1944	params.state = CTL_IOCTL_INPROG;
1945	last_state = params.state;
1946
1947	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1948
1949	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1950
1951	/* This shouldn't happen */
1952	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1953		return (retval);
1954
1955	done = 0;
1956
1957	do {
1958		mtx_lock(&params.ioctl_mtx);
1959		/*
1960		 * Check the state here, and don't sleep if the state has
1961		 * already changed (i.e. wakeup has already occured, but we
1962		 * weren't waiting yet).
1963		 */
1964		if (params.state == last_state) {
1965			/* XXX KDM cv_wait_sig instead? */
1966			cv_wait(&params.sem, &params.ioctl_mtx);
1967		}
1968		last_state = params.state;
1969
1970		switch (params.state) {
1971		case CTL_IOCTL_INPROG:
1972			/* Why did we wake up? */
1973			/* XXX KDM error here? */
1974			mtx_unlock(&params.ioctl_mtx);
1975			break;
1976		case CTL_IOCTL_DATAMOVE:
1977			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1978
1979			/*
1980			 * change last_state back to INPROG to avoid
1981			 * deadlock on subsequent data moves.
1982			 */
1983			params.state = last_state = CTL_IOCTL_INPROG;
1984
1985			mtx_unlock(&params.ioctl_mtx);
1986			ctl_ioctl_do_datamove(&io->scsiio);
1987			/*
1988			 * Note that in some cases, most notably writes,
1989			 * this will queue the I/O and call us back later.
1990			 * In other cases, generally reads, this routine
1991			 * will immediately call back and wake us up,
1992			 * probably using our own context.
1993			 */
1994			io->scsiio.be_move_done(io);
1995			break;
1996		case CTL_IOCTL_DONE:
1997			mtx_unlock(&params.ioctl_mtx);
1998			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
1999			done = 1;
2000			break;
2001		default:
2002			mtx_unlock(&params.ioctl_mtx);
2003			/* XXX KDM error here? */
2004			break;
2005		}
2006	} while (done == 0);
2007
2008	mtx_destroy(&params.ioctl_mtx);
2009	cv_destroy(&params.sem);
2010
2011	return (CTL_RETVAL_COMPLETE);
2012}
2013
2014static void
2015ctl_ioctl_datamove(union ctl_io *io)
2016{
2017	struct ctl_fe_ioctl_params *params;
2018
2019	params = (struct ctl_fe_ioctl_params *)
2020		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2021
2022	mtx_lock(&params->ioctl_mtx);
2023	params->state = CTL_IOCTL_DATAMOVE;
2024	cv_broadcast(&params->sem);
2025	mtx_unlock(&params->ioctl_mtx);
2026}
2027
2028static void
2029ctl_ioctl_done(union ctl_io *io)
2030{
2031	struct ctl_fe_ioctl_params *params;
2032
2033	params = (struct ctl_fe_ioctl_params *)
2034		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2035
2036	mtx_lock(&params->ioctl_mtx);
2037	params->state = CTL_IOCTL_DONE;
2038	cv_broadcast(&params->sem);
2039	mtx_unlock(&params->ioctl_mtx);
2040}
2041
2042static void
2043ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2044{
2045	struct ctl_fe_ioctl_startstop_info *sd_info;
2046
2047	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2048
2049	sd_info->hs_info.status = metatask->status;
2050	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2051	sd_info->hs_info.luns_complete =
2052		metatask->taskinfo.startstop.luns_complete;
2053	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2054
2055	cv_broadcast(&sd_info->sem);
2056}
2057
2058static void
2059ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2060{
2061	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2062
2063	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2064
2065	mtx_lock(fe_bbr_info->lock);
2066	fe_bbr_info->bbr_info->status = metatask->status;
2067	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2068	fe_bbr_info->wakeup_done = 1;
2069	mtx_unlock(fe_bbr_info->lock);
2070
2071	cv_broadcast(&fe_bbr_info->sem);
2072}
2073
2074/*
2075 * Returns 0 for success, errno for failure.
2076 */
2077static int
2078ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2079		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2080{
2081	union ctl_io *io;
2082	int retval;
2083
2084	retval = 0;
2085
2086	mtx_lock(&lun->lun_lock);
2087	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2088	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2089	     ooa_links)) {
2090		struct ctl_ooa_entry *entry;
2091
2092		/*
2093		 * If we've got more than we can fit, just count the
2094		 * remaining entries.
2095		 */
2096		if (*cur_fill_num >= ooa_hdr->alloc_num)
2097			continue;
2098
2099		entry = &kern_entries[*cur_fill_num];
2100
2101		entry->tag_num = io->scsiio.tag_num;
2102		entry->lun_num = lun->lun;
2103#ifdef CTL_TIME_IO
2104		entry->start_bt = io->io_hdr.start_bt;
2105#endif
2106		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2107		entry->cdb_len = io->scsiio.cdb_len;
2108		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2109			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2110
2111		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2112			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2113
2114		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2115			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2116
2117		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2118			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2119
2120		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2121			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2122	}
2123	mtx_unlock(&lun->lun_lock);
2124
2125	return (retval);
2126}
2127
2128static void *
2129ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2130		 size_t error_str_len)
2131{
2132	void *kptr;
2133
2134	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2135
2136	if (copyin(user_addr, kptr, len) != 0) {
2137		snprintf(error_str, error_str_len, "Error copying %d bytes "
2138			 "from user address %p to kernel address %p", len,
2139			 user_addr, kptr);
2140		free(kptr, M_CTL);
2141		return (NULL);
2142	}
2143
2144	return (kptr);
2145}
2146
2147static void
2148ctl_free_args(int num_args, struct ctl_be_arg *args)
2149{
2150	int i;
2151
2152	if (args == NULL)
2153		return;
2154
2155	for (i = 0; i < num_args; i++) {
2156		free(args[i].kname, M_CTL);
2157		free(args[i].kvalue, M_CTL);
2158	}
2159
2160	free(args, M_CTL);
2161}
2162
2163static struct ctl_be_arg *
2164ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2165		char *error_str, size_t error_str_len)
2166{
2167	struct ctl_be_arg *args;
2168	int i;
2169
2170	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2171				error_str, error_str_len);
2172
2173	if (args == NULL)
2174		goto bailout;
2175
2176	for (i = 0; i < num_args; i++) {
2177		args[i].kname = NULL;
2178		args[i].kvalue = NULL;
2179	}
2180
2181	for (i = 0; i < num_args; i++) {
2182		uint8_t *tmpptr;
2183
2184		args[i].kname = ctl_copyin_alloc(args[i].name,
2185			args[i].namelen, error_str, error_str_len);
2186		if (args[i].kname == NULL)
2187			goto bailout;
2188
2189		if (args[i].kname[args[i].namelen - 1] != '\0') {
2190			snprintf(error_str, error_str_len, "Argument %d "
2191				 "name is not NUL-terminated", i);
2192			goto bailout;
2193		}
2194
2195		if (args[i].flags & CTL_BEARG_RD) {
2196			tmpptr = ctl_copyin_alloc(args[i].value,
2197				args[i].vallen, error_str, error_str_len);
2198			if (tmpptr == NULL)
2199				goto bailout;
2200			if ((args[i].flags & CTL_BEARG_ASCII)
2201			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2202				snprintf(error_str, error_str_len, "Argument "
2203				    "%d value is not NUL-terminated", i);
2204				goto bailout;
2205			}
2206			args[i].kvalue = tmpptr;
2207		} else {
2208			args[i].kvalue = malloc(args[i].vallen,
2209			    M_CTL, M_WAITOK | M_ZERO);
2210		}
2211	}
2212
2213	return (args);
2214bailout:
2215
2216	ctl_free_args(num_args, args);
2217
2218	return (NULL);
2219}
2220
2221static void
2222ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2223{
2224	int i;
2225
2226	for (i = 0; i < num_args; i++) {
2227		if (args[i].flags & CTL_BEARG_WR)
2228			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2229	}
2230}
2231
2232/*
2233 * Escape characters that are illegal or not recommended in XML.
2234 */
2235int
2236ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2237{
2238	char *end = str + size;
2239	int retval;
2240
2241	retval = 0;
2242
2243	for (; *str && str < end; str++) {
2244		switch (*str) {
2245		case '&':
2246			retval = sbuf_printf(sb, "&amp;");
2247			break;
2248		case '>':
2249			retval = sbuf_printf(sb, "&gt;");
2250			break;
2251		case '<':
2252			retval = sbuf_printf(sb, "&lt;");
2253			break;
2254		default:
2255			retval = sbuf_putc(sb, *str);
2256			break;
2257		}
2258
2259		if (retval != 0)
2260			break;
2261
2262	}
2263
2264	return (retval);
2265}
2266
2267static void
2268ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2269{
2270	struct scsi_vpd_id_descriptor *desc;
2271	int i;
2272
2273	if (id == NULL || id->len < 4)
2274		return;
2275	desc = (struct scsi_vpd_id_descriptor *)id->data;
2276	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2277	case SVPD_ID_TYPE_T10:
2278		sbuf_printf(sb, "t10.");
2279		break;
2280	case SVPD_ID_TYPE_EUI64:
2281		sbuf_printf(sb, "eui.");
2282		break;
2283	case SVPD_ID_TYPE_NAA:
2284		sbuf_printf(sb, "naa.");
2285		break;
2286	case SVPD_ID_TYPE_SCSI_NAME:
2287		break;
2288	}
2289	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2290	case SVPD_ID_CODESET_BINARY:
2291		for (i = 0; i < desc->length; i++)
2292			sbuf_printf(sb, "%02x", desc->identifier[i]);
2293		break;
2294	case SVPD_ID_CODESET_ASCII:
2295		sbuf_printf(sb, "%.*s", (int)desc->length,
2296		    (char *)desc->identifier);
2297		break;
2298	case SVPD_ID_CODESET_UTF8:
2299		sbuf_printf(sb, "%s", (char *)desc->identifier);
2300		break;
2301	}
2302}
2303
2304static int
2305ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2306	  struct thread *td)
2307{
2308	struct ctl_softc *softc;
2309	int retval;
2310
2311	softc = control_softc;
2312
2313	retval = 0;
2314
2315	switch (cmd) {
2316	case CTL_IO: {
2317		union ctl_io *io;
2318		void *pool_tmp;
2319
2320		/*
2321		 * If we haven't been "enabled", don't allow any SCSI I/O
2322		 * to this FETD.
2323		 */
2324		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2325			retval = EPERM;
2326			break;
2327		}
2328
2329		io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2330
2331		/*
2332		 * Need to save the pool reference so it doesn't get
2333		 * spammed by the user's ctl_io.
2334		 */
2335		pool_tmp = io->io_hdr.pool;
2336		memcpy(io, (void *)addr, sizeof(*io));
2337		io->io_hdr.pool = pool_tmp;
2338
2339		/*
2340		 * No status yet, so make sure the status is set properly.
2341		 */
2342		io->io_hdr.status = CTL_STATUS_NONE;
2343
2344		/*
2345		 * The user sets the initiator ID, target and LUN IDs.
2346		 */
2347		io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2348		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2349		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2350		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2351			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2352
2353		retval = ctl_ioctl_submit_wait(io);
2354
2355		if (retval != 0) {
2356			ctl_free_io(io);
2357			break;
2358		}
2359
2360		memcpy((void *)addr, io, sizeof(*io));
2361
2362		/* return this to our pool */
2363		ctl_free_io(io);
2364
2365		break;
2366	}
2367	case CTL_ENABLE_PORT:
2368	case CTL_DISABLE_PORT:
2369	case CTL_SET_PORT_WWNS: {
2370		struct ctl_port *port;
2371		struct ctl_port_entry *entry;
2372
2373		entry = (struct ctl_port_entry *)addr;
2374
2375		mtx_lock(&softc->ctl_lock);
2376		STAILQ_FOREACH(port, &softc->port_list, links) {
2377			int action, done;
2378
2379			action = 0;
2380			done = 0;
2381
2382			if ((entry->port_type == CTL_PORT_NONE)
2383			 && (entry->targ_port == port->targ_port)) {
2384				/*
2385				 * If the user only wants to enable or
2386				 * disable or set WWNs on a specific port,
2387				 * do the operation and we're done.
2388				 */
2389				action = 1;
2390				done = 1;
2391			} else if (entry->port_type & port->port_type) {
2392				/*
2393				 * Compare the user's type mask with the
2394				 * particular frontend type to see if we
2395				 * have a match.
2396				 */
2397				action = 1;
2398				done = 0;
2399
2400				/*
2401				 * Make sure the user isn't trying to set
2402				 * WWNs on multiple ports at the same time.
2403				 */
2404				if (cmd == CTL_SET_PORT_WWNS) {
2405					printf("%s: Can't set WWNs on "
2406					       "multiple ports\n", __func__);
2407					retval = EINVAL;
2408					break;
2409				}
2410			}
2411			if (action != 0) {
2412				/*
2413				 * XXX KDM we have to drop the lock here,
2414				 * because the online/offline operations
2415				 * can potentially block.  We need to
2416				 * reference count the frontends so they
2417				 * can't go away,
2418				 */
2419				mtx_unlock(&softc->ctl_lock);
2420
2421				if (cmd == CTL_ENABLE_PORT) {
2422					struct ctl_lun *lun;
2423
2424					STAILQ_FOREACH(lun, &softc->lun_list,
2425						       links) {
2426						port->lun_enable(port->targ_lun_arg,
2427						    lun->target,
2428						    lun->lun);
2429					}
2430
2431					ctl_port_online(port);
2432				} else if (cmd == CTL_DISABLE_PORT) {
2433					struct ctl_lun *lun;
2434
2435					ctl_port_offline(port);
2436
2437					STAILQ_FOREACH(lun, &softc->lun_list,
2438						       links) {
2439						port->lun_disable(
2440						    port->targ_lun_arg,
2441						    lun->target,
2442						    lun->lun);
2443					}
2444				}
2445
2446				mtx_lock(&softc->ctl_lock);
2447
2448				if (cmd == CTL_SET_PORT_WWNS)
2449					ctl_port_set_wwns(port,
2450					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2451					    1 : 0, entry->wwnn,
2452					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2453					    1 : 0, entry->wwpn);
2454			}
2455			if (done != 0)
2456				break;
2457		}
2458		mtx_unlock(&softc->ctl_lock);
2459		break;
2460	}
2461	case CTL_GET_PORT_LIST: {
2462		struct ctl_port *port;
2463		struct ctl_port_list *list;
2464		int i;
2465
2466		list = (struct ctl_port_list *)addr;
2467
2468		if (list->alloc_len != (list->alloc_num *
2469		    sizeof(struct ctl_port_entry))) {
2470			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2471			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2472			       "%zu\n", __func__, list->alloc_len,
2473			       list->alloc_num, sizeof(struct ctl_port_entry));
2474			retval = EINVAL;
2475			break;
2476		}
2477		list->fill_len = 0;
2478		list->fill_num = 0;
2479		list->dropped_num = 0;
2480		i = 0;
2481		mtx_lock(&softc->ctl_lock);
2482		STAILQ_FOREACH(port, &softc->port_list, links) {
2483			struct ctl_port_entry entry, *list_entry;
2484
2485			if (list->fill_num >= list->alloc_num) {
2486				list->dropped_num++;
2487				continue;
2488			}
2489
2490			entry.port_type = port->port_type;
2491			strlcpy(entry.port_name, port->port_name,
2492				sizeof(entry.port_name));
2493			entry.targ_port = port->targ_port;
2494			entry.physical_port = port->physical_port;
2495			entry.virtual_port = port->virtual_port;
2496			entry.wwnn = port->wwnn;
2497			entry.wwpn = port->wwpn;
2498			if (port->status & CTL_PORT_STATUS_ONLINE)
2499				entry.online = 1;
2500			else
2501				entry.online = 0;
2502
2503			list_entry = &list->entries[i];
2504
2505			retval = copyout(&entry, list_entry, sizeof(entry));
2506			if (retval != 0) {
2507				printf("%s: CTL_GET_PORT_LIST: copyout "
2508				       "returned %d\n", __func__, retval);
2509				break;
2510			}
2511			i++;
2512			list->fill_num++;
2513			list->fill_len += sizeof(entry);
2514		}
2515		mtx_unlock(&softc->ctl_lock);
2516
2517		/*
2518		 * If this is non-zero, we had a copyout fault, so there's
2519		 * probably no point in attempting to set the status inside
2520		 * the structure.
2521		 */
2522		if (retval != 0)
2523			break;
2524
2525		if (list->dropped_num > 0)
2526			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2527		else
2528			list->status = CTL_PORT_LIST_OK;
2529		break;
2530	}
2531	case CTL_DUMP_OOA: {
2532		struct ctl_lun *lun;
2533		union ctl_io *io;
2534		char printbuf[128];
2535		struct sbuf sb;
2536
2537		mtx_lock(&softc->ctl_lock);
2538		printf("Dumping OOA queues:\n");
2539		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2540			mtx_lock(&lun->lun_lock);
2541			for (io = (union ctl_io *)TAILQ_FIRST(
2542			     &lun->ooa_queue); io != NULL;
2543			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2544			     ooa_links)) {
2545				sbuf_new(&sb, printbuf, sizeof(printbuf),
2546					 SBUF_FIXEDLEN);
2547				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2548					    (intmax_t)lun->lun,
2549					    io->scsiio.tag_num,
2550					    (io->io_hdr.flags &
2551					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2552					    (io->io_hdr.flags &
2553					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2554					    (io->io_hdr.flags &
2555					    CTL_FLAG_ABORT) ? " ABORT" : "",
2556			                    (io->io_hdr.flags &
2557		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2558				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2559				sbuf_finish(&sb);
2560				printf("%s\n", sbuf_data(&sb));
2561			}
2562			mtx_unlock(&lun->lun_lock);
2563		}
2564		printf("OOA queues dump done\n");
2565		mtx_unlock(&softc->ctl_lock);
2566		break;
2567	}
2568	case CTL_GET_OOA: {
2569		struct ctl_lun *lun;
2570		struct ctl_ooa *ooa_hdr;
2571		struct ctl_ooa_entry *entries;
2572		uint32_t cur_fill_num;
2573
2574		ooa_hdr = (struct ctl_ooa *)addr;
2575
2576		if ((ooa_hdr->alloc_len == 0)
2577		 || (ooa_hdr->alloc_num == 0)) {
2578			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2579			       "must be non-zero\n", __func__,
2580			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2581			retval = EINVAL;
2582			break;
2583		}
2584
2585		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2586		    sizeof(struct ctl_ooa_entry))) {
2587			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2588			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2589			       __func__, ooa_hdr->alloc_len,
2590			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2591			retval = EINVAL;
2592			break;
2593		}
2594
2595		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2596		if (entries == NULL) {
2597			printf("%s: could not allocate %d bytes for OOA "
2598			       "dump\n", __func__, ooa_hdr->alloc_len);
2599			retval = ENOMEM;
2600			break;
2601		}
2602
2603		mtx_lock(&softc->ctl_lock);
2604		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2605		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2606		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2607			mtx_unlock(&softc->ctl_lock);
2608			free(entries, M_CTL);
2609			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2610			       __func__, (uintmax_t)ooa_hdr->lun_num);
2611			retval = EINVAL;
2612			break;
2613		}
2614
2615		cur_fill_num = 0;
2616
2617		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2618			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2619				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2620					ooa_hdr, entries);
2621				if (retval != 0)
2622					break;
2623			}
2624			if (retval != 0) {
2625				mtx_unlock(&softc->ctl_lock);
2626				free(entries, M_CTL);
2627				break;
2628			}
2629		} else {
2630			lun = softc->ctl_luns[ooa_hdr->lun_num];
2631
2632			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2633						    entries);
2634		}
2635		mtx_unlock(&softc->ctl_lock);
2636
2637		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2638		ooa_hdr->fill_len = ooa_hdr->fill_num *
2639			sizeof(struct ctl_ooa_entry);
2640		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2641		if (retval != 0) {
2642			printf("%s: error copying out %d bytes for OOA dump\n",
2643			       __func__, ooa_hdr->fill_len);
2644		}
2645
2646		getbintime(&ooa_hdr->cur_bt);
2647
2648		if (cur_fill_num > ooa_hdr->alloc_num) {
2649			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2650			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2651		} else {
2652			ooa_hdr->dropped_num = 0;
2653			ooa_hdr->status = CTL_OOA_OK;
2654		}
2655
2656		free(entries, M_CTL);
2657		break;
2658	}
2659	case CTL_CHECK_OOA: {
2660		union ctl_io *io;
2661		struct ctl_lun *lun;
2662		struct ctl_ooa_info *ooa_info;
2663
2664
2665		ooa_info = (struct ctl_ooa_info *)addr;
2666
2667		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2668			ooa_info->status = CTL_OOA_INVALID_LUN;
2669			break;
2670		}
2671		mtx_lock(&softc->ctl_lock);
2672		lun = softc->ctl_luns[ooa_info->lun_id];
2673		if (lun == NULL) {
2674			mtx_unlock(&softc->ctl_lock);
2675			ooa_info->status = CTL_OOA_INVALID_LUN;
2676			break;
2677		}
2678		mtx_lock(&lun->lun_lock);
2679		mtx_unlock(&softc->ctl_lock);
2680		ooa_info->num_entries = 0;
2681		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2682		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2683		     &io->io_hdr, ooa_links)) {
2684			ooa_info->num_entries++;
2685		}
2686		mtx_unlock(&lun->lun_lock);
2687
2688		ooa_info->status = CTL_OOA_SUCCESS;
2689
2690		break;
2691	}
2692	case CTL_HARD_START:
2693	case CTL_HARD_STOP: {
2694		struct ctl_fe_ioctl_startstop_info ss_info;
2695		struct cfi_metatask *metatask;
2696		struct mtx hs_mtx;
2697
2698		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2699
2700		cv_init(&ss_info.sem, "hard start/stop cv" );
2701
2702		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2703		if (metatask == NULL) {
2704			retval = ENOMEM;
2705			mtx_destroy(&hs_mtx);
2706			break;
2707		}
2708
2709		if (cmd == CTL_HARD_START)
2710			metatask->tasktype = CFI_TASK_STARTUP;
2711		else
2712			metatask->tasktype = CFI_TASK_SHUTDOWN;
2713
2714		metatask->callback = ctl_ioctl_hard_startstop_callback;
2715		metatask->callback_arg = &ss_info;
2716
2717		cfi_action(metatask);
2718
2719		/* Wait for the callback */
2720		mtx_lock(&hs_mtx);
2721		cv_wait_sig(&ss_info.sem, &hs_mtx);
2722		mtx_unlock(&hs_mtx);
2723
2724		/*
2725		 * All information has been copied from the metatask by the
2726		 * time cv_broadcast() is called, so we free the metatask here.
2727		 */
2728		cfi_free_metatask(metatask);
2729
2730		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2731
2732		mtx_destroy(&hs_mtx);
2733		break;
2734	}
2735	case CTL_BBRREAD: {
2736		struct ctl_bbrread_info *bbr_info;
2737		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2738		struct mtx bbr_mtx;
2739		struct cfi_metatask *metatask;
2740
2741		bbr_info = (struct ctl_bbrread_info *)addr;
2742
2743		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2744
2745		bzero(&bbr_mtx, sizeof(bbr_mtx));
2746		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2747
2748		fe_bbr_info.bbr_info = bbr_info;
2749		fe_bbr_info.lock = &bbr_mtx;
2750
2751		cv_init(&fe_bbr_info.sem, "BBR read cv");
2752		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2753
2754		if (metatask == NULL) {
2755			mtx_destroy(&bbr_mtx);
2756			cv_destroy(&fe_bbr_info.sem);
2757			retval = ENOMEM;
2758			break;
2759		}
2760		metatask->tasktype = CFI_TASK_BBRREAD;
2761		metatask->callback = ctl_ioctl_bbrread_callback;
2762		metatask->callback_arg = &fe_bbr_info;
2763		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2764		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2765		metatask->taskinfo.bbrread.len = bbr_info->len;
2766
2767		cfi_action(metatask);
2768
2769		mtx_lock(&bbr_mtx);
2770		while (fe_bbr_info.wakeup_done == 0)
2771			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2772		mtx_unlock(&bbr_mtx);
2773
2774		bbr_info->status = metatask->status;
2775		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2776		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2777		memcpy(&bbr_info->sense_data,
2778		       &metatask->taskinfo.bbrread.sense_data,
2779		       ctl_min(sizeof(bbr_info->sense_data),
2780			       sizeof(metatask->taskinfo.bbrread.sense_data)));
2781
2782		cfi_free_metatask(metatask);
2783
2784		mtx_destroy(&bbr_mtx);
2785		cv_destroy(&fe_bbr_info.sem);
2786
2787		break;
2788	}
2789	case CTL_DELAY_IO: {
2790		struct ctl_io_delay_info *delay_info;
2791#ifdef CTL_IO_DELAY
2792		struct ctl_lun *lun;
2793#endif /* CTL_IO_DELAY */
2794
2795		delay_info = (struct ctl_io_delay_info *)addr;
2796
2797#ifdef CTL_IO_DELAY
2798		mtx_lock(&softc->ctl_lock);
2799
2800		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2801		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2802			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2803		} else {
2804			lun = softc->ctl_luns[delay_info->lun_id];
2805			mtx_lock(&lun->lun_lock);
2806
2807			delay_info->status = CTL_DELAY_STATUS_OK;
2808
2809			switch (delay_info->delay_type) {
2810			case CTL_DELAY_TYPE_CONT:
2811				break;
2812			case CTL_DELAY_TYPE_ONESHOT:
2813				break;
2814			default:
2815				delay_info->status =
2816					CTL_DELAY_STATUS_INVALID_TYPE;
2817				break;
2818			}
2819
2820			switch (delay_info->delay_loc) {
2821			case CTL_DELAY_LOC_DATAMOVE:
2822				lun->delay_info.datamove_type =
2823					delay_info->delay_type;
2824				lun->delay_info.datamove_delay =
2825					delay_info->delay_secs;
2826				break;
2827			case CTL_DELAY_LOC_DONE:
2828				lun->delay_info.done_type =
2829					delay_info->delay_type;
2830				lun->delay_info.done_delay =
2831					delay_info->delay_secs;
2832				break;
2833			default:
2834				delay_info->status =
2835					CTL_DELAY_STATUS_INVALID_LOC;
2836				break;
2837			}
2838			mtx_unlock(&lun->lun_lock);
2839		}
2840
2841		mtx_unlock(&softc->ctl_lock);
2842#else
2843		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2844#endif /* CTL_IO_DELAY */
2845		break;
2846	}
2847	case CTL_REALSYNC_SET: {
2848		int *syncstate;
2849
2850		syncstate = (int *)addr;
2851
2852		mtx_lock(&softc->ctl_lock);
2853		switch (*syncstate) {
2854		case 0:
2855			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2856			break;
2857		case 1:
2858			softc->flags |= CTL_FLAG_REAL_SYNC;
2859			break;
2860		default:
2861			retval = EINVAL;
2862			break;
2863		}
2864		mtx_unlock(&softc->ctl_lock);
2865		break;
2866	}
2867	case CTL_REALSYNC_GET: {
2868		int *syncstate;
2869
2870		syncstate = (int*)addr;
2871
2872		mtx_lock(&softc->ctl_lock);
2873		if (softc->flags & CTL_FLAG_REAL_SYNC)
2874			*syncstate = 1;
2875		else
2876			*syncstate = 0;
2877		mtx_unlock(&softc->ctl_lock);
2878
2879		break;
2880	}
2881	case CTL_SETSYNC:
2882	case CTL_GETSYNC: {
2883		struct ctl_sync_info *sync_info;
2884		struct ctl_lun *lun;
2885
2886		sync_info = (struct ctl_sync_info *)addr;
2887
2888		mtx_lock(&softc->ctl_lock);
2889		lun = softc->ctl_luns[sync_info->lun_id];
2890		if (lun == NULL) {
2891			mtx_unlock(&softc->ctl_lock);
2892			sync_info->status = CTL_GS_SYNC_NO_LUN;
2893		}
2894		/*
2895		 * Get or set the sync interval.  We're not bounds checking
2896		 * in the set case, hopefully the user won't do something
2897		 * silly.
2898		 */
2899		mtx_lock(&lun->lun_lock);
2900		mtx_unlock(&softc->ctl_lock);
2901		if (cmd == CTL_GETSYNC)
2902			sync_info->sync_interval = lun->sync_interval;
2903		else
2904			lun->sync_interval = sync_info->sync_interval;
2905		mtx_unlock(&lun->lun_lock);
2906
2907		sync_info->status = CTL_GS_SYNC_OK;
2908
2909		break;
2910	}
2911	case CTL_GETSTATS: {
2912		struct ctl_stats *stats;
2913		struct ctl_lun *lun;
2914		int i;
2915
2916		stats = (struct ctl_stats *)addr;
2917
2918		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2919		     stats->alloc_len) {
2920			stats->status = CTL_SS_NEED_MORE_SPACE;
2921			stats->num_luns = softc->num_luns;
2922			break;
2923		}
2924		/*
2925		 * XXX KDM no locking here.  If the LUN list changes,
2926		 * things can blow up.
2927		 */
2928		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2929		     i++, lun = STAILQ_NEXT(lun, links)) {
2930			retval = copyout(&lun->stats, &stats->lun_stats[i],
2931					 sizeof(lun->stats));
2932			if (retval != 0)
2933				break;
2934		}
2935		stats->num_luns = softc->num_luns;
2936		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2937				 softc->num_luns;
2938		stats->status = CTL_SS_OK;
2939#ifdef CTL_TIME_IO
2940		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2941#else
2942		stats->flags = CTL_STATS_FLAG_NONE;
2943#endif
2944		getnanouptime(&stats->timestamp);
2945		break;
2946	}
2947	case CTL_ERROR_INJECT: {
2948		struct ctl_error_desc *err_desc, *new_err_desc;
2949		struct ctl_lun *lun;
2950
2951		err_desc = (struct ctl_error_desc *)addr;
2952
2953		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2954				      M_WAITOK | M_ZERO);
2955		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2956
2957		mtx_lock(&softc->ctl_lock);
2958		lun = softc->ctl_luns[err_desc->lun_id];
2959		if (lun == NULL) {
2960			mtx_unlock(&softc->ctl_lock);
2961			free(new_err_desc, M_CTL);
2962			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2963			       __func__, (uintmax_t)err_desc->lun_id);
2964			retval = EINVAL;
2965			break;
2966		}
2967		mtx_lock(&lun->lun_lock);
2968		mtx_unlock(&softc->ctl_lock);
2969
2970		/*
2971		 * We could do some checking here to verify the validity
2972		 * of the request, but given the complexity of error
2973		 * injection requests, the checking logic would be fairly
2974		 * complex.
2975		 *
2976		 * For now, if the request is invalid, it just won't get
2977		 * executed and might get deleted.
2978		 */
2979		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2980
2981		/*
2982		 * XXX KDM check to make sure the serial number is unique,
2983		 * in case we somehow manage to wrap.  That shouldn't
2984		 * happen for a very long time, but it's the right thing to
2985		 * do.
2986		 */
2987		new_err_desc->serial = lun->error_serial;
2988		err_desc->serial = lun->error_serial;
2989		lun->error_serial++;
2990
2991		mtx_unlock(&lun->lun_lock);
2992		break;
2993	}
2994	case CTL_ERROR_INJECT_DELETE: {
2995		struct ctl_error_desc *delete_desc, *desc, *desc2;
2996		struct ctl_lun *lun;
2997		int delete_done;
2998
2999		delete_desc = (struct ctl_error_desc *)addr;
3000		delete_done = 0;
3001
3002		mtx_lock(&softc->ctl_lock);
3003		lun = softc->ctl_luns[delete_desc->lun_id];
3004		if (lun == NULL) {
3005			mtx_unlock(&softc->ctl_lock);
3006			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
3007			       __func__, (uintmax_t)delete_desc->lun_id);
3008			retval = EINVAL;
3009			break;
3010		}
3011		mtx_lock(&lun->lun_lock);
3012		mtx_unlock(&softc->ctl_lock);
3013		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
3014			if (desc->serial != delete_desc->serial)
3015				continue;
3016
3017			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
3018				      links);
3019			free(desc, M_CTL);
3020			delete_done = 1;
3021		}
3022		mtx_unlock(&lun->lun_lock);
3023		if (delete_done == 0) {
3024			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
3025			       "error serial %ju on LUN %u\n", __func__,
3026			       delete_desc->serial, delete_desc->lun_id);
3027			retval = EINVAL;
3028			break;
3029		}
3030		break;
3031	}
3032	case CTL_DUMP_STRUCTS: {
3033		int i, j, k;
3034		struct ctl_port *port;
3035		struct ctl_frontend *fe;
3036
3037		mtx_lock(&softc->ctl_lock);
3038		printf("CTL Persistent Reservation information start:\n");
3039		for (i = 0; i < CTL_MAX_LUNS; i++) {
3040			struct ctl_lun *lun;
3041
3042			lun = softc->ctl_luns[i];
3043
3044			if ((lun == NULL)
3045			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
3046				continue;
3047
3048			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
3049				if (lun->pr_keys[j] == NULL)
3050					continue;
3051				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
3052					if (lun->pr_keys[j][k] == 0)
3053						continue;
3054					printf("  LUN %d port %d iid %d key "
3055					       "%#jx\n", i, j, k,
3056					       (uintmax_t)lun->pr_keys[j][k]);
3057				}
3058			}
3059		}
3060		printf("CTL Persistent Reservation information end\n");
3061		printf("CTL Ports:\n");
3062		STAILQ_FOREACH(port, &softc->port_list, links) {
3063			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3064			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3065			       port->frontend->name, port->port_type,
3066			       port->physical_port, port->virtual_port,
3067			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3068			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3069				if (port->wwpn_iid[j].in_use == 0 &&
3070				    port->wwpn_iid[j].wwpn == 0 &&
3071				    port->wwpn_iid[j].name == NULL)
3072					continue;
3073
3074				printf("    iid %u use %d WWPN %#jx '%s'\n",
3075				    j, port->wwpn_iid[j].in_use,
3076				    (uintmax_t)port->wwpn_iid[j].wwpn,
3077				    port->wwpn_iid[j].name);
3078			}
3079		}
3080		printf("CTL Port information end\n");
3081		mtx_unlock(&softc->ctl_lock);
3082		/*
3083		 * XXX KDM calling this without a lock.  We'd likely want
3084		 * to drop the lock before calling the frontend's dump
3085		 * routine anyway.
3086		 */
3087		printf("CTL Frontends:\n");
3088		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3089			printf("  Frontend '%s'\n", fe->name);
3090			if (fe->fe_dump != NULL)
3091				fe->fe_dump();
3092		}
3093		printf("CTL Frontend information end\n");
3094		break;
3095	}
3096	case CTL_LUN_REQ: {
3097		struct ctl_lun_req *lun_req;
3098		struct ctl_backend_driver *backend;
3099
3100		lun_req = (struct ctl_lun_req *)addr;
3101
3102		backend = ctl_backend_find(lun_req->backend);
3103		if (backend == NULL) {
3104			lun_req->status = CTL_LUN_ERROR;
3105			snprintf(lun_req->error_str,
3106				 sizeof(lun_req->error_str),
3107				 "Backend \"%s\" not found.",
3108				 lun_req->backend);
3109			break;
3110		}
3111		if (lun_req->num_be_args > 0) {
3112			lun_req->kern_be_args = ctl_copyin_args(
3113				lun_req->num_be_args,
3114				lun_req->be_args,
3115				lun_req->error_str,
3116				sizeof(lun_req->error_str));
3117			if (lun_req->kern_be_args == NULL) {
3118				lun_req->status = CTL_LUN_ERROR;
3119				break;
3120			}
3121		}
3122
3123		retval = backend->ioctl(dev, cmd, addr, flag, td);
3124
3125		if (lun_req->num_be_args > 0) {
3126			ctl_copyout_args(lun_req->num_be_args,
3127				      lun_req->kern_be_args);
3128			ctl_free_args(lun_req->num_be_args,
3129				      lun_req->kern_be_args);
3130		}
3131		break;
3132	}
3133	case CTL_LUN_LIST: {
3134		struct sbuf *sb;
3135		struct ctl_lun *lun;
3136		struct ctl_lun_list *list;
3137		struct ctl_option *opt;
3138
3139		list = (struct ctl_lun_list *)addr;
3140
3141		/*
3142		 * Allocate a fixed length sbuf here, based on the length
3143		 * of the user's buffer.  We could allocate an auto-extending
3144		 * buffer, and then tell the user how much larger our
3145		 * amount of data is than his buffer, but that presents
3146		 * some problems:
3147		 *
3148		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3149		 *     we can't hold a lock while calling them with an
3150		 *     auto-extending buffer.
3151 		 *
3152		 * 2.  There is not currently a LUN reference counting
3153		 *     mechanism, outside of outstanding transactions on
3154		 *     the LUN's OOA queue.  So a LUN could go away on us
3155		 *     while we're getting the LUN number, backend-specific
3156		 *     information, etc.  Thus, given the way things
3157		 *     currently work, we need to hold the CTL lock while
3158		 *     grabbing LUN information.
3159		 *
3160		 * So, from the user's standpoint, the best thing to do is
3161		 * allocate what he thinks is a reasonable buffer length,
3162		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3163		 * double the buffer length and try again.  (And repeat
3164		 * that until he succeeds.)
3165		 */
3166		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3167		if (sb == NULL) {
3168			list->status = CTL_LUN_LIST_ERROR;
3169			snprintf(list->error_str, sizeof(list->error_str),
3170				 "Unable to allocate %d bytes for LUN list",
3171				 list->alloc_len);
3172			break;
3173		}
3174
3175		sbuf_printf(sb, "<ctllunlist>\n");
3176
3177		mtx_lock(&softc->ctl_lock);
3178		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3179			mtx_lock(&lun->lun_lock);
3180			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3181					     (uintmax_t)lun->lun);
3182
3183			/*
3184			 * Bail out as soon as we see that we've overfilled
3185			 * the buffer.
3186			 */
3187			if (retval != 0)
3188				break;
3189
3190			retval = sbuf_printf(sb, "\t<backend_type>%s"
3191					     "</backend_type>\n",
3192					     (lun->backend == NULL) ?  "none" :
3193					     lun->backend->name);
3194
3195			if (retval != 0)
3196				break;
3197
3198			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3199					     lun->be_lun->lun_type);
3200
3201			if (retval != 0)
3202				break;
3203
3204			if (lun->backend == NULL) {
3205				retval = sbuf_printf(sb, "</lun>\n");
3206				if (retval != 0)
3207					break;
3208				continue;
3209			}
3210
3211			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3212					     (lun->be_lun->maxlba > 0) ?
3213					     lun->be_lun->maxlba + 1 : 0);
3214
3215			if (retval != 0)
3216				break;
3217
3218			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3219					     lun->be_lun->blocksize);
3220
3221			if (retval != 0)
3222				break;
3223
3224			retval = sbuf_printf(sb, "\t<serial_number>");
3225
3226			if (retval != 0)
3227				break;
3228
3229			retval = ctl_sbuf_printf_esc(sb,
3230			    lun->be_lun->serial_num,
3231			    sizeof(lun->be_lun->serial_num));
3232
3233			if (retval != 0)
3234				break;
3235
3236			retval = sbuf_printf(sb, "</serial_number>\n");
3237
3238			if (retval != 0)
3239				break;
3240
3241			retval = sbuf_printf(sb, "\t<device_id>");
3242
3243			if (retval != 0)
3244				break;
3245
3246			retval = ctl_sbuf_printf_esc(sb,
3247			    lun->be_lun->device_id,
3248			    sizeof(lun->be_lun->device_id));
3249
3250			if (retval != 0)
3251				break;
3252
3253			retval = sbuf_printf(sb, "</device_id>\n");
3254
3255			if (retval != 0)
3256				break;
3257
3258			if (lun->backend->lun_info != NULL) {
3259				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3260				if (retval != 0)
3261					break;
3262			}
3263			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3264				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3265				    opt->name, opt->value, opt->name);
3266				if (retval != 0)
3267					break;
3268			}
3269
3270			retval = sbuf_printf(sb, "</lun>\n");
3271
3272			if (retval != 0)
3273				break;
3274			mtx_unlock(&lun->lun_lock);
3275		}
3276		if (lun != NULL)
3277			mtx_unlock(&lun->lun_lock);
3278		mtx_unlock(&softc->ctl_lock);
3279
3280		if ((retval != 0)
3281		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3282			retval = 0;
3283			sbuf_delete(sb);
3284			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3285			snprintf(list->error_str, sizeof(list->error_str),
3286				 "Out of space, %d bytes is too small",
3287				 list->alloc_len);
3288			break;
3289		}
3290
3291		sbuf_finish(sb);
3292
3293		retval = copyout(sbuf_data(sb), list->lun_xml,
3294				 sbuf_len(sb) + 1);
3295
3296		list->fill_len = sbuf_len(sb) + 1;
3297		list->status = CTL_LUN_LIST_OK;
3298		sbuf_delete(sb);
3299		break;
3300	}
3301	case CTL_ISCSI: {
3302		struct ctl_iscsi *ci;
3303		struct ctl_frontend *fe;
3304
3305		ci = (struct ctl_iscsi *)addr;
3306
3307		fe = ctl_frontend_find("iscsi");
3308		if (fe == NULL) {
3309			ci->status = CTL_ISCSI_ERROR;
3310			snprintf(ci->error_str, sizeof(ci->error_str),
3311			    "Frontend \"iscsi\" not found.");
3312			break;
3313		}
3314
3315		retval = fe->ioctl(dev, cmd, addr, flag, td);
3316		break;
3317	}
3318	case CTL_PORT_REQ: {
3319		struct ctl_req *req;
3320		struct ctl_frontend *fe;
3321
3322		req = (struct ctl_req *)addr;
3323
3324		fe = ctl_frontend_find(req->driver);
3325		if (fe == NULL) {
3326			req->status = CTL_LUN_ERROR;
3327			snprintf(req->error_str, sizeof(req->error_str),
3328			    "Frontend \"%s\" not found.", req->driver);
3329			break;
3330		}
3331		if (req->num_args > 0) {
3332			req->kern_args = ctl_copyin_args(req->num_args,
3333			    req->args, req->error_str, sizeof(req->error_str));
3334			if (req->kern_args == NULL) {
3335				req->status = CTL_LUN_ERROR;
3336				break;
3337			}
3338		}
3339
3340		retval = fe->ioctl(dev, cmd, addr, flag, td);
3341
3342		if (req->num_args > 0) {
3343			ctl_copyout_args(req->num_args, req->kern_args);
3344			ctl_free_args(req->num_args, req->kern_args);
3345		}
3346		break;
3347	}
3348	case CTL_PORT_LIST: {
3349		struct sbuf *sb;
3350		struct ctl_port *port;
3351		struct ctl_lun_list *list;
3352		struct ctl_option *opt;
3353		int j;
3354
3355		list = (struct ctl_lun_list *)addr;
3356
3357		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3358		if (sb == NULL) {
3359			list->status = CTL_LUN_LIST_ERROR;
3360			snprintf(list->error_str, sizeof(list->error_str),
3361				 "Unable to allocate %d bytes for LUN list",
3362				 list->alloc_len);
3363			break;
3364		}
3365
3366		sbuf_printf(sb, "<ctlportlist>\n");
3367
3368		mtx_lock(&softc->ctl_lock);
3369		STAILQ_FOREACH(port, &softc->port_list, links) {
3370			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3371					     (uintmax_t)port->targ_port);
3372
3373			/*
3374			 * Bail out as soon as we see that we've overfilled
3375			 * the buffer.
3376			 */
3377			if (retval != 0)
3378				break;
3379
3380			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3381			    "</frontend_type>\n", port->frontend->name);
3382			if (retval != 0)
3383				break;
3384
3385			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3386					     port->port_type);
3387			if (retval != 0)
3388				break;
3389
3390			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3391			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3392			if (retval != 0)
3393				break;
3394
3395			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3396			    port->port_name);
3397			if (retval != 0)
3398				break;
3399
3400			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3401			    port->physical_port);
3402			if (retval != 0)
3403				break;
3404
3405			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3406			    port->virtual_port);
3407			if (retval != 0)
3408				break;
3409
3410			if (port->target_devid != NULL) {
3411				sbuf_printf(sb, "\t<target>");
3412				ctl_id_sbuf(port->target_devid, sb);
3413				sbuf_printf(sb, "</target>\n");
3414			}
3415
3416			if (port->port_devid != NULL) {
3417				sbuf_printf(sb, "\t<port>");
3418				ctl_id_sbuf(port->port_devid, sb);
3419				sbuf_printf(sb, "</port>\n");
3420			}
3421
3422			if (port->port_info != NULL) {
3423				retval = port->port_info(port->onoff_arg, sb);
3424				if (retval != 0)
3425					break;
3426			}
3427			STAILQ_FOREACH(opt, &port->options, links) {
3428				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3429				    opt->name, opt->value, opt->name);
3430				if (retval != 0)
3431					break;
3432			}
3433
3434			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3435				if (port->wwpn_iid[j].in_use == 0 ||
3436				    (port->wwpn_iid[j].wwpn == 0 &&
3437				     port->wwpn_iid[j].name == NULL))
3438					continue;
3439
3440				if (port->wwpn_iid[j].name != NULL)
3441					retval = sbuf_printf(sb,
3442					    "\t<initiator>%u %s</initiator>\n",
3443					    j, port->wwpn_iid[j].name);
3444				else
3445					retval = sbuf_printf(sb,
3446					    "\t<initiator>%u naa.%08jx</initiator>\n",
3447					    j, port->wwpn_iid[j].wwpn);
3448				if (retval != 0)
3449					break;
3450			}
3451			if (retval != 0)
3452				break;
3453
3454			retval = sbuf_printf(sb, "</targ_port>\n");
3455			if (retval != 0)
3456				break;
3457		}
3458		mtx_unlock(&softc->ctl_lock);
3459
3460		if ((retval != 0)
3461		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3462			retval = 0;
3463			sbuf_delete(sb);
3464			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3465			snprintf(list->error_str, sizeof(list->error_str),
3466				 "Out of space, %d bytes is too small",
3467				 list->alloc_len);
3468			break;
3469		}
3470
3471		sbuf_finish(sb);
3472
3473		retval = copyout(sbuf_data(sb), list->lun_xml,
3474				 sbuf_len(sb) + 1);
3475
3476		list->fill_len = sbuf_len(sb) + 1;
3477		list->status = CTL_LUN_LIST_OK;
3478		sbuf_delete(sb);
3479		break;
3480	}
3481	default: {
3482		/* XXX KDM should we fix this? */
3483#if 0
3484		struct ctl_backend_driver *backend;
3485		unsigned int type;
3486		int found;
3487
3488		found = 0;
3489
3490		/*
3491		 * We encode the backend type as the ioctl type for backend
3492		 * ioctls.  So parse it out here, and then search for a
3493		 * backend of this type.
3494		 */
3495		type = _IOC_TYPE(cmd);
3496
3497		STAILQ_FOREACH(backend, &softc->be_list, links) {
3498			if (backend->type == type) {
3499				found = 1;
3500				break;
3501			}
3502		}
3503		if (found == 0) {
3504			printf("ctl: unknown ioctl command %#lx or backend "
3505			       "%d\n", cmd, type);
3506			retval = EINVAL;
3507			break;
3508		}
3509		retval = backend->ioctl(dev, cmd, addr, flag, td);
3510#endif
3511		retval = ENOTTY;
3512		break;
3513	}
3514	}
3515	return (retval);
3516}
3517
3518uint32_t
3519ctl_get_initindex(struct ctl_nexus *nexus)
3520{
3521	if (nexus->targ_port < CTL_MAX_PORTS)
3522		return (nexus->initid.id +
3523			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3524	else
3525		return (nexus->initid.id +
3526		       ((nexus->targ_port - CTL_MAX_PORTS) *
3527			CTL_MAX_INIT_PER_PORT));
3528}
3529
3530uint32_t
3531ctl_get_resindex(struct ctl_nexus *nexus)
3532{
3533	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3534}
3535
3536uint32_t
3537ctl_port_idx(int port_num)
3538{
3539	if (port_num < CTL_MAX_PORTS)
3540		return(port_num);
3541	else
3542		return(port_num - CTL_MAX_PORTS);
3543}
3544
3545static uint32_t
3546ctl_map_lun(int port_num, uint32_t lun_id)
3547{
3548	struct ctl_port *port;
3549
3550	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3551	if (port == NULL)
3552		return (UINT32_MAX);
3553	if (port->lun_map == NULL)
3554		return (lun_id);
3555	return (port->lun_map(port->targ_lun_arg, lun_id));
3556}
3557
3558static uint32_t
3559ctl_map_lun_back(int port_num, uint32_t lun_id)
3560{
3561	struct ctl_port *port;
3562	uint32_t i;
3563
3564	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3565	if (port->lun_map == NULL)
3566		return (lun_id);
3567	for (i = 0; i < CTL_MAX_LUNS; i++) {
3568		if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3569			return (i);
3570	}
3571	return (UINT32_MAX);
3572}
3573
3574/*
3575 * Note:  This only works for bitmask sizes that are at least 32 bits, and
3576 * that are a power of 2.
3577 */
3578int
3579ctl_ffz(uint32_t *mask, uint32_t size)
3580{
3581	uint32_t num_chunks, num_pieces;
3582	int i, j;
3583
3584	num_chunks = (size >> 5);
3585	if (num_chunks == 0)
3586		num_chunks++;
3587	num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3588
3589	for (i = 0; i < num_chunks; i++) {
3590		for (j = 0; j < num_pieces; j++) {
3591			if ((mask[i] & (1 << j)) == 0)
3592				return ((i << 5) + j);
3593		}
3594	}
3595
3596	return (-1);
3597}
3598
3599int
3600ctl_set_mask(uint32_t *mask, uint32_t bit)
3601{
3602	uint32_t chunk, piece;
3603
3604	chunk = bit >> 5;
3605	piece = bit % (sizeof(uint32_t) * 8);
3606
3607	if ((mask[chunk] & (1 << piece)) != 0)
3608		return (-1);
3609	else
3610		mask[chunk] |= (1 << piece);
3611
3612	return (0);
3613}
3614
3615int
3616ctl_clear_mask(uint32_t *mask, uint32_t bit)
3617{
3618	uint32_t chunk, piece;
3619
3620	chunk = bit >> 5;
3621	piece = bit % (sizeof(uint32_t) * 8);
3622
3623	if ((mask[chunk] & (1 << piece)) == 0)
3624		return (-1);
3625	else
3626		mask[chunk] &= ~(1 << piece);
3627
3628	return (0);
3629}
3630
3631int
3632ctl_is_set(uint32_t *mask, uint32_t bit)
3633{
3634	uint32_t chunk, piece;
3635
3636	chunk = bit >> 5;
3637	piece = bit % (sizeof(uint32_t) * 8);
3638
3639	if ((mask[chunk] & (1 << piece)) == 0)
3640		return (0);
3641	else
3642		return (1);
3643}
3644
3645static uint64_t
3646ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3647{
3648	uint64_t *t;
3649
3650	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3651	if (t == NULL)
3652		return (0);
3653	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3654}
3655
3656static void
3657ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3658{
3659	uint64_t *t;
3660
3661	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3662	if (t == NULL)
3663		return;
3664	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3665}
3666
3667static void
3668ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3669{
3670	uint64_t *p;
3671	u_int i;
3672
3673	i = residx/CTL_MAX_INIT_PER_PORT;
3674	if (lun->pr_keys[i] != NULL)
3675		return;
3676	mtx_unlock(&lun->lun_lock);
3677	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3678	    M_WAITOK | M_ZERO);
3679	mtx_lock(&lun->lun_lock);
3680	if (lun->pr_keys[i] == NULL)
3681		lun->pr_keys[i] = p;
3682	else
3683		free(p, M_CTL);
3684}
3685
3686static void
3687ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3688{
3689	uint64_t *t;
3690
3691	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3692	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3693	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3694}
3695
3696/*
3697 * ctl_softc, pool_name, total_ctl_io are passed in.
3698 * npool is passed out.
3699 */
3700int
3701ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3702		uint32_t total_ctl_io, void **npool)
3703{
3704#ifdef IO_POOLS
3705	struct ctl_io_pool *pool;
3706
3707	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3708					    M_NOWAIT | M_ZERO);
3709	if (pool == NULL)
3710		return (ENOMEM);
3711
3712	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3713	pool->ctl_softc = ctl_softc;
3714	pool->zone = uma_zsecond_create(pool->name, NULL,
3715	    NULL, NULL, NULL, ctl_softc->io_zone);
3716	/* uma_prealloc(pool->zone, total_ctl_io); */
3717
3718	*npool = pool;
3719#else
3720	*npool = ctl_softc->io_zone;
3721#endif
3722	return (0);
3723}
3724
3725void
3726ctl_pool_free(struct ctl_io_pool *pool)
3727{
3728
3729	if (pool == NULL)
3730		return;
3731
3732#ifdef IO_POOLS
3733	uma_zdestroy(pool->zone);
3734	free(pool, M_CTL);
3735#endif
3736}
3737
3738union ctl_io *
3739ctl_alloc_io(void *pool_ref)
3740{
3741	union ctl_io *io;
3742#ifdef IO_POOLS
3743	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3744
3745	io = uma_zalloc(pool->zone, M_WAITOK);
3746#else
3747	io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3748#endif
3749	if (io != NULL)
3750		io->io_hdr.pool = pool_ref;
3751	return (io);
3752}
3753
3754union ctl_io *
3755ctl_alloc_io_nowait(void *pool_ref)
3756{
3757	union ctl_io *io;
3758#ifdef IO_POOLS
3759	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3760
3761	io = uma_zalloc(pool->zone, M_NOWAIT);
3762#else
3763	io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3764#endif
3765	if (io != NULL)
3766		io->io_hdr.pool = pool_ref;
3767	return (io);
3768}
3769
3770void
3771ctl_free_io(union ctl_io *io)
3772{
3773#ifdef IO_POOLS
3774	struct ctl_io_pool *pool;
3775#endif
3776
3777	if (io == NULL)
3778		return;
3779
3780#ifdef IO_POOLS
3781	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3782	uma_zfree(pool->zone, io);
3783#else
3784	uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3785#endif
3786}
3787
3788void
3789ctl_zero_io(union ctl_io *io)
3790{
3791	void *pool_ref;
3792
3793	if (io == NULL)
3794		return;
3795
3796	/*
3797	 * May need to preserve linked list pointers at some point too.
3798	 */
3799	pool_ref = io->io_hdr.pool;
3800	memset(io, 0, sizeof(*io));
3801	io->io_hdr.pool = pool_ref;
3802}
3803
3804/*
3805 * This routine is currently used for internal copies of ctl_ios that need
3806 * to persist for some reason after we've already returned status to the
3807 * FETD.  (Thus the flag set.)
3808 *
3809 * XXX XXX
3810 * Note that this makes a blind copy of all fields in the ctl_io, except
3811 * for the pool reference.  This includes any memory that has been
3812 * allocated!  That memory will no longer be valid after done has been
3813 * called, so this would be VERY DANGEROUS for command that actually does
3814 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3815 * start and stop commands, which don't transfer any data, so this is not a
3816 * problem.  If it is used for anything else, the caller would also need to
3817 * allocate data buffer space and this routine would need to be modified to
3818 * copy the data buffer(s) as well.
3819 */
3820void
3821ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3822{
3823	void *pool_ref;
3824
3825	if ((src == NULL)
3826	 || (dest == NULL))
3827		return;
3828
3829	/*
3830	 * May need to preserve linked list pointers at some point too.
3831	 */
3832	pool_ref = dest->io_hdr.pool;
3833
3834	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3835
3836	dest->io_hdr.pool = pool_ref;
3837	/*
3838	 * We need to know that this is an internal copy, and doesn't need
3839	 * to get passed back to the FETD that allocated it.
3840	 */
3841	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3842}
3843
3844static int
3845ctl_expand_number(const char *buf, uint64_t *num)
3846{
3847	char *endptr;
3848	uint64_t number;
3849	unsigned shift;
3850
3851	number = strtoq(buf, &endptr, 0);
3852
3853	switch (tolower((unsigned char)*endptr)) {
3854	case 'e':
3855		shift = 60;
3856		break;
3857	case 'p':
3858		shift = 50;
3859		break;
3860	case 't':
3861		shift = 40;
3862		break;
3863	case 'g':
3864		shift = 30;
3865		break;
3866	case 'm':
3867		shift = 20;
3868		break;
3869	case 'k':
3870		shift = 10;
3871		break;
3872	case 'b':
3873	case '\0': /* No unit. */
3874		*num = number;
3875		return (0);
3876	default:
3877		/* Unrecognized unit. */
3878		return (-1);
3879	}
3880
3881	if ((number << shift) >> shift != number) {
3882		/* Overflow */
3883		return (-1);
3884	}
3885	*num = number << shift;
3886	return (0);
3887}
3888
3889
3890/*
3891 * This routine could be used in the future to load default and/or saved
3892 * mode page parameters for a particuar lun.
3893 */
3894static int
3895ctl_init_page_index(struct ctl_lun *lun)
3896{
3897	int i;
3898	struct ctl_page_index *page_index;
3899	const char *value;
3900	uint64_t ival;
3901
3902	memcpy(&lun->mode_pages.index, page_index_template,
3903	       sizeof(page_index_template));
3904
3905	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3906
3907		page_index = &lun->mode_pages.index[i];
3908		/*
3909		 * If this is a disk-only mode page, there's no point in
3910		 * setting it up.  For some pages, we have to have some
3911		 * basic information about the disk in order to calculate the
3912		 * mode page data.
3913		 */
3914		if ((lun->be_lun->lun_type != T_DIRECT)
3915		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3916			continue;
3917
3918		switch (page_index->page_code & SMPH_PC_MASK) {
3919		case SMS_RW_ERROR_RECOVERY_PAGE: {
3920			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3921				panic("subpage is incorrect!");
3922			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3923			       &rw_er_page_default,
3924			       sizeof(rw_er_page_default));
3925			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3926			       &rw_er_page_changeable,
3927			       sizeof(rw_er_page_changeable));
3928			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3929			       &rw_er_page_default,
3930			       sizeof(rw_er_page_default));
3931			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3932			       &rw_er_page_default,
3933			       sizeof(rw_er_page_default));
3934			page_index->page_data =
3935				(uint8_t *)lun->mode_pages.rw_er_page;
3936			break;
3937		}
3938		case SMS_FORMAT_DEVICE_PAGE: {
3939			struct scsi_format_page *format_page;
3940
3941			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3942				panic("subpage is incorrect!");
3943
3944			/*
3945			 * Sectors per track are set above.  Bytes per
3946			 * sector need to be set here on a per-LUN basis.
3947			 */
3948			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3949			       &format_page_default,
3950			       sizeof(format_page_default));
3951			memcpy(&lun->mode_pages.format_page[
3952			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
3953			       sizeof(format_page_changeable));
3954			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3955			       &format_page_default,
3956			       sizeof(format_page_default));
3957			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3958			       &format_page_default,
3959			       sizeof(format_page_default));
3960
3961			format_page = &lun->mode_pages.format_page[
3962				CTL_PAGE_CURRENT];
3963			scsi_ulto2b(lun->be_lun->blocksize,
3964				    format_page->bytes_per_sector);
3965
3966			format_page = &lun->mode_pages.format_page[
3967				CTL_PAGE_DEFAULT];
3968			scsi_ulto2b(lun->be_lun->blocksize,
3969				    format_page->bytes_per_sector);
3970
3971			format_page = &lun->mode_pages.format_page[
3972				CTL_PAGE_SAVED];
3973			scsi_ulto2b(lun->be_lun->blocksize,
3974				    format_page->bytes_per_sector);
3975
3976			page_index->page_data =
3977				(uint8_t *)lun->mode_pages.format_page;
3978			break;
3979		}
3980		case SMS_RIGID_DISK_PAGE: {
3981			struct scsi_rigid_disk_page *rigid_disk_page;
3982			uint32_t sectors_per_cylinder;
3983			uint64_t cylinders;
3984#ifndef	__XSCALE__
3985			int shift;
3986#endif /* !__XSCALE__ */
3987
3988			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3989				panic("invalid subpage value %d",
3990				      page_index->subpage);
3991
3992			/*
3993			 * Rotation rate and sectors per track are set
3994			 * above.  We calculate the cylinders here based on
3995			 * capacity.  Due to the number of heads and
3996			 * sectors per track we're using, smaller arrays
3997			 * may turn out to have 0 cylinders.  Linux and
3998			 * FreeBSD don't pay attention to these mode pages
3999			 * to figure out capacity, but Solaris does.  It
4000			 * seems to deal with 0 cylinders just fine, and
4001			 * works out a fake geometry based on the capacity.
4002			 */
4003			memcpy(&lun->mode_pages.rigid_disk_page[
4004			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4005			       sizeof(rigid_disk_page_default));
4006			memcpy(&lun->mode_pages.rigid_disk_page[
4007			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4008			       sizeof(rigid_disk_page_changeable));
4009
4010			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4011				CTL_DEFAULT_HEADS;
4012
4013			/*
4014			 * The divide method here will be more accurate,
4015			 * probably, but results in floating point being
4016			 * used in the kernel on i386 (__udivdi3()).  On the
4017			 * XScale, though, __udivdi3() is implemented in
4018			 * software.
4019			 *
4020			 * The shift method for cylinder calculation is
4021			 * accurate if sectors_per_cylinder is a power of
4022			 * 2.  Otherwise it might be slightly off -- you
4023			 * might have a bit of a truncation problem.
4024			 */
4025#ifdef	__XSCALE__
4026			cylinders = (lun->be_lun->maxlba + 1) /
4027				sectors_per_cylinder;
4028#else
4029			for (shift = 31; shift > 0; shift--) {
4030				if (sectors_per_cylinder & (1 << shift))
4031					break;
4032			}
4033			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4034#endif
4035
4036			/*
4037			 * We've basically got 3 bytes, or 24 bits for the
4038			 * cylinder size in the mode page.  If we're over,
4039			 * just round down to 2^24.
4040			 */
4041			if (cylinders > 0xffffff)
4042				cylinders = 0xffffff;
4043
4044			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4045				CTL_PAGE_DEFAULT];
4046			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4047
4048			if ((value = ctl_get_opt(&lun->be_lun->options,
4049			    "rpm")) != NULL) {
4050				scsi_ulto2b(strtol(value, NULL, 0),
4051				     rigid_disk_page->rotation_rate);
4052			}
4053
4054			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4055			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4056			       sizeof(rigid_disk_page_default));
4057			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4058			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4059			       sizeof(rigid_disk_page_default));
4060
4061			page_index->page_data =
4062				(uint8_t *)lun->mode_pages.rigid_disk_page;
4063			break;
4064		}
4065		case SMS_CACHING_PAGE: {
4066			struct scsi_caching_page *caching_page;
4067
4068			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4069				panic("invalid subpage value %d",
4070				      page_index->subpage);
4071			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4072			       &caching_page_default,
4073			       sizeof(caching_page_default));
4074			memcpy(&lun->mode_pages.caching_page[
4075			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4076			       sizeof(caching_page_changeable));
4077			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4078			       &caching_page_default,
4079			       sizeof(caching_page_default));
4080			caching_page = &lun->mode_pages.caching_page[
4081			    CTL_PAGE_SAVED];
4082			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4083			if (value != NULL && strcmp(value, "off") == 0)
4084				caching_page->flags1 &= ~SCP_WCE;
4085			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4086			if (value != NULL && strcmp(value, "off") == 0)
4087				caching_page->flags1 |= SCP_RCD;
4088			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4089			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4090			       sizeof(caching_page_default));
4091			page_index->page_data =
4092				(uint8_t *)lun->mode_pages.caching_page;
4093			break;
4094		}
4095		case SMS_CONTROL_MODE_PAGE: {
4096			struct scsi_control_page *control_page;
4097
4098			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4099				panic("invalid subpage value %d",
4100				      page_index->subpage);
4101
4102			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4103			       &control_page_default,
4104			       sizeof(control_page_default));
4105			memcpy(&lun->mode_pages.control_page[
4106			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4107			       sizeof(control_page_changeable));
4108			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4109			       &control_page_default,
4110			       sizeof(control_page_default));
4111			control_page = &lun->mode_pages.control_page[
4112			    CTL_PAGE_SAVED];
4113			value = ctl_get_opt(&lun->be_lun->options, "reordering");
4114			if (value != NULL && strcmp(value, "unrestricted") == 0) {
4115				control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4116				control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4117			}
4118			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4119			       &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4120			       sizeof(control_page_default));
4121			page_index->page_data =
4122				(uint8_t *)lun->mode_pages.control_page;
4123			break;
4124
4125		}
4126		case SMS_INFO_EXCEPTIONS_PAGE: {
4127			switch (page_index->subpage) {
4128			case SMS_SUBPAGE_PAGE_0:
4129				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4130				       &ie_page_default,
4131				       sizeof(ie_page_default));
4132				memcpy(&lun->mode_pages.ie_page[
4133				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4134				       sizeof(ie_page_changeable));
4135				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4136				       &ie_page_default,
4137				       sizeof(ie_page_default));
4138				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4139				       &ie_page_default,
4140				       sizeof(ie_page_default));
4141				page_index->page_data =
4142					(uint8_t *)lun->mode_pages.ie_page;
4143				break;
4144			case 0x02: {
4145				struct ctl_logical_block_provisioning_page *page;
4146
4147				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4148				       &lbp_page_default,
4149				       sizeof(lbp_page_default));
4150				memcpy(&lun->mode_pages.lbp_page[
4151				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4152				       sizeof(lbp_page_changeable));
4153				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4154				       &lbp_page_default,
4155				       sizeof(lbp_page_default));
4156				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4157				value = ctl_get_opt(&lun->be_lun->options,
4158				    "avail-threshold");
4159				if (value != NULL &&
4160				    ctl_expand_number(value, &ival) == 0) {
4161					page->descr[0].flags |= SLBPPD_ENABLED |
4162					    SLBPPD_ARMING_DEC;
4163					if (lun->be_lun->blocksize)
4164						ival /= lun->be_lun->blocksize;
4165					else
4166						ival /= 512;
4167					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4168					    page->descr[0].count);
4169				}
4170				value = ctl_get_opt(&lun->be_lun->options,
4171				    "used-threshold");
4172				if (value != NULL &&
4173				    ctl_expand_number(value, &ival) == 0) {
4174					page->descr[1].flags |= SLBPPD_ENABLED |
4175					    SLBPPD_ARMING_INC;
4176					if (lun->be_lun->blocksize)
4177						ival /= lun->be_lun->blocksize;
4178					else
4179						ival /= 512;
4180					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4181					    page->descr[1].count);
4182				}
4183				value = ctl_get_opt(&lun->be_lun->options,
4184				    "pool-avail-threshold");
4185				if (value != NULL &&
4186				    ctl_expand_number(value, &ival) == 0) {
4187					page->descr[2].flags |= SLBPPD_ENABLED |
4188					    SLBPPD_ARMING_DEC;
4189					if (lun->be_lun->blocksize)
4190						ival /= lun->be_lun->blocksize;
4191					else
4192						ival /= 512;
4193					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4194					    page->descr[2].count);
4195				}
4196				value = ctl_get_opt(&lun->be_lun->options,
4197				    "pool-used-threshold");
4198				if (value != NULL &&
4199				    ctl_expand_number(value, &ival) == 0) {
4200					page->descr[3].flags |= SLBPPD_ENABLED |
4201					    SLBPPD_ARMING_INC;
4202					if (lun->be_lun->blocksize)
4203						ival /= lun->be_lun->blocksize;
4204					else
4205						ival /= 512;
4206					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4207					    page->descr[3].count);
4208				}
4209				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4210				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4211				       sizeof(lbp_page_default));
4212				page_index->page_data =
4213					(uint8_t *)lun->mode_pages.lbp_page;
4214			}}
4215			break;
4216		}
4217		case SMS_VENDOR_SPECIFIC_PAGE:{
4218			switch (page_index->subpage) {
4219			case DBGCNF_SUBPAGE_CODE: {
4220				struct copan_debugconf_subpage *current_page,
4221							       *saved_page;
4222
4223				memcpy(&lun->mode_pages.debugconf_subpage[
4224				       CTL_PAGE_CURRENT],
4225				       &debugconf_page_default,
4226				       sizeof(debugconf_page_default));
4227				memcpy(&lun->mode_pages.debugconf_subpage[
4228				       CTL_PAGE_CHANGEABLE],
4229				       &debugconf_page_changeable,
4230				       sizeof(debugconf_page_changeable));
4231				memcpy(&lun->mode_pages.debugconf_subpage[
4232				       CTL_PAGE_DEFAULT],
4233				       &debugconf_page_default,
4234				       sizeof(debugconf_page_default));
4235				memcpy(&lun->mode_pages.debugconf_subpage[
4236				       CTL_PAGE_SAVED],
4237				       &debugconf_page_default,
4238				       sizeof(debugconf_page_default));
4239				page_index->page_data =
4240					(uint8_t *)lun->mode_pages.debugconf_subpage;
4241
4242				current_page = (struct copan_debugconf_subpage *)
4243					(page_index->page_data +
4244					 (page_index->page_len *
4245					  CTL_PAGE_CURRENT));
4246				saved_page = (struct copan_debugconf_subpage *)
4247					(page_index->page_data +
4248					 (page_index->page_len *
4249					  CTL_PAGE_SAVED));
4250				break;
4251			}
4252			default:
4253				panic("invalid subpage value %d",
4254				      page_index->subpage);
4255				break;
4256			}
4257   			break;
4258		}
4259		default:
4260			panic("invalid page value %d",
4261			      page_index->page_code & SMPH_PC_MASK);
4262			break;
4263    	}
4264	}
4265
4266	return (CTL_RETVAL_COMPLETE);
4267}
4268
4269static int
4270ctl_init_log_page_index(struct ctl_lun *lun)
4271{
4272	struct ctl_page_index *page_index;
4273	int i, j, k, prev;
4274
4275	memcpy(&lun->log_pages.index, log_page_index_template,
4276	       sizeof(log_page_index_template));
4277
4278	prev = -1;
4279	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4280
4281		page_index = &lun->log_pages.index[i];
4282		/*
4283		 * If this is a disk-only mode page, there's no point in
4284		 * setting it up.  For some pages, we have to have some
4285		 * basic information about the disk in order to calculate the
4286		 * mode page data.
4287		 */
4288		if ((lun->be_lun->lun_type != T_DIRECT)
4289		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4290			continue;
4291
4292		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4293		    ((lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) == 0 ||
4294		     lun->backend->lun_attr == NULL))
4295			continue;
4296
4297		if (page_index->page_code != prev) {
4298			lun->log_pages.pages_page[j] = page_index->page_code;
4299			prev = page_index->page_code;
4300			j++;
4301		}
4302		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4303		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4304		k++;
4305	}
4306	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4307	lun->log_pages.index[0].page_len = j;
4308	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4309	lun->log_pages.index[1].page_len = k * 2;
4310	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4311	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4312
4313	return (CTL_RETVAL_COMPLETE);
4314}
4315
4316static int
4317hex2bin(const char *str, uint8_t *buf, int buf_size)
4318{
4319	int i;
4320	u_char c;
4321
4322	memset(buf, 0, buf_size);
4323	while (isspace(str[0]))
4324		str++;
4325	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4326		str += 2;
4327	buf_size *= 2;
4328	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4329		c = str[i];
4330		if (isdigit(c))
4331			c -= '0';
4332		else if (isalpha(c))
4333			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4334		else
4335			break;
4336		if (c >= 16)
4337			break;
4338		if ((i & 1) == 0)
4339			buf[i / 2] |= (c << 4);
4340		else
4341			buf[i / 2] |= c;
4342	}
4343	return ((i + 1) / 2);
4344}
4345
4346/*
4347 * LUN allocation.
4348 *
4349 * Requirements:
4350 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4351 *   wants us to allocate the LUN and he can block.
4352 * - ctl_softc is always set
4353 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4354 *
4355 * Returns 0 for success, non-zero (errno) for failure.
4356 */
4357static int
4358ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4359	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4360{
4361	struct ctl_lun *nlun, *lun;
4362	struct ctl_port *port;
4363	struct scsi_vpd_id_descriptor *desc;
4364	struct scsi_vpd_id_t10 *t10id;
4365	const char *eui, *naa, *scsiname, *vendor, *value;
4366	int lun_number, i, lun_malloced;
4367	int devidlen, idlen1, idlen2 = 0, len;
4368
4369	if (be_lun == NULL)
4370		return (EINVAL);
4371
4372	/*
4373	 * We currently only support Direct Access or Processor LUN types.
4374	 */
4375	switch (be_lun->lun_type) {
4376	case T_DIRECT:
4377		break;
4378	case T_PROCESSOR:
4379		break;
4380	case T_SEQUENTIAL:
4381	case T_CHANGER:
4382	default:
4383		be_lun->lun_config_status(be_lun->be_lun,
4384					  CTL_LUN_CONFIG_FAILURE);
4385		break;
4386	}
4387	if (ctl_lun == NULL) {
4388		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4389		lun_malloced = 1;
4390	} else {
4391		lun_malloced = 0;
4392		lun = ctl_lun;
4393	}
4394
4395	memset(lun, 0, sizeof(*lun));
4396	if (lun_malloced)
4397		lun->flags = CTL_LUN_MALLOCED;
4398
4399	/* Generate LUN ID. */
4400	devidlen = max(CTL_DEVID_MIN_LEN,
4401	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4402	idlen1 = sizeof(*t10id) + devidlen;
4403	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4404	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4405	if (scsiname != NULL) {
4406		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4407		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4408	}
4409	eui = ctl_get_opt(&be_lun->options, "eui");
4410	if (eui != NULL) {
4411		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4412	}
4413	naa = ctl_get_opt(&be_lun->options, "naa");
4414	if (naa != NULL) {
4415		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4416	}
4417	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4418	    M_CTL, M_WAITOK | M_ZERO);
4419	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4420	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4421	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4422	desc->length = idlen1;
4423	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4424	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4425	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4426		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4427	} else {
4428		strncpy(t10id->vendor, vendor,
4429		    min(sizeof(t10id->vendor), strlen(vendor)));
4430	}
4431	strncpy((char *)t10id->vendor_spec_id,
4432	    (char *)be_lun->device_id, devidlen);
4433	if (scsiname != NULL) {
4434		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4435		    desc->length);
4436		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4437		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4438		    SVPD_ID_TYPE_SCSI_NAME;
4439		desc->length = idlen2;
4440		strlcpy(desc->identifier, scsiname, idlen2);
4441	}
4442	if (eui != NULL) {
4443		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4444		    desc->length);
4445		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4446		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4447		    SVPD_ID_TYPE_EUI64;
4448		desc->length = hex2bin(eui, desc->identifier, 16);
4449		desc->length = desc->length > 12 ? 16 :
4450		    (desc->length > 8 ? 12 : 8);
4451		len -= 16 - desc->length;
4452	}
4453	if (naa != NULL) {
4454		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4455		    desc->length);
4456		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4457		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4458		    SVPD_ID_TYPE_NAA;
4459		desc->length = hex2bin(naa, desc->identifier, 16);
4460		desc->length = desc->length > 8 ? 16 : 8;
4461		len -= 16 - desc->length;
4462	}
4463	lun->lun_devid->len = len;
4464
4465	mtx_lock(&ctl_softc->ctl_lock);
4466	/*
4467	 * See if the caller requested a particular LUN number.  If so, see
4468	 * if it is available.  Otherwise, allocate the first available LUN.
4469	 */
4470	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4471		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4472		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4473			mtx_unlock(&ctl_softc->ctl_lock);
4474			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4475				printf("ctl: requested LUN ID %d is higher "
4476				       "than CTL_MAX_LUNS - 1 (%d)\n",
4477				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4478			} else {
4479				/*
4480				 * XXX KDM return an error, or just assign
4481				 * another LUN ID in this case??
4482				 */
4483				printf("ctl: requested LUN ID %d is already "
4484				       "in use\n", be_lun->req_lun_id);
4485			}
4486			if (lun->flags & CTL_LUN_MALLOCED)
4487				free(lun, M_CTL);
4488			be_lun->lun_config_status(be_lun->be_lun,
4489						  CTL_LUN_CONFIG_FAILURE);
4490			return (ENOSPC);
4491		}
4492		lun_number = be_lun->req_lun_id;
4493	} else {
4494		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4495		if (lun_number == -1) {
4496			mtx_unlock(&ctl_softc->ctl_lock);
4497			printf("ctl: can't allocate LUN on target %ju, out of "
4498			       "LUNs\n", (uintmax_t)target_id.id);
4499			if (lun->flags & CTL_LUN_MALLOCED)
4500				free(lun, M_CTL);
4501			be_lun->lun_config_status(be_lun->be_lun,
4502						  CTL_LUN_CONFIG_FAILURE);
4503			return (ENOSPC);
4504		}
4505	}
4506	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4507
4508	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4509	lun->target = target_id;
4510	lun->lun = lun_number;
4511	lun->be_lun = be_lun;
4512	/*
4513	 * The processor LUN is always enabled.  Disk LUNs come on line
4514	 * disabled, and must be enabled by the backend.
4515	 */
4516	lun->flags |= CTL_LUN_DISABLED;
4517	lun->backend = be_lun->be;
4518	be_lun->ctl_lun = lun;
4519	be_lun->lun_id = lun_number;
4520	atomic_add_int(&be_lun->be->num_luns, 1);
4521	if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4522		lun->flags |= CTL_LUN_OFFLINE;
4523
4524	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4525		lun->flags |= CTL_LUN_STOPPED;
4526
4527	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4528		lun->flags |= CTL_LUN_INOPERABLE;
4529
4530	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4531		lun->flags |= CTL_LUN_PRIMARY_SC;
4532
4533	value = ctl_get_opt(&be_lun->options, "readonly");
4534	if (value != NULL && strcmp(value, "on") == 0)
4535		lun->flags |= CTL_LUN_READONLY;
4536
4537	lun->ctl_softc = ctl_softc;
4538	TAILQ_INIT(&lun->ooa_queue);
4539	TAILQ_INIT(&lun->blocked_queue);
4540	STAILQ_INIT(&lun->error_list);
4541	ctl_tpc_lun_init(lun);
4542
4543	/*
4544	 * Initialize the mode and log page index.
4545	 */
4546	ctl_init_page_index(lun);
4547	ctl_init_log_page_index(lun);
4548
4549	/*
4550	 * Set the poweron UA for all initiators on this LUN only.
4551	 */
4552	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4553		lun->pending_ua[i] = CTL_UA_POWERON;
4554
4555	/*
4556	 * Now, before we insert this lun on the lun list, set the lun
4557	 * inventory changed UA for all other luns.
4558	 */
4559	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4560		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4561			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4562		}
4563	}
4564
4565	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4566
4567	ctl_softc->ctl_luns[lun_number] = lun;
4568
4569	ctl_softc->num_luns++;
4570
4571	/* Setup statistics gathering */
4572	lun->stats.device_type = be_lun->lun_type;
4573	lun->stats.lun_number = lun_number;
4574	if (lun->stats.device_type == T_DIRECT)
4575		lun->stats.blocksize = be_lun->blocksize;
4576	else
4577		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4578	for (i = 0;i < CTL_MAX_PORTS;i++)
4579		lun->stats.ports[i].targ_port = i;
4580
4581	mtx_unlock(&ctl_softc->ctl_lock);
4582
4583	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4584
4585	/*
4586	 * Run through each registered FETD and bring it online if it isn't
4587	 * already.  Enable the target ID if it hasn't been enabled, and
4588	 * enable this particular LUN.
4589	 */
4590	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4591		int retval;
4592
4593		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4594		if (retval != 0) {
4595			printf("ctl_alloc_lun: FETD %s port %d returned error "
4596			       "%d for lun_enable on target %ju lun %d\n",
4597			       port->port_name, port->targ_port, retval,
4598			       (uintmax_t)target_id.id, lun_number);
4599		} else
4600			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4601	}
4602	return (0);
4603}
4604
4605/*
4606 * Delete a LUN.
4607 * Assumptions:
4608 * - LUN has already been marked invalid and any pending I/O has been taken
4609 *   care of.
4610 */
4611static int
4612ctl_free_lun(struct ctl_lun *lun)
4613{
4614	struct ctl_softc *softc;
4615#if 0
4616	struct ctl_port *port;
4617#endif
4618	struct ctl_lun *nlun;
4619	int i;
4620
4621	softc = lun->ctl_softc;
4622
4623	mtx_assert(&softc->ctl_lock, MA_OWNED);
4624
4625	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4626
4627	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4628
4629	softc->ctl_luns[lun->lun] = NULL;
4630
4631	if (!TAILQ_EMPTY(&lun->ooa_queue))
4632		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4633
4634	softc->num_luns--;
4635
4636	/*
4637	 * XXX KDM this scheme only works for a single target/multiple LUN
4638	 * setup.  It needs to be revamped for a multiple target scheme.
4639	 *
4640	 * XXX KDM this results in port->lun_disable() getting called twice,
4641	 * once when ctl_disable_lun() is called, and a second time here.
4642	 * We really need to re-think the LUN disable semantics.  There
4643	 * should probably be several steps/levels to LUN removal:
4644	 *  - disable
4645	 *  - invalidate
4646	 *  - free
4647 	 *
4648	 * Right now we only have a disable method when communicating to
4649	 * the front end ports, at least for individual LUNs.
4650	 */
4651#if 0
4652	STAILQ_FOREACH(port, &softc->port_list, links) {
4653		int retval;
4654
4655		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4656					 lun->lun);
4657		if (retval != 0) {
4658			printf("ctl_free_lun: FETD %s port %d returned error "
4659			       "%d for lun_disable on target %ju lun %jd\n",
4660			       port->port_name, port->targ_port, retval,
4661			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4662		}
4663
4664		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4665			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4666
4667			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4668			if (retval != 0) {
4669				printf("ctl_free_lun: FETD %s port %d "
4670				       "returned error %d for targ_disable on "
4671				       "target %ju\n", port->port_name,
4672				       port->targ_port, retval,
4673				       (uintmax_t)lun->target.id);
4674			} else
4675				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4676
4677			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4678				continue;
4679
4680#if 0
4681			port->port_offline(port->onoff_arg);
4682			port->status &= ~CTL_PORT_STATUS_ONLINE;
4683#endif
4684		}
4685	}
4686#endif
4687
4688	/*
4689	 * Tell the backend to free resources, if this LUN has a backend.
4690	 */
4691	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4692	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4693
4694	ctl_tpc_lun_shutdown(lun);
4695	mtx_destroy(&lun->lun_lock);
4696	free(lun->lun_devid, M_CTL);
4697	for (i = 0; i < 2 * CTL_MAX_PORTS; i++) {
4698		if (lun->pr_keys[i] != NULL)
4699			free(lun->pr_keys[i], M_CTL);
4700	}
4701	free(lun->write_buffer, M_CTL);
4702	if (lun->flags & CTL_LUN_MALLOCED)
4703		free(lun, M_CTL);
4704
4705	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4706		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4707			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4708		}
4709	}
4710
4711	return (0);
4712}
4713
4714static void
4715ctl_create_lun(struct ctl_be_lun *be_lun)
4716{
4717	struct ctl_softc *ctl_softc;
4718
4719	ctl_softc = control_softc;
4720
4721	/*
4722	 * ctl_alloc_lun() should handle all potential failure cases.
4723	 */
4724	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4725}
4726
4727int
4728ctl_add_lun(struct ctl_be_lun *be_lun)
4729{
4730	struct ctl_softc *ctl_softc = control_softc;
4731
4732	mtx_lock(&ctl_softc->ctl_lock);
4733	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4734	mtx_unlock(&ctl_softc->ctl_lock);
4735	wakeup(&ctl_softc->pending_lun_queue);
4736
4737	return (0);
4738}
4739
4740int
4741ctl_enable_lun(struct ctl_be_lun *be_lun)
4742{
4743	struct ctl_softc *ctl_softc;
4744	struct ctl_port *port, *nport;
4745	struct ctl_lun *lun;
4746	int retval;
4747
4748	ctl_softc = control_softc;
4749
4750	lun = (struct ctl_lun *)be_lun->ctl_lun;
4751
4752	mtx_lock(&ctl_softc->ctl_lock);
4753	mtx_lock(&lun->lun_lock);
4754	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4755		/*
4756		 * eh?  Why did we get called if the LUN is already
4757		 * enabled?
4758		 */
4759		mtx_unlock(&lun->lun_lock);
4760		mtx_unlock(&ctl_softc->ctl_lock);
4761		return (0);
4762	}
4763	lun->flags &= ~CTL_LUN_DISABLED;
4764	mtx_unlock(&lun->lun_lock);
4765
4766	for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4767		nport = STAILQ_NEXT(port, links);
4768
4769		/*
4770		 * Drop the lock while we call the FETD's enable routine.
4771		 * This can lead to a callback into CTL (at least in the
4772		 * case of the internal initiator frontend.
4773		 */
4774		mtx_unlock(&ctl_softc->ctl_lock);
4775		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4776		mtx_lock(&ctl_softc->ctl_lock);
4777		if (retval != 0) {
4778			printf("%s: FETD %s port %d returned error "
4779			       "%d for lun_enable on target %ju lun %jd\n",
4780			       __func__, port->port_name, port->targ_port, retval,
4781			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4782		}
4783#if 0
4784		 else {
4785            /* NOTE:  TODO:  why does lun enable affect port status? */
4786			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4787		}
4788#endif
4789	}
4790
4791	mtx_unlock(&ctl_softc->ctl_lock);
4792
4793	return (0);
4794}
4795
4796int
4797ctl_disable_lun(struct ctl_be_lun *be_lun)
4798{
4799	struct ctl_softc *ctl_softc;
4800	struct ctl_port *port;
4801	struct ctl_lun *lun;
4802	int retval;
4803
4804	ctl_softc = control_softc;
4805
4806	lun = (struct ctl_lun *)be_lun->ctl_lun;
4807
4808	mtx_lock(&ctl_softc->ctl_lock);
4809	mtx_lock(&lun->lun_lock);
4810	if (lun->flags & CTL_LUN_DISABLED) {
4811		mtx_unlock(&lun->lun_lock);
4812		mtx_unlock(&ctl_softc->ctl_lock);
4813		return (0);
4814	}
4815	lun->flags |= CTL_LUN_DISABLED;
4816	mtx_unlock(&lun->lun_lock);
4817
4818	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4819		mtx_unlock(&ctl_softc->ctl_lock);
4820		/*
4821		 * Drop the lock before we call the frontend's disable
4822		 * routine, to avoid lock order reversals.
4823		 *
4824		 * XXX KDM what happens if the frontend list changes while
4825		 * we're traversing it?  It's unlikely, but should be handled.
4826		 */
4827		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4828					 lun->lun);
4829		mtx_lock(&ctl_softc->ctl_lock);
4830		if (retval != 0) {
4831			printf("ctl_alloc_lun: FETD %s port %d returned error "
4832			       "%d for lun_disable on target %ju lun %jd\n",
4833			       port->port_name, port->targ_port, retval,
4834			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4835		}
4836	}
4837
4838	mtx_unlock(&ctl_softc->ctl_lock);
4839
4840	return (0);
4841}
4842
4843int
4844ctl_start_lun(struct ctl_be_lun *be_lun)
4845{
4846	struct ctl_softc *ctl_softc;
4847	struct ctl_lun *lun;
4848
4849	ctl_softc = control_softc;
4850
4851	lun = (struct ctl_lun *)be_lun->ctl_lun;
4852
4853	mtx_lock(&lun->lun_lock);
4854	lun->flags &= ~CTL_LUN_STOPPED;
4855	mtx_unlock(&lun->lun_lock);
4856
4857	return (0);
4858}
4859
4860int
4861ctl_stop_lun(struct ctl_be_lun *be_lun)
4862{
4863	struct ctl_softc *ctl_softc;
4864	struct ctl_lun *lun;
4865
4866	ctl_softc = control_softc;
4867
4868	lun = (struct ctl_lun *)be_lun->ctl_lun;
4869
4870	mtx_lock(&lun->lun_lock);
4871	lun->flags |= CTL_LUN_STOPPED;
4872	mtx_unlock(&lun->lun_lock);
4873
4874	return (0);
4875}
4876
4877int
4878ctl_lun_offline(struct ctl_be_lun *be_lun)
4879{
4880	struct ctl_softc *ctl_softc;
4881	struct ctl_lun *lun;
4882
4883	ctl_softc = control_softc;
4884
4885	lun = (struct ctl_lun *)be_lun->ctl_lun;
4886
4887	mtx_lock(&lun->lun_lock);
4888	lun->flags |= CTL_LUN_OFFLINE;
4889	mtx_unlock(&lun->lun_lock);
4890
4891	return (0);
4892}
4893
4894int
4895ctl_lun_online(struct ctl_be_lun *be_lun)
4896{
4897	struct ctl_softc *ctl_softc;
4898	struct ctl_lun *lun;
4899
4900	ctl_softc = control_softc;
4901
4902	lun = (struct ctl_lun *)be_lun->ctl_lun;
4903
4904	mtx_lock(&lun->lun_lock);
4905	lun->flags &= ~CTL_LUN_OFFLINE;
4906	mtx_unlock(&lun->lun_lock);
4907
4908	return (0);
4909}
4910
4911int
4912ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4913{
4914	struct ctl_softc *ctl_softc;
4915	struct ctl_lun *lun;
4916
4917	ctl_softc = control_softc;
4918
4919	lun = (struct ctl_lun *)be_lun->ctl_lun;
4920
4921	mtx_lock(&lun->lun_lock);
4922
4923	/*
4924	 * The LUN needs to be disabled before it can be marked invalid.
4925	 */
4926	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4927		mtx_unlock(&lun->lun_lock);
4928		return (-1);
4929	}
4930	/*
4931	 * Mark the LUN invalid.
4932	 */
4933	lun->flags |= CTL_LUN_INVALID;
4934
4935	/*
4936	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4937	 * If we have something in the OOA queue, we'll free it when the
4938	 * last I/O completes.
4939	 */
4940	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4941		mtx_unlock(&lun->lun_lock);
4942		mtx_lock(&ctl_softc->ctl_lock);
4943		ctl_free_lun(lun);
4944		mtx_unlock(&ctl_softc->ctl_lock);
4945	} else
4946		mtx_unlock(&lun->lun_lock);
4947
4948	return (0);
4949}
4950
4951int
4952ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4953{
4954	struct ctl_softc *ctl_softc;
4955	struct ctl_lun *lun;
4956
4957	ctl_softc = control_softc;
4958	lun = (struct ctl_lun *)be_lun->ctl_lun;
4959
4960	mtx_lock(&lun->lun_lock);
4961	lun->flags |= CTL_LUN_INOPERABLE;
4962	mtx_unlock(&lun->lun_lock);
4963
4964	return (0);
4965}
4966
4967int
4968ctl_lun_operable(struct ctl_be_lun *be_lun)
4969{
4970	struct ctl_softc *ctl_softc;
4971	struct ctl_lun *lun;
4972
4973	ctl_softc = control_softc;
4974	lun = (struct ctl_lun *)be_lun->ctl_lun;
4975
4976	mtx_lock(&lun->lun_lock);
4977	lun->flags &= ~CTL_LUN_INOPERABLE;
4978	mtx_unlock(&lun->lun_lock);
4979
4980	return (0);
4981}
4982
4983void
4984ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4985{
4986	struct ctl_lun *lun;
4987	struct ctl_softc *softc;
4988	int i;
4989
4990	softc = control_softc;
4991
4992	lun = (struct ctl_lun *)be_lun->ctl_lun;
4993
4994	mtx_lock(&lun->lun_lock);
4995
4996	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4997		lun->pending_ua[i] |= CTL_UA_CAPACITY_CHANGED;
4998
4999	mtx_unlock(&lun->lun_lock);
5000}
5001
5002/*
5003 * Backend "memory move is complete" callback for requests that never
5004 * make it down to say RAIDCore's configuration code.
5005 */
5006int
5007ctl_config_move_done(union ctl_io *io)
5008{
5009	int retval;
5010
5011	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5012	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5013	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5014
5015	if ((io->io_hdr.port_status != 0) &&
5016	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5017	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5018		/*
5019		 * For hardware error sense keys, the sense key
5020		 * specific value is defined to be a retry count,
5021		 * but we use it to pass back an internal FETD
5022		 * error code.  XXX KDM  Hopefully the FETD is only
5023		 * using 16 bits for an error code, since that's
5024		 * all the space we have in the sks field.
5025		 */
5026		ctl_set_internal_failure(&io->scsiio,
5027					 /*sks_valid*/ 1,
5028					 /*retry_count*/
5029					 io->io_hdr.port_status);
5030	}
5031
5032	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5033	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5034	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5035	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5036		/*
5037		 * XXX KDM just assuming a single pointer here, and not a
5038		 * S/G list.  If we start using S/G lists for config data,
5039		 * we'll need to know how to clean them up here as well.
5040		 */
5041		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5042			free(io->scsiio.kern_data_ptr, M_CTL);
5043		ctl_done(io);
5044		retval = CTL_RETVAL_COMPLETE;
5045	} else {
5046		/*
5047		 * XXX KDM now we need to continue data movement.  Some
5048		 * options:
5049		 * - call ctl_scsiio() again?  We don't do this for data
5050		 *   writes, because for those at least we know ahead of
5051		 *   time where the write will go and how long it is.  For
5052		 *   config writes, though, that information is largely
5053		 *   contained within the write itself, thus we need to
5054		 *   parse out the data again.
5055		 *
5056		 * - Call some other function once the data is in?
5057		 */
5058		if (ctl_debug & CTL_DEBUG_CDB_DATA)
5059			ctl_data_print(io);
5060
5061		/*
5062		 * XXX KDM call ctl_scsiio() again for now, and check flag
5063		 * bits to see whether we're allocated or not.
5064		 */
5065		retval = ctl_scsiio(&io->scsiio);
5066	}
5067	return (retval);
5068}
5069
5070/*
5071 * This gets called by a backend driver when it is done with a
5072 * data_submit method.
5073 */
5074void
5075ctl_data_submit_done(union ctl_io *io)
5076{
5077	/*
5078	 * If the IO_CONT flag is set, we need to call the supplied
5079	 * function to continue processing the I/O, instead of completing
5080	 * the I/O just yet.
5081	 *
5082	 * If there is an error, though, we don't want to keep processing.
5083	 * Instead, just send status back to the initiator.
5084	 */
5085	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5086	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5087	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5088	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5089		io->scsiio.io_cont(io);
5090		return;
5091	}
5092	ctl_done(io);
5093}
5094
5095/*
5096 * This gets called by a backend driver when it is done with a
5097 * configuration write.
5098 */
5099void
5100ctl_config_write_done(union ctl_io *io)
5101{
5102	uint8_t *buf;
5103
5104	/*
5105	 * If the IO_CONT flag is set, we need to call the supplied
5106	 * function to continue processing the I/O, instead of completing
5107	 * the I/O just yet.
5108	 *
5109	 * If there is an error, though, we don't want to keep processing.
5110	 * Instead, just send status back to the initiator.
5111	 */
5112	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5113	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5114	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5115	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5116		io->scsiio.io_cont(io);
5117		return;
5118	}
5119	/*
5120	 * Since a configuration write can be done for commands that actually
5121	 * have data allocated, like write buffer, and commands that have
5122	 * no data, like start/stop unit, we need to check here.
5123	 */
5124	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5125		buf = io->scsiio.kern_data_ptr;
5126	else
5127		buf = NULL;
5128	ctl_done(io);
5129	if (buf)
5130		free(buf, M_CTL);
5131}
5132
5133/*
5134 * SCSI release command.
5135 */
5136int
5137ctl_scsi_release(struct ctl_scsiio *ctsio)
5138{
5139	int length, longid, thirdparty_id, resv_id;
5140	struct ctl_softc *ctl_softc;
5141	struct ctl_lun *lun;
5142	uint32_t residx;
5143
5144	length = 0;
5145	resv_id = 0;
5146
5147	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5148
5149	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5150	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5151	ctl_softc = control_softc;
5152
5153	switch (ctsio->cdb[0]) {
5154	case RELEASE_10: {
5155		struct scsi_release_10 *cdb;
5156
5157		cdb = (struct scsi_release_10 *)ctsio->cdb;
5158
5159		if (cdb->byte2 & SR10_LONGID)
5160			longid = 1;
5161		else
5162			thirdparty_id = cdb->thirdparty_id;
5163
5164		resv_id = cdb->resv_id;
5165		length = scsi_2btoul(cdb->length);
5166		break;
5167	}
5168	}
5169
5170
5171	/*
5172	 * XXX KDM right now, we only support LUN reservation.  We don't
5173	 * support 3rd party reservations, or extent reservations, which
5174	 * might actually need the parameter list.  If we've gotten this
5175	 * far, we've got a LUN reservation.  Anything else got kicked out
5176	 * above.  So, according to SPC, ignore the length.
5177	 */
5178	length = 0;
5179
5180	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5181	 && (length > 0)) {
5182		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5183		ctsio->kern_data_len = length;
5184		ctsio->kern_total_len = length;
5185		ctsio->kern_data_resid = 0;
5186		ctsio->kern_rel_offset = 0;
5187		ctsio->kern_sg_entries = 0;
5188		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5189		ctsio->be_move_done = ctl_config_move_done;
5190		ctl_datamove((union ctl_io *)ctsio);
5191
5192		return (CTL_RETVAL_COMPLETE);
5193	}
5194
5195	if (length > 0)
5196		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5197
5198	mtx_lock(&lun->lun_lock);
5199
5200	/*
5201	 * According to SPC, it is not an error for an intiator to attempt
5202	 * to release a reservation on a LUN that isn't reserved, or that
5203	 * is reserved by another initiator.  The reservation can only be
5204	 * released, though, by the initiator who made it or by one of
5205	 * several reset type events.
5206	 */
5207	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5208			lun->flags &= ~CTL_LUN_RESERVED;
5209
5210	mtx_unlock(&lun->lun_lock);
5211
5212	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5213		free(ctsio->kern_data_ptr, M_CTL);
5214		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5215	}
5216
5217	ctl_set_success(ctsio);
5218	ctl_done((union ctl_io *)ctsio);
5219	return (CTL_RETVAL_COMPLETE);
5220}
5221
5222int
5223ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5224{
5225	int extent, thirdparty, longid;
5226	int resv_id, length;
5227	uint64_t thirdparty_id;
5228	struct ctl_softc *ctl_softc;
5229	struct ctl_lun *lun;
5230	uint32_t residx;
5231
5232	extent = 0;
5233	thirdparty = 0;
5234	longid = 0;
5235	resv_id = 0;
5236	length = 0;
5237	thirdparty_id = 0;
5238
5239	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5240
5241	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5242	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5243	ctl_softc = control_softc;
5244
5245	switch (ctsio->cdb[0]) {
5246	case RESERVE_10: {
5247		struct scsi_reserve_10 *cdb;
5248
5249		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5250
5251		if (cdb->byte2 & SR10_LONGID)
5252			longid = 1;
5253		else
5254			thirdparty_id = cdb->thirdparty_id;
5255
5256		resv_id = cdb->resv_id;
5257		length = scsi_2btoul(cdb->length);
5258		break;
5259	}
5260	}
5261
5262	/*
5263	 * XXX KDM right now, we only support LUN reservation.  We don't
5264	 * support 3rd party reservations, or extent reservations, which
5265	 * might actually need the parameter list.  If we've gotten this
5266	 * far, we've got a LUN reservation.  Anything else got kicked out
5267	 * above.  So, according to SPC, ignore the length.
5268	 */
5269	length = 0;
5270
5271	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5272	 && (length > 0)) {
5273		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5274		ctsio->kern_data_len = length;
5275		ctsio->kern_total_len = length;
5276		ctsio->kern_data_resid = 0;
5277		ctsio->kern_rel_offset = 0;
5278		ctsio->kern_sg_entries = 0;
5279		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5280		ctsio->be_move_done = ctl_config_move_done;
5281		ctl_datamove((union ctl_io *)ctsio);
5282
5283		return (CTL_RETVAL_COMPLETE);
5284	}
5285
5286	if (length > 0)
5287		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5288
5289	mtx_lock(&lun->lun_lock);
5290	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5291		ctl_set_reservation_conflict(ctsio);
5292		goto bailout;
5293	}
5294
5295	lun->flags |= CTL_LUN_RESERVED;
5296	lun->res_idx = residx;
5297
5298	ctl_set_success(ctsio);
5299
5300bailout:
5301	mtx_unlock(&lun->lun_lock);
5302
5303	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5304		free(ctsio->kern_data_ptr, M_CTL);
5305		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5306	}
5307
5308	ctl_done((union ctl_io *)ctsio);
5309	return (CTL_RETVAL_COMPLETE);
5310}
5311
5312int
5313ctl_start_stop(struct ctl_scsiio *ctsio)
5314{
5315	struct scsi_start_stop_unit *cdb;
5316	struct ctl_lun *lun;
5317	struct ctl_softc *ctl_softc;
5318	int retval;
5319
5320	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5321
5322	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5323	ctl_softc = control_softc;
5324	retval = 0;
5325
5326	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5327
5328	/*
5329	 * XXX KDM
5330	 * We don't support the immediate bit on a stop unit.  In order to
5331	 * do that, we would need to code up a way to know that a stop is
5332	 * pending, and hold off any new commands until it completes, one
5333	 * way or another.  Then we could accept or reject those commands
5334	 * depending on its status.  We would almost need to do the reverse
5335	 * of what we do below for an immediate start -- return the copy of
5336	 * the ctl_io to the FETD with status to send to the host (and to
5337	 * free the copy!) and then free the original I/O once the stop
5338	 * actually completes.  That way, the OOA queue mechanism can work
5339	 * to block commands that shouldn't proceed.  Another alternative
5340	 * would be to put the copy in the queue in place of the original,
5341	 * and return the original back to the caller.  That could be
5342	 * slightly safer..
5343	 */
5344	if ((cdb->byte2 & SSS_IMMED)
5345	 && ((cdb->how & SSS_START) == 0)) {
5346		ctl_set_invalid_field(ctsio,
5347				      /*sks_valid*/ 1,
5348				      /*command*/ 1,
5349				      /*field*/ 1,
5350				      /*bit_valid*/ 1,
5351				      /*bit*/ 0);
5352		ctl_done((union ctl_io *)ctsio);
5353		return (CTL_RETVAL_COMPLETE);
5354	}
5355
5356	if ((lun->flags & CTL_LUN_PR_RESERVED)
5357	 && ((cdb->how & SSS_START)==0)) {
5358		uint32_t residx;
5359
5360		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5361		if (ctl_get_prkey(lun, residx) == 0
5362		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5363
5364			ctl_set_reservation_conflict(ctsio);
5365			ctl_done((union ctl_io *)ctsio);
5366			return (CTL_RETVAL_COMPLETE);
5367		}
5368	}
5369
5370	/*
5371	 * If there is no backend on this device, we can't start or stop
5372	 * it.  In theory we shouldn't get any start/stop commands in the
5373	 * first place at this level if the LUN doesn't have a backend.
5374	 * That should get stopped by the command decode code.
5375	 */
5376	if (lun->backend == NULL) {
5377		ctl_set_invalid_opcode(ctsio);
5378		ctl_done((union ctl_io *)ctsio);
5379		return (CTL_RETVAL_COMPLETE);
5380	}
5381
5382	/*
5383	 * XXX KDM Copan-specific offline behavior.
5384	 * Figure out a reasonable way to port this?
5385	 */
5386#ifdef NEEDTOPORT
5387	mtx_lock(&lun->lun_lock);
5388
5389	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5390	 && (lun->flags & CTL_LUN_OFFLINE)) {
5391		/*
5392		 * If the LUN is offline, and the on/offline bit isn't set,
5393		 * reject the start or stop.  Otherwise, let it through.
5394		 */
5395		mtx_unlock(&lun->lun_lock);
5396		ctl_set_lun_not_ready(ctsio);
5397		ctl_done((union ctl_io *)ctsio);
5398	} else {
5399		mtx_unlock(&lun->lun_lock);
5400#endif /* NEEDTOPORT */
5401		/*
5402		 * This could be a start or a stop when we're online,
5403		 * or a stop/offline or start/online.  A start or stop when
5404		 * we're offline is covered in the case above.
5405		 */
5406		/*
5407		 * In the non-immediate case, we send the request to
5408		 * the backend and return status to the user when
5409		 * it is done.
5410		 *
5411		 * In the immediate case, we allocate a new ctl_io
5412		 * to hold a copy of the request, and send that to
5413		 * the backend.  We then set good status on the
5414		 * user's request and return it immediately.
5415		 */
5416		if (cdb->byte2 & SSS_IMMED) {
5417			union ctl_io *new_io;
5418
5419			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5420			ctl_copy_io((union ctl_io *)ctsio, new_io);
5421			retval = lun->backend->config_write(new_io);
5422			ctl_set_success(ctsio);
5423			ctl_done((union ctl_io *)ctsio);
5424		} else {
5425			retval = lun->backend->config_write(
5426				(union ctl_io *)ctsio);
5427		}
5428#ifdef NEEDTOPORT
5429	}
5430#endif
5431	return (retval);
5432}
5433
5434/*
5435 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5436 * we don't really do anything with the LBA and length fields if the user
5437 * passes them in.  Instead we'll just flush out the cache for the entire
5438 * LUN.
5439 */
5440int
5441ctl_sync_cache(struct ctl_scsiio *ctsio)
5442{
5443	struct ctl_lun *lun;
5444	struct ctl_softc *ctl_softc;
5445	uint64_t starting_lba;
5446	uint32_t block_count;
5447	int retval;
5448
5449	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5450
5451	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5452	ctl_softc = control_softc;
5453	retval = 0;
5454
5455	switch (ctsio->cdb[0]) {
5456	case SYNCHRONIZE_CACHE: {
5457		struct scsi_sync_cache *cdb;
5458		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5459
5460		starting_lba = scsi_4btoul(cdb->begin_lba);
5461		block_count = scsi_2btoul(cdb->lb_count);
5462		break;
5463	}
5464	case SYNCHRONIZE_CACHE_16: {
5465		struct scsi_sync_cache_16 *cdb;
5466		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5467
5468		starting_lba = scsi_8btou64(cdb->begin_lba);
5469		block_count = scsi_4btoul(cdb->lb_count);
5470		break;
5471	}
5472	default:
5473		ctl_set_invalid_opcode(ctsio);
5474		ctl_done((union ctl_io *)ctsio);
5475		goto bailout;
5476		break; /* NOTREACHED */
5477	}
5478
5479	/*
5480	 * We check the LBA and length, but don't do anything with them.
5481	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5482	 * get flushed.  This check will just help satisfy anyone who wants
5483	 * to see an error for an out of range LBA.
5484	 */
5485	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5486		ctl_set_lba_out_of_range(ctsio);
5487		ctl_done((union ctl_io *)ctsio);
5488		goto bailout;
5489	}
5490
5491	/*
5492	 * If this LUN has no backend, we can't flush the cache anyway.
5493	 */
5494	if (lun->backend == NULL) {
5495		ctl_set_invalid_opcode(ctsio);
5496		ctl_done((union ctl_io *)ctsio);
5497		goto bailout;
5498	}
5499
5500	/*
5501	 * Check to see whether we're configured to send the SYNCHRONIZE
5502	 * CACHE command directly to the back end.
5503	 */
5504	mtx_lock(&lun->lun_lock);
5505	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5506	 && (++(lun->sync_count) >= lun->sync_interval)) {
5507		lun->sync_count = 0;
5508		mtx_unlock(&lun->lun_lock);
5509		retval = lun->backend->config_write((union ctl_io *)ctsio);
5510	} else {
5511		mtx_unlock(&lun->lun_lock);
5512		ctl_set_success(ctsio);
5513		ctl_done((union ctl_io *)ctsio);
5514	}
5515
5516bailout:
5517
5518	return (retval);
5519}
5520
5521int
5522ctl_format(struct ctl_scsiio *ctsio)
5523{
5524	struct scsi_format *cdb;
5525	struct ctl_lun *lun;
5526	struct ctl_softc *ctl_softc;
5527	int length, defect_list_len;
5528
5529	CTL_DEBUG_PRINT(("ctl_format\n"));
5530
5531	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5532	ctl_softc = control_softc;
5533
5534	cdb = (struct scsi_format *)ctsio->cdb;
5535
5536	length = 0;
5537	if (cdb->byte2 & SF_FMTDATA) {
5538		if (cdb->byte2 & SF_LONGLIST)
5539			length = sizeof(struct scsi_format_header_long);
5540		else
5541			length = sizeof(struct scsi_format_header_short);
5542	}
5543
5544	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5545	 && (length > 0)) {
5546		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5547		ctsio->kern_data_len = length;
5548		ctsio->kern_total_len = length;
5549		ctsio->kern_data_resid = 0;
5550		ctsio->kern_rel_offset = 0;
5551		ctsio->kern_sg_entries = 0;
5552		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5553		ctsio->be_move_done = ctl_config_move_done;
5554		ctl_datamove((union ctl_io *)ctsio);
5555
5556		return (CTL_RETVAL_COMPLETE);
5557	}
5558
5559	defect_list_len = 0;
5560
5561	if (cdb->byte2 & SF_FMTDATA) {
5562		if (cdb->byte2 & SF_LONGLIST) {
5563			struct scsi_format_header_long *header;
5564
5565			header = (struct scsi_format_header_long *)
5566				ctsio->kern_data_ptr;
5567
5568			defect_list_len = scsi_4btoul(header->defect_list_len);
5569			if (defect_list_len != 0) {
5570				ctl_set_invalid_field(ctsio,
5571						      /*sks_valid*/ 1,
5572						      /*command*/ 0,
5573						      /*field*/ 2,
5574						      /*bit_valid*/ 0,
5575						      /*bit*/ 0);
5576				goto bailout;
5577			}
5578		} else {
5579			struct scsi_format_header_short *header;
5580
5581			header = (struct scsi_format_header_short *)
5582				ctsio->kern_data_ptr;
5583
5584			defect_list_len = scsi_2btoul(header->defect_list_len);
5585			if (defect_list_len != 0) {
5586				ctl_set_invalid_field(ctsio,
5587						      /*sks_valid*/ 1,
5588						      /*command*/ 0,
5589						      /*field*/ 2,
5590						      /*bit_valid*/ 0,
5591						      /*bit*/ 0);
5592				goto bailout;
5593			}
5594		}
5595	}
5596
5597	/*
5598	 * The format command will clear out the "Medium format corrupted"
5599	 * status if set by the configuration code.  That status is really
5600	 * just a way to notify the host that we have lost the media, and
5601	 * get them to issue a command that will basically make them think
5602	 * they're blowing away the media.
5603	 */
5604	mtx_lock(&lun->lun_lock);
5605	lun->flags &= ~CTL_LUN_INOPERABLE;
5606	mtx_unlock(&lun->lun_lock);
5607
5608	ctl_set_success(ctsio);
5609bailout:
5610
5611	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5612		free(ctsio->kern_data_ptr, M_CTL);
5613		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5614	}
5615
5616	ctl_done((union ctl_io *)ctsio);
5617	return (CTL_RETVAL_COMPLETE);
5618}
5619
5620int
5621ctl_read_buffer(struct ctl_scsiio *ctsio)
5622{
5623	struct scsi_read_buffer *cdb;
5624	struct ctl_lun *lun;
5625	int buffer_offset, len;
5626	static uint8_t descr[4];
5627	static uint8_t echo_descr[4] = { 0 };
5628
5629	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5630
5631	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5632	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5633
5634	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5635	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5636	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5637		ctl_set_invalid_field(ctsio,
5638				      /*sks_valid*/ 1,
5639				      /*command*/ 1,
5640				      /*field*/ 1,
5641				      /*bit_valid*/ 1,
5642				      /*bit*/ 4);
5643		ctl_done((union ctl_io *)ctsio);
5644		return (CTL_RETVAL_COMPLETE);
5645	}
5646
5647	len = scsi_3btoul(cdb->length);
5648	buffer_offset = scsi_3btoul(cdb->offset);
5649
5650	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5651		ctl_set_invalid_field(ctsio,
5652				      /*sks_valid*/ 1,
5653				      /*command*/ 1,
5654				      /*field*/ 6,
5655				      /*bit_valid*/ 0,
5656				      /*bit*/ 0);
5657		ctl_done((union ctl_io *)ctsio);
5658		return (CTL_RETVAL_COMPLETE);
5659	}
5660
5661	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5662		descr[0] = 0;
5663		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5664		ctsio->kern_data_ptr = descr;
5665		len = min(len, sizeof(descr));
5666	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5667		ctsio->kern_data_ptr = echo_descr;
5668		len = min(len, sizeof(echo_descr));
5669	} else {
5670		if (lun->write_buffer == NULL) {
5671			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5672			    M_CTL, M_WAITOK);
5673		}
5674		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5675	}
5676	ctsio->kern_data_len = len;
5677	ctsio->kern_total_len = len;
5678	ctsio->kern_data_resid = 0;
5679	ctsio->kern_rel_offset = 0;
5680	ctsio->kern_sg_entries = 0;
5681	ctl_set_success(ctsio);
5682	ctsio->be_move_done = ctl_config_move_done;
5683	ctl_datamove((union ctl_io *)ctsio);
5684	return (CTL_RETVAL_COMPLETE);
5685}
5686
5687int
5688ctl_write_buffer(struct ctl_scsiio *ctsio)
5689{
5690	struct scsi_write_buffer *cdb;
5691	struct ctl_lun *lun;
5692	int buffer_offset, len;
5693
5694	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5695
5696	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5697	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5698
5699	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5700		ctl_set_invalid_field(ctsio,
5701				      /*sks_valid*/ 1,
5702				      /*command*/ 1,
5703				      /*field*/ 1,
5704				      /*bit_valid*/ 1,
5705				      /*bit*/ 4);
5706		ctl_done((union ctl_io *)ctsio);
5707		return (CTL_RETVAL_COMPLETE);
5708	}
5709
5710	len = scsi_3btoul(cdb->length);
5711	buffer_offset = scsi_3btoul(cdb->offset);
5712
5713	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5714		ctl_set_invalid_field(ctsio,
5715				      /*sks_valid*/ 1,
5716				      /*command*/ 1,
5717				      /*field*/ 6,
5718				      /*bit_valid*/ 0,
5719				      /*bit*/ 0);
5720		ctl_done((union ctl_io *)ctsio);
5721		return (CTL_RETVAL_COMPLETE);
5722	}
5723
5724	/*
5725	 * If we've got a kernel request that hasn't been malloced yet,
5726	 * malloc it and tell the caller the data buffer is here.
5727	 */
5728	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5729		if (lun->write_buffer == NULL) {
5730			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5731			    M_CTL, M_WAITOK);
5732		}
5733		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5734		ctsio->kern_data_len = len;
5735		ctsio->kern_total_len = len;
5736		ctsio->kern_data_resid = 0;
5737		ctsio->kern_rel_offset = 0;
5738		ctsio->kern_sg_entries = 0;
5739		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5740		ctsio->be_move_done = ctl_config_move_done;
5741		ctl_datamove((union ctl_io *)ctsio);
5742
5743		return (CTL_RETVAL_COMPLETE);
5744	}
5745
5746	ctl_set_success(ctsio);
5747	ctl_done((union ctl_io *)ctsio);
5748	return (CTL_RETVAL_COMPLETE);
5749}
5750
5751int
5752ctl_write_same(struct ctl_scsiio *ctsio)
5753{
5754	struct ctl_lun *lun;
5755	struct ctl_lba_len_flags *lbalen;
5756	uint64_t lba;
5757	uint32_t num_blocks;
5758	int len, retval;
5759	uint8_t byte2;
5760
5761	retval = CTL_RETVAL_COMPLETE;
5762
5763	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5764
5765	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5766
5767	switch (ctsio->cdb[0]) {
5768	case WRITE_SAME_10: {
5769		struct scsi_write_same_10 *cdb;
5770
5771		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5772
5773		lba = scsi_4btoul(cdb->addr);
5774		num_blocks = scsi_2btoul(cdb->length);
5775		byte2 = cdb->byte2;
5776		break;
5777	}
5778	case WRITE_SAME_16: {
5779		struct scsi_write_same_16 *cdb;
5780
5781		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5782
5783		lba = scsi_8btou64(cdb->addr);
5784		num_blocks = scsi_4btoul(cdb->length);
5785		byte2 = cdb->byte2;
5786		break;
5787	}
5788	default:
5789		/*
5790		 * We got a command we don't support.  This shouldn't
5791		 * happen, commands should be filtered out above us.
5792		 */
5793		ctl_set_invalid_opcode(ctsio);
5794		ctl_done((union ctl_io *)ctsio);
5795
5796		return (CTL_RETVAL_COMPLETE);
5797		break; /* NOTREACHED */
5798	}
5799
5800	/* NDOB and ANCHOR flags can be used only together with UNMAP */
5801	if ((byte2 & SWS_UNMAP) == 0 &&
5802	    (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5803		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5804		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5805		ctl_done((union ctl_io *)ctsio);
5806		return (CTL_RETVAL_COMPLETE);
5807	}
5808
5809	/*
5810	 * The first check is to make sure we're in bounds, the second
5811	 * check is to catch wrap-around problems.  If the lba + num blocks
5812	 * is less than the lba, then we've wrapped around and the block
5813	 * range is invalid anyway.
5814	 */
5815	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5816	 || ((lba + num_blocks) < lba)) {
5817		ctl_set_lba_out_of_range(ctsio);
5818		ctl_done((union ctl_io *)ctsio);
5819		return (CTL_RETVAL_COMPLETE);
5820	}
5821
5822	/* Zero number of blocks means "to the last logical block" */
5823	if (num_blocks == 0) {
5824		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5825			ctl_set_invalid_field(ctsio,
5826					      /*sks_valid*/ 0,
5827					      /*command*/ 1,
5828					      /*field*/ 0,
5829					      /*bit_valid*/ 0,
5830					      /*bit*/ 0);
5831			ctl_done((union ctl_io *)ctsio);
5832			return (CTL_RETVAL_COMPLETE);
5833		}
5834		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5835	}
5836
5837	len = lun->be_lun->blocksize;
5838
5839	/*
5840	 * If we've got a kernel request that hasn't been malloced yet,
5841	 * malloc it and tell the caller the data buffer is here.
5842	 */
5843	if ((byte2 & SWS_NDOB) == 0 &&
5844	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5845		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5846		ctsio->kern_data_len = len;
5847		ctsio->kern_total_len = len;
5848		ctsio->kern_data_resid = 0;
5849		ctsio->kern_rel_offset = 0;
5850		ctsio->kern_sg_entries = 0;
5851		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5852		ctsio->be_move_done = ctl_config_move_done;
5853		ctl_datamove((union ctl_io *)ctsio);
5854
5855		return (CTL_RETVAL_COMPLETE);
5856	}
5857
5858	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5859	lbalen->lba = lba;
5860	lbalen->len = num_blocks;
5861	lbalen->flags = byte2;
5862	retval = lun->backend->config_write((union ctl_io *)ctsio);
5863
5864	return (retval);
5865}
5866
5867int
5868ctl_unmap(struct ctl_scsiio *ctsio)
5869{
5870	struct ctl_lun *lun;
5871	struct scsi_unmap *cdb;
5872	struct ctl_ptr_len_flags *ptrlen;
5873	struct scsi_unmap_header *hdr;
5874	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5875	uint64_t lba;
5876	uint32_t num_blocks;
5877	int len, retval;
5878	uint8_t byte2;
5879
5880	retval = CTL_RETVAL_COMPLETE;
5881
5882	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5883
5884	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5885	cdb = (struct scsi_unmap *)ctsio->cdb;
5886
5887	len = scsi_2btoul(cdb->length);
5888	byte2 = cdb->byte2;
5889
5890	/*
5891	 * If we've got a kernel request that hasn't been malloced yet,
5892	 * malloc it and tell the caller the data buffer is here.
5893	 */
5894	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5895		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5896		ctsio->kern_data_len = len;
5897		ctsio->kern_total_len = len;
5898		ctsio->kern_data_resid = 0;
5899		ctsio->kern_rel_offset = 0;
5900		ctsio->kern_sg_entries = 0;
5901		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5902		ctsio->be_move_done = ctl_config_move_done;
5903		ctl_datamove((union ctl_io *)ctsio);
5904
5905		return (CTL_RETVAL_COMPLETE);
5906	}
5907
5908	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5909	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5910	if (len < sizeof (*hdr) ||
5911	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5912	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5913	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5914		ctl_set_invalid_field(ctsio,
5915				      /*sks_valid*/ 0,
5916				      /*command*/ 0,
5917				      /*field*/ 0,
5918				      /*bit_valid*/ 0,
5919				      /*bit*/ 0);
5920		goto done;
5921	}
5922	len = scsi_2btoul(hdr->desc_length);
5923	buf = (struct scsi_unmap_desc *)(hdr + 1);
5924	end = buf + len / sizeof(*buf);
5925
5926	endnz = buf;
5927	for (range = buf; range < end; range++) {
5928		lba = scsi_8btou64(range->lba);
5929		num_blocks = scsi_4btoul(range->length);
5930		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5931		 || ((lba + num_blocks) < lba)) {
5932			ctl_set_lba_out_of_range(ctsio);
5933			ctl_done((union ctl_io *)ctsio);
5934			return (CTL_RETVAL_COMPLETE);
5935		}
5936		if (num_blocks != 0)
5937			endnz = range + 1;
5938	}
5939
5940	/*
5941	 * Block backend can not handle zero last range.
5942	 * Filter it out and return if there is nothing left.
5943	 */
5944	len = (uint8_t *)endnz - (uint8_t *)buf;
5945	if (len == 0) {
5946		ctl_set_success(ctsio);
5947		goto done;
5948	}
5949
5950	mtx_lock(&lun->lun_lock);
5951	ptrlen = (struct ctl_ptr_len_flags *)
5952	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5953	ptrlen->ptr = (void *)buf;
5954	ptrlen->len = len;
5955	ptrlen->flags = byte2;
5956	ctl_check_blocked(lun);
5957	mtx_unlock(&lun->lun_lock);
5958
5959	retval = lun->backend->config_write((union ctl_io *)ctsio);
5960	return (retval);
5961
5962done:
5963	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5964		free(ctsio->kern_data_ptr, M_CTL);
5965		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5966	}
5967	ctl_done((union ctl_io *)ctsio);
5968	return (CTL_RETVAL_COMPLETE);
5969}
5970
5971/*
5972 * Note that this function currently doesn't actually do anything inside
5973 * CTL to enforce things if the DQue bit is turned on.
5974 *
5975 * Also note that this function can't be used in the default case, because
5976 * the DQue bit isn't set in the changeable mask for the control mode page
5977 * anyway.  This is just here as an example for how to implement a page
5978 * handler, and a placeholder in case we want to allow the user to turn
5979 * tagged queueing on and off.
5980 *
5981 * The D_SENSE bit handling is functional, however, and will turn
5982 * descriptor sense on and off for a given LUN.
5983 */
5984int
5985ctl_control_page_handler(struct ctl_scsiio *ctsio,
5986			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5987{
5988	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5989	struct ctl_lun *lun;
5990	struct ctl_softc *softc;
5991	int set_ua;
5992	uint32_t initidx;
5993
5994	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5995	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5996	set_ua = 0;
5997
5998	user_cp = (struct scsi_control_page *)page_ptr;
5999	current_cp = (struct scsi_control_page *)
6000		(page_index->page_data + (page_index->page_len *
6001		CTL_PAGE_CURRENT));
6002	saved_cp = (struct scsi_control_page *)
6003		(page_index->page_data + (page_index->page_len *
6004		CTL_PAGE_SAVED));
6005
6006	softc = control_softc;
6007
6008	mtx_lock(&lun->lun_lock);
6009	if (((current_cp->rlec & SCP_DSENSE) == 0)
6010	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6011		/*
6012		 * Descriptor sense is currently turned off and the user
6013		 * wants to turn it on.
6014		 */
6015		current_cp->rlec |= SCP_DSENSE;
6016		saved_cp->rlec |= SCP_DSENSE;
6017		lun->flags |= CTL_LUN_SENSE_DESC;
6018		set_ua = 1;
6019	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6020		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6021		/*
6022		 * Descriptor sense is currently turned on, and the user
6023		 * wants to turn it off.
6024		 */
6025		current_cp->rlec &= ~SCP_DSENSE;
6026		saved_cp->rlec &= ~SCP_DSENSE;
6027		lun->flags &= ~CTL_LUN_SENSE_DESC;
6028		set_ua = 1;
6029	}
6030	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6031	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6032		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6033		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6034		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6035		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6036		set_ua = 1;
6037	}
6038	if ((current_cp->eca_and_aen & SCP_SWP) !=
6039	    (user_cp->eca_and_aen & SCP_SWP)) {
6040		current_cp->eca_and_aen &= ~SCP_SWP;
6041		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6042		saved_cp->eca_and_aen &= ~SCP_SWP;
6043		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6044		set_ua = 1;
6045	}
6046	if (set_ua != 0) {
6047		int i;
6048		/*
6049		 * Let other initiators know that the mode
6050		 * parameters for this LUN have changed.
6051		 */
6052		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6053			if (i == initidx)
6054				continue;
6055
6056			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6057		}
6058	}
6059	mtx_unlock(&lun->lun_lock);
6060
6061	return (0);
6062}
6063
6064int
6065ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6066		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6067{
6068	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6069	struct ctl_lun *lun;
6070	int set_ua;
6071	uint32_t initidx;
6072
6073	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6074	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6075	set_ua = 0;
6076
6077	user_cp = (struct scsi_caching_page *)page_ptr;
6078	current_cp = (struct scsi_caching_page *)
6079		(page_index->page_data + (page_index->page_len *
6080		CTL_PAGE_CURRENT));
6081	saved_cp = (struct scsi_caching_page *)
6082		(page_index->page_data + (page_index->page_len *
6083		CTL_PAGE_SAVED));
6084
6085	mtx_lock(&lun->lun_lock);
6086	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6087	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6088		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6089		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6090		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6091		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6092		set_ua = 1;
6093	}
6094	if (set_ua != 0) {
6095		int i;
6096		/*
6097		 * Let other initiators know that the mode
6098		 * parameters for this LUN have changed.
6099		 */
6100		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6101			if (i == initidx)
6102				continue;
6103
6104			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6105		}
6106	}
6107	mtx_unlock(&lun->lun_lock);
6108
6109	return (0);
6110}
6111
6112int
6113ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6114				struct ctl_page_index *page_index,
6115				uint8_t *page_ptr)
6116{
6117	uint8_t *c;
6118	int i;
6119
6120	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6121	ctl_time_io_secs =
6122		(c[0] << 8) |
6123		(c[1] << 0) |
6124		0;
6125	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6126	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6127	printf("page data:");
6128	for (i=0; i<8; i++)
6129		printf(" %.2x",page_ptr[i]);
6130	printf("\n");
6131	return (0);
6132}
6133
6134int
6135ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6136			       struct ctl_page_index *page_index,
6137			       int pc)
6138{
6139	struct copan_debugconf_subpage *page;
6140
6141	page = (struct copan_debugconf_subpage *)page_index->page_data +
6142		(page_index->page_len * pc);
6143
6144	switch (pc) {
6145	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6146	case SMS_PAGE_CTRL_DEFAULT >> 6:
6147	case SMS_PAGE_CTRL_SAVED >> 6:
6148		/*
6149		 * We don't update the changable or default bits for this page.
6150		 */
6151		break;
6152	case SMS_PAGE_CTRL_CURRENT >> 6:
6153		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6154		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6155		break;
6156	default:
6157#ifdef NEEDTOPORT
6158		EPRINT(0, "Invalid PC %d!!", pc);
6159#endif /* NEEDTOPORT */
6160		break;
6161	}
6162	return (0);
6163}
6164
6165
6166static int
6167ctl_do_mode_select(union ctl_io *io)
6168{
6169	struct scsi_mode_page_header *page_header;
6170	struct ctl_page_index *page_index;
6171	struct ctl_scsiio *ctsio;
6172	int control_dev, page_len;
6173	int page_len_offset, page_len_size;
6174	union ctl_modepage_info *modepage_info;
6175	struct ctl_lun *lun;
6176	int *len_left, *len_used;
6177	int retval, i;
6178
6179	ctsio = &io->scsiio;
6180	page_index = NULL;
6181	page_len = 0;
6182	retval = CTL_RETVAL_COMPLETE;
6183
6184	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6185
6186	if (lun->be_lun->lun_type != T_DIRECT)
6187		control_dev = 1;
6188	else
6189		control_dev = 0;
6190
6191	modepage_info = (union ctl_modepage_info *)
6192		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6193	len_left = &modepage_info->header.len_left;
6194	len_used = &modepage_info->header.len_used;
6195
6196do_next_page:
6197
6198	page_header = (struct scsi_mode_page_header *)
6199		(ctsio->kern_data_ptr + *len_used);
6200
6201	if (*len_left == 0) {
6202		free(ctsio->kern_data_ptr, M_CTL);
6203		ctl_set_success(ctsio);
6204		ctl_done((union ctl_io *)ctsio);
6205		return (CTL_RETVAL_COMPLETE);
6206	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6207
6208		free(ctsio->kern_data_ptr, M_CTL);
6209		ctl_set_param_len_error(ctsio);
6210		ctl_done((union ctl_io *)ctsio);
6211		return (CTL_RETVAL_COMPLETE);
6212
6213	} else if ((page_header->page_code & SMPH_SPF)
6214		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6215
6216		free(ctsio->kern_data_ptr, M_CTL);
6217		ctl_set_param_len_error(ctsio);
6218		ctl_done((union ctl_io *)ctsio);
6219		return (CTL_RETVAL_COMPLETE);
6220	}
6221
6222
6223	/*
6224	 * XXX KDM should we do something with the block descriptor?
6225	 */
6226	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6227
6228		if ((control_dev != 0)
6229		 && (lun->mode_pages.index[i].page_flags &
6230		     CTL_PAGE_FLAG_DISK_ONLY))
6231			continue;
6232
6233		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6234		    (page_header->page_code & SMPH_PC_MASK))
6235			continue;
6236
6237		/*
6238		 * If neither page has a subpage code, then we've got a
6239		 * match.
6240		 */
6241		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6242		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6243			page_index = &lun->mode_pages.index[i];
6244			page_len = page_header->page_length;
6245			break;
6246		}
6247
6248		/*
6249		 * If both pages have subpages, then the subpage numbers
6250		 * have to match.
6251		 */
6252		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6253		  && (page_header->page_code & SMPH_SPF)) {
6254			struct scsi_mode_page_header_sp *sph;
6255
6256			sph = (struct scsi_mode_page_header_sp *)page_header;
6257
6258			if (lun->mode_pages.index[i].subpage ==
6259			    sph->subpage) {
6260				page_index = &lun->mode_pages.index[i];
6261				page_len = scsi_2btoul(sph->page_length);
6262				break;
6263			}
6264		}
6265	}
6266
6267	/*
6268	 * If we couldn't find the page, or if we don't have a mode select
6269	 * handler for it, send back an error to the user.
6270	 */
6271	if ((page_index == NULL)
6272	 || (page_index->select_handler == NULL)) {
6273		ctl_set_invalid_field(ctsio,
6274				      /*sks_valid*/ 1,
6275				      /*command*/ 0,
6276				      /*field*/ *len_used,
6277				      /*bit_valid*/ 0,
6278				      /*bit*/ 0);
6279		free(ctsio->kern_data_ptr, M_CTL);
6280		ctl_done((union ctl_io *)ctsio);
6281		return (CTL_RETVAL_COMPLETE);
6282	}
6283
6284	if (page_index->page_code & SMPH_SPF) {
6285		page_len_offset = 2;
6286		page_len_size = 2;
6287	} else {
6288		page_len_size = 1;
6289		page_len_offset = 1;
6290	}
6291
6292	/*
6293	 * If the length the initiator gives us isn't the one we specify in
6294	 * the mode page header, or if they didn't specify enough data in
6295	 * the CDB to avoid truncating this page, kick out the request.
6296	 */
6297	if ((page_len != (page_index->page_len - page_len_offset -
6298			  page_len_size))
6299	 || (*len_left < page_index->page_len)) {
6300
6301
6302		ctl_set_invalid_field(ctsio,
6303				      /*sks_valid*/ 1,
6304				      /*command*/ 0,
6305				      /*field*/ *len_used + page_len_offset,
6306				      /*bit_valid*/ 0,
6307				      /*bit*/ 0);
6308		free(ctsio->kern_data_ptr, M_CTL);
6309		ctl_done((union ctl_io *)ctsio);
6310		return (CTL_RETVAL_COMPLETE);
6311	}
6312
6313	/*
6314	 * Run through the mode page, checking to make sure that the bits
6315	 * the user changed are actually legal for him to change.
6316	 */
6317	for (i = 0; i < page_index->page_len; i++) {
6318		uint8_t *user_byte, *change_mask, *current_byte;
6319		int bad_bit;
6320		int j;
6321
6322		user_byte = (uint8_t *)page_header + i;
6323		change_mask = page_index->page_data +
6324			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6325		current_byte = page_index->page_data +
6326			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6327
6328		/*
6329		 * Check to see whether the user set any bits in this byte
6330		 * that he is not allowed to set.
6331		 */
6332		if ((*user_byte & ~(*change_mask)) ==
6333		    (*current_byte & ~(*change_mask)))
6334			continue;
6335
6336		/*
6337		 * Go through bit by bit to determine which one is illegal.
6338		 */
6339		bad_bit = 0;
6340		for (j = 7; j >= 0; j--) {
6341			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6342			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6343				bad_bit = i;
6344				break;
6345			}
6346		}
6347		ctl_set_invalid_field(ctsio,
6348				      /*sks_valid*/ 1,
6349				      /*command*/ 0,
6350				      /*field*/ *len_used + i,
6351				      /*bit_valid*/ 1,
6352				      /*bit*/ bad_bit);
6353		free(ctsio->kern_data_ptr, M_CTL);
6354		ctl_done((union ctl_io *)ctsio);
6355		return (CTL_RETVAL_COMPLETE);
6356	}
6357
6358	/*
6359	 * Decrement these before we call the page handler, since we may
6360	 * end up getting called back one way or another before the handler
6361	 * returns to this context.
6362	 */
6363	*len_left -= page_index->page_len;
6364	*len_used += page_index->page_len;
6365
6366	retval = page_index->select_handler(ctsio, page_index,
6367					    (uint8_t *)page_header);
6368
6369	/*
6370	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6371	 * wait until this queued command completes to finish processing
6372	 * the mode page.  If it returns anything other than
6373	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6374	 * already set the sense information, freed the data pointer, and
6375	 * completed the io for us.
6376	 */
6377	if (retval != CTL_RETVAL_COMPLETE)
6378		goto bailout_no_done;
6379
6380	/*
6381	 * If the initiator sent us more than one page, parse the next one.
6382	 */
6383	if (*len_left > 0)
6384		goto do_next_page;
6385
6386	ctl_set_success(ctsio);
6387	free(ctsio->kern_data_ptr, M_CTL);
6388	ctl_done((union ctl_io *)ctsio);
6389
6390bailout_no_done:
6391
6392	return (CTL_RETVAL_COMPLETE);
6393
6394}
6395
6396int
6397ctl_mode_select(struct ctl_scsiio *ctsio)
6398{
6399	int param_len, pf, sp;
6400	int header_size, bd_len;
6401	int len_left, len_used;
6402	struct ctl_page_index *page_index;
6403	struct ctl_lun *lun;
6404	int control_dev, page_len;
6405	union ctl_modepage_info *modepage_info;
6406	int retval;
6407
6408	pf = 0;
6409	sp = 0;
6410	page_len = 0;
6411	len_used = 0;
6412	len_left = 0;
6413	retval = 0;
6414	bd_len = 0;
6415	page_index = NULL;
6416
6417	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6418
6419	if (lun->be_lun->lun_type != T_DIRECT)
6420		control_dev = 1;
6421	else
6422		control_dev = 0;
6423
6424	switch (ctsio->cdb[0]) {
6425	case MODE_SELECT_6: {
6426		struct scsi_mode_select_6 *cdb;
6427
6428		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6429
6430		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6431		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6432
6433		param_len = cdb->length;
6434		header_size = sizeof(struct scsi_mode_header_6);
6435		break;
6436	}
6437	case MODE_SELECT_10: {
6438		struct scsi_mode_select_10 *cdb;
6439
6440		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6441
6442		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6443		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6444
6445		param_len = scsi_2btoul(cdb->length);
6446		header_size = sizeof(struct scsi_mode_header_10);
6447		break;
6448	}
6449	default:
6450		ctl_set_invalid_opcode(ctsio);
6451		ctl_done((union ctl_io *)ctsio);
6452		return (CTL_RETVAL_COMPLETE);
6453		break; /* NOTREACHED */
6454	}
6455
6456	/*
6457	 * From SPC-3:
6458	 * "A parameter list length of zero indicates that the Data-Out Buffer
6459	 * shall be empty. This condition shall not be considered as an error."
6460	 */
6461	if (param_len == 0) {
6462		ctl_set_success(ctsio);
6463		ctl_done((union ctl_io *)ctsio);
6464		return (CTL_RETVAL_COMPLETE);
6465	}
6466
6467	/*
6468	 * Since we'll hit this the first time through, prior to
6469	 * allocation, we don't need to free a data buffer here.
6470	 */
6471	if (param_len < header_size) {
6472		ctl_set_param_len_error(ctsio);
6473		ctl_done((union ctl_io *)ctsio);
6474		return (CTL_RETVAL_COMPLETE);
6475	}
6476
6477	/*
6478	 * Allocate the data buffer and grab the user's data.  In theory,
6479	 * we shouldn't have to sanity check the parameter list length here
6480	 * because the maximum size is 64K.  We should be able to malloc
6481	 * that much without too many problems.
6482	 */
6483	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6484		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6485		ctsio->kern_data_len = param_len;
6486		ctsio->kern_total_len = param_len;
6487		ctsio->kern_data_resid = 0;
6488		ctsio->kern_rel_offset = 0;
6489		ctsio->kern_sg_entries = 0;
6490		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6491		ctsio->be_move_done = ctl_config_move_done;
6492		ctl_datamove((union ctl_io *)ctsio);
6493
6494		return (CTL_RETVAL_COMPLETE);
6495	}
6496
6497	switch (ctsio->cdb[0]) {
6498	case MODE_SELECT_6: {
6499		struct scsi_mode_header_6 *mh6;
6500
6501		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6502		bd_len = mh6->blk_desc_len;
6503		break;
6504	}
6505	case MODE_SELECT_10: {
6506		struct scsi_mode_header_10 *mh10;
6507
6508		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6509		bd_len = scsi_2btoul(mh10->blk_desc_len);
6510		break;
6511	}
6512	default:
6513		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6514		break;
6515	}
6516
6517	if (param_len < (header_size + bd_len)) {
6518		free(ctsio->kern_data_ptr, M_CTL);
6519		ctl_set_param_len_error(ctsio);
6520		ctl_done((union ctl_io *)ctsio);
6521		return (CTL_RETVAL_COMPLETE);
6522	}
6523
6524	/*
6525	 * Set the IO_CONT flag, so that if this I/O gets passed to
6526	 * ctl_config_write_done(), it'll get passed back to
6527	 * ctl_do_mode_select() for further processing, or completion if
6528	 * we're all done.
6529	 */
6530	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6531	ctsio->io_cont = ctl_do_mode_select;
6532
6533	modepage_info = (union ctl_modepage_info *)
6534		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6535
6536	memset(modepage_info, 0, sizeof(*modepage_info));
6537
6538	len_left = param_len - header_size - bd_len;
6539	len_used = header_size + bd_len;
6540
6541	modepage_info->header.len_left = len_left;
6542	modepage_info->header.len_used = len_used;
6543
6544	return (ctl_do_mode_select((union ctl_io *)ctsio));
6545}
6546
6547int
6548ctl_mode_sense(struct ctl_scsiio *ctsio)
6549{
6550	struct ctl_lun *lun;
6551	int pc, page_code, dbd, llba, subpage;
6552	int alloc_len, page_len, header_len, total_len;
6553	struct scsi_mode_block_descr *block_desc;
6554	struct ctl_page_index *page_index;
6555	int control_dev;
6556
6557	dbd = 0;
6558	llba = 0;
6559	block_desc = NULL;
6560	page_index = NULL;
6561
6562	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6563
6564	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6565
6566	if (lun->be_lun->lun_type != T_DIRECT)
6567		control_dev = 1;
6568	else
6569		control_dev = 0;
6570
6571	switch (ctsio->cdb[0]) {
6572	case MODE_SENSE_6: {
6573		struct scsi_mode_sense_6 *cdb;
6574
6575		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6576
6577		header_len = sizeof(struct scsi_mode_hdr_6);
6578		if (cdb->byte2 & SMS_DBD)
6579			dbd = 1;
6580		else
6581			header_len += sizeof(struct scsi_mode_block_descr);
6582
6583		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6584		page_code = cdb->page & SMS_PAGE_CODE;
6585		subpage = cdb->subpage;
6586		alloc_len = cdb->length;
6587		break;
6588	}
6589	case MODE_SENSE_10: {
6590		struct scsi_mode_sense_10 *cdb;
6591
6592		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6593
6594		header_len = sizeof(struct scsi_mode_hdr_10);
6595
6596		if (cdb->byte2 & SMS_DBD)
6597			dbd = 1;
6598		else
6599			header_len += sizeof(struct scsi_mode_block_descr);
6600		if (cdb->byte2 & SMS10_LLBAA)
6601			llba = 1;
6602		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6603		page_code = cdb->page & SMS_PAGE_CODE;
6604		subpage = cdb->subpage;
6605		alloc_len = scsi_2btoul(cdb->length);
6606		break;
6607	}
6608	default:
6609		ctl_set_invalid_opcode(ctsio);
6610		ctl_done((union ctl_io *)ctsio);
6611		return (CTL_RETVAL_COMPLETE);
6612		break; /* NOTREACHED */
6613	}
6614
6615	/*
6616	 * We have to make a first pass through to calculate the size of
6617	 * the pages that match the user's query.  Then we allocate enough
6618	 * memory to hold it, and actually copy the data into the buffer.
6619	 */
6620	switch (page_code) {
6621	case SMS_ALL_PAGES_PAGE: {
6622		int i;
6623
6624		page_len = 0;
6625
6626		/*
6627		 * At the moment, values other than 0 and 0xff here are
6628		 * reserved according to SPC-3.
6629		 */
6630		if ((subpage != SMS_SUBPAGE_PAGE_0)
6631		 && (subpage != SMS_SUBPAGE_ALL)) {
6632			ctl_set_invalid_field(ctsio,
6633					      /*sks_valid*/ 1,
6634					      /*command*/ 1,
6635					      /*field*/ 3,
6636					      /*bit_valid*/ 0,
6637					      /*bit*/ 0);
6638			ctl_done((union ctl_io *)ctsio);
6639			return (CTL_RETVAL_COMPLETE);
6640		}
6641
6642		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6643			if ((control_dev != 0)
6644			 && (lun->mode_pages.index[i].page_flags &
6645			     CTL_PAGE_FLAG_DISK_ONLY))
6646				continue;
6647
6648			/*
6649			 * We don't use this subpage if the user didn't
6650			 * request all subpages.
6651			 */
6652			if ((lun->mode_pages.index[i].subpage != 0)
6653			 && (subpage == SMS_SUBPAGE_PAGE_0))
6654				continue;
6655
6656#if 0
6657			printf("found page %#x len %d\n",
6658			       lun->mode_pages.index[i].page_code &
6659			       SMPH_PC_MASK,
6660			       lun->mode_pages.index[i].page_len);
6661#endif
6662			page_len += lun->mode_pages.index[i].page_len;
6663		}
6664		break;
6665	}
6666	default: {
6667		int i;
6668
6669		page_len = 0;
6670
6671		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6672			/* Look for the right page code */
6673			if ((lun->mode_pages.index[i].page_code &
6674			     SMPH_PC_MASK) != page_code)
6675				continue;
6676
6677			/* Look for the right subpage or the subpage wildcard*/
6678			if ((lun->mode_pages.index[i].subpage != subpage)
6679			 && (subpage != SMS_SUBPAGE_ALL))
6680				continue;
6681
6682			/* Make sure the page is supported for this dev type */
6683			if ((control_dev != 0)
6684			 && (lun->mode_pages.index[i].page_flags &
6685			     CTL_PAGE_FLAG_DISK_ONLY))
6686				continue;
6687
6688#if 0
6689			printf("found page %#x len %d\n",
6690			       lun->mode_pages.index[i].page_code &
6691			       SMPH_PC_MASK,
6692			       lun->mode_pages.index[i].page_len);
6693#endif
6694
6695			page_len += lun->mode_pages.index[i].page_len;
6696		}
6697
6698		if (page_len == 0) {
6699			ctl_set_invalid_field(ctsio,
6700					      /*sks_valid*/ 1,
6701					      /*command*/ 1,
6702					      /*field*/ 2,
6703					      /*bit_valid*/ 1,
6704					      /*bit*/ 5);
6705			ctl_done((union ctl_io *)ctsio);
6706			return (CTL_RETVAL_COMPLETE);
6707		}
6708		break;
6709	}
6710	}
6711
6712	total_len = header_len + page_len;
6713#if 0
6714	printf("header_len = %d, page_len = %d, total_len = %d\n",
6715	       header_len, page_len, total_len);
6716#endif
6717
6718	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6719	ctsio->kern_sg_entries = 0;
6720	ctsio->kern_data_resid = 0;
6721	ctsio->kern_rel_offset = 0;
6722	if (total_len < alloc_len) {
6723		ctsio->residual = alloc_len - total_len;
6724		ctsio->kern_data_len = total_len;
6725		ctsio->kern_total_len = total_len;
6726	} else {
6727		ctsio->residual = 0;
6728		ctsio->kern_data_len = alloc_len;
6729		ctsio->kern_total_len = alloc_len;
6730	}
6731
6732	switch (ctsio->cdb[0]) {
6733	case MODE_SENSE_6: {
6734		struct scsi_mode_hdr_6 *header;
6735
6736		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6737
6738		header->datalen = ctl_min(total_len - 1, 254);
6739		if (control_dev == 0) {
6740			header->dev_specific = 0x10; /* DPOFUA */
6741			if ((lun->flags & CTL_LUN_READONLY) ||
6742			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6743			    .eca_and_aen & SCP_SWP) != 0)
6744				    header->dev_specific |= 0x80; /* WP */
6745		}
6746		if (dbd)
6747			header->block_descr_len = 0;
6748		else
6749			header->block_descr_len =
6750				sizeof(struct scsi_mode_block_descr);
6751		block_desc = (struct scsi_mode_block_descr *)&header[1];
6752		break;
6753	}
6754	case MODE_SENSE_10: {
6755		struct scsi_mode_hdr_10 *header;
6756		int datalen;
6757
6758		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6759
6760		datalen = ctl_min(total_len - 2, 65533);
6761		scsi_ulto2b(datalen, header->datalen);
6762		if (control_dev == 0) {
6763			header->dev_specific = 0x10; /* DPOFUA */
6764			if ((lun->flags & CTL_LUN_READONLY) ||
6765			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6766			    .eca_and_aen & SCP_SWP) != 0)
6767				    header->dev_specific |= 0x80; /* WP */
6768		}
6769		if (dbd)
6770			scsi_ulto2b(0, header->block_descr_len);
6771		else
6772			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6773				    header->block_descr_len);
6774		block_desc = (struct scsi_mode_block_descr *)&header[1];
6775		break;
6776	}
6777	default:
6778		panic("invalid CDB type %#x", ctsio->cdb[0]);
6779		break; /* NOTREACHED */
6780	}
6781
6782	/*
6783	 * If we've got a disk, use its blocksize in the block
6784	 * descriptor.  Otherwise, just set it to 0.
6785	 */
6786	if (dbd == 0) {
6787		if (control_dev == 0)
6788			scsi_ulto3b(lun->be_lun->blocksize,
6789				    block_desc->block_len);
6790		else
6791			scsi_ulto3b(0, block_desc->block_len);
6792	}
6793
6794	switch (page_code) {
6795	case SMS_ALL_PAGES_PAGE: {
6796		int i, data_used;
6797
6798		data_used = header_len;
6799		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6800			struct ctl_page_index *page_index;
6801
6802			page_index = &lun->mode_pages.index[i];
6803
6804			if ((control_dev != 0)
6805			 && (page_index->page_flags &
6806			    CTL_PAGE_FLAG_DISK_ONLY))
6807				continue;
6808
6809			/*
6810			 * We don't use this subpage if the user didn't
6811			 * request all subpages.  We already checked (above)
6812			 * to make sure the user only specified a subpage
6813			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6814			 */
6815			if ((page_index->subpage != 0)
6816			 && (subpage == SMS_SUBPAGE_PAGE_0))
6817				continue;
6818
6819			/*
6820			 * Call the handler, if it exists, to update the
6821			 * page to the latest values.
6822			 */
6823			if (page_index->sense_handler != NULL)
6824				page_index->sense_handler(ctsio, page_index,pc);
6825
6826			memcpy(ctsio->kern_data_ptr + data_used,
6827			       page_index->page_data +
6828			       (page_index->page_len * pc),
6829			       page_index->page_len);
6830			data_used += page_index->page_len;
6831		}
6832		break;
6833	}
6834	default: {
6835		int i, data_used;
6836
6837		data_used = header_len;
6838
6839		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6840			struct ctl_page_index *page_index;
6841
6842			page_index = &lun->mode_pages.index[i];
6843
6844			/* Look for the right page code */
6845			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6846				continue;
6847
6848			/* Look for the right subpage or the subpage wildcard*/
6849			if ((page_index->subpage != subpage)
6850			 && (subpage != SMS_SUBPAGE_ALL))
6851				continue;
6852
6853			/* Make sure the page is supported for this dev type */
6854			if ((control_dev != 0)
6855			 && (page_index->page_flags &
6856			     CTL_PAGE_FLAG_DISK_ONLY))
6857				continue;
6858
6859			/*
6860			 * Call the handler, if it exists, to update the
6861			 * page to the latest values.
6862			 */
6863			if (page_index->sense_handler != NULL)
6864				page_index->sense_handler(ctsio, page_index,pc);
6865
6866			memcpy(ctsio->kern_data_ptr + data_used,
6867			       page_index->page_data +
6868			       (page_index->page_len * pc),
6869			       page_index->page_len);
6870			data_used += page_index->page_len;
6871		}
6872		break;
6873	}
6874	}
6875
6876	ctl_set_success(ctsio);
6877	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6878	ctsio->be_move_done = ctl_config_move_done;
6879	ctl_datamove((union ctl_io *)ctsio);
6880	return (CTL_RETVAL_COMPLETE);
6881}
6882
6883int
6884ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6885			       struct ctl_page_index *page_index,
6886			       int pc)
6887{
6888	struct ctl_lun *lun;
6889	struct scsi_log_param_header *phdr;
6890	uint8_t *data;
6891	uint64_t val;
6892
6893	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6894	data = page_index->page_data;
6895
6896	if (lun->backend->lun_attr != NULL &&
6897	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6898	     != UINT64_MAX) {
6899		phdr = (struct scsi_log_param_header *)data;
6900		scsi_ulto2b(0x0001, phdr->param_code);
6901		phdr->param_control = SLP_LBIN | SLP_LP;
6902		phdr->param_len = 8;
6903		data = (uint8_t *)(phdr + 1);
6904		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6905		data[4] = 0x01; /* per-LUN */
6906		data += phdr->param_len;
6907	}
6908
6909	if (lun->backend->lun_attr != NULL &&
6910	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6911	     != UINT64_MAX) {
6912		phdr = (struct scsi_log_param_header *)data;
6913		scsi_ulto2b(0x0002, phdr->param_code);
6914		phdr->param_control = SLP_LBIN | SLP_LP;
6915		phdr->param_len = 8;
6916		data = (uint8_t *)(phdr + 1);
6917		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6918		data[4] = 0x02; /* per-pool */
6919		data += phdr->param_len;
6920	}
6921
6922	if (lun->backend->lun_attr != NULL &&
6923	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6924	     != UINT64_MAX) {
6925		phdr = (struct scsi_log_param_header *)data;
6926		scsi_ulto2b(0x00f1, phdr->param_code);
6927		phdr->param_control = SLP_LBIN | SLP_LP;
6928		phdr->param_len = 8;
6929		data = (uint8_t *)(phdr + 1);
6930		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6931		data[4] = 0x02; /* per-pool */
6932		data += phdr->param_len;
6933	}
6934
6935	if (lun->backend->lun_attr != NULL &&
6936	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6937	     != UINT64_MAX) {
6938		phdr = (struct scsi_log_param_header *)data;
6939		scsi_ulto2b(0x00f2, phdr->param_code);
6940		phdr->param_control = SLP_LBIN | SLP_LP;
6941		phdr->param_len = 8;
6942		data = (uint8_t *)(phdr + 1);
6943		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6944		data[4] = 0x02; /* per-pool */
6945		data += phdr->param_len;
6946	}
6947
6948	page_index->page_len = data - page_index->page_data;
6949	return (0);
6950}
6951
6952int
6953ctl_log_sense(struct ctl_scsiio *ctsio)
6954{
6955	struct ctl_lun *lun;
6956	int i, pc, page_code, subpage;
6957	int alloc_len, total_len;
6958	struct ctl_page_index *page_index;
6959	struct scsi_log_sense *cdb;
6960	struct scsi_log_header *header;
6961
6962	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6963
6964	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6965	cdb = (struct scsi_log_sense *)ctsio->cdb;
6966	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6967	page_code = cdb->page & SLS_PAGE_CODE;
6968	subpage = cdb->subpage;
6969	alloc_len = scsi_2btoul(cdb->length);
6970
6971	page_index = NULL;
6972	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6973		page_index = &lun->log_pages.index[i];
6974
6975		/* Look for the right page code */
6976		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6977			continue;
6978
6979		/* Look for the right subpage or the subpage wildcard*/
6980		if (page_index->subpage != subpage)
6981			continue;
6982
6983		break;
6984	}
6985	if (i >= CTL_NUM_LOG_PAGES) {
6986		ctl_set_invalid_field(ctsio,
6987				      /*sks_valid*/ 1,
6988				      /*command*/ 1,
6989				      /*field*/ 2,
6990				      /*bit_valid*/ 0,
6991				      /*bit*/ 0);
6992		ctl_done((union ctl_io *)ctsio);
6993		return (CTL_RETVAL_COMPLETE);
6994	}
6995
6996	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6997
6998	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6999	ctsio->kern_sg_entries = 0;
7000	ctsio->kern_data_resid = 0;
7001	ctsio->kern_rel_offset = 0;
7002	if (total_len < alloc_len) {
7003		ctsio->residual = alloc_len - total_len;
7004		ctsio->kern_data_len = total_len;
7005		ctsio->kern_total_len = total_len;
7006	} else {
7007		ctsio->residual = 0;
7008		ctsio->kern_data_len = alloc_len;
7009		ctsio->kern_total_len = alloc_len;
7010	}
7011
7012	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7013	header->page = page_index->page_code;
7014	if (page_index->subpage) {
7015		header->page |= SL_SPF;
7016		header->subpage = page_index->subpage;
7017	}
7018	scsi_ulto2b(page_index->page_len, header->datalen);
7019
7020	/*
7021	 * Call the handler, if it exists, to update the
7022	 * page to the latest values.
7023	 */
7024	if (page_index->sense_handler != NULL)
7025		page_index->sense_handler(ctsio, page_index, pc);
7026
7027	memcpy(header + 1, page_index->page_data, page_index->page_len);
7028
7029	ctl_set_success(ctsio);
7030	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7031	ctsio->be_move_done = ctl_config_move_done;
7032	ctl_datamove((union ctl_io *)ctsio);
7033	return (CTL_RETVAL_COMPLETE);
7034}
7035
7036int
7037ctl_read_capacity(struct ctl_scsiio *ctsio)
7038{
7039	struct scsi_read_capacity *cdb;
7040	struct scsi_read_capacity_data *data;
7041	struct ctl_lun *lun;
7042	uint32_t lba;
7043
7044	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7045
7046	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7047
7048	lba = scsi_4btoul(cdb->addr);
7049	if (((cdb->pmi & SRC_PMI) == 0)
7050	 && (lba != 0)) {
7051		ctl_set_invalid_field(/*ctsio*/ ctsio,
7052				      /*sks_valid*/ 1,
7053				      /*command*/ 1,
7054				      /*field*/ 2,
7055				      /*bit_valid*/ 0,
7056				      /*bit*/ 0);
7057		ctl_done((union ctl_io *)ctsio);
7058		return (CTL_RETVAL_COMPLETE);
7059	}
7060
7061	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7062
7063	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7064	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7065	ctsio->residual = 0;
7066	ctsio->kern_data_len = sizeof(*data);
7067	ctsio->kern_total_len = sizeof(*data);
7068	ctsio->kern_data_resid = 0;
7069	ctsio->kern_rel_offset = 0;
7070	ctsio->kern_sg_entries = 0;
7071
7072	/*
7073	 * If the maximum LBA is greater than 0xfffffffe, the user must
7074	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7075	 * serivce action set.
7076	 */
7077	if (lun->be_lun->maxlba > 0xfffffffe)
7078		scsi_ulto4b(0xffffffff, data->addr);
7079	else
7080		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7081
7082	/*
7083	 * XXX KDM this may not be 512 bytes...
7084	 */
7085	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7086
7087	ctl_set_success(ctsio);
7088	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7089	ctsio->be_move_done = ctl_config_move_done;
7090	ctl_datamove((union ctl_io *)ctsio);
7091	return (CTL_RETVAL_COMPLETE);
7092}
7093
7094int
7095ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7096{
7097	struct scsi_read_capacity_16 *cdb;
7098	struct scsi_read_capacity_data_long *data;
7099	struct ctl_lun *lun;
7100	uint64_t lba;
7101	uint32_t alloc_len;
7102
7103	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7104
7105	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7106
7107	alloc_len = scsi_4btoul(cdb->alloc_len);
7108	lba = scsi_8btou64(cdb->addr);
7109
7110	if ((cdb->reladr & SRC16_PMI)
7111	 && (lba != 0)) {
7112		ctl_set_invalid_field(/*ctsio*/ ctsio,
7113				      /*sks_valid*/ 1,
7114				      /*command*/ 1,
7115				      /*field*/ 2,
7116				      /*bit_valid*/ 0,
7117				      /*bit*/ 0);
7118		ctl_done((union ctl_io *)ctsio);
7119		return (CTL_RETVAL_COMPLETE);
7120	}
7121
7122	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7123
7124	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7125	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7126
7127	if (sizeof(*data) < alloc_len) {
7128		ctsio->residual = alloc_len - sizeof(*data);
7129		ctsio->kern_data_len = sizeof(*data);
7130		ctsio->kern_total_len = sizeof(*data);
7131	} else {
7132		ctsio->residual = 0;
7133		ctsio->kern_data_len = alloc_len;
7134		ctsio->kern_total_len = alloc_len;
7135	}
7136	ctsio->kern_data_resid = 0;
7137	ctsio->kern_rel_offset = 0;
7138	ctsio->kern_sg_entries = 0;
7139
7140	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7141	/* XXX KDM this may not be 512 bytes... */
7142	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7143	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7144	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7145	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7146		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7147
7148	ctl_set_success(ctsio);
7149	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7150	ctsio->be_move_done = ctl_config_move_done;
7151	ctl_datamove((union ctl_io *)ctsio);
7152	return (CTL_RETVAL_COMPLETE);
7153}
7154
7155int
7156ctl_read_defect(struct ctl_scsiio *ctsio)
7157{
7158	struct scsi_read_defect_data_10 *ccb10;
7159	struct scsi_read_defect_data_12 *ccb12;
7160	struct scsi_read_defect_data_hdr_10 *data10;
7161	struct scsi_read_defect_data_hdr_12 *data12;
7162	uint32_t alloc_len, data_len;
7163	uint8_t format;
7164
7165	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7166
7167	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7168		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7169		format = ccb10->format;
7170		alloc_len = scsi_2btoul(ccb10->alloc_length);
7171		data_len = sizeof(*data10);
7172	} else {
7173		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7174		format = ccb12->format;
7175		alloc_len = scsi_4btoul(ccb12->alloc_length);
7176		data_len = sizeof(*data12);
7177	}
7178	if (alloc_len == 0) {
7179		ctl_set_success(ctsio);
7180		ctl_done((union ctl_io *)ctsio);
7181		return (CTL_RETVAL_COMPLETE);
7182	}
7183
7184	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7185	if (data_len < alloc_len) {
7186		ctsio->residual = alloc_len - data_len;
7187		ctsio->kern_data_len = data_len;
7188		ctsio->kern_total_len = data_len;
7189	} else {
7190		ctsio->residual = 0;
7191		ctsio->kern_data_len = alloc_len;
7192		ctsio->kern_total_len = alloc_len;
7193	}
7194	ctsio->kern_data_resid = 0;
7195	ctsio->kern_rel_offset = 0;
7196	ctsio->kern_sg_entries = 0;
7197
7198	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7199		data10 = (struct scsi_read_defect_data_hdr_10 *)
7200		    ctsio->kern_data_ptr;
7201		data10->format = format;
7202		scsi_ulto2b(0, data10->length);
7203	} else {
7204		data12 = (struct scsi_read_defect_data_hdr_12 *)
7205		    ctsio->kern_data_ptr;
7206		data12->format = format;
7207		scsi_ulto2b(0, data12->generation);
7208		scsi_ulto4b(0, data12->length);
7209	}
7210
7211	ctl_set_success(ctsio);
7212	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7213	ctsio->be_move_done = ctl_config_move_done;
7214	ctl_datamove((union ctl_io *)ctsio);
7215	return (CTL_RETVAL_COMPLETE);
7216}
7217
7218int
7219ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7220{
7221	struct scsi_maintenance_in *cdb;
7222	int retval;
7223	int alloc_len, ext, total_len = 0, g, p, pc, pg, gs, os;
7224	int num_target_port_groups, num_target_ports;
7225	struct ctl_lun *lun;
7226	struct ctl_softc *softc;
7227	struct ctl_port *port;
7228	struct scsi_target_group_data *rtg_ptr;
7229	struct scsi_target_group_data_extended *rtg_ext_ptr;
7230	struct scsi_target_port_group_descriptor *tpg_desc;
7231
7232	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7233
7234	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7235	softc = control_softc;
7236	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7237
7238	retval = CTL_RETVAL_COMPLETE;
7239
7240	switch (cdb->byte2 & STG_PDF_MASK) {
7241	case STG_PDF_LENGTH:
7242		ext = 0;
7243		break;
7244	case STG_PDF_EXTENDED:
7245		ext = 1;
7246		break;
7247	default:
7248		ctl_set_invalid_field(/*ctsio*/ ctsio,
7249				      /*sks_valid*/ 1,
7250				      /*command*/ 1,
7251				      /*field*/ 2,
7252				      /*bit_valid*/ 1,
7253				      /*bit*/ 5);
7254		ctl_done((union ctl_io *)ctsio);
7255		return(retval);
7256	}
7257
7258	if (softc->is_single)
7259		num_target_port_groups = 1;
7260	else
7261		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7262	num_target_ports = 0;
7263	mtx_lock(&softc->ctl_lock);
7264	STAILQ_FOREACH(port, &softc->port_list, links) {
7265		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7266			continue;
7267		if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7268			continue;
7269		num_target_ports++;
7270	}
7271	mtx_unlock(&softc->ctl_lock);
7272
7273	if (ext)
7274		total_len = sizeof(struct scsi_target_group_data_extended);
7275	else
7276		total_len = sizeof(struct scsi_target_group_data);
7277	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7278		num_target_port_groups +
7279	    sizeof(struct scsi_target_port_descriptor) *
7280		num_target_ports * num_target_port_groups;
7281
7282	alloc_len = scsi_4btoul(cdb->length);
7283
7284	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7285
7286	ctsio->kern_sg_entries = 0;
7287
7288	if (total_len < alloc_len) {
7289		ctsio->residual = alloc_len - total_len;
7290		ctsio->kern_data_len = total_len;
7291		ctsio->kern_total_len = total_len;
7292	} else {
7293		ctsio->residual = 0;
7294		ctsio->kern_data_len = alloc_len;
7295		ctsio->kern_total_len = alloc_len;
7296	}
7297	ctsio->kern_data_resid = 0;
7298	ctsio->kern_rel_offset = 0;
7299
7300	if (ext) {
7301		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7302		    ctsio->kern_data_ptr;
7303		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7304		rtg_ext_ptr->format_type = 0x10;
7305		rtg_ext_ptr->implicit_transition_time = 0;
7306		tpg_desc = &rtg_ext_ptr->groups[0];
7307	} else {
7308		rtg_ptr = (struct scsi_target_group_data *)
7309		    ctsio->kern_data_ptr;
7310		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7311		tpg_desc = &rtg_ptr->groups[0];
7312	}
7313
7314	mtx_lock(&softc->ctl_lock);
7315	pg = softc->port_offset / CTL_MAX_PORTS;
7316	if (softc->flags & CTL_FLAG_ACTIVE_SHELF) {
7317		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY) {
7318			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7319			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7320		} else if (lun->flags & CTL_LUN_PRIMARY_SC) {
7321			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7322			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7323		} else {
7324			gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7325			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7326		}
7327	} else {
7328		gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7329		os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7330	}
7331	for (g = 0; g < num_target_port_groups; g++) {
7332		tpg_desc->pref_state = (g == pg) ? gs : os;
7333		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP;
7334		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7335		tpg_desc->status = TPG_IMPLICIT;
7336		pc = 0;
7337		STAILQ_FOREACH(port, &softc->port_list, links) {
7338			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7339				continue;
7340			if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7341			    CTL_MAX_LUNS)
7342				continue;
7343			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7344			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7345			    relative_target_port_identifier);
7346			pc++;
7347		}
7348		tpg_desc->target_port_count = pc;
7349		tpg_desc = (struct scsi_target_port_group_descriptor *)
7350		    &tpg_desc->descriptors[pc];
7351	}
7352	mtx_unlock(&softc->ctl_lock);
7353
7354	ctl_set_success(ctsio);
7355	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7356	ctsio->be_move_done = ctl_config_move_done;
7357	ctl_datamove((union ctl_io *)ctsio);
7358	return(retval);
7359}
7360
7361int
7362ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7363{
7364	struct ctl_lun *lun;
7365	struct scsi_report_supported_opcodes *cdb;
7366	const struct ctl_cmd_entry *entry, *sentry;
7367	struct scsi_report_supported_opcodes_all *all;
7368	struct scsi_report_supported_opcodes_descr *descr;
7369	struct scsi_report_supported_opcodes_one *one;
7370	int retval;
7371	int alloc_len, total_len;
7372	int opcode, service_action, i, j, num;
7373
7374	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7375
7376	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7377	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7378
7379	retval = CTL_RETVAL_COMPLETE;
7380
7381	opcode = cdb->requested_opcode;
7382	service_action = scsi_2btoul(cdb->requested_service_action);
7383	switch (cdb->options & RSO_OPTIONS_MASK) {
7384	case RSO_OPTIONS_ALL:
7385		num = 0;
7386		for (i = 0; i < 256; i++) {
7387			entry = &ctl_cmd_table[i];
7388			if (entry->flags & CTL_CMD_FLAG_SA5) {
7389				for (j = 0; j < 32; j++) {
7390					sentry = &((const struct ctl_cmd_entry *)
7391					    entry->execute)[j];
7392					if (ctl_cmd_applicable(
7393					    lun->be_lun->lun_type, sentry))
7394						num++;
7395				}
7396			} else {
7397				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7398				    entry))
7399					num++;
7400			}
7401		}
7402		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7403		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7404		break;
7405	case RSO_OPTIONS_OC:
7406		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7407			ctl_set_invalid_field(/*ctsio*/ ctsio,
7408					      /*sks_valid*/ 1,
7409					      /*command*/ 1,
7410					      /*field*/ 2,
7411					      /*bit_valid*/ 1,
7412					      /*bit*/ 2);
7413			ctl_done((union ctl_io *)ctsio);
7414			return (CTL_RETVAL_COMPLETE);
7415		}
7416		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7417		break;
7418	case RSO_OPTIONS_OC_SA:
7419		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7420		    service_action >= 32) {
7421			ctl_set_invalid_field(/*ctsio*/ ctsio,
7422					      /*sks_valid*/ 1,
7423					      /*command*/ 1,
7424					      /*field*/ 2,
7425					      /*bit_valid*/ 1,
7426					      /*bit*/ 2);
7427			ctl_done((union ctl_io *)ctsio);
7428			return (CTL_RETVAL_COMPLETE);
7429		}
7430		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7431		break;
7432	default:
7433		ctl_set_invalid_field(/*ctsio*/ ctsio,
7434				      /*sks_valid*/ 1,
7435				      /*command*/ 1,
7436				      /*field*/ 2,
7437				      /*bit_valid*/ 1,
7438				      /*bit*/ 2);
7439		ctl_done((union ctl_io *)ctsio);
7440		return (CTL_RETVAL_COMPLETE);
7441	}
7442
7443	alloc_len = scsi_4btoul(cdb->length);
7444
7445	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7446
7447	ctsio->kern_sg_entries = 0;
7448
7449	if (total_len < alloc_len) {
7450		ctsio->residual = alloc_len - total_len;
7451		ctsio->kern_data_len = total_len;
7452		ctsio->kern_total_len = total_len;
7453	} else {
7454		ctsio->residual = 0;
7455		ctsio->kern_data_len = alloc_len;
7456		ctsio->kern_total_len = alloc_len;
7457	}
7458	ctsio->kern_data_resid = 0;
7459	ctsio->kern_rel_offset = 0;
7460
7461	switch (cdb->options & RSO_OPTIONS_MASK) {
7462	case RSO_OPTIONS_ALL:
7463		all = (struct scsi_report_supported_opcodes_all *)
7464		    ctsio->kern_data_ptr;
7465		num = 0;
7466		for (i = 0; i < 256; i++) {
7467			entry = &ctl_cmd_table[i];
7468			if (entry->flags & CTL_CMD_FLAG_SA5) {
7469				for (j = 0; j < 32; j++) {
7470					sentry = &((const struct ctl_cmd_entry *)
7471					    entry->execute)[j];
7472					if (!ctl_cmd_applicable(
7473					    lun->be_lun->lun_type, sentry))
7474						continue;
7475					descr = &all->descr[num++];
7476					descr->opcode = i;
7477					scsi_ulto2b(j, descr->service_action);
7478					descr->flags = RSO_SERVACTV;
7479					scsi_ulto2b(sentry->length,
7480					    descr->cdb_length);
7481				}
7482			} else {
7483				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7484				    entry))
7485					continue;
7486				descr = &all->descr[num++];
7487				descr->opcode = i;
7488				scsi_ulto2b(0, descr->service_action);
7489				descr->flags = 0;
7490				scsi_ulto2b(entry->length, descr->cdb_length);
7491			}
7492		}
7493		scsi_ulto4b(
7494		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7495		    all->length);
7496		break;
7497	case RSO_OPTIONS_OC:
7498		one = (struct scsi_report_supported_opcodes_one *)
7499		    ctsio->kern_data_ptr;
7500		entry = &ctl_cmd_table[opcode];
7501		goto fill_one;
7502	case RSO_OPTIONS_OC_SA:
7503		one = (struct scsi_report_supported_opcodes_one *)
7504		    ctsio->kern_data_ptr;
7505		entry = &ctl_cmd_table[opcode];
7506		entry = &((const struct ctl_cmd_entry *)
7507		    entry->execute)[service_action];
7508fill_one:
7509		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7510			one->support = 3;
7511			scsi_ulto2b(entry->length, one->cdb_length);
7512			one->cdb_usage[0] = opcode;
7513			memcpy(&one->cdb_usage[1], entry->usage,
7514			    entry->length - 1);
7515		} else
7516			one->support = 1;
7517		break;
7518	}
7519
7520	ctl_set_success(ctsio);
7521	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7522	ctsio->be_move_done = ctl_config_move_done;
7523	ctl_datamove((union ctl_io *)ctsio);
7524	return(retval);
7525}
7526
7527int
7528ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7529{
7530	struct scsi_report_supported_tmf *cdb;
7531	struct scsi_report_supported_tmf_data *data;
7532	int retval;
7533	int alloc_len, total_len;
7534
7535	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7536
7537	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7538
7539	retval = CTL_RETVAL_COMPLETE;
7540
7541	total_len = sizeof(struct scsi_report_supported_tmf_data);
7542	alloc_len = scsi_4btoul(cdb->length);
7543
7544	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7545
7546	ctsio->kern_sg_entries = 0;
7547
7548	if (total_len < alloc_len) {
7549		ctsio->residual = alloc_len - total_len;
7550		ctsio->kern_data_len = total_len;
7551		ctsio->kern_total_len = total_len;
7552	} else {
7553		ctsio->residual = 0;
7554		ctsio->kern_data_len = alloc_len;
7555		ctsio->kern_total_len = alloc_len;
7556	}
7557	ctsio->kern_data_resid = 0;
7558	ctsio->kern_rel_offset = 0;
7559
7560	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7561	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7562	data->byte2 |= RST_ITNRS;
7563
7564	ctl_set_success(ctsio);
7565	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7566	ctsio->be_move_done = ctl_config_move_done;
7567	ctl_datamove((union ctl_io *)ctsio);
7568	return (retval);
7569}
7570
7571int
7572ctl_report_timestamp(struct ctl_scsiio *ctsio)
7573{
7574	struct scsi_report_timestamp *cdb;
7575	struct scsi_report_timestamp_data *data;
7576	struct timeval tv;
7577	int64_t timestamp;
7578	int retval;
7579	int alloc_len, total_len;
7580
7581	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7582
7583	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7584
7585	retval = CTL_RETVAL_COMPLETE;
7586
7587	total_len = sizeof(struct scsi_report_timestamp_data);
7588	alloc_len = scsi_4btoul(cdb->length);
7589
7590	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7591
7592	ctsio->kern_sg_entries = 0;
7593
7594	if (total_len < alloc_len) {
7595		ctsio->residual = alloc_len - total_len;
7596		ctsio->kern_data_len = total_len;
7597		ctsio->kern_total_len = total_len;
7598	} else {
7599		ctsio->residual = 0;
7600		ctsio->kern_data_len = alloc_len;
7601		ctsio->kern_total_len = alloc_len;
7602	}
7603	ctsio->kern_data_resid = 0;
7604	ctsio->kern_rel_offset = 0;
7605
7606	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7607	scsi_ulto2b(sizeof(*data) - 2, data->length);
7608	data->origin = RTS_ORIG_OUTSIDE;
7609	getmicrotime(&tv);
7610	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7611	scsi_ulto4b(timestamp >> 16, data->timestamp);
7612	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7613
7614	ctl_set_success(ctsio);
7615	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7616	ctsio->be_move_done = ctl_config_move_done;
7617	ctl_datamove((union ctl_io *)ctsio);
7618	return (retval);
7619}
7620
7621int
7622ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7623{
7624	struct scsi_per_res_in *cdb;
7625	int alloc_len, total_len = 0;
7626	/* struct scsi_per_res_in_rsrv in_data; */
7627	struct ctl_lun *lun;
7628	struct ctl_softc *softc;
7629	uint64_t key;
7630
7631	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7632
7633	softc = control_softc;
7634
7635	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7636
7637	alloc_len = scsi_2btoul(cdb->length);
7638
7639	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7640
7641retry:
7642	mtx_lock(&lun->lun_lock);
7643	switch (cdb->action) {
7644	case SPRI_RK: /* read keys */
7645		total_len = sizeof(struct scsi_per_res_in_keys) +
7646			lun->pr_key_count *
7647			sizeof(struct scsi_per_res_key);
7648		break;
7649	case SPRI_RR: /* read reservation */
7650		if (lun->flags & CTL_LUN_PR_RESERVED)
7651			total_len = sizeof(struct scsi_per_res_in_rsrv);
7652		else
7653			total_len = sizeof(struct scsi_per_res_in_header);
7654		break;
7655	case SPRI_RC: /* report capabilities */
7656		total_len = sizeof(struct scsi_per_res_cap);
7657		break;
7658	case SPRI_RS: /* read full status */
7659		total_len = sizeof(struct scsi_per_res_in_header) +
7660		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7661		    lun->pr_key_count;
7662		break;
7663	default:
7664		panic("Invalid PR type %x", cdb->action);
7665	}
7666	mtx_unlock(&lun->lun_lock);
7667
7668	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7669
7670	if (total_len < alloc_len) {
7671		ctsio->residual = alloc_len - total_len;
7672		ctsio->kern_data_len = total_len;
7673		ctsio->kern_total_len = total_len;
7674	} else {
7675		ctsio->residual = 0;
7676		ctsio->kern_data_len = alloc_len;
7677		ctsio->kern_total_len = alloc_len;
7678	}
7679
7680	ctsio->kern_data_resid = 0;
7681	ctsio->kern_rel_offset = 0;
7682	ctsio->kern_sg_entries = 0;
7683
7684	mtx_lock(&lun->lun_lock);
7685	switch (cdb->action) {
7686	case SPRI_RK: { // read keys
7687        struct scsi_per_res_in_keys *res_keys;
7688		int i, key_count;
7689
7690		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7691
7692		/*
7693		 * We had to drop the lock to allocate our buffer, which
7694		 * leaves time for someone to come in with another
7695		 * persistent reservation.  (That is unlikely, though,
7696		 * since this should be the only persistent reservation
7697		 * command active right now.)
7698		 */
7699		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7700		    (lun->pr_key_count *
7701		     sizeof(struct scsi_per_res_key)))){
7702			mtx_unlock(&lun->lun_lock);
7703			free(ctsio->kern_data_ptr, M_CTL);
7704			printf("%s: reservation length changed, retrying\n",
7705			       __func__);
7706			goto retry;
7707		}
7708
7709		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7710
7711		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7712			     lun->pr_key_count, res_keys->header.length);
7713
7714		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7715			if ((key = ctl_get_prkey(lun, i)) == 0)
7716				continue;
7717
7718			/*
7719			 * We used lun->pr_key_count to calculate the
7720			 * size to allocate.  If it turns out the number of
7721			 * initiators with the registered flag set is
7722			 * larger than that (i.e. they haven't been kept in
7723			 * sync), we've got a problem.
7724			 */
7725			if (key_count >= lun->pr_key_count) {
7726#ifdef NEEDTOPORT
7727				csevent_log(CSC_CTL | CSC_SHELF_SW |
7728					    CTL_PR_ERROR,
7729					    csevent_LogType_Fault,
7730					    csevent_AlertLevel_Yellow,
7731					    csevent_FRU_ShelfController,
7732					    csevent_FRU_Firmware,
7733				        csevent_FRU_Unknown,
7734					    "registered keys %d >= key "
7735					    "count %d", key_count,
7736					    lun->pr_key_count);
7737#endif
7738				key_count++;
7739				continue;
7740			}
7741			scsi_u64to8b(key, res_keys->keys[key_count].key);
7742			key_count++;
7743		}
7744		break;
7745	}
7746	case SPRI_RR: { // read reservation
7747		struct scsi_per_res_in_rsrv *res;
7748		int tmp_len, header_only;
7749
7750		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7751
7752		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7753
7754		if (lun->flags & CTL_LUN_PR_RESERVED)
7755		{
7756			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7757			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7758				    res->header.length);
7759			header_only = 0;
7760		} else {
7761			tmp_len = sizeof(struct scsi_per_res_in_header);
7762			scsi_ulto4b(0, res->header.length);
7763			header_only = 1;
7764		}
7765
7766		/*
7767		 * We had to drop the lock to allocate our buffer, which
7768		 * leaves time for someone to come in with another
7769		 * persistent reservation.  (That is unlikely, though,
7770		 * since this should be the only persistent reservation
7771		 * command active right now.)
7772		 */
7773		if (tmp_len != total_len) {
7774			mtx_unlock(&lun->lun_lock);
7775			free(ctsio->kern_data_ptr, M_CTL);
7776			printf("%s: reservation status changed, retrying\n",
7777			       __func__);
7778			goto retry;
7779		}
7780
7781		/*
7782		 * No reservation held, so we're done.
7783		 */
7784		if (header_only != 0)
7785			break;
7786
7787		/*
7788		 * If the registration is an All Registrants type, the key
7789		 * is 0, since it doesn't really matter.
7790		 */
7791		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7792			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7793			    res->data.reservation);
7794		}
7795		res->data.scopetype = lun->res_type;
7796		break;
7797	}
7798	case SPRI_RC:     //report capabilities
7799	{
7800		struct scsi_per_res_cap *res_cap;
7801		uint16_t type_mask;
7802
7803		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7804		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7805		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7806		type_mask = SPRI_TM_WR_EX_AR |
7807			    SPRI_TM_EX_AC_RO |
7808			    SPRI_TM_WR_EX_RO |
7809			    SPRI_TM_EX_AC |
7810			    SPRI_TM_WR_EX |
7811			    SPRI_TM_EX_AC_AR;
7812		scsi_ulto2b(type_mask, res_cap->type_mask);
7813		break;
7814	}
7815	case SPRI_RS: { // read full status
7816		struct scsi_per_res_in_full *res_status;
7817		struct scsi_per_res_in_full_desc *res_desc;
7818		struct ctl_port *port;
7819		int i, len;
7820
7821		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7822
7823		/*
7824		 * We had to drop the lock to allocate our buffer, which
7825		 * leaves time for someone to come in with another
7826		 * persistent reservation.  (That is unlikely, though,
7827		 * since this should be the only persistent reservation
7828		 * command active right now.)
7829		 */
7830		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7831		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7832		     lun->pr_key_count)){
7833			mtx_unlock(&lun->lun_lock);
7834			free(ctsio->kern_data_ptr, M_CTL);
7835			printf("%s: reservation length changed, retrying\n",
7836			       __func__);
7837			goto retry;
7838		}
7839
7840		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7841
7842		res_desc = &res_status->desc[0];
7843		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7844			if ((key = ctl_get_prkey(lun, i)) == 0)
7845				continue;
7846
7847			scsi_u64to8b(key, res_desc->res_key.key);
7848			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7849			    (lun->pr_res_idx == i ||
7850			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7851				res_desc->flags = SPRI_FULL_R_HOLDER;
7852				res_desc->scopetype = lun->res_type;
7853			}
7854			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7855			    res_desc->rel_trgt_port_id);
7856			len = 0;
7857			port = softc->ctl_ports[
7858			    ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
7859			if (port != NULL)
7860				len = ctl_create_iid(port,
7861				    i % CTL_MAX_INIT_PER_PORT,
7862				    res_desc->transport_id);
7863			scsi_ulto4b(len, res_desc->additional_length);
7864			res_desc = (struct scsi_per_res_in_full_desc *)
7865			    &res_desc->transport_id[len];
7866		}
7867		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7868		    res_status->header.length);
7869		break;
7870	}
7871	default:
7872		/*
7873		 * This is a bug, because we just checked for this above,
7874		 * and should have returned an error.
7875		 */
7876		panic("Invalid PR type %x", cdb->action);
7877		break; /* NOTREACHED */
7878	}
7879	mtx_unlock(&lun->lun_lock);
7880
7881	ctl_set_success(ctsio);
7882	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7883	ctsio->be_move_done = ctl_config_move_done;
7884	ctl_datamove((union ctl_io *)ctsio);
7885	return (CTL_RETVAL_COMPLETE);
7886}
7887
7888static void
7889ctl_set_res_ua(struct ctl_lun *lun, uint32_t residx, ctl_ua_type ua)
7890{
7891	int off = lun->ctl_softc->persis_offset;
7892
7893	if (residx >= off && residx < off + CTL_MAX_INITIATORS)
7894		lun->pending_ua[residx - off] |= ua;
7895}
7896
7897/*
7898 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7899 * it should return.
7900 */
7901static int
7902ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7903		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7904		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7905		struct scsi_per_res_out_parms* param)
7906{
7907	union ctl_ha_msg persis_io;
7908	int retval, i;
7909	int isc_retval;
7910
7911	retval = 0;
7912
7913	mtx_lock(&lun->lun_lock);
7914	if (sa_res_key == 0) {
7915		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7916			/* validate scope and type */
7917			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7918			     SPR_LU_SCOPE) {
7919				mtx_unlock(&lun->lun_lock);
7920				ctl_set_invalid_field(/*ctsio*/ ctsio,
7921						      /*sks_valid*/ 1,
7922						      /*command*/ 1,
7923						      /*field*/ 2,
7924						      /*bit_valid*/ 1,
7925						      /*bit*/ 4);
7926				ctl_done((union ctl_io *)ctsio);
7927				return (1);
7928			}
7929
7930		        if (type>8 || type==2 || type==4 || type==0) {
7931				mtx_unlock(&lun->lun_lock);
7932				ctl_set_invalid_field(/*ctsio*/ ctsio,
7933       	           				      /*sks_valid*/ 1,
7934						      /*command*/ 1,
7935						      /*field*/ 2,
7936						      /*bit_valid*/ 1,
7937						      /*bit*/ 0);
7938				ctl_done((union ctl_io *)ctsio);
7939				return (1);
7940		        }
7941
7942			/*
7943			 * Unregister everybody else and build UA for
7944			 * them
7945			 */
7946			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7947				if (i == residx || ctl_get_prkey(lun, i) == 0)
7948					continue;
7949
7950				ctl_clr_prkey(lun, i);
7951				ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
7952			}
7953			lun->pr_key_count = 1;
7954			lun->res_type = type;
7955			if (lun->res_type != SPR_TYPE_WR_EX_AR
7956			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7957				lun->pr_res_idx = residx;
7958
7959			/* send msg to other side */
7960			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7961			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7962			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7963			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7964			persis_io.pr.pr_info.res_type = type;
7965			memcpy(persis_io.pr.pr_info.sa_res_key,
7966			       param->serv_act_res_key,
7967			       sizeof(param->serv_act_res_key));
7968			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7969			     &persis_io, sizeof(persis_io), 0)) >
7970			     CTL_HA_STATUS_SUCCESS) {
7971				printf("CTL:Persis Out error returned "
7972				       "from ctl_ha_msg_send %d\n",
7973				       isc_retval);
7974			}
7975		} else {
7976			/* not all registrants */
7977			mtx_unlock(&lun->lun_lock);
7978			free(ctsio->kern_data_ptr, M_CTL);
7979			ctl_set_invalid_field(ctsio,
7980					      /*sks_valid*/ 1,
7981					      /*command*/ 0,
7982					      /*field*/ 8,
7983					      /*bit_valid*/ 0,
7984					      /*bit*/ 0);
7985			ctl_done((union ctl_io *)ctsio);
7986			return (1);
7987		}
7988	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7989		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7990		int found = 0;
7991
7992		if (res_key == sa_res_key) {
7993			/* special case */
7994			/*
7995			 * The spec implies this is not good but doesn't
7996			 * say what to do. There are two choices either
7997			 * generate a res conflict or check condition
7998			 * with illegal field in parameter data. Since
7999			 * that is what is done when the sa_res_key is
8000			 * zero I'll take that approach since this has
8001			 * to do with the sa_res_key.
8002			 */
8003			mtx_unlock(&lun->lun_lock);
8004			free(ctsio->kern_data_ptr, M_CTL);
8005			ctl_set_invalid_field(ctsio,
8006					      /*sks_valid*/ 1,
8007					      /*command*/ 0,
8008					      /*field*/ 8,
8009					      /*bit_valid*/ 0,
8010					      /*bit*/ 0);
8011			ctl_done((union ctl_io *)ctsio);
8012			return (1);
8013		}
8014
8015		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8016			if (ctl_get_prkey(lun, i) != sa_res_key)
8017				continue;
8018
8019			found = 1;
8020			ctl_clr_prkey(lun, i);
8021			lun->pr_key_count--;
8022			ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8023		}
8024		if (!found) {
8025			mtx_unlock(&lun->lun_lock);
8026			free(ctsio->kern_data_ptr, M_CTL);
8027			ctl_set_reservation_conflict(ctsio);
8028			ctl_done((union ctl_io *)ctsio);
8029			return (CTL_RETVAL_COMPLETE);
8030		}
8031		/* send msg to other side */
8032		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8033		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8034		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8035		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8036		persis_io.pr.pr_info.res_type = type;
8037		memcpy(persis_io.pr.pr_info.sa_res_key,
8038		       param->serv_act_res_key,
8039		       sizeof(param->serv_act_res_key));
8040		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8041		     &persis_io, sizeof(persis_io), 0)) >
8042		     CTL_HA_STATUS_SUCCESS) {
8043			printf("CTL:Persis Out error returned from "
8044			       "ctl_ha_msg_send %d\n", isc_retval);
8045		}
8046	} else {
8047		/* Reserved but not all registrants */
8048		/* sa_res_key is res holder */
8049		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
8050			/* validate scope and type */
8051			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8052			     SPR_LU_SCOPE) {
8053				mtx_unlock(&lun->lun_lock);
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 (1);
8062			}
8063
8064			if (type>8 || type==2 || type==4 || type==0) {
8065				mtx_unlock(&lun->lun_lock);
8066				ctl_set_invalid_field(/*ctsio*/ ctsio,
8067						      /*sks_valid*/ 1,
8068						      /*command*/ 1,
8069						      /*field*/ 2,
8070						      /*bit_valid*/ 1,
8071						      /*bit*/ 0);
8072				ctl_done((union ctl_io *)ctsio);
8073				return (1);
8074			}
8075
8076			/*
8077			 * Do the following:
8078			 * if sa_res_key != res_key remove all
8079			 * registrants w/sa_res_key and generate UA
8080			 * for these registrants(Registrations
8081			 * Preempted) if it wasn't an exclusive
8082			 * reservation generate UA(Reservations
8083			 * Preempted) for all other registered nexuses
8084			 * if the type has changed. Establish the new
8085			 * reservation and holder. If res_key and
8086			 * sa_res_key are the same do the above
8087			 * except don't unregister the res holder.
8088			 */
8089
8090			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8091				if (i == residx || ctl_get_prkey(lun, i) == 0)
8092					continue;
8093
8094				if (sa_res_key == ctl_get_prkey(lun, i)) {
8095					ctl_clr_prkey(lun, i);
8096					lun->pr_key_count--;
8097					ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8098				} else if (type != lun->res_type
8099					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8100					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8101					ctl_set_res_ua(lun, i, CTL_UA_RES_RELEASE);
8102				}
8103			}
8104			lun->res_type = type;
8105			if (lun->res_type != SPR_TYPE_WR_EX_AR
8106			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8107				lun->pr_res_idx = residx;
8108			else
8109				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8110
8111			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8112			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8113			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8114			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8115			persis_io.pr.pr_info.res_type = type;
8116			memcpy(persis_io.pr.pr_info.sa_res_key,
8117			       param->serv_act_res_key,
8118			       sizeof(param->serv_act_res_key));
8119			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8120			     &persis_io, sizeof(persis_io), 0)) >
8121			     CTL_HA_STATUS_SUCCESS) {
8122				printf("CTL:Persis Out error returned "
8123				       "from ctl_ha_msg_send %d\n",
8124				       isc_retval);
8125			}
8126		} else {
8127			/*
8128			 * sa_res_key is not the res holder just
8129			 * remove registrants
8130			 */
8131			int found=0;
8132
8133			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8134				if (sa_res_key != ctl_get_prkey(lun, i))
8135					continue;
8136
8137				found = 1;
8138				ctl_clr_prkey(lun, i);
8139				lun->pr_key_count--;
8140				ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8141			}
8142
8143			if (!found) {
8144				mtx_unlock(&lun->lun_lock);
8145				free(ctsio->kern_data_ptr, M_CTL);
8146				ctl_set_reservation_conflict(ctsio);
8147				ctl_done((union ctl_io *)ctsio);
8148		        	return (1);
8149			}
8150			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8151			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8152			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8153			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8154			persis_io.pr.pr_info.res_type = type;
8155			memcpy(persis_io.pr.pr_info.sa_res_key,
8156			       param->serv_act_res_key,
8157			       sizeof(param->serv_act_res_key));
8158			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8159			     &persis_io, sizeof(persis_io), 0)) >
8160			     CTL_HA_STATUS_SUCCESS) {
8161				printf("CTL:Persis Out error returned "
8162				       "from ctl_ha_msg_send %d\n",
8163				isc_retval);
8164			}
8165		}
8166	}
8167
8168	lun->PRGeneration++;
8169	mtx_unlock(&lun->lun_lock);
8170
8171	return (retval);
8172}
8173
8174static void
8175ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8176{
8177	uint64_t sa_res_key;
8178	int i;
8179
8180	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8181
8182	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8183	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8184	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8185		if (sa_res_key == 0) {
8186			/*
8187			 * Unregister everybody else and build UA for
8188			 * them
8189			 */
8190			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8191				if (i == msg->pr.pr_info.residx ||
8192				    ctl_get_prkey(lun, i) == 0)
8193					continue;
8194
8195				ctl_clr_prkey(lun, i);
8196				ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8197			}
8198
8199			lun->pr_key_count = 1;
8200			lun->res_type = msg->pr.pr_info.res_type;
8201			if (lun->res_type != SPR_TYPE_WR_EX_AR
8202			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8203				lun->pr_res_idx = msg->pr.pr_info.residx;
8204		} else {
8205		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8206				if (sa_res_key == ctl_get_prkey(lun, i))
8207					continue;
8208
8209				ctl_clr_prkey(lun, i);
8210				lun->pr_key_count--;
8211				ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8212			}
8213		}
8214	} else {
8215		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8216			if (i == msg->pr.pr_info.residx ||
8217			    ctl_get_prkey(lun, i) == 0)
8218				continue;
8219
8220			if (sa_res_key == ctl_get_prkey(lun, i)) {
8221				ctl_clr_prkey(lun, i);
8222				lun->pr_key_count--;
8223				ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8224			} else if (msg->pr.pr_info.res_type != lun->res_type
8225				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8226				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8227				ctl_set_res_ua(lun, i, CTL_UA_RES_RELEASE);
8228			}
8229		}
8230		lun->res_type = msg->pr.pr_info.res_type;
8231		if (lun->res_type != SPR_TYPE_WR_EX_AR
8232		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8233			lun->pr_res_idx = msg->pr.pr_info.residx;
8234		else
8235			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8236	}
8237	lun->PRGeneration++;
8238
8239}
8240
8241
8242int
8243ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8244{
8245	int retval;
8246	int isc_retval;
8247	u_int32_t param_len;
8248	struct scsi_per_res_out *cdb;
8249	struct ctl_lun *lun;
8250	struct scsi_per_res_out_parms* param;
8251	struct ctl_softc *softc;
8252	uint32_t residx;
8253	uint64_t res_key, sa_res_key, key;
8254	uint8_t type;
8255	union ctl_ha_msg persis_io;
8256	int    i;
8257
8258	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8259
8260	retval = CTL_RETVAL_COMPLETE;
8261
8262	softc = control_softc;
8263
8264	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8265	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8266
8267	/*
8268	 * We only support whole-LUN scope.  The scope & type are ignored for
8269	 * register, register and ignore existing key and clear.
8270	 * We sometimes ignore scope and type on preempts too!!
8271	 * Verify reservation type here as well.
8272	 */
8273	type = cdb->scope_type & SPR_TYPE_MASK;
8274	if ((cdb->action == SPRO_RESERVE)
8275	 || (cdb->action == SPRO_RELEASE)) {
8276		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8277			ctl_set_invalid_field(/*ctsio*/ ctsio,
8278					      /*sks_valid*/ 1,
8279					      /*command*/ 1,
8280					      /*field*/ 2,
8281					      /*bit_valid*/ 1,
8282					      /*bit*/ 4);
8283			ctl_done((union ctl_io *)ctsio);
8284			return (CTL_RETVAL_COMPLETE);
8285		}
8286
8287		if (type>8 || type==2 || type==4 || type==0) {
8288			ctl_set_invalid_field(/*ctsio*/ ctsio,
8289					      /*sks_valid*/ 1,
8290					      /*command*/ 1,
8291					      /*field*/ 2,
8292					      /*bit_valid*/ 1,
8293					      /*bit*/ 0);
8294			ctl_done((union ctl_io *)ctsio);
8295			return (CTL_RETVAL_COMPLETE);
8296		}
8297	}
8298
8299	param_len = scsi_4btoul(cdb->length);
8300
8301	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8302		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8303		ctsio->kern_data_len = param_len;
8304		ctsio->kern_total_len = param_len;
8305		ctsio->kern_data_resid = 0;
8306		ctsio->kern_rel_offset = 0;
8307		ctsio->kern_sg_entries = 0;
8308		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8309		ctsio->be_move_done = ctl_config_move_done;
8310		ctl_datamove((union ctl_io *)ctsio);
8311
8312		return (CTL_RETVAL_COMPLETE);
8313	}
8314
8315	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8316
8317	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8318	res_key = scsi_8btou64(param->res_key.key);
8319	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8320
8321	/*
8322	 * Validate the reservation key here except for SPRO_REG_IGNO
8323	 * This must be done for all other service actions
8324	 */
8325	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8326		mtx_lock(&lun->lun_lock);
8327		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8328			if (res_key != key) {
8329				/*
8330				 * The current key passed in doesn't match
8331				 * the one the initiator previously
8332				 * registered.
8333				 */
8334				mtx_unlock(&lun->lun_lock);
8335				free(ctsio->kern_data_ptr, M_CTL);
8336				ctl_set_reservation_conflict(ctsio);
8337				ctl_done((union ctl_io *)ctsio);
8338				return (CTL_RETVAL_COMPLETE);
8339			}
8340		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8341			/*
8342			 * We are not registered
8343			 */
8344			mtx_unlock(&lun->lun_lock);
8345			free(ctsio->kern_data_ptr, M_CTL);
8346			ctl_set_reservation_conflict(ctsio);
8347			ctl_done((union ctl_io *)ctsio);
8348			return (CTL_RETVAL_COMPLETE);
8349		} else if (res_key != 0) {
8350			/*
8351			 * We are not registered and trying to register but
8352			 * the register key isn't zero.
8353			 */
8354			mtx_unlock(&lun->lun_lock);
8355			free(ctsio->kern_data_ptr, M_CTL);
8356			ctl_set_reservation_conflict(ctsio);
8357			ctl_done((union ctl_io *)ctsio);
8358			return (CTL_RETVAL_COMPLETE);
8359		}
8360		mtx_unlock(&lun->lun_lock);
8361	}
8362
8363	switch (cdb->action & SPRO_ACTION_MASK) {
8364	case SPRO_REGISTER:
8365	case SPRO_REG_IGNO: {
8366
8367#if 0
8368		printf("Registration received\n");
8369#endif
8370
8371		/*
8372		 * We don't support any of these options, as we report in
8373		 * the read capabilities request (see
8374		 * ctl_persistent_reserve_in(), above).
8375		 */
8376		if ((param->flags & SPR_SPEC_I_PT)
8377		 || (param->flags & SPR_ALL_TG_PT)
8378		 || (param->flags & SPR_APTPL)) {
8379			int bit_ptr;
8380
8381			if (param->flags & SPR_APTPL)
8382				bit_ptr = 0;
8383			else if (param->flags & SPR_ALL_TG_PT)
8384				bit_ptr = 2;
8385			else /* SPR_SPEC_I_PT */
8386				bit_ptr = 3;
8387
8388			free(ctsio->kern_data_ptr, M_CTL);
8389			ctl_set_invalid_field(ctsio,
8390					      /*sks_valid*/ 1,
8391					      /*command*/ 0,
8392					      /*field*/ 20,
8393					      /*bit_valid*/ 1,
8394					      /*bit*/ bit_ptr);
8395			ctl_done((union ctl_io *)ctsio);
8396			return (CTL_RETVAL_COMPLETE);
8397		}
8398
8399		mtx_lock(&lun->lun_lock);
8400
8401		/*
8402		 * The initiator wants to clear the
8403		 * key/unregister.
8404		 */
8405		if (sa_res_key == 0) {
8406			if ((res_key == 0
8407			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8408			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8409			  && ctl_get_prkey(lun, residx) == 0)) {
8410				mtx_unlock(&lun->lun_lock);
8411				goto done;
8412			}
8413
8414			ctl_clr_prkey(lun, residx);
8415			lun->pr_key_count--;
8416
8417			if (residx == lun->pr_res_idx) {
8418				lun->flags &= ~CTL_LUN_PR_RESERVED;
8419				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8420
8421				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8422				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8423				 && lun->pr_key_count) {
8424					/*
8425					 * If the reservation is a registrants
8426					 * only type we need to generate a UA
8427					 * for other registered inits.  The
8428					 * sense code should be RESERVATIONS
8429					 * RELEASED
8430					 */
8431
8432					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8433						if (ctl_get_prkey(lun, i +
8434						    softc->persis_offset) == 0)
8435							continue;
8436						lun->pending_ua[i] |=
8437							CTL_UA_RES_RELEASE;
8438					}
8439				}
8440				lun->res_type = 0;
8441			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8442				if (lun->pr_key_count==0) {
8443					lun->flags &= ~CTL_LUN_PR_RESERVED;
8444					lun->res_type = 0;
8445					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8446				}
8447			}
8448			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8449			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8450			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8451			persis_io.pr.pr_info.residx = residx;
8452			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8453			     &persis_io, sizeof(persis_io), 0 )) >
8454			     CTL_HA_STATUS_SUCCESS) {
8455				printf("CTL:Persis Out error returned from "
8456				       "ctl_ha_msg_send %d\n", isc_retval);
8457			}
8458		} else /* sa_res_key != 0 */ {
8459
8460			/*
8461			 * If we aren't registered currently then increment
8462			 * the key count and set the registered flag.
8463			 */
8464			ctl_alloc_prkey(lun, residx);
8465			if (ctl_get_prkey(lun, residx) == 0)
8466				lun->pr_key_count++;
8467			ctl_set_prkey(lun, residx, sa_res_key);
8468
8469			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8470			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8471			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8472			persis_io.pr.pr_info.residx = residx;
8473			memcpy(persis_io.pr.pr_info.sa_res_key,
8474			       param->serv_act_res_key,
8475			       sizeof(param->serv_act_res_key));
8476			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8477			     &persis_io, sizeof(persis_io), 0)) >
8478			     CTL_HA_STATUS_SUCCESS) {
8479				printf("CTL:Persis Out error returned from "
8480				       "ctl_ha_msg_send %d\n", isc_retval);
8481			}
8482		}
8483		lun->PRGeneration++;
8484		mtx_unlock(&lun->lun_lock);
8485
8486		break;
8487	}
8488	case SPRO_RESERVE:
8489#if 0
8490                printf("Reserve executed type %d\n", type);
8491#endif
8492		mtx_lock(&lun->lun_lock);
8493		if (lun->flags & CTL_LUN_PR_RESERVED) {
8494			/*
8495			 * if this isn't the reservation holder and it's
8496			 * not a "all registrants" type or if the type is
8497			 * different then we have a conflict
8498			 */
8499			if ((lun->pr_res_idx != residx
8500			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8501			 || lun->res_type != type) {
8502				mtx_unlock(&lun->lun_lock);
8503				free(ctsio->kern_data_ptr, M_CTL);
8504				ctl_set_reservation_conflict(ctsio);
8505				ctl_done((union ctl_io *)ctsio);
8506				return (CTL_RETVAL_COMPLETE);
8507			}
8508			mtx_unlock(&lun->lun_lock);
8509		} else /* create a reservation */ {
8510			/*
8511			 * If it's not an "all registrants" type record
8512			 * reservation holder
8513			 */
8514			if (type != SPR_TYPE_WR_EX_AR
8515			 && type != SPR_TYPE_EX_AC_AR)
8516				lun->pr_res_idx = residx; /* Res holder */
8517			else
8518				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8519
8520			lun->flags |= CTL_LUN_PR_RESERVED;
8521			lun->res_type = type;
8522
8523			mtx_unlock(&lun->lun_lock);
8524
8525			/* send msg to other side */
8526			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8527			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8528			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8529			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8530			persis_io.pr.pr_info.res_type = type;
8531			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8532			     &persis_io, sizeof(persis_io), 0)) >
8533			     CTL_HA_STATUS_SUCCESS) {
8534				printf("CTL:Persis Out error returned from "
8535				       "ctl_ha_msg_send %d\n", isc_retval);
8536			}
8537		}
8538		break;
8539
8540	case SPRO_RELEASE:
8541		mtx_lock(&lun->lun_lock);
8542		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8543			/* No reservation exists return good status */
8544			mtx_unlock(&lun->lun_lock);
8545			goto done;
8546		}
8547		/*
8548		 * Is this nexus a reservation holder?
8549		 */
8550		if (lun->pr_res_idx != residx
8551		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8552			/*
8553			 * not a res holder return good status but
8554			 * do nothing
8555			 */
8556			mtx_unlock(&lun->lun_lock);
8557			goto done;
8558		}
8559
8560		if (lun->res_type != type) {
8561			mtx_unlock(&lun->lun_lock);
8562			free(ctsio->kern_data_ptr, M_CTL);
8563			ctl_set_illegal_pr_release(ctsio);
8564			ctl_done((union ctl_io *)ctsio);
8565			return (CTL_RETVAL_COMPLETE);
8566		}
8567
8568		/* okay to release */
8569		lun->flags &= ~CTL_LUN_PR_RESERVED;
8570		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8571		lun->res_type = 0;
8572
8573		/*
8574		 * if this isn't an exclusive access
8575		 * res generate UA for all other
8576		 * registrants.
8577		 */
8578		if (type != SPR_TYPE_EX_AC
8579		 && type != SPR_TYPE_WR_EX) {
8580			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8581				if (i == residx ||
8582				    ctl_get_prkey(lun,
8583				     i + softc->persis_offset) == 0)
8584					continue;
8585				lun->pending_ua[i] |= CTL_UA_RES_RELEASE;
8586			}
8587		}
8588		mtx_unlock(&lun->lun_lock);
8589		/* Send msg to other side */
8590		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8591		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8592		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8593		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8594		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8595			printf("CTL:Persis Out error returned from "
8596			       "ctl_ha_msg_send %d\n", isc_retval);
8597		}
8598		break;
8599
8600	case SPRO_CLEAR:
8601		/* send msg to other side */
8602
8603		mtx_lock(&lun->lun_lock);
8604		lun->flags &= ~CTL_LUN_PR_RESERVED;
8605		lun->res_type = 0;
8606		lun->pr_key_count = 0;
8607		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8608
8609		ctl_clr_prkey(lun, residx);
8610		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8611			if (ctl_get_prkey(lun, i) != 0) {
8612				ctl_clr_prkey(lun, i);
8613				ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8614			}
8615		lun->PRGeneration++;
8616		mtx_unlock(&lun->lun_lock);
8617		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8618		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8619		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8620		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8621		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8622			printf("CTL:Persis Out error returned from "
8623			       "ctl_ha_msg_send %d\n", isc_retval);
8624		}
8625		break;
8626
8627	case SPRO_PREEMPT:
8628	case SPRO_PRE_ABO: {
8629		int nretval;
8630
8631		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8632					  residx, ctsio, cdb, param);
8633		if (nretval != 0)
8634			return (CTL_RETVAL_COMPLETE);
8635		break;
8636	}
8637	default:
8638		panic("Invalid PR type %x", cdb->action);
8639	}
8640
8641done:
8642	free(ctsio->kern_data_ptr, M_CTL);
8643	ctl_set_success(ctsio);
8644	ctl_done((union ctl_io *)ctsio);
8645
8646	return (retval);
8647}
8648
8649/*
8650 * This routine is for handling a message from the other SC pertaining to
8651 * persistent reserve out. All the error checking will have been done
8652 * so only perorming the action need be done here to keep the two
8653 * in sync.
8654 */
8655static void
8656ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8657{
8658	struct ctl_lun *lun;
8659	struct ctl_softc *softc;
8660	int i;
8661	uint32_t targ_lun;
8662
8663	softc = control_softc;
8664
8665	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8666	lun = softc->ctl_luns[targ_lun];
8667	mtx_lock(&lun->lun_lock);
8668	switch(msg->pr.pr_info.action) {
8669	case CTL_PR_REG_KEY:
8670		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8671		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8672			lun->pr_key_count++;
8673		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8674		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8675		lun->PRGeneration++;
8676		break;
8677
8678	case CTL_PR_UNREG_KEY:
8679		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8680		lun->pr_key_count--;
8681
8682		/* XXX Need to see if the reservation has been released */
8683		/* if so do we need to generate UA? */
8684		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8685			lun->flags &= ~CTL_LUN_PR_RESERVED;
8686			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8687
8688			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8689			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8690			 && lun->pr_key_count) {
8691				/*
8692				 * If the reservation is a registrants
8693				 * only type we need to generate a UA
8694				 * for other registered inits.  The
8695				 * sense code should be RESERVATIONS
8696				 * RELEASED
8697				 */
8698
8699				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8700					if (ctl_get_prkey(lun, i +
8701					    softc->persis_offset) == 0)
8702						continue;
8703
8704					lun->pending_ua[i] |=
8705						CTL_UA_RES_RELEASE;
8706				}
8707			}
8708			lun->res_type = 0;
8709		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8710			if (lun->pr_key_count==0) {
8711				lun->flags &= ~CTL_LUN_PR_RESERVED;
8712				lun->res_type = 0;
8713				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8714			}
8715		}
8716		lun->PRGeneration++;
8717		break;
8718
8719	case CTL_PR_RESERVE:
8720		lun->flags |= CTL_LUN_PR_RESERVED;
8721		lun->res_type = msg->pr.pr_info.res_type;
8722		lun->pr_res_idx = msg->pr.pr_info.residx;
8723
8724		break;
8725
8726	case CTL_PR_RELEASE:
8727		/*
8728		 * if this isn't an exclusive access res generate UA for all
8729		 * other registrants.
8730		 */
8731		if (lun->res_type != SPR_TYPE_EX_AC
8732		 && lun->res_type != SPR_TYPE_WR_EX) {
8733			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8734				if (ctl_get_prkey(lun, i + softc->persis_offset) != 0)
8735					lun->pending_ua[i] |=
8736						CTL_UA_RES_RELEASE;
8737		}
8738
8739		lun->flags &= ~CTL_LUN_PR_RESERVED;
8740		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8741		lun->res_type = 0;
8742		break;
8743
8744	case CTL_PR_PREEMPT:
8745		ctl_pro_preempt_other(lun, msg);
8746		break;
8747	case CTL_PR_CLEAR:
8748		lun->flags &= ~CTL_LUN_PR_RESERVED;
8749		lun->res_type = 0;
8750		lun->pr_key_count = 0;
8751		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8752
8753		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8754			if (ctl_get_prkey(lun, i) == 0)
8755				continue;
8756			ctl_clr_prkey(lun, i);
8757			ctl_set_res_ua(lun, i, CTL_UA_REG_PREEMPT);
8758		}
8759		lun->PRGeneration++;
8760		break;
8761	}
8762
8763	mtx_unlock(&lun->lun_lock);
8764}
8765
8766int
8767ctl_read_write(struct ctl_scsiio *ctsio)
8768{
8769	struct ctl_lun *lun;
8770	struct ctl_lba_len_flags *lbalen;
8771	uint64_t lba;
8772	uint32_t num_blocks;
8773	int flags, retval;
8774	int isread;
8775
8776	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8777
8778	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8779
8780	flags = 0;
8781	retval = CTL_RETVAL_COMPLETE;
8782
8783	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8784	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8785	switch (ctsio->cdb[0]) {
8786	case READ_6:
8787	case WRITE_6: {
8788		struct scsi_rw_6 *cdb;
8789
8790		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8791
8792		lba = scsi_3btoul(cdb->addr);
8793		/* only 5 bits are valid in the most significant address byte */
8794		lba &= 0x1fffff;
8795		num_blocks = cdb->length;
8796		/*
8797		 * This is correct according to SBC-2.
8798		 */
8799		if (num_blocks == 0)
8800			num_blocks = 256;
8801		break;
8802	}
8803	case READ_10:
8804	case WRITE_10: {
8805		struct scsi_rw_10 *cdb;
8806
8807		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8808		if (cdb->byte2 & SRW10_FUA)
8809			flags |= CTL_LLF_FUA;
8810		if (cdb->byte2 & SRW10_DPO)
8811			flags |= CTL_LLF_DPO;
8812		lba = scsi_4btoul(cdb->addr);
8813		num_blocks = scsi_2btoul(cdb->length);
8814		break;
8815	}
8816	case WRITE_VERIFY_10: {
8817		struct scsi_write_verify_10 *cdb;
8818
8819		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8820		flags |= CTL_LLF_FUA;
8821		if (cdb->byte2 & SWV_DPO)
8822			flags |= CTL_LLF_DPO;
8823		lba = scsi_4btoul(cdb->addr);
8824		num_blocks = scsi_2btoul(cdb->length);
8825		break;
8826	}
8827	case READ_12:
8828	case WRITE_12: {
8829		struct scsi_rw_12 *cdb;
8830
8831		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8832		if (cdb->byte2 & SRW12_FUA)
8833			flags |= CTL_LLF_FUA;
8834		if (cdb->byte2 & SRW12_DPO)
8835			flags |= CTL_LLF_DPO;
8836		lba = scsi_4btoul(cdb->addr);
8837		num_blocks = scsi_4btoul(cdb->length);
8838		break;
8839	}
8840	case WRITE_VERIFY_12: {
8841		struct scsi_write_verify_12 *cdb;
8842
8843		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8844		flags |= CTL_LLF_FUA;
8845		if (cdb->byte2 & SWV_DPO)
8846			flags |= CTL_LLF_DPO;
8847		lba = scsi_4btoul(cdb->addr);
8848		num_blocks = scsi_4btoul(cdb->length);
8849		break;
8850	}
8851	case READ_16:
8852	case WRITE_16: {
8853		struct scsi_rw_16 *cdb;
8854
8855		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8856		if (cdb->byte2 & SRW12_FUA)
8857			flags |= CTL_LLF_FUA;
8858		if (cdb->byte2 & SRW12_DPO)
8859			flags |= CTL_LLF_DPO;
8860		lba = scsi_8btou64(cdb->addr);
8861		num_blocks = scsi_4btoul(cdb->length);
8862		break;
8863	}
8864	case WRITE_ATOMIC_16: {
8865		struct scsi_rw_16 *cdb;
8866
8867		if (lun->be_lun->atomicblock == 0) {
8868			ctl_set_invalid_opcode(ctsio);
8869			ctl_done((union ctl_io *)ctsio);
8870			return (CTL_RETVAL_COMPLETE);
8871		}
8872
8873		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8874		if (cdb->byte2 & SRW12_FUA)
8875			flags |= CTL_LLF_FUA;
8876		if (cdb->byte2 & SRW12_DPO)
8877			flags |= CTL_LLF_DPO;
8878		lba = scsi_8btou64(cdb->addr);
8879		num_blocks = scsi_4btoul(cdb->length);
8880		if (num_blocks > lun->be_lun->atomicblock) {
8881			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8882			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8883			    /*bit*/ 0);
8884			ctl_done((union ctl_io *)ctsio);
8885			return (CTL_RETVAL_COMPLETE);
8886		}
8887		break;
8888	}
8889	case WRITE_VERIFY_16: {
8890		struct scsi_write_verify_16 *cdb;
8891
8892		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8893		flags |= CTL_LLF_FUA;
8894		if (cdb->byte2 & SWV_DPO)
8895			flags |= CTL_LLF_DPO;
8896		lba = scsi_8btou64(cdb->addr);
8897		num_blocks = scsi_4btoul(cdb->length);
8898		break;
8899	}
8900	default:
8901		/*
8902		 * We got a command we don't support.  This shouldn't
8903		 * happen, commands should be filtered out above us.
8904		 */
8905		ctl_set_invalid_opcode(ctsio);
8906		ctl_done((union ctl_io *)ctsio);
8907
8908		return (CTL_RETVAL_COMPLETE);
8909		break; /* NOTREACHED */
8910	}
8911
8912	/*
8913	 * The first check is to make sure we're in bounds, the second
8914	 * check is to catch wrap-around problems.  If the lba + num blocks
8915	 * is less than the lba, then we've wrapped around and the block
8916	 * range is invalid anyway.
8917	 */
8918	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8919	 || ((lba + num_blocks) < lba)) {
8920		ctl_set_lba_out_of_range(ctsio);
8921		ctl_done((union ctl_io *)ctsio);
8922		return (CTL_RETVAL_COMPLETE);
8923	}
8924
8925	/*
8926	 * According to SBC-3, a transfer length of 0 is not an error.
8927	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8928	 * translates to 256 blocks for those commands.
8929	 */
8930	if (num_blocks == 0) {
8931		ctl_set_success(ctsio);
8932		ctl_done((union ctl_io *)ctsio);
8933		return (CTL_RETVAL_COMPLETE);
8934	}
8935
8936	/* Set FUA and/or DPO if caches are disabled. */
8937	if (isread) {
8938		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8939		    SCP_RCD) != 0)
8940			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8941	} else {
8942		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8943		    SCP_WCE) == 0)
8944			flags |= CTL_LLF_FUA;
8945	}
8946
8947	lbalen = (struct ctl_lba_len_flags *)
8948	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8949	lbalen->lba = lba;
8950	lbalen->len = num_blocks;
8951	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8952
8953	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8954	ctsio->kern_rel_offset = 0;
8955
8956	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8957
8958	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8959
8960	return (retval);
8961}
8962
8963static int
8964ctl_cnw_cont(union ctl_io *io)
8965{
8966	struct ctl_scsiio *ctsio;
8967	struct ctl_lun *lun;
8968	struct ctl_lba_len_flags *lbalen;
8969	int retval;
8970
8971	ctsio = &io->scsiio;
8972	ctsio->io_hdr.status = CTL_STATUS_NONE;
8973	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8974	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8975	lbalen = (struct ctl_lba_len_flags *)
8976	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8977	lbalen->flags &= ~CTL_LLF_COMPARE;
8978	lbalen->flags |= CTL_LLF_WRITE;
8979
8980	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8981	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8982	return (retval);
8983}
8984
8985int
8986ctl_cnw(struct ctl_scsiio *ctsio)
8987{
8988	struct ctl_lun *lun;
8989	struct ctl_lba_len_flags *lbalen;
8990	uint64_t lba;
8991	uint32_t num_blocks;
8992	int flags, retval;
8993
8994	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8995
8996	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8997
8998	flags = 0;
8999	retval = CTL_RETVAL_COMPLETE;
9000
9001	switch (ctsio->cdb[0]) {
9002	case COMPARE_AND_WRITE: {
9003		struct scsi_compare_and_write *cdb;
9004
9005		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9006		if (cdb->byte2 & SRW10_FUA)
9007			flags |= CTL_LLF_FUA;
9008		if (cdb->byte2 & SRW10_DPO)
9009			flags |= CTL_LLF_DPO;
9010		lba = scsi_8btou64(cdb->addr);
9011		num_blocks = cdb->length;
9012		break;
9013	}
9014	default:
9015		/*
9016		 * We got a command we don't support.  This shouldn't
9017		 * happen, commands should be filtered out above us.
9018		 */
9019		ctl_set_invalid_opcode(ctsio);
9020		ctl_done((union ctl_io *)ctsio);
9021
9022		return (CTL_RETVAL_COMPLETE);
9023		break; /* NOTREACHED */
9024	}
9025
9026	/*
9027	 * The first check is to make sure we're in bounds, the second
9028	 * check is to catch wrap-around problems.  If the lba + num blocks
9029	 * is less than the lba, then we've wrapped around and the block
9030	 * range is invalid anyway.
9031	 */
9032	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9033	 || ((lba + num_blocks) < lba)) {
9034		ctl_set_lba_out_of_range(ctsio);
9035		ctl_done((union ctl_io *)ctsio);
9036		return (CTL_RETVAL_COMPLETE);
9037	}
9038
9039	/*
9040	 * According to SBC-3, a transfer length of 0 is not an error.
9041	 */
9042	if (num_blocks == 0) {
9043		ctl_set_success(ctsio);
9044		ctl_done((union ctl_io *)ctsio);
9045		return (CTL_RETVAL_COMPLETE);
9046	}
9047
9048	/* Set FUA if write cache is disabled. */
9049	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9050	    SCP_WCE) == 0)
9051		flags |= CTL_LLF_FUA;
9052
9053	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9054	ctsio->kern_rel_offset = 0;
9055
9056	/*
9057	 * Set the IO_CONT flag, so that if this I/O gets passed to
9058	 * ctl_data_submit_done(), it'll get passed back to
9059	 * ctl_ctl_cnw_cont() for further processing.
9060	 */
9061	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9062	ctsio->io_cont = ctl_cnw_cont;
9063
9064	lbalen = (struct ctl_lba_len_flags *)
9065	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9066	lbalen->lba = lba;
9067	lbalen->len = num_blocks;
9068	lbalen->flags = CTL_LLF_COMPARE | flags;
9069
9070	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9071	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9072	return (retval);
9073}
9074
9075int
9076ctl_verify(struct ctl_scsiio *ctsio)
9077{
9078	struct ctl_lun *lun;
9079	struct ctl_lba_len_flags *lbalen;
9080	uint64_t lba;
9081	uint32_t num_blocks;
9082	int bytchk, flags;
9083	int retval;
9084
9085	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9086
9087	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9088
9089	bytchk = 0;
9090	flags = CTL_LLF_FUA;
9091	retval = CTL_RETVAL_COMPLETE;
9092
9093	switch (ctsio->cdb[0]) {
9094	case VERIFY_10: {
9095		struct scsi_verify_10 *cdb;
9096
9097		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9098		if (cdb->byte2 & SVFY_BYTCHK)
9099			bytchk = 1;
9100		if (cdb->byte2 & SVFY_DPO)
9101			flags |= CTL_LLF_DPO;
9102		lba = scsi_4btoul(cdb->addr);
9103		num_blocks = scsi_2btoul(cdb->length);
9104		break;
9105	}
9106	case VERIFY_12: {
9107		struct scsi_verify_12 *cdb;
9108
9109		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9110		if (cdb->byte2 & SVFY_BYTCHK)
9111			bytchk = 1;
9112		if (cdb->byte2 & SVFY_DPO)
9113			flags |= CTL_LLF_DPO;
9114		lba = scsi_4btoul(cdb->addr);
9115		num_blocks = scsi_4btoul(cdb->length);
9116		break;
9117	}
9118	case VERIFY_16: {
9119		struct scsi_rw_16 *cdb;
9120
9121		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9122		if (cdb->byte2 & SVFY_BYTCHK)
9123			bytchk = 1;
9124		if (cdb->byte2 & SVFY_DPO)
9125			flags |= CTL_LLF_DPO;
9126		lba = scsi_8btou64(cdb->addr);
9127		num_blocks = scsi_4btoul(cdb->length);
9128		break;
9129	}
9130	default:
9131		/*
9132		 * We got a command we don't support.  This shouldn't
9133		 * happen, commands should be filtered out above us.
9134		 */
9135		ctl_set_invalid_opcode(ctsio);
9136		ctl_done((union ctl_io *)ctsio);
9137		return (CTL_RETVAL_COMPLETE);
9138	}
9139
9140	/*
9141	 * The first check is to make sure we're in bounds, the second
9142	 * check is to catch wrap-around problems.  If the lba + num blocks
9143	 * is less than the lba, then we've wrapped around and the block
9144	 * range is invalid anyway.
9145	 */
9146	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9147	 || ((lba + num_blocks) < lba)) {
9148		ctl_set_lba_out_of_range(ctsio);
9149		ctl_done((union ctl_io *)ctsio);
9150		return (CTL_RETVAL_COMPLETE);
9151	}
9152
9153	/*
9154	 * According to SBC-3, a transfer length of 0 is not an error.
9155	 */
9156	if (num_blocks == 0) {
9157		ctl_set_success(ctsio);
9158		ctl_done((union ctl_io *)ctsio);
9159		return (CTL_RETVAL_COMPLETE);
9160	}
9161
9162	lbalen = (struct ctl_lba_len_flags *)
9163	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9164	lbalen->lba = lba;
9165	lbalen->len = num_blocks;
9166	if (bytchk) {
9167		lbalen->flags = CTL_LLF_COMPARE | flags;
9168		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9169	} else {
9170		lbalen->flags = CTL_LLF_VERIFY | flags;
9171		ctsio->kern_total_len = 0;
9172	}
9173	ctsio->kern_rel_offset = 0;
9174
9175	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9176	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9177	return (retval);
9178}
9179
9180int
9181ctl_report_luns(struct ctl_scsiio *ctsio)
9182{
9183	struct scsi_report_luns *cdb;
9184	struct scsi_report_luns_data *lun_data;
9185	struct ctl_lun *lun, *request_lun;
9186	int num_luns, retval;
9187	uint32_t alloc_len, lun_datalen;
9188	int num_filled, well_known;
9189	uint32_t initidx, targ_lun_id, lun_id;
9190
9191	retval = CTL_RETVAL_COMPLETE;
9192	well_known = 0;
9193
9194	cdb = (struct scsi_report_luns *)ctsio->cdb;
9195
9196	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9197
9198	mtx_lock(&control_softc->ctl_lock);
9199	num_luns = control_softc->num_luns;
9200	mtx_unlock(&control_softc->ctl_lock);
9201
9202	switch (cdb->select_report) {
9203	case RPL_REPORT_DEFAULT:
9204	case RPL_REPORT_ALL:
9205		break;
9206	case RPL_REPORT_WELLKNOWN:
9207		well_known = 1;
9208		num_luns = 0;
9209		break;
9210	default:
9211		ctl_set_invalid_field(ctsio,
9212				      /*sks_valid*/ 1,
9213				      /*command*/ 1,
9214				      /*field*/ 2,
9215				      /*bit_valid*/ 0,
9216				      /*bit*/ 0);
9217		ctl_done((union ctl_io *)ctsio);
9218		return (retval);
9219		break; /* NOTREACHED */
9220	}
9221
9222	alloc_len = scsi_4btoul(cdb->length);
9223	/*
9224	 * The initiator has to allocate at least 16 bytes for this request,
9225	 * so he can at least get the header and the first LUN.  Otherwise
9226	 * we reject the request (per SPC-3 rev 14, section 6.21).
9227	 */
9228	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9229	    sizeof(struct scsi_report_luns_lundata))) {
9230		ctl_set_invalid_field(ctsio,
9231				      /*sks_valid*/ 1,
9232				      /*command*/ 1,
9233				      /*field*/ 6,
9234				      /*bit_valid*/ 0,
9235				      /*bit*/ 0);
9236		ctl_done((union ctl_io *)ctsio);
9237		return (retval);
9238	}
9239
9240	request_lun = (struct ctl_lun *)
9241		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9242
9243	lun_datalen = sizeof(*lun_data) +
9244		(num_luns * sizeof(struct scsi_report_luns_lundata));
9245
9246	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9247	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9248	ctsio->kern_sg_entries = 0;
9249
9250	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9251
9252	mtx_lock(&control_softc->ctl_lock);
9253	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9254		lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9255		if (lun_id >= CTL_MAX_LUNS)
9256			continue;
9257		lun = control_softc->ctl_luns[lun_id];
9258		if (lun == NULL)
9259			continue;
9260
9261		if (targ_lun_id <= 0xff) {
9262			/*
9263			 * Peripheral addressing method, bus number 0.
9264			 */
9265			lun_data->luns[num_filled].lundata[0] =
9266				RPL_LUNDATA_ATYP_PERIPH;
9267			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9268			num_filled++;
9269		} else if (targ_lun_id <= 0x3fff) {
9270			/*
9271			 * Flat addressing method.
9272			 */
9273			lun_data->luns[num_filled].lundata[0] =
9274				RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9275			lun_data->luns[num_filled].lundata[1] =
9276				(targ_lun_id & 0xff);
9277			num_filled++;
9278		} else if (targ_lun_id <= 0xffffff) {
9279			/*
9280			 * Extended flat addressing method.
9281			 */
9282			lun_data->luns[num_filled].lundata[0] =
9283			    RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9284			scsi_ulto3b(targ_lun_id,
9285			    &lun_data->luns[num_filled].lundata[1]);
9286			num_filled++;
9287		} else {
9288			printf("ctl_report_luns: bogus LUN number %jd, "
9289			       "skipping\n", (intmax_t)targ_lun_id);
9290		}
9291		/*
9292		 * According to SPC-3, rev 14 section 6.21:
9293		 *
9294		 * "The execution of a REPORT LUNS command to any valid and
9295		 * installed logical unit shall clear the REPORTED LUNS DATA
9296		 * HAS CHANGED unit attention condition for all logical
9297		 * units of that target with respect to the requesting
9298		 * initiator. A valid and installed logical unit is one
9299		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9300		 * INQUIRY data (see 6.4.2)."
9301		 *
9302		 * If request_lun is NULL, the LUN this report luns command
9303		 * was issued to is either disabled or doesn't exist. In that
9304		 * case, we shouldn't clear any pending lun change unit
9305		 * attention.
9306		 */
9307		if (request_lun != NULL) {
9308			mtx_lock(&lun->lun_lock);
9309			lun->pending_ua[initidx] &= ~CTL_UA_LUN_CHANGE;
9310			mtx_unlock(&lun->lun_lock);
9311		}
9312	}
9313	mtx_unlock(&control_softc->ctl_lock);
9314
9315	/*
9316	 * It's quite possible that we've returned fewer LUNs than we allocated
9317	 * space for.  Trim it.
9318	 */
9319	lun_datalen = sizeof(*lun_data) +
9320		(num_filled * sizeof(struct scsi_report_luns_lundata));
9321
9322	if (lun_datalen < alloc_len) {
9323		ctsio->residual = alloc_len - lun_datalen;
9324		ctsio->kern_data_len = lun_datalen;
9325		ctsio->kern_total_len = lun_datalen;
9326	} else {
9327		ctsio->residual = 0;
9328		ctsio->kern_data_len = alloc_len;
9329		ctsio->kern_total_len = alloc_len;
9330	}
9331	ctsio->kern_data_resid = 0;
9332	ctsio->kern_rel_offset = 0;
9333	ctsio->kern_sg_entries = 0;
9334
9335	/*
9336	 * We set this to the actual data length, regardless of how much
9337	 * space we actually have to return results.  If the user looks at
9338	 * this value, he'll know whether or not he allocated enough space
9339	 * and reissue the command if necessary.  We don't support well
9340	 * known logical units, so if the user asks for that, return none.
9341	 */
9342	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9343
9344	/*
9345	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9346	 * this request.
9347	 */
9348	ctl_set_success(ctsio);
9349	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9350	ctsio->be_move_done = ctl_config_move_done;
9351	ctl_datamove((union ctl_io *)ctsio);
9352	return (retval);
9353}
9354
9355int
9356ctl_request_sense(struct ctl_scsiio *ctsio)
9357{
9358	struct scsi_request_sense *cdb;
9359	struct scsi_sense_data *sense_ptr;
9360	struct ctl_lun *lun;
9361	uint32_t initidx;
9362	int have_error;
9363	scsi_sense_data_type sense_format;
9364
9365	cdb = (struct scsi_request_sense *)ctsio->cdb;
9366
9367	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9368
9369	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9370
9371	/*
9372	 * Determine which sense format the user wants.
9373	 */
9374	if (cdb->byte2 & SRS_DESC)
9375		sense_format = SSD_TYPE_DESC;
9376	else
9377		sense_format = SSD_TYPE_FIXED;
9378
9379	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9380	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9381	ctsio->kern_sg_entries = 0;
9382
9383	/*
9384	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9385	 * larger than the largest allowed value for the length field in the
9386	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9387	 */
9388	ctsio->residual = 0;
9389	ctsio->kern_data_len = cdb->length;
9390	ctsio->kern_total_len = cdb->length;
9391
9392	ctsio->kern_data_resid = 0;
9393	ctsio->kern_rel_offset = 0;
9394	ctsio->kern_sg_entries = 0;
9395
9396	/*
9397	 * If we don't have a LUN, we don't have any pending sense.
9398	 */
9399	if (lun == NULL)
9400		goto no_sense;
9401
9402	have_error = 0;
9403	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9404	/*
9405	 * Check for pending sense, and then for pending unit attentions.
9406	 * Pending sense gets returned first, then pending unit attentions.
9407	 */
9408	mtx_lock(&lun->lun_lock);
9409#ifdef CTL_WITH_CA
9410	if (ctl_is_set(lun->have_ca, initidx)) {
9411		scsi_sense_data_type stored_format;
9412
9413		/*
9414		 * Check to see which sense format was used for the stored
9415		 * sense data.
9416		 */
9417		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9418
9419		/*
9420		 * If the user requested a different sense format than the
9421		 * one we stored, then we need to convert it to the other
9422		 * format.  If we're going from descriptor to fixed format
9423		 * sense data, we may lose things in translation, depending
9424		 * on what options were used.
9425		 *
9426		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9427		 * for some reason we'll just copy it out as-is.
9428		 */
9429		if ((stored_format == SSD_TYPE_FIXED)
9430		 && (sense_format == SSD_TYPE_DESC))
9431			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9432			    &lun->pending_sense[initidx],
9433			    (struct scsi_sense_data_desc *)sense_ptr);
9434		else if ((stored_format == SSD_TYPE_DESC)
9435		      && (sense_format == SSD_TYPE_FIXED))
9436			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9437			    &lun->pending_sense[initidx],
9438			    (struct scsi_sense_data_fixed *)sense_ptr);
9439		else
9440			memcpy(sense_ptr, &lun->pending_sense[initidx],
9441			       ctl_min(sizeof(*sense_ptr),
9442			       sizeof(lun->pending_sense[initidx])));
9443
9444		ctl_clear_mask(lun->have_ca, initidx);
9445		have_error = 1;
9446	} else
9447#endif
9448	if (lun->pending_ua[initidx] != CTL_UA_NONE) {
9449		ctl_ua_type ua_type;
9450
9451		ua_type = ctl_build_ua(&lun->pending_ua[initidx],
9452				       sense_ptr, sense_format);
9453		if (ua_type != CTL_UA_NONE)
9454			have_error = 1;
9455	}
9456	mtx_unlock(&lun->lun_lock);
9457
9458	/*
9459	 * We already have a pending error, return it.
9460	 */
9461	if (have_error != 0) {
9462		/*
9463		 * We report the SCSI status as OK, since the status of the
9464		 * request sense command itself is OK.
9465		 * We report 0 for the sense length, because we aren't doing
9466		 * autosense in this case.  We're reporting sense as
9467		 * parameter data.
9468		 */
9469		ctl_set_success(ctsio);
9470		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9471		ctsio->be_move_done = ctl_config_move_done;
9472		ctl_datamove((union ctl_io *)ctsio);
9473		return (CTL_RETVAL_COMPLETE);
9474	}
9475
9476no_sense:
9477
9478	/*
9479	 * No sense information to report, so we report that everything is
9480	 * okay.
9481	 */
9482	ctl_set_sense_data(sense_ptr,
9483			   lun,
9484			   sense_format,
9485			   /*current_error*/ 1,
9486			   /*sense_key*/ SSD_KEY_NO_SENSE,
9487			   /*asc*/ 0x00,
9488			   /*ascq*/ 0x00,
9489			   SSD_ELEM_NONE);
9490
9491	/*
9492	 * We report 0 for the sense length, because we aren't doing
9493	 * autosense in this case.  We're reporting sense as parameter data.
9494	 */
9495	ctl_set_success(ctsio);
9496	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9497	ctsio->be_move_done = ctl_config_move_done;
9498	ctl_datamove((union ctl_io *)ctsio);
9499	return (CTL_RETVAL_COMPLETE);
9500}
9501
9502int
9503ctl_tur(struct ctl_scsiio *ctsio)
9504{
9505
9506	CTL_DEBUG_PRINT(("ctl_tur\n"));
9507
9508	ctl_set_success(ctsio);
9509	ctl_done((union ctl_io *)ctsio);
9510
9511	return (CTL_RETVAL_COMPLETE);
9512}
9513
9514#ifdef notyet
9515static int
9516ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9517{
9518
9519}
9520#endif
9521
9522static int
9523ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9524{
9525	struct scsi_vpd_supported_pages *pages;
9526	int sup_page_size;
9527	struct ctl_lun *lun;
9528
9529	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9530
9531	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9532	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9533	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9534	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9535	ctsio->kern_sg_entries = 0;
9536
9537	if (sup_page_size < alloc_len) {
9538		ctsio->residual = alloc_len - sup_page_size;
9539		ctsio->kern_data_len = sup_page_size;
9540		ctsio->kern_total_len = sup_page_size;
9541	} else {
9542		ctsio->residual = 0;
9543		ctsio->kern_data_len = alloc_len;
9544		ctsio->kern_total_len = alloc_len;
9545	}
9546	ctsio->kern_data_resid = 0;
9547	ctsio->kern_rel_offset = 0;
9548	ctsio->kern_sg_entries = 0;
9549
9550	/*
9551	 * The control device is always connected.  The disk device, on the
9552	 * other hand, may not be online all the time.  Need to change this
9553	 * to figure out whether the disk device is actually online or not.
9554	 */
9555	if (lun != NULL)
9556		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9557				lun->be_lun->lun_type;
9558	else
9559		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9560
9561	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9562	/* Supported VPD pages */
9563	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9564	/* Serial Number */
9565	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9566	/* Device Identification */
9567	pages->page_list[2] = SVPD_DEVICE_ID;
9568	/* Extended INQUIRY Data */
9569	pages->page_list[3] = SVPD_EXTENDED_INQUIRY_DATA;
9570	/* Mode Page Policy */
9571	pages->page_list[4] = SVPD_MODE_PAGE_POLICY;
9572	/* SCSI Ports */
9573	pages->page_list[5] = SVPD_SCSI_PORTS;
9574	/* Third-party Copy */
9575	pages->page_list[6] = SVPD_SCSI_TPC;
9576	/* Block limits */
9577	pages->page_list[7] = SVPD_BLOCK_LIMITS;
9578	/* Block Device Characteristics */
9579	pages->page_list[8] = SVPD_BDC;
9580	/* Logical Block Provisioning */
9581	pages->page_list[9] = SVPD_LBP;
9582
9583	ctl_set_success(ctsio);
9584	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9585	ctsio->be_move_done = ctl_config_move_done;
9586	ctl_datamove((union ctl_io *)ctsio);
9587	return (CTL_RETVAL_COMPLETE);
9588}
9589
9590static int
9591ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9592{
9593	struct scsi_vpd_unit_serial_number *sn_ptr;
9594	struct ctl_lun *lun;
9595	int data_len;
9596
9597	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9598
9599	data_len = 4 + CTL_SN_LEN;
9600	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9601	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9602	if (data_len < alloc_len) {
9603		ctsio->residual = alloc_len - data_len;
9604		ctsio->kern_data_len = data_len;
9605		ctsio->kern_total_len = data_len;
9606	} else {
9607		ctsio->residual = 0;
9608		ctsio->kern_data_len = alloc_len;
9609		ctsio->kern_total_len = alloc_len;
9610	}
9611	ctsio->kern_data_resid = 0;
9612	ctsio->kern_rel_offset = 0;
9613	ctsio->kern_sg_entries = 0;
9614
9615	/*
9616	 * The control device is always connected.  The disk device, on the
9617	 * other hand, may not be online all the time.  Need to change this
9618	 * to figure out whether the disk device is actually online or not.
9619	 */
9620	if (lun != NULL)
9621		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9622				  lun->be_lun->lun_type;
9623	else
9624		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9625
9626	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9627	sn_ptr->length = CTL_SN_LEN;
9628	/*
9629	 * If we don't have a LUN, we just leave the serial number as
9630	 * all spaces.
9631	 */
9632	if (lun != NULL) {
9633		strncpy((char *)sn_ptr->serial_num,
9634			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9635	} else
9636		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9637
9638	ctl_set_success(ctsio);
9639	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9640	ctsio->be_move_done = ctl_config_move_done;
9641	ctl_datamove((union ctl_io *)ctsio);
9642	return (CTL_RETVAL_COMPLETE);
9643}
9644
9645
9646static int
9647ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9648{
9649	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9650	struct ctl_lun *lun;
9651	int data_len;
9652
9653	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9654
9655	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9656	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9657	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9658	ctsio->kern_sg_entries = 0;
9659
9660	if (data_len < alloc_len) {
9661		ctsio->residual = alloc_len - data_len;
9662		ctsio->kern_data_len = data_len;
9663		ctsio->kern_total_len = data_len;
9664	} else {
9665		ctsio->residual = 0;
9666		ctsio->kern_data_len = alloc_len;
9667		ctsio->kern_total_len = alloc_len;
9668	}
9669	ctsio->kern_data_resid = 0;
9670	ctsio->kern_rel_offset = 0;
9671	ctsio->kern_sg_entries = 0;
9672
9673	/*
9674	 * The control device is always connected.  The disk device, on the
9675	 * other hand, may not be online all the time.
9676	 */
9677	if (lun != NULL)
9678		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9679				     lun->be_lun->lun_type;
9680	else
9681		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9682	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9683	eid_ptr->page_length = data_len - 4;
9684	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9685	eid_ptr->flags3 = SVPD_EID_V_SUP;
9686
9687	ctl_set_success(ctsio);
9688	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9689	ctsio->be_move_done = ctl_config_move_done;
9690	ctl_datamove((union ctl_io *)ctsio);
9691	return (CTL_RETVAL_COMPLETE);
9692}
9693
9694static int
9695ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9696{
9697	struct scsi_vpd_mode_page_policy *mpp_ptr;
9698	struct ctl_lun *lun;
9699	int data_len;
9700
9701	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9702
9703	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9704	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9705
9706	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9707	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9708	ctsio->kern_sg_entries = 0;
9709
9710	if (data_len < alloc_len) {
9711		ctsio->residual = alloc_len - data_len;
9712		ctsio->kern_data_len = data_len;
9713		ctsio->kern_total_len = data_len;
9714	} else {
9715		ctsio->residual = 0;
9716		ctsio->kern_data_len = alloc_len;
9717		ctsio->kern_total_len = alloc_len;
9718	}
9719	ctsio->kern_data_resid = 0;
9720	ctsio->kern_rel_offset = 0;
9721	ctsio->kern_sg_entries = 0;
9722
9723	/*
9724	 * The control device is always connected.  The disk device, on the
9725	 * other hand, may not be online all the time.
9726	 */
9727	if (lun != NULL)
9728		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9729				     lun->be_lun->lun_type;
9730	else
9731		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9732	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9733	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9734	mpp_ptr->descr[0].page_code = 0x3f;
9735	mpp_ptr->descr[0].subpage_code = 0xff;
9736	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9737
9738	ctl_set_success(ctsio);
9739	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9740	ctsio->be_move_done = ctl_config_move_done;
9741	ctl_datamove((union ctl_io *)ctsio);
9742	return (CTL_RETVAL_COMPLETE);
9743}
9744
9745static int
9746ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9747{
9748	struct scsi_vpd_device_id *devid_ptr;
9749	struct scsi_vpd_id_descriptor *desc;
9750	struct ctl_softc *ctl_softc;
9751	struct ctl_lun *lun;
9752	struct ctl_port *port;
9753	int data_len;
9754	uint8_t proto;
9755
9756	ctl_softc = control_softc;
9757
9758	port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9759	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9760
9761	data_len = sizeof(struct scsi_vpd_device_id) +
9762	    sizeof(struct scsi_vpd_id_descriptor) +
9763		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9764	    sizeof(struct scsi_vpd_id_descriptor) +
9765		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9766	if (lun && lun->lun_devid)
9767		data_len += lun->lun_devid->len;
9768	if (port->port_devid)
9769		data_len += port->port_devid->len;
9770	if (port->target_devid)
9771		data_len += port->target_devid->len;
9772
9773	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9774	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9775	ctsio->kern_sg_entries = 0;
9776
9777	if (data_len < alloc_len) {
9778		ctsio->residual = alloc_len - data_len;
9779		ctsio->kern_data_len = data_len;
9780		ctsio->kern_total_len = data_len;
9781	} else {
9782		ctsio->residual = 0;
9783		ctsio->kern_data_len = alloc_len;
9784		ctsio->kern_total_len = alloc_len;
9785	}
9786	ctsio->kern_data_resid = 0;
9787	ctsio->kern_rel_offset = 0;
9788	ctsio->kern_sg_entries = 0;
9789
9790	/*
9791	 * The control device is always connected.  The disk device, on the
9792	 * other hand, may not be online all the time.
9793	 */
9794	if (lun != NULL)
9795		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9796				     lun->be_lun->lun_type;
9797	else
9798		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9799	devid_ptr->page_code = SVPD_DEVICE_ID;
9800	scsi_ulto2b(data_len - 4, devid_ptr->length);
9801
9802	if (port->port_type == CTL_PORT_FC)
9803		proto = SCSI_PROTO_FC << 4;
9804	else if (port->port_type == CTL_PORT_ISCSI)
9805		proto = SCSI_PROTO_ISCSI << 4;
9806	else
9807		proto = SCSI_PROTO_SPI << 4;
9808	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9809
9810	/*
9811	 * We're using a LUN association here.  i.e., this device ID is a
9812	 * per-LUN identifier.
9813	 */
9814	if (lun && lun->lun_devid) {
9815		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9816		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9817		    lun->lun_devid->len);
9818	}
9819
9820	/*
9821	 * This is for the WWPN which is a port association.
9822	 */
9823	if (port->port_devid) {
9824		memcpy(desc, port->port_devid->data, port->port_devid->len);
9825		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9826		    port->port_devid->len);
9827	}
9828
9829	/*
9830	 * This is for the Relative Target Port(type 4h) identifier
9831	 */
9832	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9833	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9834	    SVPD_ID_TYPE_RELTARG;
9835	desc->length = 4;
9836	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9837	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9838	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9839
9840	/*
9841	 * This is for the Target Port Group(type 5h) identifier
9842	 */
9843	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9844	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9845	    SVPD_ID_TYPE_TPORTGRP;
9846	desc->length = 4;
9847	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
9848	    &desc->identifier[2]);
9849	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9850	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9851
9852	/*
9853	 * This is for the Target identifier
9854	 */
9855	if (port->target_devid) {
9856		memcpy(desc, port->target_devid->data, port->target_devid->len);
9857	}
9858
9859	ctl_set_success(ctsio);
9860	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9861	ctsio->be_move_done = ctl_config_move_done;
9862	ctl_datamove((union ctl_io *)ctsio);
9863	return (CTL_RETVAL_COMPLETE);
9864}
9865
9866static int
9867ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9868{
9869	struct ctl_softc *softc = control_softc;
9870	struct scsi_vpd_scsi_ports *sp;
9871	struct scsi_vpd_port_designation *pd;
9872	struct scsi_vpd_port_designation_cont *pdc;
9873	struct ctl_lun *lun;
9874	struct ctl_port *port;
9875	int data_len, num_target_ports, iid_len, id_len, g, pg, p;
9876	int num_target_port_groups;
9877
9878	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9879
9880	if (softc->is_single)
9881		num_target_port_groups = 1;
9882	else
9883		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
9884	num_target_ports = 0;
9885	iid_len = 0;
9886	id_len = 0;
9887	mtx_lock(&softc->ctl_lock);
9888	STAILQ_FOREACH(port, &softc->port_list, links) {
9889		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9890			continue;
9891		if (lun != NULL &&
9892		    ctl_map_lun_back(port->targ_port, lun->lun) >=
9893		    CTL_MAX_LUNS)
9894			continue;
9895		num_target_ports++;
9896		if (port->init_devid)
9897			iid_len += port->init_devid->len;
9898		if (port->port_devid)
9899			id_len += port->port_devid->len;
9900	}
9901	mtx_unlock(&softc->ctl_lock);
9902
9903	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
9904	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9905	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9906	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9907	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9908	ctsio->kern_sg_entries = 0;
9909
9910	if (data_len < alloc_len) {
9911		ctsio->residual = alloc_len - data_len;
9912		ctsio->kern_data_len = data_len;
9913		ctsio->kern_total_len = data_len;
9914	} else {
9915		ctsio->residual = 0;
9916		ctsio->kern_data_len = alloc_len;
9917		ctsio->kern_total_len = alloc_len;
9918	}
9919	ctsio->kern_data_resid = 0;
9920	ctsio->kern_rel_offset = 0;
9921	ctsio->kern_sg_entries = 0;
9922
9923	/*
9924	 * The control device is always connected.  The disk device, on the
9925	 * other hand, may not be online all the time.  Need to change this
9926	 * to figure out whether the disk device is actually online or not.
9927	 */
9928	if (lun != NULL)
9929		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9930				  lun->be_lun->lun_type;
9931	else
9932		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9933
9934	sp->page_code = SVPD_SCSI_PORTS;
9935	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9936	    sp->page_length);
9937	pd = &sp->design[0];
9938
9939	mtx_lock(&softc->ctl_lock);
9940	pg = softc->port_offset / CTL_MAX_PORTS;
9941	for (g = 0; g < num_target_port_groups; g++) {
9942		STAILQ_FOREACH(port, &softc->port_list, links) {
9943			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9944				continue;
9945			if (lun != NULL &&
9946			    ctl_map_lun_back(port->targ_port, lun->lun) >=
9947			    CTL_MAX_LUNS)
9948				continue;
9949			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
9950			scsi_ulto2b(p, pd->relative_port_id);
9951			if (port->init_devid && g == pg) {
9952				iid_len = port->init_devid->len;
9953				memcpy(pd->initiator_transportid,
9954				    port->init_devid->data, port->init_devid->len);
9955			} else
9956				iid_len = 0;
9957			scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9958			pdc = (struct scsi_vpd_port_designation_cont *)
9959			    (&pd->initiator_transportid[iid_len]);
9960			if (port->port_devid && g == pg) {
9961				id_len = port->port_devid->len;
9962				memcpy(pdc->target_port_descriptors,
9963				    port->port_devid->data, port->port_devid->len);
9964			} else
9965				id_len = 0;
9966			scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9967			pd = (struct scsi_vpd_port_designation *)
9968			    ((uint8_t *)pdc->target_port_descriptors + id_len);
9969		}
9970	}
9971	mtx_unlock(&softc->ctl_lock);
9972
9973	ctl_set_success(ctsio);
9974	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9975	ctsio->be_move_done = ctl_config_move_done;
9976	ctl_datamove((union ctl_io *)ctsio);
9977	return (CTL_RETVAL_COMPLETE);
9978}
9979
9980static int
9981ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9982{
9983	struct scsi_vpd_block_limits *bl_ptr;
9984	struct ctl_lun *lun;
9985	int bs;
9986
9987	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9988
9989	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9990	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9991	ctsio->kern_sg_entries = 0;
9992
9993	if (sizeof(*bl_ptr) < alloc_len) {
9994		ctsio->residual = alloc_len - sizeof(*bl_ptr);
9995		ctsio->kern_data_len = sizeof(*bl_ptr);
9996		ctsio->kern_total_len = sizeof(*bl_ptr);
9997	} else {
9998		ctsio->residual = 0;
9999		ctsio->kern_data_len = alloc_len;
10000		ctsio->kern_total_len = alloc_len;
10001	}
10002	ctsio->kern_data_resid = 0;
10003	ctsio->kern_rel_offset = 0;
10004	ctsio->kern_sg_entries = 0;
10005
10006	/*
10007	 * The control device is always connected.  The disk device, on the
10008	 * other hand, may not be online all the time.  Need to change this
10009	 * to figure out whether the disk device is actually online or not.
10010	 */
10011	if (lun != NULL)
10012		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10013				  lun->be_lun->lun_type;
10014	else
10015		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10016
10017	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10018	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10019	bl_ptr->max_cmp_write_len = 0xff;
10020	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10021	if (lun != NULL) {
10022		bs = lun->be_lun->blocksize;
10023		scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10024		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10025			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10026			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10027			if (lun->be_lun->pblockexp != 0) {
10028				scsi_ulto4b((1 << lun->be_lun->pblockexp),
10029				    bl_ptr->opt_unmap_grain);
10030				scsi_ulto4b(0x80000000 | lun->be_lun->pblockoff,
10031				    bl_ptr->unmap_grain_align);
10032			}
10033		}
10034		scsi_ulto4b(lun->be_lun->atomicblock,
10035		    bl_ptr->max_atomic_transfer_length);
10036		scsi_ulto4b(0, bl_ptr->atomic_alignment);
10037		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10038	}
10039	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10040
10041	ctl_set_success(ctsio);
10042	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10043	ctsio->be_move_done = ctl_config_move_done;
10044	ctl_datamove((union ctl_io *)ctsio);
10045	return (CTL_RETVAL_COMPLETE);
10046}
10047
10048static int
10049ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10050{
10051	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10052	struct ctl_lun *lun;
10053	const char *value;
10054	u_int i;
10055
10056	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10057
10058	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10059	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10060	ctsio->kern_sg_entries = 0;
10061
10062	if (sizeof(*bdc_ptr) < alloc_len) {
10063		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10064		ctsio->kern_data_len = sizeof(*bdc_ptr);
10065		ctsio->kern_total_len = sizeof(*bdc_ptr);
10066	} else {
10067		ctsio->residual = 0;
10068		ctsio->kern_data_len = alloc_len;
10069		ctsio->kern_total_len = alloc_len;
10070	}
10071	ctsio->kern_data_resid = 0;
10072	ctsio->kern_rel_offset = 0;
10073	ctsio->kern_sg_entries = 0;
10074
10075	/*
10076	 * The control device is always connected.  The disk device, on the
10077	 * other hand, may not be online all the time.  Need to change this
10078	 * to figure out whether the disk device is actually online or not.
10079	 */
10080	if (lun != NULL)
10081		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10082				  lun->be_lun->lun_type;
10083	else
10084		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10085	bdc_ptr->page_code = SVPD_BDC;
10086	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10087	if (lun != NULL &&
10088	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10089		i = strtol(value, NULL, 0);
10090	else
10091		i = CTL_DEFAULT_ROTATION_RATE;
10092	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10093	if (lun != NULL &&
10094	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10095		i = strtol(value, NULL, 0);
10096	else
10097		i = 0;
10098	bdc_ptr->wab_wac_ff = (i & 0x0f);
10099	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10100
10101	ctl_set_success(ctsio);
10102	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10103	ctsio->be_move_done = ctl_config_move_done;
10104	ctl_datamove((union ctl_io *)ctsio);
10105	return (CTL_RETVAL_COMPLETE);
10106}
10107
10108static int
10109ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10110{
10111	struct scsi_vpd_logical_block_prov *lbp_ptr;
10112	struct ctl_lun *lun;
10113
10114	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10115
10116	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10117	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10118	ctsio->kern_sg_entries = 0;
10119
10120	if (sizeof(*lbp_ptr) < alloc_len) {
10121		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10122		ctsio->kern_data_len = sizeof(*lbp_ptr);
10123		ctsio->kern_total_len = sizeof(*lbp_ptr);
10124	} else {
10125		ctsio->residual = 0;
10126		ctsio->kern_data_len = alloc_len;
10127		ctsio->kern_total_len = alloc_len;
10128	}
10129	ctsio->kern_data_resid = 0;
10130	ctsio->kern_rel_offset = 0;
10131	ctsio->kern_sg_entries = 0;
10132
10133	/*
10134	 * The control device is always connected.  The disk device, on the
10135	 * other hand, may not be online all the time.  Need to change this
10136	 * to figure out whether the disk device is actually online or not.
10137	 */
10138	if (lun != NULL)
10139		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10140				  lun->be_lun->lun_type;
10141	else
10142		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10143
10144	lbp_ptr->page_code = SVPD_LBP;
10145	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10146	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10147		lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10148		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10149		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10150		lbp_ptr->prov_type = SVPD_LBP_THIN;
10151	}
10152
10153	ctl_set_success(ctsio);
10154	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10155	ctsio->be_move_done = ctl_config_move_done;
10156	ctl_datamove((union ctl_io *)ctsio);
10157	return (CTL_RETVAL_COMPLETE);
10158}
10159
10160static int
10161ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10162{
10163	struct scsi_inquiry *cdb;
10164	int alloc_len, retval;
10165
10166	cdb = (struct scsi_inquiry *)ctsio->cdb;
10167
10168	retval = CTL_RETVAL_COMPLETE;
10169
10170	alloc_len = scsi_2btoul(cdb->length);
10171
10172	switch (cdb->page_code) {
10173	case SVPD_SUPPORTED_PAGES:
10174		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10175		break;
10176	case SVPD_UNIT_SERIAL_NUMBER:
10177		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10178		break;
10179	case SVPD_DEVICE_ID:
10180		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10181		break;
10182	case SVPD_EXTENDED_INQUIRY_DATA:
10183		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10184		break;
10185	case SVPD_MODE_PAGE_POLICY:
10186		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10187		break;
10188	case SVPD_SCSI_PORTS:
10189		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10190		break;
10191	case SVPD_SCSI_TPC:
10192		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10193		break;
10194	case SVPD_BLOCK_LIMITS:
10195		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10196		break;
10197	case SVPD_BDC:
10198		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10199		break;
10200	case SVPD_LBP:
10201		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10202		break;
10203	default:
10204		ctl_set_invalid_field(ctsio,
10205				      /*sks_valid*/ 1,
10206				      /*command*/ 1,
10207				      /*field*/ 2,
10208				      /*bit_valid*/ 0,
10209				      /*bit*/ 0);
10210		ctl_done((union ctl_io *)ctsio);
10211		retval = CTL_RETVAL_COMPLETE;
10212		break;
10213	}
10214
10215	return (retval);
10216}
10217
10218static int
10219ctl_inquiry_std(struct ctl_scsiio *ctsio)
10220{
10221	struct scsi_inquiry_data *inq_ptr;
10222	struct scsi_inquiry *cdb;
10223	struct ctl_softc *ctl_softc;
10224	struct ctl_lun *lun;
10225	char *val;
10226	uint32_t alloc_len, data_len;
10227	ctl_port_type port_type;
10228
10229	ctl_softc = control_softc;
10230
10231	/*
10232	 * Figure out whether we're talking to a Fibre Channel port or not.
10233	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10234	 * SCSI front ends.
10235	 */
10236	port_type = ctl_softc->ctl_ports[
10237	    ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10238	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10239		port_type = CTL_PORT_SCSI;
10240
10241	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10242	cdb = (struct scsi_inquiry *)ctsio->cdb;
10243	alloc_len = scsi_2btoul(cdb->length);
10244
10245	/*
10246	 * We malloc the full inquiry data size here and fill it
10247	 * in.  If the user only asks for less, we'll give him
10248	 * that much.
10249	 */
10250	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10251	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10252	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10253	ctsio->kern_sg_entries = 0;
10254	ctsio->kern_data_resid = 0;
10255	ctsio->kern_rel_offset = 0;
10256
10257	if (data_len < alloc_len) {
10258		ctsio->residual = alloc_len - data_len;
10259		ctsio->kern_data_len = data_len;
10260		ctsio->kern_total_len = data_len;
10261	} else {
10262		ctsio->residual = 0;
10263		ctsio->kern_data_len = alloc_len;
10264		ctsio->kern_total_len = alloc_len;
10265	}
10266
10267	/*
10268	 * If we have a LUN configured, report it as connected.  Otherwise,
10269	 * report that it is offline or no device is supported, depending
10270	 * on the value of inquiry_pq_no_lun.
10271	 *
10272	 * According to the spec (SPC-4 r34), the peripheral qualifier
10273	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10274	 *
10275	 * "A peripheral device having the specified peripheral device type
10276	 * is not connected to this logical unit. However, the device
10277	 * server is capable of supporting the specified peripheral device
10278	 * type on this logical unit."
10279	 *
10280	 * According to the same spec, the peripheral qualifier
10281	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10282	 *
10283	 * "The device server is not capable of supporting a peripheral
10284	 * device on this logical unit. For this peripheral qualifier the
10285	 * peripheral device type shall be set to 1Fh. All other peripheral
10286	 * device type values are reserved for this peripheral qualifier."
10287	 *
10288	 * Given the text, it would seem that we probably want to report that
10289	 * the LUN is offline here.  There is no LUN connected, but we can
10290	 * support a LUN at the given LUN number.
10291	 *
10292	 * In the real world, though, it sounds like things are a little
10293	 * different:
10294	 *
10295	 * - Linux, when presented with a LUN with the offline peripheral
10296	 *   qualifier, will create an sg driver instance for it.  So when
10297	 *   you attach it to CTL, you wind up with a ton of sg driver
10298	 *   instances.  (One for every LUN that Linux bothered to probe.)
10299	 *   Linux does this despite the fact that it issues a REPORT LUNs
10300	 *   to LUN 0 to get the inventory of supported LUNs.
10301	 *
10302	 * - There is other anecdotal evidence (from Emulex folks) about
10303	 *   arrays that use the offline peripheral qualifier for LUNs that
10304	 *   are on the "passive" path in an active/passive array.
10305	 *
10306	 * So the solution is provide a hopefully reasonable default
10307	 * (return bad/no LUN) and allow the user to change the behavior
10308	 * with a tunable/sysctl variable.
10309	 */
10310	if (lun != NULL)
10311		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10312				  lun->be_lun->lun_type;
10313	else if (ctl_softc->inquiry_pq_no_lun == 0)
10314		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10315	else
10316		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10317
10318	/* RMB in byte 2 is 0 */
10319	inq_ptr->version = SCSI_REV_SPC4;
10320
10321	/*
10322	 * According to SAM-3, even if a device only supports a single
10323	 * level of LUN addressing, it should still set the HISUP bit:
10324	 *
10325	 * 4.9.1 Logical unit numbers overview
10326	 *
10327	 * All logical unit number formats described in this standard are
10328	 * hierarchical in structure even when only a single level in that
10329	 * hierarchy is used. The HISUP bit shall be set to one in the
10330	 * standard INQUIRY data (see SPC-2) when any logical unit number
10331	 * format described in this standard is used.  Non-hierarchical
10332	 * formats are outside the scope of this standard.
10333	 *
10334	 * Therefore we set the HiSup bit here.
10335	 *
10336	 * The reponse format is 2, per SPC-3.
10337	 */
10338	inq_ptr->response_format = SID_HiSup | 2;
10339
10340	inq_ptr->additional_length = data_len -
10341	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10342	CTL_DEBUG_PRINT(("additional_length = %d\n",
10343			 inq_ptr->additional_length));
10344
10345	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10346	/* 16 bit addressing */
10347	if (port_type == CTL_PORT_SCSI)
10348		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10349	/* XXX set the SID_MultiP bit here if we're actually going to
10350	   respond on multiple ports */
10351	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10352
10353	/* 16 bit data bus, synchronous transfers */
10354	if (port_type == CTL_PORT_SCSI)
10355		inq_ptr->flags = SID_WBus16 | SID_Sync;
10356	/*
10357	 * XXX KDM do we want to support tagged queueing on the control
10358	 * device at all?
10359	 */
10360	if ((lun == NULL)
10361	 || (lun->be_lun->lun_type != T_PROCESSOR))
10362		inq_ptr->flags |= SID_CmdQue;
10363	/*
10364	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10365	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10366	 * name and 4 bytes for the revision.
10367	 */
10368	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10369	    "vendor")) == NULL) {
10370		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10371	} else {
10372		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10373		strncpy(inq_ptr->vendor, val,
10374		    min(sizeof(inq_ptr->vendor), strlen(val)));
10375	}
10376	if (lun == NULL) {
10377		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10378		    sizeof(inq_ptr->product));
10379	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10380		switch (lun->be_lun->lun_type) {
10381		case T_DIRECT:
10382			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10383			    sizeof(inq_ptr->product));
10384			break;
10385		case T_PROCESSOR:
10386			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10387			    sizeof(inq_ptr->product));
10388			break;
10389		default:
10390			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10391			    sizeof(inq_ptr->product));
10392			break;
10393		}
10394	} else {
10395		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10396		strncpy(inq_ptr->product, val,
10397		    min(sizeof(inq_ptr->product), strlen(val)));
10398	}
10399
10400	/*
10401	 * XXX make this a macro somewhere so it automatically gets
10402	 * incremented when we make changes.
10403	 */
10404	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10405	    "revision")) == NULL) {
10406		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10407	} else {
10408		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10409		strncpy(inq_ptr->revision, val,
10410		    min(sizeof(inq_ptr->revision), strlen(val)));
10411	}
10412
10413	/*
10414	 * For parallel SCSI, we support double transition and single
10415	 * transition clocking.  We also support QAS (Quick Arbitration
10416	 * and Selection) and Information Unit transfers on both the
10417	 * control and array devices.
10418	 */
10419	if (port_type == CTL_PORT_SCSI)
10420		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10421				    SID_SPI_IUS;
10422
10423	/* SAM-5 (no version claimed) */
10424	scsi_ulto2b(0x00A0, inq_ptr->version1);
10425	/* SPC-4 (no version claimed) */
10426	scsi_ulto2b(0x0460, inq_ptr->version2);
10427	if (port_type == CTL_PORT_FC) {
10428		/* FCP-2 ANSI INCITS.350:2003 */
10429		scsi_ulto2b(0x0917, inq_ptr->version3);
10430	} else if (port_type == CTL_PORT_SCSI) {
10431		/* SPI-4 ANSI INCITS.362:200x */
10432		scsi_ulto2b(0x0B56, inq_ptr->version3);
10433	} else if (port_type == CTL_PORT_ISCSI) {
10434		/* iSCSI (no version claimed) */
10435		scsi_ulto2b(0x0960, inq_ptr->version3);
10436	} else if (port_type == CTL_PORT_SAS) {
10437		/* SAS (no version claimed) */
10438		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10439	}
10440
10441	if (lun == NULL) {
10442		/* SBC-4 (no version claimed) */
10443		scsi_ulto2b(0x0600, inq_ptr->version4);
10444	} else {
10445		switch (lun->be_lun->lun_type) {
10446		case T_DIRECT:
10447			/* SBC-4 (no version claimed) */
10448			scsi_ulto2b(0x0600, inq_ptr->version4);
10449			break;
10450		case T_PROCESSOR:
10451		default:
10452			break;
10453		}
10454	}
10455
10456	ctl_set_success(ctsio);
10457	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10458	ctsio->be_move_done = ctl_config_move_done;
10459	ctl_datamove((union ctl_io *)ctsio);
10460	return (CTL_RETVAL_COMPLETE);
10461}
10462
10463int
10464ctl_inquiry(struct ctl_scsiio *ctsio)
10465{
10466	struct scsi_inquiry *cdb;
10467	int retval;
10468
10469	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10470
10471	cdb = (struct scsi_inquiry *)ctsio->cdb;
10472	if (cdb->byte2 & SI_EVPD)
10473		retval = ctl_inquiry_evpd(ctsio);
10474	else if (cdb->page_code == 0)
10475		retval = ctl_inquiry_std(ctsio);
10476	else {
10477		ctl_set_invalid_field(ctsio,
10478				      /*sks_valid*/ 1,
10479				      /*command*/ 1,
10480				      /*field*/ 2,
10481				      /*bit_valid*/ 0,
10482				      /*bit*/ 0);
10483		ctl_done((union ctl_io *)ctsio);
10484		return (CTL_RETVAL_COMPLETE);
10485	}
10486
10487	return (retval);
10488}
10489
10490/*
10491 * For known CDB types, parse the LBA and length.
10492 */
10493static int
10494ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10495{
10496	if (io->io_hdr.io_type != CTL_IO_SCSI)
10497		return (1);
10498
10499	switch (io->scsiio.cdb[0]) {
10500	case COMPARE_AND_WRITE: {
10501		struct scsi_compare_and_write *cdb;
10502
10503		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10504
10505		*lba = scsi_8btou64(cdb->addr);
10506		*len = cdb->length;
10507		break;
10508	}
10509	case READ_6:
10510	case WRITE_6: {
10511		struct scsi_rw_6 *cdb;
10512
10513		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10514
10515		*lba = scsi_3btoul(cdb->addr);
10516		/* only 5 bits are valid in the most significant address byte */
10517		*lba &= 0x1fffff;
10518		*len = cdb->length;
10519		break;
10520	}
10521	case READ_10:
10522	case WRITE_10: {
10523		struct scsi_rw_10 *cdb;
10524
10525		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10526
10527		*lba = scsi_4btoul(cdb->addr);
10528		*len = scsi_2btoul(cdb->length);
10529		break;
10530	}
10531	case WRITE_VERIFY_10: {
10532		struct scsi_write_verify_10 *cdb;
10533
10534		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10535
10536		*lba = scsi_4btoul(cdb->addr);
10537		*len = scsi_2btoul(cdb->length);
10538		break;
10539	}
10540	case READ_12:
10541	case WRITE_12: {
10542		struct scsi_rw_12 *cdb;
10543
10544		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10545
10546		*lba = scsi_4btoul(cdb->addr);
10547		*len = scsi_4btoul(cdb->length);
10548		break;
10549	}
10550	case WRITE_VERIFY_12: {
10551		struct scsi_write_verify_12 *cdb;
10552
10553		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10554
10555		*lba = scsi_4btoul(cdb->addr);
10556		*len = scsi_4btoul(cdb->length);
10557		break;
10558	}
10559	case READ_16:
10560	case WRITE_16:
10561	case WRITE_ATOMIC_16: {
10562		struct scsi_rw_16 *cdb;
10563
10564		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10565
10566		*lba = scsi_8btou64(cdb->addr);
10567		*len = scsi_4btoul(cdb->length);
10568		break;
10569	}
10570	case WRITE_VERIFY_16: {
10571		struct scsi_write_verify_16 *cdb;
10572
10573		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10574
10575		*lba = scsi_8btou64(cdb->addr);
10576		*len = scsi_4btoul(cdb->length);
10577		break;
10578	}
10579	case WRITE_SAME_10: {
10580		struct scsi_write_same_10 *cdb;
10581
10582		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10583
10584		*lba = scsi_4btoul(cdb->addr);
10585		*len = scsi_2btoul(cdb->length);
10586		break;
10587	}
10588	case WRITE_SAME_16: {
10589		struct scsi_write_same_16 *cdb;
10590
10591		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10592
10593		*lba = scsi_8btou64(cdb->addr);
10594		*len = scsi_4btoul(cdb->length);
10595		break;
10596	}
10597	case VERIFY_10: {
10598		struct scsi_verify_10 *cdb;
10599
10600		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10601
10602		*lba = scsi_4btoul(cdb->addr);
10603		*len = scsi_2btoul(cdb->length);
10604		break;
10605	}
10606	case VERIFY_12: {
10607		struct scsi_verify_12 *cdb;
10608
10609		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10610
10611		*lba = scsi_4btoul(cdb->addr);
10612		*len = scsi_4btoul(cdb->length);
10613		break;
10614	}
10615	case VERIFY_16: {
10616		struct scsi_verify_16 *cdb;
10617
10618		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10619
10620		*lba = scsi_8btou64(cdb->addr);
10621		*len = scsi_4btoul(cdb->length);
10622		break;
10623	}
10624	case UNMAP: {
10625		*lba = 0;
10626		*len = UINT64_MAX;
10627		break;
10628	}
10629	default:
10630		return (1);
10631		break; /* NOTREACHED */
10632	}
10633
10634	return (0);
10635}
10636
10637static ctl_action
10638ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2)
10639{
10640	uint64_t endlba1, endlba2;
10641
10642	endlba1 = lba1 + len1 - 1;
10643	endlba2 = lba2 + len2 - 1;
10644
10645	if ((endlba1 < lba2)
10646	 || (endlba2 < lba1))
10647		return (CTL_ACTION_PASS);
10648	else
10649		return (CTL_ACTION_BLOCK);
10650}
10651
10652static int
10653ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10654{
10655	struct ctl_ptr_len_flags *ptrlen;
10656	struct scsi_unmap_desc *buf, *end, *range;
10657	uint64_t lba;
10658	uint32_t len;
10659
10660	/* If not UNMAP -- go other way. */
10661	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10662	    io->scsiio.cdb[0] != UNMAP)
10663		return (CTL_ACTION_ERROR);
10664
10665	/* If UNMAP without data -- block and wait for data. */
10666	ptrlen = (struct ctl_ptr_len_flags *)
10667	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10668	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10669	    ptrlen->ptr == NULL)
10670		return (CTL_ACTION_BLOCK);
10671
10672	/* UNMAP with data -- check for collision. */
10673	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10674	end = buf + ptrlen->len / sizeof(*buf);
10675	for (range = buf; range < end; range++) {
10676		lba = scsi_8btou64(range->lba);
10677		len = scsi_4btoul(range->length);
10678		if ((lba < lba2 + len2) && (lba + len > lba2))
10679			return (CTL_ACTION_BLOCK);
10680	}
10681	return (CTL_ACTION_PASS);
10682}
10683
10684static ctl_action
10685ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10686{
10687	uint64_t lba1, lba2;
10688	uint64_t len1, len2;
10689	int retval;
10690
10691	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10692		return (CTL_ACTION_ERROR);
10693
10694	retval = ctl_extent_check_unmap(io2, lba1, len1);
10695	if (retval != CTL_ACTION_ERROR)
10696		return (retval);
10697
10698	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10699		return (CTL_ACTION_ERROR);
10700
10701	return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10702}
10703
10704static ctl_action
10705ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10706    union ctl_io *ooa_io)
10707{
10708	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10709	ctl_serialize_action *serialize_row;
10710
10711	/*
10712	 * The initiator attempted multiple untagged commands at the same
10713	 * time.  Can't do that.
10714	 */
10715	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10716	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10717	 && ((pending_io->io_hdr.nexus.targ_port ==
10718	      ooa_io->io_hdr.nexus.targ_port)
10719	  && (pending_io->io_hdr.nexus.initid.id ==
10720	      ooa_io->io_hdr.nexus.initid.id))
10721	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10722		return (CTL_ACTION_OVERLAP);
10723
10724	/*
10725	 * The initiator attempted to send multiple tagged commands with
10726	 * the same ID.  (It's fine if different initiators have the same
10727	 * tag ID.)
10728	 *
10729	 * Even if all of those conditions are true, we don't kill the I/O
10730	 * if the command ahead of us has been aborted.  We won't end up
10731	 * sending it to the FETD, and it's perfectly legal to resend a
10732	 * command with the same tag number as long as the previous
10733	 * instance of this tag number has been aborted somehow.
10734	 */
10735	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10736	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10737	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10738	 && ((pending_io->io_hdr.nexus.targ_port ==
10739	      ooa_io->io_hdr.nexus.targ_port)
10740	  && (pending_io->io_hdr.nexus.initid.id ==
10741	      ooa_io->io_hdr.nexus.initid.id))
10742	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10743		return (CTL_ACTION_OVERLAP_TAG);
10744
10745	/*
10746	 * If we get a head of queue tag, SAM-3 says that we should
10747	 * immediately execute it.
10748	 *
10749	 * What happens if this command would normally block for some other
10750	 * reason?  e.g. a request sense with a head of queue tag
10751	 * immediately after a write.  Normally that would block, but this
10752	 * will result in its getting executed immediately...
10753	 *
10754	 * We currently return "pass" instead of "skip", so we'll end up
10755	 * going through the rest of the queue to check for overlapped tags.
10756	 *
10757	 * XXX KDM check for other types of blockage first??
10758	 */
10759	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10760		return (CTL_ACTION_PASS);
10761
10762	/*
10763	 * Ordered tags have to block until all items ahead of them
10764	 * have completed.  If we get called with an ordered tag, we always
10765	 * block, if something else is ahead of us in the queue.
10766	 */
10767	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10768		return (CTL_ACTION_BLOCK);
10769
10770	/*
10771	 * Simple tags get blocked until all head of queue and ordered tags
10772	 * ahead of them have completed.  I'm lumping untagged commands in
10773	 * with simple tags here.  XXX KDM is that the right thing to do?
10774	 */
10775	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10776	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10777	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10778	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10779		return (CTL_ACTION_BLOCK);
10780
10781	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10782	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10783
10784	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10785
10786	switch (serialize_row[pending_entry->seridx]) {
10787	case CTL_SER_BLOCK:
10788		return (CTL_ACTION_BLOCK);
10789	case CTL_SER_EXTENT:
10790		return (ctl_extent_check(pending_io, ooa_io));
10791	case CTL_SER_EXTENTOPT:
10792		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10793		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10794			return (ctl_extent_check(pending_io, ooa_io));
10795		/* FALLTHROUGH */
10796	case CTL_SER_PASS:
10797		return (CTL_ACTION_PASS);
10798	case CTL_SER_BLOCKOPT:
10799		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10800		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10801			return (CTL_ACTION_BLOCK);
10802		return (CTL_ACTION_PASS);
10803	case CTL_SER_SKIP:
10804		return (CTL_ACTION_SKIP);
10805	default:
10806		panic("invalid serialization value %d",
10807		      serialize_row[pending_entry->seridx]);
10808	}
10809
10810	return (CTL_ACTION_ERROR);
10811}
10812
10813/*
10814 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10815 * Assumptions:
10816 * - pending_io is generally either incoming, or on the blocked queue
10817 * - starting I/O is the I/O we want to start the check with.
10818 */
10819static ctl_action
10820ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10821	      union ctl_io *starting_io)
10822{
10823	union ctl_io *ooa_io;
10824	ctl_action action;
10825
10826	mtx_assert(&lun->lun_lock, MA_OWNED);
10827
10828	/*
10829	 * Run back along the OOA queue, starting with the current
10830	 * blocked I/O and going through every I/O before it on the
10831	 * queue.  If starting_io is NULL, we'll just end up returning
10832	 * CTL_ACTION_PASS.
10833	 */
10834	for (ooa_io = starting_io; ooa_io != NULL;
10835	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10836	     ooa_links)){
10837
10838		/*
10839		 * This routine just checks to see whether
10840		 * cur_blocked is blocked by ooa_io, which is ahead
10841		 * of it in the queue.  It doesn't queue/dequeue
10842		 * cur_blocked.
10843		 */
10844		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10845		switch (action) {
10846		case CTL_ACTION_BLOCK:
10847		case CTL_ACTION_OVERLAP:
10848		case CTL_ACTION_OVERLAP_TAG:
10849		case CTL_ACTION_SKIP:
10850		case CTL_ACTION_ERROR:
10851			return (action);
10852			break; /* NOTREACHED */
10853		case CTL_ACTION_PASS:
10854			break;
10855		default:
10856			panic("invalid action %d", action);
10857			break;  /* NOTREACHED */
10858		}
10859	}
10860
10861	return (CTL_ACTION_PASS);
10862}
10863
10864/*
10865 * Assumptions:
10866 * - An I/O has just completed, and has been removed from the per-LUN OOA
10867 *   queue, so some items on the blocked queue may now be unblocked.
10868 */
10869static int
10870ctl_check_blocked(struct ctl_lun *lun)
10871{
10872	union ctl_io *cur_blocked, *next_blocked;
10873
10874	mtx_assert(&lun->lun_lock, MA_OWNED);
10875
10876	/*
10877	 * Run forward from the head of the blocked queue, checking each
10878	 * entry against the I/Os prior to it on the OOA queue to see if
10879	 * there is still any blockage.
10880	 *
10881	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10882	 * with our removing a variable on it while it is traversing the
10883	 * list.
10884	 */
10885	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10886	     cur_blocked != NULL; cur_blocked = next_blocked) {
10887		union ctl_io *prev_ooa;
10888		ctl_action action;
10889
10890		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10891							  blocked_links);
10892
10893		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10894						      ctl_ooaq, ooa_links);
10895
10896		/*
10897		 * If cur_blocked happens to be the first item in the OOA
10898		 * queue now, prev_ooa will be NULL, and the action
10899		 * returned will just be CTL_ACTION_PASS.
10900		 */
10901		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
10902
10903		switch (action) {
10904		case CTL_ACTION_BLOCK:
10905			/* Nothing to do here, still blocked */
10906			break;
10907		case CTL_ACTION_OVERLAP:
10908		case CTL_ACTION_OVERLAP_TAG:
10909			/*
10910			 * This shouldn't happen!  In theory we've already
10911			 * checked this command for overlap...
10912			 */
10913			break;
10914		case CTL_ACTION_PASS:
10915		case CTL_ACTION_SKIP: {
10916			struct ctl_softc *softc;
10917			const struct ctl_cmd_entry *entry;
10918			int isc_retval;
10919
10920			/*
10921			 * The skip case shouldn't happen, this transaction
10922			 * should have never made it onto the blocked queue.
10923			 */
10924			/*
10925			 * This I/O is no longer blocked, we can remove it
10926			 * from the blocked queue.  Since this is a TAILQ
10927			 * (doubly linked list), we can do O(1) removals
10928			 * from any place on the list.
10929			 */
10930			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
10931				     blocked_links);
10932			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10933
10934			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
10935				/*
10936				 * Need to send IO back to original side to
10937				 * run
10938				 */
10939				union ctl_ha_msg msg_info;
10940
10941				msg_info.hdr.original_sc =
10942					cur_blocked->io_hdr.original_sc;
10943				msg_info.hdr.serializing_sc = cur_blocked;
10944				msg_info.hdr.msg_type = CTL_MSG_R2R;
10945				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
10946				     &msg_info, sizeof(msg_info), 0)) >
10947				     CTL_HA_STATUS_SUCCESS) {
10948					printf("CTL:Check Blocked error from "
10949					       "ctl_ha_msg_send %d\n",
10950					       isc_retval);
10951				}
10952				break;
10953			}
10954			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
10955			softc = control_softc;
10956
10957			/*
10958			 * Check this I/O for LUN state changes that may
10959			 * have happened while this command was blocked.
10960			 * The LUN state may have been changed by a command
10961			 * ahead of us in the queue, so we need to re-check
10962			 * for any states that can be caused by SCSI
10963			 * commands.
10964			 */
10965			if (ctl_scsiio_lun_check(softc, lun, entry,
10966						 &cur_blocked->scsiio) == 0) {
10967				cur_blocked->io_hdr.flags |=
10968				                      CTL_FLAG_IS_WAS_ON_RTR;
10969				ctl_enqueue_rtr(cur_blocked);
10970			} else
10971				ctl_done(cur_blocked);
10972			break;
10973		}
10974		default:
10975			/*
10976			 * This probably shouldn't happen -- we shouldn't
10977			 * get CTL_ACTION_ERROR, or anything else.
10978			 */
10979			break;
10980		}
10981	}
10982
10983	return (CTL_RETVAL_COMPLETE);
10984}
10985
10986/*
10987 * This routine (with one exception) checks LUN flags that can be set by
10988 * commands ahead of us in the OOA queue.  These flags have to be checked
10989 * when a command initially comes in, and when we pull a command off the
10990 * blocked queue and are preparing to execute it.  The reason we have to
10991 * check these flags for commands on the blocked queue is that the LUN
10992 * state may have been changed by a command ahead of us while we're on the
10993 * blocked queue.
10994 *
10995 * Ordering is somewhat important with these checks, so please pay
10996 * careful attention to the placement of any new checks.
10997 */
10998static int
10999ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11000    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11001{
11002	int retval;
11003	uint32_t residx;
11004
11005	retval = 0;
11006
11007	mtx_assert(&lun->lun_lock, MA_OWNED);
11008
11009	/*
11010	 * If this shelf is a secondary shelf controller, we have to reject
11011	 * any media access commands.
11012	 */
11013	if ((ctl_softc->flags & CTL_FLAG_ACTIVE_SHELF) == 0 &&
11014	    (entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0) {
11015		ctl_set_lun_standby(ctsio);
11016		retval = 1;
11017		goto bailout;
11018	}
11019
11020	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11021		if (lun->flags & CTL_LUN_READONLY) {
11022			ctl_set_sense(ctsio, /*current_error*/ 1,
11023			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11024			    /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11025			retval = 1;
11026			goto bailout;
11027		}
11028		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11029		    .eca_and_aen & SCP_SWP) != 0) {
11030			ctl_set_sense(ctsio, /*current_error*/ 1,
11031			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11032			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11033			retval = 1;
11034			goto bailout;
11035		}
11036	}
11037
11038	/*
11039	 * Check for a reservation conflict.  If this command isn't allowed
11040	 * even on reserved LUNs, and if this initiator isn't the one who
11041	 * reserved us, reject the command with a reservation conflict.
11042	 */
11043	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11044	if ((lun->flags & CTL_LUN_RESERVED)
11045	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11046		if (lun->res_idx != residx) {
11047			ctl_set_reservation_conflict(ctsio);
11048			retval = 1;
11049			goto bailout;
11050		}
11051	}
11052
11053	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11054	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11055		/* No reservation or command is allowed. */;
11056	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11057	    (lun->res_type == SPR_TYPE_WR_EX ||
11058	     lun->res_type == SPR_TYPE_WR_EX_RO ||
11059	     lun->res_type == SPR_TYPE_WR_EX_AR)) {
11060		/* The command is allowed for Write Exclusive resv. */;
11061	} else {
11062		/*
11063		 * if we aren't registered or it's a res holder type
11064		 * reservation and this isn't the res holder then set a
11065		 * conflict.
11066		 */
11067		if (ctl_get_prkey(lun, residx) == 0
11068		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11069			ctl_set_reservation_conflict(ctsio);
11070			retval = 1;
11071			goto bailout;
11072		}
11073
11074	}
11075
11076	if ((lun->flags & CTL_LUN_OFFLINE)
11077	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11078		ctl_set_lun_not_ready(ctsio);
11079		retval = 1;
11080		goto bailout;
11081	}
11082
11083	/*
11084	 * If the LUN is stopped, see if this particular command is allowed
11085	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11086	 */
11087	if ((lun->flags & CTL_LUN_STOPPED)
11088	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11089		/* "Logical unit not ready, initializing cmd. required" */
11090		ctl_set_lun_stopped(ctsio);
11091		retval = 1;
11092		goto bailout;
11093	}
11094
11095	if ((lun->flags & CTL_LUN_INOPERABLE)
11096	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11097		/* "Medium format corrupted" */
11098		ctl_set_medium_format_corrupted(ctsio);
11099		retval = 1;
11100		goto bailout;
11101	}
11102
11103bailout:
11104	return (retval);
11105
11106}
11107
11108static void
11109ctl_failover_io(union ctl_io *io, int have_lock)
11110{
11111	ctl_set_busy(&io->scsiio);
11112	ctl_done(io);
11113}
11114
11115static void
11116ctl_failover(void)
11117{
11118	struct ctl_lun *lun;
11119	struct ctl_softc *ctl_softc;
11120	union ctl_io *next_io, *pending_io;
11121	union ctl_io *io;
11122	int lun_idx;
11123	int i;
11124
11125	ctl_softc = control_softc;
11126
11127	mtx_lock(&ctl_softc->ctl_lock);
11128	/*
11129	 * Remove any cmds from the other SC from the rtr queue.  These
11130	 * will obviously only be for LUNs for which we're the primary.
11131	 * We can't send status or get/send data for these commands.
11132	 * Since they haven't been executed yet, we can just remove them.
11133	 * We'll either abort them or delete them below, depending on
11134	 * which HA mode we're in.
11135	 */
11136#ifdef notyet
11137	mtx_lock(&ctl_softc->queue_lock);
11138	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11139	     io != NULL; io = next_io) {
11140		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11141		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11142			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11143				      ctl_io_hdr, links);
11144	}
11145	mtx_unlock(&ctl_softc->queue_lock);
11146#endif
11147
11148	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11149		lun = ctl_softc->ctl_luns[lun_idx];
11150		if (lun==NULL)
11151			continue;
11152
11153		/*
11154		 * Processor LUNs are primary on both sides.
11155		 * XXX will this always be true?
11156		 */
11157		if (lun->be_lun->lun_type == T_PROCESSOR)
11158			continue;
11159
11160		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11161		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11162			printf("FAILOVER: primary lun %d\n", lun_idx);
11163		        /*
11164			 * Remove all commands from the other SC. First from the
11165			 * blocked queue then from the ooa queue. Once we have
11166			 * removed them. Call ctl_check_blocked to see if there
11167			 * is anything that can run.
11168			 */
11169			for (io = (union ctl_io *)TAILQ_FIRST(
11170			     &lun->blocked_queue); io != NULL; io = next_io) {
11171
11172		        	next_io = (union ctl_io *)TAILQ_NEXT(
11173				    &io->io_hdr, blocked_links);
11174
11175				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11176					TAILQ_REMOVE(&lun->blocked_queue,
11177						     &io->io_hdr,blocked_links);
11178					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11179					TAILQ_REMOVE(&lun->ooa_queue,
11180						     &io->io_hdr, ooa_links);
11181
11182					ctl_free_io(io);
11183				}
11184			}
11185
11186			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11187	     		     io != NULL; io = next_io) {
11188
11189		        	next_io = (union ctl_io *)TAILQ_NEXT(
11190				    &io->io_hdr, ooa_links);
11191
11192				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11193
11194					TAILQ_REMOVE(&lun->ooa_queue,
11195						&io->io_hdr,
11196					     	ooa_links);
11197
11198					ctl_free_io(io);
11199				}
11200			}
11201			ctl_check_blocked(lun);
11202		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11203			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11204
11205			printf("FAILOVER: primary lun %d\n", lun_idx);
11206			/*
11207			 * Abort all commands from the other SC.  We can't
11208			 * send status back for them now.  These should get
11209			 * cleaned up when they are completed or come out
11210			 * for a datamove operation.
11211			 */
11212			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11213	     		     io != NULL; io = next_io) {
11214		        	next_io = (union ctl_io *)TAILQ_NEXT(
11215					&io->io_hdr, ooa_links);
11216
11217				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11218					io->io_hdr.flags |= CTL_FLAG_ABORT;
11219			}
11220		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11221			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11222
11223			printf("FAILOVER: secondary lun %d\n", lun_idx);
11224
11225			lun->flags |= CTL_LUN_PRIMARY_SC;
11226
11227			/*
11228			 * We send all I/O that was sent to this controller
11229			 * and redirected to the other side back with
11230			 * busy status, and have the initiator retry it.
11231			 * Figuring out how much data has been transferred,
11232			 * etc. and picking up where we left off would be
11233			 * very tricky.
11234			 *
11235			 * XXX KDM need to remove I/O from the blocked
11236			 * queue as well!
11237			 */
11238			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11239			     &lun->ooa_queue); pending_io != NULL;
11240			     pending_io = next_io) {
11241
11242				next_io =  (union ctl_io *)TAILQ_NEXT(
11243					&pending_io->io_hdr, ooa_links);
11244
11245				pending_io->io_hdr.flags &=
11246					~CTL_FLAG_SENT_2OTHER_SC;
11247
11248				if (pending_io->io_hdr.flags &
11249				    CTL_FLAG_IO_ACTIVE) {
11250					pending_io->io_hdr.flags |=
11251						CTL_FLAG_FAILOVER;
11252				} else {
11253					ctl_set_busy(&pending_io->scsiio);
11254					ctl_done(pending_io);
11255				}
11256			}
11257
11258			/*
11259			 * Build Unit Attention
11260			 */
11261			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11262				lun->pending_ua[i] |=
11263				                     CTL_UA_ASYM_ACC_CHANGE;
11264			}
11265		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11266			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11267			printf("FAILOVER: secondary lun %d\n", lun_idx);
11268			/*
11269			 * if the first io on the OOA is not on the RtR queue
11270			 * add it.
11271			 */
11272			lun->flags |= CTL_LUN_PRIMARY_SC;
11273
11274			pending_io = (union ctl_io *)TAILQ_FIRST(
11275			    &lun->ooa_queue);
11276			if (pending_io==NULL) {
11277				printf("Nothing on OOA queue\n");
11278				continue;
11279			}
11280
11281			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11282			if ((pending_io->io_hdr.flags &
11283			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11284				pending_io->io_hdr.flags |=
11285				    CTL_FLAG_IS_WAS_ON_RTR;
11286				ctl_enqueue_rtr(pending_io);
11287			}
11288#if 0
11289			else
11290			{
11291				printf("Tag 0x%04x is running\n",
11292				      pending_io->scsiio.tag_num);
11293			}
11294#endif
11295
11296			next_io = (union ctl_io *)TAILQ_NEXT(
11297			    &pending_io->io_hdr, ooa_links);
11298			for (pending_io=next_io; pending_io != NULL;
11299			     pending_io = next_io) {
11300				pending_io->io_hdr.flags &=
11301				    ~CTL_FLAG_SENT_2OTHER_SC;
11302				next_io = (union ctl_io *)TAILQ_NEXT(
11303					&pending_io->io_hdr, ooa_links);
11304				if (pending_io->io_hdr.flags &
11305				    CTL_FLAG_IS_WAS_ON_RTR) {
11306#if 0
11307				        printf("Tag 0x%04x is running\n",
11308				      		pending_io->scsiio.tag_num);
11309#endif
11310					continue;
11311				}
11312
11313				switch (ctl_check_ooa(lun, pending_io,
11314			            (union ctl_io *)TAILQ_PREV(
11315				    &pending_io->io_hdr, ctl_ooaq,
11316				    ooa_links))) {
11317
11318				case CTL_ACTION_BLOCK:
11319					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11320							  &pending_io->io_hdr,
11321							  blocked_links);
11322					pending_io->io_hdr.flags |=
11323					    CTL_FLAG_BLOCKED;
11324					break;
11325				case CTL_ACTION_PASS:
11326				case CTL_ACTION_SKIP:
11327					pending_io->io_hdr.flags |=
11328					    CTL_FLAG_IS_WAS_ON_RTR;
11329					ctl_enqueue_rtr(pending_io);
11330					break;
11331				case CTL_ACTION_OVERLAP:
11332					ctl_set_overlapped_cmd(
11333					    (struct ctl_scsiio *)pending_io);
11334					ctl_done(pending_io);
11335					break;
11336				case CTL_ACTION_OVERLAP_TAG:
11337					ctl_set_overlapped_tag(
11338					    (struct ctl_scsiio *)pending_io,
11339					    pending_io->scsiio.tag_num & 0xff);
11340					ctl_done(pending_io);
11341					break;
11342				case CTL_ACTION_ERROR:
11343				default:
11344					ctl_set_internal_failure(
11345						(struct ctl_scsiio *)pending_io,
11346						0,  // sks_valid
11347						0); //retry count
11348					ctl_done(pending_io);
11349					break;
11350				}
11351			}
11352
11353			/*
11354			 * Build Unit Attention
11355			 */
11356			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11357				lun->pending_ua[i] |=
11358				                     CTL_UA_ASYM_ACC_CHANGE;
11359			}
11360		} else {
11361			panic("Unhandled HA mode failover, LUN flags = %#x, "
11362			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11363		}
11364	}
11365	ctl_pause_rtr = 0;
11366	mtx_unlock(&ctl_softc->ctl_lock);
11367}
11368
11369static int
11370ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11371{
11372	struct ctl_lun *lun;
11373	const struct ctl_cmd_entry *entry;
11374	uint32_t initidx, targ_lun;
11375	int retval;
11376
11377	retval = 0;
11378
11379	lun = NULL;
11380
11381	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11382	if ((targ_lun < CTL_MAX_LUNS)
11383	 && ((lun = ctl_softc->ctl_luns[targ_lun]) != NULL)) {
11384		/*
11385		 * If the LUN is invalid, pretend that it doesn't exist.
11386		 * It will go away as soon as all pending I/O has been
11387		 * completed.
11388		 */
11389		mtx_lock(&lun->lun_lock);
11390		if (lun->flags & CTL_LUN_DISABLED) {
11391			mtx_unlock(&lun->lun_lock);
11392			lun = NULL;
11393			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11394			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11395		} else {
11396			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11397			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11398				lun->be_lun;
11399			if (lun->be_lun->lun_type == T_PROCESSOR) {
11400				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11401			}
11402
11403			/*
11404			 * Every I/O goes into the OOA queue for a
11405			 * particular LUN, and stays there until completion.
11406			 */
11407			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11408			    ooa_links);
11409		}
11410	} else {
11411		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11412		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11413	}
11414
11415	/* Get command entry and return error if it is unsuppotyed. */
11416	entry = ctl_validate_command(ctsio);
11417	if (entry == NULL) {
11418		if (lun)
11419			mtx_unlock(&lun->lun_lock);
11420		return (retval);
11421	}
11422
11423	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11424	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11425
11426	/*
11427	 * Check to see whether we can send this command to LUNs that don't
11428	 * exist.  This should pretty much only be the case for inquiry
11429	 * and request sense.  Further checks, below, really require having
11430	 * a LUN, so we can't really check the command anymore.  Just put
11431	 * it on the rtr queue.
11432	 */
11433	if (lun == NULL) {
11434		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11435			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11436			ctl_enqueue_rtr((union ctl_io *)ctsio);
11437			return (retval);
11438		}
11439
11440		ctl_set_unsupported_lun(ctsio);
11441		ctl_done((union ctl_io *)ctsio);
11442		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11443		return (retval);
11444	} else {
11445		/*
11446		 * Make sure we support this particular command on this LUN.
11447		 * e.g., we don't support writes to the control LUN.
11448		 */
11449		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11450			mtx_unlock(&lun->lun_lock);
11451			ctl_set_invalid_opcode(ctsio);
11452			ctl_done((union ctl_io *)ctsio);
11453			return (retval);
11454		}
11455	}
11456
11457	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11458
11459#ifdef CTL_WITH_CA
11460	/*
11461	 * If we've got a request sense, it'll clear the contingent
11462	 * allegiance condition.  Otherwise, if we have a CA condition for
11463	 * this initiator, clear it, because it sent down a command other
11464	 * than request sense.
11465	 */
11466	if ((ctsio->cdb[0] != REQUEST_SENSE)
11467	 && (ctl_is_set(lun->have_ca, initidx)))
11468		ctl_clear_mask(lun->have_ca, initidx);
11469#endif
11470
11471	/*
11472	 * If the command has this flag set, it handles its own unit
11473	 * attention reporting, we shouldn't do anything.  Otherwise we
11474	 * check for any pending unit attentions, and send them back to the
11475	 * initiator.  We only do this when a command initially comes in,
11476	 * not when we pull it off the blocked queue.
11477	 *
11478	 * According to SAM-3, section 5.3.2, the order that things get
11479	 * presented back to the host is basically unit attentions caused
11480	 * by some sort of reset event, busy status, reservation conflicts
11481	 * or task set full, and finally any other status.
11482	 *
11483	 * One issue here is that some of the unit attentions we report
11484	 * don't fall into the "reset" category (e.g. "reported luns data
11485	 * has changed").  So reporting it here, before the reservation
11486	 * check, may be technically wrong.  I guess the only thing to do
11487	 * would be to check for and report the reset events here, and then
11488	 * check for the other unit attention types after we check for a
11489	 * reservation conflict.
11490	 *
11491	 * XXX KDM need to fix this
11492	 */
11493	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11494		ctl_ua_type ua_type;
11495
11496		if (lun->pending_ua[initidx] != CTL_UA_NONE) {
11497			scsi_sense_data_type sense_format;
11498
11499			if (lun != NULL)
11500				sense_format = (lun->flags &
11501				    CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11502				    SSD_TYPE_FIXED;
11503			else
11504				sense_format = SSD_TYPE_FIXED;
11505
11506			ua_type = ctl_build_ua(&lun->pending_ua[initidx],
11507			    &ctsio->sense_data, sense_format);
11508			if (ua_type != CTL_UA_NONE) {
11509				ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11510				ctsio->io_hdr.status = CTL_SCSI_ERROR |
11511						       CTL_AUTOSENSE;
11512				ctsio->sense_len = SSD_FULL_SIZE;
11513				mtx_unlock(&lun->lun_lock);
11514				ctl_done((union ctl_io *)ctsio);
11515				return (retval);
11516			}
11517		}
11518	}
11519
11520
11521	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11522		mtx_unlock(&lun->lun_lock);
11523		ctl_done((union ctl_io *)ctsio);
11524		return (retval);
11525	}
11526
11527	/*
11528	 * XXX CHD this is where we want to send IO to other side if
11529	 * this LUN is secondary on this SC. We will need to make a copy
11530	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11531	 * the copy we send as FROM_OTHER.
11532	 * We also need to stuff the address of the original IO so we can
11533	 * find it easily. Something similar will need be done on the other
11534	 * side so when we are done we can find the copy.
11535	 */
11536	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11537		union ctl_ha_msg msg_info;
11538		int isc_retval;
11539
11540		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11541
11542		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11543		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11544#if 0
11545		printf("1. ctsio %p\n", ctsio);
11546#endif
11547		msg_info.hdr.serializing_sc = NULL;
11548		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11549		msg_info.scsi.tag_num = ctsio->tag_num;
11550		msg_info.scsi.tag_type = ctsio->tag_type;
11551		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11552
11553		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11554
11555		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11556		    (void *)&msg_info, sizeof(msg_info), 0)) >
11557		    CTL_HA_STATUS_SUCCESS) {
11558			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11559			       isc_retval);
11560			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11561		} else {
11562#if 0
11563			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11564#endif
11565		}
11566
11567		/*
11568		 * XXX KDM this I/O is off the incoming queue, but hasn't
11569		 * been inserted on any other queue.  We may need to come
11570		 * up with a holding queue while we wait for serialization
11571		 * so that we have an idea of what we're waiting for from
11572		 * the other side.
11573		 */
11574		mtx_unlock(&lun->lun_lock);
11575		return (retval);
11576	}
11577
11578	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11579			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11580			      ctl_ooaq, ooa_links))) {
11581	case CTL_ACTION_BLOCK:
11582		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11583		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11584				  blocked_links);
11585		mtx_unlock(&lun->lun_lock);
11586		return (retval);
11587	case CTL_ACTION_PASS:
11588	case CTL_ACTION_SKIP:
11589		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11590		mtx_unlock(&lun->lun_lock);
11591		ctl_enqueue_rtr((union ctl_io *)ctsio);
11592		break;
11593	case CTL_ACTION_OVERLAP:
11594		mtx_unlock(&lun->lun_lock);
11595		ctl_set_overlapped_cmd(ctsio);
11596		ctl_done((union ctl_io *)ctsio);
11597		break;
11598	case CTL_ACTION_OVERLAP_TAG:
11599		mtx_unlock(&lun->lun_lock);
11600		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11601		ctl_done((union ctl_io *)ctsio);
11602		break;
11603	case CTL_ACTION_ERROR:
11604	default:
11605		mtx_unlock(&lun->lun_lock);
11606		ctl_set_internal_failure(ctsio,
11607					 /*sks_valid*/ 0,
11608					 /*retry_count*/ 0);
11609		ctl_done((union ctl_io *)ctsio);
11610		break;
11611	}
11612	return (retval);
11613}
11614
11615const struct ctl_cmd_entry *
11616ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11617{
11618	const struct ctl_cmd_entry *entry;
11619	int service_action;
11620
11621	entry = &ctl_cmd_table[ctsio->cdb[0]];
11622	if (sa)
11623		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11624	if (entry->flags & CTL_CMD_FLAG_SA5) {
11625		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11626		entry = &((const struct ctl_cmd_entry *)
11627		    entry->execute)[service_action];
11628	}
11629	return (entry);
11630}
11631
11632const struct ctl_cmd_entry *
11633ctl_validate_command(struct ctl_scsiio *ctsio)
11634{
11635	const struct ctl_cmd_entry *entry;
11636	int i, sa;
11637	uint8_t diff;
11638
11639	entry = ctl_get_cmd_entry(ctsio, &sa);
11640	if (entry->execute == NULL) {
11641		if (sa)
11642			ctl_set_invalid_field(ctsio,
11643					      /*sks_valid*/ 1,
11644					      /*command*/ 1,
11645					      /*field*/ 1,
11646					      /*bit_valid*/ 1,
11647					      /*bit*/ 4);
11648		else
11649			ctl_set_invalid_opcode(ctsio);
11650		ctl_done((union ctl_io *)ctsio);
11651		return (NULL);
11652	}
11653	KASSERT(entry->length > 0,
11654	    ("Not defined length for command 0x%02x/0x%02x",
11655	     ctsio->cdb[0], ctsio->cdb[1]));
11656	for (i = 1; i < entry->length; i++) {
11657		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11658		if (diff == 0)
11659			continue;
11660		ctl_set_invalid_field(ctsio,
11661				      /*sks_valid*/ 1,
11662				      /*command*/ 1,
11663				      /*field*/ i,
11664				      /*bit_valid*/ 1,
11665				      /*bit*/ fls(diff) - 1);
11666		ctl_done((union ctl_io *)ctsio);
11667		return (NULL);
11668	}
11669	return (entry);
11670}
11671
11672static int
11673ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11674{
11675
11676	switch (lun_type) {
11677	case T_PROCESSOR:
11678		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11679		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11680			return (0);
11681		break;
11682	case T_DIRECT:
11683		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11684		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11685			return (0);
11686		break;
11687	default:
11688		return (0);
11689	}
11690	return (1);
11691}
11692
11693static int
11694ctl_scsiio(struct ctl_scsiio *ctsio)
11695{
11696	int retval;
11697	const struct ctl_cmd_entry *entry;
11698
11699	retval = CTL_RETVAL_COMPLETE;
11700
11701	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11702
11703	entry = ctl_get_cmd_entry(ctsio, NULL);
11704
11705	/*
11706	 * If this I/O has been aborted, just send it straight to
11707	 * ctl_done() without executing it.
11708	 */
11709	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11710		ctl_done((union ctl_io *)ctsio);
11711		goto bailout;
11712	}
11713
11714	/*
11715	 * All the checks should have been handled by ctl_scsiio_precheck().
11716	 * We should be clear now to just execute the I/O.
11717	 */
11718	retval = entry->execute(ctsio);
11719
11720bailout:
11721	return (retval);
11722}
11723
11724/*
11725 * Since we only implement one target right now, a bus reset simply resets
11726 * our single target.
11727 */
11728static int
11729ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11730{
11731	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11732}
11733
11734static int
11735ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11736		 ctl_ua_type ua_type)
11737{
11738	struct ctl_lun *lun;
11739	int retval;
11740
11741	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11742		union ctl_ha_msg msg_info;
11743
11744		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11745		msg_info.hdr.nexus = io->io_hdr.nexus;
11746		if (ua_type==CTL_UA_TARG_RESET)
11747			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11748		else
11749			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11750		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11751		msg_info.hdr.original_sc = NULL;
11752		msg_info.hdr.serializing_sc = NULL;
11753		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11754		    (void *)&msg_info, sizeof(msg_info), 0)) {
11755		}
11756	}
11757	retval = 0;
11758
11759	mtx_lock(&ctl_softc->ctl_lock);
11760	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11761		retval += ctl_lun_reset(lun, io, ua_type);
11762	mtx_unlock(&ctl_softc->ctl_lock);
11763
11764	return (retval);
11765}
11766
11767/*
11768 * The LUN should always be set.  The I/O is optional, and is used to
11769 * distinguish between I/Os sent by this initiator, and by other
11770 * initiators.  We set unit attention for initiators other than this one.
11771 * SAM-3 is vague on this point.  It does say that a unit attention should
11772 * be established for other initiators when a LUN is reset (see section
11773 * 5.7.3), but it doesn't specifically say that the unit attention should
11774 * be established for this particular initiator when a LUN is reset.  Here
11775 * is the relevant text, from SAM-3 rev 8:
11776 *
11777 * 5.7.2 When a SCSI initiator port aborts its own tasks
11778 *
11779 * When a SCSI initiator port causes its own task(s) to be aborted, no
11780 * notification that the task(s) have been aborted shall be returned to
11781 * the SCSI initiator port other than the completion response for the
11782 * command or task management function action that caused the task(s) to
11783 * be aborted and notification(s) associated with related effects of the
11784 * action (e.g., a reset unit attention condition).
11785 *
11786 * XXX KDM for now, we're setting unit attention for all initiators.
11787 */
11788static int
11789ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11790{
11791	union ctl_io *xio;
11792#if 0
11793	uint32_t initidx;
11794#endif
11795	int i;
11796
11797	mtx_lock(&lun->lun_lock);
11798	/*
11799	 * Run through the OOA queue and abort each I/O.
11800	 */
11801#if 0
11802	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11803#endif
11804	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11805	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11806		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11807	}
11808
11809	/*
11810	 * This version sets unit attention for every
11811	 */
11812#if 0
11813	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11814	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11815		if (initidx == i)
11816			continue;
11817		lun->pending_ua[i] |= ua_type;
11818	}
11819#endif
11820
11821	/*
11822	 * A reset (any kind, really) clears reservations established with
11823	 * RESERVE/RELEASE.  It does not clear reservations established
11824	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11825	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11826	 * reservations made with the RESERVE/RELEASE commands, because
11827	 * those commands are obsolete in SPC-3.
11828	 */
11829	lun->flags &= ~CTL_LUN_RESERVED;
11830
11831	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11832#ifdef CTL_WITH_CA
11833		ctl_clear_mask(lun->have_ca, i);
11834#endif
11835		lun->pending_ua[i] |= ua_type;
11836	}
11837	mtx_unlock(&lun->lun_lock);
11838
11839	return (0);
11840}
11841
11842static void
11843ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11844    int other_sc)
11845{
11846	union ctl_io *xio;
11847
11848	mtx_assert(&lun->lun_lock, MA_OWNED);
11849
11850	/*
11851	 * Run through the OOA queue and attempt to find the given I/O.
11852	 * The target port, initiator ID, tag type and tag number have to
11853	 * match the values that we got from the initiator.  If we have an
11854	 * untagged command to abort, simply abort the first untagged command
11855	 * we come to.  We only allow one untagged command at a time of course.
11856	 */
11857	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11858	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11859
11860		if ((targ_port == UINT32_MAX ||
11861		     targ_port == xio->io_hdr.nexus.targ_port) &&
11862		    (init_id == UINT32_MAX ||
11863		     init_id == xio->io_hdr.nexus.initid.id)) {
11864			if (targ_port != xio->io_hdr.nexus.targ_port ||
11865			    init_id != xio->io_hdr.nexus.initid.id)
11866				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11867			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11868			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11869				union ctl_ha_msg msg_info;
11870
11871				msg_info.hdr.nexus = xio->io_hdr.nexus;
11872				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11873				msg_info.task.tag_num = xio->scsiio.tag_num;
11874				msg_info.task.tag_type = xio->scsiio.tag_type;
11875				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11876				msg_info.hdr.original_sc = NULL;
11877				msg_info.hdr.serializing_sc = NULL;
11878				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11879				    (void *)&msg_info, sizeof(msg_info), 0);
11880			}
11881		}
11882	}
11883}
11884
11885static int
11886ctl_abort_task_set(union ctl_io *io)
11887{
11888	struct ctl_softc *softc = control_softc;
11889	struct ctl_lun *lun;
11890	uint32_t targ_lun;
11891
11892	/*
11893	 * Look up the LUN.
11894	 */
11895	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11896	mtx_lock(&softc->ctl_lock);
11897	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
11898		lun = softc->ctl_luns[targ_lun];
11899	else {
11900		mtx_unlock(&softc->ctl_lock);
11901		return (1);
11902	}
11903
11904	mtx_lock(&lun->lun_lock);
11905	mtx_unlock(&softc->ctl_lock);
11906	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11907		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11908		    io->io_hdr.nexus.initid.id,
11909		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11910	} else { /* CTL_TASK_CLEAR_TASK_SET */
11911		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11912		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11913	}
11914	mtx_unlock(&lun->lun_lock);
11915	return (0);
11916}
11917
11918static int
11919ctl_i_t_nexus_reset(union ctl_io *io)
11920{
11921	struct ctl_softc *softc = control_softc;
11922	struct ctl_lun *lun;
11923	uint32_t initidx, residx;
11924
11925	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11926	residx = ctl_get_resindex(&io->io_hdr.nexus);
11927	mtx_lock(&softc->ctl_lock);
11928	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11929		mtx_lock(&lun->lun_lock);
11930		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11931		    io->io_hdr.nexus.initid.id,
11932		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11933#ifdef CTL_WITH_CA
11934		ctl_clear_mask(lun->have_ca, initidx);
11935#endif
11936		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
11937			lun->flags &= ~CTL_LUN_RESERVED;
11938		lun->pending_ua[initidx] |= CTL_UA_I_T_NEXUS_LOSS;
11939		mtx_unlock(&lun->lun_lock);
11940	}
11941	mtx_unlock(&softc->ctl_lock);
11942	return (0);
11943}
11944
11945static int
11946ctl_abort_task(union ctl_io *io)
11947{
11948	union ctl_io *xio;
11949	struct ctl_lun *lun;
11950	struct ctl_softc *ctl_softc;
11951#if 0
11952	struct sbuf sb;
11953	char printbuf[128];
11954#endif
11955	int found;
11956	uint32_t targ_lun;
11957
11958	ctl_softc = control_softc;
11959	found = 0;
11960
11961	/*
11962	 * Look up the LUN.
11963	 */
11964	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11965	mtx_lock(&ctl_softc->ctl_lock);
11966	if ((targ_lun < CTL_MAX_LUNS)
11967	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
11968		lun = ctl_softc->ctl_luns[targ_lun];
11969	else {
11970		mtx_unlock(&ctl_softc->ctl_lock);
11971		return (1);
11972	}
11973
11974#if 0
11975	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11976	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11977#endif
11978
11979	mtx_lock(&lun->lun_lock);
11980	mtx_unlock(&ctl_softc->ctl_lock);
11981	/*
11982	 * Run through the OOA queue and attempt to find the given I/O.
11983	 * The target port, initiator ID, tag type and tag number have to
11984	 * match the values that we got from the initiator.  If we have an
11985	 * untagged command to abort, simply abort the first untagged command
11986	 * we come to.  We only allow one untagged command at a time of course.
11987	 */
11988#if 0
11989	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11990#endif
11991	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11992	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11993#if 0
11994		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
11995
11996		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
11997			    lun->lun, xio->scsiio.tag_num,
11998			    xio->scsiio.tag_type,
11999			    (xio->io_hdr.blocked_links.tqe_prev
12000			    == NULL) ? "" : " BLOCKED",
12001			    (xio->io_hdr.flags &
12002			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12003			    (xio->io_hdr.flags &
12004			    CTL_FLAG_ABORT) ? " ABORT" : "",
12005			    (xio->io_hdr.flags &
12006			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12007		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12008		sbuf_finish(&sb);
12009		printf("%s\n", sbuf_data(&sb));
12010#endif
12011
12012		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12013		 && (xio->io_hdr.nexus.initid.id ==
12014		     io->io_hdr.nexus.initid.id)) {
12015			/*
12016			 * If the abort says that the task is untagged, the
12017			 * task in the queue must be untagged.  Otherwise,
12018			 * we just check to see whether the tag numbers
12019			 * match.  This is because the QLogic firmware
12020			 * doesn't pass back the tag type in an abort
12021			 * request.
12022			 */
12023#if 0
12024			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12025			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12026			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12027#endif
12028			/*
12029			 * XXX KDM we've got problems with FC, because it
12030			 * doesn't send down a tag type with aborts.  So we
12031			 * can only really go by the tag number...
12032			 * This may cause problems with parallel SCSI.
12033			 * Need to figure that out!!
12034			 */
12035			if (xio->scsiio.tag_num == io->taskio.tag_num) {
12036				xio->io_hdr.flags |= CTL_FLAG_ABORT;
12037				found = 1;
12038				if ((io->io_hdr.flags &
12039				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
12040				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12041					union ctl_ha_msg msg_info;
12042
12043					io->io_hdr.flags |=
12044					                CTL_FLAG_SENT_2OTHER_SC;
12045					msg_info.hdr.nexus = io->io_hdr.nexus;
12046					msg_info.task.task_action =
12047						CTL_TASK_ABORT_TASK;
12048					msg_info.task.tag_num =
12049						io->taskio.tag_num;
12050					msg_info.task.tag_type =
12051						io->taskio.tag_type;
12052					msg_info.hdr.msg_type =
12053						CTL_MSG_MANAGE_TASKS;
12054					msg_info.hdr.original_sc = NULL;
12055					msg_info.hdr.serializing_sc = NULL;
12056#if 0
12057					printf("Sent Abort to other side\n");
12058#endif
12059					if (CTL_HA_STATUS_SUCCESS !=
12060					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12061		    				(void *)&msg_info,
12062						sizeof(msg_info), 0)) {
12063					}
12064				}
12065#if 0
12066				printf("ctl_abort_task: found I/O to abort\n");
12067#endif
12068				break;
12069			}
12070		}
12071	}
12072	mtx_unlock(&lun->lun_lock);
12073
12074	if (found == 0) {
12075		/*
12076		 * This isn't really an error.  It's entirely possible for
12077		 * the abort and command completion to cross on the wire.
12078		 * This is more of an informative/diagnostic error.
12079		 */
12080#if 0
12081		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12082		       "%d:%d:%d:%d tag %d type %d\n",
12083		       io->io_hdr.nexus.initid.id,
12084		       io->io_hdr.nexus.targ_port,
12085		       io->io_hdr.nexus.targ_target.id,
12086		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12087		       io->taskio.tag_type);
12088#endif
12089	}
12090	return (0);
12091}
12092
12093static void
12094ctl_run_task(union ctl_io *io)
12095{
12096	struct ctl_softc *ctl_softc = control_softc;
12097	int retval = 1;
12098	const char *task_desc;
12099
12100	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12101
12102	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12103	    ("ctl_run_task: Unextected io_type %d\n",
12104	     io->io_hdr.io_type));
12105
12106	task_desc = ctl_scsi_task_string(&io->taskio);
12107	if (task_desc != NULL) {
12108#ifdef NEEDTOPORT
12109		csevent_log(CSC_CTL | CSC_SHELF_SW |
12110			    CTL_TASK_REPORT,
12111			    csevent_LogType_Trace,
12112			    csevent_Severity_Information,
12113			    csevent_AlertLevel_Green,
12114			    csevent_FRU_Firmware,
12115			    csevent_FRU_Unknown,
12116			    "CTL: received task: %s",task_desc);
12117#endif
12118	} else {
12119#ifdef NEEDTOPORT
12120		csevent_log(CSC_CTL | CSC_SHELF_SW |
12121			    CTL_TASK_REPORT,
12122			    csevent_LogType_Trace,
12123			    csevent_Severity_Information,
12124			    csevent_AlertLevel_Green,
12125			    csevent_FRU_Firmware,
12126			    csevent_FRU_Unknown,
12127			    "CTL: received unknown task "
12128			    "type: %d (%#x)",
12129			    io->taskio.task_action,
12130			    io->taskio.task_action);
12131#endif
12132	}
12133	switch (io->taskio.task_action) {
12134	case CTL_TASK_ABORT_TASK:
12135		retval = ctl_abort_task(io);
12136		break;
12137	case CTL_TASK_ABORT_TASK_SET:
12138	case CTL_TASK_CLEAR_TASK_SET:
12139		retval = ctl_abort_task_set(io);
12140		break;
12141	case CTL_TASK_CLEAR_ACA:
12142		break;
12143	case CTL_TASK_I_T_NEXUS_RESET:
12144		retval = ctl_i_t_nexus_reset(io);
12145		break;
12146	case CTL_TASK_LUN_RESET: {
12147		struct ctl_lun *lun;
12148		uint32_t targ_lun;
12149
12150		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12151		mtx_lock(&ctl_softc->ctl_lock);
12152		if ((targ_lun < CTL_MAX_LUNS)
12153		 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12154			lun = ctl_softc->ctl_luns[targ_lun];
12155		else {
12156			mtx_unlock(&ctl_softc->ctl_lock);
12157			retval = 1;
12158			break;
12159		}
12160
12161		if (!(io->io_hdr.flags &
12162		    CTL_FLAG_FROM_OTHER_SC)) {
12163			union ctl_ha_msg msg_info;
12164
12165			io->io_hdr.flags |=
12166				CTL_FLAG_SENT_2OTHER_SC;
12167			msg_info.hdr.msg_type =
12168				CTL_MSG_MANAGE_TASKS;
12169			msg_info.hdr.nexus = io->io_hdr.nexus;
12170			msg_info.task.task_action =
12171				CTL_TASK_LUN_RESET;
12172			msg_info.hdr.original_sc = NULL;
12173			msg_info.hdr.serializing_sc = NULL;
12174			if (CTL_HA_STATUS_SUCCESS !=
12175			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12176			    (void *)&msg_info,
12177			    sizeof(msg_info), 0)) {
12178			}
12179		}
12180
12181		retval = ctl_lun_reset(lun, io,
12182				       CTL_UA_LUN_RESET);
12183		mtx_unlock(&ctl_softc->ctl_lock);
12184		break;
12185	}
12186	case CTL_TASK_TARGET_RESET:
12187		retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12188		break;
12189	case CTL_TASK_BUS_RESET:
12190		retval = ctl_bus_reset(ctl_softc, io);
12191		break;
12192	case CTL_TASK_PORT_LOGIN:
12193		break;
12194	case CTL_TASK_PORT_LOGOUT:
12195		break;
12196	default:
12197		printf("ctl_run_task: got unknown task management event %d\n",
12198		       io->taskio.task_action);
12199		break;
12200	}
12201	if (retval == 0)
12202		io->io_hdr.status = CTL_SUCCESS;
12203	else
12204		io->io_hdr.status = CTL_ERROR;
12205	ctl_done(io);
12206}
12207
12208/*
12209 * For HA operation.  Handle commands that come in from the other
12210 * controller.
12211 */
12212static void
12213ctl_handle_isc(union ctl_io *io)
12214{
12215	int free_io;
12216	struct ctl_lun *lun;
12217	struct ctl_softc *ctl_softc;
12218	uint32_t targ_lun;
12219
12220	ctl_softc = control_softc;
12221
12222	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12223	lun = ctl_softc->ctl_luns[targ_lun];
12224
12225	switch (io->io_hdr.msg_type) {
12226	case CTL_MSG_SERIALIZE:
12227		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12228		break;
12229	case CTL_MSG_R2R: {
12230		const struct ctl_cmd_entry *entry;
12231
12232		/*
12233		 * This is only used in SER_ONLY mode.
12234		 */
12235		free_io = 0;
12236		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12237		mtx_lock(&lun->lun_lock);
12238		if (ctl_scsiio_lun_check(ctl_softc, lun,
12239		    entry, (struct ctl_scsiio *)io) != 0) {
12240			mtx_unlock(&lun->lun_lock);
12241			ctl_done(io);
12242			break;
12243		}
12244		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12245		mtx_unlock(&lun->lun_lock);
12246		ctl_enqueue_rtr(io);
12247		break;
12248	}
12249	case CTL_MSG_FINISH_IO:
12250		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12251			free_io = 0;
12252			ctl_done(io);
12253		} else {
12254			free_io = 1;
12255			mtx_lock(&lun->lun_lock);
12256			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12257				     ooa_links);
12258			ctl_check_blocked(lun);
12259			mtx_unlock(&lun->lun_lock);
12260		}
12261		break;
12262	case CTL_MSG_PERS_ACTION:
12263		ctl_hndl_per_res_out_on_other_sc(
12264			(union ctl_ha_msg *)&io->presio.pr_msg);
12265		free_io = 1;
12266		break;
12267	case CTL_MSG_BAD_JUJU:
12268		free_io = 0;
12269		ctl_done(io);
12270		break;
12271	case CTL_MSG_DATAMOVE:
12272		/* Only used in XFER mode */
12273		free_io = 0;
12274		ctl_datamove_remote(io);
12275		break;
12276	case CTL_MSG_DATAMOVE_DONE:
12277		/* Only used in XFER mode */
12278		free_io = 0;
12279		io->scsiio.be_move_done(io);
12280		break;
12281	default:
12282		free_io = 1;
12283		printf("%s: Invalid message type %d\n",
12284		       __func__, io->io_hdr.msg_type);
12285		break;
12286	}
12287	if (free_io)
12288		ctl_free_io(io);
12289
12290}
12291
12292
12293/*
12294 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12295 * there is no match.
12296 */
12297static ctl_lun_error_pattern
12298ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12299{
12300	const struct ctl_cmd_entry *entry;
12301	ctl_lun_error_pattern filtered_pattern, pattern;
12302
12303	pattern = desc->error_pattern;
12304
12305	/*
12306	 * XXX KDM we need more data passed into this function to match a
12307	 * custom pattern, and we actually need to implement custom pattern
12308	 * matching.
12309	 */
12310	if (pattern & CTL_LUN_PAT_CMD)
12311		return (CTL_LUN_PAT_CMD);
12312
12313	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12314		return (CTL_LUN_PAT_ANY);
12315
12316	entry = ctl_get_cmd_entry(ctsio, NULL);
12317
12318	filtered_pattern = entry->pattern & pattern;
12319
12320	/*
12321	 * If the user requested specific flags in the pattern (e.g.
12322	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12323	 * flags.
12324	 *
12325	 * If the user did not specify any flags, it doesn't matter whether
12326	 * or not the command supports the flags.
12327	 */
12328	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12329	     (pattern & ~CTL_LUN_PAT_MASK))
12330		return (CTL_LUN_PAT_NONE);
12331
12332	/*
12333	 * If the user asked for a range check, see if the requested LBA
12334	 * range overlaps with this command's LBA range.
12335	 */
12336	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12337		uint64_t lba1;
12338		uint64_t len1;
12339		ctl_action action;
12340		int retval;
12341
12342		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12343		if (retval != 0)
12344			return (CTL_LUN_PAT_NONE);
12345
12346		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12347					      desc->lba_range.len);
12348		/*
12349		 * A "pass" means that the LBA ranges don't overlap, so
12350		 * this doesn't match the user's range criteria.
12351		 */
12352		if (action == CTL_ACTION_PASS)
12353			return (CTL_LUN_PAT_NONE);
12354	}
12355
12356	return (filtered_pattern);
12357}
12358
12359static void
12360ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12361{
12362	struct ctl_error_desc *desc, *desc2;
12363
12364	mtx_assert(&lun->lun_lock, MA_OWNED);
12365
12366	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12367		ctl_lun_error_pattern pattern;
12368		/*
12369		 * Check to see whether this particular command matches
12370		 * the pattern in the descriptor.
12371		 */
12372		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12373		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12374			continue;
12375
12376		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12377		case CTL_LUN_INJ_ABORTED:
12378			ctl_set_aborted(&io->scsiio);
12379			break;
12380		case CTL_LUN_INJ_MEDIUM_ERR:
12381			ctl_set_medium_error(&io->scsiio);
12382			break;
12383		case CTL_LUN_INJ_UA:
12384			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12385			 * OCCURRED */
12386			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12387			break;
12388		case CTL_LUN_INJ_CUSTOM:
12389			/*
12390			 * We're assuming the user knows what he is doing.
12391			 * Just copy the sense information without doing
12392			 * checks.
12393			 */
12394			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12395			      ctl_min(sizeof(desc->custom_sense),
12396				      sizeof(io->scsiio.sense_data)));
12397			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12398			io->scsiio.sense_len = SSD_FULL_SIZE;
12399			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12400			break;
12401		case CTL_LUN_INJ_NONE:
12402		default:
12403			/*
12404			 * If this is an error injection type we don't know
12405			 * about, clear the continuous flag (if it is set)
12406			 * so it will get deleted below.
12407			 */
12408			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12409			break;
12410		}
12411		/*
12412		 * By default, each error injection action is a one-shot
12413		 */
12414		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12415			continue;
12416
12417		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12418
12419		free(desc, M_CTL);
12420	}
12421}
12422
12423#ifdef CTL_IO_DELAY
12424static void
12425ctl_datamove_timer_wakeup(void *arg)
12426{
12427	union ctl_io *io;
12428
12429	io = (union ctl_io *)arg;
12430
12431	ctl_datamove(io);
12432}
12433#endif /* CTL_IO_DELAY */
12434
12435void
12436ctl_datamove(union ctl_io *io)
12437{
12438	void (*fe_datamove)(union ctl_io *io);
12439
12440	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12441
12442	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12443
12444#ifdef CTL_TIME_IO
12445	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12446		char str[256];
12447		char path_str[64];
12448		struct sbuf sb;
12449
12450		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12451		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12452
12453		sbuf_cat(&sb, path_str);
12454		switch (io->io_hdr.io_type) {
12455		case CTL_IO_SCSI:
12456			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12457			sbuf_printf(&sb, "\n");
12458			sbuf_cat(&sb, path_str);
12459			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12460				    io->scsiio.tag_num, io->scsiio.tag_type);
12461			break;
12462		case CTL_IO_TASK:
12463			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12464				    "Tag Type: %d\n", io->taskio.task_action,
12465				    io->taskio.tag_num, io->taskio.tag_type);
12466			break;
12467		default:
12468			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12469			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12470			break;
12471		}
12472		sbuf_cat(&sb, path_str);
12473		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12474			    (intmax_t)time_uptime - io->io_hdr.start_time);
12475		sbuf_finish(&sb);
12476		printf("%s", sbuf_data(&sb));
12477	}
12478#endif /* CTL_TIME_IO */
12479
12480#ifdef CTL_IO_DELAY
12481	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12482		struct ctl_lun *lun;
12483
12484		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12485
12486		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12487	} else {
12488		struct ctl_lun *lun;
12489
12490		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12491		if ((lun != NULL)
12492		 && (lun->delay_info.datamove_delay > 0)) {
12493			struct callout *callout;
12494
12495			callout = (struct callout *)&io->io_hdr.timer_bytes;
12496			callout_init(callout, /*mpsafe*/ 1);
12497			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12498			callout_reset(callout,
12499				      lun->delay_info.datamove_delay * hz,
12500				      ctl_datamove_timer_wakeup, io);
12501			if (lun->delay_info.datamove_type ==
12502			    CTL_DELAY_TYPE_ONESHOT)
12503				lun->delay_info.datamove_delay = 0;
12504			return;
12505		}
12506	}
12507#endif
12508
12509	/*
12510	 * This command has been aborted.  Set the port status, so we fail
12511	 * the data move.
12512	 */
12513	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12514		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12515		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12516		       io->io_hdr.nexus.targ_port,
12517		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12518		       io->io_hdr.nexus.targ_lun);
12519		io->io_hdr.port_status = 31337;
12520		/*
12521		 * Note that the backend, in this case, will get the
12522		 * callback in its context.  In other cases it may get
12523		 * called in the frontend's interrupt thread context.
12524		 */
12525		io->scsiio.be_move_done(io);
12526		return;
12527	}
12528
12529	/* Don't confuse frontend with zero length data move. */
12530	if (io->scsiio.kern_data_len == 0) {
12531		io->scsiio.be_move_done(io);
12532		return;
12533	}
12534
12535	/*
12536	 * If we're in XFER mode and this I/O is from the other shelf
12537	 * controller, we need to send the DMA to the other side to
12538	 * actually transfer the data to/from the host.  In serialize only
12539	 * mode the transfer happens below CTL and ctl_datamove() is only
12540	 * called on the machine that originally received the I/O.
12541	 */
12542	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12543	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12544		union ctl_ha_msg msg;
12545		uint32_t sg_entries_sent;
12546		int do_sg_copy;
12547		int i;
12548
12549		memset(&msg, 0, sizeof(msg));
12550		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12551		msg.hdr.original_sc = io->io_hdr.original_sc;
12552		msg.hdr.serializing_sc = io;
12553		msg.hdr.nexus = io->io_hdr.nexus;
12554		msg.dt.flags = io->io_hdr.flags;
12555		/*
12556		 * We convert everything into a S/G list here.  We can't
12557		 * pass by reference, only by value between controllers.
12558		 * So we can't pass a pointer to the S/G list, only as many
12559		 * S/G entries as we can fit in here.  If it's possible for
12560		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12561		 * then we need to break this up into multiple transfers.
12562		 */
12563		if (io->scsiio.kern_sg_entries == 0) {
12564			msg.dt.kern_sg_entries = 1;
12565			/*
12566			 * If this is in cached memory, flush the cache
12567			 * before we send the DMA request to the other
12568			 * controller.  We want to do this in either the
12569			 * read or the write case.  The read case is
12570			 * straightforward.  In the write case, we want to
12571			 * make sure nothing is in the local cache that
12572			 * could overwrite the DMAed data.
12573			 */
12574			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12575				/*
12576				 * XXX KDM use bus_dmamap_sync() here.
12577				 */
12578			}
12579
12580			/*
12581			 * Convert to a physical address if this is a
12582			 * virtual address.
12583			 */
12584			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12585				msg.dt.sg_list[0].addr =
12586					io->scsiio.kern_data_ptr;
12587			} else {
12588				/*
12589				 * XXX KDM use busdma here!
12590				 */
12591#if 0
12592				msg.dt.sg_list[0].addr = (void *)
12593					vtophys(io->scsiio.kern_data_ptr);
12594#endif
12595			}
12596
12597			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12598			do_sg_copy = 0;
12599		} else {
12600			struct ctl_sg_entry *sgl;
12601
12602			do_sg_copy = 1;
12603			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12604			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12605			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12606				/*
12607				 * XXX KDM use bus_dmamap_sync() here.
12608				 */
12609			}
12610		}
12611
12612		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12613		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12614		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12615		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12616		msg.dt.sg_sequence = 0;
12617
12618		/*
12619		 * Loop until we've sent all of the S/G entries.  On the
12620		 * other end, we'll recompose these S/G entries into one
12621		 * contiguous list before passing it to the
12622		 */
12623		for (sg_entries_sent = 0; sg_entries_sent <
12624		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12625			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12626				sizeof(msg.dt.sg_list[0])),
12627				msg.dt.kern_sg_entries - sg_entries_sent);
12628
12629			if (do_sg_copy != 0) {
12630				struct ctl_sg_entry *sgl;
12631				int j;
12632
12633				sgl = (struct ctl_sg_entry *)
12634					io->scsiio.kern_data_ptr;
12635				/*
12636				 * If this is in cached memory, flush the cache
12637				 * before we send the DMA request to the other
12638				 * controller.  We want to do this in either
12639				 * the * read or the write case.  The read
12640				 * case is straightforward.  In the write
12641				 * case, we want to make sure nothing is
12642				 * in the local cache that could overwrite
12643				 * the DMAed data.
12644				 */
12645
12646				for (i = sg_entries_sent, j = 0;
12647				     i < msg.dt.cur_sg_entries; i++, j++) {
12648					if ((io->io_hdr.flags &
12649					     CTL_FLAG_NO_DATASYNC) == 0) {
12650						/*
12651						 * XXX KDM use bus_dmamap_sync()
12652						 */
12653					}
12654					if ((io->io_hdr.flags &
12655					     CTL_FLAG_BUS_ADDR) == 0) {
12656						/*
12657						 * XXX KDM use busdma.
12658						 */
12659#if 0
12660						msg.dt.sg_list[j].addr =(void *)
12661						       vtophys(sgl[i].addr);
12662#endif
12663					} else {
12664						msg.dt.sg_list[j].addr =
12665							sgl[i].addr;
12666					}
12667					msg.dt.sg_list[j].len = sgl[i].len;
12668				}
12669			}
12670
12671			sg_entries_sent += msg.dt.cur_sg_entries;
12672			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12673				msg.dt.sg_last = 1;
12674			else
12675				msg.dt.sg_last = 0;
12676
12677			/*
12678			 * XXX KDM drop and reacquire the lock here?
12679			 */
12680			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12681			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12682				/*
12683				 * XXX do something here.
12684				 */
12685			}
12686
12687			msg.dt.sent_sg_entries = sg_entries_sent;
12688		}
12689		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12690		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12691			ctl_failover_io(io, /*have_lock*/ 0);
12692
12693	} else {
12694
12695		/*
12696		 * Lookup the fe_datamove() function for this particular
12697		 * front end.
12698		 */
12699		fe_datamove =
12700		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12701
12702		fe_datamove(io);
12703	}
12704}
12705
12706static void
12707ctl_send_datamove_done(union ctl_io *io, int have_lock)
12708{
12709	union ctl_ha_msg msg;
12710	int isc_status;
12711
12712	memset(&msg, 0, sizeof(msg));
12713
12714	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12715	msg.hdr.original_sc = io;
12716	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12717	msg.hdr.nexus = io->io_hdr.nexus;
12718	msg.hdr.status = io->io_hdr.status;
12719	msg.scsi.tag_num = io->scsiio.tag_num;
12720	msg.scsi.tag_type = io->scsiio.tag_type;
12721	msg.scsi.scsi_status = io->scsiio.scsi_status;
12722	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12723	       sizeof(io->scsiio.sense_data));
12724	msg.scsi.sense_len = io->scsiio.sense_len;
12725	msg.scsi.sense_residual = io->scsiio.sense_residual;
12726	msg.scsi.fetd_status = io->io_hdr.port_status;
12727	msg.scsi.residual = io->scsiio.residual;
12728	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12729
12730	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12731		ctl_failover_io(io, /*have_lock*/ have_lock);
12732		return;
12733	}
12734
12735	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12736	if (isc_status > CTL_HA_STATUS_SUCCESS) {
12737		/* XXX do something if this fails */
12738	}
12739
12740}
12741
12742/*
12743 * The DMA to the remote side is done, now we need to tell the other side
12744 * we're done so it can continue with its data movement.
12745 */
12746static void
12747ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12748{
12749	union ctl_io *io;
12750
12751	io = rq->context;
12752
12753	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12754		printf("%s: ISC DMA write failed with error %d", __func__,
12755		       rq->ret);
12756		ctl_set_internal_failure(&io->scsiio,
12757					 /*sks_valid*/ 1,
12758					 /*retry_count*/ rq->ret);
12759	}
12760
12761	ctl_dt_req_free(rq);
12762
12763	/*
12764	 * In this case, we had to malloc the memory locally.  Free it.
12765	 */
12766	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12767		int i;
12768		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12769			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12770	}
12771	/*
12772	 * The data is in local and remote memory, so now we need to send
12773	 * status (good or back) back to the other side.
12774	 */
12775	ctl_send_datamove_done(io, /*have_lock*/ 0);
12776}
12777
12778/*
12779 * We've moved the data from the host/controller into local memory.  Now we
12780 * need to push it over to the remote controller's memory.
12781 */
12782static int
12783ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12784{
12785	int retval;
12786
12787	retval = 0;
12788
12789	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12790					  ctl_datamove_remote_write_cb);
12791
12792	return (retval);
12793}
12794
12795static void
12796ctl_datamove_remote_write(union ctl_io *io)
12797{
12798	int retval;
12799	void (*fe_datamove)(union ctl_io *io);
12800
12801	/*
12802	 * - Get the data from the host/HBA into local memory.
12803	 * - DMA memory from the local controller to the remote controller.
12804	 * - Send status back to the remote controller.
12805	 */
12806
12807	retval = ctl_datamove_remote_sgl_setup(io);
12808	if (retval != 0)
12809		return;
12810
12811	/* Switch the pointer over so the FETD knows what to do */
12812	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12813
12814	/*
12815	 * Use a custom move done callback, since we need to send completion
12816	 * back to the other controller, not to the backend on this side.
12817	 */
12818	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12819
12820	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12821
12822	fe_datamove(io);
12823
12824	return;
12825
12826}
12827
12828static int
12829ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12830{
12831#if 0
12832	char str[256];
12833	char path_str[64];
12834	struct sbuf sb;
12835#endif
12836
12837	/*
12838	 * In this case, we had to malloc the memory locally.  Free it.
12839	 */
12840	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12841		int i;
12842		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12843			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12844	}
12845
12846#if 0
12847	scsi_path_string(io, path_str, sizeof(path_str));
12848	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12849	sbuf_cat(&sb, path_str);
12850	scsi_command_string(&io->scsiio, NULL, &sb);
12851	sbuf_printf(&sb, "\n");
12852	sbuf_cat(&sb, path_str);
12853	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12854		    io->scsiio.tag_num, io->scsiio.tag_type);
12855	sbuf_cat(&sb, path_str);
12856	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12857		    io->io_hdr.flags, io->io_hdr.status);
12858	sbuf_finish(&sb);
12859	printk("%s", sbuf_data(&sb));
12860#endif
12861
12862
12863	/*
12864	 * The read is done, now we need to send status (good or bad) back
12865	 * to the other side.
12866	 */
12867	ctl_send_datamove_done(io, /*have_lock*/ 0);
12868
12869	return (0);
12870}
12871
12872static void
12873ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12874{
12875	union ctl_io *io;
12876	void (*fe_datamove)(union ctl_io *io);
12877
12878	io = rq->context;
12879
12880	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12881		printf("%s: ISC DMA read failed with error %d", __func__,
12882		       rq->ret);
12883		ctl_set_internal_failure(&io->scsiio,
12884					 /*sks_valid*/ 1,
12885					 /*retry_count*/ rq->ret);
12886	}
12887
12888	ctl_dt_req_free(rq);
12889
12890	/* Switch the pointer over so the FETD knows what to do */
12891	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12892
12893	/*
12894	 * Use a custom move done callback, since we need to send completion
12895	 * back to the other controller, not to the backend on this side.
12896	 */
12897	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12898
12899	/* XXX KDM add checks like the ones in ctl_datamove? */
12900
12901	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12902
12903	fe_datamove(io);
12904}
12905
12906static int
12907ctl_datamove_remote_sgl_setup(union ctl_io *io)
12908{
12909	struct ctl_sg_entry *local_sglist, *remote_sglist;
12910	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
12911	struct ctl_softc *softc;
12912	int retval;
12913	int i;
12914
12915	retval = 0;
12916	softc = control_softc;
12917
12918	local_sglist = io->io_hdr.local_sglist;
12919	local_dma_sglist = io->io_hdr.local_dma_sglist;
12920	remote_sglist = io->io_hdr.remote_sglist;
12921	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
12922
12923	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
12924		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
12925			local_sglist[i].len = remote_sglist[i].len;
12926
12927			/*
12928			 * XXX Detect the situation where the RS-level I/O
12929			 * redirector on the other side has already read the
12930			 * data off of the AOR RS on this side, and
12931			 * transferred it to remote (mirror) memory on the
12932			 * other side.  Since we already have the data in
12933			 * memory here, we just need to use it.
12934			 *
12935			 * XXX KDM this can probably be removed once we
12936			 * get the cache device code in and take the
12937			 * current AOR implementation out.
12938			 */
12939#ifdef NEEDTOPORT
12940			if ((remote_sglist[i].addr >=
12941			     (void *)vtophys(softc->mirr->addr))
12942			 && (remote_sglist[i].addr <
12943			     ((void *)vtophys(softc->mirr->addr) +
12944			     CacheMirrorOffset))) {
12945				local_sglist[i].addr = remote_sglist[i].addr -
12946					CacheMirrorOffset;
12947				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12948				     CTL_FLAG_DATA_IN)
12949					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
12950			} else {
12951				local_sglist[i].addr = remote_sglist[i].addr +
12952					CacheMirrorOffset;
12953			}
12954#endif
12955#if 0
12956			printf("%s: local %p, remote %p, len %d\n",
12957			       __func__, local_sglist[i].addr,
12958			       remote_sglist[i].addr, local_sglist[i].len);
12959#endif
12960		}
12961	} else {
12962		uint32_t len_to_go;
12963
12964		/*
12965		 * In this case, we don't have automatically allocated
12966		 * memory for this I/O on this controller.  This typically
12967		 * happens with internal CTL I/O -- e.g. inquiry, mode
12968		 * sense, etc.  Anything coming from RAIDCore will have
12969		 * a mirror area available.
12970		 */
12971		len_to_go = io->scsiio.kern_data_len;
12972
12973		/*
12974		 * Clear the no datasync flag, we have to use malloced
12975		 * buffers.
12976		 */
12977		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
12978
12979		/*
12980		 * The difficult thing here is that the size of the various
12981		 * S/G segments may be different than the size from the
12982		 * remote controller.  That'll make it harder when DMAing
12983		 * the data back to the other side.
12984		 */
12985		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
12986		     sizeof(io->io_hdr.remote_sglist[0])) &&
12987		     (len_to_go > 0); i++) {
12988			local_sglist[i].len = ctl_min(len_to_go, 131072);
12989			CTL_SIZE_8B(local_dma_sglist[i].len,
12990				    local_sglist[i].len);
12991			local_sglist[i].addr =
12992				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
12993
12994			local_dma_sglist[i].addr = local_sglist[i].addr;
12995
12996			if (local_sglist[i].addr == NULL) {
12997				int j;
12998
12999				printf("malloc failed for %zd bytes!",
13000				       local_dma_sglist[i].len);
13001				for (j = 0; j < i; j++) {
13002					free(local_sglist[j].addr, M_CTL);
13003				}
13004				ctl_set_internal_failure(&io->scsiio,
13005							 /*sks_valid*/ 1,
13006							 /*retry_count*/ 4857);
13007				retval = 1;
13008				goto bailout_error;
13009
13010			}
13011			/* XXX KDM do we need a sync here? */
13012
13013			len_to_go -= local_sglist[i].len;
13014		}
13015		/*
13016		 * Reset the number of S/G entries accordingly.  The
13017		 * original number of S/G entries is available in
13018		 * rem_sg_entries.
13019		 */
13020		io->scsiio.kern_sg_entries = i;
13021
13022#if 0
13023		printf("%s: kern_sg_entries = %d\n", __func__,
13024		       io->scsiio.kern_sg_entries);
13025		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13026			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13027			       local_sglist[i].addr, local_sglist[i].len,
13028			       local_dma_sglist[i].len);
13029#endif
13030	}
13031
13032
13033	return (retval);
13034
13035bailout_error:
13036
13037	ctl_send_datamove_done(io, /*have_lock*/ 0);
13038
13039	return (retval);
13040}
13041
13042static int
13043ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13044			 ctl_ha_dt_cb callback)
13045{
13046	struct ctl_ha_dt_req *rq;
13047	struct ctl_sg_entry *remote_sglist, *local_sglist;
13048	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13049	uint32_t local_used, remote_used, total_used;
13050	int retval;
13051	int i, j;
13052
13053	retval = 0;
13054
13055	rq = ctl_dt_req_alloc();
13056
13057	/*
13058	 * If we failed to allocate the request, and if the DMA didn't fail
13059	 * anyway, set busy status.  This is just a resource allocation
13060	 * failure.
13061	 */
13062	if ((rq == NULL)
13063	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13064		ctl_set_busy(&io->scsiio);
13065
13066	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13067
13068		if (rq != NULL)
13069			ctl_dt_req_free(rq);
13070
13071		/*
13072		 * The data move failed.  We need to return status back
13073		 * to the other controller.  No point in trying to DMA
13074		 * data to the remote controller.
13075		 */
13076
13077		ctl_send_datamove_done(io, /*have_lock*/ 0);
13078
13079		retval = 1;
13080
13081		goto bailout;
13082	}
13083
13084	local_sglist = io->io_hdr.local_sglist;
13085	local_dma_sglist = io->io_hdr.local_dma_sglist;
13086	remote_sglist = io->io_hdr.remote_sglist;
13087	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13088	local_used = 0;
13089	remote_used = 0;
13090	total_used = 0;
13091
13092	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13093		rq->ret = CTL_HA_STATUS_SUCCESS;
13094		rq->context = io;
13095		callback(rq);
13096		goto bailout;
13097	}
13098
13099	/*
13100	 * Pull/push the data over the wire from/to the other controller.
13101	 * This takes into account the possibility that the local and
13102	 * remote sglists may not be identical in terms of the size of
13103	 * the elements and the number of elements.
13104	 *
13105	 * One fundamental assumption here is that the length allocated for
13106	 * both the local and remote sglists is identical.  Otherwise, we've
13107	 * essentially got a coding error of some sort.
13108	 */
13109	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13110		int isc_ret;
13111		uint32_t cur_len, dma_length;
13112		uint8_t *tmp_ptr;
13113
13114		rq->id = CTL_HA_DATA_CTL;
13115		rq->command = command;
13116		rq->context = io;
13117
13118		/*
13119		 * Both pointers should be aligned.  But it is possible
13120		 * that the allocation length is not.  They should both
13121		 * also have enough slack left over at the end, though,
13122		 * to round up to the next 8 byte boundary.
13123		 */
13124		cur_len = ctl_min(local_sglist[i].len - local_used,
13125				  remote_sglist[j].len - remote_used);
13126
13127		/*
13128		 * In this case, we have a size issue and need to decrease
13129		 * the size, except in the case where we actually have less
13130		 * than 8 bytes left.  In that case, we need to increase
13131		 * the DMA length to get the last bit.
13132		 */
13133		if ((cur_len & 0x7) != 0) {
13134			if (cur_len > 0x7) {
13135				cur_len = cur_len - (cur_len & 0x7);
13136				dma_length = cur_len;
13137			} else {
13138				CTL_SIZE_8B(dma_length, cur_len);
13139			}
13140
13141		} else
13142			dma_length = cur_len;
13143
13144		/*
13145		 * If we had to allocate memory for this I/O, instead of using
13146		 * the non-cached mirror memory, we'll need to flush the cache
13147		 * before trying to DMA to the other controller.
13148		 *
13149		 * We could end up doing this multiple times for the same
13150		 * segment if we have a larger local segment than remote
13151		 * segment.  That shouldn't be an issue.
13152		 */
13153		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13154			/*
13155			 * XXX KDM use bus_dmamap_sync() here.
13156			 */
13157		}
13158
13159		rq->size = dma_length;
13160
13161		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13162		tmp_ptr += local_used;
13163
13164		/* Use physical addresses when talking to ISC hardware */
13165		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13166			/* XXX KDM use busdma */
13167#if 0
13168			rq->local = vtophys(tmp_ptr);
13169#endif
13170		} else
13171			rq->local = tmp_ptr;
13172
13173		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13174		tmp_ptr += remote_used;
13175		rq->remote = tmp_ptr;
13176
13177		rq->callback = NULL;
13178
13179		local_used += cur_len;
13180		if (local_used >= local_sglist[i].len) {
13181			i++;
13182			local_used = 0;
13183		}
13184
13185		remote_used += cur_len;
13186		if (remote_used >= remote_sglist[j].len) {
13187			j++;
13188			remote_used = 0;
13189		}
13190		total_used += cur_len;
13191
13192		if (total_used >= io->scsiio.kern_data_len)
13193			rq->callback = callback;
13194
13195		if ((rq->size & 0x7) != 0) {
13196			printf("%s: warning: size %d is not on 8b boundary\n",
13197			       __func__, rq->size);
13198		}
13199		if (((uintptr_t)rq->local & 0x7) != 0) {
13200			printf("%s: warning: local %p not on 8b boundary\n",
13201			       __func__, rq->local);
13202		}
13203		if (((uintptr_t)rq->remote & 0x7) != 0) {
13204			printf("%s: warning: remote %p not on 8b boundary\n",
13205			       __func__, rq->local);
13206		}
13207#if 0
13208		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13209		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13210		       rq->local, rq->remote, rq->size);
13211#endif
13212
13213		isc_ret = ctl_dt_single(rq);
13214		if (isc_ret == CTL_HA_STATUS_WAIT)
13215			continue;
13216
13217		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13218			rq->ret = CTL_HA_STATUS_SUCCESS;
13219		} else {
13220			rq->ret = isc_ret;
13221		}
13222		callback(rq);
13223		goto bailout;
13224	}
13225
13226bailout:
13227	return (retval);
13228
13229}
13230
13231static void
13232ctl_datamove_remote_read(union ctl_io *io)
13233{
13234	int retval;
13235	int i;
13236
13237	/*
13238	 * This will send an error to the other controller in the case of a
13239	 * failure.
13240	 */
13241	retval = ctl_datamove_remote_sgl_setup(io);
13242	if (retval != 0)
13243		return;
13244
13245	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13246					  ctl_datamove_remote_read_cb);
13247	if ((retval != 0)
13248	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13249		/*
13250		 * Make sure we free memory if there was an error..  The
13251		 * ctl_datamove_remote_xfer() function will send the
13252		 * datamove done message, or call the callback with an
13253		 * error if there is a problem.
13254		 */
13255		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13256			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13257	}
13258
13259	return;
13260}
13261
13262/*
13263 * Process a datamove request from the other controller.  This is used for
13264 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13265 * first.  Once that is complete, the data gets DMAed into the remote
13266 * controller's memory.  For reads, we DMA from the remote controller's
13267 * memory into our memory first, and then move it out to the FETD.
13268 */
13269static void
13270ctl_datamove_remote(union ctl_io *io)
13271{
13272	struct ctl_softc *softc;
13273
13274	softc = control_softc;
13275
13276	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13277
13278	/*
13279	 * Note that we look for an aborted I/O here, but don't do some of
13280	 * the other checks that ctl_datamove() normally does.
13281	 * We don't need to run the datamove delay code, since that should
13282	 * have been done if need be on the other controller.
13283	 */
13284	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13285		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13286		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13287		       io->io_hdr.nexus.targ_port,
13288		       io->io_hdr.nexus.targ_target.id,
13289		       io->io_hdr.nexus.targ_lun);
13290		io->io_hdr.port_status = 31338;
13291		ctl_send_datamove_done(io, /*have_lock*/ 0);
13292		return;
13293	}
13294
13295	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13296		ctl_datamove_remote_write(io);
13297	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13298		ctl_datamove_remote_read(io);
13299	} else {
13300		union ctl_ha_msg msg;
13301		struct scsi_sense_data *sense;
13302		uint8_t sks[3];
13303		int retry_count;
13304
13305		memset(&msg, 0, sizeof(msg));
13306
13307		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13308		msg.hdr.status = CTL_SCSI_ERROR;
13309		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13310
13311		retry_count = 4243;
13312
13313		sense = &msg.scsi.sense_data;
13314		sks[0] = SSD_SCS_VALID;
13315		sks[1] = (retry_count >> 8) & 0xff;
13316		sks[2] = retry_count & 0xff;
13317
13318		/* "Internal target failure" */
13319		scsi_set_sense_data(sense,
13320				    /*sense_format*/ SSD_TYPE_NONE,
13321				    /*current_error*/ 1,
13322				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13323				    /*asc*/ 0x44,
13324				    /*ascq*/ 0x00,
13325				    /*type*/ SSD_ELEM_SKS,
13326				    /*size*/ sizeof(sks),
13327				    /*data*/ sks,
13328				    SSD_ELEM_NONE);
13329
13330		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13331		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13332			ctl_failover_io(io, /*have_lock*/ 1);
13333			return;
13334		}
13335
13336		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13337		    CTL_HA_STATUS_SUCCESS) {
13338			/* XXX KDM what to do if this fails? */
13339		}
13340		return;
13341	}
13342
13343}
13344
13345static int
13346ctl_process_done(union ctl_io *io)
13347{
13348	struct ctl_lun *lun;
13349	struct ctl_softc *ctl_softc = control_softc;
13350	void (*fe_done)(union ctl_io *io);
13351	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13352
13353	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13354
13355	fe_done =
13356	    control_softc->ctl_ports[targ_port]->fe_done;
13357
13358#ifdef CTL_TIME_IO
13359	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13360		char str[256];
13361		char path_str[64];
13362		struct sbuf sb;
13363
13364		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13365		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13366
13367		sbuf_cat(&sb, path_str);
13368		switch (io->io_hdr.io_type) {
13369		case CTL_IO_SCSI:
13370			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13371			sbuf_printf(&sb, "\n");
13372			sbuf_cat(&sb, path_str);
13373			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13374				    io->scsiio.tag_num, io->scsiio.tag_type);
13375			break;
13376		case CTL_IO_TASK:
13377			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13378				    "Tag Type: %d\n", io->taskio.task_action,
13379				    io->taskio.tag_num, io->taskio.tag_type);
13380			break;
13381		default:
13382			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13383			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13384			break;
13385		}
13386		sbuf_cat(&sb, path_str);
13387		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13388			    (intmax_t)time_uptime - io->io_hdr.start_time);
13389		sbuf_finish(&sb);
13390		printf("%s", sbuf_data(&sb));
13391	}
13392#endif /* CTL_TIME_IO */
13393
13394	switch (io->io_hdr.io_type) {
13395	case CTL_IO_SCSI:
13396		break;
13397	case CTL_IO_TASK:
13398		if (bootverbose || (ctl_debug & CTL_DEBUG_INFO))
13399			ctl_io_error_print(io, NULL);
13400		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13401			ctl_free_io(io);
13402		else
13403			fe_done(io);
13404		return (CTL_RETVAL_COMPLETE);
13405	default:
13406		panic("ctl_process_done: invalid io type %d\n",
13407		      io->io_hdr.io_type);
13408		break; /* NOTREACHED */
13409	}
13410
13411	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13412	if (lun == NULL) {
13413		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13414				 io->io_hdr.nexus.targ_mapped_lun));
13415		goto bailout;
13416	}
13417
13418	mtx_lock(&lun->lun_lock);
13419
13420	/*
13421	 * Check to see if we have any errors to inject here.  We only
13422	 * inject errors for commands that don't already have errors set.
13423	 */
13424	if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
13425	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13426	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13427		ctl_inject_error(lun, io);
13428
13429	/*
13430	 * XXX KDM how do we treat commands that aren't completed
13431	 * successfully?
13432	 *
13433	 * XXX KDM should we also track I/O latency?
13434	 */
13435	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13436	    io->io_hdr.io_type == CTL_IO_SCSI) {
13437#ifdef CTL_TIME_IO
13438		struct bintime cur_bt;
13439#endif
13440		int type;
13441
13442		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13443		    CTL_FLAG_DATA_IN)
13444			type = CTL_STATS_READ;
13445		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13446		    CTL_FLAG_DATA_OUT)
13447			type = CTL_STATS_WRITE;
13448		else
13449			type = CTL_STATS_NO_IO;
13450
13451		lun->stats.ports[targ_port].bytes[type] +=
13452		    io->scsiio.kern_total_len;
13453		lun->stats.ports[targ_port].operations[type]++;
13454#ifdef CTL_TIME_IO
13455		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13456		   &io->io_hdr.dma_bt);
13457		lun->stats.ports[targ_port].num_dmas[type] +=
13458		    io->io_hdr.num_dmas;
13459		getbintime(&cur_bt);
13460		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13461		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13462#endif
13463	}
13464
13465	/*
13466	 * Remove this from the OOA queue.
13467	 */
13468	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13469
13470	/*
13471	 * Run through the blocked queue on this LUN and see if anything
13472	 * has become unblocked, now that this transaction is done.
13473	 */
13474	ctl_check_blocked(lun);
13475
13476	/*
13477	 * If the LUN has been invalidated, free it if there is nothing
13478	 * left on its OOA queue.
13479	 */
13480	if ((lun->flags & CTL_LUN_INVALID)
13481	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13482		mtx_unlock(&lun->lun_lock);
13483		mtx_lock(&ctl_softc->ctl_lock);
13484		ctl_free_lun(lun);
13485		mtx_unlock(&ctl_softc->ctl_lock);
13486	} else
13487		mtx_unlock(&lun->lun_lock);
13488
13489bailout:
13490
13491	/*
13492	 * If this command has been aborted, make sure we set the status
13493	 * properly.  The FETD is responsible for freeing the I/O and doing
13494	 * whatever it needs to do to clean up its state.
13495	 */
13496	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13497		ctl_set_task_aborted(&io->scsiio);
13498
13499	/*
13500	 * If enabled, print command error status.
13501	 * We don't print UAs unless debugging was enabled explicitly.
13502	 */
13503	do {
13504		if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)
13505			break;
13506		if (!bootverbose && (ctl_debug & CTL_DEBUG_INFO) == 0)
13507			break;
13508		if ((ctl_debug & CTL_DEBUG_INFO) == 0 &&
13509		    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR) &&
13510		     (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13511			int error_code, sense_key, asc, ascq;
13512
13513			scsi_extract_sense_len(&io->scsiio.sense_data,
13514			    io->scsiio.sense_len, &error_code, &sense_key,
13515			    &asc, &ascq, /*show_errors*/ 0);
13516			if (sense_key == SSD_KEY_UNIT_ATTENTION)
13517				break;
13518		}
13519
13520		ctl_io_error_print(io, NULL);
13521	} while (0);
13522
13523	/*
13524	 * Tell the FETD or the other shelf controller we're done with this
13525	 * command.  Note that only SCSI commands get to this point.  Task
13526	 * management commands are completed above.
13527	 *
13528	 * We only send status to the other controller if we're in XFER
13529	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13530	 * received the I/O (from CTL's perspective), and so the status is
13531	 * generated there.
13532	 *
13533	 * XXX KDM if we hold the lock here, we could cause a deadlock
13534	 * if the frontend comes back in in this context to queue
13535	 * something.
13536	 */
13537	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13538	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13539		union ctl_ha_msg msg;
13540
13541		memset(&msg, 0, sizeof(msg));
13542		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13543		msg.hdr.original_sc = io->io_hdr.original_sc;
13544		msg.hdr.nexus = io->io_hdr.nexus;
13545		msg.hdr.status = io->io_hdr.status;
13546		msg.scsi.scsi_status = io->scsiio.scsi_status;
13547		msg.scsi.tag_num = io->scsiio.tag_num;
13548		msg.scsi.tag_type = io->scsiio.tag_type;
13549		msg.scsi.sense_len = io->scsiio.sense_len;
13550		msg.scsi.sense_residual = io->scsiio.sense_residual;
13551		msg.scsi.residual = io->scsiio.residual;
13552		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13553		       sizeof(io->scsiio.sense_data));
13554		/*
13555		 * We copy this whether or not this is an I/O-related
13556		 * command.  Otherwise, we'd have to go and check to see
13557		 * whether it's a read/write command, and it really isn't
13558		 * worth it.
13559		 */
13560		memcpy(&msg.scsi.lbalen,
13561		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13562		       sizeof(msg.scsi.lbalen));
13563
13564		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13565				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13566			/* XXX do something here */
13567		}
13568
13569		ctl_free_io(io);
13570	} else
13571		fe_done(io);
13572
13573	return (CTL_RETVAL_COMPLETE);
13574}
13575
13576#ifdef CTL_WITH_CA
13577/*
13578 * Front end should call this if it doesn't do autosense.  When the request
13579 * sense comes back in from the initiator, we'll dequeue this and send it.
13580 */
13581int
13582ctl_queue_sense(union ctl_io *io)
13583{
13584	struct ctl_lun *lun;
13585	struct ctl_softc *ctl_softc;
13586	uint32_t initidx, targ_lun;
13587
13588	ctl_softc = control_softc;
13589
13590	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13591
13592	/*
13593	 * LUN lookup will likely move to the ctl_work_thread() once we
13594	 * have our new queueing infrastructure (that doesn't put things on
13595	 * a per-LUN queue initially).  That is so that we can handle
13596	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13597	 * can't deal with that right now.
13598	 */
13599	mtx_lock(&ctl_softc->ctl_lock);
13600
13601	/*
13602	 * If we don't have a LUN for this, just toss the sense
13603	 * information.
13604	 */
13605	targ_lun = io->io_hdr.nexus.targ_lun;
13606	targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13607	if ((targ_lun < CTL_MAX_LUNS)
13608	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
13609		lun = ctl_softc->ctl_luns[targ_lun];
13610	else
13611		goto bailout;
13612
13613	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13614
13615	mtx_lock(&lun->lun_lock);
13616	/*
13617	 * Already have CA set for this LUN...toss the sense information.
13618	 */
13619	if (ctl_is_set(lun->have_ca, initidx)) {
13620		mtx_unlock(&lun->lun_lock);
13621		goto bailout;
13622	}
13623
13624	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13625	       ctl_min(sizeof(lun->pending_sense[initidx]),
13626	       sizeof(io->scsiio.sense_data)));
13627	ctl_set_mask(lun->have_ca, initidx);
13628	mtx_unlock(&lun->lun_lock);
13629
13630bailout:
13631	mtx_unlock(&ctl_softc->ctl_lock);
13632
13633	ctl_free_io(io);
13634
13635	return (CTL_RETVAL_COMPLETE);
13636}
13637#endif
13638
13639/*
13640 * Primary command inlet from frontend ports.  All SCSI and task I/O
13641 * requests must go through this function.
13642 */
13643int
13644ctl_queue(union ctl_io *io)
13645{
13646	struct ctl_softc *ctl_softc;
13647
13648	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13649
13650	ctl_softc = control_softc;
13651
13652#ifdef CTL_TIME_IO
13653	io->io_hdr.start_time = time_uptime;
13654	getbintime(&io->io_hdr.start_bt);
13655#endif /* CTL_TIME_IO */
13656
13657	/* Map FE-specific LUN ID into global one. */
13658	io->io_hdr.nexus.targ_mapped_lun =
13659	    ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13660
13661	switch (io->io_hdr.io_type) {
13662	case CTL_IO_SCSI:
13663	case CTL_IO_TASK:
13664		if (ctl_debug & CTL_DEBUG_CDB)
13665			ctl_io_print(io);
13666		ctl_enqueue_incoming(io);
13667		break;
13668	default:
13669		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13670		return (EINVAL);
13671	}
13672
13673	return (CTL_RETVAL_COMPLETE);
13674}
13675
13676#ifdef CTL_IO_DELAY
13677static void
13678ctl_done_timer_wakeup(void *arg)
13679{
13680	union ctl_io *io;
13681
13682	io = (union ctl_io *)arg;
13683	ctl_done(io);
13684}
13685#endif /* CTL_IO_DELAY */
13686
13687void
13688ctl_done(union ctl_io *io)
13689{
13690	struct ctl_softc *ctl_softc;
13691
13692	ctl_softc = control_softc;
13693
13694	/*
13695	 * Enable this to catch duplicate completion issues.
13696	 */
13697#if 0
13698	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13699		printf("%s: type %d msg %d cdb %x iptl: "
13700		       "%d:%d:%d:%d tag 0x%04x "
13701		       "flag %#x status %x\n",
13702			__func__,
13703			io->io_hdr.io_type,
13704			io->io_hdr.msg_type,
13705			io->scsiio.cdb[0],
13706			io->io_hdr.nexus.initid.id,
13707			io->io_hdr.nexus.targ_port,
13708			io->io_hdr.nexus.targ_target.id,
13709			io->io_hdr.nexus.targ_lun,
13710			(io->io_hdr.io_type ==
13711			CTL_IO_TASK) ?
13712			io->taskio.tag_num :
13713			io->scsiio.tag_num,
13714		        io->io_hdr.flags,
13715			io->io_hdr.status);
13716	} else
13717		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13718#endif
13719
13720	/*
13721	 * This is an internal copy of an I/O, and should not go through
13722	 * the normal done processing logic.
13723	 */
13724	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13725		return;
13726
13727	/*
13728	 * We need to send a msg to the serializing shelf to finish the IO
13729	 * as well.  We don't send a finish message to the other shelf if
13730	 * this is a task management command.  Task management commands
13731	 * aren't serialized in the OOA queue, but rather just executed on
13732	 * both shelf controllers for commands that originated on that
13733	 * controller.
13734	 */
13735	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13736	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
13737		union ctl_ha_msg msg_io;
13738
13739		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13740		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13741		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13742		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13743		}
13744		/* continue on to finish IO */
13745	}
13746#ifdef CTL_IO_DELAY
13747	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13748		struct ctl_lun *lun;
13749
13750		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13751
13752		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13753	} else {
13754		struct ctl_lun *lun;
13755
13756		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13757
13758		if ((lun != NULL)
13759		 && (lun->delay_info.done_delay > 0)) {
13760			struct callout *callout;
13761
13762			callout = (struct callout *)&io->io_hdr.timer_bytes;
13763			callout_init(callout, /*mpsafe*/ 1);
13764			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13765			callout_reset(callout,
13766				      lun->delay_info.done_delay * hz,
13767				      ctl_done_timer_wakeup, io);
13768			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13769				lun->delay_info.done_delay = 0;
13770			return;
13771		}
13772	}
13773#endif /* CTL_IO_DELAY */
13774
13775	ctl_enqueue_done(io);
13776}
13777
13778int
13779ctl_isc(struct ctl_scsiio *ctsio)
13780{
13781	struct ctl_lun *lun;
13782	int retval;
13783
13784	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13785
13786	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13787
13788	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13789
13790	retval = lun->backend->data_submit((union ctl_io *)ctsio);
13791
13792	return (retval);
13793}
13794
13795
13796static void
13797ctl_work_thread(void *arg)
13798{
13799	struct ctl_thread *thr = (struct ctl_thread *)arg;
13800	struct ctl_softc *softc = thr->ctl_softc;
13801	union ctl_io *io;
13802	int retval;
13803
13804	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13805
13806	for (;;) {
13807		retval = 0;
13808
13809		/*
13810		 * We handle the queues in this order:
13811		 * - ISC
13812		 * - done queue (to free up resources, unblock other commands)
13813		 * - RtR queue
13814		 * - incoming queue
13815		 *
13816		 * If those queues are empty, we break out of the loop and
13817		 * go to sleep.
13818		 */
13819		mtx_lock(&thr->queue_lock);
13820		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13821		if (io != NULL) {
13822			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13823			mtx_unlock(&thr->queue_lock);
13824			ctl_handle_isc(io);
13825			continue;
13826		}
13827		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13828		if (io != NULL) {
13829			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13830			/* clear any blocked commands, call fe_done */
13831			mtx_unlock(&thr->queue_lock);
13832			retval = ctl_process_done(io);
13833			continue;
13834		}
13835		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13836		if (io != NULL) {
13837			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13838			mtx_unlock(&thr->queue_lock);
13839			if (io->io_hdr.io_type == CTL_IO_TASK)
13840				ctl_run_task(io);
13841			else
13842				ctl_scsiio_precheck(softc, &io->scsiio);
13843			continue;
13844		}
13845		if (!ctl_pause_rtr) {
13846			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13847			if (io != NULL) {
13848				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13849				mtx_unlock(&thr->queue_lock);
13850				retval = ctl_scsiio(&io->scsiio);
13851				if (retval != CTL_RETVAL_COMPLETE)
13852					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13853				continue;
13854			}
13855		}
13856
13857		/* Sleep until we have something to do. */
13858		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13859	}
13860}
13861
13862static void
13863ctl_lun_thread(void *arg)
13864{
13865	struct ctl_softc *softc = (struct ctl_softc *)arg;
13866	struct ctl_be_lun *be_lun;
13867	int retval;
13868
13869	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13870
13871	for (;;) {
13872		retval = 0;
13873		mtx_lock(&softc->ctl_lock);
13874		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13875		if (be_lun != NULL) {
13876			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13877			mtx_unlock(&softc->ctl_lock);
13878			ctl_create_lun(be_lun);
13879			continue;
13880		}
13881
13882		/* Sleep until we have something to do. */
13883		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13884		    PDROP | PRIBIO, "-", 0);
13885	}
13886}
13887
13888static void
13889ctl_thresh_thread(void *arg)
13890{
13891	struct ctl_softc *softc = (struct ctl_softc *)arg;
13892	struct ctl_lun *lun;
13893	struct ctl_be_lun *be_lun;
13894	struct scsi_da_rw_recovery_page *rwpage;
13895	struct ctl_logical_block_provisioning_page *page;
13896	const char *attr;
13897	uint64_t thres, val;
13898	int i, e;
13899
13900	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13901
13902	for (;;) {
13903		mtx_lock(&softc->ctl_lock);
13904		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13905			be_lun = lun->be_lun;
13906			if ((lun->flags & CTL_LUN_DISABLED) ||
13907			    (lun->flags & CTL_LUN_OFFLINE) ||
13908			    (be_lun->flags & CTL_LUN_FLAG_UNMAP) == 0 ||
13909			    lun->backend->lun_attr == NULL)
13910				continue;
13911			rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13912			if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13913				continue;
13914			e = 0;
13915			page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13916			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13917				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13918					continue;
13919				thres = scsi_4btoul(page->descr[i].count);
13920				thres <<= CTL_LBP_EXPONENT;
13921				switch (page->descr[i].resource) {
13922				case 0x01:
13923					attr = "blocksavail";
13924					break;
13925				case 0x02:
13926					attr = "blocksused";
13927					break;
13928				case 0xf1:
13929					attr = "poolblocksavail";
13930					break;
13931				case 0xf2:
13932					attr = "poolblocksused";
13933					break;
13934				default:
13935					continue;
13936				}
13937				mtx_unlock(&softc->ctl_lock); // XXX
13938				val = lun->backend->lun_attr(
13939				    lun->be_lun->be_lun, attr);
13940				mtx_lock(&softc->ctl_lock);
13941				if (val == UINT64_MAX)
13942					continue;
13943				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13944				    == SLBPPD_ARMING_INC)
13945					e |= (val >= thres);
13946				else
13947					e |= (val <= thres);
13948			}
13949			mtx_lock(&lun->lun_lock);
13950			if (e) {
13951				if (lun->lasttpt == 0 ||
13952				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13953					lun->lasttpt = time_uptime;
13954					for (i = 0; i < CTL_MAX_INITIATORS; i++)
13955						lun->pending_ua[i] |=
13956						    CTL_UA_THIN_PROV_THRES;
13957				}
13958			} else {
13959				lun->lasttpt = 0;
13960				for (i = 0; i < CTL_MAX_INITIATORS; i++)
13961					lun->pending_ua[i] &= ~CTL_UA_THIN_PROV_THRES;
13962			}
13963			mtx_unlock(&lun->lun_lock);
13964		}
13965		mtx_unlock(&softc->ctl_lock);
13966		pause("-", CTL_LBP_PERIOD * hz);
13967	}
13968}
13969
13970static void
13971ctl_enqueue_incoming(union ctl_io *io)
13972{
13973	struct ctl_softc *softc = control_softc;
13974	struct ctl_thread *thr;
13975	u_int idx;
13976
13977	idx = (io->io_hdr.nexus.targ_port * 127 +
13978	       io->io_hdr.nexus.initid.id) % worker_threads;
13979	thr = &softc->threads[idx];
13980	mtx_lock(&thr->queue_lock);
13981	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13982	mtx_unlock(&thr->queue_lock);
13983	wakeup(thr);
13984}
13985
13986static void
13987ctl_enqueue_rtr(union ctl_io *io)
13988{
13989	struct ctl_softc *softc = control_softc;
13990	struct ctl_thread *thr;
13991
13992	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13993	mtx_lock(&thr->queue_lock);
13994	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13995	mtx_unlock(&thr->queue_lock);
13996	wakeup(thr);
13997}
13998
13999static void
14000ctl_enqueue_done(union ctl_io *io)
14001{
14002	struct ctl_softc *softc = control_softc;
14003	struct ctl_thread *thr;
14004
14005	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14006	mtx_lock(&thr->queue_lock);
14007	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14008	mtx_unlock(&thr->queue_lock);
14009	wakeup(thr);
14010}
14011
14012static void
14013ctl_enqueue_isc(union ctl_io *io)
14014{
14015	struct ctl_softc *softc = control_softc;
14016	struct ctl_thread *thr;
14017
14018	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14019	mtx_lock(&thr->queue_lock);
14020	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14021	mtx_unlock(&thr->queue_lock);
14022	wakeup(thr);
14023}
14024
14025/* Initialization and failover */
14026
14027void
14028ctl_init_isc_msg(void)
14029{
14030	printf("CTL: Still calling this thing\n");
14031}
14032
14033/*
14034 * Init component
14035 * 	Initializes component into configuration defined by bootMode
14036 *	(see hasc-sv.c)
14037 *  	returns hasc_Status:
14038 * 		OK
14039 *		ERROR - fatal error
14040 */
14041static ctl_ha_comp_status
14042ctl_isc_init(struct ctl_ha_component *c)
14043{
14044	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14045
14046	c->status = ret;
14047	return ret;
14048}
14049
14050/* Start component
14051 * 	Starts component in state requested. If component starts successfully,
14052 *	it must set its own state to the requestrd state
14053 *	When requested state is HASC_STATE_HA, the component may refine it
14054 * 	by adding _SLAVE or _MASTER flags.
14055 *	Currently allowed state transitions are:
14056 *	UNKNOWN->HA		- initial startup
14057 *	UNKNOWN->SINGLE - initial startup when no parter detected
14058 *	HA->SINGLE		- failover
14059 * returns ctl_ha_comp_status:
14060 * 		OK	- component successfully started in requested state
14061 *		FAILED  - could not start the requested state, failover may
14062 * 			  be possible
14063 *		ERROR	- fatal error detected, no future startup possible
14064 */
14065static ctl_ha_comp_status
14066ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14067{
14068	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14069
14070	printf("%s: go\n", __func__);
14071
14072	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14073	if (c->state == CTL_HA_STATE_UNKNOWN ) {
14074		control_softc->is_single = 0;
14075		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14076		    != CTL_HA_STATUS_SUCCESS) {
14077			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14078			ret = CTL_HA_COMP_STATUS_ERROR;
14079		}
14080	} else if (CTL_HA_STATE_IS_HA(c->state)
14081		&& CTL_HA_STATE_IS_SINGLE(state)){
14082		// HA->SINGLE transition
14083	        ctl_failover();
14084		control_softc->is_single = 1;
14085	} else {
14086		printf("ctl_isc_start:Invalid state transition %X->%X\n",
14087		       c->state, state);
14088		ret = CTL_HA_COMP_STATUS_ERROR;
14089	}
14090	if (CTL_HA_STATE_IS_SINGLE(state))
14091		control_softc->is_single = 1;
14092
14093	c->state = state;
14094	c->status = ret;
14095	return ret;
14096}
14097
14098/*
14099 * Quiesce component
14100 * The component must clear any error conditions (set status to OK) and
14101 * prepare itself to another Start call
14102 * returns ctl_ha_comp_status:
14103 * 	OK
14104 *	ERROR
14105 */
14106static ctl_ha_comp_status
14107ctl_isc_quiesce(struct ctl_ha_component *c)
14108{
14109	int ret = CTL_HA_COMP_STATUS_OK;
14110
14111	ctl_pause_rtr = 1;
14112	c->status = ret;
14113	return ret;
14114}
14115
14116struct ctl_ha_component ctl_ha_component_ctlisc =
14117{
14118	.name = "CTL ISC",
14119	.state = CTL_HA_STATE_UNKNOWN,
14120	.init = ctl_isc_init,
14121	.start = ctl_isc_start,
14122	.quiesce = ctl_isc_quiesce
14123};
14124
14125/*
14126 *  vim: ts=8
14127 */
14128