ctl.c revision 275883
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: stable/10/sys/cam/ctl/ctl.c 275883 2014-12-18 08:27:00Z 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 int persis_offset;
360static uint8_t ctl_pause_rtr;
361
362SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
363static int worker_threads = -1;
364TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
365SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
366    &worker_threads, 1, "Number of worker threads");
367static int ctl_debug = CTL_DEBUG_NONE;
368TUNABLE_INT("kern.cam.ctl.debug", &ctl_debug);
369SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
370    &ctl_debug, 0, "Enabled debug flags");
371
372/*
373 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
374 * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
375 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
376 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
377 */
378#define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
379
380static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
381				  int param);
382static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
383static int ctl_init(void);
384void ctl_shutdown(void);
385static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
386static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
387static void ctl_ioctl_online(void *arg);
388static void ctl_ioctl_offline(void *arg);
389static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
390static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
391static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
392static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
393static int ctl_ioctl_submit_wait(union ctl_io *io);
394static void ctl_ioctl_datamove(union ctl_io *io);
395static void ctl_ioctl_done(union ctl_io *io);
396static void ctl_ioctl_hard_startstop_callback(void *arg,
397					      struct cfi_metatask *metatask);
398static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
399static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
400			      struct ctl_ooa *ooa_hdr,
401			      struct ctl_ooa_entry *kern_entries);
402static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
403		     struct thread *td);
404static uint32_t ctl_map_lun(int port_num, uint32_t lun);
405static uint32_t ctl_map_lun_back(int port_num, uint32_t lun);
406#ifdef unused
407static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
408				   uint32_t targ_target, uint32_t targ_lun,
409				   int can_wait);
410static void ctl_kfree_io(union ctl_io *io);
411#endif /* unused */
412static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
413			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
414static int ctl_free_lun(struct ctl_lun *lun);
415static void ctl_create_lun(struct ctl_be_lun *be_lun);
416/**
417static void ctl_failover_change_pages(struct ctl_softc *softc,
418				      struct ctl_scsiio *ctsio, int master);
419**/
420
421static int ctl_do_mode_select(union ctl_io *io);
422static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
423			   uint64_t res_key, uint64_t sa_res_key,
424			   uint8_t type, uint32_t residx,
425			   struct ctl_scsiio *ctsio,
426			   struct scsi_per_res_out *cdb,
427			   struct scsi_per_res_out_parms* param);
428static void ctl_pro_preempt_other(struct ctl_lun *lun,
429				  union ctl_ha_msg *msg);
430static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
431static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
432static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
433static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
434static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
435static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
436static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
437					 int alloc_len);
438static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
439					 int alloc_len);
440static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
441static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
442static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
443static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
444static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
445static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
446static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
447    union ctl_io *pending_io, union ctl_io *ooa_io);
448static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
449				union ctl_io *starting_io);
450static int ctl_check_blocked(struct ctl_lun *lun);
451static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
452				struct ctl_lun *lun,
453				const struct ctl_cmd_entry *entry,
454				struct ctl_scsiio *ctsio);
455//static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
456static void ctl_failover(void);
457static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
458			       struct ctl_scsiio *ctsio);
459static int ctl_scsiio(struct ctl_scsiio *ctsio);
460
461static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
462static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
463			    ctl_ua_type ua_type);
464static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
465			 ctl_ua_type ua_type);
466static int ctl_abort_task(union ctl_io *io);
467static int ctl_abort_task_set(union ctl_io *io);
468static int ctl_i_t_nexus_reset(union ctl_io *io);
469static void ctl_run_task(union ctl_io *io);
470#ifdef CTL_IO_DELAY
471static void ctl_datamove_timer_wakeup(void *arg);
472static void ctl_done_timer_wakeup(void *arg);
473#endif /* CTL_IO_DELAY */
474
475static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
476static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
477static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
478static void ctl_datamove_remote_write(union ctl_io *io);
479static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
480static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
481static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
482static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
483				    ctl_ha_dt_cb callback);
484static void ctl_datamove_remote_read(union ctl_io *io);
485static void ctl_datamove_remote(union ctl_io *io);
486static int ctl_process_done(union ctl_io *io);
487static void ctl_lun_thread(void *arg);
488static void ctl_thresh_thread(void *arg);
489static void ctl_work_thread(void *arg);
490static void ctl_enqueue_incoming(union ctl_io *io);
491static void ctl_enqueue_rtr(union ctl_io *io);
492static void ctl_enqueue_done(union ctl_io *io);
493static void ctl_enqueue_isc(union ctl_io *io);
494static const struct ctl_cmd_entry *
495    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
496static const struct ctl_cmd_entry *
497    ctl_validate_command(struct ctl_scsiio *ctsio);
498static int ctl_cmd_applicable(uint8_t lun_type,
499    const struct ctl_cmd_entry *entry);
500
501/*
502 * Load the serialization table.  This isn't very pretty, but is probably
503 * the easiest way to do it.
504 */
505#include "ctl_ser_table.c"
506
507/*
508 * We only need to define open, close and ioctl routines for this driver.
509 */
510static struct cdevsw ctl_cdevsw = {
511	.d_version =	D_VERSION,
512	.d_flags =	0,
513	.d_open =	ctl_open,
514	.d_close =	ctl_close,
515	.d_ioctl =	ctl_ioctl,
516	.d_name =	"ctl",
517};
518
519
520MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
521MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
522
523static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
524
525static moduledata_t ctl_moduledata = {
526	"ctl",
527	ctl_module_event_handler,
528	NULL
529};
530
531DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
532MODULE_VERSION(ctl, 1);
533
534static struct ctl_frontend ioctl_frontend =
535{
536	.name = "ioctl",
537};
538
539static void
540ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
541			    union ctl_ha_msg *msg_info)
542{
543	struct ctl_scsiio *ctsio;
544
545	if (msg_info->hdr.original_sc == NULL) {
546		printf("%s: original_sc == NULL!\n", __func__);
547		/* XXX KDM now what? */
548		return;
549	}
550
551	ctsio = &msg_info->hdr.original_sc->scsiio;
552	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
553	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
554	ctsio->io_hdr.status = msg_info->hdr.status;
555	ctsio->scsi_status = msg_info->scsi.scsi_status;
556	ctsio->sense_len = msg_info->scsi.sense_len;
557	ctsio->sense_residual = msg_info->scsi.sense_residual;
558	ctsio->residual = msg_info->scsi.residual;
559	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
560	       sizeof(ctsio->sense_data));
561	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
562	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
563	ctl_enqueue_isc((union ctl_io *)ctsio);
564}
565
566static void
567ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
568				union ctl_ha_msg *msg_info)
569{
570	struct ctl_scsiio *ctsio;
571
572	if (msg_info->hdr.serializing_sc == NULL) {
573		printf("%s: serializing_sc == NULL!\n", __func__);
574		/* XXX KDM now what? */
575		return;
576	}
577
578	ctsio = &msg_info->hdr.serializing_sc->scsiio;
579#if 0
580	/*
581	 * Attempt to catch the situation where an I/O has
582	 * been freed, and we're using it again.
583	 */
584	if (ctsio->io_hdr.io_type == 0xff) {
585		union ctl_io *tmp_io;
586		tmp_io = (union ctl_io *)ctsio;
587		printf("%s: %p use after free!\n", __func__,
588		       ctsio);
589		printf("%s: type %d msg %d cdb %x iptl: "
590		       "%d:%d:%d:%d tag 0x%04x "
591		       "flag %#x status %x\n",
592			__func__,
593			tmp_io->io_hdr.io_type,
594			tmp_io->io_hdr.msg_type,
595			tmp_io->scsiio.cdb[0],
596			tmp_io->io_hdr.nexus.initid.id,
597			tmp_io->io_hdr.nexus.targ_port,
598			tmp_io->io_hdr.nexus.targ_target.id,
599			tmp_io->io_hdr.nexus.targ_lun,
600			(tmp_io->io_hdr.io_type ==
601			CTL_IO_TASK) ?
602			tmp_io->taskio.tag_num :
603			tmp_io->scsiio.tag_num,
604		        tmp_io->io_hdr.flags,
605			tmp_io->io_hdr.status);
606	}
607#endif
608	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
609	ctl_enqueue_isc((union ctl_io *)ctsio);
610}
611
612/*
613 * ISC (Inter Shelf Communication) event handler.  Events from the HA
614 * subsystem come in here.
615 */
616static void
617ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
618{
619	struct ctl_softc *ctl_softc;
620	union ctl_io *io;
621	struct ctl_prio *presio;
622	ctl_ha_status isc_status;
623
624	ctl_softc = control_softc;
625	io = NULL;
626
627
628#if 0
629	printf("CTL: Isc Msg event %d\n", event);
630#endif
631	if (event == CTL_HA_EVT_MSG_RECV) {
632		union ctl_ha_msg msg_info;
633
634		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
635					     sizeof(msg_info), /*wait*/ 0);
636#if 0
637		printf("CTL: msg_type %d\n", msg_info.msg_type);
638#endif
639		if (isc_status != 0) {
640			printf("Error receiving message, status = %d\n",
641			       isc_status);
642			return;
643		}
644
645		switch (msg_info.hdr.msg_type) {
646		case CTL_MSG_SERIALIZE:
647#if 0
648			printf("Serialize\n");
649#endif
650			io = ctl_alloc_io_nowait(ctl_softc->othersc_pool);
651			if (io == NULL) {
652				printf("ctl_isc_event_handler: can't allocate "
653				       "ctl_io!\n");
654				/* Bad Juju */
655				/* Need to set busy and send msg back */
656				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
657				msg_info.hdr.status = CTL_SCSI_ERROR;
658				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
659				msg_info.scsi.sense_len = 0;
660			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
661				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
662				}
663				goto bailout;
664			}
665			ctl_zero_io(io);
666			// populate ctsio from msg_info
667			io->io_hdr.io_type = CTL_IO_SCSI;
668			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
669			io->io_hdr.original_sc = msg_info.hdr.original_sc;
670#if 0
671			printf("pOrig %x\n", (int)msg_info.original_sc);
672#endif
673			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
674					    CTL_FLAG_IO_ACTIVE;
675			/*
676			 * If we're in serialization-only mode, we don't
677			 * want to go through full done processing.  Thus
678			 * the COPY flag.
679			 *
680			 * XXX KDM add another flag that is more specific.
681			 */
682			if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
683				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
684			io->io_hdr.nexus = msg_info.hdr.nexus;
685#if 0
686			printf("targ %d, port %d, iid %d, lun %d\n",
687			       io->io_hdr.nexus.targ_target.id,
688			       io->io_hdr.nexus.targ_port,
689			       io->io_hdr.nexus.initid.id,
690			       io->io_hdr.nexus.targ_lun);
691#endif
692			io->scsiio.tag_num = msg_info.scsi.tag_num;
693			io->scsiio.tag_type = msg_info.scsi.tag_type;
694			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
695			       CTL_MAX_CDBLEN);
696			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
697				const struct ctl_cmd_entry *entry;
698
699				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
700				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
701				io->io_hdr.flags |=
702					entry->flags & CTL_FLAG_DATA_MASK;
703			}
704			ctl_enqueue_isc(io);
705			break;
706
707		/* Performed on the Originating SC, XFER mode only */
708		case CTL_MSG_DATAMOVE: {
709			struct ctl_sg_entry *sgl;
710			int i, j;
711
712			io = msg_info.hdr.original_sc;
713			if (io == NULL) {
714				printf("%s: original_sc == NULL!\n", __func__);
715				/* XXX KDM do something here */
716				break;
717			}
718			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
719			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
720			/*
721			 * Keep track of this, we need to send it back over
722			 * when the datamove is complete.
723			 */
724			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
725
726			if (msg_info.dt.sg_sequence == 0) {
727				/*
728				 * XXX KDM we use the preallocated S/G list
729				 * here, but we'll need to change this to
730				 * dynamic allocation if we need larger S/G
731				 * lists.
732				 */
733				if (msg_info.dt.kern_sg_entries >
734				    sizeof(io->io_hdr.remote_sglist) /
735				    sizeof(io->io_hdr.remote_sglist[0])) {
736					printf("%s: number of S/G entries "
737					    "needed %u > allocated num %zd\n",
738					    __func__,
739					    msg_info.dt.kern_sg_entries,
740					    sizeof(io->io_hdr.remote_sglist)/
741					    sizeof(io->io_hdr.remote_sglist[0]));
742
743					/*
744					 * XXX KDM send a message back to
745					 * the other side to shut down the
746					 * DMA.  The error will come back
747					 * through via the normal channel.
748					 */
749					break;
750				}
751				sgl = io->io_hdr.remote_sglist;
752				memset(sgl, 0,
753				       sizeof(io->io_hdr.remote_sglist));
754
755				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
756
757				io->scsiio.kern_sg_entries =
758					msg_info.dt.kern_sg_entries;
759				io->scsiio.rem_sg_entries =
760					msg_info.dt.kern_sg_entries;
761				io->scsiio.kern_data_len =
762					msg_info.dt.kern_data_len;
763				io->scsiio.kern_total_len =
764					msg_info.dt.kern_total_len;
765				io->scsiio.kern_data_resid =
766					msg_info.dt.kern_data_resid;
767				io->scsiio.kern_rel_offset =
768					msg_info.dt.kern_rel_offset;
769				/*
770				 * Clear out per-DMA flags.
771				 */
772				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
773				/*
774				 * Add per-DMA flags that are set for this
775				 * particular DMA request.
776				 */
777				io->io_hdr.flags |= msg_info.dt.flags &
778						    CTL_FLAG_RDMA_MASK;
779			} else
780				sgl = (struct ctl_sg_entry *)
781					io->scsiio.kern_data_ptr;
782
783			for (i = msg_info.dt.sent_sg_entries, j = 0;
784			     i < (msg_info.dt.sent_sg_entries +
785			     msg_info.dt.cur_sg_entries); i++, j++) {
786				sgl[i].addr = msg_info.dt.sg_list[j].addr;
787				sgl[i].len = msg_info.dt.sg_list[j].len;
788
789#if 0
790				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
791				       __func__,
792				       msg_info.dt.sg_list[j].addr,
793				       msg_info.dt.sg_list[j].len,
794				       sgl[i].addr, sgl[i].len, j, i);
795#endif
796			}
797#if 0
798			memcpy(&sgl[msg_info.dt.sent_sg_entries],
799			       msg_info.dt.sg_list,
800			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
801#endif
802
803			/*
804			 * If this is the last piece of the I/O, we've got
805			 * the full S/G list.  Queue processing in the thread.
806			 * Otherwise wait for the next piece.
807			 */
808			if (msg_info.dt.sg_last != 0)
809				ctl_enqueue_isc(io);
810			break;
811		}
812		/* Performed on the Serializing (primary) SC, XFER mode only */
813		case CTL_MSG_DATAMOVE_DONE: {
814			if (msg_info.hdr.serializing_sc == NULL) {
815				printf("%s: serializing_sc == NULL!\n",
816				       __func__);
817				/* XXX KDM now what? */
818				break;
819			}
820			/*
821			 * We grab the sense information here in case
822			 * there was a failure, so we can return status
823			 * back to the initiator.
824			 */
825			io = msg_info.hdr.serializing_sc;
826			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
827			io->io_hdr.status = msg_info.hdr.status;
828			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
829			io->scsiio.sense_len = msg_info.scsi.sense_len;
830			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
831			io->io_hdr.port_status = msg_info.scsi.fetd_status;
832			io->scsiio.residual = msg_info.scsi.residual;
833			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
834			       sizeof(io->scsiio.sense_data));
835			ctl_enqueue_isc(io);
836			break;
837		}
838
839		/* Preformed on Originating SC, SER_ONLY mode */
840		case CTL_MSG_R2R:
841			io = msg_info.hdr.original_sc;
842			if (io == NULL) {
843				printf("%s: Major Bummer\n", __func__);
844				return;
845			} else {
846#if 0
847				printf("pOrig %x\n",(int) ctsio);
848#endif
849			}
850			io->io_hdr.msg_type = CTL_MSG_R2R;
851			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
852			ctl_enqueue_isc(io);
853			break;
854
855		/*
856		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
857		 * mode.
858		 * Performed on the Originating (i.e. secondary) SC in XFER
859		 * mode
860		 */
861		case CTL_MSG_FINISH_IO:
862			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
863				ctl_isc_handler_finish_xfer(ctl_softc,
864							    &msg_info);
865			else
866				ctl_isc_handler_finish_ser_only(ctl_softc,
867								&msg_info);
868			break;
869
870		/* Preformed on Originating SC */
871		case CTL_MSG_BAD_JUJU:
872			io = msg_info.hdr.original_sc;
873			if (io == NULL) {
874				printf("%s: Bad JUJU!, original_sc is NULL!\n",
875				       __func__);
876				break;
877			}
878			ctl_copy_sense_data(&msg_info, io);
879			/*
880			 * IO should have already been cleaned up on other
881			 * SC so clear this flag so we won't send a message
882			 * back to finish the IO there.
883			 */
884			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
885			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
886
887			/* io = msg_info.hdr.serializing_sc; */
888			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
889			ctl_enqueue_isc(io);
890			break;
891
892		/* Handle resets sent from the other side */
893		case CTL_MSG_MANAGE_TASKS: {
894			struct ctl_taskio *taskio;
895			taskio = (struct ctl_taskio *)ctl_alloc_io_nowait(
896			    ctl_softc->othersc_pool);
897			if (taskio == NULL) {
898				printf("ctl_isc_event_handler: can't allocate "
899				       "ctl_io!\n");
900				/* Bad Juju */
901				/* should I just call the proper reset func
902				   here??? */
903				goto bailout;
904			}
905			ctl_zero_io((union ctl_io *)taskio);
906			taskio->io_hdr.io_type = CTL_IO_TASK;
907			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
908			taskio->io_hdr.nexus = msg_info.hdr.nexus;
909			taskio->task_action = msg_info.task.task_action;
910			taskio->tag_num = msg_info.task.tag_num;
911			taskio->tag_type = msg_info.task.tag_type;
912#ifdef CTL_TIME_IO
913			taskio->io_hdr.start_time = time_uptime;
914			getbintime(&taskio->io_hdr.start_bt);
915#if 0
916			cs_prof_gettime(&taskio->io_hdr.start_ticks);
917#endif
918#endif /* CTL_TIME_IO */
919			ctl_run_task((union ctl_io *)taskio);
920			break;
921		}
922		/* Persistent Reserve action which needs attention */
923		case CTL_MSG_PERS_ACTION:
924			presio = (struct ctl_prio *)ctl_alloc_io_nowait(
925			    ctl_softc->othersc_pool);
926			if (presio == NULL) {
927				printf("ctl_isc_event_handler: can't allocate "
928				       "ctl_io!\n");
929				/* Bad Juju */
930				/* Need to set busy and send msg back */
931				goto bailout;
932			}
933			ctl_zero_io((union ctl_io *)presio);
934			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
935			presio->pr_msg = msg_info.pr;
936			ctl_enqueue_isc((union ctl_io *)presio);
937			break;
938		case CTL_MSG_SYNC_FE:
939			rcv_sync_msg = 1;
940			break;
941		default:
942		        printf("How did I get here?\n");
943		}
944	} else if (event == CTL_HA_EVT_MSG_SENT) {
945		if (param != CTL_HA_STATUS_SUCCESS) {
946			printf("Bad status from ctl_ha_msg_send status %d\n",
947			       param);
948		}
949		return;
950	} else if (event == CTL_HA_EVT_DISCONNECT) {
951		printf("CTL: Got a disconnect from Isc\n");
952		return;
953	} else {
954		printf("ctl_isc_event_handler: Unknown event %d\n", event);
955		return;
956	}
957
958bailout:
959	return;
960}
961
962static void
963ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
964{
965	struct scsi_sense_data *sense;
966
967	sense = &dest->scsiio.sense_data;
968	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
969	dest->scsiio.scsi_status = src->scsi.scsi_status;
970	dest->scsiio.sense_len = src->scsi.sense_len;
971	dest->io_hdr.status = src->hdr.status;
972}
973
974static int
975ctl_ha_state_sysctl(SYSCTL_HANDLER_ARGS)
976{
977	struct ctl_softc *softc = (struct ctl_softc *)arg1;
978	struct ctl_lun *lun;
979	int error, value, i;
980
981	if (softc->flags & CTL_FLAG_ACTIVE_SHELF)
982		value = 0;
983	else
984		value = 1;
985
986	error = sysctl_handle_int(oidp, &value, 0, req);
987	if ((error != 0) || (req->newptr == NULL))
988		return (error);
989
990	mtx_lock(&softc->ctl_lock);
991	if (value == 0)
992		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
993	else
994		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
995	STAILQ_FOREACH(lun, &softc->lun_list, links) {
996		mtx_lock(&lun->lun_lock);
997		for (i = 0; i < CTL_MAX_INITIATORS; i++)
998			lun->pending_ua[i] |= CTL_UA_ASYM_ACC_CHANGE;
999		mtx_unlock(&lun->lun_lock);
1000	}
1001	mtx_unlock(&softc->ctl_lock);
1002	return (0);
1003}
1004
1005static int
1006ctl_init(void)
1007{
1008	struct ctl_softc *softc;
1009	void *other_pool;
1010	struct ctl_port *port;
1011	int i, error, retval;
1012	//int isc_retval;
1013
1014	retval = 0;
1015	ctl_pause_rtr = 0;
1016        rcv_sync_msg = 0;
1017
1018	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1019			       M_WAITOK | M_ZERO);
1020	softc = control_softc;
1021
1022	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1023			      "cam/ctl");
1024
1025	softc->dev->si_drv1 = softc;
1026
1027	/*
1028	 * By default, return a "bad LUN" peripheral qualifier for unknown
1029	 * LUNs.  The user can override this default using the tunable or
1030	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
1031	 */
1032	softc->inquiry_pq_no_lun = 1;
1033	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
1034			  &softc->inquiry_pq_no_lun);
1035	sysctl_ctx_init(&softc->sysctl_ctx);
1036	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1037		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1038		CTLFLAG_RD, 0, "CAM Target Layer");
1039
1040	if (softc->sysctl_tree == NULL) {
1041		printf("%s: unable to allocate sysctl tree\n", __func__);
1042		destroy_dev(softc->dev);
1043		free(control_softc, M_DEVBUF);
1044		control_softc = NULL;
1045		return (ENOMEM);
1046	}
1047
1048	SYSCTL_ADD_INT(&softc->sysctl_ctx,
1049		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
1050		       "inquiry_pq_no_lun", CTLFLAG_RW,
1051		       &softc->inquiry_pq_no_lun, 0,
1052		       "Report no lun possible for invalid LUNs");
1053
1054	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1055	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1056	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1057	softc->open_count = 0;
1058
1059	/*
1060	 * Default to actually sending a SYNCHRONIZE CACHE command down to
1061	 * the drive.
1062	 */
1063	softc->flags = CTL_FLAG_REAL_SYNC;
1064
1065	/*
1066	 * In Copan's HA scheme, the "master" and "slave" roles are
1067	 * figured out through the slot the controller is in.  Although it
1068	 * is an active/active system, someone has to be in charge.
1069	 */
1070	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1071	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1072	    "HA head ID (0 - no HA)");
1073	if (softc->ha_id == 0) {
1074		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1075		softc->is_single = 1;
1076		softc->port_offset = 0;
1077	} else
1078		softc->port_offset = (softc->ha_id - 1) * CTL_MAX_PORTS;
1079	persis_offset = softc->port_offset * CTL_MAX_INIT_PER_PORT;
1080
1081	/*
1082	 * XXX KDM need to figure out where we want to get our target ID
1083	 * and WWID.  Is it different on each port?
1084	 */
1085	softc->target.id = 0;
1086	softc->target.wwid[0] = 0x12345678;
1087	softc->target.wwid[1] = 0x87654321;
1088	STAILQ_INIT(&softc->lun_list);
1089	STAILQ_INIT(&softc->pending_lun_queue);
1090	STAILQ_INIT(&softc->fe_list);
1091	STAILQ_INIT(&softc->port_list);
1092	STAILQ_INIT(&softc->be_list);
1093	ctl_tpc_init(softc);
1094
1095	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1096	                    &other_pool) != 0)
1097	{
1098		printf("ctl: can't allocate %d entry other SC pool, "
1099		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1100		return (ENOMEM);
1101	}
1102	softc->othersc_pool = other_pool;
1103
1104	if (worker_threads <= 0)
1105		worker_threads = max(1, mp_ncpus / 4);
1106	if (worker_threads > CTL_MAX_THREADS)
1107		worker_threads = CTL_MAX_THREADS;
1108
1109	for (i = 0; i < worker_threads; i++) {
1110		struct ctl_thread *thr = &softc->threads[i];
1111
1112		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1113		thr->ctl_softc = softc;
1114		STAILQ_INIT(&thr->incoming_queue);
1115		STAILQ_INIT(&thr->rtr_queue);
1116		STAILQ_INIT(&thr->done_queue);
1117		STAILQ_INIT(&thr->isc_queue);
1118
1119		error = kproc_kthread_add(ctl_work_thread, thr,
1120		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1121		if (error != 0) {
1122			printf("error creating CTL work thread!\n");
1123			ctl_pool_free(other_pool);
1124			return (error);
1125		}
1126	}
1127	error = kproc_kthread_add(ctl_lun_thread, softc,
1128	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1129	if (error != 0) {
1130		printf("error creating CTL lun thread!\n");
1131		ctl_pool_free(other_pool);
1132		return (error);
1133	}
1134	error = kproc_kthread_add(ctl_thresh_thread, softc,
1135	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1136	if (error != 0) {
1137		printf("error creating CTL threshold thread!\n");
1138		ctl_pool_free(other_pool);
1139		return (error);
1140	}
1141	if (bootverbose)
1142		printf("ctl: CAM Target Layer loaded\n");
1143
1144	/*
1145	 * Initialize the ioctl front end.
1146	 */
1147	ctl_frontend_register(&ioctl_frontend);
1148	port = &softc->ioctl_info.port;
1149	port->frontend = &ioctl_frontend;
1150	sprintf(softc->ioctl_info.port_name, "ioctl");
1151	port->port_type = CTL_PORT_IOCTL;
1152	port->num_requested_ctl_io = 100;
1153	port->port_name = softc->ioctl_info.port_name;
1154	port->port_online = ctl_ioctl_online;
1155	port->port_offline = ctl_ioctl_offline;
1156	port->onoff_arg = &softc->ioctl_info;
1157	port->lun_enable = ctl_ioctl_lun_enable;
1158	port->lun_disable = ctl_ioctl_lun_disable;
1159	port->targ_lun_arg = &softc->ioctl_info;
1160	port->fe_datamove = ctl_ioctl_datamove;
1161	port->fe_done = ctl_ioctl_done;
1162	port->max_targets = 15;
1163	port->max_target_id = 15;
1164
1165	if (ctl_port_register(&softc->ioctl_info.port) != 0) {
1166		printf("ctl: ioctl front end registration failed, will "
1167		       "continue anyway\n");
1168	}
1169
1170	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1171	    OID_AUTO, "ha_state", CTLTYPE_INT | CTLFLAG_RWTUN,
1172	    softc, 0, ctl_ha_state_sysctl, "I", "HA state for this head");
1173
1174#ifdef CTL_IO_DELAY
1175	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1176		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1177		       sizeof(struct callout), CTL_TIMER_BYTES);
1178		return (EINVAL);
1179	}
1180#endif /* CTL_IO_DELAY */
1181
1182	return (0);
1183}
1184
1185void
1186ctl_shutdown(void)
1187{
1188	struct ctl_softc *softc;
1189	struct ctl_lun *lun, *next_lun;
1190
1191	softc = (struct ctl_softc *)control_softc;
1192
1193	if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1194		printf("ctl: ioctl front end deregistration failed\n");
1195
1196	mtx_lock(&softc->ctl_lock);
1197
1198	/*
1199	 * Free up each LUN.
1200	 */
1201	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1202		next_lun = STAILQ_NEXT(lun, links);
1203		ctl_free_lun(lun);
1204	}
1205
1206	mtx_unlock(&softc->ctl_lock);
1207
1208	ctl_frontend_deregister(&ioctl_frontend);
1209
1210#if 0
1211	ctl_shutdown_thread(softc->work_thread);
1212	mtx_destroy(&softc->queue_lock);
1213#endif
1214
1215	ctl_tpc_shutdown(softc);
1216	uma_zdestroy(softc->io_zone);
1217	mtx_destroy(&softc->ctl_lock);
1218
1219	destroy_dev(softc->dev);
1220
1221	sysctl_ctx_free(&softc->sysctl_ctx);
1222
1223	free(control_softc, M_DEVBUF);
1224	control_softc = NULL;
1225
1226	if (bootverbose)
1227		printf("ctl: CAM Target Layer unloaded\n");
1228}
1229
1230static int
1231ctl_module_event_handler(module_t mod, int what, void *arg)
1232{
1233
1234	switch (what) {
1235	case MOD_LOAD:
1236		return (ctl_init());
1237	case MOD_UNLOAD:
1238		return (EBUSY);
1239	default:
1240		return (EOPNOTSUPP);
1241	}
1242}
1243
1244/*
1245 * XXX KDM should we do some access checks here?  Bump a reference count to
1246 * prevent a CTL module from being unloaded while someone has it open?
1247 */
1248static int
1249ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1250{
1251	return (0);
1252}
1253
1254static int
1255ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1256{
1257	return (0);
1258}
1259
1260int
1261ctl_port_enable(ctl_port_type port_type)
1262{
1263	struct ctl_softc *softc = control_softc;
1264	struct ctl_port *port;
1265
1266	if (softc->is_single == 0) {
1267		union ctl_ha_msg msg_info;
1268		int isc_retval;
1269
1270#if 0
1271		printf("%s: HA mode, synchronizing frontend enable\n",
1272		        __func__);
1273#endif
1274		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1275	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1276		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1277			printf("Sync msg send error retval %d\n", isc_retval);
1278		}
1279		if (!rcv_sync_msg) {
1280			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1281			        sizeof(msg_info), 1);
1282		}
1283#if 0
1284        	printf("CTL:Frontend Enable\n");
1285	} else {
1286		printf("%s: single mode, skipping frontend synchronization\n",
1287		        __func__);
1288#endif
1289	}
1290
1291	STAILQ_FOREACH(port, &softc->port_list, links) {
1292		if (port_type & port->port_type)
1293		{
1294#if 0
1295			printf("port %d\n", port->targ_port);
1296#endif
1297			ctl_port_online(port);
1298		}
1299	}
1300
1301	return (0);
1302}
1303
1304int
1305ctl_port_disable(ctl_port_type port_type)
1306{
1307	struct ctl_softc *softc;
1308	struct ctl_port *port;
1309
1310	softc = control_softc;
1311
1312	STAILQ_FOREACH(port, &softc->port_list, links) {
1313		if (port_type & port->port_type)
1314			ctl_port_offline(port);
1315	}
1316
1317	return (0);
1318}
1319
1320/*
1321 * Returns 0 for success, 1 for failure.
1322 * Currently the only failure mode is if there aren't enough entries
1323 * allocated.  So, in case of a failure, look at num_entries_dropped,
1324 * reallocate and try again.
1325 */
1326int
1327ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1328	      int *num_entries_filled, int *num_entries_dropped,
1329	      ctl_port_type port_type, int no_virtual)
1330{
1331	struct ctl_softc *softc;
1332	struct ctl_port *port;
1333	int entries_dropped, entries_filled;
1334	int retval;
1335	int i;
1336
1337	softc = control_softc;
1338
1339	retval = 0;
1340	entries_filled = 0;
1341	entries_dropped = 0;
1342
1343	i = 0;
1344	mtx_lock(&softc->ctl_lock);
1345	STAILQ_FOREACH(port, &softc->port_list, links) {
1346		struct ctl_port_entry *entry;
1347
1348		if ((port->port_type & port_type) == 0)
1349			continue;
1350
1351		if ((no_virtual != 0)
1352		 && (port->virtual_port != 0))
1353			continue;
1354
1355		if (entries_filled >= num_entries_alloced) {
1356			entries_dropped++;
1357			continue;
1358		}
1359		entry = &entries[i];
1360
1361		entry->port_type = port->port_type;
1362		strlcpy(entry->port_name, port->port_name,
1363			sizeof(entry->port_name));
1364		entry->physical_port = port->physical_port;
1365		entry->virtual_port = port->virtual_port;
1366		entry->wwnn = port->wwnn;
1367		entry->wwpn = port->wwpn;
1368
1369		i++;
1370		entries_filled++;
1371	}
1372
1373	mtx_unlock(&softc->ctl_lock);
1374
1375	if (entries_dropped > 0)
1376		retval = 1;
1377
1378	*num_entries_dropped = entries_dropped;
1379	*num_entries_filled = entries_filled;
1380
1381	return (retval);
1382}
1383
1384static void
1385ctl_ioctl_online(void *arg)
1386{
1387	struct ctl_ioctl_info *ioctl_info;
1388
1389	ioctl_info = (struct ctl_ioctl_info *)arg;
1390
1391	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1392}
1393
1394static void
1395ctl_ioctl_offline(void *arg)
1396{
1397	struct ctl_ioctl_info *ioctl_info;
1398
1399	ioctl_info = (struct ctl_ioctl_info *)arg;
1400
1401	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1402}
1403
1404/*
1405 * Remove an initiator by port number and initiator ID.
1406 * Returns 0 for success, -1 for failure.
1407 */
1408int
1409ctl_remove_initiator(struct ctl_port *port, int iid)
1410{
1411	struct ctl_softc *softc = control_softc;
1412
1413	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1414
1415	if (iid > CTL_MAX_INIT_PER_PORT) {
1416		printf("%s: initiator ID %u > maximun %u!\n",
1417		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1418		return (-1);
1419	}
1420
1421	mtx_lock(&softc->ctl_lock);
1422	port->wwpn_iid[iid].in_use--;
1423	port->wwpn_iid[iid].last_use = time_uptime;
1424	mtx_unlock(&softc->ctl_lock);
1425
1426	return (0);
1427}
1428
1429/*
1430 * Add an initiator to the initiator map.
1431 * Returns iid for success, < 0 for failure.
1432 */
1433int
1434ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1435{
1436	struct ctl_softc *softc = control_softc;
1437	time_t best_time;
1438	int i, best;
1439
1440	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1441
1442	if (iid >= CTL_MAX_INIT_PER_PORT) {
1443		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1444		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1445		free(name, M_CTL);
1446		return (-1);
1447	}
1448
1449	mtx_lock(&softc->ctl_lock);
1450
1451	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1452		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1453			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1454				iid = i;
1455				break;
1456			}
1457			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1458			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1459				iid = i;
1460				break;
1461			}
1462		}
1463	}
1464
1465	if (iid < 0) {
1466		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1467			if (port->wwpn_iid[i].in_use == 0 &&
1468			    port->wwpn_iid[i].wwpn == 0 &&
1469			    port->wwpn_iid[i].name == NULL) {
1470				iid = i;
1471				break;
1472			}
1473		}
1474	}
1475
1476	if (iid < 0) {
1477		best = -1;
1478		best_time = INT32_MAX;
1479		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1480			if (port->wwpn_iid[i].in_use == 0) {
1481				if (port->wwpn_iid[i].last_use < best_time) {
1482					best = i;
1483					best_time = port->wwpn_iid[i].last_use;
1484				}
1485			}
1486		}
1487		iid = best;
1488	}
1489
1490	if (iid < 0) {
1491		mtx_unlock(&softc->ctl_lock);
1492		free(name, M_CTL);
1493		return (-2);
1494	}
1495
1496	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1497		/*
1498		 * This is not an error yet.
1499		 */
1500		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1501#if 0
1502			printf("%s: port %d iid %u WWPN %#jx arrived"
1503			    " again\n", __func__, port->targ_port,
1504			    iid, (uintmax_t)wwpn);
1505#endif
1506			goto take;
1507		}
1508		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1509		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1510#if 0
1511			printf("%s: port %d iid %u name '%s' arrived"
1512			    " again\n", __func__, port->targ_port,
1513			    iid, name);
1514#endif
1515			goto take;
1516		}
1517
1518		/*
1519		 * This is an error, but what do we do about it?  The
1520		 * driver is telling us we have a new WWPN for this
1521		 * initiator ID, so we pretty much need to use it.
1522		 */
1523		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1524		    " but WWPN %#jx '%s' is still at that address\n",
1525		    __func__, port->targ_port, iid, wwpn, name,
1526		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1527		    port->wwpn_iid[iid].name);
1528
1529		/*
1530		 * XXX KDM clear have_ca and ua_pending on each LUN for
1531		 * this initiator.
1532		 */
1533	}
1534take:
1535	free(port->wwpn_iid[iid].name, M_CTL);
1536	port->wwpn_iid[iid].name = name;
1537	port->wwpn_iid[iid].wwpn = wwpn;
1538	port->wwpn_iid[iid].in_use++;
1539	mtx_unlock(&softc->ctl_lock);
1540
1541	return (iid);
1542}
1543
1544static int
1545ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1546{
1547	int len;
1548
1549	switch (port->port_type) {
1550	case CTL_PORT_FC:
1551	{
1552		struct scsi_transportid_fcp *id =
1553		    (struct scsi_transportid_fcp *)buf;
1554		if (port->wwpn_iid[iid].wwpn == 0)
1555			return (0);
1556		memset(id, 0, sizeof(*id));
1557		id->format_protocol = SCSI_PROTO_FC;
1558		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1559		return (sizeof(*id));
1560	}
1561	case CTL_PORT_ISCSI:
1562	{
1563		struct scsi_transportid_iscsi_port *id =
1564		    (struct scsi_transportid_iscsi_port *)buf;
1565		if (port->wwpn_iid[iid].name == NULL)
1566			return (0);
1567		memset(id, 0, 256);
1568		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1569		    SCSI_PROTO_ISCSI;
1570		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1571		len = roundup2(min(len, 252), 4);
1572		scsi_ulto2b(len, id->additional_length);
1573		return (sizeof(*id) + len);
1574	}
1575	case CTL_PORT_SAS:
1576	{
1577		struct scsi_transportid_sas *id =
1578		    (struct scsi_transportid_sas *)buf;
1579		if (port->wwpn_iid[iid].wwpn == 0)
1580			return (0);
1581		memset(id, 0, sizeof(*id));
1582		id->format_protocol = SCSI_PROTO_SAS;
1583		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1584		return (sizeof(*id));
1585	}
1586	default:
1587	{
1588		struct scsi_transportid_spi *id =
1589		    (struct scsi_transportid_spi *)buf;
1590		memset(id, 0, sizeof(*id));
1591		id->format_protocol = SCSI_PROTO_SPI;
1592		scsi_ulto2b(iid, id->scsi_addr);
1593		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1594		return (sizeof(*id));
1595	}
1596	}
1597}
1598
1599static int
1600ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1601{
1602	return (0);
1603}
1604
1605static int
1606ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1607{
1608	return (0);
1609}
1610
1611/*
1612 * Data movement routine for the CTL ioctl frontend port.
1613 */
1614static int
1615ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1616{
1617	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1618	struct ctl_sg_entry ext_entry, kern_entry;
1619	int ext_sglen, ext_sg_entries, kern_sg_entries;
1620	int ext_sg_start, ext_offset;
1621	int len_to_copy, len_copied;
1622	int kern_watermark, ext_watermark;
1623	int ext_sglist_malloced;
1624	int i, j;
1625
1626	ext_sglist_malloced = 0;
1627	ext_sg_start = 0;
1628	ext_offset = 0;
1629
1630	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1631
1632	/*
1633	 * If this flag is set, fake the data transfer.
1634	 */
1635	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1636		ctsio->ext_data_filled = ctsio->ext_data_len;
1637		goto bailout;
1638	}
1639
1640	/*
1641	 * To simplify things here, if we have a single buffer, stick it in
1642	 * a S/G entry and just make it a single entry S/G list.
1643	 */
1644	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1645		int len_seen;
1646
1647		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1648
1649		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1650							   M_WAITOK);
1651		ext_sglist_malloced = 1;
1652		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1653				   ext_sglen) != 0) {
1654			ctl_set_internal_failure(ctsio,
1655						 /*sks_valid*/ 0,
1656						 /*retry_count*/ 0);
1657			goto bailout;
1658		}
1659		ext_sg_entries = ctsio->ext_sg_entries;
1660		len_seen = 0;
1661		for (i = 0; i < ext_sg_entries; i++) {
1662			if ((len_seen + ext_sglist[i].len) >=
1663			     ctsio->ext_data_filled) {
1664				ext_sg_start = i;
1665				ext_offset = ctsio->ext_data_filled - len_seen;
1666				break;
1667			}
1668			len_seen += ext_sglist[i].len;
1669		}
1670	} else {
1671		ext_sglist = &ext_entry;
1672		ext_sglist->addr = ctsio->ext_data_ptr;
1673		ext_sglist->len = ctsio->ext_data_len;
1674		ext_sg_entries = 1;
1675		ext_sg_start = 0;
1676		ext_offset = ctsio->ext_data_filled;
1677	}
1678
1679	if (ctsio->kern_sg_entries > 0) {
1680		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1681		kern_sg_entries = ctsio->kern_sg_entries;
1682	} else {
1683		kern_sglist = &kern_entry;
1684		kern_sglist->addr = ctsio->kern_data_ptr;
1685		kern_sglist->len = ctsio->kern_data_len;
1686		kern_sg_entries = 1;
1687	}
1688
1689
1690	kern_watermark = 0;
1691	ext_watermark = ext_offset;
1692	len_copied = 0;
1693	for (i = ext_sg_start, j = 0;
1694	     i < ext_sg_entries && j < kern_sg_entries;) {
1695		uint8_t *ext_ptr, *kern_ptr;
1696
1697		len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1698				      kern_sglist[j].len - kern_watermark);
1699
1700		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1701		ext_ptr = ext_ptr + ext_watermark;
1702		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1703			/*
1704			 * XXX KDM fix this!
1705			 */
1706			panic("need to implement bus address support");
1707#if 0
1708			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1709#endif
1710		} else
1711			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1712		kern_ptr = kern_ptr + kern_watermark;
1713
1714		kern_watermark += len_to_copy;
1715		ext_watermark += len_to_copy;
1716
1717		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1718		     CTL_FLAG_DATA_IN) {
1719			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1720					 "bytes to user\n", len_to_copy));
1721			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1722					 "to %p\n", kern_ptr, ext_ptr));
1723			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1724				ctl_set_internal_failure(ctsio,
1725							 /*sks_valid*/ 0,
1726							 /*retry_count*/ 0);
1727				goto bailout;
1728			}
1729		} else {
1730			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1731					 "bytes from user\n", len_to_copy));
1732			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1733					 "to %p\n", ext_ptr, kern_ptr));
1734			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1735				ctl_set_internal_failure(ctsio,
1736							 /*sks_valid*/ 0,
1737							 /*retry_count*/0);
1738				goto bailout;
1739			}
1740		}
1741
1742		len_copied += len_to_copy;
1743
1744		if (ext_sglist[i].len == ext_watermark) {
1745			i++;
1746			ext_watermark = 0;
1747		}
1748
1749		if (kern_sglist[j].len == kern_watermark) {
1750			j++;
1751			kern_watermark = 0;
1752		}
1753	}
1754
1755	ctsio->ext_data_filled += len_copied;
1756
1757	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1758			 "kern_sg_entries: %d\n", ext_sg_entries,
1759			 kern_sg_entries));
1760	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1761			 "kern_data_len = %d\n", ctsio->ext_data_len,
1762			 ctsio->kern_data_len));
1763
1764
1765	/* XXX KDM set residual?? */
1766bailout:
1767
1768	if (ext_sglist_malloced != 0)
1769		free(ext_sglist, M_CTL);
1770
1771	return (CTL_RETVAL_COMPLETE);
1772}
1773
1774/*
1775 * Serialize a command that went down the "wrong" side, and so was sent to
1776 * this controller for execution.  The logic is a little different than the
1777 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1778 * sent back to the other side, but in the success case, we execute the
1779 * command on this side (XFER mode) or tell the other side to execute it
1780 * (SER_ONLY mode).
1781 */
1782static int
1783ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1784{
1785	struct ctl_softc *ctl_softc;
1786	union ctl_ha_msg msg_info;
1787	struct ctl_lun *lun;
1788	int retval = 0;
1789	uint32_t targ_lun;
1790
1791	ctl_softc = control_softc;
1792
1793	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1794	lun = ctl_softc->ctl_luns[targ_lun];
1795	if (lun==NULL)
1796	{
1797		/*
1798		 * Why isn't LUN defined? The other side wouldn't
1799		 * send a cmd if the LUN is undefined.
1800		 */
1801		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1802
1803		/* "Logical unit not supported" */
1804		ctl_set_sense_data(&msg_info.scsi.sense_data,
1805				   lun,
1806				   /*sense_format*/SSD_TYPE_NONE,
1807				   /*current_error*/ 1,
1808				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1809				   /*asc*/ 0x25,
1810				   /*ascq*/ 0x00,
1811				   SSD_ELEM_NONE);
1812
1813		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1814		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1815		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1816		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1817		msg_info.hdr.serializing_sc = NULL;
1818		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1819	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1820				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1821		}
1822		return(1);
1823
1824	}
1825
1826	mtx_lock(&lun->lun_lock);
1827    	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1828
1829	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1830		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1831		 ooa_links))) {
1832	case CTL_ACTION_BLOCK:
1833		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1834		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1835				  blocked_links);
1836		break;
1837	case CTL_ACTION_PASS:
1838	case CTL_ACTION_SKIP:
1839		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1840			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1841			ctl_enqueue_rtr((union ctl_io *)ctsio);
1842		} else {
1843
1844			/* send msg back to other side */
1845			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1846			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1847			msg_info.hdr.msg_type = CTL_MSG_R2R;
1848#if 0
1849			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1850#endif
1851		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1852			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1853			}
1854		}
1855		break;
1856	case CTL_ACTION_OVERLAP:
1857		/* OVERLAPPED COMMANDS ATTEMPTED */
1858		ctl_set_sense_data(&msg_info.scsi.sense_data,
1859				   lun,
1860				   /*sense_format*/SSD_TYPE_NONE,
1861				   /*current_error*/ 1,
1862				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1863				   /*asc*/ 0x4E,
1864				   /*ascq*/ 0x00,
1865				   SSD_ELEM_NONE);
1866
1867		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1868		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1869		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1870		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1871		msg_info.hdr.serializing_sc = NULL;
1872		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1873#if 0
1874		printf("BAD JUJU:Major Bummer Overlap\n");
1875#endif
1876		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1877		retval = 1;
1878		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1879		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1880		}
1881		break;
1882	case CTL_ACTION_OVERLAP_TAG:
1883		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1884		ctl_set_sense_data(&msg_info.scsi.sense_data,
1885				   lun,
1886				   /*sense_format*/SSD_TYPE_NONE,
1887				   /*current_error*/ 1,
1888				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1889				   /*asc*/ 0x4D,
1890				   /*ascq*/ ctsio->tag_num & 0xff,
1891				   SSD_ELEM_NONE);
1892
1893		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1894		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1895		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1896		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1897		msg_info.hdr.serializing_sc = NULL;
1898		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1899#if 0
1900		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1901#endif
1902		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1903		retval = 1;
1904		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1905		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1906		}
1907		break;
1908	case CTL_ACTION_ERROR:
1909	default:
1910		/* "Internal target failure" */
1911		ctl_set_sense_data(&msg_info.scsi.sense_data,
1912				   lun,
1913				   /*sense_format*/SSD_TYPE_NONE,
1914				   /*current_error*/ 1,
1915				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1916				   /*asc*/ 0x44,
1917				   /*ascq*/ 0x00,
1918				   SSD_ELEM_NONE);
1919
1920		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1921		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1922		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1923		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1924		msg_info.hdr.serializing_sc = NULL;
1925		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1926#if 0
1927		printf("BAD JUJU:Major Bummer HW Error\n");
1928#endif
1929		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1930		retval = 1;
1931		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1932		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1933		}
1934		break;
1935	}
1936	mtx_unlock(&lun->lun_lock);
1937	return (retval);
1938}
1939
1940static int
1941ctl_ioctl_submit_wait(union ctl_io *io)
1942{
1943	struct ctl_fe_ioctl_params params;
1944	ctl_fe_ioctl_state last_state;
1945	int done, retval;
1946
1947	retval = 0;
1948
1949	bzero(&params, sizeof(params));
1950
1951	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1952	cv_init(&params.sem, "ctlioccv");
1953	params.state = CTL_IOCTL_INPROG;
1954	last_state = params.state;
1955
1956	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1957
1958	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1959
1960	/* This shouldn't happen */
1961	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1962		return (retval);
1963
1964	done = 0;
1965
1966	do {
1967		mtx_lock(&params.ioctl_mtx);
1968		/*
1969		 * Check the state here, and don't sleep if the state has
1970		 * already changed (i.e. wakeup has already occured, but we
1971		 * weren't waiting yet).
1972		 */
1973		if (params.state == last_state) {
1974			/* XXX KDM cv_wait_sig instead? */
1975			cv_wait(&params.sem, &params.ioctl_mtx);
1976		}
1977		last_state = params.state;
1978
1979		switch (params.state) {
1980		case CTL_IOCTL_INPROG:
1981			/* Why did we wake up? */
1982			/* XXX KDM error here? */
1983			mtx_unlock(&params.ioctl_mtx);
1984			break;
1985		case CTL_IOCTL_DATAMOVE:
1986			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1987
1988			/*
1989			 * change last_state back to INPROG to avoid
1990			 * deadlock on subsequent data moves.
1991			 */
1992			params.state = last_state = CTL_IOCTL_INPROG;
1993
1994			mtx_unlock(&params.ioctl_mtx);
1995			ctl_ioctl_do_datamove(&io->scsiio);
1996			/*
1997			 * Note that in some cases, most notably writes,
1998			 * this will queue the I/O and call us back later.
1999			 * In other cases, generally reads, this routine
2000			 * will immediately call back and wake us up,
2001			 * probably using our own context.
2002			 */
2003			io->scsiio.be_move_done(io);
2004			break;
2005		case CTL_IOCTL_DONE:
2006			mtx_unlock(&params.ioctl_mtx);
2007			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
2008			done = 1;
2009			break;
2010		default:
2011			mtx_unlock(&params.ioctl_mtx);
2012			/* XXX KDM error here? */
2013			break;
2014		}
2015	} while (done == 0);
2016
2017	mtx_destroy(&params.ioctl_mtx);
2018	cv_destroy(&params.sem);
2019
2020	return (CTL_RETVAL_COMPLETE);
2021}
2022
2023static void
2024ctl_ioctl_datamove(union ctl_io *io)
2025{
2026	struct ctl_fe_ioctl_params *params;
2027
2028	params = (struct ctl_fe_ioctl_params *)
2029		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2030
2031	mtx_lock(&params->ioctl_mtx);
2032	params->state = CTL_IOCTL_DATAMOVE;
2033	cv_broadcast(&params->sem);
2034	mtx_unlock(&params->ioctl_mtx);
2035}
2036
2037static void
2038ctl_ioctl_done(union ctl_io *io)
2039{
2040	struct ctl_fe_ioctl_params *params;
2041
2042	params = (struct ctl_fe_ioctl_params *)
2043		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2044
2045	mtx_lock(&params->ioctl_mtx);
2046	params->state = CTL_IOCTL_DONE;
2047	cv_broadcast(&params->sem);
2048	mtx_unlock(&params->ioctl_mtx);
2049}
2050
2051static void
2052ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2053{
2054	struct ctl_fe_ioctl_startstop_info *sd_info;
2055
2056	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2057
2058	sd_info->hs_info.status = metatask->status;
2059	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2060	sd_info->hs_info.luns_complete =
2061		metatask->taskinfo.startstop.luns_complete;
2062	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2063
2064	cv_broadcast(&sd_info->sem);
2065}
2066
2067static void
2068ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2069{
2070	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2071
2072	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2073
2074	mtx_lock(fe_bbr_info->lock);
2075	fe_bbr_info->bbr_info->status = metatask->status;
2076	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2077	fe_bbr_info->wakeup_done = 1;
2078	mtx_unlock(fe_bbr_info->lock);
2079
2080	cv_broadcast(&fe_bbr_info->sem);
2081}
2082
2083/*
2084 * Returns 0 for success, errno for failure.
2085 */
2086static int
2087ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2088		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2089{
2090	union ctl_io *io;
2091	int retval;
2092
2093	retval = 0;
2094
2095	mtx_lock(&lun->lun_lock);
2096	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2097	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2098	     ooa_links)) {
2099		struct ctl_ooa_entry *entry;
2100
2101		/*
2102		 * If we've got more than we can fit, just count the
2103		 * remaining entries.
2104		 */
2105		if (*cur_fill_num >= ooa_hdr->alloc_num)
2106			continue;
2107
2108		entry = &kern_entries[*cur_fill_num];
2109
2110		entry->tag_num = io->scsiio.tag_num;
2111		entry->lun_num = lun->lun;
2112#ifdef CTL_TIME_IO
2113		entry->start_bt = io->io_hdr.start_bt;
2114#endif
2115		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2116		entry->cdb_len = io->scsiio.cdb_len;
2117		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2118			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2119
2120		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2121			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2122
2123		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2124			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2125
2126		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2127			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2128
2129		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2130			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2131	}
2132	mtx_unlock(&lun->lun_lock);
2133
2134	return (retval);
2135}
2136
2137static void *
2138ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2139		 size_t error_str_len)
2140{
2141	void *kptr;
2142
2143	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2144
2145	if (copyin(user_addr, kptr, len) != 0) {
2146		snprintf(error_str, error_str_len, "Error copying %d bytes "
2147			 "from user address %p to kernel address %p", len,
2148			 user_addr, kptr);
2149		free(kptr, M_CTL);
2150		return (NULL);
2151	}
2152
2153	return (kptr);
2154}
2155
2156static void
2157ctl_free_args(int num_args, struct ctl_be_arg *args)
2158{
2159	int i;
2160
2161	if (args == NULL)
2162		return;
2163
2164	for (i = 0; i < num_args; i++) {
2165		free(args[i].kname, M_CTL);
2166		free(args[i].kvalue, M_CTL);
2167	}
2168
2169	free(args, M_CTL);
2170}
2171
2172static struct ctl_be_arg *
2173ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2174		char *error_str, size_t error_str_len)
2175{
2176	struct ctl_be_arg *args;
2177	int i;
2178
2179	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2180				error_str, error_str_len);
2181
2182	if (args == NULL)
2183		goto bailout;
2184
2185	for (i = 0; i < num_args; i++) {
2186		args[i].kname = NULL;
2187		args[i].kvalue = NULL;
2188	}
2189
2190	for (i = 0; i < num_args; i++) {
2191		uint8_t *tmpptr;
2192
2193		args[i].kname = ctl_copyin_alloc(args[i].name,
2194			args[i].namelen, error_str, error_str_len);
2195		if (args[i].kname == NULL)
2196			goto bailout;
2197
2198		if (args[i].kname[args[i].namelen - 1] != '\0') {
2199			snprintf(error_str, error_str_len, "Argument %d "
2200				 "name is not NUL-terminated", i);
2201			goto bailout;
2202		}
2203
2204		if (args[i].flags & CTL_BEARG_RD) {
2205			tmpptr = ctl_copyin_alloc(args[i].value,
2206				args[i].vallen, error_str, error_str_len);
2207			if (tmpptr == NULL)
2208				goto bailout;
2209			if ((args[i].flags & CTL_BEARG_ASCII)
2210			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2211				snprintf(error_str, error_str_len, "Argument "
2212				    "%d value is not NUL-terminated", i);
2213				goto bailout;
2214			}
2215			args[i].kvalue = tmpptr;
2216		} else {
2217			args[i].kvalue = malloc(args[i].vallen,
2218			    M_CTL, M_WAITOK | M_ZERO);
2219		}
2220	}
2221
2222	return (args);
2223bailout:
2224
2225	ctl_free_args(num_args, args);
2226
2227	return (NULL);
2228}
2229
2230static void
2231ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2232{
2233	int i;
2234
2235	for (i = 0; i < num_args; i++) {
2236		if (args[i].flags & CTL_BEARG_WR)
2237			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2238	}
2239}
2240
2241/*
2242 * Escape characters that are illegal or not recommended in XML.
2243 */
2244int
2245ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2246{
2247	char *end = str + size;
2248	int retval;
2249
2250	retval = 0;
2251
2252	for (; *str && str < end; str++) {
2253		switch (*str) {
2254		case '&':
2255			retval = sbuf_printf(sb, "&amp;");
2256			break;
2257		case '>':
2258			retval = sbuf_printf(sb, "&gt;");
2259			break;
2260		case '<':
2261			retval = sbuf_printf(sb, "&lt;");
2262			break;
2263		default:
2264			retval = sbuf_putc(sb, *str);
2265			break;
2266		}
2267
2268		if (retval != 0)
2269			break;
2270
2271	}
2272
2273	return (retval);
2274}
2275
2276static void
2277ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2278{
2279	struct scsi_vpd_id_descriptor *desc;
2280	int i;
2281
2282	if (id == NULL || id->len < 4)
2283		return;
2284	desc = (struct scsi_vpd_id_descriptor *)id->data;
2285	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2286	case SVPD_ID_TYPE_T10:
2287		sbuf_printf(sb, "t10.");
2288		break;
2289	case SVPD_ID_TYPE_EUI64:
2290		sbuf_printf(sb, "eui.");
2291		break;
2292	case SVPD_ID_TYPE_NAA:
2293		sbuf_printf(sb, "naa.");
2294		break;
2295	case SVPD_ID_TYPE_SCSI_NAME:
2296		break;
2297	}
2298	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2299	case SVPD_ID_CODESET_BINARY:
2300		for (i = 0; i < desc->length; i++)
2301			sbuf_printf(sb, "%02x", desc->identifier[i]);
2302		break;
2303	case SVPD_ID_CODESET_ASCII:
2304		sbuf_printf(sb, "%.*s", (int)desc->length,
2305		    (char *)desc->identifier);
2306		break;
2307	case SVPD_ID_CODESET_UTF8:
2308		sbuf_printf(sb, "%s", (char *)desc->identifier);
2309		break;
2310	}
2311}
2312
2313static int
2314ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2315	  struct thread *td)
2316{
2317	struct ctl_softc *softc;
2318	int retval;
2319
2320	softc = control_softc;
2321
2322	retval = 0;
2323
2324	switch (cmd) {
2325	case CTL_IO: {
2326		union ctl_io *io;
2327		void *pool_tmp;
2328
2329		/*
2330		 * If we haven't been "enabled", don't allow any SCSI I/O
2331		 * to this FETD.
2332		 */
2333		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2334			retval = EPERM;
2335			break;
2336		}
2337
2338		io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2339
2340		/*
2341		 * Need to save the pool reference so it doesn't get
2342		 * spammed by the user's ctl_io.
2343		 */
2344		pool_tmp = io->io_hdr.pool;
2345		memcpy(io, (void *)addr, sizeof(*io));
2346		io->io_hdr.pool = pool_tmp;
2347
2348		/*
2349		 * No status yet, so make sure the status is set properly.
2350		 */
2351		io->io_hdr.status = CTL_STATUS_NONE;
2352
2353		/*
2354		 * The user sets the initiator ID, target and LUN IDs.
2355		 */
2356		io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2357		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2358		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2359		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2360			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2361
2362		retval = ctl_ioctl_submit_wait(io);
2363
2364		if (retval != 0) {
2365			ctl_free_io(io);
2366			break;
2367		}
2368
2369		memcpy((void *)addr, io, sizeof(*io));
2370
2371		/* return this to our pool */
2372		ctl_free_io(io);
2373
2374		break;
2375	}
2376	case CTL_ENABLE_PORT:
2377	case CTL_DISABLE_PORT:
2378	case CTL_SET_PORT_WWNS: {
2379		struct ctl_port *port;
2380		struct ctl_port_entry *entry;
2381
2382		entry = (struct ctl_port_entry *)addr;
2383
2384		mtx_lock(&softc->ctl_lock);
2385		STAILQ_FOREACH(port, &softc->port_list, links) {
2386			int action, done;
2387
2388			action = 0;
2389			done = 0;
2390
2391			if ((entry->port_type == CTL_PORT_NONE)
2392			 && (entry->targ_port == port->targ_port)) {
2393				/*
2394				 * If the user only wants to enable or
2395				 * disable or set WWNs on a specific port,
2396				 * do the operation and we're done.
2397				 */
2398				action = 1;
2399				done = 1;
2400			} else if (entry->port_type & port->port_type) {
2401				/*
2402				 * Compare the user's type mask with the
2403				 * particular frontend type to see if we
2404				 * have a match.
2405				 */
2406				action = 1;
2407				done = 0;
2408
2409				/*
2410				 * Make sure the user isn't trying to set
2411				 * WWNs on multiple ports at the same time.
2412				 */
2413				if (cmd == CTL_SET_PORT_WWNS) {
2414					printf("%s: Can't set WWNs on "
2415					       "multiple ports\n", __func__);
2416					retval = EINVAL;
2417					break;
2418				}
2419			}
2420			if (action != 0) {
2421				/*
2422				 * XXX KDM we have to drop the lock here,
2423				 * because the online/offline operations
2424				 * can potentially block.  We need to
2425				 * reference count the frontends so they
2426				 * can't go away,
2427				 */
2428				mtx_unlock(&softc->ctl_lock);
2429
2430				if (cmd == CTL_ENABLE_PORT) {
2431					struct ctl_lun *lun;
2432
2433					STAILQ_FOREACH(lun, &softc->lun_list,
2434						       links) {
2435						port->lun_enable(port->targ_lun_arg,
2436						    lun->target,
2437						    lun->lun);
2438					}
2439
2440					ctl_port_online(port);
2441				} else if (cmd == CTL_DISABLE_PORT) {
2442					struct ctl_lun *lun;
2443
2444					ctl_port_offline(port);
2445
2446					STAILQ_FOREACH(lun, &softc->lun_list,
2447						       links) {
2448						port->lun_disable(
2449						    port->targ_lun_arg,
2450						    lun->target,
2451						    lun->lun);
2452					}
2453				}
2454
2455				mtx_lock(&softc->ctl_lock);
2456
2457				if (cmd == CTL_SET_PORT_WWNS)
2458					ctl_port_set_wwns(port,
2459					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2460					    1 : 0, entry->wwnn,
2461					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2462					    1 : 0, entry->wwpn);
2463			}
2464			if (done != 0)
2465				break;
2466		}
2467		mtx_unlock(&softc->ctl_lock);
2468		break;
2469	}
2470	case CTL_GET_PORT_LIST: {
2471		struct ctl_port *port;
2472		struct ctl_port_list *list;
2473		int i;
2474
2475		list = (struct ctl_port_list *)addr;
2476
2477		if (list->alloc_len != (list->alloc_num *
2478		    sizeof(struct ctl_port_entry))) {
2479			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2480			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2481			       "%zu\n", __func__, list->alloc_len,
2482			       list->alloc_num, sizeof(struct ctl_port_entry));
2483			retval = EINVAL;
2484			break;
2485		}
2486		list->fill_len = 0;
2487		list->fill_num = 0;
2488		list->dropped_num = 0;
2489		i = 0;
2490		mtx_lock(&softc->ctl_lock);
2491		STAILQ_FOREACH(port, &softc->port_list, links) {
2492			struct ctl_port_entry entry, *list_entry;
2493
2494			if (list->fill_num >= list->alloc_num) {
2495				list->dropped_num++;
2496				continue;
2497			}
2498
2499			entry.port_type = port->port_type;
2500			strlcpy(entry.port_name, port->port_name,
2501				sizeof(entry.port_name));
2502			entry.targ_port = port->targ_port;
2503			entry.physical_port = port->physical_port;
2504			entry.virtual_port = port->virtual_port;
2505			entry.wwnn = port->wwnn;
2506			entry.wwpn = port->wwpn;
2507			if (port->status & CTL_PORT_STATUS_ONLINE)
2508				entry.online = 1;
2509			else
2510				entry.online = 0;
2511
2512			list_entry = &list->entries[i];
2513
2514			retval = copyout(&entry, list_entry, sizeof(entry));
2515			if (retval != 0) {
2516				printf("%s: CTL_GET_PORT_LIST: copyout "
2517				       "returned %d\n", __func__, retval);
2518				break;
2519			}
2520			i++;
2521			list->fill_num++;
2522			list->fill_len += sizeof(entry);
2523		}
2524		mtx_unlock(&softc->ctl_lock);
2525
2526		/*
2527		 * If this is non-zero, we had a copyout fault, so there's
2528		 * probably no point in attempting to set the status inside
2529		 * the structure.
2530		 */
2531		if (retval != 0)
2532			break;
2533
2534		if (list->dropped_num > 0)
2535			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2536		else
2537			list->status = CTL_PORT_LIST_OK;
2538		break;
2539	}
2540	case CTL_DUMP_OOA: {
2541		struct ctl_lun *lun;
2542		union ctl_io *io;
2543		char printbuf[128];
2544		struct sbuf sb;
2545
2546		mtx_lock(&softc->ctl_lock);
2547		printf("Dumping OOA queues:\n");
2548		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2549			mtx_lock(&lun->lun_lock);
2550			for (io = (union ctl_io *)TAILQ_FIRST(
2551			     &lun->ooa_queue); io != NULL;
2552			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2553			     ooa_links)) {
2554				sbuf_new(&sb, printbuf, sizeof(printbuf),
2555					 SBUF_FIXEDLEN);
2556				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2557					    (intmax_t)lun->lun,
2558					    io->scsiio.tag_num,
2559					    (io->io_hdr.flags &
2560					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2561					    (io->io_hdr.flags &
2562					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2563					    (io->io_hdr.flags &
2564					    CTL_FLAG_ABORT) ? " ABORT" : "",
2565			                    (io->io_hdr.flags &
2566		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2567				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2568				sbuf_finish(&sb);
2569				printf("%s\n", sbuf_data(&sb));
2570			}
2571			mtx_unlock(&lun->lun_lock);
2572		}
2573		printf("OOA queues dump done\n");
2574		mtx_unlock(&softc->ctl_lock);
2575		break;
2576	}
2577	case CTL_GET_OOA: {
2578		struct ctl_lun *lun;
2579		struct ctl_ooa *ooa_hdr;
2580		struct ctl_ooa_entry *entries;
2581		uint32_t cur_fill_num;
2582
2583		ooa_hdr = (struct ctl_ooa *)addr;
2584
2585		if ((ooa_hdr->alloc_len == 0)
2586		 || (ooa_hdr->alloc_num == 0)) {
2587			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2588			       "must be non-zero\n", __func__,
2589			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2590			retval = EINVAL;
2591			break;
2592		}
2593
2594		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2595		    sizeof(struct ctl_ooa_entry))) {
2596			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2597			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2598			       __func__, ooa_hdr->alloc_len,
2599			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2600			retval = EINVAL;
2601			break;
2602		}
2603
2604		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2605		if (entries == NULL) {
2606			printf("%s: could not allocate %d bytes for OOA "
2607			       "dump\n", __func__, ooa_hdr->alloc_len);
2608			retval = ENOMEM;
2609			break;
2610		}
2611
2612		mtx_lock(&softc->ctl_lock);
2613		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2614		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2615		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2616			mtx_unlock(&softc->ctl_lock);
2617			free(entries, M_CTL);
2618			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2619			       __func__, (uintmax_t)ooa_hdr->lun_num);
2620			retval = EINVAL;
2621			break;
2622		}
2623
2624		cur_fill_num = 0;
2625
2626		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2627			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2628				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2629					ooa_hdr, entries);
2630				if (retval != 0)
2631					break;
2632			}
2633			if (retval != 0) {
2634				mtx_unlock(&softc->ctl_lock);
2635				free(entries, M_CTL);
2636				break;
2637			}
2638		} else {
2639			lun = softc->ctl_luns[ooa_hdr->lun_num];
2640
2641			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2642						    entries);
2643		}
2644		mtx_unlock(&softc->ctl_lock);
2645
2646		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2647		ooa_hdr->fill_len = ooa_hdr->fill_num *
2648			sizeof(struct ctl_ooa_entry);
2649		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2650		if (retval != 0) {
2651			printf("%s: error copying out %d bytes for OOA dump\n",
2652			       __func__, ooa_hdr->fill_len);
2653		}
2654
2655		getbintime(&ooa_hdr->cur_bt);
2656
2657		if (cur_fill_num > ooa_hdr->alloc_num) {
2658			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2659			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2660		} else {
2661			ooa_hdr->dropped_num = 0;
2662			ooa_hdr->status = CTL_OOA_OK;
2663		}
2664
2665		free(entries, M_CTL);
2666		break;
2667	}
2668	case CTL_CHECK_OOA: {
2669		union ctl_io *io;
2670		struct ctl_lun *lun;
2671		struct ctl_ooa_info *ooa_info;
2672
2673
2674		ooa_info = (struct ctl_ooa_info *)addr;
2675
2676		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2677			ooa_info->status = CTL_OOA_INVALID_LUN;
2678			break;
2679		}
2680		mtx_lock(&softc->ctl_lock);
2681		lun = softc->ctl_luns[ooa_info->lun_id];
2682		if (lun == NULL) {
2683			mtx_unlock(&softc->ctl_lock);
2684			ooa_info->status = CTL_OOA_INVALID_LUN;
2685			break;
2686		}
2687		mtx_lock(&lun->lun_lock);
2688		mtx_unlock(&softc->ctl_lock);
2689		ooa_info->num_entries = 0;
2690		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2691		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2692		     &io->io_hdr, ooa_links)) {
2693			ooa_info->num_entries++;
2694		}
2695		mtx_unlock(&lun->lun_lock);
2696
2697		ooa_info->status = CTL_OOA_SUCCESS;
2698
2699		break;
2700	}
2701	case CTL_HARD_START:
2702	case CTL_HARD_STOP: {
2703		struct ctl_fe_ioctl_startstop_info ss_info;
2704		struct cfi_metatask *metatask;
2705		struct mtx hs_mtx;
2706
2707		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2708
2709		cv_init(&ss_info.sem, "hard start/stop cv" );
2710
2711		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2712		if (metatask == NULL) {
2713			retval = ENOMEM;
2714			mtx_destroy(&hs_mtx);
2715			break;
2716		}
2717
2718		if (cmd == CTL_HARD_START)
2719			metatask->tasktype = CFI_TASK_STARTUP;
2720		else
2721			metatask->tasktype = CFI_TASK_SHUTDOWN;
2722
2723		metatask->callback = ctl_ioctl_hard_startstop_callback;
2724		metatask->callback_arg = &ss_info;
2725
2726		cfi_action(metatask);
2727
2728		/* Wait for the callback */
2729		mtx_lock(&hs_mtx);
2730		cv_wait_sig(&ss_info.sem, &hs_mtx);
2731		mtx_unlock(&hs_mtx);
2732
2733		/*
2734		 * All information has been copied from the metatask by the
2735		 * time cv_broadcast() is called, so we free the metatask here.
2736		 */
2737		cfi_free_metatask(metatask);
2738
2739		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2740
2741		mtx_destroy(&hs_mtx);
2742		break;
2743	}
2744	case CTL_BBRREAD: {
2745		struct ctl_bbrread_info *bbr_info;
2746		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2747		struct mtx bbr_mtx;
2748		struct cfi_metatask *metatask;
2749
2750		bbr_info = (struct ctl_bbrread_info *)addr;
2751
2752		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2753
2754		bzero(&bbr_mtx, sizeof(bbr_mtx));
2755		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2756
2757		fe_bbr_info.bbr_info = bbr_info;
2758		fe_bbr_info.lock = &bbr_mtx;
2759
2760		cv_init(&fe_bbr_info.sem, "BBR read cv");
2761		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2762
2763		if (metatask == NULL) {
2764			mtx_destroy(&bbr_mtx);
2765			cv_destroy(&fe_bbr_info.sem);
2766			retval = ENOMEM;
2767			break;
2768		}
2769		metatask->tasktype = CFI_TASK_BBRREAD;
2770		metatask->callback = ctl_ioctl_bbrread_callback;
2771		metatask->callback_arg = &fe_bbr_info;
2772		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2773		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2774		metatask->taskinfo.bbrread.len = bbr_info->len;
2775
2776		cfi_action(metatask);
2777
2778		mtx_lock(&bbr_mtx);
2779		while (fe_bbr_info.wakeup_done == 0)
2780			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2781		mtx_unlock(&bbr_mtx);
2782
2783		bbr_info->status = metatask->status;
2784		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2785		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2786		memcpy(&bbr_info->sense_data,
2787		       &metatask->taskinfo.bbrread.sense_data,
2788		       ctl_min(sizeof(bbr_info->sense_data),
2789			       sizeof(metatask->taskinfo.bbrread.sense_data)));
2790
2791		cfi_free_metatask(metatask);
2792
2793		mtx_destroy(&bbr_mtx);
2794		cv_destroy(&fe_bbr_info.sem);
2795
2796		break;
2797	}
2798	case CTL_DELAY_IO: {
2799		struct ctl_io_delay_info *delay_info;
2800#ifdef CTL_IO_DELAY
2801		struct ctl_lun *lun;
2802#endif /* CTL_IO_DELAY */
2803
2804		delay_info = (struct ctl_io_delay_info *)addr;
2805
2806#ifdef CTL_IO_DELAY
2807		mtx_lock(&softc->ctl_lock);
2808
2809		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2810		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2811			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2812		} else {
2813			lun = softc->ctl_luns[delay_info->lun_id];
2814			mtx_lock(&lun->lun_lock);
2815
2816			delay_info->status = CTL_DELAY_STATUS_OK;
2817
2818			switch (delay_info->delay_type) {
2819			case CTL_DELAY_TYPE_CONT:
2820				break;
2821			case CTL_DELAY_TYPE_ONESHOT:
2822				break;
2823			default:
2824				delay_info->status =
2825					CTL_DELAY_STATUS_INVALID_TYPE;
2826				break;
2827			}
2828
2829			switch (delay_info->delay_loc) {
2830			case CTL_DELAY_LOC_DATAMOVE:
2831				lun->delay_info.datamove_type =
2832					delay_info->delay_type;
2833				lun->delay_info.datamove_delay =
2834					delay_info->delay_secs;
2835				break;
2836			case CTL_DELAY_LOC_DONE:
2837				lun->delay_info.done_type =
2838					delay_info->delay_type;
2839				lun->delay_info.done_delay =
2840					delay_info->delay_secs;
2841				break;
2842			default:
2843				delay_info->status =
2844					CTL_DELAY_STATUS_INVALID_LOC;
2845				break;
2846			}
2847			mtx_unlock(&lun->lun_lock);
2848		}
2849
2850		mtx_unlock(&softc->ctl_lock);
2851#else
2852		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2853#endif /* CTL_IO_DELAY */
2854		break;
2855	}
2856	case CTL_REALSYNC_SET: {
2857		int *syncstate;
2858
2859		syncstate = (int *)addr;
2860
2861		mtx_lock(&softc->ctl_lock);
2862		switch (*syncstate) {
2863		case 0:
2864			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2865			break;
2866		case 1:
2867			softc->flags |= CTL_FLAG_REAL_SYNC;
2868			break;
2869		default:
2870			retval = EINVAL;
2871			break;
2872		}
2873		mtx_unlock(&softc->ctl_lock);
2874		break;
2875	}
2876	case CTL_REALSYNC_GET: {
2877		int *syncstate;
2878
2879		syncstate = (int*)addr;
2880
2881		mtx_lock(&softc->ctl_lock);
2882		if (softc->flags & CTL_FLAG_REAL_SYNC)
2883			*syncstate = 1;
2884		else
2885			*syncstate = 0;
2886		mtx_unlock(&softc->ctl_lock);
2887
2888		break;
2889	}
2890	case CTL_SETSYNC:
2891	case CTL_GETSYNC: {
2892		struct ctl_sync_info *sync_info;
2893		struct ctl_lun *lun;
2894
2895		sync_info = (struct ctl_sync_info *)addr;
2896
2897		mtx_lock(&softc->ctl_lock);
2898		lun = softc->ctl_luns[sync_info->lun_id];
2899		if (lun == NULL) {
2900			mtx_unlock(&softc->ctl_lock);
2901			sync_info->status = CTL_GS_SYNC_NO_LUN;
2902		}
2903		/*
2904		 * Get or set the sync interval.  We're not bounds checking
2905		 * in the set case, hopefully the user won't do something
2906		 * silly.
2907		 */
2908		mtx_lock(&lun->lun_lock);
2909		mtx_unlock(&softc->ctl_lock);
2910		if (cmd == CTL_GETSYNC)
2911			sync_info->sync_interval = lun->sync_interval;
2912		else
2913			lun->sync_interval = sync_info->sync_interval;
2914		mtx_unlock(&lun->lun_lock);
2915
2916		sync_info->status = CTL_GS_SYNC_OK;
2917
2918		break;
2919	}
2920	case CTL_GETSTATS: {
2921		struct ctl_stats *stats;
2922		struct ctl_lun *lun;
2923		int i;
2924
2925		stats = (struct ctl_stats *)addr;
2926
2927		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2928		     stats->alloc_len) {
2929			stats->status = CTL_SS_NEED_MORE_SPACE;
2930			stats->num_luns = softc->num_luns;
2931			break;
2932		}
2933		/*
2934		 * XXX KDM no locking here.  If the LUN list changes,
2935		 * things can blow up.
2936		 */
2937		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2938		     i++, lun = STAILQ_NEXT(lun, links)) {
2939			retval = copyout(&lun->stats, &stats->lun_stats[i],
2940					 sizeof(lun->stats));
2941			if (retval != 0)
2942				break;
2943		}
2944		stats->num_luns = softc->num_luns;
2945		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2946				 softc->num_luns;
2947		stats->status = CTL_SS_OK;
2948#ifdef CTL_TIME_IO
2949		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2950#else
2951		stats->flags = CTL_STATS_FLAG_NONE;
2952#endif
2953		getnanouptime(&stats->timestamp);
2954		break;
2955	}
2956	case CTL_ERROR_INJECT: {
2957		struct ctl_error_desc *err_desc, *new_err_desc;
2958		struct ctl_lun *lun;
2959
2960		err_desc = (struct ctl_error_desc *)addr;
2961
2962		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2963				      M_WAITOK | M_ZERO);
2964		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2965
2966		mtx_lock(&softc->ctl_lock);
2967		lun = softc->ctl_luns[err_desc->lun_id];
2968		if (lun == NULL) {
2969			mtx_unlock(&softc->ctl_lock);
2970			free(new_err_desc, M_CTL);
2971			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2972			       __func__, (uintmax_t)err_desc->lun_id);
2973			retval = EINVAL;
2974			break;
2975		}
2976		mtx_lock(&lun->lun_lock);
2977		mtx_unlock(&softc->ctl_lock);
2978
2979		/*
2980		 * We could do some checking here to verify the validity
2981		 * of the request, but given the complexity of error
2982		 * injection requests, the checking logic would be fairly
2983		 * complex.
2984		 *
2985		 * For now, if the request is invalid, it just won't get
2986		 * executed and might get deleted.
2987		 */
2988		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2989
2990		/*
2991		 * XXX KDM check to make sure the serial number is unique,
2992		 * in case we somehow manage to wrap.  That shouldn't
2993		 * happen for a very long time, but it's the right thing to
2994		 * do.
2995		 */
2996		new_err_desc->serial = lun->error_serial;
2997		err_desc->serial = lun->error_serial;
2998		lun->error_serial++;
2999
3000		mtx_unlock(&lun->lun_lock);
3001		break;
3002	}
3003	case CTL_ERROR_INJECT_DELETE: {
3004		struct ctl_error_desc *delete_desc, *desc, *desc2;
3005		struct ctl_lun *lun;
3006		int delete_done;
3007
3008		delete_desc = (struct ctl_error_desc *)addr;
3009		delete_done = 0;
3010
3011		mtx_lock(&softc->ctl_lock);
3012		lun = softc->ctl_luns[delete_desc->lun_id];
3013		if (lun == NULL) {
3014			mtx_unlock(&softc->ctl_lock);
3015			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
3016			       __func__, (uintmax_t)delete_desc->lun_id);
3017			retval = EINVAL;
3018			break;
3019		}
3020		mtx_lock(&lun->lun_lock);
3021		mtx_unlock(&softc->ctl_lock);
3022		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
3023			if (desc->serial != delete_desc->serial)
3024				continue;
3025
3026			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
3027				      links);
3028			free(desc, M_CTL);
3029			delete_done = 1;
3030		}
3031		mtx_unlock(&lun->lun_lock);
3032		if (delete_done == 0) {
3033			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
3034			       "error serial %ju on LUN %u\n", __func__,
3035			       delete_desc->serial, delete_desc->lun_id);
3036			retval = EINVAL;
3037			break;
3038		}
3039		break;
3040	}
3041	case CTL_DUMP_STRUCTS: {
3042		int i, j, k, idx;
3043		struct ctl_port *port;
3044		struct ctl_frontend *fe;
3045
3046		mtx_lock(&softc->ctl_lock);
3047		printf("CTL Persistent Reservation information start:\n");
3048		for (i = 0; i < CTL_MAX_LUNS; i++) {
3049			struct ctl_lun *lun;
3050
3051			lun = softc->ctl_luns[i];
3052
3053			if ((lun == NULL)
3054			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
3055				continue;
3056
3057			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
3058				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
3059					idx = j * CTL_MAX_INIT_PER_PORT + k;
3060					if (lun->pr_keys[idx] == 0)
3061						continue;
3062					printf("  LUN %d port %d iid %d key "
3063					       "%#jx\n", i, j, k,
3064					       (uintmax_t)lun->pr_keys[idx]);
3065				}
3066			}
3067		}
3068		printf("CTL Persistent Reservation information end\n");
3069		printf("CTL Ports:\n");
3070		STAILQ_FOREACH(port, &softc->port_list, links) {
3071			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3072			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3073			       port->frontend->name, port->port_type,
3074			       port->physical_port, port->virtual_port,
3075			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3076			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3077				if (port->wwpn_iid[j].in_use == 0 &&
3078				    port->wwpn_iid[j].wwpn == 0 &&
3079				    port->wwpn_iid[j].name == NULL)
3080					continue;
3081
3082				printf("    iid %u use %d WWPN %#jx '%s'\n",
3083				    j, port->wwpn_iid[j].in_use,
3084				    (uintmax_t)port->wwpn_iid[j].wwpn,
3085				    port->wwpn_iid[j].name);
3086			}
3087		}
3088		printf("CTL Port information end\n");
3089		mtx_unlock(&softc->ctl_lock);
3090		/*
3091		 * XXX KDM calling this without a lock.  We'd likely want
3092		 * to drop the lock before calling the frontend's dump
3093		 * routine anyway.
3094		 */
3095		printf("CTL Frontends:\n");
3096		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3097			printf("  Frontend '%s'\n", fe->name);
3098			if (fe->fe_dump != NULL)
3099				fe->fe_dump();
3100		}
3101		printf("CTL Frontend information end\n");
3102		break;
3103	}
3104	case CTL_LUN_REQ: {
3105		struct ctl_lun_req *lun_req;
3106		struct ctl_backend_driver *backend;
3107
3108		lun_req = (struct ctl_lun_req *)addr;
3109
3110		backend = ctl_backend_find(lun_req->backend);
3111		if (backend == NULL) {
3112			lun_req->status = CTL_LUN_ERROR;
3113			snprintf(lun_req->error_str,
3114				 sizeof(lun_req->error_str),
3115				 "Backend \"%s\" not found.",
3116				 lun_req->backend);
3117			break;
3118		}
3119		if (lun_req->num_be_args > 0) {
3120			lun_req->kern_be_args = ctl_copyin_args(
3121				lun_req->num_be_args,
3122				lun_req->be_args,
3123				lun_req->error_str,
3124				sizeof(lun_req->error_str));
3125			if (lun_req->kern_be_args == NULL) {
3126				lun_req->status = CTL_LUN_ERROR;
3127				break;
3128			}
3129		}
3130
3131		retval = backend->ioctl(dev, cmd, addr, flag, td);
3132
3133		if (lun_req->num_be_args > 0) {
3134			ctl_copyout_args(lun_req->num_be_args,
3135				      lun_req->kern_be_args);
3136			ctl_free_args(lun_req->num_be_args,
3137				      lun_req->kern_be_args);
3138		}
3139		break;
3140	}
3141	case CTL_LUN_LIST: {
3142		struct sbuf *sb;
3143		struct ctl_lun *lun;
3144		struct ctl_lun_list *list;
3145		struct ctl_option *opt;
3146
3147		list = (struct ctl_lun_list *)addr;
3148
3149		/*
3150		 * Allocate a fixed length sbuf here, based on the length
3151		 * of the user's buffer.  We could allocate an auto-extending
3152		 * buffer, and then tell the user how much larger our
3153		 * amount of data is than his buffer, but that presents
3154		 * some problems:
3155		 *
3156		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3157		 *     we can't hold a lock while calling them with an
3158		 *     auto-extending buffer.
3159 		 *
3160		 * 2.  There is not currently a LUN reference counting
3161		 *     mechanism, outside of outstanding transactions on
3162		 *     the LUN's OOA queue.  So a LUN could go away on us
3163		 *     while we're getting the LUN number, backend-specific
3164		 *     information, etc.  Thus, given the way things
3165		 *     currently work, we need to hold the CTL lock while
3166		 *     grabbing LUN information.
3167		 *
3168		 * So, from the user's standpoint, the best thing to do is
3169		 * allocate what he thinks is a reasonable buffer length,
3170		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3171		 * double the buffer length and try again.  (And repeat
3172		 * that until he succeeds.)
3173		 */
3174		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3175		if (sb == NULL) {
3176			list->status = CTL_LUN_LIST_ERROR;
3177			snprintf(list->error_str, sizeof(list->error_str),
3178				 "Unable to allocate %d bytes for LUN list",
3179				 list->alloc_len);
3180			break;
3181		}
3182
3183		sbuf_printf(sb, "<ctllunlist>\n");
3184
3185		mtx_lock(&softc->ctl_lock);
3186		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3187			mtx_lock(&lun->lun_lock);
3188			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3189					     (uintmax_t)lun->lun);
3190
3191			/*
3192			 * Bail out as soon as we see that we've overfilled
3193			 * the buffer.
3194			 */
3195			if (retval != 0)
3196				break;
3197
3198			retval = sbuf_printf(sb, "\t<backend_type>%s"
3199					     "</backend_type>\n",
3200					     (lun->backend == NULL) ?  "none" :
3201					     lun->backend->name);
3202
3203			if (retval != 0)
3204				break;
3205
3206			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3207					     lun->be_lun->lun_type);
3208
3209			if (retval != 0)
3210				break;
3211
3212			if (lun->backend == NULL) {
3213				retval = sbuf_printf(sb, "</lun>\n");
3214				if (retval != 0)
3215					break;
3216				continue;
3217			}
3218
3219			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3220					     (lun->be_lun->maxlba > 0) ?
3221					     lun->be_lun->maxlba + 1 : 0);
3222
3223			if (retval != 0)
3224				break;
3225
3226			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3227					     lun->be_lun->blocksize);
3228
3229			if (retval != 0)
3230				break;
3231
3232			retval = sbuf_printf(sb, "\t<serial_number>");
3233
3234			if (retval != 0)
3235				break;
3236
3237			retval = ctl_sbuf_printf_esc(sb,
3238			    lun->be_lun->serial_num,
3239			    sizeof(lun->be_lun->serial_num));
3240
3241			if (retval != 0)
3242				break;
3243
3244			retval = sbuf_printf(sb, "</serial_number>\n");
3245
3246			if (retval != 0)
3247				break;
3248
3249			retval = sbuf_printf(sb, "\t<device_id>");
3250
3251			if (retval != 0)
3252				break;
3253
3254			retval = ctl_sbuf_printf_esc(sb,
3255			    lun->be_lun->device_id,
3256			    sizeof(lun->be_lun->device_id));
3257
3258			if (retval != 0)
3259				break;
3260
3261			retval = sbuf_printf(sb, "</device_id>\n");
3262
3263			if (retval != 0)
3264				break;
3265
3266			if (lun->backend->lun_info != NULL) {
3267				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3268				if (retval != 0)
3269					break;
3270			}
3271			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3272				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3273				    opt->name, opt->value, opt->name);
3274				if (retval != 0)
3275					break;
3276			}
3277
3278			retval = sbuf_printf(sb, "</lun>\n");
3279
3280			if (retval != 0)
3281				break;
3282			mtx_unlock(&lun->lun_lock);
3283		}
3284		if (lun != NULL)
3285			mtx_unlock(&lun->lun_lock);
3286		mtx_unlock(&softc->ctl_lock);
3287
3288		if ((retval != 0)
3289		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3290			retval = 0;
3291			sbuf_delete(sb);
3292			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3293			snprintf(list->error_str, sizeof(list->error_str),
3294				 "Out of space, %d bytes is too small",
3295				 list->alloc_len);
3296			break;
3297		}
3298
3299		sbuf_finish(sb);
3300
3301		retval = copyout(sbuf_data(sb), list->lun_xml,
3302				 sbuf_len(sb) + 1);
3303
3304		list->fill_len = sbuf_len(sb) + 1;
3305		list->status = CTL_LUN_LIST_OK;
3306		sbuf_delete(sb);
3307		break;
3308	}
3309	case CTL_ISCSI: {
3310		struct ctl_iscsi *ci;
3311		struct ctl_frontend *fe;
3312
3313		ci = (struct ctl_iscsi *)addr;
3314
3315		fe = ctl_frontend_find("iscsi");
3316		if (fe == NULL) {
3317			ci->status = CTL_ISCSI_ERROR;
3318			snprintf(ci->error_str, sizeof(ci->error_str),
3319			    "Frontend \"iscsi\" not found.");
3320			break;
3321		}
3322
3323		retval = fe->ioctl(dev, cmd, addr, flag, td);
3324		break;
3325	}
3326	case CTL_PORT_REQ: {
3327		struct ctl_req *req;
3328		struct ctl_frontend *fe;
3329
3330		req = (struct ctl_req *)addr;
3331
3332		fe = ctl_frontend_find(req->driver);
3333		if (fe == NULL) {
3334			req->status = CTL_LUN_ERROR;
3335			snprintf(req->error_str, sizeof(req->error_str),
3336			    "Frontend \"%s\" not found.", req->driver);
3337			break;
3338		}
3339		if (req->num_args > 0) {
3340			req->kern_args = ctl_copyin_args(req->num_args,
3341			    req->args, req->error_str, sizeof(req->error_str));
3342			if (req->kern_args == NULL) {
3343				req->status = CTL_LUN_ERROR;
3344				break;
3345			}
3346		}
3347
3348		retval = fe->ioctl(dev, cmd, addr, flag, td);
3349
3350		if (req->num_args > 0) {
3351			ctl_copyout_args(req->num_args, req->kern_args);
3352			ctl_free_args(req->num_args, req->kern_args);
3353		}
3354		break;
3355	}
3356	case CTL_PORT_LIST: {
3357		struct sbuf *sb;
3358		struct ctl_port *port;
3359		struct ctl_lun_list *list;
3360		struct ctl_option *opt;
3361		int j;
3362
3363		list = (struct ctl_lun_list *)addr;
3364
3365		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3366		if (sb == NULL) {
3367			list->status = CTL_LUN_LIST_ERROR;
3368			snprintf(list->error_str, sizeof(list->error_str),
3369				 "Unable to allocate %d bytes for LUN list",
3370				 list->alloc_len);
3371			break;
3372		}
3373
3374		sbuf_printf(sb, "<ctlportlist>\n");
3375
3376		mtx_lock(&softc->ctl_lock);
3377		STAILQ_FOREACH(port, &softc->port_list, links) {
3378			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3379					     (uintmax_t)port->targ_port);
3380
3381			/*
3382			 * Bail out as soon as we see that we've overfilled
3383			 * the buffer.
3384			 */
3385			if (retval != 0)
3386				break;
3387
3388			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3389			    "</frontend_type>\n", port->frontend->name);
3390			if (retval != 0)
3391				break;
3392
3393			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3394					     port->port_type);
3395			if (retval != 0)
3396				break;
3397
3398			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3399			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3400			if (retval != 0)
3401				break;
3402
3403			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3404			    port->port_name);
3405			if (retval != 0)
3406				break;
3407
3408			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3409			    port->physical_port);
3410			if (retval != 0)
3411				break;
3412
3413			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3414			    port->virtual_port);
3415			if (retval != 0)
3416				break;
3417
3418			if (port->target_devid != NULL) {
3419				sbuf_printf(sb, "\t<target>");
3420				ctl_id_sbuf(port->target_devid, sb);
3421				sbuf_printf(sb, "</target>\n");
3422			}
3423
3424			if (port->port_devid != NULL) {
3425				sbuf_printf(sb, "\t<port>");
3426				ctl_id_sbuf(port->port_devid, sb);
3427				sbuf_printf(sb, "</port>\n");
3428			}
3429
3430			if (port->port_info != NULL) {
3431				retval = port->port_info(port->onoff_arg, sb);
3432				if (retval != 0)
3433					break;
3434			}
3435			STAILQ_FOREACH(opt, &port->options, links) {
3436				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3437				    opt->name, opt->value, opt->name);
3438				if (retval != 0)
3439					break;
3440			}
3441
3442			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3443				if (port->wwpn_iid[j].in_use == 0 ||
3444				    (port->wwpn_iid[j].wwpn == 0 &&
3445				     port->wwpn_iid[j].name == NULL))
3446					continue;
3447
3448				if (port->wwpn_iid[j].name != NULL)
3449					retval = sbuf_printf(sb,
3450					    "\t<initiator>%u %s</initiator>\n",
3451					    j, port->wwpn_iid[j].name);
3452				else
3453					retval = sbuf_printf(sb,
3454					    "\t<initiator>%u naa.%08jx</initiator>\n",
3455					    j, port->wwpn_iid[j].wwpn);
3456				if (retval != 0)
3457					break;
3458			}
3459			if (retval != 0)
3460				break;
3461
3462			retval = sbuf_printf(sb, "</targ_port>\n");
3463			if (retval != 0)
3464				break;
3465		}
3466		mtx_unlock(&softc->ctl_lock);
3467
3468		if ((retval != 0)
3469		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3470			retval = 0;
3471			sbuf_delete(sb);
3472			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3473			snprintf(list->error_str, sizeof(list->error_str),
3474				 "Out of space, %d bytes is too small",
3475				 list->alloc_len);
3476			break;
3477		}
3478
3479		sbuf_finish(sb);
3480
3481		retval = copyout(sbuf_data(sb), list->lun_xml,
3482				 sbuf_len(sb) + 1);
3483
3484		list->fill_len = sbuf_len(sb) + 1;
3485		list->status = CTL_LUN_LIST_OK;
3486		sbuf_delete(sb);
3487		break;
3488	}
3489	default: {
3490		/* XXX KDM should we fix this? */
3491#if 0
3492		struct ctl_backend_driver *backend;
3493		unsigned int type;
3494		int found;
3495
3496		found = 0;
3497
3498		/*
3499		 * We encode the backend type as the ioctl type for backend
3500		 * ioctls.  So parse it out here, and then search for a
3501		 * backend of this type.
3502		 */
3503		type = _IOC_TYPE(cmd);
3504
3505		STAILQ_FOREACH(backend, &softc->be_list, links) {
3506			if (backend->type == type) {
3507				found = 1;
3508				break;
3509			}
3510		}
3511		if (found == 0) {
3512			printf("ctl: unknown ioctl command %#lx or backend "
3513			       "%d\n", cmd, type);
3514			retval = EINVAL;
3515			break;
3516		}
3517		retval = backend->ioctl(dev, cmd, addr, flag, td);
3518#endif
3519		retval = ENOTTY;
3520		break;
3521	}
3522	}
3523	return (retval);
3524}
3525
3526uint32_t
3527ctl_get_initindex(struct ctl_nexus *nexus)
3528{
3529	if (nexus->targ_port < CTL_MAX_PORTS)
3530		return (nexus->initid.id +
3531			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3532	else
3533		return (nexus->initid.id +
3534		       ((nexus->targ_port - CTL_MAX_PORTS) *
3535			CTL_MAX_INIT_PER_PORT));
3536}
3537
3538uint32_t
3539ctl_get_resindex(struct ctl_nexus *nexus)
3540{
3541	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3542}
3543
3544uint32_t
3545ctl_port_idx(int port_num)
3546{
3547	if (port_num < CTL_MAX_PORTS)
3548		return(port_num);
3549	else
3550		return(port_num - CTL_MAX_PORTS);
3551}
3552
3553static uint32_t
3554ctl_map_lun(int port_num, uint32_t lun_id)
3555{
3556	struct ctl_port *port;
3557
3558	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3559	if (port == NULL)
3560		return (UINT32_MAX);
3561	if (port->lun_map == NULL)
3562		return (lun_id);
3563	return (port->lun_map(port->targ_lun_arg, lun_id));
3564}
3565
3566static uint32_t
3567ctl_map_lun_back(int port_num, uint32_t lun_id)
3568{
3569	struct ctl_port *port;
3570	uint32_t i;
3571
3572	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3573	if (port->lun_map == NULL)
3574		return (lun_id);
3575	for (i = 0; i < CTL_MAX_LUNS; i++) {
3576		if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3577			return (i);
3578	}
3579	return (UINT32_MAX);
3580}
3581
3582/*
3583 * Note:  This only works for bitmask sizes that are at least 32 bits, and
3584 * that are a power of 2.
3585 */
3586int
3587ctl_ffz(uint32_t *mask, uint32_t size)
3588{
3589	uint32_t num_chunks, num_pieces;
3590	int i, j;
3591
3592	num_chunks = (size >> 5);
3593	if (num_chunks == 0)
3594		num_chunks++;
3595	num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3596
3597	for (i = 0; i < num_chunks; i++) {
3598		for (j = 0; j < num_pieces; j++) {
3599			if ((mask[i] & (1 << j)) == 0)
3600				return ((i << 5) + j);
3601		}
3602	}
3603
3604	return (-1);
3605}
3606
3607int
3608ctl_set_mask(uint32_t *mask, uint32_t bit)
3609{
3610	uint32_t chunk, piece;
3611
3612	chunk = bit >> 5;
3613	piece = bit % (sizeof(uint32_t) * 8);
3614
3615	if ((mask[chunk] & (1 << piece)) != 0)
3616		return (-1);
3617	else
3618		mask[chunk] |= (1 << piece);
3619
3620	return (0);
3621}
3622
3623int
3624ctl_clear_mask(uint32_t *mask, uint32_t bit)
3625{
3626	uint32_t chunk, piece;
3627
3628	chunk = bit >> 5;
3629	piece = bit % (sizeof(uint32_t) * 8);
3630
3631	if ((mask[chunk] & (1 << piece)) == 0)
3632		return (-1);
3633	else
3634		mask[chunk] &= ~(1 << piece);
3635
3636	return (0);
3637}
3638
3639int
3640ctl_is_set(uint32_t *mask, uint32_t bit)
3641{
3642	uint32_t chunk, piece;
3643
3644	chunk = bit >> 5;
3645	piece = bit % (sizeof(uint32_t) * 8);
3646
3647	if ((mask[chunk] & (1 << piece)) == 0)
3648		return (0);
3649	else
3650		return (1);
3651}
3652
3653#ifdef unused
3654/*
3655 * The bus, target and lun are optional, they can be filled in later.
3656 * can_wait is used to determine whether we can wait on the malloc or not.
3657 */
3658union ctl_io*
3659ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3660	      uint32_t targ_lun, int can_wait)
3661{
3662	union ctl_io *io;
3663
3664	if (can_wait)
3665		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3666	else
3667		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3668
3669	if (io != NULL) {
3670		io->io_hdr.io_type = io_type;
3671		io->io_hdr.targ_port = targ_port;
3672		/*
3673		 * XXX KDM this needs to change/go away.  We need to move
3674		 * to a preallocated pool of ctl_scsiio structures.
3675		 */
3676		io->io_hdr.nexus.targ_target.id = targ_target;
3677		io->io_hdr.nexus.targ_lun = targ_lun;
3678	}
3679
3680	return (io);
3681}
3682
3683void
3684ctl_kfree_io(union ctl_io *io)
3685{
3686	free(io, M_CTL);
3687}
3688#endif /* unused */
3689
3690/*
3691 * ctl_softc, pool_name, total_ctl_io are passed in.
3692 * npool is passed out.
3693 */
3694int
3695ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3696		uint32_t total_ctl_io, void **npool)
3697{
3698#ifdef IO_POOLS
3699	struct ctl_io_pool *pool;
3700
3701	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3702					    M_NOWAIT | M_ZERO);
3703	if (pool == NULL)
3704		return (ENOMEM);
3705
3706	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3707	pool->ctl_softc = ctl_softc;
3708	pool->zone = uma_zsecond_create(pool->name, NULL,
3709	    NULL, NULL, NULL, ctl_softc->io_zone);
3710	/* uma_prealloc(pool->zone, total_ctl_io); */
3711
3712	*npool = pool;
3713#else
3714	*npool = ctl_softc->io_zone;
3715#endif
3716	return (0);
3717}
3718
3719void
3720ctl_pool_free(struct ctl_io_pool *pool)
3721{
3722
3723	if (pool == NULL)
3724		return;
3725
3726#ifdef IO_POOLS
3727	uma_zdestroy(pool->zone);
3728	free(pool, M_CTL);
3729#endif
3730}
3731
3732union ctl_io *
3733ctl_alloc_io(void *pool_ref)
3734{
3735	union ctl_io *io;
3736#ifdef IO_POOLS
3737	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3738
3739	io = uma_zalloc(pool->zone, M_WAITOK);
3740#else
3741	io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3742#endif
3743	if (io != NULL)
3744		io->io_hdr.pool = pool_ref;
3745	return (io);
3746}
3747
3748union ctl_io *
3749ctl_alloc_io_nowait(void *pool_ref)
3750{
3751	union ctl_io *io;
3752#ifdef IO_POOLS
3753	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3754
3755	io = uma_zalloc(pool->zone, M_NOWAIT);
3756#else
3757	io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3758#endif
3759	if (io != NULL)
3760		io->io_hdr.pool = pool_ref;
3761	return (io);
3762}
3763
3764void
3765ctl_free_io(union ctl_io *io)
3766{
3767#ifdef IO_POOLS
3768	struct ctl_io_pool *pool;
3769#endif
3770
3771	if (io == NULL)
3772		return;
3773
3774#ifdef IO_POOLS
3775	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3776	uma_zfree(pool->zone, io);
3777#else
3778	uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3779#endif
3780}
3781
3782void
3783ctl_zero_io(union ctl_io *io)
3784{
3785	void *pool_ref;
3786
3787	if (io == NULL)
3788		return;
3789
3790	/*
3791	 * May need to preserve linked list pointers at some point too.
3792	 */
3793	pool_ref = io->io_hdr.pool;
3794	memset(io, 0, sizeof(*io));
3795	io->io_hdr.pool = pool_ref;
3796}
3797
3798/*
3799 * This routine is currently used for internal copies of ctl_ios that need
3800 * to persist for some reason after we've already returned status to the
3801 * FETD.  (Thus the flag set.)
3802 *
3803 * XXX XXX
3804 * Note that this makes a blind copy of all fields in the ctl_io, except
3805 * for the pool reference.  This includes any memory that has been
3806 * allocated!  That memory will no longer be valid after done has been
3807 * called, so this would be VERY DANGEROUS for command that actually does
3808 * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3809 * start and stop commands, which don't transfer any data, so this is not a
3810 * problem.  If it is used for anything else, the caller would also need to
3811 * allocate data buffer space and this routine would need to be modified to
3812 * copy the data buffer(s) as well.
3813 */
3814void
3815ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3816{
3817	void *pool_ref;
3818
3819	if ((src == NULL)
3820	 || (dest == NULL))
3821		return;
3822
3823	/*
3824	 * May need to preserve linked list pointers at some point too.
3825	 */
3826	pool_ref = dest->io_hdr.pool;
3827
3828	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3829
3830	dest->io_hdr.pool = pool_ref;
3831	/*
3832	 * We need to know that this is an internal copy, and doesn't need
3833	 * to get passed back to the FETD that allocated it.
3834	 */
3835	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3836}
3837
3838static int
3839ctl_expand_number(const char *buf, uint64_t *num)
3840{
3841	char *endptr;
3842	uint64_t number;
3843	unsigned shift;
3844
3845	number = strtoq(buf, &endptr, 0);
3846
3847	switch (tolower((unsigned char)*endptr)) {
3848	case 'e':
3849		shift = 60;
3850		break;
3851	case 'p':
3852		shift = 50;
3853		break;
3854	case 't':
3855		shift = 40;
3856		break;
3857	case 'g':
3858		shift = 30;
3859		break;
3860	case 'm':
3861		shift = 20;
3862		break;
3863	case 'k':
3864		shift = 10;
3865		break;
3866	case 'b':
3867	case '\0': /* No unit. */
3868		*num = number;
3869		return (0);
3870	default:
3871		/* Unrecognized unit. */
3872		return (-1);
3873	}
3874
3875	if ((number << shift) >> shift != number) {
3876		/* Overflow */
3877		return (-1);
3878	}
3879	*num = number << shift;
3880	return (0);
3881}
3882
3883
3884/*
3885 * This routine could be used in the future to load default and/or saved
3886 * mode page parameters for a particuar lun.
3887 */
3888static int
3889ctl_init_page_index(struct ctl_lun *lun)
3890{
3891	int i;
3892	struct ctl_page_index *page_index;
3893	const char *value;
3894	uint64_t ival;
3895
3896	memcpy(&lun->mode_pages.index, page_index_template,
3897	       sizeof(page_index_template));
3898
3899	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3900
3901		page_index = &lun->mode_pages.index[i];
3902		/*
3903		 * If this is a disk-only mode page, there's no point in
3904		 * setting it up.  For some pages, we have to have some
3905		 * basic information about the disk in order to calculate the
3906		 * mode page data.
3907		 */
3908		if ((lun->be_lun->lun_type != T_DIRECT)
3909		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
3910			continue;
3911
3912		switch (page_index->page_code & SMPH_PC_MASK) {
3913		case SMS_RW_ERROR_RECOVERY_PAGE: {
3914			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3915				panic("subpage is incorrect!");
3916			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3917			       &rw_er_page_default,
3918			       sizeof(rw_er_page_default));
3919			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3920			       &rw_er_page_changeable,
3921			       sizeof(rw_er_page_changeable));
3922			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3923			       &rw_er_page_default,
3924			       sizeof(rw_er_page_default));
3925			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3926			       &rw_er_page_default,
3927			       sizeof(rw_er_page_default));
3928			page_index->page_data =
3929				(uint8_t *)lun->mode_pages.rw_er_page;
3930			break;
3931		}
3932		case SMS_FORMAT_DEVICE_PAGE: {
3933			struct scsi_format_page *format_page;
3934
3935			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3936				panic("subpage is incorrect!");
3937
3938			/*
3939			 * Sectors per track are set above.  Bytes per
3940			 * sector need to be set here on a per-LUN basis.
3941			 */
3942			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3943			       &format_page_default,
3944			       sizeof(format_page_default));
3945			memcpy(&lun->mode_pages.format_page[
3946			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
3947			       sizeof(format_page_changeable));
3948			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3949			       &format_page_default,
3950			       sizeof(format_page_default));
3951			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3952			       &format_page_default,
3953			       sizeof(format_page_default));
3954
3955			format_page = &lun->mode_pages.format_page[
3956				CTL_PAGE_CURRENT];
3957			scsi_ulto2b(lun->be_lun->blocksize,
3958				    format_page->bytes_per_sector);
3959
3960			format_page = &lun->mode_pages.format_page[
3961				CTL_PAGE_DEFAULT];
3962			scsi_ulto2b(lun->be_lun->blocksize,
3963				    format_page->bytes_per_sector);
3964
3965			format_page = &lun->mode_pages.format_page[
3966				CTL_PAGE_SAVED];
3967			scsi_ulto2b(lun->be_lun->blocksize,
3968				    format_page->bytes_per_sector);
3969
3970			page_index->page_data =
3971				(uint8_t *)lun->mode_pages.format_page;
3972			break;
3973		}
3974		case SMS_RIGID_DISK_PAGE: {
3975			struct scsi_rigid_disk_page *rigid_disk_page;
3976			uint32_t sectors_per_cylinder;
3977			uint64_t cylinders;
3978#ifndef	__XSCALE__
3979			int shift;
3980#endif /* !__XSCALE__ */
3981
3982			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3983				panic("invalid subpage value %d",
3984				      page_index->subpage);
3985
3986			/*
3987			 * Rotation rate and sectors per track are set
3988			 * above.  We calculate the cylinders here based on
3989			 * capacity.  Due to the number of heads and
3990			 * sectors per track we're using, smaller arrays
3991			 * may turn out to have 0 cylinders.  Linux and
3992			 * FreeBSD don't pay attention to these mode pages
3993			 * to figure out capacity, but Solaris does.  It
3994			 * seems to deal with 0 cylinders just fine, and
3995			 * works out a fake geometry based on the capacity.
3996			 */
3997			memcpy(&lun->mode_pages.rigid_disk_page[
3998			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
3999			       sizeof(rigid_disk_page_default));
4000			memcpy(&lun->mode_pages.rigid_disk_page[
4001			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4002			       sizeof(rigid_disk_page_changeable));
4003
4004			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4005				CTL_DEFAULT_HEADS;
4006
4007			/*
4008			 * The divide method here will be more accurate,
4009			 * probably, but results in floating point being
4010			 * used in the kernel on i386 (__udivdi3()).  On the
4011			 * XScale, though, __udivdi3() is implemented in
4012			 * software.
4013			 *
4014			 * The shift method for cylinder calculation is
4015			 * accurate if sectors_per_cylinder is a power of
4016			 * 2.  Otherwise it might be slightly off -- you
4017			 * might have a bit of a truncation problem.
4018			 */
4019#ifdef	__XSCALE__
4020			cylinders = (lun->be_lun->maxlba + 1) /
4021				sectors_per_cylinder;
4022#else
4023			for (shift = 31; shift > 0; shift--) {
4024				if (sectors_per_cylinder & (1 << shift))
4025					break;
4026			}
4027			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4028#endif
4029
4030			/*
4031			 * We've basically got 3 bytes, or 24 bits for the
4032			 * cylinder size in the mode page.  If we're over,
4033			 * just round down to 2^24.
4034			 */
4035			if (cylinders > 0xffffff)
4036				cylinders = 0xffffff;
4037
4038			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4039				CTL_PAGE_DEFAULT];
4040			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4041
4042			if ((value = ctl_get_opt(&lun->be_lun->options,
4043			    "rpm")) != NULL) {
4044				scsi_ulto2b(strtol(value, NULL, 0),
4045				     rigid_disk_page->rotation_rate);
4046			}
4047
4048			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4049			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4050			       sizeof(rigid_disk_page_default));
4051			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4052			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4053			       sizeof(rigid_disk_page_default));
4054
4055			page_index->page_data =
4056				(uint8_t *)lun->mode_pages.rigid_disk_page;
4057			break;
4058		}
4059		case SMS_CACHING_PAGE: {
4060			struct scsi_caching_page *caching_page;
4061
4062			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4063				panic("invalid subpage value %d",
4064				      page_index->subpage);
4065			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4066			       &caching_page_default,
4067			       sizeof(caching_page_default));
4068			memcpy(&lun->mode_pages.caching_page[
4069			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4070			       sizeof(caching_page_changeable));
4071			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4072			       &caching_page_default,
4073			       sizeof(caching_page_default));
4074			caching_page = &lun->mode_pages.caching_page[
4075			    CTL_PAGE_SAVED];
4076			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4077			if (value != NULL && strcmp(value, "off") == 0)
4078				caching_page->flags1 &= ~SCP_WCE;
4079			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4080			if (value != NULL && strcmp(value, "off") == 0)
4081				caching_page->flags1 |= SCP_RCD;
4082			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4083			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4084			       sizeof(caching_page_default));
4085			page_index->page_data =
4086				(uint8_t *)lun->mode_pages.caching_page;
4087			break;
4088		}
4089		case SMS_CONTROL_MODE_PAGE: {
4090			struct scsi_control_page *control_page;
4091
4092			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4093				panic("invalid subpage value %d",
4094				      page_index->subpage);
4095
4096			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4097			       &control_page_default,
4098			       sizeof(control_page_default));
4099			memcpy(&lun->mode_pages.control_page[
4100			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4101			       sizeof(control_page_changeable));
4102			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4103			       &control_page_default,
4104			       sizeof(control_page_default));
4105			control_page = &lun->mode_pages.control_page[
4106			    CTL_PAGE_SAVED];
4107			value = ctl_get_opt(&lun->be_lun->options, "reordering");
4108			if (value != NULL && strcmp(value, "unrestricted") == 0) {
4109				control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4110				control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4111			}
4112			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4113			       &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4114			       sizeof(control_page_default));
4115			page_index->page_data =
4116				(uint8_t *)lun->mode_pages.control_page;
4117			break;
4118
4119		}
4120		case SMS_INFO_EXCEPTIONS_PAGE: {
4121			switch (page_index->subpage) {
4122			case SMS_SUBPAGE_PAGE_0:
4123				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4124				       &ie_page_default,
4125				       sizeof(ie_page_default));
4126				memcpy(&lun->mode_pages.ie_page[
4127				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4128				       sizeof(ie_page_changeable));
4129				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4130				       &ie_page_default,
4131				       sizeof(ie_page_default));
4132				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4133				       &ie_page_default,
4134				       sizeof(ie_page_default));
4135				page_index->page_data =
4136					(uint8_t *)lun->mode_pages.ie_page;
4137				break;
4138			case 0x02: {
4139				struct ctl_logical_block_provisioning_page *page;
4140
4141				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4142				       &lbp_page_default,
4143				       sizeof(lbp_page_default));
4144				memcpy(&lun->mode_pages.lbp_page[
4145				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4146				       sizeof(lbp_page_changeable));
4147				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4148				       &lbp_page_default,
4149				       sizeof(lbp_page_default));
4150				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4151				value = ctl_get_opt(&lun->be_lun->options,
4152				    "avail-threshold");
4153				if (value != NULL &&
4154				    ctl_expand_number(value, &ival) == 0) {
4155					page->descr[0].flags |= SLBPPD_ENABLED |
4156					    SLBPPD_ARMING_DEC;
4157					if (lun->be_lun->blocksize)
4158						ival /= lun->be_lun->blocksize;
4159					else
4160						ival /= 512;
4161					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4162					    page->descr[0].count);
4163				}
4164				value = ctl_get_opt(&lun->be_lun->options,
4165				    "used-threshold");
4166				if (value != NULL &&
4167				    ctl_expand_number(value, &ival) == 0) {
4168					page->descr[1].flags |= SLBPPD_ENABLED |
4169					    SLBPPD_ARMING_INC;
4170					if (lun->be_lun->blocksize)
4171						ival /= lun->be_lun->blocksize;
4172					else
4173						ival /= 512;
4174					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4175					    page->descr[1].count);
4176				}
4177				value = ctl_get_opt(&lun->be_lun->options,
4178				    "pool-avail-threshold");
4179				if (value != NULL &&
4180				    ctl_expand_number(value, &ival) == 0) {
4181					page->descr[2].flags |= SLBPPD_ENABLED |
4182					    SLBPPD_ARMING_DEC;
4183					if (lun->be_lun->blocksize)
4184						ival /= lun->be_lun->blocksize;
4185					else
4186						ival /= 512;
4187					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4188					    page->descr[2].count);
4189				}
4190				value = ctl_get_opt(&lun->be_lun->options,
4191				    "pool-used-threshold");
4192				if (value != NULL &&
4193				    ctl_expand_number(value, &ival) == 0) {
4194					page->descr[3].flags |= SLBPPD_ENABLED |
4195					    SLBPPD_ARMING_INC;
4196					if (lun->be_lun->blocksize)
4197						ival /= lun->be_lun->blocksize;
4198					else
4199						ival /= 512;
4200					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4201					    page->descr[3].count);
4202				}
4203				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4204				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4205				       sizeof(lbp_page_default));
4206				page_index->page_data =
4207					(uint8_t *)lun->mode_pages.lbp_page;
4208			}}
4209			break;
4210		}
4211		case SMS_VENDOR_SPECIFIC_PAGE:{
4212			switch (page_index->subpage) {
4213			case DBGCNF_SUBPAGE_CODE: {
4214				struct copan_debugconf_subpage *current_page,
4215							       *saved_page;
4216
4217				memcpy(&lun->mode_pages.debugconf_subpage[
4218				       CTL_PAGE_CURRENT],
4219				       &debugconf_page_default,
4220				       sizeof(debugconf_page_default));
4221				memcpy(&lun->mode_pages.debugconf_subpage[
4222				       CTL_PAGE_CHANGEABLE],
4223				       &debugconf_page_changeable,
4224				       sizeof(debugconf_page_changeable));
4225				memcpy(&lun->mode_pages.debugconf_subpage[
4226				       CTL_PAGE_DEFAULT],
4227				       &debugconf_page_default,
4228				       sizeof(debugconf_page_default));
4229				memcpy(&lun->mode_pages.debugconf_subpage[
4230				       CTL_PAGE_SAVED],
4231				       &debugconf_page_default,
4232				       sizeof(debugconf_page_default));
4233				page_index->page_data =
4234					(uint8_t *)lun->mode_pages.debugconf_subpage;
4235
4236				current_page = (struct copan_debugconf_subpage *)
4237					(page_index->page_data +
4238					 (page_index->page_len *
4239					  CTL_PAGE_CURRENT));
4240				saved_page = (struct copan_debugconf_subpage *)
4241					(page_index->page_data +
4242					 (page_index->page_len *
4243					  CTL_PAGE_SAVED));
4244				break;
4245			}
4246			default:
4247				panic("invalid subpage value %d",
4248				      page_index->subpage);
4249				break;
4250			}
4251   			break;
4252		}
4253		default:
4254			panic("invalid page value %d",
4255			      page_index->page_code & SMPH_PC_MASK);
4256			break;
4257    	}
4258	}
4259
4260	return (CTL_RETVAL_COMPLETE);
4261}
4262
4263static int
4264ctl_init_log_page_index(struct ctl_lun *lun)
4265{
4266	struct ctl_page_index *page_index;
4267	int i, j, k, prev;
4268
4269	memcpy(&lun->log_pages.index, log_page_index_template,
4270	       sizeof(log_page_index_template));
4271
4272	prev = -1;
4273	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4274
4275		page_index = &lun->log_pages.index[i];
4276		/*
4277		 * If this is a disk-only mode page, there's no point in
4278		 * setting it up.  For some pages, we have to have some
4279		 * basic information about the disk in order to calculate the
4280		 * mode page data.
4281		 */
4282		if ((lun->be_lun->lun_type != T_DIRECT)
4283		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4284			continue;
4285
4286		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4287		    ((lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) == 0 ||
4288		     lun->backend->lun_attr == NULL))
4289			continue;
4290
4291		if (page_index->page_code != prev) {
4292			lun->log_pages.pages_page[j] = page_index->page_code;
4293			prev = page_index->page_code;
4294			j++;
4295		}
4296		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4297		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4298		k++;
4299	}
4300	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4301	lun->log_pages.index[0].page_len = j;
4302	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4303	lun->log_pages.index[1].page_len = k * 2;
4304	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4305	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4306
4307	return (CTL_RETVAL_COMPLETE);
4308}
4309
4310static int
4311hex2bin(const char *str, uint8_t *buf, int buf_size)
4312{
4313	int i;
4314	u_char c;
4315
4316	memset(buf, 0, buf_size);
4317	while (isspace(str[0]))
4318		str++;
4319	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4320		str += 2;
4321	buf_size *= 2;
4322	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4323		c = str[i];
4324		if (isdigit(c))
4325			c -= '0';
4326		else if (isalpha(c))
4327			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4328		else
4329			break;
4330		if (c >= 16)
4331			break;
4332		if ((i & 1) == 0)
4333			buf[i / 2] |= (c << 4);
4334		else
4335			buf[i / 2] |= c;
4336	}
4337	return ((i + 1) / 2);
4338}
4339
4340/*
4341 * LUN allocation.
4342 *
4343 * Requirements:
4344 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4345 *   wants us to allocate the LUN and he can block.
4346 * - ctl_softc is always set
4347 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4348 *
4349 * Returns 0 for success, non-zero (errno) for failure.
4350 */
4351static int
4352ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4353	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4354{
4355	struct ctl_lun *nlun, *lun;
4356	struct ctl_port *port;
4357	struct scsi_vpd_id_descriptor *desc;
4358	struct scsi_vpd_id_t10 *t10id;
4359	const char *eui, *naa, *scsiname, *vendor, *value;
4360	int lun_number, i, lun_malloced;
4361	int devidlen, idlen1, idlen2 = 0, len;
4362
4363	if (be_lun == NULL)
4364		return (EINVAL);
4365
4366	/*
4367	 * We currently only support Direct Access or Processor LUN types.
4368	 */
4369	switch (be_lun->lun_type) {
4370	case T_DIRECT:
4371		break;
4372	case T_PROCESSOR:
4373		break;
4374	case T_SEQUENTIAL:
4375	case T_CHANGER:
4376	default:
4377		be_lun->lun_config_status(be_lun->be_lun,
4378					  CTL_LUN_CONFIG_FAILURE);
4379		break;
4380	}
4381	if (ctl_lun == NULL) {
4382		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4383		lun_malloced = 1;
4384	} else {
4385		lun_malloced = 0;
4386		lun = ctl_lun;
4387	}
4388
4389	memset(lun, 0, sizeof(*lun));
4390	if (lun_malloced)
4391		lun->flags = CTL_LUN_MALLOCED;
4392
4393	/* Generate LUN ID. */
4394	devidlen = max(CTL_DEVID_MIN_LEN,
4395	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4396	idlen1 = sizeof(*t10id) + devidlen;
4397	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4398	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4399	if (scsiname != NULL) {
4400		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4401		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4402	}
4403	eui = ctl_get_opt(&be_lun->options, "eui");
4404	if (eui != NULL) {
4405		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4406	}
4407	naa = ctl_get_opt(&be_lun->options, "naa");
4408	if (naa != NULL) {
4409		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4410	}
4411	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4412	    M_CTL, M_WAITOK | M_ZERO);
4413	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4414	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4415	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4416	desc->length = idlen1;
4417	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4418	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4419	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4420		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4421	} else {
4422		strncpy(t10id->vendor, vendor,
4423		    min(sizeof(t10id->vendor), strlen(vendor)));
4424	}
4425	strncpy((char *)t10id->vendor_spec_id,
4426	    (char *)be_lun->device_id, devidlen);
4427	if (scsiname != NULL) {
4428		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4429		    desc->length);
4430		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4431		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4432		    SVPD_ID_TYPE_SCSI_NAME;
4433		desc->length = idlen2;
4434		strlcpy(desc->identifier, scsiname, idlen2);
4435	}
4436	if (eui != NULL) {
4437		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4438		    desc->length);
4439		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4440		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4441		    SVPD_ID_TYPE_EUI64;
4442		desc->length = hex2bin(eui, desc->identifier, 16);
4443		desc->length = desc->length > 12 ? 16 :
4444		    (desc->length > 8 ? 12 : 8);
4445		len -= 16 - desc->length;
4446	}
4447	if (naa != NULL) {
4448		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4449		    desc->length);
4450		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4451		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4452		    SVPD_ID_TYPE_NAA;
4453		desc->length = hex2bin(naa, desc->identifier, 16);
4454		desc->length = desc->length > 8 ? 16 : 8;
4455		len -= 16 - desc->length;
4456	}
4457	lun->lun_devid->len = len;
4458
4459	mtx_lock(&ctl_softc->ctl_lock);
4460	/*
4461	 * See if the caller requested a particular LUN number.  If so, see
4462	 * if it is available.  Otherwise, allocate the first available LUN.
4463	 */
4464	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4465		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4466		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4467			mtx_unlock(&ctl_softc->ctl_lock);
4468			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4469				printf("ctl: requested LUN ID %d is higher "
4470				       "than CTL_MAX_LUNS - 1 (%d)\n",
4471				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4472			} else {
4473				/*
4474				 * XXX KDM return an error, or just assign
4475				 * another LUN ID in this case??
4476				 */
4477				printf("ctl: requested LUN ID %d is already "
4478				       "in use\n", be_lun->req_lun_id);
4479			}
4480			if (lun->flags & CTL_LUN_MALLOCED)
4481				free(lun, M_CTL);
4482			be_lun->lun_config_status(be_lun->be_lun,
4483						  CTL_LUN_CONFIG_FAILURE);
4484			return (ENOSPC);
4485		}
4486		lun_number = be_lun->req_lun_id;
4487	} else {
4488		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4489		if (lun_number == -1) {
4490			mtx_unlock(&ctl_softc->ctl_lock);
4491			printf("ctl: can't allocate LUN on target %ju, out of "
4492			       "LUNs\n", (uintmax_t)target_id.id);
4493			if (lun->flags & CTL_LUN_MALLOCED)
4494				free(lun, M_CTL);
4495			be_lun->lun_config_status(be_lun->be_lun,
4496						  CTL_LUN_CONFIG_FAILURE);
4497			return (ENOSPC);
4498		}
4499	}
4500	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4501
4502	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4503	lun->target = target_id;
4504	lun->lun = lun_number;
4505	lun->be_lun = be_lun;
4506	/*
4507	 * The processor LUN is always enabled.  Disk LUNs come on line
4508	 * disabled, and must be enabled by the backend.
4509	 */
4510	lun->flags |= CTL_LUN_DISABLED;
4511	lun->backend = be_lun->be;
4512	be_lun->ctl_lun = lun;
4513	be_lun->lun_id = lun_number;
4514	atomic_add_int(&be_lun->be->num_luns, 1);
4515	if (be_lun->flags & CTL_LUN_FLAG_OFFLINE)
4516		lun->flags |= CTL_LUN_OFFLINE;
4517
4518	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4519		lun->flags |= CTL_LUN_STOPPED;
4520
4521	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4522		lun->flags |= CTL_LUN_INOPERABLE;
4523
4524	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4525		lun->flags |= CTL_LUN_PRIMARY_SC;
4526
4527	value = ctl_get_opt(&be_lun->options, "readonly");
4528	if (value != NULL && strcmp(value, "on") == 0)
4529		lun->flags |= CTL_LUN_READONLY;
4530
4531	lun->ctl_softc = ctl_softc;
4532	TAILQ_INIT(&lun->ooa_queue);
4533	TAILQ_INIT(&lun->blocked_queue);
4534	STAILQ_INIT(&lun->error_list);
4535	ctl_tpc_lun_init(lun);
4536
4537	/*
4538	 * Initialize the mode and log page index.
4539	 */
4540	ctl_init_page_index(lun);
4541	ctl_init_log_page_index(lun);
4542
4543	/*
4544	 * Set the poweron UA for all initiators on this LUN only.
4545	 */
4546	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4547		lun->pending_ua[i] = CTL_UA_POWERON;
4548
4549	/*
4550	 * Now, before we insert this lun on the lun list, set the lun
4551	 * inventory changed UA for all other luns.
4552	 */
4553	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4554		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4555			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4556		}
4557	}
4558
4559	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4560
4561	ctl_softc->ctl_luns[lun_number] = lun;
4562
4563	ctl_softc->num_luns++;
4564
4565	/* Setup statistics gathering */
4566	lun->stats.device_type = be_lun->lun_type;
4567	lun->stats.lun_number = lun_number;
4568	if (lun->stats.device_type == T_DIRECT)
4569		lun->stats.blocksize = be_lun->blocksize;
4570	else
4571		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4572	for (i = 0;i < CTL_MAX_PORTS;i++)
4573		lun->stats.ports[i].targ_port = i;
4574
4575	mtx_unlock(&ctl_softc->ctl_lock);
4576
4577	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4578
4579	/*
4580	 * Run through each registered FETD and bring it online if it isn't
4581	 * already.  Enable the target ID if it hasn't been enabled, and
4582	 * enable this particular LUN.
4583	 */
4584	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4585		int retval;
4586
4587		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4588		if (retval != 0) {
4589			printf("ctl_alloc_lun: FETD %s port %d returned error "
4590			       "%d for lun_enable on target %ju lun %d\n",
4591			       port->port_name, port->targ_port, retval,
4592			       (uintmax_t)target_id.id, lun_number);
4593		} else
4594			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4595	}
4596	return (0);
4597}
4598
4599/*
4600 * Delete a LUN.
4601 * Assumptions:
4602 * - LUN has already been marked invalid and any pending I/O has been taken
4603 *   care of.
4604 */
4605static int
4606ctl_free_lun(struct ctl_lun *lun)
4607{
4608	struct ctl_softc *softc;
4609#if 0
4610	struct ctl_port *port;
4611#endif
4612	struct ctl_lun *nlun;
4613	int i;
4614
4615	softc = lun->ctl_softc;
4616
4617	mtx_assert(&softc->ctl_lock, MA_OWNED);
4618
4619	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4620
4621	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4622
4623	softc->ctl_luns[lun->lun] = NULL;
4624
4625	if (!TAILQ_EMPTY(&lun->ooa_queue))
4626		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4627
4628	softc->num_luns--;
4629
4630	/*
4631	 * XXX KDM this scheme only works for a single target/multiple LUN
4632	 * setup.  It needs to be revamped for a multiple target scheme.
4633	 *
4634	 * XXX KDM this results in port->lun_disable() getting called twice,
4635	 * once when ctl_disable_lun() is called, and a second time here.
4636	 * We really need to re-think the LUN disable semantics.  There
4637	 * should probably be several steps/levels to LUN removal:
4638	 *  - disable
4639	 *  - invalidate
4640	 *  - free
4641 	 *
4642	 * Right now we only have a disable method when communicating to
4643	 * the front end ports, at least for individual LUNs.
4644	 */
4645#if 0
4646	STAILQ_FOREACH(port, &softc->port_list, links) {
4647		int retval;
4648
4649		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4650					 lun->lun);
4651		if (retval != 0) {
4652			printf("ctl_free_lun: FETD %s port %d returned error "
4653			       "%d for lun_disable on target %ju lun %jd\n",
4654			       port->port_name, port->targ_port, retval,
4655			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4656		}
4657
4658		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4659			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4660
4661			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4662			if (retval != 0) {
4663				printf("ctl_free_lun: FETD %s port %d "
4664				       "returned error %d for targ_disable on "
4665				       "target %ju\n", port->port_name,
4666				       port->targ_port, retval,
4667				       (uintmax_t)lun->target.id);
4668			} else
4669				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4670
4671			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4672				continue;
4673
4674#if 0
4675			port->port_offline(port->onoff_arg);
4676			port->status &= ~CTL_PORT_STATUS_ONLINE;
4677#endif
4678		}
4679	}
4680#endif
4681
4682	/*
4683	 * Tell the backend to free resources, if this LUN has a backend.
4684	 */
4685	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4686	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4687
4688	ctl_tpc_lun_shutdown(lun);
4689	mtx_destroy(&lun->lun_lock);
4690	free(lun->lun_devid, M_CTL);
4691	free(lun->write_buffer, M_CTL);
4692	if (lun->flags & CTL_LUN_MALLOCED)
4693		free(lun, M_CTL);
4694
4695	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4696		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4697			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4698		}
4699	}
4700
4701	return (0);
4702}
4703
4704static void
4705ctl_create_lun(struct ctl_be_lun *be_lun)
4706{
4707	struct ctl_softc *ctl_softc;
4708
4709	ctl_softc = control_softc;
4710
4711	/*
4712	 * ctl_alloc_lun() should handle all potential failure cases.
4713	 */
4714	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4715}
4716
4717int
4718ctl_add_lun(struct ctl_be_lun *be_lun)
4719{
4720	struct ctl_softc *ctl_softc = control_softc;
4721
4722	mtx_lock(&ctl_softc->ctl_lock);
4723	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4724	mtx_unlock(&ctl_softc->ctl_lock);
4725	wakeup(&ctl_softc->pending_lun_queue);
4726
4727	return (0);
4728}
4729
4730int
4731ctl_enable_lun(struct ctl_be_lun *be_lun)
4732{
4733	struct ctl_softc *ctl_softc;
4734	struct ctl_port *port, *nport;
4735	struct ctl_lun *lun;
4736	int retval;
4737
4738	ctl_softc = control_softc;
4739
4740	lun = (struct ctl_lun *)be_lun->ctl_lun;
4741
4742	mtx_lock(&ctl_softc->ctl_lock);
4743	mtx_lock(&lun->lun_lock);
4744	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4745		/*
4746		 * eh?  Why did we get called if the LUN is already
4747		 * enabled?
4748		 */
4749		mtx_unlock(&lun->lun_lock);
4750		mtx_unlock(&ctl_softc->ctl_lock);
4751		return (0);
4752	}
4753	lun->flags &= ~CTL_LUN_DISABLED;
4754	mtx_unlock(&lun->lun_lock);
4755
4756	for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4757		nport = STAILQ_NEXT(port, links);
4758
4759		/*
4760		 * Drop the lock while we call the FETD's enable routine.
4761		 * This can lead to a callback into CTL (at least in the
4762		 * case of the internal initiator frontend.
4763		 */
4764		mtx_unlock(&ctl_softc->ctl_lock);
4765		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4766		mtx_lock(&ctl_softc->ctl_lock);
4767		if (retval != 0) {
4768			printf("%s: FETD %s port %d returned error "
4769			       "%d for lun_enable on target %ju lun %jd\n",
4770			       __func__, port->port_name, port->targ_port, retval,
4771			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4772		}
4773#if 0
4774		 else {
4775            /* NOTE:  TODO:  why does lun enable affect port status? */
4776			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4777		}
4778#endif
4779	}
4780
4781	mtx_unlock(&ctl_softc->ctl_lock);
4782
4783	return (0);
4784}
4785
4786int
4787ctl_disable_lun(struct ctl_be_lun *be_lun)
4788{
4789	struct ctl_softc *ctl_softc;
4790	struct ctl_port *port;
4791	struct ctl_lun *lun;
4792	int retval;
4793
4794	ctl_softc = control_softc;
4795
4796	lun = (struct ctl_lun *)be_lun->ctl_lun;
4797
4798	mtx_lock(&ctl_softc->ctl_lock);
4799	mtx_lock(&lun->lun_lock);
4800	if (lun->flags & CTL_LUN_DISABLED) {
4801		mtx_unlock(&lun->lun_lock);
4802		mtx_unlock(&ctl_softc->ctl_lock);
4803		return (0);
4804	}
4805	lun->flags |= CTL_LUN_DISABLED;
4806	mtx_unlock(&lun->lun_lock);
4807
4808	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4809		mtx_unlock(&ctl_softc->ctl_lock);
4810		/*
4811		 * Drop the lock before we call the frontend's disable
4812		 * routine, to avoid lock order reversals.
4813		 *
4814		 * XXX KDM what happens if the frontend list changes while
4815		 * we're traversing it?  It's unlikely, but should be handled.
4816		 */
4817		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4818					 lun->lun);
4819		mtx_lock(&ctl_softc->ctl_lock);
4820		if (retval != 0) {
4821			printf("ctl_alloc_lun: FETD %s port %d returned error "
4822			       "%d for lun_disable on target %ju lun %jd\n",
4823			       port->port_name, port->targ_port, retval,
4824			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4825		}
4826	}
4827
4828	mtx_unlock(&ctl_softc->ctl_lock);
4829
4830	return (0);
4831}
4832
4833int
4834ctl_start_lun(struct ctl_be_lun *be_lun)
4835{
4836	struct ctl_softc *ctl_softc;
4837	struct ctl_lun *lun;
4838
4839	ctl_softc = control_softc;
4840
4841	lun = (struct ctl_lun *)be_lun->ctl_lun;
4842
4843	mtx_lock(&lun->lun_lock);
4844	lun->flags &= ~CTL_LUN_STOPPED;
4845	mtx_unlock(&lun->lun_lock);
4846
4847	return (0);
4848}
4849
4850int
4851ctl_stop_lun(struct ctl_be_lun *be_lun)
4852{
4853	struct ctl_softc *ctl_softc;
4854	struct ctl_lun *lun;
4855
4856	ctl_softc = control_softc;
4857
4858	lun = (struct ctl_lun *)be_lun->ctl_lun;
4859
4860	mtx_lock(&lun->lun_lock);
4861	lun->flags |= CTL_LUN_STOPPED;
4862	mtx_unlock(&lun->lun_lock);
4863
4864	return (0);
4865}
4866
4867int
4868ctl_lun_offline(struct ctl_be_lun *be_lun)
4869{
4870	struct ctl_softc *ctl_softc;
4871	struct ctl_lun *lun;
4872
4873	ctl_softc = control_softc;
4874
4875	lun = (struct ctl_lun *)be_lun->ctl_lun;
4876
4877	mtx_lock(&lun->lun_lock);
4878	lun->flags |= CTL_LUN_OFFLINE;
4879	mtx_unlock(&lun->lun_lock);
4880
4881	return (0);
4882}
4883
4884int
4885ctl_lun_online(struct ctl_be_lun *be_lun)
4886{
4887	struct ctl_softc *ctl_softc;
4888	struct ctl_lun *lun;
4889
4890	ctl_softc = control_softc;
4891
4892	lun = (struct ctl_lun *)be_lun->ctl_lun;
4893
4894	mtx_lock(&lun->lun_lock);
4895	lun->flags &= ~CTL_LUN_OFFLINE;
4896	mtx_unlock(&lun->lun_lock);
4897
4898	return (0);
4899}
4900
4901int
4902ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4903{
4904	struct ctl_softc *ctl_softc;
4905	struct ctl_lun *lun;
4906
4907	ctl_softc = control_softc;
4908
4909	lun = (struct ctl_lun *)be_lun->ctl_lun;
4910
4911	mtx_lock(&lun->lun_lock);
4912
4913	/*
4914	 * The LUN needs to be disabled before it can be marked invalid.
4915	 */
4916	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4917		mtx_unlock(&lun->lun_lock);
4918		return (-1);
4919	}
4920	/*
4921	 * Mark the LUN invalid.
4922	 */
4923	lun->flags |= CTL_LUN_INVALID;
4924
4925	/*
4926	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4927	 * If we have something in the OOA queue, we'll free it when the
4928	 * last I/O completes.
4929	 */
4930	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4931		mtx_unlock(&lun->lun_lock);
4932		mtx_lock(&ctl_softc->ctl_lock);
4933		ctl_free_lun(lun);
4934		mtx_unlock(&ctl_softc->ctl_lock);
4935	} else
4936		mtx_unlock(&lun->lun_lock);
4937
4938	return (0);
4939}
4940
4941int
4942ctl_lun_inoperable(struct ctl_be_lun *be_lun)
4943{
4944	struct ctl_softc *ctl_softc;
4945	struct ctl_lun *lun;
4946
4947	ctl_softc = control_softc;
4948	lun = (struct ctl_lun *)be_lun->ctl_lun;
4949
4950	mtx_lock(&lun->lun_lock);
4951	lun->flags |= CTL_LUN_INOPERABLE;
4952	mtx_unlock(&lun->lun_lock);
4953
4954	return (0);
4955}
4956
4957int
4958ctl_lun_operable(struct ctl_be_lun *be_lun)
4959{
4960	struct ctl_softc *ctl_softc;
4961	struct ctl_lun *lun;
4962
4963	ctl_softc = control_softc;
4964	lun = (struct ctl_lun *)be_lun->ctl_lun;
4965
4966	mtx_lock(&lun->lun_lock);
4967	lun->flags &= ~CTL_LUN_INOPERABLE;
4968	mtx_unlock(&lun->lun_lock);
4969
4970	return (0);
4971}
4972
4973void
4974ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4975{
4976	struct ctl_lun *lun;
4977	struct ctl_softc *softc;
4978	int i;
4979
4980	softc = control_softc;
4981
4982	lun = (struct ctl_lun *)be_lun->ctl_lun;
4983
4984	mtx_lock(&lun->lun_lock);
4985
4986	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4987		lun->pending_ua[i] |= CTL_UA_CAPACITY_CHANGED;
4988
4989	mtx_unlock(&lun->lun_lock);
4990}
4991
4992/*
4993 * Backend "memory move is complete" callback for requests that never
4994 * make it down to say RAIDCore's configuration code.
4995 */
4996int
4997ctl_config_move_done(union ctl_io *io)
4998{
4999	int retval;
5000
5001	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5002	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5003	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5004
5005	if ((io->io_hdr.port_status != 0) &&
5006	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5007	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5008		/*
5009		 * For hardware error sense keys, the sense key
5010		 * specific value is defined to be a retry count,
5011		 * but we use it to pass back an internal FETD
5012		 * error code.  XXX KDM  Hopefully the FETD is only
5013		 * using 16 bits for an error code, since that's
5014		 * all the space we have in the sks field.
5015		 */
5016		ctl_set_internal_failure(&io->scsiio,
5017					 /*sks_valid*/ 1,
5018					 /*retry_count*/
5019					 io->io_hdr.port_status);
5020	}
5021
5022	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5023	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5024	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5025	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5026		/*
5027		 * XXX KDM just assuming a single pointer here, and not a
5028		 * S/G list.  If we start using S/G lists for config data,
5029		 * we'll need to know how to clean them up here as well.
5030		 */
5031		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5032			free(io->scsiio.kern_data_ptr, M_CTL);
5033		ctl_done(io);
5034		retval = CTL_RETVAL_COMPLETE;
5035	} else {
5036		/*
5037		 * XXX KDM now we need to continue data movement.  Some
5038		 * options:
5039		 * - call ctl_scsiio() again?  We don't do this for data
5040		 *   writes, because for those at least we know ahead of
5041		 *   time where the write will go and how long it is.  For
5042		 *   config writes, though, that information is largely
5043		 *   contained within the write itself, thus we need to
5044		 *   parse out the data again.
5045		 *
5046		 * - Call some other function once the data is in?
5047		 */
5048		if (ctl_debug & CTL_DEBUG_CDB_DATA)
5049			ctl_data_print(io);
5050
5051		/*
5052		 * XXX KDM call ctl_scsiio() again for now, and check flag
5053		 * bits to see whether we're allocated or not.
5054		 */
5055		retval = ctl_scsiio(&io->scsiio);
5056	}
5057	return (retval);
5058}
5059
5060/*
5061 * This gets called by a backend driver when it is done with a
5062 * data_submit method.
5063 */
5064void
5065ctl_data_submit_done(union ctl_io *io)
5066{
5067	/*
5068	 * If the IO_CONT flag is set, we need to call the supplied
5069	 * function to continue processing the I/O, instead of completing
5070	 * the I/O just yet.
5071	 *
5072	 * If there is an error, though, we don't want to keep processing.
5073	 * Instead, just send status back to the initiator.
5074	 */
5075	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5076	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5077	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5078	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5079		io->scsiio.io_cont(io);
5080		return;
5081	}
5082	ctl_done(io);
5083}
5084
5085/*
5086 * This gets called by a backend driver when it is done with a
5087 * configuration write.
5088 */
5089void
5090ctl_config_write_done(union ctl_io *io)
5091{
5092	uint8_t *buf;
5093
5094	/*
5095	 * If the IO_CONT flag is set, we need to call the supplied
5096	 * function to continue processing the I/O, instead of completing
5097	 * the I/O just yet.
5098	 *
5099	 * If there is an error, though, we don't want to keep processing.
5100	 * Instead, just send status back to the initiator.
5101	 */
5102	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5103	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5104	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5105	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5106		io->scsiio.io_cont(io);
5107		return;
5108	}
5109	/*
5110	 * Since a configuration write can be done for commands that actually
5111	 * have data allocated, like write buffer, and commands that have
5112	 * no data, like start/stop unit, we need to check here.
5113	 */
5114	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5115		buf = io->scsiio.kern_data_ptr;
5116	else
5117		buf = NULL;
5118	ctl_done(io);
5119	if (buf)
5120		free(buf, M_CTL);
5121}
5122
5123/*
5124 * SCSI release command.
5125 */
5126int
5127ctl_scsi_release(struct ctl_scsiio *ctsio)
5128{
5129	int length, longid, thirdparty_id, resv_id;
5130	struct ctl_softc *ctl_softc;
5131	struct ctl_lun *lun;
5132	uint32_t residx;
5133
5134	length = 0;
5135	resv_id = 0;
5136
5137	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5138
5139	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5140	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5141	ctl_softc = control_softc;
5142
5143	switch (ctsio->cdb[0]) {
5144	case RELEASE_10: {
5145		struct scsi_release_10 *cdb;
5146
5147		cdb = (struct scsi_release_10 *)ctsio->cdb;
5148
5149		if (cdb->byte2 & SR10_LONGID)
5150			longid = 1;
5151		else
5152			thirdparty_id = cdb->thirdparty_id;
5153
5154		resv_id = cdb->resv_id;
5155		length = scsi_2btoul(cdb->length);
5156		break;
5157	}
5158	}
5159
5160
5161	/*
5162	 * XXX KDM right now, we only support LUN reservation.  We don't
5163	 * support 3rd party reservations, or extent reservations, which
5164	 * might actually need the parameter list.  If we've gotten this
5165	 * far, we've got a LUN reservation.  Anything else got kicked out
5166	 * above.  So, according to SPC, ignore the length.
5167	 */
5168	length = 0;
5169
5170	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5171	 && (length > 0)) {
5172		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5173		ctsio->kern_data_len = length;
5174		ctsio->kern_total_len = length;
5175		ctsio->kern_data_resid = 0;
5176		ctsio->kern_rel_offset = 0;
5177		ctsio->kern_sg_entries = 0;
5178		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5179		ctsio->be_move_done = ctl_config_move_done;
5180		ctl_datamove((union ctl_io *)ctsio);
5181
5182		return (CTL_RETVAL_COMPLETE);
5183	}
5184
5185	if (length > 0)
5186		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5187
5188	mtx_lock(&lun->lun_lock);
5189
5190	/*
5191	 * According to SPC, it is not an error for an intiator to attempt
5192	 * to release a reservation on a LUN that isn't reserved, or that
5193	 * is reserved by another initiator.  The reservation can only be
5194	 * released, though, by the initiator who made it or by one of
5195	 * several reset type events.
5196	 */
5197	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5198			lun->flags &= ~CTL_LUN_RESERVED;
5199
5200	mtx_unlock(&lun->lun_lock);
5201
5202	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5203		free(ctsio->kern_data_ptr, M_CTL);
5204		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5205	}
5206
5207	ctl_set_success(ctsio);
5208	ctl_done((union ctl_io *)ctsio);
5209	return (CTL_RETVAL_COMPLETE);
5210}
5211
5212int
5213ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5214{
5215	int extent, thirdparty, longid;
5216	int resv_id, length;
5217	uint64_t thirdparty_id;
5218	struct ctl_softc *ctl_softc;
5219	struct ctl_lun *lun;
5220	uint32_t residx;
5221
5222	extent = 0;
5223	thirdparty = 0;
5224	longid = 0;
5225	resv_id = 0;
5226	length = 0;
5227	thirdparty_id = 0;
5228
5229	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5230
5231	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5232	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5233	ctl_softc = control_softc;
5234
5235	switch (ctsio->cdb[0]) {
5236	case RESERVE_10: {
5237		struct scsi_reserve_10 *cdb;
5238
5239		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5240
5241		if (cdb->byte2 & SR10_LONGID)
5242			longid = 1;
5243		else
5244			thirdparty_id = cdb->thirdparty_id;
5245
5246		resv_id = cdb->resv_id;
5247		length = scsi_2btoul(cdb->length);
5248		break;
5249	}
5250	}
5251
5252	/*
5253	 * XXX KDM right now, we only support LUN reservation.  We don't
5254	 * support 3rd party reservations, or extent reservations, which
5255	 * might actually need the parameter list.  If we've gotten this
5256	 * far, we've got a LUN reservation.  Anything else got kicked out
5257	 * above.  So, according to SPC, ignore the length.
5258	 */
5259	length = 0;
5260
5261	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5262	 && (length > 0)) {
5263		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5264		ctsio->kern_data_len = length;
5265		ctsio->kern_total_len = length;
5266		ctsio->kern_data_resid = 0;
5267		ctsio->kern_rel_offset = 0;
5268		ctsio->kern_sg_entries = 0;
5269		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5270		ctsio->be_move_done = ctl_config_move_done;
5271		ctl_datamove((union ctl_io *)ctsio);
5272
5273		return (CTL_RETVAL_COMPLETE);
5274	}
5275
5276	if (length > 0)
5277		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5278
5279	mtx_lock(&lun->lun_lock);
5280	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5281		ctl_set_reservation_conflict(ctsio);
5282		goto bailout;
5283	}
5284
5285	lun->flags |= CTL_LUN_RESERVED;
5286	lun->res_idx = residx;
5287
5288	ctl_set_success(ctsio);
5289
5290bailout:
5291	mtx_unlock(&lun->lun_lock);
5292
5293	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5294		free(ctsio->kern_data_ptr, M_CTL);
5295		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5296	}
5297
5298	ctl_done((union ctl_io *)ctsio);
5299	return (CTL_RETVAL_COMPLETE);
5300}
5301
5302int
5303ctl_start_stop(struct ctl_scsiio *ctsio)
5304{
5305	struct scsi_start_stop_unit *cdb;
5306	struct ctl_lun *lun;
5307	struct ctl_softc *ctl_softc;
5308	int retval;
5309
5310	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5311
5312	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5313	ctl_softc = control_softc;
5314	retval = 0;
5315
5316	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5317
5318	/*
5319	 * XXX KDM
5320	 * We don't support the immediate bit on a stop unit.  In order to
5321	 * do that, we would need to code up a way to know that a stop is
5322	 * pending, and hold off any new commands until it completes, one
5323	 * way or another.  Then we could accept or reject those commands
5324	 * depending on its status.  We would almost need to do the reverse
5325	 * of what we do below for an immediate start -- return the copy of
5326	 * the ctl_io to the FETD with status to send to the host (and to
5327	 * free the copy!) and then free the original I/O once the stop
5328	 * actually completes.  That way, the OOA queue mechanism can work
5329	 * to block commands that shouldn't proceed.  Another alternative
5330	 * would be to put the copy in the queue in place of the original,
5331	 * and return the original back to the caller.  That could be
5332	 * slightly safer..
5333	 */
5334	if ((cdb->byte2 & SSS_IMMED)
5335	 && ((cdb->how & SSS_START) == 0)) {
5336		ctl_set_invalid_field(ctsio,
5337				      /*sks_valid*/ 1,
5338				      /*command*/ 1,
5339				      /*field*/ 1,
5340				      /*bit_valid*/ 1,
5341				      /*bit*/ 0);
5342		ctl_done((union ctl_io *)ctsio);
5343		return (CTL_RETVAL_COMPLETE);
5344	}
5345
5346	if ((lun->flags & CTL_LUN_PR_RESERVED)
5347	 && ((cdb->how & SSS_START)==0)) {
5348		uint32_t residx;
5349
5350		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5351		if (lun->pr_keys[residx] == 0
5352		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5353
5354			ctl_set_reservation_conflict(ctsio);
5355			ctl_done((union ctl_io *)ctsio);
5356			return (CTL_RETVAL_COMPLETE);
5357		}
5358	}
5359
5360	/*
5361	 * If there is no backend on this device, we can't start or stop
5362	 * it.  In theory we shouldn't get any start/stop commands in the
5363	 * first place at this level if the LUN doesn't have a backend.
5364	 * That should get stopped by the command decode code.
5365	 */
5366	if (lun->backend == NULL) {
5367		ctl_set_invalid_opcode(ctsio);
5368		ctl_done((union ctl_io *)ctsio);
5369		return (CTL_RETVAL_COMPLETE);
5370	}
5371
5372	/*
5373	 * XXX KDM Copan-specific offline behavior.
5374	 * Figure out a reasonable way to port this?
5375	 */
5376#ifdef NEEDTOPORT
5377	mtx_lock(&lun->lun_lock);
5378
5379	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5380	 && (lun->flags & CTL_LUN_OFFLINE)) {
5381		/*
5382		 * If the LUN is offline, and the on/offline bit isn't set,
5383		 * reject the start or stop.  Otherwise, let it through.
5384		 */
5385		mtx_unlock(&lun->lun_lock);
5386		ctl_set_lun_not_ready(ctsio);
5387		ctl_done((union ctl_io *)ctsio);
5388	} else {
5389		mtx_unlock(&lun->lun_lock);
5390#endif /* NEEDTOPORT */
5391		/*
5392		 * This could be a start or a stop when we're online,
5393		 * or a stop/offline or start/online.  A start or stop when
5394		 * we're offline is covered in the case above.
5395		 */
5396		/*
5397		 * In the non-immediate case, we send the request to
5398		 * the backend and return status to the user when
5399		 * it is done.
5400		 *
5401		 * In the immediate case, we allocate a new ctl_io
5402		 * to hold a copy of the request, and send that to
5403		 * the backend.  We then set good status on the
5404		 * user's request and return it immediately.
5405		 */
5406		if (cdb->byte2 & SSS_IMMED) {
5407			union ctl_io *new_io;
5408
5409			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5410			ctl_copy_io((union ctl_io *)ctsio, new_io);
5411			retval = lun->backend->config_write(new_io);
5412			ctl_set_success(ctsio);
5413			ctl_done((union ctl_io *)ctsio);
5414		} else {
5415			retval = lun->backend->config_write(
5416				(union ctl_io *)ctsio);
5417		}
5418#ifdef NEEDTOPORT
5419	}
5420#endif
5421	return (retval);
5422}
5423
5424/*
5425 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5426 * we don't really do anything with the LBA and length fields if the user
5427 * passes them in.  Instead we'll just flush out the cache for the entire
5428 * LUN.
5429 */
5430int
5431ctl_sync_cache(struct ctl_scsiio *ctsio)
5432{
5433	struct ctl_lun *lun;
5434	struct ctl_softc *ctl_softc;
5435	uint64_t starting_lba;
5436	uint32_t block_count;
5437	int retval;
5438
5439	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5440
5441	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5442	ctl_softc = control_softc;
5443	retval = 0;
5444
5445	switch (ctsio->cdb[0]) {
5446	case SYNCHRONIZE_CACHE: {
5447		struct scsi_sync_cache *cdb;
5448		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5449
5450		starting_lba = scsi_4btoul(cdb->begin_lba);
5451		block_count = scsi_2btoul(cdb->lb_count);
5452		break;
5453	}
5454	case SYNCHRONIZE_CACHE_16: {
5455		struct scsi_sync_cache_16 *cdb;
5456		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5457
5458		starting_lba = scsi_8btou64(cdb->begin_lba);
5459		block_count = scsi_4btoul(cdb->lb_count);
5460		break;
5461	}
5462	default:
5463		ctl_set_invalid_opcode(ctsio);
5464		ctl_done((union ctl_io *)ctsio);
5465		goto bailout;
5466		break; /* NOTREACHED */
5467	}
5468
5469	/*
5470	 * We check the LBA and length, but don't do anything with them.
5471	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5472	 * get flushed.  This check will just help satisfy anyone who wants
5473	 * to see an error for an out of range LBA.
5474	 */
5475	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5476		ctl_set_lba_out_of_range(ctsio);
5477		ctl_done((union ctl_io *)ctsio);
5478		goto bailout;
5479	}
5480
5481	/*
5482	 * If this LUN has no backend, we can't flush the cache anyway.
5483	 */
5484	if (lun->backend == NULL) {
5485		ctl_set_invalid_opcode(ctsio);
5486		ctl_done((union ctl_io *)ctsio);
5487		goto bailout;
5488	}
5489
5490	/*
5491	 * Check to see whether we're configured to send the SYNCHRONIZE
5492	 * CACHE command directly to the back end.
5493	 */
5494	mtx_lock(&lun->lun_lock);
5495	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5496	 && (++(lun->sync_count) >= lun->sync_interval)) {
5497		lun->sync_count = 0;
5498		mtx_unlock(&lun->lun_lock);
5499		retval = lun->backend->config_write((union ctl_io *)ctsio);
5500	} else {
5501		mtx_unlock(&lun->lun_lock);
5502		ctl_set_success(ctsio);
5503		ctl_done((union ctl_io *)ctsio);
5504	}
5505
5506bailout:
5507
5508	return (retval);
5509}
5510
5511int
5512ctl_format(struct ctl_scsiio *ctsio)
5513{
5514	struct scsi_format *cdb;
5515	struct ctl_lun *lun;
5516	struct ctl_softc *ctl_softc;
5517	int length, defect_list_len;
5518
5519	CTL_DEBUG_PRINT(("ctl_format\n"));
5520
5521	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5522	ctl_softc = control_softc;
5523
5524	cdb = (struct scsi_format *)ctsio->cdb;
5525
5526	length = 0;
5527	if (cdb->byte2 & SF_FMTDATA) {
5528		if (cdb->byte2 & SF_LONGLIST)
5529			length = sizeof(struct scsi_format_header_long);
5530		else
5531			length = sizeof(struct scsi_format_header_short);
5532	}
5533
5534	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5535	 && (length > 0)) {
5536		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5537		ctsio->kern_data_len = length;
5538		ctsio->kern_total_len = length;
5539		ctsio->kern_data_resid = 0;
5540		ctsio->kern_rel_offset = 0;
5541		ctsio->kern_sg_entries = 0;
5542		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5543		ctsio->be_move_done = ctl_config_move_done;
5544		ctl_datamove((union ctl_io *)ctsio);
5545
5546		return (CTL_RETVAL_COMPLETE);
5547	}
5548
5549	defect_list_len = 0;
5550
5551	if (cdb->byte2 & SF_FMTDATA) {
5552		if (cdb->byte2 & SF_LONGLIST) {
5553			struct scsi_format_header_long *header;
5554
5555			header = (struct scsi_format_header_long *)
5556				ctsio->kern_data_ptr;
5557
5558			defect_list_len = scsi_4btoul(header->defect_list_len);
5559			if (defect_list_len != 0) {
5560				ctl_set_invalid_field(ctsio,
5561						      /*sks_valid*/ 1,
5562						      /*command*/ 0,
5563						      /*field*/ 2,
5564						      /*bit_valid*/ 0,
5565						      /*bit*/ 0);
5566				goto bailout;
5567			}
5568		} else {
5569			struct scsi_format_header_short *header;
5570
5571			header = (struct scsi_format_header_short *)
5572				ctsio->kern_data_ptr;
5573
5574			defect_list_len = scsi_2btoul(header->defect_list_len);
5575			if (defect_list_len != 0) {
5576				ctl_set_invalid_field(ctsio,
5577						      /*sks_valid*/ 1,
5578						      /*command*/ 0,
5579						      /*field*/ 2,
5580						      /*bit_valid*/ 0,
5581						      /*bit*/ 0);
5582				goto bailout;
5583			}
5584		}
5585	}
5586
5587	/*
5588	 * The format command will clear out the "Medium format corrupted"
5589	 * status if set by the configuration code.  That status is really
5590	 * just a way to notify the host that we have lost the media, and
5591	 * get them to issue a command that will basically make them think
5592	 * they're blowing away the media.
5593	 */
5594	mtx_lock(&lun->lun_lock);
5595	lun->flags &= ~CTL_LUN_INOPERABLE;
5596	mtx_unlock(&lun->lun_lock);
5597
5598	ctl_set_success(ctsio);
5599bailout:
5600
5601	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5602		free(ctsio->kern_data_ptr, M_CTL);
5603		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5604	}
5605
5606	ctl_done((union ctl_io *)ctsio);
5607	return (CTL_RETVAL_COMPLETE);
5608}
5609
5610int
5611ctl_read_buffer(struct ctl_scsiio *ctsio)
5612{
5613	struct scsi_read_buffer *cdb;
5614	struct ctl_lun *lun;
5615	int buffer_offset, len;
5616	static uint8_t descr[4];
5617	static uint8_t echo_descr[4] = { 0 };
5618
5619	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5620
5621	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5622	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5623
5624	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5625	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5626	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5627		ctl_set_invalid_field(ctsio,
5628				      /*sks_valid*/ 1,
5629				      /*command*/ 1,
5630				      /*field*/ 1,
5631				      /*bit_valid*/ 1,
5632				      /*bit*/ 4);
5633		ctl_done((union ctl_io *)ctsio);
5634		return (CTL_RETVAL_COMPLETE);
5635	}
5636
5637	len = scsi_3btoul(cdb->length);
5638	buffer_offset = scsi_3btoul(cdb->offset);
5639
5640	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5641		ctl_set_invalid_field(ctsio,
5642				      /*sks_valid*/ 1,
5643				      /*command*/ 1,
5644				      /*field*/ 6,
5645				      /*bit_valid*/ 0,
5646				      /*bit*/ 0);
5647		ctl_done((union ctl_io *)ctsio);
5648		return (CTL_RETVAL_COMPLETE);
5649	}
5650
5651	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5652		descr[0] = 0;
5653		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5654		ctsio->kern_data_ptr = descr;
5655		len = min(len, sizeof(descr));
5656	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5657		ctsio->kern_data_ptr = echo_descr;
5658		len = min(len, sizeof(echo_descr));
5659	} else {
5660		if (lun->write_buffer == NULL) {
5661			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5662			    M_CTL, M_WAITOK);
5663		}
5664		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5665	}
5666	ctsio->kern_data_len = len;
5667	ctsio->kern_total_len = len;
5668	ctsio->kern_data_resid = 0;
5669	ctsio->kern_rel_offset = 0;
5670	ctsio->kern_sg_entries = 0;
5671	ctl_set_success(ctsio);
5672	ctsio->be_move_done = ctl_config_move_done;
5673	ctl_datamove((union ctl_io *)ctsio);
5674	return (CTL_RETVAL_COMPLETE);
5675}
5676
5677int
5678ctl_write_buffer(struct ctl_scsiio *ctsio)
5679{
5680	struct scsi_write_buffer *cdb;
5681	struct ctl_lun *lun;
5682	int buffer_offset, len;
5683
5684	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5685
5686	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5687	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5688
5689	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5690		ctl_set_invalid_field(ctsio,
5691				      /*sks_valid*/ 1,
5692				      /*command*/ 1,
5693				      /*field*/ 1,
5694				      /*bit_valid*/ 1,
5695				      /*bit*/ 4);
5696		ctl_done((union ctl_io *)ctsio);
5697		return (CTL_RETVAL_COMPLETE);
5698	}
5699
5700	len = scsi_3btoul(cdb->length);
5701	buffer_offset = scsi_3btoul(cdb->offset);
5702
5703	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5704		ctl_set_invalid_field(ctsio,
5705				      /*sks_valid*/ 1,
5706				      /*command*/ 1,
5707				      /*field*/ 6,
5708				      /*bit_valid*/ 0,
5709				      /*bit*/ 0);
5710		ctl_done((union ctl_io *)ctsio);
5711		return (CTL_RETVAL_COMPLETE);
5712	}
5713
5714	/*
5715	 * If we've got a kernel request that hasn't been malloced yet,
5716	 * malloc it and tell the caller the data buffer is here.
5717	 */
5718	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5719		if (lun->write_buffer == NULL) {
5720			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5721			    M_CTL, M_WAITOK);
5722		}
5723		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5724		ctsio->kern_data_len = len;
5725		ctsio->kern_total_len = len;
5726		ctsio->kern_data_resid = 0;
5727		ctsio->kern_rel_offset = 0;
5728		ctsio->kern_sg_entries = 0;
5729		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5730		ctsio->be_move_done = ctl_config_move_done;
5731		ctl_datamove((union ctl_io *)ctsio);
5732
5733		return (CTL_RETVAL_COMPLETE);
5734	}
5735
5736	ctl_set_success(ctsio);
5737	ctl_done((union ctl_io *)ctsio);
5738	return (CTL_RETVAL_COMPLETE);
5739}
5740
5741int
5742ctl_write_same(struct ctl_scsiio *ctsio)
5743{
5744	struct ctl_lun *lun;
5745	struct ctl_lba_len_flags *lbalen;
5746	uint64_t lba;
5747	uint32_t num_blocks;
5748	int len, retval;
5749	uint8_t byte2;
5750
5751	retval = CTL_RETVAL_COMPLETE;
5752
5753	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5754
5755	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5756
5757	switch (ctsio->cdb[0]) {
5758	case WRITE_SAME_10: {
5759		struct scsi_write_same_10 *cdb;
5760
5761		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5762
5763		lba = scsi_4btoul(cdb->addr);
5764		num_blocks = scsi_2btoul(cdb->length);
5765		byte2 = cdb->byte2;
5766		break;
5767	}
5768	case WRITE_SAME_16: {
5769		struct scsi_write_same_16 *cdb;
5770
5771		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5772
5773		lba = scsi_8btou64(cdb->addr);
5774		num_blocks = scsi_4btoul(cdb->length);
5775		byte2 = cdb->byte2;
5776		break;
5777	}
5778	default:
5779		/*
5780		 * We got a command we don't support.  This shouldn't
5781		 * happen, commands should be filtered out above us.
5782		 */
5783		ctl_set_invalid_opcode(ctsio);
5784		ctl_done((union ctl_io *)ctsio);
5785
5786		return (CTL_RETVAL_COMPLETE);
5787		break; /* NOTREACHED */
5788	}
5789
5790	/* NDOB and ANCHOR flags can be used only together with UNMAP */
5791	if ((byte2 & SWS_UNMAP) == 0 &&
5792	    (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5793		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5794		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5795		ctl_done((union ctl_io *)ctsio);
5796		return (CTL_RETVAL_COMPLETE);
5797	}
5798
5799	/*
5800	 * The first check is to make sure we're in bounds, the second
5801	 * check is to catch wrap-around problems.  If the lba + num blocks
5802	 * is less than the lba, then we've wrapped around and the block
5803	 * range is invalid anyway.
5804	 */
5805	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5806	 || ((lba + num_blocks) < lba)) {
5807		ctl_set_lba_out_of_range(ctsio);
5808		ctl_done((union ctl_io *)ctsio);
5809		return (CTL_RETVAL_COMPLETE);
5810	}
5811
5812	/* Zero number of blocks means "to the last logical block" */
5813	if (num_blocks == 0) {
5814		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5815			ctl_set_invalid_field(ctsio,
5816					      /*sks_valid*/ 0,
5817					      /*command*/ 1,
5818					      /*field*/ 0,
5819					      /*bit_valid*/ 0,
5820					      /*bit*/ 0);
5821			ctl_done((union ctl_io *)ctsio);
5822			return (CTL_RETVAL_COMPLETE);
5823		}
5824		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5825	}
5826
5827	len = lun->be_lun->blocksize;
5828
5829	/*
5830	 * If we've got a kernel request that hasn't been malloced yet,
5831	 * malloc it and tell the caller the data buffer is here.
5832	 */
5833	if ((byte2 & SWS_NDOB) == 0 &&
5834	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5835		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5836		ctsio->kern_data_len = len;
5837		ctsio->kern_total_len = len;
5838		ctsio->kern_data_resid = 0;
5839		ctsio->kern_rel_offset = 0;
5840		ctsio->kern_sg_entries = 0;
5841		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5842		ctsio->be_move_done = ctl_config_move_done;
5843		ctl_datamove((union ctl_io *)ctsio);
5844
5845		return (CTL_RETVAL_COMPLETE);
5846	}
5847
5848	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5849	lbalen->lba = lba;
5850	lbalen->len = num_blocks;
5851	lbalen->flags = byte2;
5852	retval = lun->backend->config_write((union ctl_io *)ctsio);
5853
5854	return (retval);
5855}
5856
5857int
5858ctl_unmap(struct ctl_scsiio *ctsio)
5859{
5860	struct ctl_lun *lun;
5861	struct scsi_unmap *cdb;
5862	struct ctl_ptr_len_flags *ptrlen;
5863	struct scsi_unmap_header *hdr;
5864	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5865	uint64_t lba;
5866	uint32_t num_blocks;
5867	int len, retval;
5868	uint8_t byte2;
5869
5870	retval = CTL_RETVAL_COMPLETE;
5871
5872	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5873
5874	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5875	cdb = (struct scsi_unmap *)ctsio->cdb;
5876
5877	len = scsi_2btoul(cdb->length);
5878	byte2 = cdb->byte2;
5879
5880	/*
5881	 * If we've got a kernel request that hasn't been malloced yet,
5882	 * malloc it and tell the caller the data buffer is here.
5883	 */
5884	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5885		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5886		ctsio->kern_data_len = len;
5887		ctsio->kern_total_len = len;
5888		ctsio->kern_data_resid = 0;
5889		ctsio->kern_rel_offset = 0;
5890		ctsio->kern_sg_entries = 0;
5891		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5892		ctsio->be_move_done = ctl_config_move_done;
5893		ctl_datamove((union ctl_io *)ctsio);
5894
5895		return (CTL_RETVAL_COMPLETE);
5896	}
5897
5898	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5899	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5900	if (len < sizeof (*hdr) ||
5901	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5902	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5903	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5904		ctl_set_invalid_field(ctsio,
5905				      /*sks_valid*/ 0,
5906				      /*command*/ 0,
5907				      /*field*/ 0,
5908				      /*bit_valid*/ 0,
5909				      /*bit*/ 0);
5910		goto done;
5911	}
5912	len = scsi_2btoul(hdr->desc_length);
5913	buf = (struct scsi_unmap_desc *)(hdr + 1);
5914	end = buf + len / sizeof(*buf);
5915
5916	endnz = buf;
5917	for (range = buf; range < end; range++) {
5918		lba = scsi_8btou64(range->lba);
5919		num_blocks = scsi_4btoul(range->length);
5920		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5921		 || ((lba + num_blocks) < lba)) {
5922			ctl_set_lba_out_of_range(ctsio);
5923			ctl_done((union ctl_io *)ctsio);
5924			return (CTL_RETVAL_COMPLETE);
5925		}
5926		if (num_blocks != 0)
5927			endnz = range + 1;
5928	}
5929
5930	/*
5931	 * Block backend can not handle zero last range.
5932	 * Filter it out and return if there is nothing left.
5933	 */
5934	len = (uint8_t *)endnz - (uint8_t *)buf;
5935	if (len == 0) {
5936		ctl_set_success(ctsio);
5937		goto done;
5938	}
5939
5940	mtx_lock(&lun->lun_lock);
5941	ptrlen = (struct ctl_ptr_len_flags *)
5942	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5943	ptrlen->ptr = (void *)buf;
5944	ptrlen->len = len;
5945	ptrlen->flags = byte2;
5946	ctl_check_blocked(lun);
5947	mtx_unlock(&lun->lun_lock);
5948
5949	retval = lun->backend->config_write((union ctl_io *)ctsio);
5950	return (retval);
5951
5952done:
5953	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5954		free(ctsio->kern_data_ptr, M_CTL);
5955		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5956	}
5957	ctl_done((union ctl_io *)ctsio);
5958	return (CTL_RETVAL_COMPLETE);
5959}
5960
5961/*
5962 * Note that this function currently doesn't actually do anything inside
5963 * CTL to enforce things if the DQue bit is turned on.
5964 *
5965 * Also note that this function can't be used in the default case, because
5966 * the DQue bit isn't set in the changeable mask for the control mode page
5967 * anyway.  This is just here as an example for how to implement a page
5968 * handler, and a placeholder in case we want to allow the user to turn
5969 * tagged queueing on and off.
5970 *
5971 * The D_SENSE bit handling is functional, however, and will turn
5972 * descriptor sense on and off for a given LUN.
5973 */
5974int
5975ctl_control_page_handler(struct ctl_scsiio *ctsio,
5976			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5977{
5978	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5979	struct ctl_lun *lun;
5980	struct ctl_softc *softc;
5981	int set_ua;
5982	uint32_t initidx;
5983
5984	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5985	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5986	set_ua = 0;
5987
5988	user_cp = (struct scsi_control_page *)page_ptr;
5989	current_cp = (struct scsi_control_page *)
5990		(page_index->page_data + (page_index->page_len *
5991		CTL_PAGE_CURRENT));
5992	saved_cp = (struct scsi_control_page *)
5993		(page_index->page_data + (page_index->page_len *
5994		CTL_PAGE_SAVED));
5995
5996	softc = control_softc;
5997
5998	mtx_lock(&lun->lun_lock);
5999	if (((current_cp->rlec & SCP_DSENSE) == 0)
6000	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6001		/*
6002		 * Descriptor sense is currently turned off and the user
6003		 * wants to turn it on.
6004		 */
6005		current_cp->rlec |= SCP_DSENSE;
6006		saved_cp->rlec |= SCP_DSENSE;
6007		lun->flags |= CTL_LUN_SENSE_DESC;
6008		set_ua = 1;
6009	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6010		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6011		/*
6012		 * Descriptor sense is currently turned on, and the user
6013		 * wants to turn it off.
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	}
6020	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6021	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6022		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6023		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6024		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6025		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6026		set_ua = 1;
6027	}
6028	if ((current_cp->eca_and_aen & SCP_SWP) !=
6029	    (user_cp->eca_and_aen & SCP_SWP)) {
6030		current_cp->eca_and_aen &= ~SCP_SWP;
6031		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6032		saved_cp->eca_and_aen &= ~SCP_SWP;
6033		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6034		set_ua = 1;
6035	}
6036	if (set_ua != 0) {
6037		int i;
6038		/*
6039		 * Let other initiators know that the mode
6040		 * parameters for this LUN have changed.
6041		 */
6042		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6043			if (i == initidx)
6044				continue;
6045
6046			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6047		}
6048	}
6049	mtx_unlock(&lun->lun_lock);
6050
6051	return (0);
6052}
6053
6054int
6055ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6056		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6057{
6058	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6059	struct ctl_lun *lun;
6060	int set_ua;
6061	uint32_t initidx;
6062
6063	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6064	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6065	set_ua = 0;
6066
6067	user_cp = (struct scsi_caching_page *)page_ptr;
6068	current_cp = (struct scsi_caching_page *)
6069		(page_index->page_data + (page_index->page_len *
6070		CTL_PAGE_CURRENT));
6071	saved_cp = (struct scsi_caching_page *)
6072		(page_index->page_data + (page_index->page_len *
6073		CTL_PAGE_SAVED));
6074
6075	mtx_lock(&lun->lun_lock);
6076	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6077	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6078		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6079		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6080		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6081		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6082		set_ua = 1;
6083	}
6084	if (set_ua != 0) {
6085		int i;
6086		/*
6087		 * Let other initiators know that the mode
6088		 * parameters for this LUN have changed.
6089		 */
6090		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6091			if (i == initidx)
6092				continue;
6093
6094			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6095		}
6096	}
6097	mtx_unlock(&lun->lun_lock);
6098
6099	return (0);
6100}
6101
6102int
6103ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6104				struct ctl_page_index *page_index,
6105				uint8_t *page_ptr)
6106{
6107	uint8_t *c;
6108	int i;
6109
6110	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6111	ctl_time_io_secs =
6112		(c[0] << 8) |
6113		(c[1] << 0) |
6114		0;
6115	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6116	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6117	printf("page data:");
6118	for (i=0; i<8; i++)
6119		printf(" %.2x",page_ptr[i]);
6120	printf("\n");
6121	return (0);
6122}
6123
6124int
6125ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6126			       struct ctl_page_index *page_index,
6127			       int pc)
6128{
6129	struct copan_debugconf_subpage *page;
6130
6131	page = (struct copan_debugconf_subpage *)page_index->page_data +
6132		(page_index->page_len * pc);
6133
6134	switch (pc) {
6135	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6136	case SMS_PAGE_CTRL_DEFAULT >> 6:
6137	case SMS_PAGE_CTRL_SAVED >> 6:
6138		/*
6139		 * We don't update the changable or default bits for this page.
6140		 */
6141		break;
6142	case SMS_PAGE_CTRL_CURRENT >> 6:
6143		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6144		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6145		break;
6146	default:
6147#ifdef NEEDTOPORT
6148		EPRINT(0, "Invalid PC %d!!", pc);
6149#endif /* NEEDTOPORT */
6150		break;
6151	}
6152	return (0);
6153}
6154
6155
6156static int
6157ctl_do_mode_select(union ctl_io *io)
6158{
6159	struct scsi_mode_page_header *page_header;
6160	struct ctl_page_index *page_index;
6161	struct ctl_scsiio *ctsio;
6162	int control_dev, page_len;
6163	int page_len_offset, page_len_size;
6164	union ctl_modepage_info *modepage_info;
6165	struct ctl_lun *lun;
6166	int *len_left, *len_used;
6167	int retval, i;
6168
6169	ctsio = &io->scsiio;
6170	page_index = NULL;
6171	page_len = 0;
6172	retval = CTL_RETVAL_COMPLETE;
6173
6174	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6175
6176	if (lun->be_lun->lun_type != T_DIRECT)
6177		control_dev = 1;
6178	else
6179		control_dev = 0;
6180
6181	modepage_info = (union ctl_modepage_info *)
6182		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6183	len_left = &modepage_info->header.len_left;
6184	len_used = &modepage_info->header.len_used;
6185
6186do_next_page:
6187
6188	page_header = (struct scsi_mode_page_header *)
6189		(ctsio->kern_data_ptr + *len_used);
6190
6191	if (*len_left == 0) {
6192		free(ctsio->kern_data_ptr, M_CTL);
6193		ctl_set_success(ctsio);
6194		ctl_done((union ctl_io *)ctsio);
6195		return (CTL_RETVAL_COMPLETE);
6196	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6197
6198		free(ctsio->kern_data_ptr, M_CTL);
6199		ctl_set_param_len_error(ctsio);
6200		ctl_done((union ctl_io *)ctsio);
6201		return (CTL_RETVAL_COMPLETE);
6202
6203	} else if ((page_header->page_code & SMPH_SPF)
6204		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6205
6206		free(ctsio->kern_data_ptr, M_CTL);
6207		ctl_set_param_len_error(ctsio);
6208		ctl_done((union ctl_io *)ctsio);
6209		return (CTL_RETVAL_COMPLETE);
6210	}
6211
6212
6213	/*
6214	 * XXX KDM should we do something with the block descriptor?
6215	 */
6216	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6217
6218		if ((control_dev != 0)
6219		 && (lun->mode_pages.index[i].page_flags &
6220		     CTL_PAGE_FLAG_DISK_ONLY))
6221			continue;
6222
6223		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6224		    (page_header->page_code & SMPH_PC_MASK))
6225			continue;
6226
6227		/*
6228		 * If neither page has a subpage code, then we've got a
6229		 * match.
6230		 */
6231		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6232		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6233			page_index = &lun->mode_pages.index[i];
6234			page_len = page_header->page_length;
6235			break;
6236		}
6237
6238		/*
6239		 * If both pages have subpages, then the subpage numbers
6240		 * have to match.
6241		 */
6242		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6243		  && (page_header->page_code & SMPH_SPF)) {
6244			struct scsi_mode_page_header_sp *sph;
6245
6246			sph = (struct scsi_mode_page_header_sp *)page_header;
6247
6248			if (lun->mode_pages.index[i].subpage ==
6249			    sph->subpage) {
6250				page_index = &lun->mode_pages.index[i];
6251				page_len = scsi_2btoul(sph->page_length);
6252				break;
6253			}
6254		}
6255	}
6256
6257	/*
6258	 * If we couldn't find the page, or if we don't have a mode select
6259	 * handler for it, send back an error to the user.
6260	 */
6261	if ((page_index == NULL)
6262	 || (page_index->select_handler == NULL)) {
6263		ctl_set_invalid_field(ctsio,
6264				      /*sks_valid*/ 1,
6265				      /*command*/ 0,
6266				      /*field*/ *len_used,
6267				      /*bit_valid*/ 0,
6268				      /*bit*/ 0);
6269		free(ctsio->kern_data_ptr, M_CTL);
6270		ctl_done((union ctl_io *)ctsio);
6271		return (CTL_RETVAL_COMPLETE);
6272	}
6273
6274	if (page_index->page_code & SMPH_SPF) {
6275		page_len_offset = 2;
6276		page_len_size = 2;
6277	} else {
6278		page_len_size = 1;
6279		page_len_offset = 1;
6280	}
6281
6282	/*
6283	 * If the length the initiator gives us isn't the one we specify in
6284	 * the mode page header, or if they didn't specify enough data in
6285	 * the CDB to avoid truncating this page, kick out the request.
6286	 */
6287	if ((page_len != (page_index->page_len - page_len_offset -
6288			  page_len_size))
6289	 || (*len_left < page_index->page_len)) {
6290
6291
6292		ctl_set_invalid_field(ctsio,
6293				      /*sks_valid*/ 1,
6294				      /*command*/ 0,
6295				      /*field*/ *len_used + page_len_offset,
6296				      /*bit_valid*/ 0,
6297				      /*bit*/ 0);
6298		free(ctsio->kern_data_ptr, M_CTL);
6299		ctl_done((union ctl_io *)ctsio);
6300		return (CTL_RETVAL_COMPLETE);
6301	}
6302
6303	/*
6304	 * Run through the mode page, checking to make sure that the bits
6305	 * the user changed are actually legal for him to change.
6306	 */
6307	for (i = 0; i < page_index->page_len; i++) {
6308		uint8_t *user_byte, *change_mask, *current_byte;
6309		int bad_bit;
6310		int j;
6311
6312		user_byte = (uint8_t *)page_header + i;
6313		change_mask = page_index->page_data +
6314			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6315		current_byte = page_index->page_data +
6316			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6317
6318		/*
6319		 * Check to see whether the user set any bits in this byte
6320		 * that he is not allowed to set.
6321		 */
6322		if ((*user_byte & ~(*change_mask)) ==
6323		    (*current_byte & ~(*change_mask)))
6324			continue;
6325
6326		/*
6327		 * Go through bit by bit to determine which one is illegal.
6328		 */
6329		bad_bit = 0;
6330		for (j = 7; j >= 0; j--) {
6331			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6332			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6333				bad_bit = i;
6334				break;
6335			}
6336		}
6337		ctl_set_invalid_field(ctsio,
6338				      /*sks_valid*/ 1,
6339				      /*command*/ 0,
6340				      /*field*/ *len_used + i,
6341				      /*bit_valid*/ 1,
6342				      /*bit*/ bad_bit);
6343		free(ctsio->kern_data_ptr, M_CTL);
6344		ctl_done((union ctl_io *)ctsio);
6345		return (CTL_RETVAL_COMPLETE);
6346	}
6347
6348	/*
6349	 * Decrement these before we call the page handler, since we may
6350	 * end up getting called back one way or another before the handler
6351	 * returns to this context.
6352	 */
6353	*len_left -= page_index->page_len;
6354	*len_used += page_index->page_len;
6355
6356	retval = page_index->select_handler(ctsio, page_index,
6357					    (uint8_t *)page_header);
6358
6359	/*
6360	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6361	 * wait until this queued command completes to finish processing
6362	 * the mode page.  If it returns anything other than
6363	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6364	 * already set the sense information, freed the data pointer, and
6365	 * completed the io for us.
6366	 */
6367	if (retval != CTL_RETVAL_COMPLETE)
6368		goto bailout_no_done;
6369
6370	/*
6371	 * If the initiator sent us more than one page, parse the next one.
6372	 */
6373	if (*len_left > 0)
6374		goto do_next_page;
6375
6376	ctl_set_success(ctsio);
6377	free(ctsio->kern_data_ptr, M_CTL);
6378	ctl_done((union ctl_io *)ctsio);
6379
6380bailout_no_done:
6381
6382	return (CTL_RETVAL_COMPLETE);
6383
6384}
6385
6386int
6387ctl_mode_select(struct ctl_scsiio *ctsio)
6388{
6389	int param_len, pf, sp;
6390	int header_size, bd_len;
6391	int len_left, len_used;
6392	struct ctl_page_index *page_index;
6393	struct ctl_lun *lun;
6394	int control_dev, page_len;
6395	union ctl_modepage_info *modepage_info;
6396	int retval;
6397
6398	pf = 0;
6399	sp = 0;
6400	page_len = 0;
6401	len_used = 0;
6402	len_left = 0;
6403	retval = 0;
6404	bd_len = 0;
6405	page_index = NULL;
6406
6407	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6408
6409	if (lun->be_lun->lun_type != T_DIRECT)
6410		control_dev = 1;
6411	else
6412		control_dev = 0;
6413
6414	switch (ctsio->cdb[0]) {
6415	case MODE_SELECT_6: {
6416		struct scsi_mode_select_6 *cdb;
6417
6418		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6419
6420		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6421		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6422
6423		param_len = cdb->length;
6424		header_size = sizeof(struct scsi_mode_header_6);
6425		break;
6426	}
6427	case MODE_SELECT_10: {
6428		struct scsi_mode_select_10 *cdb;
6429
6430		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6431
6432		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6433		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6434
6435		param_len = scsi_2btoul(cdb->length);
6436		header_size = sizeof(struct scsi_mode_header_10);
6437		break;
6438	}
6439	default:
6440		ctl_set_invalid_opcode(ctsio);
6441		ctl_done((union ctl_io *)ctsio);
6442		return (CTL_RETVAL_COMPLETE);
6443		break; /* NOTREACHED */
6444	}
6445
6446	/*
6447	 * From SPC-3:
6448	 * "A parameter list length of zero indicates that the Data-Out Buffer
6449	 * shall be empty. This condition shall not be considered as an error."
6450	 */
6451	if (param_len == 0) {
6452		ctl_set_success(ctsio);
6453		ctl_done((union ctl_io *)ctsio);
6454		return (CTL_RETVAL_COMPLETE);
6455	}
6456
6457	/*
6458	 * Since we'll hit this the first time through, prior to
6459	 * allocation, we don't need to free a data buffer here.
6460	 */
6461	if (param_len < header_size) {
6462		ctl_set_param_len_error(ctsio);
6463		ctl_done((union ctl_io *)ctsio);
6464		return (CTL_RETVAL_COMPLETE);
6465	}
6466
6467	/*
6468	 * Allocate the data buffer and grab the user's data.  In theory,
6469	 * we shouldn't have to sanity check the parameter list length here
6470	 * because the maximum size is 64K.  We should be able to malloc
6471	 * that much without too many problems.
6472	 */
6473	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6474		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6475		ctsio->kern_data_len = param_len;
6476		ctsio->kern_total_len = param_len;
6477		ctsio->kern_data_resid = 0;
6478		ctsio->kern_rel_offset = 0;
6479		ctsio->kern_sg_entries = 0;
6480		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6481		ctsio->be_move_done = ctl_config_move_done;
6482		ctl_datamove((union ctl_io *)ctsio);
6483
6484		return (CTL_RETVAL_COMPLETE);
6485	}
6486
6487	switch (ctsio->cdb[0]) {
6488	case MODE_SELECT_6: {
6489		struct scsi_mode_header_6 *mh6;
6490
6491		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6492		bd_len = mh6->blk_desc_len;
6493		break;
6494	}
6495	case MODE_SELECT_10: {
6496		struct scsi_mode_header_10 *mh10;
6497
6498		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6499		bd_len = scsi_2btoul(mh10->blk_desc_len);
6500		break;
6501	}
6502	default:
6503		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6504		break;
6505	}
6506
6507	if (param_len < (header_size + bd_len)) {
6508		free(ctsio->kern_data_ptr, M_CTL);
6509		ctl_set_param_len_error(ctsio);
6510		ctl_done((union ctl_io *)ctsio);
6511		return (CTL_RETVAL_COMPLETE);
6512	}
6513
6514	/*
6515	 * Set the IO_CONT flag, so that if this I/O gets passed to
6516	 * ctl_config_write_done(), it'll get passed back to
6517	 * ctl_do_mode_select() for further processing, or completion if
6518	 * we're all done.
6519	 */
6520	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6521	ctsio->io_cont = ctl_do_mode_select;
6522
6523	modepage_info = (union ctl_modepage_info *)
6524		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6525
6526	memset(modepage_info, 0, sizeof(*modepage_info));
6527
6528	len_left = param_len - header_size - bd_len;
6529	len_used = header_size + bd_len;
6530
6531	modepage_info->header.len_left = len_left;
6532	modepage_info->header.len_used = len_used;
6533
6534	return (ctl_do_mode_select((union ctl_io *)ctsio));
6535}
6536
6537int
6538ctl_mode_sense(struct ctl_scsiio *ctsio)
6539{
6540	struct ctl_lun *lun;
6541	int pc, page_code, dbd, llba, subpage;
6542	int alloc_len, page_len, header_len, total_len;
6543	struct scsi_mode_block_descr *block_desc;
6544	struct ctl_page_index *page_index;
6545	int control_dev;
6546
6547	dbd = 0;
6548	llba = 0;
6549	block_desc = NULL;
6550	page_index = NULL;
6551
6552	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6553
6554	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6555
6556	if (lun->be_lun->lun_type != T_DIRECT)
6557		control_dev = 1;
6558	else
6559		control_dev = 0;
6560
6561	switch (ctsio->cdb[0]) {
6562	case MODE_SENSE_6: {
6563		struct scsi_mode_sense_6 *cdb;
6564
6565		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6566
6567		header_len = sizeof(struct scsi_mode_hdr_6);
6568		if (cdb->byte2 & SMS_DBD)
6569			dbd = 1;
6570		else
6571			header_len += sizeof(struct scsi_mode_block_descr);
6572
6573		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6574		page_code = cdb->page & SMS_PAGE_CODE;
6575		subpage = cdb->subpage;
6576		alloc_len = cdb->length;
6577		break;
6578	}
6579	case MODE_SENSE_10: {
6580		struct scsi_mode_sense_10 *cdb;
6581
6582		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6583
6584		header_len = sizeof(struct scsi_mode_hdr_10);
6585
6586		if (cdb->byte2 & SMS_DBD)
6587			dbd = 1;
6588		else
6589			header_len += sizeof(struct scsi_mode_block_descr);
6590		if (cdb->byte2 & SMS10_LLBAA)
6591			llba = 1;
6592		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6593		page_code = cdb->page & SMS_PAGE_CODE;
6594		subpage = cdb->subpage;
6595		alloc_len = scsi_2btoul(cdb->length);
6596		break;
6597	}
6598	default:
6599		ctl_set_invalid_opcode(ctsio);
6600		ctl_done((union ctl_io *)ctsio);
6601		return (CTL_RETVAL_COMPLETE);
6602		break; /* NOTREACHED */
6603	}
6604
6605	/*
6606	 * We have to make a first pass through to calculate the size of
6607	 * the pages that match the user's query.  Then we allocate enough
6608	 * memory to hold it, and actually copy the data into the buffer.
6609	 */
6610	switch (page_code) {
6611	case SMS_ALL_PAGES_PAGE: {
6612		int i;
6613
6614		page_len = 0;
6615
6616		/*
6617		 * At the moment, values other than 0 and 0xff here are
6618		 * reserved according to SPC-3.
6619		 */
6620		if ((subpage != SMS_SUBPAGE_PAGE_0)
6621		 && (subpage != SMS_SUBPAGE_ALL)) {
6622			ctl_set_invalid_field(ctsio,
6623					      /*sks_valid*/ 1,
6624					      /*command*/ 1,
6625					      /*field*/ 3,
6626					      /*bit_valid*/ 0,
6627					      /*bit*/ 0);
6628			ctl_done((union ctl_io *)ctsio);
6629			return (CTL_RETVAL_COMPLETE);
6630		}
6631
6632		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6633			if ((control_dev != 0)
6634			 && (lun->mode_pages.index[i].page_flags &
6635			     CTL_PAGE_FLAG_DISK_ONLY))
6636				continue;
6637
6638			/*
6639			 * We don't use this subpage if the user didn't
6640			 * request all subpages.
6641			 */
6642			if ((lun->mode_pages.index[i].subpage != 0)
6643			 && (subpage == SMS_SUBPAGE_PAGE_0))
6644				continue;
6645
6646#if 0
6647			printf("found page %#x len %d\n",
6648			       lun->mode_pages.index[i].page_code &
6649			       SMPH_PC_MASK,
6650			       lun->mode_pages.index[i].page_len);
6651#endif
6652			page_len += lun->mode_pages.index[i].page_len;
6653		}
6654		break;
6655	}
6656	default: {
6657		int i;
6658
6659		page_len = 0;
6660
6661		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6662			/* Look for the right page code */
6663			if ((lun->mode_pages.index[i].page_code &
6664			     SMPH_PC_MASK) != page_code)
6665				continue;
6666
6667			/* Look for the right subpage or the subpage wildcard*/
6668			if ((lun->mode_pages.index[i].subpage != subpage)
6669			 && (subpage != SMS_SUBPAGE_ALL))
6670				continue;
6671
6672			/* Make sure the page is supported for this dev type */
6673			if ((control_dev != 0)
6674			 && (lun->mode_pages.index[i].page_flags &
6675			     CTL_PAGE_FLAG_DISK_ONLY))
6676				continue;
6677
6678#if 0
6679			printf("found page %#x len %d\n",
6680			       lun->mode_pages.index[i].page_code &
6681			       SMPH_PC_MASK,
6682			       lun->mode_pages.index[i].page_len);
6683#endif
6684
6685			page_len += lun->mode_pages.index[i].page_len;
6686		}
6687
6688		if (page_len == 0) {
6689			ctl_set_invalid_field(ctsio,
6690					      /*sks_valid*/ 1,
6691					      /*command*/ 1,
6692					      /*field*/ 2,
6693					      /*bit_valid*/ 1,
6694					      /*bit*/ 5);
6695			ctl_done((union ctl_io *)ctsio);
6696			return (CTL_RETVAL_COMPLETE);
6697		}
6698		break;
6699	}
6700	}
6701
6702	total_len = header_len + page_len;
6703#if 0
6704	printf("header_len = %d, page_len = %d, total_len = %d\n",
6705	       header_len, page_len, total_len);
6706#endif
6707
6708	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6709	ctsio->kern_sg_entries = 0;
6710	ctsio->kern_data_resid = 0;
6711	ctsio->kern_rel_offset = 0;
6712	if (total_len < alloc_len) {
6713		ctsio->residual = alloc_len - total_len;
6714		ctsio->kern_data_len = total_len;
6715		ctsio->kern_total_len = total_len;
6716	} else {
6717		ctsio->residual = 0;
6718		ctsio->kern_data_len = alloc_len;
6719		ctsio->kern_total_len = alloc_len;
6720	}
6721
6722	switch (ctsio->cdb[0]) {
6723	case MODE_SENSE_6: {
6724		struct scsi_mode_hdr_6 *header;
6725
6726		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6727
6728		header->datalen = ctl_min(total_len - 1, 254);
6729		if (control_dev == 0) {
6730			header->dev_specific = 0x10; /* DPOFUA */
6731			if ((lun->flags & CTL_LUN_READONLY) ||
6732			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6733			    .eca_and_aen & SCP_SWP) != 0)
6734				    header->dev_specific |= 0x80; /* WP */
6735		}
6736		if (dbd)
6737			header->block_descr_len = 0;
6738		else
6739			header->block_descr_len =
6740				sizeof(struct scsi_mode_block_descr);
6741		block_desc = (struct scsi_mode_block_descr *)&header[1];
6742		break;
6743	}
6744	case MODE_SENSE_10: {
6745		struct scsi_mode_hdr_10 *header;
6746		int datalen;
6747
6748		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6749
6750		datalen = ctl_min(total_len - 2, 65533);
6751		scsi_ulto2b(datalen, header->datalen);
6752		if (control_dev == 0) {
6753			header->dev_specific = 0x10; /* DPOFUA */
6754			if ((lun->flags & CTL_LUN_READONLY) ||
6755			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6756			    .eca_and_aen & SCP_SWP) != 0)
6757				    header->dev_specific |= 0x80; /* WP */
6758		}
6759		if (dbd)
6760			scsi_ulto2b(0, header->block_descr_len);
6761		else
6762			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6763				    header->block_descr_len);
6764		block_desc = (struct scsi_mode_block_descr *)&header[1];
6765		break;
6766	}
6767	default:
6768		panic("invalid CDB type %#x", ctsio->cdb[0]);
6769		break; /* NOTREACHED */
6770	}
6771
6772	/*
6773	 * If we've got a disk, use its blocksize in the block
6774	 * descriptor.  Otherwise, just set it to 0.
6775	 */
6776	if (dbd == 0) {
6777		if (control_dev == 0)
6778			scsi_ulto3b(lun->be_lun->blocksize,
6779				    block_desc->block_len);
6780		else
6781			scsi_ulto3b(0, block_desc->block_len);
6782	}
6783
6784	switch (page_code) {
6785	case SMS_ALL_PAGES_PAGE: {
6786		int i, data_used;
6787
6788		data_used = header_len;
6789		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6790			struct ctl_page_index *page_index;
6791
6792			page_index = &lun->mode_pages.index[i];
6793
6794			if ((control_dev != 0)
6795			 && (page_index->page_flags &
6796			    CTL_PAGE_FLAG_DISK_ONLY))
6797				continue;
6798
6799			/*
6800			 * We don't use this subpage if the user didn't
6801			 * request all subpages.  We already checked (above)
6802			 * to make sure the user only specified a subpage
6803			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6804			 */
6805			if ((page_index->subpage != 0)
6806			 && (subpage == SMS_SUBPAGE_PAGE_0))
6807				continue;
6808
6809			/*
6810			 * Call the handler, if it exists, to update the
6811			 * page to the latest values.
6812			 */
6813			if (page_index->sense_handler != NULL)
6814				page_index->sense_handler(ctsio, page_index,pc);
6815
6816			memcpy(ctsio->kern_data_ptr + data_used,
6817			       page_index->page_data +
6818			       (page_index->page_len * pc),
6819			       page_index->page_len);
6820			data_used += page_index->page_len;
6821		}
6822		break;
6823	}
6824	default: {
6825		int i, data_used;
6826
6827		data_used = header_len;
6828
6829		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6830			struct ctl_page_index *page_index;
6831
6832			page_index = &lun->mode_pages.index[i];
6833
6834			/* Look for the right page code */
6835			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6836				continue;
6837
6838			/* Look for the right subpage or the subpage wildcard*/
6839			if ((page_index->subpage != subpage)
6840			 && (subpage != SMS_SUBPAGE_ALL))
6841				continue;
6842
6843			/* Make sure the page is supported for this dev type */
6844			if ((control_dev != 0)
6845			 && (page_index->page_flags &
6846			     CTL_PAGE_FLAG_DISK_ONLY))
6847				continue;
6848
6849			/*
6850			 * Call the handler, if it exists, to update the
6851			 * page to the latest values.
6852			 */
6853			if (page_index->sense_handler != NULL)
6854				page_index->sense_handler(ctsio, page_index,pc);
6855
6856			memcpy(ctsio->kern_data_ptr + data_used,
6857			       page_index->page_data +
6858			       (page_index->page_len * pc),
6859			       page_index->page_len);
6860			data_used += page_index->page_len;
6861		}
6862		break;
6863	}
6864	}
6865
6866	ctl_set_success(ctsio);
6867	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6868	ctsio->be_move_done = ctl_config_move_done;
6869	ctl_datamove((union ctl_io *)ctsio);
6870	return (CTL_RETVAL_COMPLETE);
6871}
6872
6873int
6874ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6875			       struct ctl_page_index *page_index,
6876			       int pc)
6877{
6878	struct ctl_lun *lun;
6879	struct scsi_log_param_header *phdr;
6880	uint8_t *data;
6881	uint64_t val;
6882
6883	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6884	data = page_index->page_data;
6885
6886	if (lun->backend->lun_attr != NULL &&
6887	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6888	     != UINT64_MAX) {
6889		phdr = (struct scsi_log_param_header *)data;
6890		scsi_ulto2b(0x0001, phdr->param_code);
6891		phdr->param_control = SLP_LBIN | SLP_LP;
6892		phdr->param_len = 8;
6893		data = (uint8_t *)(phdr + 1);
6894		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6895		data[4] = 0x02; /* per-pool */
6896		data += phdr->param_len;
6897	}
6898
6899	if (lun->backend->lun_attr != NULL &&
6900	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6901	     != UINT64_MAX) {
6902		phdr = (struct scsi_log_param_header *)data;
6903		scsi_ulto2b(0x0002, phdr->param_code);
6904		phdr->param_control = SLP_LBIN | SLP_LP;
6905		phdr->param_len = 8;
6906		data = (uint8_t *)(phdr + 1);
6907		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6908		data[4] = 0x01; /* per-LUN */
6909		data += phdr->param_len;
6910	}
6911
6912	if (lun->backend->lun_attr != NULL &&
6913	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6914	     != UINT64_MAX) {
6915		phdr = (struct scsi_log_param_header *)data;
6916		scsi_ulto2b(0x00f1, phdr->param_code);
6917		phdr->param_control = SLP_LBIN | SLP_LP;
6918		phdr->param_len = 8;
6919		data = (uint8_t *)(phdr + 1);
6920		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6921		data[4] = 0x02; /* per-pool */
6922		data += phdr->param_len;
6923	}
6924
6925	if (lun->backend->lun_attr != NULL &&
6926	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6927	     != UINT64_MAX) {
6928		phdr = (struct scsi_log_param_header *)data;
6929		scsi_ulto2b(0x00f2, phdr->param_code);
6930		phdr->param_control = SLP_LBIN | SLP_LP;
6931		phdr->param_len = 8;
6932		data = (uint8_t *)(phdr + 1);
6933		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6934		data[4] = 0x02; /* per-pool */
6935		data += phdr->param_len;
6936	}
6937
6938	page_index->page_len = data - page_index->page_data;
6939	return (0);
6940}
6941
6942int
6943ctl_log_sense(struct ctl_scsiio *ctsio)
6944{
6945	struct ctl_lun *lun;
6946	int i, pc, page_code, subpage;
6947	int alloc_len, total_len;
6948	struct ctl_page_index *page_index;
6949	struct scsi_log_sense *cdb;
6950	struct scsi_log_header *header;
6951
6952	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6953
6954	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6955	cdb = (struct scsi_log_sense *)ctsio->cdb;
6956	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6957	page_code = cdb->page & SLS_PAGE_CODE;
6958	subpage = cdb->subpage;
6959	alloc_len = scsi_2btoul(cdb->length);
6960
6961	page_index = NULL;
6962	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6963		page_index = &lun->log_pages.index[i];
6964
6965		/* Look for the right page code */
6966		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6967			continue;
6968
6969		/* Look for the right subpage or the subpage wildcard*/
6970		if (page_index->subpage != subpage)
6971			continue;
6972
6973		break;
6974	}
6975	if (i >= CTL_NUM_LOG_PAGES) {
6976		ctl_set_invalid_field(ctsio,
6977				      /*sks_valid*/ 1,
6978				      /*command*/ 1,
6979				      /*field*/ 2,
6980				      /*bit_valid*/ 0,
6981				      /*bit*/ 0);
6982		ctl_done((union ctl_io *)ctsio);
6983		return (CTL_RETVAL_COMPLETE);
6984	}
6985
6986	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6987
6988	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6989	ctsio->kern_sg_entries = 0;
6990	ctsio->kern_data_resid = 0;
6991	ctsio->kern_rel_offset = 0;
6992	if (total_len < alloc_len) {
6993		ctsio->residual = alloc_len - total_len;
6994		ctsio->kern_data_len = total_len;
6995		ctsio->kern_total_len = total_len;
6996	} else {
6997		ctsio->residual = 0;
6998		ctsio->kern_data_len = alloc_len;
6999		ctsio->kern_total_len = alloc_len;
7000	}
7001
7002	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
7003	header->page = page_index->page_code;
7004	if (page_index->subpage) {
7005		header->page |= SL_SPF;
7006		header->subpage = page_index->subpage;
7007	}
7008	scsi_ulto2b(page_index->page_len, header->datalen);
7009
7010	/*
7011	 * Call the handler, if it exists, to update the
7012	 * page to the latest values.
7013	 */
7014	if (page_index->sense_handler != NULL)
7015		page_index->sense_handler(ctsio, page_index, pc);
7016
7017	memcpy(header + 1, page_index->page_data, page_index->page_len);
7018
7019	ctl_set_success(ctsio);
7020	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7021	ctsio->be_move_done = ctl_config_move_done;
7022	ctl_datamove((union ctl_io *)ctsio);
7023	return (CTL_RETVAL_COMPLETE);
7024}
7025
7026int
7027ctl_read_capacity(struct ctl_scsiio *ctsio)
7028{
7029	struct scsi_read_capacity *cdb;
7030	struct scsi_read_capacity_data *data;
7031	struct ctl_lun *lun;
7032	uint32_t lba;
7033
7034	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7035
7036	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7037
7038	lba = scsi_4btoul(cdb->addr);
7039	if (((cdb->pmi & SRC_PMI) == 0)
7040	 && (lba != 0)) {
7041		ctl_set_invalid_field(/*ctsio*/ ctsio,
7042				      /*sks_valid*/ 1,
7043				      /*command*/ 1,
7044				      /*field*/ 2,
7045				      /*bit_valid*/ 0,
7046				      /*bit*/ 0);
7047		ctl_done((union ctl_io *)ctsio);
7048		return (CTL_RETVAL_COMPLETE);
7049	}
7050
7051	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7052
7053	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7054	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7055	ctsio->residual = 0;
7056	ctsio->kern_data_len = sizeof(*data);
7057	ctsio->kern_total_len = sizeof(*data);
7058	ctsio->kern_data_resid = 0;
7059	ctsio->kern_rel_offset = 0;
7060	ctsio->kern_sg_entries = 0;
7061
7062	/*
7063	 * If the maximum LBA is greater than 0xfffffffe, the user must
7064	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7065	 * serivce action set.
7066	 */
7067	if (lun->be_lun->maxlba > 0xfffffffe)
7068		scsi_ulto4b(0xffffffff, data->addr);
7069	else
7070		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7071
7072	/*
7073	 * XXX KDM this may not be 512 bytes...
7074	 */
7075	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7076
7077	ctl_set_success(ctsio);
7078	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7079	ctsio->be_move_done = ctl_config_move_done;
7080	ctl_datamove((union ctl_io *)ctsio);
7081	return (CTL_RETVAL_COMPLETE);
7082}
7083
7084int
7085ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7086{
7087	struct scsi_read_capacity_16 *cdb;
7088	struct scsi_read_capacity_data_long *data;
7089	struct ctl_lun *lun;
7090	uint64_t lba;
7091	uint32_t alloc_len;
7092
7093	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7094
7095	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7096
7097	alloc_len = scsi_4btoul(cdb->alloc_len);
7098	lba = scsi_8btou64(cdb->addr);
7099
7100	if ((cdb->reladr & SRC16_PMI)
7101	 && (lba != 0)) {
7102		ctl_set_invalid_field(/*ctsio*/ ctsio,
7103				      /*sks_valid*/ 1,
7104				      /*command*/ 1,
7105				      /*field*/ 2,
7106				      /*bit_valid*/ 0,
7107				      /*bit*/ 0);
7108		ctl_done((union ctl_io *)ctsio);
7109		return (CTL_RETVAL_COMPLETE);
7110	}
7111
7112	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7113
7114	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7115	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7116
7117	if (sizeof(*data) < alloc_len) {
7118		ctsio->residual = alloc_len - sizeof(*data);
7119		ctsio->kern_data_len = sizeof(*data);
7120		ctsio->kern_total_len = sizeof(*data);
7121	} else {
7122		ctsio->residual = 0;
7123		ctsio->kern_data_len = alloc_len;
7124		ctsio->kern_total_len = alloc_len;
7125	}
7126	ctsio->kern_data_resid = 0;
7127	ctsio->kern_rel_offset = 0;
7128	ctsio->kern_sg_entries = 0;
7129
7130	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7131	/* XXX KDM this may not be 512 bytes... */
7132	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7133	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7134	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7135	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7136		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7137
7138	ctl_set_success(ctsio);
7139	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7140	ctsio->be_move_done = ctl_config_move_done;
7141	ctl_datamove((union ctl_io *)ctsio);
7142	return (CTL_RETVAL_COMPLETE);
7143}
7144
7145int
7146ctl_read_defect(struct ctl_scsiio *ctsio)
7147{
7148	struct scsi_read_defect_data_10 *ccb10;
7149	struct scsi_read_defect_data_12 *ccb12;
7150	struct scsi_read_defect_data_hdr_10 *data10;
7151	struct scsi_read_defect_data_hdr_12 *data12;
7152	uint32_t alloc_len, data_len;
7153	uint8_t format;
7154
7155	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7156
7157	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7158		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7159		format = ccb10->format;
7160		alloc_len = scsi_2btoul(ccb10->alloc_length);
7161		data_len = sizeof(*data10);
7162	} else {
7163		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7164		format = ccb12->format;
7165		alloc_len = scsi_4btoul(ccb12->alloc_length);
7166		data_len = sizeof(*data12);
7167	}
7168	if (alloc_len == 0) {
7169		ctl_set_success(ctsio);
7170		ctl_done((union ctl_io *)ctsio);
7171		return (CTL_RETVAL_COMPLETE);
7172	}
7173
7174	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7175	if (data_len < alloc_len) {
7176		ctsio->residual = alloc_len - data_len;
7177		ctsio->kern_data_len = data_len;
7178		ctsio->kern_total_len = data_len;
7179	} else {
7180		ctsio->residual = 0;
7181		ctsio->kern_data_len = alloc_len;
7182		ctsio->kern_total_len = alloc_len;
7183	}
7184	ctsio->kern_data_resid = 0;
7185	ctsio->kern_rel_offset = 0;
7186	ctsio->kern_sg_entries = 0;
7187
7188	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7189		data10 = (struct scsi_read_defect_data_hdr_10 *)
7190		    ctsio->kern_data_ptr;
7191		data10->format = format;
7192		scsi_ulto2b(0, data10->length);
7193	} else {
7194		data12 = (struct scsi_read_defect_data_hdr_12 *)
7195		    ctsio->kern_data_ptr;
7196		data12->format = format;
7197		scsi_ulto2b(0, data12->generation);
7198		scsi_ulto4b(0, data12->length);
7199	}
7200
7201	ctl_set_success(ctsio);
7202	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7203	ctsio->be_move_done = ctl_config_move_done;
7204	ctl_datamove((union ctl_io *)ctsio);
7205	return (CTL_RETVAL_COMPLETE);
7206}
7207
7208int
7209ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7210{
7211	struct scsi_maintenance_in *cdb;
7212	int retval;
7213	int alloc_len, ext, total_len = 0, g, p, pc, pg, gs, os;
7214	int num_target_port_groups, num_target_ports;
7215	struct ctl_lun *lun;
7216	struct ctl_softc *softc;
7217	struct ctl_port *port;
7218	struct scsi_target_group_data *rtg_ptr;
7219	struct scsi_target_group_data_extended *rtg_ext_ptr;
7220	struct scsi_target_port_group_descriptor *tpg_desc;
7221
7222	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7223
7224	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7225	softc = control_softc;
7226	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7227
7228	retval = CTL_RETVAL_COMPLETE;
7229
7230	switch (cdb->byte2 & STG_PDF_MASK) {
7231	case STG_PDF_LENGTH:
7232		ext = 0;
7233		break;
7234	case STG_PDF_EXTENDED:
7235		ext = 1;
7236		break;
7237	default:
7238		ctl_set_invalid_field(/*ctsio*/ ctsio,
7239				      /*sks_valid*/ 1,
7240				      /*command*/ 1,
7241				      /*field*/ 2,
7242				      /*bit_valid*/ 1,
7243				      /*bit*/ 5);
7244		ctl_done((union ctl_io *)ctsio);
7245		return(retval);
7246	}
7247
7248	if (softc->is_single)
7249		num_target_port_groups = 1;
7250	else
7251		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7252	num_target_ports = 0;
7253	mtx_lock(&softc->ctl_lock);
7254	STAILQ_FOREACH(port, &softc->port_list, links) {
7255		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7256			continue;
7257		if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7258			continue;
7259		num_target_ports++;
7260	}
7261	mtx_unlock(&softc->ctl_lock);
7262
7263	if (ext)
7264		total_len = sizeof(struct scsi_target_group_data_extended);
7265	else
7266		total_len = sizeof(struct scsi_target_group_data);
7267	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7268		num_target_port_groups +
7269	    sizeof(struct scsi_target_port_descriptor) *
7270		num_target_ports * num_target_port_groups;
7271
7272	alloc_len = scsi_4btoul(cdb->length);
7273
7274	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7275
7276	ctsio->kern_sg_entries = 0;
7277
7278	if (total_len < alloc_len) {
7279		ctsio->residual = alloc_len - total_len;
7280		ctsio->kern_data_len = total_len;
7281		ctsio->kern_total_len = total_len;
7282	} else {
7283		ctsio->residual = 0;
7284		ctsio->kern_data_len = alloc_len;
7285		ctsio->kern_total_len = alloc_len;
7286	}
7287	ctsio->kern_data_resid = 0;
7288	ctsio->kern_rel_offset = 0;
7289
7290	if (ext) {
7291		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7292		    ctsio->kern_data_ptr;
7293		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7294		rtg_ext_ptr->format_type = 0x10;
7295		rtg_ext_ptr->implicit_transition_time = 0;
7296		tpg_desc = &rtg_ext_ptr->groups[0];
7297	} else {
7298		rtg_ptr = (struct scsi_target_group_data *)
7299		    ctsio->kern_data_ptr;
7300		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7301		tpg_desc = &rtg_ptr->groups[0];
7302	}
7303
7304	mtx_lock(&softc->ctl_lock);
7305	pg = softc->port_offset / CTL_MAX_PORTS;
7306	if (softc->flags & CTL_FLAG_ACTIVE_SHELF) {
7307		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY) {
7308			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7309			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7310		} else if (lun->flags & CTL_LUN_PRIMARY_SC) {
7311			gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7312			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7313		} else {
7314			gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7315			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7316		}
7317	} else {
7318		gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7319		os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7320	}
7321	for (g = 0; g < num_target_port_groups; g++) {
7322		tpg_desc->pref_state = (g == pg) ? gs : os;
7323		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP;
7324		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7325		tpg_desc->status = TPG_IMPLICIT;
7326		pc = 0;
7327		STAILQ_FOREACH(port, &softc->port_list, links) {
7328			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7329				continue;
7330			if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7331			    CTL_MAX_LUNS)
7332				continue;
7333			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7334			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7335			    relative_target_port_identifier);
7336			pc++;
7337		}
7338		tpg_desc->target_port_count = pc;
7339		tpg_desc = (struct scsi_target_port_group_descriptor *)
7340		    &tpg_desc->descriptors[pc];
7341	}
7342	mtx_unlock(&softc->ctl_lock);
7343
7344	ctl_set_success(ctsio);
7345	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7346	ctsio->be_move_done = ctl_config_move_done;
7347	ctl_datamove((union ctl_io *)ctsio);
7348	return(retval);
7349}
7350
7351int
7352ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7353{
7354	struct ctl_lun *lun;
7355	struct scsi_report_supported_opcodes *cdb;
7356	const struct ctl_cmd_entry *entry, *sentry;
7357	struct scsi_report_supported_opcodes_all *all;
7358	struct scsi_report_supported_opcodes_descr *descr;
7359	struct scsi_report_supported_opcodes_one *one;
7360	int retval;
7361	int alloc_len, total_len;
7362	int opcode, service_action, i, j, num;
7363
7364	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7365
7366	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7367	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7368
7369	retval = CTL_RETVAL_COMPLETE;
7370
7371	opcode = cdb->requested_opcode;
7372	service_action = scsi_2btoul(cdb->requested_service_action);
7373	switch (cdb->options & RSO_OPTIONS_MASK) {
7374	case RSO_OPTIONS_ALL:
7375		num = 0;
7376		for (i = 0; i < 256; i++) {
7377			entry = &ctl_cmd_table[i];
7378			if (entry->flags & CTL_CMD_FLAG_SA5) {
7379				for (j = 0; j < 32; j++) {
7380					sentry = &((const struct ctl_cmd_entry *)
7381					    entry->execute)[j];
7382					if (ctl_cmd_applicable(
7383					    lun->be_lun->lun_type, sentry))
7384						num++;
7385				}
7386			} else {
7387				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7388				    entry))
7389					num++;
7390			}
7391		}
7392		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7393		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7394		break;
7395	case RSO_OPTIONS_OC:
7396		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7397			ctl_set_invalid_field(/*ctsio*/ ctsio,
7398					      /*sks_valid*/ 1,
7399					      /*command*/ 1,
7400					      /*field*/ 2,
7401					      /*bit_valid*/ 1,
7402					      /*bit*/ 2);
7403			ctl_done((union ctl_io *)ctsio);
7404			return (CTL_RETVAL_COMPLETE);
7405		}
7406		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7407		break;
7408	case RSO_OPTIONS_OC_SA:
7409		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7410		    service_action >= 32) {
7411			ctl_set_invalid_field(/*ctsio*/ ctsio,
7412					      /*sks_valid*/ 1,
7413					      /*command*/ 1,
7414					      /*field*/ 2,
7415					      /*bit_valid*/ 1,
7416					      /*bit*/ 2);
7417			ctl_done((union ctl_io *)ctsio);
7418			return (CTL_RETVAL_COMPLETE);
7419		}
7420		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7421		break;
7422	default:
7423		ctl_set_invalid_field(/*ctsio*/ ctsio,
7424				      /*sks_valid*/ 1,
7425				      /*command*/ 1,
7426				      /*field*/ 2,
7427				      /*bit_valid*/ 1,
7428				      /*bit*/ 2);
7429		ctl_done((union ctl_io *)ctsio);
7430		return (CTL_RETVAL_COMPLETE);
7431	}
7432
7433	alloc_len = scsi_4btoul(cdb->length);
7434
7435	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7436
7437	ctsio->kern_sg_entries = 0;
7438
7439	if (total_len < alloc_len) {
7440		ctsio->residual = alloc_len - total_len;
7441		ctsio->kern_data_len = total_len;
7442		ctsio->kern_total_len = total_len;
7443	} else {
7444		ctsio->residual = 0;
7445		ctsio->kern_data_len = alloc_len;
7446		ctsio->kern_total_len = alloc_len;
7447	}
7448	ctsio->kern_data_resid = 0;
7449	ctsio->kern_rel_offset = 0;
7450
7451	switch (cdb->options & RSO_OPTIONS_MASK) {
7452	case RSO_OPTIONS_ALL:
7453		all = (struct scsi_report_supported_opcodes_all *)
7454		    ctsio->kern_data_ptr;
7455		num = 0;
7456		for (i = 0; i < 256; i++) {
7457			entry = &ctl_cmd_table[i];
7458			if (entry->flags & CTL_CMD_FLAG_SA5) {
7459				for (j = 0; j < 32; j++) {
7460					sentry = &((const struct ctl_cmd_entry *)
7461					    entry->execute)[j];
7462					if (!ctl_cmd_applicable(
7463					    lun->be_lun->lun_type, sentry))
7464						continue;
7465					descr = &all->descr[num++];
7466					descr->opcode = i;
7467					scsi_ulto2b(j, descr->service_action);
7468					descr->flags = RSO_SERVACTV;
7469					scsi_ulto2b(sentry->length,
7470					    descr->cdb_length);
7471				}
7472			} else {
7473				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7474				    entry))
7475					continue;
7476				descr = &all->descr[num++];
7477				descr->opcode = i;
7478				scsi_ulto2b(0, descr->service_action);
7479				descr->flags = 0;
7480				scsi_ulto2b(entry->length, descr->cdb_length);
7481			}
7482		}
7483		scsi_ulto4b(
7484		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7485		    all->length);
7486		break;
7487	case RSO_OPTIONS_OC:
7488		one = (struct scsi_report_supported_opcodes_one *)
7489		    ctsio->kern_data_ptr;
7490		entry = &ctl_cmd_table[opcode];
7491		goto fill_one;
7492	case RSO_OPTIONS_OC_SA:
7493		one = (struct scsi_report_supported_opcodes_one *)
7494		    ctsio->kern_data_ptr;
7495		entry = &ctl_cmd_table[opcode];
7496		entry = &((const struct ctl_cmd_entry *)
7497		    entry->execute)[service_action];
7498fill_one:
7499		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7500			one->support = 3;
7501			scsi_ulto2b(entry->length, one->cdb_length);
7502			one->cdb_usage[0] = opcode;
7503			memcpy(&one->cdb_usage[1], entry->usage,
7504			    entry->length - 1);
7505		} else
7506			one->support = 1;
7507		break;
7508	}
7509
7510	ctl_set_success(ctsio);
7511	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7512	ctsio->be_move_done = ctl_config_move_done;
7513	ctl_datamove((union ctl_io *)ctsio);
7514	return(retval);
7515}
7516
7517int
7518ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7519{
7520	struct scsi_report_supported_tmf *cdb;
7521	struct scsi_report_supported_tmf_data *data;
7522	int retval;
7523	int alloc_len, total_len;
7524
7525	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7526
7527	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7528
7529	retval = CTL_RETVAL_COMPLETE;
7530
7531	total_len = sizeof(struct scsi_report_supported_tmf_data);
7532	alloc_len = scsi_4btoul(cdb->length);
7533
7534	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7535
7536	ctsio->kern_sg_entries = 0;
7537
7538	if (total_len < alloc_len) {
7539		ctsio->residual = alloc_len - total_len;
7540		ctsio->kern_data_len = total_len;
7541		ctsio->kern_total_len = total_len;
7542	} else {
7543		ctsio->residual = 0;
7544		ctsio->kern_data_len = alloc_len;
7545		ctsio->kern_total_len = alloc_len;
7546	}
7547	ctsio->kern_data_resid = 0;
7548	ctsio->kern_rel_offset = 0;
7549
7550	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7551	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7552	data->byte2 |= RST_ITNRS;
7553
7554	ctl_set_success(ctsio);
7555	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7556	ctsio->be_move_done = ctl_config_move_done;
7557	ctl_datamove((union ctl_io *)ctsio);
7558	return (retval);
7559}
7560
7561int
7562ctl_report_timestamp(struct ctl_scsiio *ctsio)
7563{
7564	struct scsi_report_timestamp *cdb;
7565	struct scsi_report_timestamp_data *data;
7566	struct timeval tv;
7567	int64_t timestamp;
7568	int retval;
7569	int alloc_len, total_len;
7570
7571	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7572
7573	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7574
7575	retval = CTL_RETVAL_COMPLETE;
7576
7577	total_len = sizeof(struct scsi_report_timestamp_data);
7578	alloc_len = scsi_4btoul(cdb->length);
7579
7580	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7581
7582	ctsio->kern_sg_entries = 0;
7583
7584	if (total_len < alloc_len) {
7585		ctsio->residual = alloc_len - total_len;
7586		ctsio->kern_data_len = total_len;
7587		ctsio->kern_total_len = total_len;
7588	} else {
7589		ctsio->residual = 0;
7590		ctsio->kern_data_len = alloc_len;
7591		ctsio->kern_total_len = alloc_len;
7592	}
7593	ctsio->kern_data_resid = 0;
7594	ctsio->kern_rel_offset = 0;
7595
7596	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7597	scsi_ulto2b(sizeof(*data) - 2, data->length);
7598	data->origin = RTS_ORIG_OUTSIDE;
7599	getmicrotime(&tv);
7600	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7601	scsi_ulto4b(timestamp >> 16, data->timestamp);
7602	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7603
7604	ctl_set_success(ctsio);
7605	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7606	ctsio->be_move_done = ctl_config_move_done;
7607	ctl_datamove((union ctl_io *)ctsio);
7608	return (retval);
7609}
7610
7611int
7612ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7613{
7614	struct scsi_per_res_in *cdb;
7615	int alloc_len, total_len = 0;
7616	/* struct scsi_per_res_in_rsrv in_data; */
7617	struct ctl_lun *lun;
7618	struct ctl_softc *softc;
7619
7620	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7621
7622	softc = control_softc;
7623
7624	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7625
7626	alloc_len = scsi_2btoul(cdb->length);
7627
7628	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7629
7630retry:
7631	mtx_lock(&lun->lun_lock);
7632	switch (cdb->action) {
7633	case SPRI_RK: /* read keys */
7634		total_len = sizeof(struct scsi_per_res_in_keys) +
7635			lun->pr_key_count *
7636			sizeof(struct scsi_per_res_key);
7637		break;
7638	case SPRI_RR: /* read reservation */
7639		if (lun->flags & CTL_LUN_PR_RESERVED)
7640			total_len = sizeof(struct scsi_per_res_in_rsrv);
7641		else
7642			total_len = sizeof(struct scsi_per_res_in_header);
7643		break;
7644	case SPRI_RC: /* report capabilities */
7645		total_len = sizeof(struct scsi_per_res_cap);
7646		break;
7647	case SPRI_RS: /* read full status */
7648		total_len = sizeof(struct scsi_per_res_in_header) +
7649		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7650		    lun->pr_key_count;
7651		break;
7652	default:
7653		panic("Invalid PR type %x", cdb->action);
7654	}
7655	mtx_unlock(&lun->lun_lock);
7656
7657	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7658
7659	if (total_len < alloc_len) {
7660		ctsio->residual = alloc_len - total_len;
7661		ctsio->kern_data_len = total_len;
7662		ctsio->kern_total_len = total_len;
7663	} else {
7664		ctsio->residual = 0;
7665		ctsio->kern_data_len = alloc_len;
7666		ctsio->kern_total_len = alloc_len;
7667	}
7668
7669	ctsio->kern_data_resid = 0;
7670	ctsio->kern_rel_offset = 0;
7671	ctsio->kern_sg_entries = 0;
7672
7673	mtx_lock(&lun->lun_lock);
7674	switch (cdb->action) {
7675	case SPRI_RK: { // read keys
7676        struct scsi_per_res_in_keys *res_keys;
7677		int i, key_count;
7678
7679		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7680
7681		/*
7682		 * We had to drop the lock to allocate our buffer, which
7683		 * leaves time for someone to come in with another
7684		 * persistent reservation.  (That is unlikely, though,
7685		 * since this should be the only persistent reservation
7686		 * command active right now.)
7687		 */
7688		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7689		    (lun->pr_key_count *
7690		     sizeof(struct scsi_per_res_key)))){
7691			mtx_unlock(&lun->lun_lock);
7692			free(ctsio->kern_data_ptr, M_CTL);
7693			printf("%s: reservation length changed, retrying\n",
7694			       __func__);
7695			goto retry;
7696		}
7697
7698		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7699
7700		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7701			     lun->pr_key_count, res_keys->header.length);
7702
7703		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7704			if (lun->pr_keys[i] == 0)
7705				continue;
7706
7707			/*
7708			 * We used lun->pr_key_count to calculate the
7709			 * size to allocate.  If it turns out the number of
7710			 * initiators with the registered flag set is
7711			 * larger than that (i.e. they haven't been kept in
7712			 * sync), we've got a problem.
7713			 */
7714			if (key_count >= lun->pr_key_count) {
7715#ifdef NEEDTOPORT
7716				csevent_log(CSC_CTL | CSC_SHELF_SW |
7717					    CTL_PR_ERROR,
7718					    csevent_LogType_Fault,
7719					    csevent_AlertLevel_Yellow,
7720					    csevent_FRU_ShelfController,
7721					    csevent_FRU_Firmware,
7722				        csevent_FRU_Unknown,
7723					    "registered keys %d >= key "
7724					    "count %d", key_count,
7725					    lun->pr_key_count);
7726#endif
7727				key_count++;
7728				continue;
7729			}
7730			scsi_u64to8b(lun->pr_keys[i],
7731			    res_keys->keys[key_count].key);
7732			key_count++;
7733		}
7734		break;
7735	}
7736	case SPRI_RR: { // read reservation
7737		struct scsi_per_res_in_rsrv *res;
7738		int tmp_len, header_only;
7739
7740		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7741
7742		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7743
7744		if (lun->flags & CTL_LUN_PR_RESERVED)
7745		{
7746			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7747			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7748				    res->header.length);
7749			header_only = 0;
7750		} else {
7751			tmp_len = sizeof(struct scsi_per_res_in_header);
7752			scsi_ulto4b(0, res->header.length);
7753			header_only = 1;
7754		}
7755
7756		/*
7757		 * We had to drop the lock to allocate our buffer, which
7758		 * leaves time for someone to come in with another
7759		 * persistent reservation.  (That is unlikely, though,
7760		 * since this should be the only persistent reservation
7761		 * command active right now.)
7762		 */
7763		if (tmp_len != total_len) {
7764			mtx_unlock(&lun->lun_lock);
7765			free(ctsio->kern_data_ptr, M_CTL);
7766			printf("%s: reservation status changed, retrying\n",
7767			       __func__);
7768			goto retry;
7769		}
7770
7771		/*
7772		 * No reservation held, so we're done.
7773		 */
7774		if (header_only != 0)
7775			break;
7776
7777		/*
7778		 * If the registration is an All Registrants type, the key
7779		 * is 0, since it doesn't really matter.
7780		 */
7781		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7782			scsi_u64to8b(lun->pr_keys[lun->pr_res_idx],
7783			    res->data.reservation);
7784		}
7785		res->data.scopetype = lun->res_type;
7786		break;
7787	}
7788	case SPRI_RC:     //report capabilities
7789	{
7790		struct scsi_per_res_cap *res_cap;
7791		uint16_t type_mask;
7792
7793		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7794		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7795		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7796		type_mask = SPRI_TM_WR_EX_AR |
7797			    SPRI_TM_EX_AC_RO |
7798			    SPRI_TM_WR_EX_RO |
7799			    SPRI_TM_EX_AC |
7800			    SPRI_TM_WR_EX |
7801			    SPRI_TM_EX_AC_AR;
7802		scsi_ulto2b(type_mask, res_cap->type_mask);
7803		break;
7804	}
7805	case SPRI_RS: { // read full status
7806		struct scsi_per_res_in_full *res_status;
7807		struct scsi_per_res_in_full_desc *res_desc;
7808		struct ctl_port *port;
7809		int i, len;
7810
7811		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7812
7813		/*
7814		 * We had to drop the lock to allocate our buffer, which
7815		 * leaves time for someone to come in with another
7816		 * persistent reservation.  (That is unlikely, though,
7817		 * since this should be the only persistent reservation
7818		 * command active right now.)
7819		 */
7820		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7821		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7822		     lun->pr_key_count)){
7823			mtx_unlock(&lun->lun_lock);
7824			free(ctsio->kern_data_ptr, M_CTL);
7825			printf("%s: reservation length changed, retrying\n",
7826			       __func__);
7827			goto retry;
7828		}
7829
7830		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7831
7832		res_desc = &res_status->desc[0];
7833		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7834			if (lun->pr_keys[i] == 0)
7835				continue;
7836
7837			scsi_u64to8b(lun->pr_keys[i], res_desc->res_key.key);
7838			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7839			    (lun->pr_res_idx == i ||
7840			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7841				res_desc->flags = SPRI_FULL_R_HOLDER;
7842				res_desc->scopetype = lun->res_type;
7843			}
7844			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7845			    res_desc->rel_trgt_port_id);
7846			len = 0;
7847			port = softc->ctl_ports[
7848			    ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
7849			if (port != NULL)
7850				len = ctl_create_iid(port,
7851				    i % CTL_MAX_INIT_PER_PORT,
7852				    res_desc->transport_id);
7853			scsi_ulto4b(len, res_desc->additional_length);
7854			res_desc = (struct scsi_per_res_in_full_desc *)
7855			    &res_desc->transport_id[len];
7856		}
7857		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7858		    res_status->header.length);
7859		break;
7860	}
7861	default:
7862		/*
7863		 * This is a bug, because we just checked for this above,
7864		 * and should have returned an error.
7865		 */
7866		panic("Invalid PR type %x", cdb->action);
7867		break; /* NOTREACHED */
7868	}
7869	mtx_unlock(&lun->lun_lock);
7870
7871	ctl_set_success(ctsio);
7872	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7873	ctsio->be_move_done = ctl_config_move_done;
7874	ctl_datamove((union ctl_io *)ctsio);
7875	return (CTL_RETVAL_COMPLETE);
7876}
7877
7878/*
7879 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7880 * it should return.
7881 */
7882static int
7883ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7884		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7885		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7886		struct scsi_per_res_out_parms* param)
7887{
7888	union ctl_ha_msg persis_io;
7889	int retval, i;
7890	int isc_retval;
7891
7892	retval = 0;
7893
7894	mtx_lock(&lun->lun_lock);
7895	if (sa_res_key == 0) {
7896		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7897			/* validate scope and type */
7898			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7899			     SPR_LU_SCOPE) {
7900				mtx_unlock(&lun->lun_lock);
7901				ctl_set_invalid_field(/*ctsio*/ ctsio,
7902						      /*sks_valid*/ 1,
7903						      /*command*/ 1,
7904						      /*field*/ 2,
7905						      /*bit_valid*/ 1,
7906						      /*bit*/ 4);
7907				ctl_done((union ctl_io *)ctsio);
7908				return (1);
7909			}
7910
7911		        if (type>8 || type==2 || type==4 || type==0) {
7912				mtx_unlock(&lun->lun_lock);
7913				ctl_set_invalid_field(/*ctsio*/ ctsio,
7914       	           				      /*sks_valid*/ 1,
7915						      /*command*/ 1,
7916						      /*field*/ 2,
7917						      /*bit_valid*/ 1,
7918						      /*bit*/ 0);
7919				ctl_done((union ctl_io *)ctsio);
7920				return (1);
7921		        }
7922
7923			/*
7924			 * Unregister everybody else and build UA for
7925			 * them
7926			 */
7927			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
7928				if (i == residx || lun->pr_keys[i] == 0)
7929					continue;
7930
7931				if (!persis_offset
7932				 && i <CTL_MAX_INITIATORS)
7933					lun->pending_ua[i] |=
7934						CTL_UA_REG_PREEMPT;
7935				else if (persis_offset
7936				      && i >= persis_offset)
7937					lun->pending_ua[i-persis_offset] |=
7938						CTL_UA_REG_PREEMPT;
7939				lun->pr_keys[i] = 0;
7940			}
7941			lun->pr_key_count = 1;
7942			lun->res_type = type;
7943			if (lun->res_type != SPR_TYPE_WR_EX_AR
7944			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7945				lun->pr_res_idx = residx;
7946
7947			/* send msg to other side */
7948			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7949			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7950			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7951			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7952			persis_io.pr.pr_info.res_type = type;
7953			memcpy(persis_io.pr.pr_info.sa_res_key,
7954			       param->serv_act_res_key,
7955			       sizeof(param->serv_act_res_key));
7956			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
7957			     &persis_io, sizeof(persis_io), 0)) >
7958			     CTL_HA_STATUS_SUCCESS) {
7959				printf("CTL:Persis Out error returned "
7960				       "from ctl_ha_msg_send %d\n",
7961				       isc_retval);
7962			}
7963		} else {
7964			/* not all registrants */
7965			mtx_unlock(&lun->lun_lock);
7966			free(ctsio->kern_data_ptr, M_CTL);
7967			ctl_set_invalid_field(ctsio,
7968					      /*sks_valid*/ 1,
7969					      /*command*/ 0,
7970					      /*field*/ 8,
7971					      /*bit_valid*/ 0,
7972					      /*bit*/ 0);
7973			ctl_done((union ctl_io *)ctsio);
7974			return (1);
7975		}
7976	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7977		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7978		int found = 0;
7979
7980		if (res_key == sa_res_key) {
7981			/* special case */
7982			/*
7983			 * The spec implies this is not good but doesn't
7984			 * say what to do. There are two choices either
7985			 * generate a res conflict or check condition
7986			 * with illegal field in parameter data. Since
7987			 * that is what is done when the sa_res_key is
7988			 * zero I'll take that approach since this has
7989			 * to do with the sa_res_key.
7990			 */
7991			mtx_unlock(&lun->lun_lock);
7992			free(ctsio->kern_data_ptr, M_CTL);
7993			ctl_set_invalid_field(ctsio,
7994					      /*sks_valid*/ 1,
7995					      /*command*/ 0,
7996					      /*field*/ 8,
7997					      /*bit_valid*/ 0,
7998					      /*bit*/ 0);
7999			ctl_done((union ctl_io *)ctsio);
8000			return (1);
8001		}
8002
8003		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8004			if (lun->pr_keys[i] != sa_res_key)
8005				continue;
8006
8007			found = 1;
8008			lun->pr_keys[i] = 0;
8009			lun->pr_key_count--;
8010
8011			if (!persis_offset && i < CTL_MAX_INITIATORS)
8012				lun->pending_ua[i] |= CTL_UA_REG_PREEMPT;
8013			else if (persis_offset && i >= persis_offset)
8014				lun->pending_ua[i-persis_offset] |=
8015					CTL_UA_REG_PREEMPT;
8016		}
8017		if (!found) {
8018			mtx_unlock(&lun->lun_lock);
8019			free(ctsio->kern_data_ptr, M_CTL);
8020			ctl_set_reservation_conflict(ctsio);
8021			ctl_done((union ctl_io *)ctsio);
8022			return (CTL_RETVAL_COMPLETE);
8023		}
8024		/* send msg to other side */
8025		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8026		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8027		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8028		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8029		persis_io.pr.pr_info.res_type = type;
8030		memcpy(persis_io.pr.pr_info.sa_res_key,
8031		       param->serv_act_res_key,
8032		       sizeof(param->serv_act_res_key));
8033		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8034		     &persis_io, sizeof(persis_io), 0)) >
8035		     CTL_HA_STATUS_SUCCESS) {
8036			printf("CTL:Persis Out error returned from "
8037			       "ctl_ha_msg_send %d\n", isc_retval);
8038		}
8039	} else {
8040		/* Reserved but not all registrants */
8041		/* sa_res_key is res holder */
8042		if (sa_res_key == lun->pr_keys[lun->pr_res_idx]) {
8043			/* validate scope and type */
8044			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8045			     SPR_LU_SCOPE) {
8046				mtx_unlock(&lun->lun_lock);
8047				ctl_set_invalid_field(/*ctsio*/ ctsio,
8048						      /*sks_valid*/ 1,
8049						      /*command*/ 1,
8050						      /*field*/ 2,
8051						      /*bit_valid*/ 1,
8052						      /*bit*/ 4);
8053				ctl_done((union ctl_io *)ctsio);
8054				return (1);
8055			}
8056
8057			if (type>8 || type==2 || type==4 || type==0) {
8058				mtx_unlock(&lun->lun_lock);
8059				ctl_set_invalid_field(/*ctsio*/ ctsio,
8060						      /*sks_valid*/ 1,
8061						      /*command*/ 1,
8062						      /*field*/ 2,
8063						      /*bit_valid*/ 1,
8064						      /*bit*/ 0);
8065				ctl_done((union ctl_io *)ctsio);
8066				return (1);
8067			}
8068
8069			/*
8070			 * Do the following:
8071			 * if sa_res_key != res_key remove all
8072			 * registrants w/sa_res_key and generate UA
8073			 * for these registrants(Registrations
8074			 * Preempted) if it wasn't an exclusive
8075			 * reservation generate UA(Reservations
8076			 * Preempted) for all other registered nexuses
8077			 * if the type has changed. Establish the new
8078			 * reservation and holder. If res_key and
8079			 * sa_res_key are the same do the above
8080			 * except don't unregister the res holder.
8081			 */
8082
8083			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8084				if (i == residx || lun->pr_keys[i] == 0)
8085					continue;
8086
8087				if (sa_res_key == lun->pr_keys[i]) {
8088					lun->pr_keys[i] = 0;
8089					lun->pr_key_count--;
8090
8091					if (!persis_offset
8092					 && i < CTL_MAX_INITIATORS)
8093						lun->pending_ua[i] |=
8094							CTL_UA_REG_PREEMPT;
8095					else if (persis_offset
8096					      && i >= persis_offset)
8097						lun->pending_ua[i-persis_offset] |=
8098						  CTL_UA_REG_PREEMPT;
8099				} else if (type != lun->res_type
8100					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8101					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8102						if (!persis_offset
8103						 && i < CTL_MAX_INITIATORS)
8104							lun->pending_ua[i] |=
8105							CTL_UA_RES_RELEASE;
8106						else if (persis_offset
8107						      && i >= persis_offset)
8108							lun->pending_ua[
8109							i-persis_offset] |=
8110							CTL_UA_RES_RELEASE;
8111				}
8112			}
8113			lun->res_type = type;
8114			if (lun->res_type != SPR_TYPE_WR_EX_AR
8115			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8116				lun->pr_res_idx = residx;
8117			else
8118				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8119
8120			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8121			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8122			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8123			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8124			persis_io.pr.pr_info.res_type = type;
8125			memcpy(persis_io.pr.pr_info.sa_res_key,
8126			       param->serv_act_res_key,
8127			       sizeof(param->serv_act_res_key));
8128			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8129			     &persis_io, sizeof(persis_io), 0)) >
8130			     CTL_HA_STATUS_SUCCESS) {
8131				printf("CTL:Persis Out error returned "
8132				       "from ctl_ha_msg_send %d\n",
8133				       isc_retval);
8134			}
8135		} else {
8136			/*
8137			 * sa_res_key is not the res holder just
8138			 * remove registrants
8139			 */
8140			int found=0;
8141
8142			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8143				if (sa_res_key != lun->pr_keys[i])
8144					continue;
8145
8146				found = 1;
8147				lun->pr_keys[i] = 0;
8148				lun->pr_key_count--;
8149
8150				if (!persis_offset
8151				 && i < CTL_MAX_INITIATORS)
8152					lun->pending_ua[i] |=
8153						CTL_UA_REG_PREEMPT;
8154				else if (persis_offset
8155				      && i >= persis_offset)
8156					lun->pending_ua[i-persis_offset] |=
8157						CTL_UA_REG_PREEMPT;
8158			}
8159
8160			if (!found) {
8161				mtx_unlock(&lun->lun_lock);
8162				free(ctsio->kern_data_ptr, M_CTL);
8163				ctl_set_reservation_conflict(ctsio);
8164				ctl_done((union ctl_io *)ctsio);
8165		        	return (1);
8166			}
8167			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8168			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8169			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8170			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8171			persis_io.pr.pr_info.res_type = type;
8172			memcpy(persis_io.pr.pr_info.sa_res_key,
8173			       param->serv_act_res_key,
8174			       sizeof(param->serv_act_res_key));
8175			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8176			     &persis_io, sizeof(persis_io), 0)) >
8177			     CTL_HA_STATUS_SUCCESS) {
8178				printf("CTL:Persis Out error returned "
8179				       "from ctl_ha_msg_send %d\n",
8180				isc_retval);
8181			}
8182		}
8183	}
8184
8185	lun->PRGeneration++;
8186	mtx_unlock(&lun->lun_lock);
8187
8188	return (retval);
8189}
8190
8191static void
8192ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8193{
8194	uint64_t sa_res_key;
8195	int i;
8196
8197	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8198
8199	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8200	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8201	 || sa_res_key != lun->pr_keys[lun->pr_res_idx]) {
8202		if (sa_res_key == 0) {
8203			/*
8204			 * Unregister everybody else and build UA for
8205			 * them
8206			 */
8207			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8208				if (i == msg->pr.pr_info.residx ||
8209				    lun->pr_keys[i] == 0)
8210					continue;
8211
8212				if (!persis_offset
8213				 && i < CTL_MAX_INITIATORS)
8214					lun->pending_ua[i] |=
8215						CTL_UA_REG_PREEMPT;
8216				else if (persis_offset && i >= persis_offset)
8217					lun->pending_ua[i - persis_offset] |=
8218						CTL_UA_REG_PREEMPT;
8219				lun->pr_keys[i] = 0;
8220			}
8221
8222			lun->pr_key_count = 1;
8223			lun->res_type = msg->pr.pr_info.res_type;
8224			if (lun->res_type != SPR_TYPE_WR_EX_AR
8225			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8226				lun->pr_res_idx = msg->pr.pr_info.residx;
8227		} else {
8228		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8229				if (sa_res_key == lun->pr_keys[i])
8230					continue;
8231
8232				lun->pr_keys[i] = 0;
8233				lun->pr_key_count--;
8234
8235				if (!persis_offset
8236				 && i < persis_offset)
8237					lun->pending_ua[i] |=
8238						CTL_UA_REG_PREEMPT;
8239				else if (persis_offset
8240				      && i >= persis_offset)
8241					lun->pending_ua[i - persis_offset] |=
8242						CTL_UA_REG_PREEMPT;
8243			}
8244		}
8245	} else {
8246		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8247			if (i == msg->pr.pr_info.residx ||
8248			    lun->pr_keys[i] == 0)
8249				continue;
8250
8251			if (sa_res_key == lun->pr_keys[i]) {
8252				lun->pr_keys[i] = 0;
8253				lun->pr_key_count--;
8254				if (!persis_offset
8255				 && i < CTL_MAX_INITIATORS)
8256					lun->pending_ua[i] |=
8257						CTL_UA_REG_PREEMPT;
8258				else if (persis_offset
8259				      && i >= persis_offset)
8260					lun->pending_ua[i - persis_offset] |=
8261						CTL_UA_REG_PREEMPT;
8262			} else if (msg->pr.pr_info.res_type != lun->res_type
8263				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8264				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8265					if (!persis_offset
8266					 && i < persis_offset)
8267						lun->pending_ua[i] |=
8268							CTL_UA_RES_RELEASE;
8269					else if (persis_offset
8270					      && i >= persis_offset)
8271					lun->pending_ua[i - persis_offset] |=
8272						CTL_UA_RES_RELEASE;
8273			}
8274		}
8275		lun->res_type = msg->pr.pr_info.res_type;
8276		if (lun->res_type != SPR_TYPE_WR_EX_AR
8277		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8278			lun->pr_res_idx = msg->pr.pr_info.residx;
8279		else
8280			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8281	}
8282	lun->PRGeneration++;
8283
8284}
8285
8286
8287int
8288ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8289{
8290	int retval;
8291	int isc_retval;
8292	u_int32_t param_len;
8293	struct scsi_per_res_out *cdb;
8294	struct ctl_lun *lun;
8295	struct scsi_per_res_out_parms* param;
8296	struct ctl_softc *softc;
8297	uint32_t residx;
8298	uint64_t res_key, sa_res_key;
8299	uint8_t type;
8300	union ctl_ha_msg persis_io;
8301	int    i;
8302
8303	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8304
8305	retval = CTL_RETVAL_COMPLETE;
8306
8307	softc = control_softc;
8308
8309	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8310	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8311
8312	/*
8313	 * We only support whole-LUN scope.  The scope & type are ignored for
8314	 * register, register and ignore existing key and clear.
8315	 * We sometimes ignore scope and type on preempts too!!
8316	 * Verify reservation type here as well.
8317	 */
8318	type = cdb->scope_type & SPR_TYPE_MASK;
8319	if ((cdb->action == SPRO_RESERVE)
8320	 || (cdb->action == SPRO_RELEASE)) {
8321		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8322			ctl_set_invalid_field(/*ctsio*/ ctsio,
8323					      /*sks_valid*/ 1,
8324					      /*command*/ 1,
8325					      /*field*/ 2,
8326					      /*bit_valid*/ 1,
8327					      /*bit*/ 4);
8328			ctl_done((union ctl_io *)ctsio);
8329			return (CTL_RETVAL_COMPLETE);
8330		}
8331
8332		if (type>8 || type==2 || type==4 || type==0) {
8333			ctl_set_invalid_field(/*ctsio*/ ctsio,
8334					      /*sks_valid*/ 1,
8335					      /*command*/ 1,
8336					      /*field*/ 2,
8337					      /*bit_valid*/ 1,
8338					      /*bit*/ 0);
8339			ctl_done((union ctl_io *)ctsio);
8340			return (CTL_RETVAL_COMPLETE);
8341		}
8342	}
8343
8344	param_len = scsi_4btoul(cdb->length);
8345
8346	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8347		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8348		ctsio->kern_data_len = param_len;
8349		ctsio->kern_total_len = param_len;
8350		ctsio->kern_data_resid = 0;
8351		ctsio->kern_rel_offset = 0;
8352		ctsio->kern_sg_entries = 0;
8353		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8354		ctsio->be_move_done = ctl_config_move_done;
8355		ctl_datamove((union ctl_io *)ctsio);
8356
8357		return (CTL_RETVAL_COMPLETE);
8358	}
8359
8360	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8361
8362	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8363	res_key = scsi_8btou64(param->res_key.key);
8364	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8365
8366	/*
8367	 * Validate the reservation key here except for SPRO_REG_IGNO
8368	 * This must be done for all other service actions
8369	 */
8370	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8371		mtx_lock(&lun->lun_lock);
8372		if (lun->pr_keys[residx] != 0) {
8373		    if (res_key != lun->pr_keys[residx]) {
8374				/*
8375				 * The current key passed in doesn't match
8376				 * the one the initiator previously
8377				 * registered.
8378				 */
8379				mtx_unlock(&lun->lun_lock);
8380				free(ctsio->kern_data_ptr, M_CTL);
8381				ctl_set_reservation_conflict(ctsio);
8382				ctl_done((union ctl_io *)ctsio);
8383				return (CTL_RETVAL_COMPLETE);
8384			}
8385		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8386			/*
8387			 * We are not registered
8388			 */
8389			mtx_unlock(&lun->lun_lock);
8390			free(ctsio->kern_data_ptr, M_CTL);
8391			ctl_set_reservation_conflict(ctsio);
8392			ctl_done((union ctl_io *)ctsio);
8393			return (CTL_RETVAL_COMPLETE);
8394		} else if (res_key != 0) {
8395			/*
8396			 * We are not registered and trying to register but
8397			 * the register key isn't zero.
8398			 */
8399			mtx_unlock(&lun->lun_lock);
8400			free(ctsio->kern_data_ptr, M_CTL);
8401			ctl_set_reservation_conflict(ctsio);
8402			ctl_done((union ctl_io *)ctsio);
8403			return (CTL_RETVAL_COMPLETE);
8404		}
8405		mtx_unlock(&lun->lun_lock);
8406	}
8407
8408	switch (cdb->action & SPRO_ACTION_MASK) {
8409	case SPRO_REGISTER:
8410	case SPRO_REG_IGNO: {
8411
8412#if 0
8413		printf("Registration received\n");
8414#endif
8415
8416		/*
8417		 * We don't support any of these options, as we report in
8418		 * the read capabilities request (see
8419		 * ctl_persistent_reserve_in(), above).
8420		 */
8421		if ((param->flags & SPR_SPEC_I_PT)
8422		 || (param->flags & SPR_ALL_TG_PT)
8423		 || (param->flags & SPR_APTPL)) {
8424			int bit_ptr;
8425
8426			if (param->flags & SPR_APTPL)
8427				bit_ptr = 0;
8428			else if (param->flags & SPR_ALL_TG_PT)
8429				bit_ptr = 2;
8430			else /* SPR_SPEC_I_PT */
8431				bit_ptr = 3;
8432
8433			free(ctsio->kern_data_ptr, M_CTL);
8434			ctl_set_invalid_field(ctsio,
8435					      /*sks_valid*/ 1,
8436					      /*command*/ 0,
8437					      /*field*/ 20,
8438					      /*bit_valid*/ 1,
8439					      /*bit*/ bit_ptr);
8440			ctl_done((union ctl_io *)ctsio);
8441			return (CTL_RETVAL_COMPLETE);
8442		}
8443
8444		mtx_lock(&lun->lun_lock);
8445
8446		/*
8447		 * The initiator wants to clear the
8448		 * key/unregister.
8449		 */
8450		if (sa_res_key == 0) {
8451			if ((res_key == 0
8452			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8453			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8454			  && lun->pr_keys[residx] == 0)) {
8455				mtx_unlock(&lun->lun_lock);
8456				goto done;
8457			}
8458
8459			lun->pr_keys[residx] = 0;
8460			lun->pr_key_count--;
8461
8462			if (residx == lun->pr_res_idx) {
8463				lun->flags &= ~CTL_LUN_PR_RESERVED;
8464				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8465
8466				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8467				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8468				 && lun->pr_key_count) {
8469					/*
8470					 * If the reservation is a registrants
8471					 * only type we need to generate a UA
8472					 * for other registered inits.  The
8473					 * sense code should be RESERVATIONS
8474					 * RELEASED
8475					 */
8476
8477					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8478						if (lun->pr_keys[
8479						    i + persis_offset] == 0)
8480							continue;
8481						lun->pending_ua[i] |=
8482							CTL_UA_RES_RELEASE;
8483					}
8484				}
8485				lun->res_type = 0;
8486			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8487				if (lun->pr_key_count==0) {
8488					lun->flags &= ~CTL_LUN_PR_RESERVED;
8489					lun->res_type = 0;
8490					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8491				}
8492			}
8493			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8494			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8495			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8496			persis_io.pr.pr_info.residx = residx;
8497			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8498			     &persis_io, sizeof(persis_io), 0 )) >
8499			     CTL_HA_STATUS_SUCCESS) {
8500				printf("CTL:Persis Out error returned from "
8501				       "ctl_ha_msg_send %d\n", isc_retval);
8502			}
8503		} else /* sa_res_key != 0 */ {
8504
8505			/*
8506			 * If we aren't registered currently then increment
8507			 * the key count and set the registered flag.
8508			 */
8509			if (lun->pr_keys[residx] == 0)
8510				lun->pr_key_count++;
8511			lun->pr_keys[residx] = sa_res_key;
8512
8513			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8514			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8515			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8516			persis_io.pr.pr_info.residx = residx;
8517			memcpy(persis_io.pr.pr_info.sa_res_key,
8518			       param->serv_act_res_key,
8519			       sizeof(param->serv_act_res_key));
8520			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8521			     &persis_io, sizeof(persis_io), 0)) >
8522			     CTL_HA_STATUS_SUCCESS) {
8523				printf("CTL:Persis Out error returned from "
8524				       "ctl_ha_msg_send %d\n", isc_retval);
8525			}
8526		}
8527		lun->PRGeneration++;
8528		mtx_unlock(&lun->lun_lock);
8529
8530		break;
8531	}
8532	case SPRO_RESERVE:
8533#if 0
8534                printf("Reserve executed type %d\n", type);
8535#endif
8536		mtx_lock(&lun->lun_lock);
8537		if (lun->flags & CTL_LUN_PR_RESERVED) {
8538			/*
8539			 * if this isn't the reservation holder and it's
8540			 * not a "all registrants" type or if the type is
8541			 * different then we have a conflict
8542			 */
8543			if ((lun->pr_res_idx != residx
8544			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8545			 || lun->res_type != type) {
8546				mtx_unlock(&lun->lun_lock);
8547				free(ctsio->kern_data_ptr, M_CTL);
8548				ctl_set_reservation_conflict(ctsio);
8549				ctl_done((union ctl_io *)ctsio);
8550				return (CTL_RETVAL_COMPLETE);
8551			}
8552			mtx_unlock(&lun->lun_lock);
8553		} else /* create a reservation */ {
8554			/*
8555			 * If it's not an "all registrants" type record
8556			 * reservation holder
8557			 */
8558			if (type != SPR_TYPE_WR_EX_AR
8559			 && type != SPR_TYPE_EX_AC_AR)
8560				lun->pr_res_idx = residx; /* Res holder */
8561			else
8562				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8563
8564			lun->flags |= CTL_LUN_PR_RESERVED;
8565			lun->res_type = type;
8566
8567			mtx_unlock(&lun->lun_lock);
8568
8569			/* send msg to other side */
8570			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8571			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8572			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8573			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8574			persis_io.pr.pr_info.res_type = type;
8575			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8576			     &persis_io, sizeof(persis_io), 0)) >
8577			     CTL_HA_STATUS_SUCCESS) {
8578				printf("CTL:Persis Out error returned from "
8579				       "ctl_ha_msg_send %d\n", isc_retval);
8580			}
8581		}
8582		break;
8583
8584	case SPRO_RELEASE:
8585		mtx_lock(&lun->lun_lock);
8586		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8587			/* No reservation exists return good status */
8588			mtx_unlock(&lun->lun_lock);
8589			goto done;
8590		}
8591		/*
8592		 * Is this nexus a reservation holder?
8593		 */
8594		if (lun->pr_res_idx != residx
8595		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8596			/*
8597			 * not a res holder return good status but
8598			 * do nothing
8599			 */
8600			mtx_unlock(&lun->lun_lock);
8601			goto done;
8602		}
8603
8604		if (lun->res_type != type) {
8605			mtx_unlock(&lun->lun_lock);
8606			free(ctsio->kern_data_ptr, M_CTL);
8607			ctl_set_illegal_pr_release(ctsio);
8608			ctl_done((union ctl_io *)ctsio);
8609			return (CTL_RETVAL_COMPLETE);
8610		}
8611
8612		/* okay to release */
8613		lun->flags &= ~CTL_LUN_PR_RESERVED;
8614		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8615		lun->res_type = 0;
8616
8617		/*
8618		 * if this isn't an exclusive access
8619		 * res generate UA for all other
8620		 * registrants.
8621		 */
8622		if (type != SPR_TYPE_EX_AC
8623		 && type != SPR_TYPE_WR_EX) {
8624			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8625				if (i == residx ||
8626				    lun->pr_keys[i + persis_offset] == 0)
8627					continue;
8628				lun->pending_ua[i] |= CTL_UA_RES_RELEASE;
8629			}
8630		}
8631		mtx_unlock(&lun->lun_lock);
8632		/* Send msg to other side */
8633		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8634		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8635		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8636		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8637		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8638			printf("CTL:Persis Out error returned from "
8639			       "ctl_ha_msg_send %d\n", isc_retval);
8640		}
8641		break;
8642
8643	case SPRO_CLEAR:
8644		/* send msg to other side */
8645
8646		mtx_lock(&lun->lun_lock);
8647		lun->flags &= ~CTL_LUN_PR_RESERVED;
8648		lun->res_type = 0;
8649		lun->pr_key_count = 0;
8650		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8651
8652		lun->pr_keys[residx] = 0;
8653
8654		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8655			if (lun->pr_keys[i] != 0) {
8656				if (!persis_offset && i < CTL_MAX_INITIATORS)
8657					lun->pending_ua[i] |=
8658						CTL_UA_RES_PREEMPT;
8659				else if (persis_offset && i >= persis_offset)
8660					lun->pending_ua[i-persis_offset] |=
8661					    CTL_UA_RES_PREEMPT;
8662
8663				lun->pr_keys[i] = 0;
8664			}
8665		lun->PRGeneration++;
8666		mtx_unlock(&lun->lun_lock);
8667		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8668		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8669		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8670		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8671		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8672			printf("CTL:Persis Out error returned from "
8673			       "ctl_ha_msg_send %d\n", isc_retval);
8674		}
8675		break;
8676
8677	case SPRO_PREEMPT:
8678	case SPRO_PRE_ABO: {
8679		int nretval;
8680
8681		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8682					  residx, ctsio, cdb, param);
8683		if (nretval != 0)
8684			return (CTL_RETVAL_COMPLETE);
8685		break;
8686	}
8687	default:
8688		panic("Invalid PR type %x", cdb->action);
8689	}
8690
8691done:
8692	free(ctsio->kern_data_ptr, M_CTL);
8693	ctl_set_success(ctsio);
8694	ctl_done((union ctl_io *)ctsio);
8695
8696	return (retval);
8697}
8698
8699/*
8700 * This routine is for handling a message from the other SC pertaining to
8701 * persistent reserve out. All the error checking will have been done
8702 * so only perorming the action need be done here to keep the two
8703 * in sync.
8704 */
8705static void
8706ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8707{
8708	struct ctl_lun *lun;
8709	struct ctl_softc *softc;
8710	int i;
8711	uint32_t targ_lun;
8712
8713	softc = control_softc;
8714
8715	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8716	lun = softc->ctl_luns[targ_lun];
8717	mtx_lock(&lun->lun_lock);
8718	switch(msg->pr.pr_info.action) {
8719	case CTL_PR_REG_KEY:
8720		if (lun->pr_keys[msg->pr.pr_info.residx] == 0)
8721			lun->pr_key_count++;
8722		lun->pr_keys[msg->pr.pr_info.residx] =
8723		    scsi_8btou64(msg->pr.pr_info.sa_res_key);
8724		lun->PRGeneration++;
8725		break;
8726
8727	case CTL_PR_UNREG_KEY:
8728		lun->pr_keys[msg->pr.pr_info.residx] = 0;
8729		lun->pr_key_count--;
8730
8731		/* XXX Need to see if the reservation has been released */
8732		/* if so do we need to generate UA? */
8733		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8734			lun->flags &= ~CTL_LUN_PR_RESERVED;
8735			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8736
8737			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8738			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8739			 && lun->pr_key_count) {
8740				/*
8741				 * If the reservation is a registrants
8742				 * only type we need to generate a UA
8743				 * for other registered inits.  The
8744				 * sense code should be RESERVATIONS
8745				 * RELEASED
8746				 */
8747
8748				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8749					if (lun->pr_keys[i+
8750					    persis_offset] == 0)
8751						continue;
8752
8753					lun->pending_ua[i] |=
8754						CTL_UA_RES_RELEASE;
8755				}
8756			}
8757			lun->res_type = 0;
8758		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8759			if (lun->pr_key_count==0) {
8760				lun->flags &= ~CTL_LUN_PR_RESERVED;
8761				lun->res_type = 0;
8762				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8763			}
8764		}
8765		lun->PRGeneration++;
8766		break;
8767
8768	case CTL_PR_RESERVE:
8769		lun->flags |= CTL_LUN_PR_RESERVED;
8770		lun->res_type = msg->pr.pr_info.res_type;
8771		lun->pr_res_idx = msg->pr.pr_info.residx;
8772
8773		break;
8774
8775	case CTL_PR_RELEASE:
8776		/*
8777		 * if this isn't an exclusive access res generate UA for all
8778		 * other registrants.
8779		 */
8780		if (lun->res_type != SPR_TYPE_EX_AC
8781		 && lun->res_type != SPR_TYPE_WR_EX) {
8782			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8783				if (lun->pr_keys[i+persis_offset] != 0)
8784					lun->pending_ua[i] |=
8785						CTL_UA_RES_RELEASE;
8786		}
8787
8788		lun->flags &= ~CTL_LUN_PR_RESERVED;
8789		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8790		lun->res_type = 0;
8791		break;
8792
8793	case CTL_PR_PREEMPT:
8794		ctl_pro_preempt_other(lun, msg);
8795		break;
8796	case CTL_PR_CLEAR:
8797		lun->flags &= ~CTL_LUN_PR_RESERVED;
8798		lun->res_type = 0;
8799		lun->pr_key_count = 0;
8800		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8801
8802		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8803			if (lun->pr_keys[i] == 0)
8804				continue;
8805			if (!persis_offset
8806			 && i < CTL_MAX_INITIATORS)
8807				lun->pending_ua[i] |= CTL_UA_RES_PREEMPT;
8808			else if (persis_offset
8809			      && i >= persis_offset)
8810				lun->pending_ua[i-persis_offset] |=
8811					CTL_UA_RES_PREEMPT;
8812			lun->pr_keys[i] = 0;
8813		}
8814		lun->PRGeneration++;
8815		break;
8816	}
8817
8818	mtx_unlock(&lun->lun_lock);
8819}
8820
8821int
8822ctl_read_write(struct ctl_scsiio *ctsio)
8823{
8824	struct ctl_lun *lun;
8825	struct ctl_lba_len_flags *lbalen;
8826	uint64_t lba;
8827	uint32_t num_blocks;
8828	int flags, retval;
8829	int isread;
8830
8831	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8832
8833	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8834
8835	flags = 0;
8836	retval = CTL_RETVAL_COMPLETE;
8837
8838	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8839	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8840	switch (ctsio->cdb[0]) {
8841	case READ_6:
8842	case WRITE_6: {
8843		struct scsi_rw_6 *cdb;
8844
8845		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8846
8847		lba = scsi_3btoul(cdb->addr);
8848		/* only 5 bits are valid in the most significant address byte */
8849		lba &= 0x1fffff;
8850		num_blocks = cdb->length;
8851		/*
8852		 * This is correct according to SBC-2.
8853		 */
8854		if (num_blocks == 0)
8855			num_blocks = 256;
8856		break;
8857	}
8858	case READ_10:
8859	case WRITE_10: {
8860		struct scsi_rw_10 *cdb;
8861
8862		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8863		if (cdb->byte2 & SRW10_FUA)
8864			flags |= CTL_LLF_FUA;
8865		if (cdb->byte2 & SRW10_DPO)
8866			flags |= CTL_LLF_DPO;
8867		lba = scsi_4btoul(cdb->addr);
8868		num_blocks = scsi_2btoul(cdb->length);
8869		break;
8870	}
8871	case WRITE_VERIFY_10: {
8872		struct scsi_write_verify_10 *cdb;
8873
8874		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8875		flags |= CTL_LLF_FUA;
8876		if (cdb->byte2 & SWV_DPO)
8877			flags |= CTL_LLF_DPO;
8878		lba = scsi_4btoul(cdb->addr);
8879		num_blocks = scsi_2btoul(cdb->length);
8880		break;
8881	}
8882	case READ_12:
8883	case WRITE_12: {
8884		struct scsi_rw_12 *cdb;
8885
8886		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8887		if (cdb->byte2 & SRW12_FUA)
8888			flags |= CTL_LLF_FUA;
8889		if (cdb->byte2 & SRW12_DPO)
8890			flags |= CTL_LLF_DPO;
8891		lba = scsi_4btoul(cdb->addr);
8892		num_blocks = scsi_4btoul(cdb->length);
8893		break;
8894	}
8895	case WRITE_VERIFY_12: {
8896		struct scsi_write_verify_12 *cdb;
8897
8898		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8899		flags |= CTL_LLF_FUA;
8900		if (cdb->byte2 & SWV_DPO)
8901			flags |= CTL_LLF_DPO;
8902		lba = scsi_4btoul(cdb->addr);
8903		num_blocks = scsi_4btoul(cdb->length);
8904		break;
8905	}
8906	case READ_16:
8907	case WRITE_16: {
8908		struct scsi_rw_16 *cdb;
8909
8910		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8911		if (cdb->byte2 & SRW12_FUA)
8912			flags |= CTL_LLF_FUA;
8913		if (cdb->byte2 & SRW12_DPO)
8914			flags |= CTL_LLF_DPO;
8915		lba = scsi_8btou64(cdb->addr);
8916		num_blocks = scsi_4btoul(cdb->length);
8917		break;
8918	}
8919	case WRITE_ATOMIC_16: {
8920		struct scsi_rw_16 *cdb;
8921
8922		if (lun->be_lun->atomicblock == 0) {
8923			ctl_set_invalid_opcode(ctsio);
8924			ctl_done((union ctl_io *)ctsio);
8925			return (CTL_RETVAL_COMPLETE);
8926		}
8927
8928		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8929		if (cdb->byte2 & SRW12_FUA)
8930			flags |= CTL_LLF_FUA;
8931		if (cdb->byte2 & SRW12_DPO)
8932			flags |= CTL_LLF_DPO;
8933		lba = scsi_8btou64(cdb->addr);
8934		num_blocks = scsi_4btoul(cdb->length);
8935		if (num_blocks > lun->be_lun->atomicblock) {
8936			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8937			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8938			    /*bit*/ 0);
8939			ctl_done((union ctl_io *)ctsio);
8940			return (CTL_RETVAL_COMPLETE);
8941		}
8942		break;
8943	}
8944	case WRITE_VERIFY_16: {
8945		struct scsi_write_verify_16 *cdb;
8946
8947		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8948		flags |= CTL_LLF_FUA;
8949		if (cdb->byte2 & SWV_DPO)
8950			flags |= CTL_LLF_DPO;
8951		lba = scsi_8btou64(cdb->addr);
8952		num_blocks = scsi_4btoul(cdb->length);
8953		break;
8954	}
8955	default:
8956		/*
8957		 * We got a command we don't support.  This shouldn't
8958		 * happen, commands should be filtered out above us.
8959		 */
8960		ctl_set_invalid_opcode(ctsio);
8961		ctl_done((union ctl_io *)ctsio);
8962
8963		return (CTL_RETVAL_COMPLETE);
8964		break; /* NOTREACHED */
8965	}
8966
8967	/*
8968	 * The first check is to make sure we're in bounds, the second
8969	 * check is to catch wrap-around problems.  If the lba + num blocks
8970	 * is less than the lba, then we've wrapped around and the block
8971	 * range is invalid anyway.
8972	 */
8973	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8974	 || ((lba + num_blocks) < lba)) {
8975		ctl_set_lba_out_of_range(ctsio);
8976		ctl_done((union ctl_io *)ctsio);
8977		return (CTL_RETVAL_COMPLETE);
8978	}
8979
8980	/*
8981	 * According to SBC-3, a transfer length of 0 is not an error.
8982	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8983	 * translates to 256 blocks for those commands.
8984	 */
8985	if (num_blocks == 0) {
8986		ctl_set_success(ctsio);
8987		ctl_done((union ctl_io *)ctsio);
8988		return (CTL_RETVAL_COMPLETE);
8989	}
8990
8991	/* Set FUA and/or DPO if caches are disabled. */
8992	if (isread) {
8993		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8994		    SCP_RCD) != 0)
8995			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8996	} else {
8997		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8998		    SCP_WCE) == 0)
8999			flags |= CTL_LLF_FUA;
9000	}
9001
9002	lbalen = (struct ctl_lba_len_flags *)
9003	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9004	lbalen->lba = lba;
9005	lbalen->len = num_blocks;
9006	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9007
9008	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9009	ctsio->kern_rel_offset = 0;
9010
9011	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9012
9013	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9014
9015	return (retval);
9016}
9017
9018static int
9019ctl_cnw_cont(union ctl_io *io)
9020{
9021	struct ctl_scsiio *ctsio;
9022	struct ctl_lun *lun;
9023	struct ctl_lba_len_flags *lbalen;
9024	int retval;
9025
9026	ctsio = &io->scsiio;
9027	ctsio->io_hdr.status = CTL_STATUS_NONE;
9028	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9029	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9030	lbalen = (struct ctl_lba_len_flags *)
9031	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9032	lbalen->flags &= ~CTL_LLF_COMPARE;
9033	lbalen->flags |= CTL_LLF_WRITE;
9034
9035	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9036	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9037	return (retval);
9038}
9039
9040int
9041ctl_cnw(struct ctl_scsiio *ctsio)
9042{
9043	struct ctl_lun *lun;
9044	struct ctl_lba_len_flags *lbalen;
9045	uint64_t lba;
9046	uint32_t num_blocks;
9047	int flags, retval;
9048
9049	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9050
9051	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9052
9053	flags = 0;
9054	retval = CTL_RETVAL_COMPLETE;
9055
9056	switch (ctsio->cdb[0]) {
9057	case COMPARE_AND_WRITE: {
9058		struct scsi_compare_and_write *cdb;
9059
9060		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9061		if (cdb->byte2 & SRW10_FUA)
9062			flags |= CTL_LLF_FUA;
9063		if (cdb->byte2 & SRW10_DPO)
9064			flags |= CTL_LLF_DPO;
9065		lba = scsi_8btou64(cdb->addr);
9066		num_blocks = cdb->length;
9067		break;
9068	}
9069	default:
9070		/*
9071		 * We got a command we don't support.  This shouldn't
9072		 * happen, commands should be filtered out above us.
9073		 */
9074		ctl_set_invalid_opcode(ctsio);
9075		ctl_done((union ctl_io *)ctsio);
9076
9077		return (CTL_RETVAL_COMPLETE);
9078		break; /* NOTREACHED */
9079	}
9080
9081	/*
9082	 * The first check is to make sure we're in bounds, the second
9083	 * check is to catch wrap-around problems.  If the lba + num blocks
9084	 * is less than the lba, then we've wrapped around and the block
9085	 * range is invalid anyway.
9086	 */
9087	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9088	 || ((lba + num_blocks) < lba)) {
9089		ctl_set_lba_out_of_range(ctsio);
9090		ctl_done((union ctl_io *)ctsio);
9091		return (CTL_RETVAL_COMPLETE);
9092	}
9093
9094	/*
9095	 * According to SBC-3, a transfer length of 0 is not an error.
9096	 */
9097	if (num_blocks == 0) {
9098		ctl_set_success(ctsio);
9099		ctl_done((union ctl_io *)ctsio);
9100		return (CTL_RETVAL_COMPLETE);
9101	}
9102
9103	/* Set FUA if write cache is disabled. */
9104	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9105	    SCP_WCE) == 0)
9106		flags |= CTL_LLF_FUA;
9107
9108	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9109	ctsio->kern_rel_offset = 0;
9110
9111	/*
9112	 * Set the IO_CONT flag, so that if this I/O gets passed to
9113	 * ctl_data_submit_done(), it'll get passed back to
9114	 * ctl_ctl_cnw_cont() for further processing.
9115	 */
9116	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9117	ctsio->io_cont = ctl_cnw_cont;
9118
9119	lbalen = (struct ctl_lba_len_flags *)
9120	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9121	lbalen->lba = lba;
9122	lbalen->len = num_blocks;
9123	lbalen->flags = CTL_LLF_COMPARE | flags;
9124
9125	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9126	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9127	return (retval);
9128}
9129
9130int
9131ctl_verify(struct ctl_scsiio *ctsio)
9132{
9133	struct ctl_lun *lun;
9134	struct ctl_lba_len_flags *lbalen;
9135	uint64_t lba;
9136	uint32_t num_blocks;
9137	int bytchk, flags;
9138	int retval;
9139
9140	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9141
9142	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9143
9144	bytchk = 0;
9145	flags = CTL_LLF_FUA;
9146	retval = CTL_RETVAL_COMPLETE;
9147
9148	switch (ctsio->cdb[0]) {
9149	case VERIFY_10: {
9150		struct scsi_verify_10 *cdb;
9151
9152		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9153		if (cdb->byte2 & SVFY_BYTCHK)
9154			bytchk = 1;
9155		if (cdb->byte2 & SVFY_DPO)
9156			flags |= CTL_LLF_DPO;
9157		lba = scsi_4btoul(cdb->addr);
9158		num_blocks = scsi_2btoul(cdb->length);
9159		break;
9160	}
9161	case VERIFY_12: {
9162		struct scsi_verify_12 *cdb;
9163
9164		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9165		if (cdb->byte2 & SVFY_BYTCHK)
9166			bytchk = 1;
9167		if (cdb->byte2 & SVFY_DPO)
9168			flags |= CTL_LLF_DPO;
9169		lba = scsi_4btoul(cdb->addr);
9170		num_blocks = scsi_4btoul(cdb->length);
9171		break;
9172	}
9173	case VERIFY_16: {
9174		struct scsi_rw_16 *cdb;
9175
9176		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9177		if (cdb->byte2 & SVFY_BYTCHK)
9178			bytchk = 1;
9179		if (cdb->byte2 & SVFY_DPO)
9180			flags |= CTL_LLF_DPO;
9181		lba = scsi_8btou64(cdb->addr);
9182		num_blocks = scsi_4btoul(cdb->length);
9183		break;
9184	}
9185	default:
9186		/*
9187		 * We got a command we don't support.  This shouldn't
9188		 * happen, commands should be filtered out above us.
9189		 */
9190		ctl_set_invalid_opcode(ctsio);
9191		ctl_done((union ctl_io *)ctsio);
9192		return (CTL_RETVAL_COMPLETE);
9193	}
9194
9195	/*
9196	 * The first check is to make sure we're in bounds, the second
9197	 * check is to catch wrap-around problems.  If the lba + num blocks
9198	 * is less than the lba, then we've wrapped around and the block
9199	 * range is invalid anyway.
9200	 */
9201	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9202	 || ((lba + num_blocks) < lba)) {
9203		ctl_set_lba_out_of_range(ctsio);
9204		ctl_done((union ctl_io *)ctsio);
9205		return (CTL_RETVAL_COMPLETE);
9206	}
9207
9208	/*
9209	 * According to SBC-3, a transfer length of 0 is not an error.
9210	 */
9211	if (num_blocks == 0) {
9212		ctl_set_success(ctsio);
9213		ctl_done((union ctl_io *)ctsio);
9214		return (CTL_RETVAL_COMPLETE);
9215	}
9216
9217	lbalen = (struct ctl_lba_len_flags *)
9218	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9219	lbalen->lba = lba;
9220	lbalen->len = num_blocks;
9221	if (bytchk) {
9222		lbalen->flags = CTL_LLF_COMPARE | flags;
9223		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9224	} else {
9225		lbalen->flags = CTL_LLF_VERIFY | flags;
9226		ctsio->kern_total_len = 0;
9227	}
9228	ctsio->kern_rel_offset = 0;
9229
9230	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9231	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9232	return (retval);
9233}
9234
9235int
9236ctl_report_luns(struct ctl_scsiio *ctsio)
9237{
9238	struct scsi_report_luns *cdb;
9239	struct scsi_report_luns_data *lun_data;
9240	struct ctl_lun *lun, *request_lun;
9241	int num_luns, retval;
9242	uint32_t alloc_len, lun_datalen;
9243	int num_filled, well_known;
9244	uint32_t initidx, targ_lun_id, lun_id;
9245
9246	retval = CTL_RETVAL_COMPLETE;
9247	well_known = 0;
9248
9249	cdb = (struct scsi_report_luns *)ctsio->cdb;
9250
9251	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9252
9253	mtx_lock(&control_softc->ctl_lock);
9254	num_luns = control_softc->num_luns;
9255	mtx_unlock(&control_softc->ctl_lock);
9256
9257	switch (cdb->select_report) {
9258	case RPL_REPORT_DEFAULT:
9259	case RPL_REPORT_ALL:
9260		break;
9261	case RPL_REPORT_WELLKNOWN:
9262		well_known = 1;
9263		num_luns = 0;
9264		break;
9265	default:
9266		ctl_set_invalid_field(ctsio,
9267				      /*sks_valid*/ 1,
9268				      /*command*/ 1,
9269				      /*field*/ 2,
9270				      /*bit_valid*/ 0,
9271				      /*bit*/ 0);
9272		ctl_done((union ctl_io *)ctsio);
9273		return (retval);
9274		break; /* NOTREACHED */
9275	}
9276
9277	alloc_len = scsi_4btoul(cdb->length);
9278	/*
9279	 * The initiator has to allocate at least 16 bytes for this request,
9280	 * so he can at least get the header and the first LUN.  Otherwise
9281	 * we reject the request (per SPC-3 rev 14, section 6.21).
9282	 */
9283	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9284	    sizeof(struct scsi_report_luns_lundata))) {
9285		ctl_set_invalid_field(ctsio,
9286				      /*sks_valid*/ 1,
9287				      /*command*/ 1,
9288				      /*field*/ 6,
9289				      /*bit_valid*/ 0,
9290				      /*bit*/ 0);
9291		ctl_done((union ctl_io *)ctsio);
9292		return (retval);
9293	}
9294
9295	request_lun = (struct ctl_lun *)
9296		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9297
9298	lun_datalen = sizeof(*lun_data) +
9299		(num_luns * sizeof(struct scsi_report_luns_lundata));
9300
9301	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9302	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9303	ctsio->kern_sg_entries = 0;
9304
9305	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9306
9307	mtx_lock(&control_softc->ctl_lock);
9308	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9309		lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9310		if (lun_id >= CTL_MAX_LUNS)
9311			continue;
9312		lun = control_softc->ctl_luns[lun_id];
9313		if (lun == NULL)
9314			continue;
9315
9316		if (targ_lun_id <= 0xff) {
9317			/*
9318			 * Peripheral addressing method, bus number 0.
9319			 */
9320			lun_data->luns[num_filled].lundata[0] =
9321				RPL_LUNDATA_ATYP_PERIPH;
9322			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9323			num_filled++;
9324		} else if (targ_lun_id <= 0x3fff) {
9325			/*
9326			 * Flat addressing method.
9327			 */
9328			lun_data->luns[num_filled].lundata[0] =
9329				RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9330			lun_data->luns[num_filled].lundata[1] =
9331				(targ_lun_id & 0xff);
9332			num_filled++;
9333		} else if (targ_lun_id <= 0xffffff) {
9334			/*
9335			 * Extended flat addressing method.
9336			 */
9337			lun_data->luns[num_filled].lundata[0] =
9338			    RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9339			scsi_ulto3b(targ_lun_id,
9340			    &lun_data->luns[num_filled].lundata[1]);
9341			num_filled++;
9342		} else {
9343			printf("ctl_report_luns: bogus LUN number %jd, "
9344			       "skipping\n", (intmax_t)targ_lun_id);
9345		}
9346		/*
9347		 * According to SPC-3, rev 14 section 6.21:
9348		 *
9349		 * "The execution of a REPORT LUNS command to any valid and
9350		 * installed logical unit shall clear the REPORTED LUNS DATA
9351		 * HAS CHANGED unit attention condition for all logical
9352		 * units of that target with respect to the requesting
9353		 * initiator. A valid and installed logical unit is one
9354		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9355		 * INQUIRY data (see 6.4.2)."
9356		 *
9357		 * If request_lun is NULL, the LUN this report luns command
9358		 * was issued to is either disabled or doesn't exist. In that
9359		 * case, we shouldn't clear any pending lun change unit
9360		 * attention.
9361		 */
9362		if (request_lun != NULL) {
9363			mtx_lock(&lun->lun_lock);
9364			lun->pending_ua[initidx] &= ~CTL_UA_LUN_CHANGE;
9365			mtx_unlock(&lun->lun_lock);
9366		}
9367	}
9368	mtx_unlock(&control_softc->ctl_lock);
9369
9370	/*
9371	 * It's quite possible that we've returned fewer LUNs than we allocated
9372	 * space for.  Trim it.
9373	 */
9374	lun_datalen = sizeof(*lun_data) +
9375		(num_filled * sizeof(struct scsi_report_luns_lundata));
9376
9377	if (lun_datalen < alloc_len) {
9378		ctsio->residual = alloc_len - lun_datalen;
9379		ctsio->kern_data_len = lun_datalen;
9380		ctsio->kern_total_len = lun_datalen;
9381	} else {
9382		ctsio->residual = 0;
9383		ctsio->kern_data_len = alloc_len;
9384		ctsio->kern_total_len = alloc_len;
9385	}
9386	ctsio->kern_data_resid = 0;
9387	ctsio->kern_rel_offset = 0;
9388	ctsio->kern_sg_entries = 0;
9389
9390	/*
9391	 * We set this to the actual data length, regardless of how much
9392	 * space we actually have to return results.  If the user looks at
9393	 * this value, he'll know whether or not he allocated enough space
9394	 * and reissue the command if necessary.  We don't support well
9395	 * known logical units, so if the user asks for that, return none.
9396	 */
9397	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9398
9399	/*
9400	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9401	 * this request.
9402	 */
9403	ctl_set_success(ctsio);
9404	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9405	ctsio->be_move_done = ctl_config_move_done;
9406	ctl_datamove((union ctl_io *)ctsio);
9407	return (retval);
9408}
9409
9410int
9411ctl_request_sense(struct ctl_scsiio *ctsio)
9412{
9413	struct scsi_request_sense *cdb;
9414	struct scsi_sense_data *sense_ptr;
9415	struct ctl_lun *lun;
9416	uint32_t initidx;
9417	int have_error;
9418	scsi_sense_data_type sense_format;
9419
9420	cdb = (struct scsi_request_sense *)ctsio->cdb;
9421
9422	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9423
9424	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9425
9426	/*
9427	 * Determine which sense format the user wants.
9428	 */
9429	if (cdb->byte2 & SRS_DESC)
9430		sense_format = SSD_TYPE_DESC;
9431	else
9432		sense_format = SSD_TYPE_FIXED;
9433
9434	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9435	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9436	ctsio->kern_sg_entries = 0;
9437
9438	/*
9439	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9440	 * larger than the largest allowed value for the length field in the
9441	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9442	 */
9443	ctsio->residual = 0;
9444	ctsio->kern_data_len = cdb->length;
9445	ctsio->kern_total_len = cdb->length;
9446
9447	ctsio->kern_data_resid = 0;
9448	ctsio->kern_rel_offset = 0;
9449	ctsio->kern_sg_entries = 0;
9450
9451	/*
9452	 * If we don't have a LUN, we don't have any pending sense.
9453	 */
9454	if (lun == NULL)
9455		goto no_sense;
9456
9457	have_error = 0;
9458	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9459	/*
9460	 * Check for pending sense, and then for pending unit attentions.
9461	 * Pending sense gets returned first, then pending unit attentions.
9462	 */
9463	mtx_lock(&lun->lun_lock);
9464#ifdef CTL_WITH_CA
9465	if (ctl_is_set(lun->have_ca, initidx)) {
9466		scsi_sense_data_type stored_format;
9467
9468		/*
9469		 * Check to see which sense format was used for the stored
9470		 * sense data.
9471		 */
9472		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9473
9474		/*
9475		 * If the user requested a different sense format than the
9476		 * one we stored, then we need to convert it to the other
9477		 * format.  If we're going from descriptor to fixed format
9478		 * sense data, we may lose things in translation, depending
9479		 * on what options were used.
9480		 *
9481		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9482		 * for some reason we'll just copy it out as-is.
9483		 */
9484		if ((stored_format == SSD_TYPE_FIXED)
9485		 && (sense_format == SSD_TYPE_DESC))
9486			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9487			    &lun->pending_sense[initidx],
9488			    (struct scsi_sense_data_desc *)sense_ptr);
9489		else if ((stored_format == SSD_TYPE_DESC)
9490		      && (sense_format == SSD_TYPE_FIXED))
9491			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9492			    &lun->pending_sense[initidx],
9493			    (struct scsi_sense_data_fixed *)sense_ptr);
9494		else
9495			memcpy(sense_ptr, &lun->pending_sense[initidx],
9496			       ctl_min(sizeof(*sense_ptr),
9497			       sizeof(lun->pending_sense[initidx])));
9498
9499		ctl_clear_mask(lun->have_ca, initidx);
9500		have_error = 1;
9501	} else
9502#endif
9503	if (lun->pending_ua[initidx] != CTL_UA_NONE) {
9504		ctl_ua_type ua_type;
9505
9506		ua_type = ctl_build_ua(&lun->pending_ua[initidx],
9507				       sense_ptr, sense_format);
9508		if (ua_type != CTL_UA_NONE)
9509			have_error = 1;
9510	}
9511	mtx_unlock(&lun->lun_lock);
9512
9513	/*
9514	 * We already have a pending error, return it.
9515	 */
9516	if (have_error != 0) {
9517		/*
9518		 * We report the SCSI status as OK, since the status of the
9519		 * request sense command itself is OK.
9520		 * We report 0 for the sense length, because we aren't doing
9521		 * autosense in this case.  We're reporting sense as
9522		 * parameter data.
9523		 */
9524		ctl_set_success(ctsio);
9525		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9526		ctsio->be_move_done = ctl_config_move_done;
9527		ctl_datamove((union ctl_io *)ctsio);
9528		return (CTL_RETVAL_COMPLETE);
9529	}
9530
9531no_sense:
9532
9533	/*
9534	 * No sense information to report, so we report that everything is
9535	 * okay.
9536	 */
9537	ctl_set_sense_data(sense_ptr,
9538			   lun,
9539			   sense_format,
9540			   /*current_error*/ 1,
9541			   /*sense_key*/ SSD_KEY_NO_SENSE,
9542			   /*asc*/ 0x00,
9543			   /*ascq*/ 0x00,
9544			   SSD_ELEM_NONE);
9545
9546	/*
9547	 * We report 0 for the sense length, because we aren't doing
9548	 * autosense in this case.  We're reporting sense as parameter data.
9549	 */
9550	ctl_set_success(ctsio);
9551	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9552	ctsio->be_move_done = ctl_config_move_done;
9553	ctl_datamove((union ctl_io *)ctsio);
9554	return (CTL_RETVAL_COMPLETE);
9555}
9556
9557int
9558ctl_tur(struct ctl_scsiio *ctsio)
9559{
9560
9561	CTL_DEBUG_PRINT(("ctl_tur\n"));
9562
9563	ctl_set_success(ctsio);
9564	ctl_done((union ctl_io *)ctsio);
9565
9566	return (CTL_RETVAL_COMPLETE);
9567}
9568
9569#ifdef notyet
9570static int
9571ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9572{
9573
9574}
9575#endif
9576
9577static int
9578ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9579{
9580	struct scsi_vpd_supported_pages *pages;
9581	int sup_page_size;
9582	struct ctl_lun *lun;
9583
9584	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9585
9586	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9587	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9588	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9589	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9590	ctsio->kern_sg_entries = 0;
9591
9592	if (sup_page_size < alloc_len) {
9593		ctsio->residual = alloc_len - sup_page_size;
9594		ctsio->kern_data_len = sup_page_size;
9595		ctsio->kern_total_len = sup_page_size;
9596	} else {
9597		ctsio->residual = 0;
9598		ctsio->kern_data_len = alloc_len;
9599		ctsio->kern_total_len = alloc_len;
9600	}
9601	ctsio->kern_data_resid = 0;
9602	ctsio->kern_rel_offset = 0;
9603	ctsio->kern_sg_entries = 0;
9604
9605	/*
9606	 * The control device is always connected.  The disk device, on the
9607	 * other hand, may not be online all the time.  Need to change this
9608	 * to figure out whether the disk device is actually online or not.
9609	 */
9610	if (lun != NULL)
9611		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9612				lun->be_lun->lun_type;
9613	else
9614		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9615
9616	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9617	/* Supported VPD pages */
9618	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9619	/* Serial Number */
9620	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9621	/* Device Identification */
9622	pages->page_list[2] = SVPD_DEVICE_ID;
9623	/* Extended INQUIRY Data */
9624	pages->page_list[3] = SVPD_EXTENDED_INQUIRY_DATA;
9625	/* Mode Page Policy */
9626	pages->page_list[4] = SVPD_MODE_PAGE_POLICY;
9627	/* SCSI Ports */
9628	pages->page_list[5] = SVPD_SCSI_PORTS;
9629	/* Third-party Copy */
9630	pages->page_list[6] = SVPD_SCSI_TPC;
9631	/* Block limits */
9632	pages->page_list[7] = SVPD_BLOCK_LIMITS;
9633	/* Block Device Characteristics */
9634	pages->page_list[8] = SVPD_BDC;
9635	/* Logical Block Provisioning */
9636	pages->page_list[9] = SVPD_LBP;
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
9645static int
9646ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9647{
9648	struct scsi_vpd_unit_serial_number *sn_ptr;
9649	struct ctl_lun *lun;
9650	int data_len;
9651
9652	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9653
9654	data_len = 4 + CTL_SN_LEN;
9655	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9656	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9657	if (data_len < alloc_len) {
9658		ctsio->residual = alloc_len - data_len;
9659		ctsio->kern_data_len = data_len;
9660		ctsio->kern_total_len = data_len;
9661	} else {
9662		ctsio->residual = 0;
9663		ctsio->kern_data_len = alloc_len;
9664		ctsio->kern_total_len = alloc_len;
9665	}
9666	ctsio->kern_data_resid = 0;
9667	ctsio->kern_rel_offset = 0;
9668	ctsio->kern_sg_entries = 0;
9669
9670	/*
9671	 * The control device is always connected.  The disk device, on the
9672	 * other hand, may not be online all the time.  Need to change this
9673	 * to figure out whether the disk device is actually online or not.
9674	 */
9675	if (lun != NULL)
9676		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9677				  lun->be_lun->lun_type;
9678	else
9679		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9680
9681	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9682	sn_ptr->length = CTL_SN_LEN;
9683	/*
9684	 * If we don't have a LUN, we just leave the serial number as
9685	 * all spaces.
9686	 */
9687	if (lun != NULL) {
9688		strncpy((char *)sn_ptr->serial_num,
9689			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9690	} else
9691		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9692
9693	ctl_set_success(ctsio);
9694	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9695	ctsio->be_move_done = ctl_config_move_done;
9696	ctl_datamove((union ctl_io *)ctsio);
9697	return (CTL_RETVAL_COMPLETE);
9698}
9699
9700
9701static int
9702ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9703{
9704	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9705	struct ctl_lun *lun;
9706	int data_len;
9707
9708	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9709
9710	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9711	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9712	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9713	ctsio->kern_sg_entries = 0;
9714
9715	if (data_len < alloc_len) {
9716		ctsio->residual = alloc_len - data_len;
9717		ctsio->kern_data_len = data_len;
9718		ctsio->kern_total_len = data_len;
9719	} else {
9720		ctsio->residual = 0;
9721		ctsio->kern_data_len = alloc_len;
9722		ctsio->kern_total_len = alloc_len;
9723	}
9724	ctsio->kern_data_resid = 0;
9725	ctsio->kern_rel_offset = 0;
9726	ctsio->kern_sg_entries = 0;
9727
9728	/*
9729	 * The control device is always connected.  The disk device, on the
9730	 * other hand, may not be online all the time.
9731	 */
9732	if (lun != NULL)
9733		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9734				     lun->be_lun->lun_type;
9735	else
9736		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9737	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9738	eid_ptr->page_length = data_len - 4;
9739	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9740	eid_ptr->flags3 = SVPD_EID_V_SUP;
9741
9742	ctl_set_success(ctsio);
9743	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9744	ctsio->be_move_done = ctl_config_move_done;
9745	ctl_datamove((union ctl_io *)ctsio);
9746	return (CTL_RETVAL_COMPLETE);
9747}
9748
9749static int
9750ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9751{
9752	struct scsi_vpd_mode_page_policy *mpp_ptr;
9753	struct ctl_lun *lun;
9754	int data_len;
9755
9756	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9757
9758	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9759	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9760
9761	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9762	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9763	ctsio->kern_sg_entries = 0;
9764
9765	if (data_len < alloc_len) {
9766		ctsio->residual = alloc_len - data_len;
9767		ctsio->kern_data_len = data_len;
9768		ctsio->kern_total_len = data_len;
9769	} else {
9770		ctsio->residual = 0;
9771		ctsio->kern_data_len = alloc_len;
9772		ctsio->kern_total_len = alloc_len;
9773	}
9774	ctsio->kern_data_resid = 0;
9775	ctsio->kern_rel_offset = 0;
9776	ctsio->kern_sg_entries = 0;
9777
9778	/*
9779	 * The control device is always connected.  The disk device, on the
9780	 * other hand, may not be online all the time.
9781	 */
9782	if (lun != NULL)
9783		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9784				     lun->be_lun->lun_type;
9785	else
9786		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9787	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9788	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9789	mpp_ptr->descr[0].page_code = 0x3f;
9790	mpp_ptr->descr[0].subpage_code = 0xff;
9791	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9792
9793	ctl_set_success(ctsio);
9794	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9795	ctsio->be_move_done = ctl_config_move_done;
9796	ctl_datamove((union ctl_io *)ctsio);
9797	return (CTL_RETVAL_COMPLETE);
9798}
9799
9800static int
9801ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9802{
9803	struct scsi_vpd_device_id *devid_ptr;
9804	struct scsi_vpd_id_descriptor *desc;
9805	struct ctl_softc *ctl_softc;
9806	struct ctl_lun *lun;
9807	struct ctl_port *port;
9808	int data_len;
9809	uint8_t proto;
9810
9811	ctl_softc = control_softc;
9812
9813	port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
9814	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9815
9816	data_len = sizeof(struct scsi_vpd_device_id) +
9817	    sizeof(struct scsi_vpd_id_descriptor) +
9818		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9819	    sizeof(struct scsi_vpd_id_descriptor) +
9820		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9821	if (lun && lun->lun_devid)
9822		data_len += lun->lun_devid->len;
9823	if (port->port_devid)
9824		data_len += port->port_devid->len;
9825	if (port->target_devid)
9826		data_len += port->target_devid->len;
9827
9828	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9829	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9830	ctsio->kern_sg_entries = 0;
9831
9832	if (data_len < alloc_len) {
9833		ctsio->residual = alloc_len - data_len;
9834		ctsio->kern_data_len = data_len;
9835		ctsio->kern_total_len = data_len;
9836	} else {
9837		ctsio->residual = 0;
9838		ctsio->kern_data_len = alloc_len;
9839		ctsio->kern_total_len = alloc_len;
9840	}
9841	ctsio->kern_data_resid = 0;
9842	ctsio->kern_rel_offset = 0;
9843	ctsio->kern_sg_entries = 0;
9844
9845	/*
9846	 * The control device is always connected.  The disk device, on the
9847	 * other hand, may not be online all the time.
9848	 */
9849	if (lun != NULL)
9850		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9851				     lun->be_lun->lun_type;
9852	else
9853		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9854	devid_ptr->page_code = SVPD_DEVICE_ID;
9855	scsi_ulto2b(data_len - 4, devid_ptr->length);
9856
9857	if (port->port_type == CTL_PORT_FC)
9858		proto = SCSI_PROTO_FC << 4;
9859	else if (port->port_type == CTL_PORT_ISCSI)
9860		proto = SCSI_PROTO_ISCSI << 4;
9861	else
9862		proto = SCSI_PROTO_SPI << 4;
9863	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9864
9865	/*
9866	 * We're using a LUN association here.  i.e., this device ID is a
9867	 * per-LUN identifier.
9868	 */
9869	if (lun && lun->lun_devid) {
9870		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9871		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9872		    lun->lun_devid->len);
9873	}
9874
9875	/*
9876	 * This is for the WWPN which is a port association.
9877	 */
9878	if (port->port_devid) {
9879		memcpy(desc, port->port_devid->data, port->port_devid->len);
9880		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9881		    port->port_devid->len);
9882	}
9883
9884	/*
9885	 * This is for the Relative Target Port(type 4h) identifier
9886	 */
9887	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9888	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9889	    SVPD_ID_TYPE_RELTARG;
9890	desc->length = 4;
9891	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9892	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9893	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9894
9895	/*
9896	 * This is for the Target Port Group(type 5h) identifier
9897	 */
9898	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9899	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9900	    SVPD_ID_TYPE_TPORTGRP;
9901	desc->length = 4;
9902	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
9903	    &desc->identifier[2]);
9904	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9905	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9906
9907	/*
9908	 * This is for the Target identifier
9909	 */
9910	if (port->target_devid) {
9911		memcpy(desc, port->target_devid->data, port->target_devid->len);
9912	}
9913
9914	ctl_set_success(ctsio);
9915	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9916	ctsio->be_move_done = ctl_config_move_done;
9917	ctl_datamove((union ctl_io *)ctsio);
9918	return (CTL_RETVAL_COMPLETE);
9919}
9920
9921static int
9922ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9923{
9924	struct ctl_softc *softc = control_softc;
9925	struct scsi_vpd_scsi_ports *sp;
9926	struct scsi_vpd_port_designation *pd;
9927	struct scsi_vpd_port_designation_cont *pdc;
9928	struct ctl_lun *lun;
9929	struct ctl_port *port;
9930	int data_len, num_target_ports, iid_len, id_len, g, pg, p;
9931	int num_target_port_groups;
9932
9933	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9934
9935	if (softc->is_single)
9936		num_target_port_groups = 1;
9937	else
9938		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
9939	num_target_ports = 0;
9940	iid_len = 0;
9941	id_len = 0;
9942	mtx_lock(&softc->ctl_lock);
9943	STAILQ_FOREACH(port, &softc->port_list, links) {
9944		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9945			continue;
9946		if (lun != NULL &&
9947		    ctl_map_lun_back(port->targ_port, lun->lun) >=
9948		    CTL_MAX_LUNS)
9949			continue;
9950		num_target_ports++;
9951		if (port->init_devid)
9952			iid_len += port->init_devid->len;
9953		if (port->port_devid)
9954			id_len += port->port_devid->len;
9955	}
9956	mtx_unlock(&softc->ctl_lock);
9957
9958	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
9959	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9960	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9961	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9962	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9963	ctsio->kern_sg_entries = 0;
9964
9965	if (data_len < alloc_len) {
9966		ctsio->residual = alloc_len - data_len;
9967		ctsio->kern_data_len = data_len;
9968		ctsio->kern_total_len = data_len;
9969	} else {
9970		ctsio->residual = 0;
9971		ctsio->kern_data_len = alloc_len;
9972		ctsio->kern_total_len = alloc_len;
9973	}
9974	ctsio->kern_data_resid = 0;
9975	ctsio->kern_rel_offset = 0;
9976	ctsio->kern_sg_entries = 0;
9977
9978	/*
9979	 * The control device is always connected.  The disk device, on the
9980	 * other hand, may not be online all the time.  Need to change this
9981	 * to figure out whether the disk device is actually online or not.
9982	 */
9983	if (lun != NULL)
9984		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9985				  lun->be_lun->lun_type;
9986	else
9987		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9988
9989	sp->page_code = SVPD_SCSI_PORTS;
9990	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9991	    sp->page_length);
9992	pd = &sp->design[0];
9993
9994	mtx_lock(&softc->ctl_lock);
9995	pg = softc->port_offset / CTL_MAX_PORTS;
9996	for (g = 0; g < num_target_port_groups; g++) {
9997		STAILQ_FOREACH(port, &softc->port_list, links) {
9998			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9999				continue;
10000			if (lun != NULL &&
10001			    ctl_map_lun_back(port->targ_port, lun->lun) >=
10002			    CTL_MAX_LUNS)
10003				continue;
10004			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10005			scsi_ulto2b(p, pd->relative_port_id);
10006			if (port->init_devid && g == pg) {
10007				iid_len = port->init_devid->len;
10008				memcpy(pd->initiator_transportid,
10009				    port->init_devid->data, port->init_devid->len);
10010			} else
10011				iid_len = 0;
10012			scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10013			pdc = (struct scsi_vpd_port_designation_cont *)
10014			    (&pd->initiator_transportid[iid_len]);
10015			if (port->port_devid && g == pg) {
10016				id_len = port->port_devid->len;
10017				memcpy(pdc->target_port_descriptors,
10018				    port->port_devid->data, port->port_devid->len);
10019			} else
10020				id_len = 0;
10021			scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10022			pd = (struct scsi_vpd_port_designation *)
10023			    ((uint8_t *)pdc->target_port_descriptors + id_len);
10024		}
10025	}
10026	mtx_unlock(&softc->ctl_lock);
10027
10028	ctl_set_success(ctsio);
10029	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10030	ctsio->be_move_done = ctl_config_move_done;
10031	ctl_datamove((union ctl_io *)ctsio);
10032	return (CTL_RETVAL_COMPLETE);
10033}
10034
10035static int
10036ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10037{
10038	struct scsi_vpd_block_limits *bl_ptr;
10039	struct ctl_lun *lun;
10040	int bs;
10041
10042	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10043
10044	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10045	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10046	ctsio->kern_sg_entries = 0;
10047
10048	if (sizeof(*bl_ptr) < alloc_len) {
10049		ctsio->residual = alloc_len - sizeof(*bl_ptr);
10050		ctsio->kern_data_len = sizeof(*bl_ptr);
10051		ctsio->kern_total_len = sizeof(*bl_ptr);
10052	} else {
10053		ctsio->residual = 0;
10054		ctsio->kern_data_len = alloc_len;
10055		ctsio->kern_total_len = alloc_len;
10056	}
10057	ctsio->kern_data_resid = 0;
10058	ctsio->kern_rel_offset = 0;
10059	ctsio->kern_sg_entries = 0;
10060
10061	/*
10062	 * The control device is always connected.  The disk device, on the
10063	 * other hand, may not be online all the time.  Need to change this
10064	 * to figure out whether the disk device is actually online or not.
10065	 */
10066	if (lun != NULL)
10067		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10068				  lun->be_lun->lun_type;
10069	else
10070		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10071
10072	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10073	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10074	bl_ptr->max_cmp_write_len = 0xff;
10075	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10076	if (lun != NULL) {
10077		bs = lun->be_lun->blocksize;
10078		scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10079		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10080			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10081			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10082			if (lun->be_lun->pblockexp != 0) {
10083				scsi_ulto4b((1 << lun->be_lun->pblockexp),
10084				    bl_ptr->opt_unmap_grain);
10085				scsi_ulto4b(0x80000000 | lun->be_lun->pblockoff,
10086				    bl_ptr->unmap_grain_align);
10087			}
10088		}
10089		scsi_ulto4b(lun->be_lun->atomicblock,
10090		    bl_ptr->max_atomic_transfer_length);
10091		scsi_ulto4b(0, bl_ptr->atomic_alignment);
10092		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10093	}
10094	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10095
10096	ctl_set_success(ctsio);
10097	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10098	ctsio->be_move_done = ctl_config_move_done;
10099	ctl_datamove((union ctl_io *)ctsio);
10100	return (CTL_RETVAL_COMPLETE);
10101}
10102
10103static int
10104ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10105{
10106	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10107	struct ctl_lun *lun;
10108	const char *value;
10109	u_int i;
10110
10111	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10112
10113	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10114	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10115	ctsio->kern_sg_entries = 0;
10116
10117	if (sizeof(*bdc_ptr) < alloc_len) {
10118		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10119		ctsio->kern_data_len = sizeof(*bdc_ptr);
10120		ctsio->kern_total_len = sizeof(*bdc_ptr);
10121	} else {
10122		ctsio->residual = 0;
10123		ctsio->kern_data_len = alloc_len;
10124		ctsio->kern_total_len = alloc_len;
10125	}
10126	ctsio->kern_data_resid = 0;
10127	ctsio->kern_rel_offset = 0;
10128	ctsio->kern_sg_entries = 0;
10129
10130	/*
10131	 * The control device is always connected.  The disk device, on the
10132	 * other hand, may not be online all the time.  Need to change this
10133	 * to figure out whether the disk device is actually online or not.
10134	 */
10135	if (lun != NULL)
10136		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10137				  lun->be_lun->lun_type;
10138	else
10139		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10140	bdc_ptr->page_code = SVPD_BDC;
10141	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10142	if (lun != NULL &&
10143	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
10144		i = strtol(value, NULL, 0);
10145	else
10146		i = CTL_DEFAULT_ROTATION_RATE;
10147	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10148	if (lun != NULL &&
10149	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
10150		i = strtol(value, NULL, 0);
10151	else
10152		i = 0;
10153	bdc_ptr->wab_wac_ff = (i & 0x0f);
10154	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10155
10156	ctl_set_success(ctsio);
10157	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10158	ctsio->be_move_done = ctl_config_move_done;
10159	ctl_datamove((union ctl_io *)ctsio);
10160	return (CTL_RETVAL_COMPLETE);
10161}
10162
10163static int
10164ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10165{
10166	struct scsi_vpd_logical_block_prov *lbp_ptr;
10167	struct ctl_lun *lun;
10168
10169	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10170
10171	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10172	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10173	ctsio->kern_sg_entries = 0;
10174
10175	if (sizeof(*lbp_ptr) < alloc_len) {
10176		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10177		ctsio->kern_data_len = sizeof(*lbp_ptr);
10178		ctsio->kern_total_len = sizeof(*lbp_ptr);
10179	} else {
10180		ctsio->residual = 0;
10181		ctsio->kern_data_len = alloc_len;
10182		ctsio->kern_total_len = alloc_len;
10183	}
10184	ctsio->kern_data_resid = 0;
10185	ctsio->kern_rel_offset = 0;
10186	ctsio->kern_sg_entries = 0;
10187
10188	/*
10189	 * The control device is always connected.  The disk device, on the
10190	 * other hand, may not be online all the time.  Need to change this
10191	 * to figure out whether the disk device is actually online or not.
10192	 */
10193	if (lun != NULL)
10194		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10195				  lun->be_lun->lun_type;
10196	else
10197		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10198
10199	lbp_ptr->page_code = SVPD_LBP;
10200	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10201	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10202		lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10203		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10204		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10205		lbp_ptr->prov_type = SVPD_LBP_THIN;
10206	}
10207
10208	ctl_set_success(ctsio);
10209	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10210	ctsio->be_move_done = ctl_config_move_done;
10211	ctl_datamove((union ctl_io *)ctsio);
10212	return (CTL_RETVAL_COMPLETE);
10213}
10214
10215static int
10216ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10217{
10218	struct scsi_inquiry *cdb;
10219	int alloc_len, retval;
10220
10221	cdb = (struct scsi_inquiry *)ctsio->cdb;
10222
10223	retval = CTL_RETVAL_COMPLETE;
10224
10225	alloc_len = scsi_2btoul(cdb->length);
10226
10227	switch (cdb->page_code) {
10228	case SVPD_SUPPORTED_PAGES:
10229		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10230		break;
10231	case SVPD_UNIT_SERIAL_NUMBER:
10232		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10233		break;
10234	case SVPD_DEVICE_ID:
10235		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10236		break;
10237	case SVPD_EXTENDED_INQUIRY_DATA:
10238		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10239		break;
10240	case SVPD_MODE_PAGE_POLICY:
10241		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10242		break;
10243	case SVPD_SCSI_PORTS:
10244		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10245		break;
10246	case SVPD_SCSI_TPC:
10247		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10248		break;
10249	case SVPD_BLOCK_LIMITS:
10250		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10251		break;
10252	case SVPD_BDC:
10253		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10254		break;
10255	case SVPD_LBP:
10256		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10257		break;
10258	default:
10259		ctl_set_invalid_field(ctsio,
10260				      /*sks_valid*/ 1,
10261				      /*command*/ 1,
10262				      /*field*/ 2,
10263				      /*bit_valid*/ 0,
10264				      /*bit*/ 0);
10265		ctl_done((union ctl_io *)ctsio);
10266		retval = CTL_RETVAL_COMPLETE;
10267		break;
10268	}
10269
10270	return (retval);
10271}
10272
10273static int
10274ctl_inquiry_std(struct ctl_scsiio *ctsio)
10275{
10276	struct scsi_inquiry_data *inq_ptr;
10277	struct scsi_inquiry *cdb;
10278	struct ctl_softc *ctl_softc;
10279	struct ctl_lun *lun;
10280	char *val;
10281	uint32_t alloc_len, data_len;
10282	ctl_port_type port_type;
10283
10284	ctl_softc = control_softc;
10285
10286	/*
10287	 * Figure out whether we're talking to a Fibre Channel port or not.
10288	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10289	 * SCSI front ends.
10290	 */
10291	port_type = ctl_softc->ctl_ports[
10292	    ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10293	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10294		port_type = CTL_PORT_SCSI;
10295
10296	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10297	cdb = (struct scsi_inquiry *)ctsio->cdb;
10298	alloc_len = scsi_2btoul(cdb->length);
10299
10300	/*
10301	 * We malloc the full inquiry data size here and fill it
10302	 * in.  If the user only asks for less, we'll give him
10303	 * that much.
10304	 */
10305	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10306	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10307	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10308	ctsio->kern_sg_entries = 0;
10309	ctsio->kern_data_resid = 0;
10310	ctsio->kern_rel_offset = 0;
10311
10312	if (data_len < alloc_len) {
10313		ctsio->residual = alloc_len - data_len;
10314		ctsio->kern_data_len = data_len;
10315		ctsio->kern_total_len = data_len;
10316	} else {
10317		ctsio->residual = 0;
10318		ctsio->kern_data_len = alloc_len;
10319		ctsio->kern_total_len = alloc_len;
10320	}
10321
10322	/*
10323	 * If we have a LUN configured, report it as connected.  Otherwise,
10324	 * report that it is offline or no device is supported, depending
10325	 * on the value of inquiry_pq_no_lun.
10326	 *
10327	 * According to the spec (SPC-4 r34), the peripheral qualifier
10328	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10329	 *
10330	 * "A peripheral device having the specified peripheral device type
10331	 * is not connected to this logical unit. However, the device
10332	 * server is capable of supporting the specified peripheral device
10333	 * type on this logical unit."
10334	 *
10335	 * According to the same spec, the peripheral qualifier
10336	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10337	 *
10338	 * "The device server is not capable of supporting a peripheral
10339	 * device on this logical unit. For this peripheral qualifier the
10340	 * peripheral device type shall be set to 1Fh. All other peripheral
10341	 * device type values are reserved for this peripheral qualifier."
10342	 *
10343	 * Given the text, it would seem that we probably want to report that
10344	 * the LUN is offline here.  There is no LUN connected, but we can
10345	 * support a LUN at the given LUN number.
10346	 *
10347	 * In the real world, though, it sounds like things are a little
10348	 * different:
10349	 *
10350	 * - Linux, when presented with a LUN with the offline peripheral
10351	 *   qualifier, will create an sg driver instance for it.  So when
10352	 *   you attach it to CTL, you wind up with a ton of sg driver
10353	 *   instances.  (One for every LUN that Linux bothered to probe.)
10354	 *   Linux does this despite the fact that it issues a REPORT LUNs
10355	 *   to LUN 0 to get the inventory of supported LUNs.
10356	 *
10357	 * - There is other anecdotal evidence (from Emulex folks) about
10358	 *   arrays that use the offline peripheral qualifier for LUNs that
10359	 *   are on the "passive" path in an active/passive array.
10360	 *
10361	 * So the solution is provide a hopefully reasonable default
10362	 * (return bad/no LUN) and allow the user to change the behavior
10363	 * with a tunable/sysctl variable.
10364	 */
10365	if (lun != NULL)
10366		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10367				  lun->be_lun->lun_type;
10368	else if (ctl_softc->inquiry_pq_no_lun == 0)
10369		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10370	else
10371		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10372
10373	/* RMB in byte 2 is 0 */
10374	inq_ptr->version = SCSI_REV_SPC4;
10375
10376	/*
10377	 * According to SAM-3, even if a device only supports a single
10378	 * level of LUN addressing, it should still set the HISUP bit:
10379	 *
10380	 * 4.9.1 Logical unit numbers overview
10381	 *
10382	 * All logical unit number formats described in this standard are
10383	 * hierarchical in structure even when only a single level in that
10384	 * hierarchy is used. The HISUP bit shall be set to one in the
10385	 * standard INQUIRY data (see SPC-2) when any logical unit number
10386	 * format described in this standard is used.  Non-hierarchical
10387	 * formats are outside the scope of this standard.
10388	 *
10389	 * Therefore we set the HiSup bit here.
10390	 *
10391	 * The reponse format is 2, per SPC-3.
10392	 */
10393	inq_ptr->response_format = SID_HiSup | 2;
10394
10395	inq_ptr->additional_length = data_len -
10396	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10397	CTL_DEBUG_PRINT(("additional_length = %d\n",
10398			 inq_ptr->additional_length));
10399
10400	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10401	/* 16 bit addressing */
10402	if (port_type == CTL_PORT_SCSI)
10403		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10404	/* XXX set the SID_MultiP bit here if we're actually going to
10405	   respond on multiple ports */
10406	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10407
10408	/* 16 bit data bus, synchronous transfers */
10409	if (port_type == CTL_PORT_SCSI)
10410		inq_ptr->flags = SID_WBus16 | SID_Sync;
10411	/*
10412	 * XXX KDM do we want to support tagged queueing on the control
10413	 * device at all?
10414	 */
10415	if ((lun == NULL)
10416	 || (lun->be_lun->lun_type != T_PROCESSOR))
10417		inq_ptr->flags |= SID_CmdQue;
10418	/*
10419	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10420	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10421	 * name and 4 bytes for the revision.
10422	 */
10423	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10424	    "vendor")) == NULL) {
10425		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10426	} else {
10427		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10428		strncpy(inq_ptr->vendor, val,
10429		    min(sizeof(inq_ptr->vendor), strlen(val)));
10430	}
10431	if (lun == NULL) {
10432		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10433		    sizeof(inq_ptr->product));
10434	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10435		switch (lun->be_lun->lun_type) {
10436		case T_DIRECT:
10437			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10438			    sizeof(inq_ptr->product));
10439			break;
10440		case T_PROCESSOR:
10441			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10442			    sizeof(inq_ptr->product));
10443			break;
10444		default:
10445			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10446			    sizeof(inq_ptr->product));
10447			break;
10448		}
10449	} else {
10450		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10451		strncpy(inq_ptr->product, val,
10452		    min(sizeof(inq_ptr->product), strlen(val)));
10453	}
10454
10455	/*
10456	 * XXX make this a macro somewhere so it automatically gets
10457	 * incremented when we make changes.
10458	 */
10459	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10460	    "revision")) == NULL) {
10461		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10462	} else {
10463		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10464		strncpy(inq_ptr->revision, val,
10465		    min(sizeof(inq_ptr->revision), strlen(val)));
10466	}
10467
10468	/*
10469	 * For parallel SCSI, we support double transition and single
10470	 * transition clocking.  We also support QAS (Quick Arbitration
10471	 * and Selection) and Information Unit transfers on both the
10472	 * control and array devices.
10473	 */
10474	if (port_type == CTL_PORT_SCSI)
10475		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10476				    SID_SPI_IUS;
10477
10478	/* SAM-5 (no version claimed) */
10479	scsi_ulto2b(0x00A0, inq_ptr->version1);
10480	/* SPC-4 (no version claimed) */
10481	scsi_ulto2b(0x0460, inq_ptr->version2);
10482	if (port_type == CTL_PORT_FC) {
10483		/* FCP-2 ANSI INCITS.350:2003 */
10484		scsi_ulto2b(0x0917, inq_ptr->version3);
10485	} else if (port_type == CTL_PORT_SCSI) {
10486		/* SPI-4 ANSI INCITS.362:200x */
10487		scsi_ulto2b(0x0B56, inq_ptr->version3);
10488	} else if (port_type == CTL_PORT_ISCSI) {
10489		/* iSCSI (no version claimed) */
10490		scsi_ulto2b(0x0960, inq_ptr->version3);
10491	} else if (port_type == CTL_PORT_SAS) {
10492		/* SAS (no version claimed) */
10493		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10494	}
10495
10496	if (lun == NULL) {
10497		/* SBC-4 (no version claimed) */
10498		scsi_ulto2b(0x0600, inq_ptr->version4);
10499	} else {
10500		switch (lun->be_lun->lun_type) {
10501		case T_DIRECT:
10502			/* SBC-4 (no version claimed) */
10503			scsi_ulto2b(0x0600, inq_ptr->version4);
10504			break;
10505		case T_PROCESSOR:
10506		default:
10507			break;
10508		}
10509	}
10510
10511	ctl_set_success(ctsio);
10512	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10513	ctsio->be_move_done = ctl_config_move_done;
10514	ctl_datamove((union ctl_io *)ctsio);
10515	return (CTL_RETVAL_COMPLETE);
10516}
10517
10518int
10519ctl_inquiry(struct ctl_scsiio *ctsio)
10520{
10521	struct scsi_inquiry *cdb;
10522	int retval;
10523
10524	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10525
10526	cdb = (struct scsi_inquiry *)ctsio->cdb;
10527	if (cdb->byte2 & SI_EVPD)
10528		retval = ctl_inquiry_evpd(ctsio);
10529	else if (cdb->page_code == 0)
10530		retval = ctl_inquiry_std(ctsio);
10531	else {
10532		ctl_set_invalid_field(ctsio,
10533				      /*sks_valid*/ 1,
10534				      /*command*/ 1,
10535				      /*field*/ 2,
10536				      /*bit_valid*/ 0,
10537				      /*bit*/ 0);
10538		ctl_done((union ctl_io *)ctsio);
10539		return (CTL_RETVAL_COMPLETE);
10540	}
10541
10542	return (retval);
10543}
10544
10545/*
10546 * For known CDB types, parse the LBA and length.
10547 */
10548static int
10549ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10550{
10551	if (io->io_hdr.io_type != CTL_IO_SCSI)
10552		return (1);
10553
10554	switch (io->scsiio.cdb[0]) {
10555	case COMPARE_AND_WRITE: {
10556		struct scsi_compare_and_write *cdb;
10557
10558		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10559
10560		*lba = scsi_8btou64(cdb->addr);
10561		*len = cdb->length;
10562		break;
10563	}
10564	case READ_6:
10565	case WRITE_6: {
10566		struct scsi_rw_6 *cdb;
10567
10568		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10569
10570		*lba = scsi_3btoul(cdb->addr);
10571		/* only 5 bits are valid in the most significant address byte */
10572		*lba &= 0x1fffff;
10573		*len = cdb->length;
10574		break;
10575	}
10576	case READ_10:
10577	case WRITE_10: {
10578		struct scsi_rw_10 *cdb;
10579
10580		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10581
10582		*lba = scsi_4btoul(cdb->addr);
10583		*len = scsi_2btoul(cdb->length);
10584		break;
10585	}
10586	case WRITE_VERIFY_10: {
10587		struct scsi_write_verify_10 *cdb;
10588
10589		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10590
10591		*lba = scsi_4btoul(cdb->addr);
10592		*len = scsi_2btoul(cdb->length);
10593		break;
10594	}
10595	case READ_12:
10596	case WRITE_12: {
10597		struct scsi_rw_12 *cdb;
10598
10599		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10600
10601		*lba = scsi_4btoul(cdb->addr);
10602		*len = scsi_4btoul(cdb->length);
10603		break;
10604	}
10605	case WRITE_VERIFY_12: {
10606		struct scsi_write_verify_12 *cdb;
10607
10608		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10609
10610		*lba = scsi_4btoul(cdb->addr);
10611		*len = scsi_4btoul(cdb->length);
10612		break;
10613	}
10614	case READ_16:
10615	case WRITE_16:
10616	case WRITE_ATOMIC_16: {
10617		struct scsi_rw_16 *cdb;
10618
10619		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10620
10621		*lba = scsi_8btou64(cdb->addr);
10622		*len = scsi_4btoul(cdb->length);
10623		break;
10624	}
10625	case WRITE_VERIFY_16: {
10626		struct scsi_write_verify_16 *cdb;
10627
10628		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10629
10630		*lba = scsi_8btou64(cdb->addr);
10631		*len = scsi_4btoul(cdb->length);
10632		break;
10633	}
10634	case WRITE_SAME_10: {
10635		struct scsi_write_same_10 *cdb;
10636
10637		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10638
10639		*lba = scsi_4btoul(cdb->addr);
10640		*len = scsi_2btoul(cdb->length);
10641		break;
10642	}
10643	case WRITE_SAME_16: {
10644		struct scsi_write_same_16 *cdb;
10645
10646		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10647
10648		*lba = scsi_8btou64(cdb->addr);
10649		*len = scsi_4btoul(cdb->length);
10650		break;
10651	}
10652	case VERIFY_10: {
10653		struct scsi_verify_10 *cdb;
10654
10655		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10656
10657		*lba = scsi_4btoul(cdb->addr);
10658		*len = scsi_2btoul(cdb->length);
10659		break;
10660	}
10661	case VERIFY_12: {
10662		struct scsi_verify_12 *cdb;
10663
10664		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10665
10666		*lba = scsi_4btoul(cdb->addr);
10667		*len = scsi_4btoul(cdb->length);
10668		break;
10669	}
10670	case VERIFY_16: {
10671		struct scsi_verify_16 *cdb;
10672
10673		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10674
10675		*lba = scsi_8btou64(cdb->addr);
10676		*len = scsi_4btoul(cdb->length);
10677		break;
10678	}
10679	case UNMAP: {
10680		*lba = 0;
10681		*len = UINT64_MAX;
10682		break;
10683	}
10684	default:
10685		return (1);
10686		break; /* NOTREACHED */
10687	}
10688
10689	return (0);
10690}
10691
10692static ctl_action
10693ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2)
10694{
10695	uint64_t endlba1, endlba2;
10696
10697	endlba1 = lba1 + len1 - 1;
10698	endlba2 = lba2 + len2 - 1;
10699
10700	if ((endlba1 < lba2)
10701	 || (endlba2 < lba1))
10702		return (CTL_ACTION_PASS);
10703	else
10704		return (CTL_ACTION_BLOCK);
10705}
10706
10707static int
10708ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10709{
10710	struct ctl_ptr_len_flags *ptrlen;
10711	struct scsi_unmap_desc *buf, *end, *range;
10712	uint64_t lba;
10713	uint32_t len;
10714
10715	/* If not UNMAP -- go other way. */
10716	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10717	    io->scsiio.cdb[0] != UNMAP)
10718		return (CTL_ACTION_ERROR);
10719
10720	/* If UNMAP without data -- block and wait for data. */
10721	ptrlen = (struct ctl_ptr_len_flags *)
10722	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10723	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10724	    ptrlen->ptr == NULL)
10725		return (CTL_ACTION_BLOCK);
10726
10727	/* UNMAP with data -- check for collision. */
10728	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10729	end = buf + ptrlen->len / sizeof(*buf);
10730	for (range = buf; range < end; range++) {
10731		lba = scsi_8btou64(range->lba);
10732		len = scsi_4btoul(range->length);
10733		if ((lba < lba2 + len2) && (lba + len > lba2))
10734			return (CTL_ACTION_BLOCK);
10735	}
10736	return (CTL_ACTION_PASS);
10737}
10738
10739static ctl_action
10740ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10741{
10742	uint64_t lba1, lba2;
10743	uint64_t len1, len2;
10744	int retval;
10745
10746	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10747		return (CTL_ACTION_ERROR);
10748
10749	retval = ctl_extent_check_unmap(io2, lba1, len1);
10750	if (retval != CTL_ACTION_ERROR)
10751		return (retval);
10752
10753	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10754		return (CTL_ACTION_ERROR);
10755
10756	return (ctl_extent_check_lba(lba1, len1, lba2, len2));
10757}
10758
10759static ctl_action
10760ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10761    union ctl_io *ooa_io)
10762{
10763	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10764	ctl_serialize_action *serialize_row;
10765
10766	/*
10767	 * The initiator attempted multiple untagged commands at the same
10768	 * time.  Can't do that.
10769	 */
10770	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10771	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10772	 && ((pending_io->io_hdr.nexus.targ_port ==
10773	      ooa_io->io_hdr.nexus.targ_port)
10774	  && (pending_io->io_hdr.nexus.initid.id ==
10775	      ooa_io->io_hdr.nexus.initid.id))
10776	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10777		return (CTL_ACTION_OVERLAP);
10778
10779	/*
10780	 * The initiator attempted to send multiple tagged commands with
10781	 * the same ID.  (It's fine if different initiators have the same
10782	 * tag ID.)
10783	 *
10784	 * Even if all of those conditions are true, we don't kill the I/O
10785	 * if the command ahead of us has been aborted.  We won't end up
10786	 * sending it to the FETD, and it's perfectly legal to resend a
10787	 * command with the same tag number as long as the previous
10788	 * instance of this tag number has been aborted somehow.
10789	 */
10790	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10791	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10792	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10793	 && ((pending_io->io_hdr.nexus.targ_port ==
10794	      ooa_io->io_hdr.nexus.targ_port)
10795	  && (pending_io->io_hdr.nexus.initid.id ==
10796	      ooa_io->io_hdr.nexus.initid.id))
10797	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
10798		return (CTL_ACTION_OVERLAP_TAG);
10799
10800	/*
10801	 * If we get a head of queue tag, SAM-3 says that we should
10802	 * immediately execute it.
10803	 *
10804	 * What happens if this command would normally block for some other
10805	 * reason?  e.g. a request sense with a head of queue tag
10806	 * immediately after a write.  Normally that would block, but this
10807	 * will result in its getting executed immediately...
10808	 *
10809	 * We currently return "pass" instead of "skip", so we'll end up
10810	 * going through the rest of the queue to check for overlapped tags.
10811	 *
10812	 * XXX KDM check for other types of blockage first??
10813	 */
10814	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10815		return (CTL_ACTION_PASS);
10816
10817	/*
10818	 * Ordered tags have to block until all items ahead of them
10819	 * have completed.  If we get called with an ordered tag, we always
10820	 * block, if something else is ahead of us in the queue.
10821	 */
10822	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10823		return (CTL_ACTION_BLOCK);
10824
10825	/*
10826	 * Simple tags get blocked until all head of queue and ordered tags
10827	 * ahead of them have completed.  I'm lumping untagged commands in
10828	 * with simple tags here.  XXX KDM is that the right thing to do?
10829	 */
10830	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10831	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10832	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10833	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10834		return (CTL_ACTION_BLOCK);
10835
10836	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10837	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10838
10839	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10840
10841	switch (serialize_row[pending_entry->seridx]) {
10842	case CTL_SER_BLOCK:
10843		return (CTL_ACTION_BLOCK);
10844	case CTL_SER_EXTENT:
10845		return (ctl_extent_check(pending_io, ooa_io));
10846	case CTL_SER_EXTENTOPT:
10847		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10848		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10849			return (ctl_extent_check(pending_io, ooa_io));
10850		/* FALLTHROUGH */
10851	case CTL_SER_PASS:
10852		return (CTL_ACTION_PASS);
10853	case CTL_SER_BLOCKOPT:
10854		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10855		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10856			return (CTL_ACTION_BLOCK);
10857		return (CTL_ACTION_PASS);
10858	case CTL_SER_SKIP:
10859		return (CTL_ACTION_SKIP);
10860	default:
10861		panic("invalid serialization value %d",
10862		      serialize_row[pending_entry->seridx]);
10863	}
10864
10865	return (CTL_ACTION_ERROR);
10866}
10867
10868/*
10869 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10870 * Assumptions:
10871 * - pending_io is generally either incoming, or on the blocked queue
10872 * - starting I/O is the I/O we want to start the check with.
10873 */
10874static ctl_action
10875ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10876	      union ctl_io *starting_io)
10877{
10878	union ctl_io *ooa_io;
10879	ctl_action action;
10880
10881	mtx_assert(&lun->lun_lock, MA_OWNED);
10882
10883	/*
10884	 * Run back along the OOA queue, starting with the current
10885	 * blocked I/O and going through every I/O before it on the
10886	 * queue.  If starting_io is NULL, we'll just end up returning
10887	 * CTL_ACTION_PASS.
10888	 */
10889	for (ooa_io = starting_io; ooa_io != NULL;
10890	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10891	     ooa_links)){
10892
10893		/*
10894		 * This routine just checks to see whether
10895		 * cur_blocked is blocked by ooa_io, which is ahead
10896		 * of it in the queue.  It doesn't queue/dequeue
10897		 * cur_blocked.
10898		 */
10899		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10900		switch (action) {
10901		case CTL_ACTION_BLOCK:
10902		case CTL_ACTION_OVERLAP:
10903		case CTL_ACTION_OVERLAP_TAG:
10904		case CTL_ACTION_SKIP:
10905		case CTL_ACTION_ERROR:
10906			return (action);
10907			break; /* NOTREACHED */
10908		case CTL_ACTION_PASS:
10909			break;
10910		default:
10911			panic("invalid action %d", action);
10912			break;  /* NOTREACHED */
10913		}
10914	}
10915
10916	return (CTL_ACTION_PASS);
10917}
10918
10919/*
10920 * Assumptions:
10921 * - An I/O has just completed, and has been removed from the per-LUN OOA
10922 *   queue, so some items on the blocked queue may now be unblocked.
10923 */
10924static int
10925ctl_check_blocked(struct ctl_lun *lun)
10926{
10927	union ctl_io *cur_blocked, *next_blocked;
10928
10929	mtx_assert(&lun->lun_lock, MA_OWNED);
10930
10931	/*
10932	 * Run forward from the head of the blocked queue, checking each
10933	 * entry against the I/Os prior to it on the OOA queue to see if
10934	 * there is still any blockage.
10935	 *
10936	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10937	 * with our removing a variable on it while it is traversing the
10938	 * list.
10939	 */
10940	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10941	     cur_blocked != NULL; cur_blocked = next_blocked) {
10942		union ctl_io *prev_ooa;
10943		ctl_action action;
10944
10945		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10946							  blocked_links);
10947
10948		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10949						      ctl_ooaq, ooa_links);
10950
10951		/*
10952		 * If cur_blocked happens to be the first item in the OOA
10953		 * queue now, prev_ooa will be NULL, and the action
10954		 * returned will just be CTL_ACTION_PASS.
10955		 */
10956		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
10957
10958		switch (action) {
10959		case CTL_ACTION_BLOCK:
10960			/* Nothing to do here, still blocked */
10961			break;
10962		case CTL_ACTION_OVERLAP:
10963		case CTL_ACTION_OVERLAP_TAG:
10964			/*
10965			 * This shouldn't happen!  In theory we've already
10966			 * checked this command for overlap...
10967			 */
10968			break;
10969		case CTL_ACTION_PASS:
10970		case CTL_ACTION_SKIP: {
10971			struct ctl_softc *softc;
10972			const struct ctl_cmd_entry *entry;
10973			int isc_retval;
10974
10975			/*
10976			 * The skip case shouldn't happen, this transaction
10977			 * should have never made it onto the blocked queue.
10978			 */
10979			/*
10980			 * This I/O is no longer blocked, we can remove it
10981			 * from the blocked queue.  Since this is a TAILQ
10982			 * (doubly linked list), we can do O(1) removals
10983			 * from any place on the list.
10984			 */
10985			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
10986				     blocked_links);
10987			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
10988
10989			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
10990				/*
10991				 * Need to send IO back to original side to
10992				 * run
10993				 */
10994				union ctl_ha_msg msg_info;
10995
10996				msg_info.hdr.original_sc =
10997					cur_blocked->io_hdr.original_sc;
10998				msg_info.hdr.serializing_sc = cur_blocked;
10999				msg_info.hdr.msg_type = CTL_MSG_R2R;
11000				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11001				     &msg_info, sizeof(msg_info), 0)) >
11002				     CTL_HA_STATUS_SUCCESS) {
11003					printf("CTL:Check Blocked error from "
11004					       "ctl_ha_msg_send %d\n",
11005					       isc_retval);
11006				}
11007				break;
11008			}
11009			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11010			softc = control_softc;
11011
11012			/*
11013			 * Check this I/O for LUN state changes that may
11014			 * have happened while this command was blocked.
11015			 * The LUN state may have been changed by a command
11016			 * ahead of us in the queue, so we need to re-check
11017			 * for any states that can be caused by SCSI
11018			 * commands.
11019			 */
11020			if (ctl_scsiio_lun_check(softc, lun, entry,
11021						 &cur_blocked->scsiio) == 0) {
11022				cur_blocked->io_hdr.flags |=
11023				                      CTL_FLAG_IS_WAS_ON_RTR;
11024				ctl_enqueue_rtr(cur_blocked);
11025			} else
11026				ctl_done(cur_blocked);
11027			break;
11028		}
11029		default:
11030			/*
11031			 * This probably shouldn't happen -- we shouldn't
11032			 * get CTL_ACTION_ERROR, or anything else.
11033			 */
11034			break;
11035		}
11036	}
11037
11038	return (CTL_RETVAL_COMPLETE);
11039}
11040
11041/*
11042 * This routine (with one exception) checks LUN flags that can be set by
11043 * commands ahead of us in the OOA queue.  These flags have to be checked
11044 * when a command initially comes in, and when we pull a command off the
11045 * blocked queue and are preparing to execute it.  The reason we have to
11046 * check these flags for commands on the blocked queue is that the LUN
11047 * state may have been changed by a command ahead of us while we're on the
11048 * blocked queue.
11049 *
11050 * Ordering is somewhat important with these checks, so please pay
11051 * careful attention to the placement of any new checks.
11052 */
11053static int
11054ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11055    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11056{
11057	int retval;
11058	uint32_t residx;
11059
11060	retval = 0;
11061
11062	mtx_assert(&lun->lun_lock, MA_OWNED);
11063
11064	/*
11065	 * If this shelf is a secondary shelf controller, we have to reject
11066	 * any media access commands.
11067	 */
11068	if ((ctl_softc->flags & CTL_FLAG_ACTIVE_SHELF) == 0 &&
11069	    (entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0) {
11070		ctl_set_lun_standby(ctsio);
11071		retval = 1;
11072		goto bailout;
11073	}
11074
11075	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11076		if (lun->flags & CTL_LUN_READONLY) {
11077			ctl_set_sense(ctsio, /*current_error*/ 1,
11078			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11079			    /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11080			retval = 1;
11081			goto bailout;
11082		}
11083		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11084		    .eca_and_aen & SCP_SWP) != 0) {
11085			ctl_set_sense(ctsio, /*current_error*/ 1,
11086			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11087			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11088			retval = 1;
11089			goto bailout;
11090		}
11091	}
11092
11093	/*
11094	 * Check for a reservation conflict.  If this command isn't allowed
11095	 * even on reserved LUNs, and if this initiator isn't the one who
11096	 * reserved us, reject the command with a reservation conflict.
11097	 */
11098	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11099	if ((lun->flags & CTL_LUN_RESERVED)
11100	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11101		if (lun->res_idx != residx) {
11102			ctl_set_reservation_conflict(ctsio);
11103			retval = 1;
11104			goto bailout;
11105		}
11106	}
11107
11108	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11109	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11110		/* No reservation or command is allowed. */;
11111	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11112	    (lun->res_type == SPR_TYPE_WR_EX ||
11113	     lun->res_type == SPR_TYPE_WR_EX_RO ||
11114	     lun->res_type == SPR_TYPE_WR_EX_AR)) {
11115		/* The command is allowed for Write Exclusive resv. */;
11116	} else {
11117		/*
11118		 * if we aren't registered or it's a res holder type
11119		 * reservation and this isn't the res holder then set a
11120		 * conflict.
11121		 */
11122		if (lun->pr_keys[residx] == 0
11123		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11124			ctl_set_reservation_conflict(ctsio);
11125			retval = 1;
11126			goto bailout;
11127		}
11128
11129	}
11130
11131	if ((lun->flags & CTL_LUN_OFFLINE)
11132	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11133		ctl_set_lun_not_ready(ctsio);
11134		retval = 1;
11135		goto bailout;
11136	}
11137
11138	/*
11139	 * If the LUN is stopped, see if this particular command is allowed
11140	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11141	 */
11142	if ((lun->flags & CTL_LUN_STOPPED)
11143	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11144		/* "Logical unit not ready, initializing cmd. required" */
11145		ctl_set_lun_stopped(ctsio);
11146		retval = 1;
11147		goto bailout;
11148	}
11149
11150	if ((lun->flags & CTL_LUN_INOPERABLE)
11151	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11152		/* "Medium format corrupted" */
11153		ctl_set_medium_format_corrupted(ctsio);
11154		retval = 1;
11155		goto bailout;
11156	}
11157
11158bailout:
11159	return (retval);
11160
11161}
11162
11163static void
11164ctl_failover_io(union ctl_io *io, int have_lock)
11165{
11166	ctl_set_busy(&io->scsiio);
11167	ctl_done(io);
11168}
11169
11170static void
11171ctl_failover(void)
11172{
11173	struct ctl_lun *lun;
11174	struct ctl_softc *ctl_softc;
11175	union ctl_io *next_io, *pending_io;
11176	union ctl_io *io;
11177	int lun_idx;
11178	int i;
11179
11180	ctl_softc = control_softc;
11181
11182	mtx_lock(&ctl_softc->ctl_lock);
11183	/*
11184	 * Remove any cmds from the other SC from the rtr queue.  These
11185	 * will obviously only be for LUNs for which we're the primary.
11186	 * We can't send status or get/send data for these commands.
11187	 * Since they haven't been executed yet, we can just remove them.
11188	 * We'll either abort them or delete them below, depending on
11189	 * which HA mode we're in.
11190	 */
11191#ifdef notyet
11192	mtx_lock(&ctl_softc->queue_lock);
11193	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11194	     io != NULL; io = next_io) {
11195		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11196		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11197			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11198				      ctl_io_hdr, links);
11199	}
11200	mtx_unlock(&ctl_softc->queue_lock);
11201#endif
11202
11203	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11204		lun = ctl_softc->ctl_luns[lun_idx];
11205		if (lun==NULL)
11206			continue;
11207
11208		/*
11209		 * Processor LUNs are primary on both sides.
11210		 * XXX will this always be true?
11211		 */
11212		if (lun->be_lun->lun_type == T_PROCESSOR)
11213			continue;
11214
11215		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11216		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11217			printf("FAILOVER: primary lun %d\n", lun_idx);
11218		        /*
11219			 * Remove all commands from the other SC. First from the
11220			 * blocked queue then from the ooa queue. Once we have
11221			 * removed them. Call ctl_check_blocked to see if there
11222			 * is anything that can run.
11223			 */
11224			for (io = (union ctl_io *)TAILQ_FIRST(
11225			     &lun->blocked_queue); io != NULL; io = next_io) {
11226
11227		        	next_io = (union ctl_io *)TAILQ_NEXT(
11228				    &io->io_hdr, blocked_links);
11229
11230				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11231					TAILQ_REMOVE(&lun->blocked_queue,
11232						     &io->io_hdr,blocked_links);
11233					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11234					TAILQ_REMOVE(&lun->ooa_queue,
11235						     &io->io_hdr, ooa_links);
11236
11237					ctl_free_io(io);
11238				}
11239			}
11240
11241			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11242	     		     io != NULL; io = next_io) {
11243
11244		        	next_io = (union ctl_io *)TAILQ_NEXT(
11245				    &io->io_hdr, ooa_links);
11246
11247				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11248
11249					TAILQ_REMOVE(&lun->ooa_queue,
11250						&io->io_hdr,
11251					     	ooa_links);
11252
11253					ctl_free_io(io);
11254				}
11255			}
11256			ctl_check_blocked(lun);
11257		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11258			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11259
11260			printf("FAILOVER: primary lun %d\n", lun_idx);
11261			/*
11262			 * Abort all commands from the other SC.  We can't
11263			 * send status back for them now.  These should get
11264			 * cleaned up when they are completed or come out
11265			 * for a datamove operation.
11266			 */
11267			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11268	     		     io != NULL; io = next_io) {
11269		        	next_io = (union ctl_io *)TAILQ_NEXT(
11270					&io->io_hdr, ooa_links);
11271
11272				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11273					io->io_hdr.flags |= CTL_FLAG_ABORT;
11274			}
11275		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11276			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11277
11278			printf("FAILOVER: secondary lun %d\n", lun_idx);
11279
11280			lun->flags |= CTL_LUN_PRIMARY_SC;
11281
11282			/*
11283			 * We send all I/O that was sent to this controller
11284			 * and redirected to the other side back with
11285			 * busy status, and have the initiator retry it.
11286			 * Figuring out how much data has been transferred,
11287			 * etc. and picking up where we left off would be
11288			 * very tricky.
11289			 *
11290			 * XXX KDM need to remove I/O from the blocked
11291			 * queue as well!
11292			 */
11293			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11294			     &lun->ooa_queue); pending_io != NULL;
11295			     pending_io = next_io) {
11296
11297				next_io =  (union ctl_io *)TAILQ_NEXT(
11298					&pending_io->io_hdr, ooa_links);
11299
11300				pending_io->io_hdr.flags &=
11301					~CTL_FLAG_SENT_2OTHER_SC;
11302
11303				if (pending_io->io_hdr.flags &
11304				    CTL_FLAG_IO_ACTIVE) {
11305					pending_io->io_hdr.flags |=
11306						CTL_FLAG_FAILOVER;
11307				} else {
11308					ctl_set_busy(&pending_io->scsiio);
11309					ctl_done(pending_io);
11310				}
11311			}
11312
11313			/*
11314			 * Build Unit Attention
11315			 */
11316			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11317				lun->pending_ua[i] |=
11318				                     CTL_UA_ASYM_ACC_CHANGE;
11319			}
11320		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11321			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11322			printf("FAILOVER: secondary lun %d\n", lun_idx);
11323			/*
11324			 * if the first io on the OOA is not on the RtR queue
11325			 * add it.
11326			 */
11327			lun->flags |= CTL_LUN_PRIMARY_SC;
11328
11329			pending_io = (union ctl_io *)TAILQ_FIRST(
11330			    &lun->ooa_queue);
11331			if (pending_io==NULL) {
11332				printf("Nothing on OOA queue\n");
11333				continue;
11334			}
11335
11336			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11337			if ((pending_io->io_hdr.flags &
11338			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11339				pending_io->io_hdr.flags |=
11340				    CTL_FLAG_IS_WAS_ON_RTR;
11341				ctl_enqueue_rtr(pending_io);
11342			}
11343#if 0
11344			else
11345			{
11346				printf("Tag 0x%04x is running\n",
11347				      pending_io->scsiio.tag_num);
11348			}
11349#endif
11350
11351			next_io = (union ctl_io *)TAILQ_NEXT(
11352			    &pending_io->io_hdr, ooa_links);
11353			for (pending_io=next_io; pending_io != NULL;
11354			     pending_io = next_io) {
11355				pending_io->io_hdr.flags &=
11356				    ~CTL_FLAG_SENT_2OTHER_SC;
11357				next_io = (union ctl_io *)TAILQ_NEXT(
11358					&pending_io->io_hdr, ooa_links);
11359				if (pending_io->io_hdr.flags &
11360				    CTL_FLAG_IS_WAS_ON_RTR) {
11361#if 0
11362				        printf("Tag 0x%04x is running\n",
11363				      		pending_io->scsiio.tag_num);
11364#endif
11365					continue;
11366				}
11367
11368				switch (ctl_check_ooa(lun, pending_io,
11369			            (union ctl_io *)TAILQ_PREV(
11370				    &pending_io->io_hdr, ctl_ooaq,
11371				    ooa_links))) {
11372
11373				case CTL_ACTION_BLOCK:
11374					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11375							  &pending_io->io_hdr,
11376							  blocked_links);
11377					pending_io->io_hdr.flags |=
11378					    CTL_FLAG_BLOCKED;
11379					break;
11380				case CTL_ACTION_PASS:
11381				case CTL_ACTION_SKIP:
11382					pending_io->io_hdr.flags |=
11383					    CTL_FLAG_IS_WAS_ON_RTR;
11384					ctl_enqueue_rtr(pending_io);
11385					break;
11386				case CTL_ACTION_OVERLAP:
11387					ctl_set_overlapped_cmd(
11388					    (struct ctl_scsiio *)pending_io);
11389					ctl_done(pending_io);
11390					break;
11391				case CTL_ACTION_OVERLAP_TAG:
11392					ctl_set_overlapped_tag(
11393					    (struct ctl_scsiio *)pending_io,
11394					    pending_io->scsiio.tag_num & 0xff);
11395					ctl_done(pending_io);
11396					break;
11397				case CTL_ACTION_ERROR:
11398				default:
11399					ctl_set_internal_failure(
11400						(struct ctl_scsiio *)pending_io,
11401						0,  // sks_valid
11402						0); //retry count
11403					ctl_done(pending_io);
11404					break;
11405				}
11406			}
11407
11408			/*
11409			 * Build Unit Attention
11410			 */
11411			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11412				lun->pending_ua[i] |=
11413				                     CTL_UA_ASYM_ACC_CHANGE;
11414			}
11415		} else {
11416			panic("Unhandled HA mode failover, LUN flags = %#x, "
11417			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11418		}
11419	}
11420	ctl_pause_rtr = 0;
11421	mtx_unlock(&ctl_softc->ctl_lock);
11422}
11423
11424static int
11425ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11426{
11427	struct ctl_lun *lun;
11428	const struct ctl_cmd_entry *entry;
11429	uint32_t initidx, targ_lun;
11430	int retval;
11431
11432	retval = 0;
11433
11434	lun = NULL;
11435
11436	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11437	if ((targ_lun < CTL_MAX_LUNS)
11438	 && ((lun = ctl_softc->ctl_luns[targ_lun]) != NULL)) {
11439		/*
11440		 * If the LUN is invalid, pretend that it doesn't exist.
11441		 * It will go away as soon as all pending I/O has been
11442		 * completed.
11443		 */
11444		mtx_lock(&lun->lun_lock);
11445		if (lun->flags & CTL_LUN_DISABLED) {
11446			mtx_unlock(&lun->lun_lock);
11447			lun = NULL;
11448			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11449			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11450		} else {
11451			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11452			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11453				lun->be_lun;
11454			if (lun->be_lun->lun_type == T_PROCESSOR) {
11455				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11456			}
11457
11458			/*
11459			 * Every I/O goes into the OOA queue for a
11460			 * particular LUN, and stays there until completion.
11461			 */
11462			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11463			    ooa_links);
11464		}
11465	} else {
11466		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11467		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11468	}
11469
11470	/* Get command entry and return error if it is unsuppotyed. */
11471	entry = ctl_validate_command(ctsio);
11472	if (entry == NULL) {
11473		if (lun)
11474			mtx_unlock(&lun->lun_lock);
11475		return (retval);
11476	}
11477
11478	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11479	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11480
11481	/*
11482	 * Check to see whether we can send this command to LUNs that don't
11483	 * exist.  This should pretty much only be the case for inquiry
11484	 * and request sense.  Further checks, below, really require having
11485	 * a LUN, so we can't really check the command anymore.  Just put
11486	 * it on the rtr queue.
11487	 */
11488	if (lun == NULL) {
11489		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11490			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11491			ctl_enqueue_rtr((union ctl_io *)ctsio);
11492			return (retval);
11493		}
11494
11495		ctl_set_unsupported_lun(ctsio);
11496		ctl_done((union ctl_io *)ctsio);
11497		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11498		return (retval);
11499	} else {
11500		/*
11501		 * Make sure we support this particular command on this LUN.
11502		 * e.g., we don't support writes to the control LUN.
11503		 */
11504		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11505			mtx_unlock(&lun->lun_lock);
11506			ctl_set_invalid_opcode(ctsio);
11507			ctl_done((union ctl_io *)ctsio);
11508			return (retval);
11509		}
11510	}
11511
11512	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11513
11514#ifdef CTL_WITH_CA
11515	/*
11516	 * If we've got a request sense, it'll clear the contingent
11517	 * allegiance condition.  Otherwise, if we have a CA condition for
11518	 * this initiator, clear it, because it sent down a command other
11519	 * than request sense.
11520	 */
11521	if ((ctsio->cdb[0] != REQUEST_SENSE)
11522	 && (ctl_is_set(lun->have_ca, initidx)))
11523		ctl_clear_mask(lun->have_ca, initidx);
11524#endif
11525
11526	/*
11527	 * If the command has this flag set, it handles its own unit
11528	 * attention reporting, we shouldn't do anything.  Otherwise we
11529	 * check for any pending unit attentions, and send them back to the
11530	 * initiator.  We only do this when a command initially comes in,
11531	 * not when we pull it off the blocked queue.
11532	 *
11533	 * According to SAM-3, section 5.3.2, the order that things get
11534	 * presented back to the host is basically unit attentions caused
11535	 * by some sort of reset event, busy status, reservation conflicts
11536	 * or task set full, and finally any other status.
11537	 *
11538	 * One issue here is that some of the unit attentions we report
11539	 * don't fall into the "reset" category (e.g. "reported luns data
11540	 * has changed").  So reporting it here, before the reservation
11541	 * check, may be technically wrong.  I guess the only thing to do
11542	 * would be to check for and report the reset events here, and then
11543	 * check for the other unit attention types after we check for a
11544	 * reservation conflict.
11545	 *
11546	 * XXX KDM need to fix this
11547	 */
11548	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11549		ctl_ua_type ua_type;
11550
11551		if (lun->pending_ua[initidx] != CTL_UA_NONE) {
11552			scsi_sense_data_type sense_format;
11553
11554			if (lun != NULL)
11555				sense_format = (lun->flags &
11556				    CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11557				    SSD_TYPE_FIXED;
11558			else
11559				sense_format = SSD_TYPE_FIXED;
11560
11561			ua_type = ctl_build_ua(&lun->pending_ua[initidx],
11562			    &ctsio->sense_data, sense_format);
11563			if (ua_type != CTL_UA_NONE) {
11564				ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11565				ctsio->io_hdr.status = CTL_SCSI_ERROR |
11566						       CTL_AUTOSENSE;
11567				ctsio->sense_len = SSD_FULL_SIZE;
11568				mtx_unlock(&lun->lun_lock);
11569				ctl_done((union ctl_io *)ctsio);
11570				return (retval);
11571			}
11572		}
11573	}
11574
11575
11576	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11577		mtx_unlock(&lun->lun_lock);
11578		ctl_done((union ctl_io *)ctsio);
11579		return (retval);
11580	}
11581
11582	/*
11583	 * XXX CHD this is where we want to send IO to other side if
11584	 * this LUN is secondary on this SC. We will need to make a copy
11585	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11586	 * the copy we send as FROM_OTHER.
11587	 * We also need to stuff the address of the original IO so we can
11588	 * find it easily. Something similar will need be done on the other
11589	 * side so when we are done we can find the copy.
11590	 */
11591	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11592		union ctl_ha_msg msg_info;
11593		int isc_retval;
11594
11595		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11596
11597		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11598		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11599#if 0
11600		printf("1. ctsio %p\n", ctsio);
11601#endif
11602		msg_info.hdr.serializing_sc = NULL;
11603		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11604		msg_info.scsi.tag_num = ctsio->tag_num;
11605		msg_info.scsi.tag_type = ctsio->tag_type;
11606		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11607
11608		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11609
11610		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11611		    (void *)&msg_info, sizeof(msg_info), 0)) >
11612		    CTL_HA_STATUS_SUCCESS) {
11613			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11614			       isc_retval);
11615			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11616		} else {
11617#if 0
11618			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11619#endif
11620		}
11621
11622		/*
11623		 * XXX KDM this I/O is off the incoming queue, but hasn't
11624		 * been inserted on any other queue.  We may need to come
11625		 * up with a holding queue while we wait for serialization
11626		 * so that we have an idea of what we're waiting for from
11627		 * the other side.
11628		 */
11629		mtx_unlock(&lun->lun_lock);
11630		return (retval);
11631	}
11632
11633	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11634			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11635			      ctl_ooaq, ooa_links))) {
11636	case CTL_ACTION_BLOCK:
11637		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11638		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11639				  blocked_links);
11640		mtx_unlock(&lun->lun_lock);
11641		return (retval);
11642	case CTL_ACTION_PASS:
11643	case CTL_ACTION_SKIP:
11644		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11645		mtx_unlock(&lun->lun_lock);
11646		ctl_enqueue_rtr((union ctl_io *)ctsio);
11647		break;
11648	case CTL_ACTION_OVERLAP:
11649		mtx_unlock(&lun->lun_lock);
11650		ctl_set_overlapped_cmd(ctsio);
11651		ctl_done((union ctl_io *)ctsio);
11652		break;
11653	case CTL_ACTION_OVERLAP_TAG:
11654		mtx_unlock(&lun->lun_lock);
11655		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11656		ctl_done((union ctl_io *)ctsio);
11657		break;
11658	case CTL_ACTION_ERROR:
11659	default:
11660		mtx_unlock(&lun->lun_lock);
11661		ctl_set_internal_failure(ctsio,
11662					 /*sks_valid*/ 0,
11663					 /*retry_count*/ 0);
11664		ctl_done((union ctl_io *)ctsio);
11665		break;
11666	}
11667	return (retval);
11668}
11669
11670const struct ctl_cmd_entry *
11671ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11672{
11673	const struct ctl_cmd_entry *entry;
11674	int service_action;
11675
11676	entry = &ctl_cmd_table[ctsio->cdb[0]];
11677	if (sa)
11678		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11679	if (entry->flags & CTL_CMD_FLAG_SA5) {
11680		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11681		entry = &((const struct ctl_cmd_entry *)
11682		    entry->execute)[service_action];
11683	}
11684	return (entry);
11685}
11686
11687const struct ctl_cmd_entry *
11688ctl_validate_command(struct ctl_scsiio *ctsio)
11689{
11690	const struct ctl_cmd_entry *entry;
11691	int i, sa;
11692	uint8_t diff;
11693
11694	entry = ctl_get_cmd_entry(ctsio, &sa);
11695	if (entry->execute == NULL) {
11696		if (sa)
11697			ctl_set_invalid_field(ctsio,
11698					      /*sks_valid*/ 1,
11699					      /*command*/ 1,
11700					      /*field*/ 1,
11701					      /*bit_valid*/ 1,
11702					      /*bit*/ 4);
11703		else
11704			ctl_set_invalid_opcode(ctsio);
11705		ctl_done((union ctl_io *)ctsio);
11706		return (NULL);
11707	}
11708	KASSERT(entry->length > 0,
11709	    ("Not defined length for command 0x%02x/0x%02x",
11710	     ctsio->cdb[0], ctsio->cdb[1]));
11711	for (i = 1; i < entry->length; i++) {
11712		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11713		if (diff == 0)
11714			continue;
11715		ctl_set_invalid_field(ctsio,
11716				      /*sks_valid*/ 1,
11717				      /*command*/ 1,
11718				      /*field*/ i,
11719				      /*bit_valid*/ 1,
11720				      /*bit*/ fls(diff) - 1);
11721		ctl_done((union ctl_io *)ctsio);
11722		return (NULL);
11723	}
11724	return (entry);
11725}
11726
11727static int
11728ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11729{
11730
11731	switch (lun_type) {
11732	case T_PROCESSOR:
11733		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11734		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11735			return (0);
11736		break;
11737	case T_DIRECT:
11738		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11739		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11740			return (0);
11741		break;
11742	default:
11743		return (0);
11744	}
11745	return (1);
11746}
11747
11748static int
11749ctl_scsiio(struct ctl_scsiio *ctsio)
11750{
11751	int retval;
11752	const struct ctl_cmd_entry *entry;
11753
11754	retval = CTL_RETVAL_COMPLETE;
11755
11756	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11757
11758	entry = ctl_get_cmd_entry(ctsio, NULL);
11759
11760	/*
11761	 * If this I/O has been aborted, just send it straight to
11762	 * ctl_done() without executing it.
11763	 */
11764	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11765		ctl_done((union ctl_io *)ctsio);
11766		goto bailout;
11767	}
11768
11769	/*
11770	 * All the checks should have been handled by ctl_scsiio_precheck().
11771	 * We should be clear now to just execute the I/O.
11772	 */
11773	retval = entry->execute(ctsio);
11774
11775bailout:
11776	return (retval);
11777}
11778
11779/*
11780 * Since we only implement one target right now, a bus reset simply resets
11781 * our single target.
11782 */
11783static int
11784ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
11785{
11786	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
11787}
11788
11789static int
11790ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
11791		 ctl_ua_type ua_type)
11792{
11793	struct ctl_lun *lun;
11794	int retval;
11795
11796	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11797		union ctl_ha_msg msg_info;
11798
11799		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11800		msg_info.hdr.nexus = io->io_hdr.nexus;
11801		if (ua_type==CTL_UA_TARG_RESET)
11802			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11803		else
11804			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11805		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11806		msg_info.hdr.original_sc = NULL;
11807		msg_info.hdr.serializing_sc = NULL;
11808		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11809		    (void *)&msg_info, sizeof(msg_info), 0)) {
11810		}
11811	}
11812	retval = 0;
11813
11814	mtx_lock(&ctl_softc->ctl_lock);
11815	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
11816		retval += ctl_lun_reset(lun, io, ua_type);
11817	mtx_unlock(&ctl_softc->ctl_lock);
11818
11819	return (retval);
11820}
11821
11822/*
11823 * The LUN should always be set.  The I/O is optional, and is used to
11824 * distinguish between I/Os sent by this initiator, and by other
11825 * initiators.  We set unit attention for initiators other than this one.
11826 * SAM-3 is vague on this point.  It does say that a unit attention should
11827 * be established for other initiators when a LUN is reset (see section
11828 * 5.7.3), but it doesn't specifically say that the unit attention should
11829 * be established for this particular initiator when a LUN is reset.  Here
11830 * is the relevant text, from SAM-3 rev 8:
11831 *
11832 * 5.7.2 When a SCSI initiator port aborts its own tasks
11833 *
11834 * When a SCSI initiator port causes its own task(s) to be aborted, no
11835 * notification that the task(s) have been aborted shall be returned to
11836 * the SCSI initiator port other than the completion response for the
11837 * command or task management function action that caused the task(s) to
11838 * be aborted and notification(s) associated with related effects of the
11839 * action (e.g., a reset unit attention condition).
11840 *
11841 * XXX KDM for now, we're setting unit attention for all initiators.
11842 */
11843static int
11844ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11845{
11846	union ctl_io *xio;
11847#if 0
11848	uint32_t initidx;
11849#endif
11850	int i;
11851
11852	mtx_lock(&lun->lun_lock);
11853	/*
11854	 * Run through the OOA queue and abort each I/O.
11855	 */
11856#if 0
11857	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
11858#endif
11859	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11860	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11861		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11862	}
11863
11864	/*
11865	 * This version sets unit attention for every
11866	 */
11867#if 0
11868	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11869	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11870		if (initidx == i)
11871			continue;
11872		lun->pending_ua[i] |= ua_type;
11873	}
11874#endif
11875
11876	/*
11877	 * A reset (any kind, really) clears reservations established with
11878	 * RESERVE/RELEASE.  It does not clear reservations established
11879	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11880	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11881	 * reservations made with the RESERVE/RELEASE commands, because
11882	 * those commands are obsolete in SPC-3.
11883	 */
11884	lun->flags &= ~CTL_LUN_RESERVED;
11885
11886	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11887#ifdef CTL_WITH_CA
11888		ctl_clear_mask(lun->have_ca, i);
11889#endif
11890		lun->pending_ua[i] |= ua_type;
11891	}
11892	mtx_unlock(&lun->lun_lock);
11893
11894	return (0);
11895}
11896
11897static void
11898ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11899    int other_sc)
11900{
11901	union ctl_io *xio;
11902
11903	mtx_assert(&lun->lun_lock, MA_OWNED);
11904
11905	/*
11906	 * Run through the OOA queue and attempt to find the given I/O.
11907	 * The target port, initiator ID, tag type and tag number have to
11908	 * match the values that we got from the initiator.  If we have an
11909	 * untagged command to abort, simply abort the first untagged command
11910	 * we come to.  We only allow one untagged command at a time of course.
11911	 */
11912	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11913	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11914
11915		if ((targ_port == UINT32_MAX ||
11916		     targ_port == xio->io_hdr.nexus.targ_port) &&
11917		    (init_id == UINT32_MAX ||
11918		     init_id == xio->io_hdr.nexus.initid.id)) {
11919			if (targ_port != xio->io_hdr.nexus.targ_port ||
11920			    init_id != xio->io_hdr.nexus.initid.id)
11921				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11922			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11923			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11924				union ctl_ha_msg msg_info;
11925
11926				msg_info.hdr.nexus = xio->io_hdr.nexus;
11927				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11928				msg_info.task.tag_num = xio->scsiio.tag_num;
11929				msg_info.task.tag_type = xio->scsiio.tag_type;
11930				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11931				msg_info.hdr.original_sc = NULL;
11932				msg_info.hdr.serializing_sc = NULL;
11933				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11934				    (void *)&msg_info, sizeof(msg_info), 0);
11935			}
11936		}
11937	}
11938}
11939
11940static int
11941ctl_abort_task_set(union ctl_io *io)
11942{
11943	struct ctl_softc *softc = control_softc;
11944	struct ctl_lun *lun;
11945	uint32_t targ_lun;
11946
11947	/*
11948	 * Look up the LUN.
11949	 */
11950	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11951	mtx_lock(&softc->ctl_lock);
11952	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
11953		lun = softc->ctl_luns[targ_lun];
11954	else {
11955		mtx_unlock(&softc->ctl_lock);
11956		return (1);
11957	}
11958
11959	mtx_lock(&lun->lun_lock);
11960	mtx_unlock(&softc->ctl_lock);
11961	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11962		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11963		    io->io_hdr.nexus.initid.id,
11964		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11965	} else { /* CTL_TASK_CLEAR_TASK_SET */
11966		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11967		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11968	}
11969	mtx_unlock(&lun->lun_lock);
11970	return (0);
11971}
11972
11973static int
11974ctl_i_t_nexus_reset(union ctl_io *io)
11975{
11976	struct ctl_softc *softc = control_softc;
11977	struct ctl_lun *lun;
11978	uint32_t initidx, residx;
11979
11980	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11981	residx = ctl_get_resindex(&io->io_hdr.nexus);
11982	mtx_lock(&softc->ctl_lock);
11983	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11984		mtx_lock(&lun->lun_lock);
11985		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11986		    io->io_hdr.nexus.initid.id,
11987		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11988#ifdef CTL_WITH_CA
11989		ctl_clear_mask(lun->have_ca, initidx);
11990#endif
11991		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
11992			lun->flags &= ~CTL_LUN_RESERVED;
11993		lun->pending_ua[initidx] |= CTL_UA_I_T_NEXUS_LOSS;
11994		mtx_unlock(&lun->lun_lock);
11995	}
11996	mtx_unlock(&softc->ctl_lock);
11997	return (0);
11998}
11999
12000static int
12001ctl_abort_task(union ctl_io *io)
12002{
12003	union ctl_io *xio;
12004	struct ctl_lun *lun;
12005	struct ctl_softc *ctl_softc;
12006#if 0
12007	struct sbuf sb;
12008	char printbuf[128];
12009#endif
12010	int found;
12011	uint32_t targ_lun;
12012
12013	ctl_softc = control_softc;
12014	found = 0;
12015
12016	/*
12017	 * Look up the LUN.
12018	 */
12019	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12020	mtx_lock(&ctl_softc->ctl_lock);
12021	if ((targ_lun < CTL_MAX_LUNS)
12022	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12023		lun = ctl_softc->ctl_luns[targ_lun];
12024	else {
12025		mtx_unlock(&ctl_softc->ctl_lock);
12026		return (1);
12027	}
12028
12029#if 0
12030	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12031	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12032#endif
12033
12034	mtx_lock(&lun->lun_lock);
12035	mtx_unlock(&ctl_softc->ctl_lock);
12036	/*
12037	 * Run through the OOA queue and attempt to find the given I/O.
12038	 * The target port, initiator ID, tag type and tag number have to
12039	 * match the values that we got from the initiator.  If we have an
12040	 * untagged command to abort, simply abort the first untagged command
12041	 * we come to.  We only allow one untagged command at a time of course.
12042	 */
12043#if 0
12044	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12045#endif
12046	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12047	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12048#if 0
12049		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12050
12051		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12052			    lun->lun, xio->scsiio.tag_num,
12053			    xio->scsiio.tag_type,
12054			    (xio->io_hdr.blocked_links.tqe_prev
12055			    == NULL) ? "" : " BLOCKED",
12056			    (xio->io_hdr.flags &
12057			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12058			    (xio->io_hdr.flags &
12059			    CTL_FLAG_ABORT) ? " ABORT" : "",
12060			    (xio->io_hdr.flags &
12061			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12062		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12063		sbuf_finish(&sb);
12064		printf("%s\n", sbuf_data(&sb));
12065#endif
12066
12067		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12068		 && (xio->io_hdr.nexus.initid.id ==
12069		     io->io_hdr.nexus.initid.id)) {
12070			/*
12071			 * If the abort says that the task is untagged, the
12072			 * task in the queue must be untagged.  Otherwise,
12073			 * we just check to see whether the tag numbers
12074			 * match.  This is because the QLogic firmware
12075			 * doesn't pass back the tag type in an abort
12076			 * request.
12077			 */
12078#if 0
12079			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12080			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12081			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12082#endif
12083			/*
12084			 * XXX KDM we've got problems with FC, because it
12085			 * doesn't send down a tag type with aborts.  So we
12086			 * can only really go by the tag number...
12087			 * This may cause problems with parallel SCSI.
12088			 * Need to figure that out!!
12089			 */
12090			if (xio->scsiio.tag_num == io->taskio.tag_num) {
12091				xio->io_hdr.flags |= CTL_FLAG_ABORT;
12092				found = 1;
12093				if ((io->io_hdr.flags &
12094				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
12095				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12096					union ctl_ha_msg msg_info;
12097
12098					io->io_hdr.flags |=
12099					                CTL_FLAG_SENT_2OTHER_SC;
12100					msg_info.hdr.nexus = io->io_hdr.nexus;
12101					msg_info.task.task_action =
12102						CTL_TASK_ABORT_TASK;
12103					msg_info.task.tag_num =
12104						io->taskio.tag_num;
12105					msg_info.task.tag_type =
12106						io->taskio.tag_type;
12107					msg_info.hdr.msg_type =
12108						CTL_MSG_MANAGE_TASKS;
12109					msg_info.hdr.original_sc = NULL;
12110					msg_info.hdr.serializing_sc = NULL;
12111#if 0
12112					printf("Sent Abort to other side\n");
12113#endif
12114					if (CTL_HA_STATUS_SUCCESS !=
12115					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12116		    				(void *)&msg_info,
12117						sizeof(msg_info), 0)) {
12118					}
12119				}
12120#if 0
12121				printf("ctl_abort_task: found I/O to abort\n");
12122#endif
12123				break;
12124			}
12125		}
12126	}
12127	mtx_unlock(&lun->lun_lock);
12128
12129	if (found == 0) {
12130		/*
12131		 * This isn't really an error.  It's entirely possible for
12132		 * the abort and command completion to cross on the wire.
12133		 * This is more of an informative/diagnostic error.
12134		 */
12135#if 0
12136		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12137		       "%d:%d:%d:%d tag %d type %d\n",
12138		       io->io_hdr.nexus.initid.id,
12139		       io->io_hdr.nexus.targ_port,
12140		       io->io_hdr.nexus.targ_target.id,
12141		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12142		       io->taskio.tag_type);
12143#endif
12144	}
12145	return (0);
12146}
12147
12148static void
12149ctl_run_task(union ctl_io *io)
12150{
12151	struct ctl_softc *ctl_softc = control_softc;
12152	int retval = 1;
12153	const char *task_desc;
12154
12155	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12156
12157	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12158	    ("ctl_run_task: Unextected io_type %d\n",
12159	     io->io_hdr.io_type));
12160
12161	task_desc = ctl_scsi_task_string(&io->taskio);
12162	if (task_desc != NULL) {
12163#ifdef NEEDTOPORT
12164		csevent_log(CSC_CTL | CSC_SHELF_SW |
12165			    CTL_TASK_REPORT,
12166			    csevent_LogType_Trace,
12167			    csevent_Severity_Information,
12168			    csevent_AlertLevel_Green,
12169			    csevent_FRU_Firmware,
12170			    csevent_FRU_Unknown,
12171			    "CTL: received task: %s",task_desc);
12172#endif
12173	} else {
12174#ifdef NEEDTOPORT
12175		csevent_log(CSC_CTL | CSC_SHELF_SW |
12176			    CTL_TASK_REPORT,
12177			    csevent_LogType_Trace,
12178			    csevent_Severity_Information,
12179			    csevent_AlertLevel_Green,
12180			    csevent_FRU_Firmware,
12181			    csevent_FRU_Unknown,
12182			    "CTL: received unknown task "
12183			    "type: %d (%#x)",
12184			    io->taskio.task_action,
12185			    io->taskio.task_action);
12186#endif
12187	}
12188	switch (io->taskio.task_action) {
12189	case CTL_TASK_ABORT_TASK:
12190		retval = ctl_abort_task(io);
12191		break;
12192	case CTL_TASK_ABORT_TASK_SET:
12193	case CTL_TASK_CLEAR_TASK_SET:
12194		retval = ctl_abort_task_set(io);
12195		break;
12196	case CTL_TASK_CLEAR_ACA:
12197		break;
12198	case CTL_TASK_I_T_NEXUS_RESET:
12199		retval = ctl_i_t_nexus_reset(io);
12200		break;
12201	case CTL_TASK_LUN_RESET: {
12202		struct ctl_lun *lun;
12203		uint32_t targ_lun;
12204
12205		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12206		mtx_lock(&ctl_softc->ctl_lock);
12207		if ((targ_lun < CTL_MAX_LUNS)
12208		 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12209			lun = ctl_softc->ctl_luns[targ_lun];
12210		else {
12211			mtx_unlock(&ctl_softc->ctl_lock);
12212			retval = 1;
12213			break;
12214		}
12215
12216		if (!(io->io_hdr.flags &
12217		    CTL_FLAG_FROM_OTHER_SC)) {
12218			union ctl_ha_msg msg_info;
12219
12220			io->io_hdr.flags |=
12221				CTL_FLAG_SENT_2OTHER_SC;
12222			msg_info.hdr.msg_type =
12223				CTL_MSG_MANAGE_TASKS;
12224			msg_info.hdr.nexus = io->io_hdr.nexus;
12225			msg_info.task.task_action =
12226				CTL_TASK_LUN_RESET;
12227			msg_info.hdr.original_sc = NULL;
12228			msg_info.hdr.serializing_sc = NULL;
12229			if (CTL_HA_STATUS_SUCCESS !=
12230			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12231			    (void *)&msg_info,
12232			    sizeof(msg_info), 0)) {
12233			}
12234		}
12235
12236		retval = ctl_lun_reset(lun, io,
12237				       CTL_UA_LUN_RESET);
12238		mtx_unlock(&ctl_softc->ctl_lock);
12239		break;
12240	}
12241	case CTL_TASK_TARGET_RESET:
12242		retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12243		break;
12244	case CTL_TASK_BUS_RESET:
12245		retval = ctl_bus_reset(ctl_softc, io);
12246		break;
12247	case CTL_TASK_PORT_LOGIN:
12248		break;
12249	case CTL_TASK_PORT_LOGOUT:
12250		break;
12251	default:
12252		printf("ctl_run_task: got unknown task management event %d\n",
12253		       io->taskio.task_action);
12254		break;
12255	}
12256	if (retval == 0)
12257		io->io_hdr.status = CTL_SUCCESS;
12258	else
12259		io->io_hdr.status = CTL_ERROR;
12260	ctl_done(io);
12261}
12262
12263/*
12264 * For HA operation.  Handle commands that come in from the other
12265 * controller.
12266 */
12267static void
12268ctl_handle_isc(union ctl_io *io)
12269{
12270	int free_io;
12271	struct ctl_lun *lun;
12272	struct ctl_softc *ctl_softc;
12273	uint32_t targ_lun;
12274
12275	ctl_softc = control_softc;
12276
12277	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12278	lun = ctl_softc->ctl_luns[targ_lun];
12279
12280	switch (io->io_hdr.msg_type) {
12281	case CTL_MSG_SERIALIZE:
12282		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12283		break;
12284	case CTL_MSG_R2R: {
12285		const struct ctl_cmd_entry *entry;
12286
12287		/*
12288		 * This is only used in SER_ONLY mode.
12289		 */
12290		free_io = 0;
12291		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12292		mtx_lock(&lun->lun_lock);
12293		if (ctl_scsiio_lun_check(ctl_softc, lun,
12294		    entry, (struct ctl_scsiio *)io) != 0) {
12295			mtx_unlock(&lun->lun_lock);
12296			ctl_done(io);
12297			break;
12298		}
12299		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12300		mtx_unlock(&lun->lun_lock);
12301		ctl_enqueue_rtr(io);
12302		break;
12303	}
12304	case CTL_MSG_FINISH_IO:
12305		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12306			free_io = 0;
12307			ctl_done(io);
12308		} else {
12309			free_io = 1;
12310			mtx_lock(&lun->lun_lock);
12311			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12312				     ooa_links);
12313			ctl_check_blocked(lun);
12314			mtx_unlock(&lun->lun_lock);
12315		}
12316		break;
12317	case CTL_MSG_PERS_ACTION:
12318		ctl_hndl_per_res_out_on_other_sc(
12319			(union ctl_ha_msg *)&io->presio.pr_msg);
12320		free_io = 1;
12321		break;
12322	case CTL_MSG_BAD_JUJU:
12323		free_io = 0;
12324		ctl_done(io);
12325		break;
12326	case CTL_MSG_DATAMOVE:
12327		/* Only used in XFER mode */
12328		free_io = 0;
12329		ctl_datamove_remote(io);
12330		break;
12331	case CTL_MSG_DATAMOVE_DONE:
12332		/* Only used in XFER mode */
12333		free_io = 0;
12334		io->scsiio.be_move_done(io);
12335		break;
12336	default:
12337		free_io = 1;
12338		printf("%s: Invalid message type %d\n",
12339		       __func__, io->io_hdr.msg_type);
12340		break;
12341	}
12342	if (free_io)
12343		ctl_free_io(io);
12344
12345}
12346
12347
12348/*
12349 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12350 * there is no match.
12351 */
12352static ctl_lun_error_pattern
12353ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12354{
12355	const struct ctl_cmd_entry *entry;
12356	ctl_lun_error_pattern filtered_pattern, pattern;
12357
12358	pattern = desc->error_pattern;
12359
12360	/*
12361	 * XXX KDM we need more data passed into this function to match a
12362	 * custom pattern, and we actually need to implement custom pattern
12363	 * matching.
12364	 */
12365	if (pattern & CTL_LUN_PAT_CMD)
12366		return (CTL_LUN_PAT_CMD);
12367
12368	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12369		return (CTL_LUN_PAT_ANY);
12370
12371	entry = ctl_get_cmd_entry(ctsio, NULL);
12372
12373	filtered_pattern = entry->pattern & pattern;
12374
12375	/*
12376	 * If the user requested specific flags in the pattern (e.g.
12377	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12378	 * flags.
12379	 *
12380	 * If the user did not specify any flags, it doesn't matter whether
12381	 * or not the command supports the flags.
12382	 */
12383	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12384	     (pattern & ~CTL_LUN_PAT_MASK))
12385		return (CTL_LUN_PAT_NONE);
12386
12387	/*
12388	 * If the user asked for a range check, see if the requested LBA
12389	 * range overlaps with this command's LBA range.
12390	 */
12391	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12392		uint64_t lba1;
12393		uint64_t len1;
12394		ctl_action action;
12395		int retval;
12396
12397		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12398		if (retval != 0)
12399			return (CTL_LUN_PAT_NONE);
12400
12401		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12402					      desc->lba_range.len);
12403		/*
12404		 * A "pass" means that the LBA ranges don't overlap, so
12405		 * this doesn't match the user's range criteria.
12406		 */
12407		if (action == CTL_ACTION_PASS)
12408			return (CTL_LUN_PAT_NONE);
12409	}
12410
12411	return (filtered_pattern);
12412}
12413
12414static void
12415ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12416{
12417	struct ctl_error_desc *desc, *desc2;
12418
12419	mtx_assert(&lun->lun_lock, MA_OWNED);
12420
12421	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12422		ctl_lun_error_pattern pattern;
12423		/*
12424		 * Check to see whether this particular command matches
12425		 * the pattern in the descriptor.
12426		 */
12427		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12428		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12429			continue;
12430
12431		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12432		case CTL_LUN_INJ_ABORTED:
12433			ctl_set_aborted(&io->scsiio);
12434			break;
12435		case CTL_LUN_INJ_MEDIUM_ERR:
12436			ctl_set_medium_error(&io->scsiio);
12437			break;
12438		case CTL_LUN_INJ_UA:
12439			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12440			 * OCCURRED */
12441			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12442			break;
12443		case CTL_LUN_INJ_CUSTOM:
12444			/*
12445			 * We're assuming the user knows what he is doing.
12446			 * Just copy the sense information without doing
12447			 * checks.
12448			 */
12449			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12450			      ctl_min(sizeof(desc->custom_sense),
12451				      sizeof(io->scsiio.sense_data)));
12452			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12453			io->scsiio.sense_len = SSD_FULL_SIZE;
12454			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12455			break;
12456		case CTL_LUN_INJ_NONE:
12457		default:
12458			/*
12459			 * If this is an error injection type we don't know
12460			 * about, clear the continuous flag (if it is set)
12461			 * so it will get deleted below.
12462			 */
12463			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12464			break;
12465		}
12466		/*
12467		 * By default, each error injection action is a one-shot
12468		 */
12469		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12470			continue;
12471
12472		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12473
12474		free(desc, M_CTL);
12475	}
12476}
12477
12478#ifdef CTL_IO_DELAY
12479static void
12480ctl_datamove_timer_wakeup(void *arg)
12481{
12482	union ctl_io *io;
12483
12484	io = (union ctl_io *)arg;
12485
12486	ctl_datamove(io);
12487}
12488#endif /* CTL_IO_DELAY */
12489
12490void
12491ctl_datamove(union ctl_io *io)
12492{
12493	void (*fe_datamove)(union ctl_io *io);
12494
12495	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12496
12497	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12498
12499#ifdef CTL_TIME_IO
12500	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12501		char str[256];
12502		char path_str[64];
12503		struct sbuf sb;
12504
12505		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12506		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12507
12508		sbuf_cat(&sb, path_str);
12509		switch (io->io_hdr.io_type) {
12510		case CTL_IO_SCSI:
12511			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12512			sbuf_printf(&sb, "\n");
12513			sbuf_cat(&sb, path_str);
12514			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12515				    io->scsiio.tag_num, io->scsiio.tag_type);
12516			break;
12517		case CTL_IO_TASK:
12518			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12519				    "Tag Type: %d\n", io->taskio.task_action,
12520				    io->taskio.tag_num, io->taskio.tag_type);
12521			break;
12522		default:
12523			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12524			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12525			break;
12526		}
12527		sbuf_cat(&sb, path_str);
12528		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12529			    (intmax_t)time_uptime - io->io_hdr.start_time);
12530		sbuf_finish(&sb);
12531		printf("%s", sbuf_data(&sb));
12532	}
12533#endif /* CTL_TIME_IO */
12534
12535#ifdef CTL_IO_DELAY
12536	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12537		struct ctl_lun *lun;
12538
12539		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12540
12541		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12542	} else {
12543		struct ctl_lun *lun;
12544
12545		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12546		if ((lun != NULL)
12547		 && (lun->delay_info.datamove_delay > 0)) {
12548			struct callout *callout;
12549
12550			callout = (struct callout *)&io->io_hdr.timer_bytes;
12551			callout_init(callout, /*mpsafe*/ 1);
12552			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12553			callout_reset(callout,
12554				      lun->delay_info.datamove_delay * hz,
12555				      ctl_datamove_timer_wakeup, io);
12556			if (lun->delay_info.datamove_type ==
12557			    CTL_DELAY_TYPE_ONESHOT)
12558				lun->delay_info.datamove_delay = 0;
12559			return;
12560		}
12561	}
12562#endif
12563
12564	/*
12565	 * This command has been aborted.  Set the port status, so we fail
12566	 * the data move.
12567	 */
12568	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12569		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12570		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12571		       io->io_hdr.nexus.targ_port,
12572		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12573		       io->io_hdr.nexus.targ_lun);
12574		io->io_hdr.port_status = 31337;
12575		/*
12576		 * Note that the backend, in this case, will get the
12577		 * callback in its context.  In other cases it may get
12578		 * called in the frontend's interrupt thread context.
12579		 */
12580		io->scsiio.be_move_done(io);
12581		return;
12582	}
12583
12584	/* Don't confuse frontend with zero length data move. */
12585	if (io->scsiio.kern_data_len == 0) {
12586		io->scsiio.be_move_done(io);
12587		return;
12588	}
12589
12590	/*
12591	 * If we're in XFER mode and this I/O is from the other shelf
12592	 * controller, we need to send the DMA to the other side to
12593	 * actually transfer the data to/from the host.  In serialize only
12594	 * mode the transfer happens below CTL and ctl_datamove() is only
12595	 * called on the machine that originally received the I/O.
12596	 */
12597	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12598	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12599		union ctl_ha_msg msg;
12600		uint32_t sg_entries_sent;
12601		int do_sg_copy;
12602		int i;
12603
12604		memset(&msg, 0, sizeof(msg));
12605		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12606		msg.hdr.original_sc = io->io_hdr.original_sc;
12607		msg.hdr.serializing_sc = io;
12608		msg.hdr.nexus = io->io_hdr.nexus;
12609		msg.dt.flags = io->io_hdr.flags;
12610		/*
12611		 * We convert everything into a S/G list here.  We can't
12612		 * pass by reference, only by value between controllers.
12613		 * So we can't pass a pointer to the S/G list, only as many
12614		 * S/G entries as we can fit in here.  If it's possible for
12615		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12616		 * then we need to break this up into multiple transfers.
12617		 */
12618		if (io->scsiio.kern_sg_entries == 0) {
12619			msg.dt.kern_sg_entries = 1;
12620			/*
12621			 * If this is in cached memory, flush the cache
12622			 * before we send the DMA request to the other
12623			 * controller.  We want to do this in either the
12624			 * read or the write case.  The read case is
12625			 * straightforward.  In the write case, we want to
12626			 * make sure nothing is in the local cache that
12627			 * could overwrite the DMAed data.
12628			 */
12629			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12630				/*
12631				 * XXX KDM use bus_dmamap_sync() here.
12632				 */
12633			}
12634
12635			/*
12636			 * Convert to a physical address if this is a
12637			 * virtual address.
12638			 */
12639			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12640				msg.dt.sg_list[0].addr =
12641					io->scsiio.kern_data_ptr;
12642			} else {
12643				/*
12644				 * XXX KDM use busdma here!
12645				 */
12646#if 0
12647				msg.dt.sg_list[0].addr = (void *)
12648					vtophys(io->scsiio.kern_data_ptr);
12649#endif
12650			}
12651
12652			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12653			do_sg_copy = 0;
12654		} else {
12655			struct ctl_sg_entry *sgl;
12656
12657			do_sg_copy = 1;
12658			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12659			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12660			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12661				/*
12662				 * XXX KDM use bus_dmamap_sync() here.
12663				 */
12664			}
12665		}
12666
12667		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12668		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12669		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12670		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12671		msg.dt.sg_sequence = 0;
12672
12673		/*
12674		 * Loop until we've sent all of the S/G entries.  On the
12675		 * other end, we'll recompose these S/G entries into one
12676		 * contiguous list before passing it to the
12677		 */
12678		for (sg_entries_sent = 0; sg_entries_sent <
12679		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12680			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12681				sizeof(msg.dt.sg_list[0])),
12682				msg.dt.kern_sg_entries - sg_entries_sent);
12683
12684			if (do_sg_copy != 0) {
12685				struct ctl_sg_entry *sgl;
12686				int j;
12687
12688				sgl = (struct ctl_sg_entry *)
12689					io->scsiio.kern_data_ptr;
12690				/*
12691				 * If this is in cached memory, flush the cache
12692				 * before we send the DMA request to the other
12693				 * controller.  We want to do this in either
12694				 * the * read or the write case.  The read
12695				 * case is straightforward.  In the write
12696				 * case, we want to make sure nothing is
12697				 * in the local cache that could overwrite
12698				 * the DMAed data.
12699				 */
12700
12701				for (i = sg_entries_sent, j = 0;
12702				     i < msg.dt.cur_sg_entries; i++, j++) {
12703					if ((io->io_hdr.flags &
12704					     CTL_FLAG_NO_DATASYNC) == 0) {
12705						/*
12706						 * XXX KDM use bus_dmamap_sync()
12707						 */
12708					}
12709					if ((io->io_hdr.flags &
12710					     CTL_FLAG_BUS_ADDR) == 0) {
12711						/*
12712						 * XXX KDM use busdma.
12713						 */
12714#if 0
12715						msg.dt.sg_list[j].addr =(void *)
12716						       vtophys(sgl[i].addr);
12717#endif
12718					} else {
12719						msg.dt.sg_list[j].addr =
12720							sgl[i].addr;
12721					}
12722					msg.dt.sg_list[j].len = sgl[i].len;
12723				}
12724			}
12725
12726			sg_entries_sent += msg.dt.cur_sg_entries;
12727			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12728				msg.dt.sg_last = 1;
12729			else
12730				msg.dt.sg_last = 0;
12731
12732			/*
12733			 * XXX KDM drop and reacquire the lock here?
12734			 */
12735			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12736			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12737				/*
12738				 * XXX do something here.
12739				 */
12740			}
12741
12742			msg.dt.sent_sg_entries = sg_entries_sent;
12743		}
12744		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12745		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12746			ctl_failover_io(io, /*have_lock*/ 0);
12747
12748	} else {
12749
12750		/*
12751		 * Lookup the fe_datamove() function for this particular
12752		 * front end.
12753		 */
12754		fe_datamove =
12755		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12756
12757		fe_datamove(io);
12758	}
12759}
12760
12761static void
12762ctl_send_datamove_done(union ctl_io *io, int have_lock)
12763{
12764	union ctl_ha_msg msg;
12765	int isc_status;
12766
12767	memset(&msg, 0, sizeof(msg));
12768
12769	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12770	msg.hdr.original_sc = io;
12771	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12772	msg.hdr.nexus = io->io_hdr.nexus;
12773	msg.hdr.status = io->io_hdr.status;
12774	msg.scsi.tag_num = io->scsiio.tag_num;
12775	msg.scsi.tag_type = io->scsiio.tag_type;
12776	msg.scsi.scsi_status = io->scsiio.scsi_status;
12777	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12778	       sizeof(io->scsiio.sense_data));
12779	msg.scsi.sense_len = io->scsiio.sense_len;
12780	msg.scsi.sense_residual = io->scsiio.sense_residual;
12781	msg.scsi.fetd_status = io->io_hdr.port_status;
12782	msg.scsi.residual = io->scsiio.residual;
12783	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12784
12785	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12786		ctl_failover_io(io, /*have_lock*/ have_lock);
12787		return;
12788	}
12789
12790	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
12791	if (isc_status > CTL_HA_STATUS_SUCCESS) {
12792		/* XXX do something if this fails */
12793	}
12794
12795}
12796
12797/*
12798 * The DMA to the remote side is done, now we need to tell the other side
12799 * we're done so it can continue with its data movement.
12800 */
12801static void
12802ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12803{
12804	union ctl_io *io;
12805
12806	io = rq->context;
12807
12808	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12809		printf("%s: ISC DMA write failed with error %d", __func__,
12810		       rq->ret);
12811		ctl_set_internal_failure(&io->scsiio,
12812					 /*sks_valid*/ 1,
12813					 /*retry_count*/ rq->ret);
12814	}
12815
12816	ctl_dt_req_free(rq);
12817
12818	/*
12819	 * In this case, we had to malloc the memory locally.  Free it.
12820	 */
12821	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12822		int i;
12823		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12824			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12825	}
12826	/*
12827	 * The data is in local and remote memory, so now we need to send
12828	 * status (good or back) back to the other side.
12829	 */
12830	ctl_send_datamove_done(io, /*have_lock*/ 0);
12831}
12832
12833/*
12834 * We've moved the data from the host/controller into local memory.  Now we
12835 * need to push it over to the remote controller's memory.
12836 */
12837static int
12838ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12839{
12840	int retval;
12841
12842	retval = 0;
12843
12844	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12845					  ctl_datamove_remote_write_cb);
12846
12847	return (retval);
12848}
12849
12850static void
12851ctl_datamove_remote_write(union ctl_io *io)
12852{
12853	int retval;
12854	void (*fe_datamove)(union ctl_io *io);
12855
12856	/*
12857	 * - Get the data from the host/HBA into local memory.
12858	 * - DMA memory from the local controller to the remote controller.
12859	 * - Send status back to the remote controller.
12860	 */
12861
12862	retval = ctl_datamove_remote_sgl_setup(io);
12863	if (retval != 0)
12864		return;
12865
12866	/* Switch the pointer over so the FETD knows what to do */
12867	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12868
12869	/*
12870	 * Use a custom move done callback, since we need to send completion
12871	 * back to the other controller, not to the backend on this side.
12872	 */
12873	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12874
12875	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12876
12877	fe_datamove(io);
12878
12879	return;
12880
12881}
12882
12883static int
12884ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12885{
12886#if 0
12887	char str[256];
12888	char path_str[64];
12889	struct sbuf sb;
12890#endif
12891
12892	/*
12893	 * In this case, we had to malloc the memory locally.  Free it.
12894	 */
12895	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
12896		int i;
12897		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12898			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12899	}
12900
12901#if 0
12902	scsi_path_string(io, path_str, sizeof(path_str));
12903	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12904	sbuf_cat(&sb, path_str);
12905	scsi_command_string(&io->scsiio, NULL, &sb);
12906	sbuf_printf(&sb, "\n");
12907	sbuf_cat(&sb, path_str);
12908	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12909		    io->scsiio.tag_num, io->scsiio.tag_type);
12910	sbuf_cat(&sb, path_str);
12911	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12912		    io->io_hdr.flags, io->io_hdr.status);
12913	sbuf_finish(&sb);
12914	printk("%s", sbuf_data(&sb));
12915#endif
12916
12917
12918	/*
12919	 * The read is done, now we need to send status (good or bad) back
12920	 * to the other side.
12921	 */
12922	ctl_send_datamove_done(io, /*have_lock*/ 0);
12923
12924	return (0);
12925}
12926
12927static void
12928ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12929{
12930	union ctl_io *io;
12931	void (*fe_datamove)(union ctl_io *io);
12932
12933	io = rq->context;
12934
12935	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12936		printf("%s: ISC DMA read failed with error %d", __func__,
12937		       rq->ret);
12938		ctl_set_internal_failure(&io->scsiio,
12939					 /*sks_valid*/ 1,
12940					 /*retry_count*/ rq->ret);
12941	}
12942
12943	ctl_dt_req_free(rq);
12944
12945	/* Switch the pointer over so the FETD knows what to do */
12946	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12947
12948	/*
12949	 * Use a custom move done callback, since we need to send completion
12950	 * back to the other controller, not to the backend on this side.
12951	 */
12952	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12953
12954	/* XXX KDM add checks like the ones in ctl_datamove? */
12955
12956	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
12957
12958	fe_datamove(io);
12959}
12960
12961static int
12962ctl_datamove_remote_sgl_setup(union ctl_io *io)
12963{
12964	struct ctl_sg_entry *local_sglist, *remote_sglist;
12965	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
12966	struct ctl_softc *softc;
12967	int retval;
12968	int i;
12969
12970	retval = 0;
12971	softc = control_softc;
12972
12973	local_sglist = io->io_hdr.local_sglist;
12974	local_dma_sglist = io->io_hdr.local_dma_sglist;
12975	remote_sglist = io->io_hdr.remote_sglist;
12976	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
12977
12978	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
12979		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
12980			local_sglist[i].len = remote_sglist[i].len;
12981
12982			/*
12983			 * XXX Detect the situation where the RS-level I/O
12984			 * redirector on the other side has already read the
12985			 * data off of the AOR RS on this side, and
12986			 * transferred it to remote (mirror) memory on the
12987			 * other side.  Since we already have the data in
12988			 * memory here, we just need to use it.
12989			 *
12990			 * XXX KDM this can probably be removed once we
12991			 * get the cache device code in and take the
12992			 * current AOR implementation out.
12993			 */
12994#ifdef NEEDTOPORT
12995			if ((remote_sglist[i].addr >=
12996			     (void *)vtophys(softc->mirr->addr))
12997			 && (remote_sglist[i].addr <
12998			     ((void *)vtophys(softc->mirr->addr) +
12999			     CacheMirrorOffset))) {
13000				local_sglist[i].addr = remote_sglist[i].addr -
13001					CacheMirrorOffset;
13002				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13003				     CTL_FLAG_DATA_IN)
13004					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13005			} else {
13006				local_sglist[i].addr = remote_sglist[i].addr +
13007					CacheMirrorOffset;
13008			}
13009#endif
13010#if 0
13011			printf("%s: local %p, remote %p, len %d\n",
13012			       __func__, local_sglist[i].addr,
13013			       remote_sglist[i].addr, local_sglist[i].len);
13014#endif
13015		}
13016	} else {
13017		uint32_t len_to_go;
13018
13019		/*
13020		 * In this case, we don't have automatically allocated
13021		 * memory for this I/O on this controller.  This typically
13022		 * happens with internal CTL I/O -- e.g. inquiry, mode
13023		 * sense, etc.  Anything coming from RAIDCore will have
13024		 * a mirror area available.
13025		 */
13026		len_to_go = io->scsiio.kern_data_len;
13027
13028		/*
13029		 * Clear the no datasync flag, we have to use malloced
13030		 * buffers.
13031		 */
13032		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13033
13034		/*
13035		 * The difficult thing here is that the size of the various
13036		 * S/G segments may be different than the size from the
13037		 * remote controller.  That'll make it harder when DMAing
13038		 * the data back to the other side.
13039		 */
13040		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13041		     sizeof(io->io_hdr.remote_sglist[0])) &&
13042		     (len_to_go > 0); i++) {
13043			local_sglist[i].len = ctl_min(len_to_go, 131072);
13044			CTL_SIZE_8B(local_dma_sglist[i].len,
13045				    local_sglist[i].len);
13046			local_sglist[i].addr =
13047				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13048
13049			local_dma_sglist[i].addr = local_sglist[i].addr;
13050
13051			if (local_sglist[i].addr == NULL) {
13052				int j;
13053
13054				printf("malloc failed for %zd bytes!",
13055				       local_dma_sglist[i].len);
13056				for (j = 0; j < i; j++) {
13057					free(local_sglist[j].addr, M_CTL);
13058				}
13059				ctl_set_internal_failure(&io->scsiio,
13060							 /*sks_valid*/ 1,
13061							 /*retry_count*/ 4857);
13062				retval = 1;
13063				goto bailout_error;
13064
13065			}
13066			/* XXX KDM do we need a sync here? */
13067
13068			len_to_go -= local_sglist[i].len;
13069		}
13070		/*
13071		 * Reset the number of S/G entries accordingly.  The
13072		 * original number of S/G entries is available in
13073		 * rem_sg_entries.
13074		 */
13075		io->scsiio.kern_sg_entries = i;
13076
13077#if 0
13078		printf("%s: kern_sg_entries = %d\n", __func__,
13079		       io->scsiio.kern_sg_entries);
13080		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13081			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13082			       local_sglist[i].addr, local_sglist[i].len,
13083			       local_dma_sglist[i].len);
13084#endif
13085	}
13086
13087
13088	return (retval);
13089
13090bailout_error:
13091
13092	ctl_send_datamove_done(io, /*have_lock*/ 0);
13093
13094	return (retval);
13095}
13096
13097static int
13098ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13099			 ctl_ha_dt_cb callback)
13100{
13101	struct ctl_ha_dt_req *rq;
13102	struct ctl_sg_entry *remote_sglist, *local_sglist;
13103	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13104	uint32_t local_used, remote_used, total_used;
13105	int retval;
13106	int i, j;
13107
13108	retval = 0;
13109
13110	rq = ctl_dt_req_alloc();
13111
13112	/*
13113	 * If we failed to allocate the request, and if the DMA didn't fail
13114	 * anyway, set busy status.  This is just a resource allocation
13115	 * failure.
13116	 */
13117	if ((rq == NULL)
13118	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13119		ctl_set_busy(&io->scsiio);
13120
13121	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13122
13123		if (rq != NULL)
13124			ctl_dt_req_free(rq);
13125
13126		/*
13127		 * The data move failed.  We need to return status back
13128		 * to the other controller.  No point in trying to DMA
13129		 * data to the remote controller.
13130		 */
13131
13132		ctl_send_datamove_done(io, /*have_lock*/ 0);
13133
13134		retval = 1;
13135
13136		goto bailout;
13137	}
13138
13139	local_sglist = io->io_hdr.local_sglist;
13140	local_dma_sglist = io->io_hdr.local_dma_sglist;
13141	remote_sglist = io->io_hdr.remote_sglist;
13142	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13143	local_used = 0;
13144	remote_used = 0;
13145	total_used = 0;
13146
13147	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13148		rq->ret = CTL_HA_STATUS_SUCCESS;
13149		rq->context = io;
13150		callback(rq);
13151		goto bailout;
13152	}
13153
13154	/*
13155	 * Pull/push the data over the wire from/to the other controller.
13156	 * This takes into account the possibility that the local and
13157	 * remote sglists may not be identical in terms of the size of
13158	 * the elements and the number of elements.
13159	 *
13160	 * One fundamental assumption here is that the length allocated for
13161	 * both the local and remote sglists is identical.  Otherwise, we've
13162	 * essentially got a coding error of some sort.
13163	 */
13164	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13165		int isc_ret;
13166		uint32_t cur_len, dma_length;
13167		uint8_t *tmp_ptr;
13168
13169		rq->id = CTL_HA_DATA_CTL;
13170		rq->command = command;
13171		rq->context = io;
13172
13173		/*
13174		 * Both pointers should be aligned.  But it is possible
13175		 * that the allocation length is not.  They should both
13176		 * also have enough slack left over at the end, though,
13177		 * to round up to the next 8 byte boundary.
13178		 */
13179		cur_len = ctl_min(local_sglist[i].len - local_used,
13180				  remote_sglist[j].len - remote_used);
13181
13182		/*
13183		 * In this case, we have a size issue and need to decrease
13184		 * the size, except in the case where we actually have less
13185		 * than 8 bytes left.  In that case, we need to increase
13186		 * the DMA length to get the last bit.
13187		 */
13188		if ((cur_len & 0x7) != 0) {
13189			if (cur_len > 0x7) {
13190				cur_len = cur_len - (cur_len & 0x7);
13191				dma_length = cur_len;
13192			} else {
13193				CTL_SIZE_8B(dma_length, cur_len);
13194			}
13195
13196		} else
13197			dma_length = cur_len;
13198
13199		/*
13200		 * If we had to allocate memory for this I/O, instead of using
13201		 * the non-cached mirror memory, we'll need to flush the cache
13202		 * before trying to DMA to the other controller.
13203		 *
13204		 * We could end up doing this multiple times for the same
13205		 * segment if we have a larger local segment than remote
13206		 * segment.  That shouldn't be an issue.
13207		 */
13208		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13209			/*
13210			 * XXX KDM use bus_dmamap_sync() here.
13211			 */
13212		}
13213
13214		rq->size = dma_length;
13215
13216		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13217		tmp_ptr += local_used;
13218
13219		/* Use physical addresses when talking to ISC hardware */
13220		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13221			/* XXX KDM use busdma */
13222#if 0
13223			rq->local = vtophys(tmp_ptr);
13224#endif
13225		} else
13226			rq->local = tmp_ptr;
13227
13228		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13229		tmp_ptr += remote_used;
13230		rq->remote = tmp_ptr;
13231
13232		rq->callback = NULL;
13233
13234		local_used += cur_len;
13235		if (local_used >= local_sglist[i].len) {
13236			i++;
13237			local_used = 0;
13238		}
13239
13240		remote_used += cur_len;
13241		if (remote_used >= remote_sglist[j].len) {
13242			j++;
13243			remote_used = 0;
13244		}
13245		total_used += cur_len;
13246
13247		if (total_used >= io->scsiio.kern_data_len)
13248			rq->callback = callback;
13249
13250		if ((rq->size & 0x7) != 0) {
13251			printf("%s: warning: size %d is not on 8b boundary\n",
13252			       __func__, rq->size);
13253		}
13254		if (((uintptr_t)rq->local & 0x7) != 0) {
13255			printf("%s: warning: local %p not on 8b boundary\n",
13256			       __func__, rq->local);
13257		}
13258		if (((uintptr_t)rq->remote & 0x7) != 0) {
13259			printf("%s: warning: remote %p not on 8b boundary\n",
13260			       __func__, rq->local);
13261		}
13262#if 0
13263		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13264		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13265		       rq->local, rq->remote, rq->size);
13266#endif
13267
13268		isc_ret = ctl_dt_single(rq);
13269		if (isc_ret == CTL_HA_STATUS_WAIT)
13270			continue;
13271
13272		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13273			rq->ret = CTL_HA_STATUS_SUCCESS;
13274		} else {
13275			rq->ret = isc_ret;
13276		}
13277		callback(rq);
13278		goto bailout;
13279	}
13280
13281bailout:
13282	return (retval);
13283
13284}
13285
13286static void
13287ctl_datamove_remote_read(union ctl_io *io)
13288{
13289	int retval;
13290	int i;
13291
13292	/*
13293	 * This will send an error to the other controller in the case of a
13294	 * failure.
13295	 */
13296	retval = ctl_datamove_remote_sgl_setup(io);
13297	if (retval != 0)
13298		return;
13299
13300	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13301					  ctl_datamove_remote_read_cb);
13302	if ((retval != 0)
13303	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13304		/*
13305		 * Make sure we free memory if there was an error..  The
13306		 * ctl_datamove_remote_xfer() function will send the
13307		 * datamove done message, or call the callback with an
13308		 * error if there is a problem.
13309		 */
13310		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13311			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13312	}
13313
13314	return;
13315}
13316
13317/*
13318 * Process a datamove request from the other controller.  This is used for
13319 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13320 * first.  Once that is complete, the data gets DMAed into the remote
13321 * controller's memory.  For reads, we DMA from the remote controller's
13322 * memory into our memory first, and then move it out to the FETD.
13323 */
13324static void
13325ctl_datamove_remote(union ctl_io *io)
13326{
13327	struct ctl_softc *softc;
13328
13329	softc = control_softc;
13330
13331	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13332
13333	/*
13334	 * Note that we look for an aborted I/O here, but don't do some of
13335	 * the other checks that ctl_datamove() normally does.
13336	 * We don't need to run the datamove delay code, since that should
13337	 * have been done if need be on the other controller.
13338	 */
13339	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13340		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13341		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13342		       io->io_hdr.nexus.targ_port,
13343		       io->io_hdr.nexus.targ_target.id,
13344		       io->io_hdr.nexus.targ_lun);
13345		io->io_hdr.port_status = 31338;
13346		ctl_send_datamove_done(io, /*have_lock*/ 0);
13347		return;
13348	}
13349
13350	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13351		ctl_datamove_remote_write(io);
13352	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13353		ctl_datamove_remote_read(io);
13354	} else {
13355		union ctl_ha_msg msg;
13356		struct scsi_sense_data *sense;
13357		uint8_t sks[3];
13358		int retry_count;
13359
13360		memset(&msg, 0, sizeof(msg));
13361
13362		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13363		msg.hdr.status = CTL_SCSI_ERROR;
13364		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13365
13366		retry_count = 4243;
13367
13368		sense = &msg.scsi.sense_data;
13369		sks[0] = SSD_SCS_VALID;
13370		sks[1] = (retry_count >> 8) & 0xff;
13371		sks[2] = retry_count & 0xff;
13372
13373		/* "Internal target failure" */
13374		scsi_set_sense_data(sense,
13375				    /*sense_format*/ SSD_TYPE_NONE,
13376				    /*current_error*/ 1,
13377				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13378				    /*asc*/ 0x44,
13379				    /*ascq*/ 0x00,
13380				    /*type*/ SSD_ELEM_SKS,
13381				    /*size*/ sizeof(sks),
13382				    /*data*/ sks,
13383				    SSD_ELEM_NONE);
13384
13385		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13386		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13387			ctl_failover_io(io, /*have_lock*/ 1);
13388			return;
13389		}
13390
13391		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13392		    CTL_HA_STATUS_SUCCESS) {
13393			/* XXX KDM what to do if this fails? */
13394		}
13395		return;
13396	}
13397
13398}
13399
13400static int
13401ctl_process_done(union ctl_io *io)
13402{
13403	struct ctl_lun *lun;
13404	struct ctl_softc *ctl_softc = control_softc;
13405	void (*fe_done)(union ctl_io *io);
13406	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13407
13408	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13409
13410	fe_done =
13411	    control_softc->ctl_ports[targ_port]->fe_done;
13412
13413#ifdef CTL_TIME_IO
13414	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13415		char str[256];
13416		char path_str[64];
13417		struct sbuf sb;
13418
13419		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13420		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13421
13422		sbuf_cat(&sb, path_str);
13423		switch (io->io_hdr.io_type) {
13424		case CTL_IO_SCSI:
13425			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13426			sbuf_printf(&sb, "\n");
13427			sbuf_cat(&sb, path_str);
13428			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13429				    io->scsiio.tag_num, io->scsiio.tag_type);
13430			break;
13431		case CTL_IO_TASK:
13432			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13433				    "Tag Type: %d\n", io->taskio.task_action,
13434				    io->taskio.tag_num, io->taskio.tag_type);
13435			break;
13436		default:
13437			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13438			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13439			break;
13440		}
13441		sbuf_cat(&sb, path_str);
13442		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13443			    (intmax_t)time_uptime - io->io_hdr.start_time);
13444		sbuf_finish(&sb);
13445		printf("%s", sbuf_data(&sb));
13446	}
13447#endif /* CTL_TIME_IO */
13448
13449	switch (io->io_hdr.io_type) {
13450	case CTL_IO_SCSI:
13451		break;
13452	case CTL_IO_TASK:
13453		if (bootverbose || (ctl_debug & CTL_DEBUG_INFO))
13454			ctl_io_error_print(io, NULL);
13455		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13456			ctl_free_io(io);
13457		else
13458			fe_done(io);
13459		return (CTL_RETVAL_COMPLETE);
13460	default:
13461		panic("ctl_process_done: invalid io type %d\n",
13462		      io->io_hdr.io_type);
13463		break; /* NOTREACHED */
13464	}
13465
13466	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13467	if (lun == NULL) {
13468		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13469				 io->io_hdr.nexus.targ_mapped_lun));
13470		goto bailout;
13471	}
13472
13473	mtx_lock(&lun->lun_lock);
13474
13475	/*
13476	 * Check to see if we have any errors to inject here.  We only
13477	 * inject errors for commands that don't already have errors set.
13478	 */
13479	if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
13480	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13481	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13482		ctl_inject_error(lun, io);
13483
13484	/*
13485	 * XXX KDM how do we treat commands that aren't completed
13486	 * successfully?
13487	 *
13488	 * XXX KDM should we also track I/O latency?
13489	 */
13490	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13491	    io->io_hdr.io_type == CTL_IO_SCSI) {
13492#ifdef CTL_TIME_IO
13493		struct bintime cur_bt;
13494#endif
13495		int type;
13496
13497		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13498		    CTL_FLAG_DATA_IN)
13499			type = CTL_STATS_READ;
13500		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13501		    CTL_FLAG_DATA_OUT)
13502			type = CTL_STATS_WRITE;
13503		else
13504			type = CTL_STATS_NO_IO;
13505
13506		lun->stats.ports[targ_port].bytes[type] +=
13507		    io->scsiio.kern_total_len;
13508		lun->stats.ports[targ_port].operations[type]++;
13509#ifdef CTL_TIME_IO
13510		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13511		   &io->io_hdr.dma_bt);
13512		lun->stats.ports[targ_port].num_dmas[type] +=
13513		    io->io_hdr.num_dmas;
13514		getbintime(&cur_bt);
13515		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13516		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13517#endif
13518	}
13519
13520	/*
13521	 * Remove this from the OOA queue.
13522	 */
13523	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13524
13525	/*
13526	 * Run through the blocked queue on this LUN and see if anything
13527	 * has become unblocked, now that this transaction is done.
13528	 */
13529	ctl_check_blocked(lun);
13530
13531	/*
13532	 * If the LUN has been invalidated, free it if there is nothing
13533	 * left on its OOA queue.
13534	 */
13535	if ((lun->flags & CTL_LUN_INVALID)
13536	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13537		mtx_unlock(&lun->lun_lock);
13538		mtx_lock(&ctl_softc->ctl_lock);
13539		ctl_free_lun(lun);
13540		mtx_unlock(&ctl_softc->ctl_lock);
13541	} else
13542		mtx_unlock(&lun->lun_lock);
13543
13544bailout:
13545
13546	/*
13547	 * If this command has been aborted, make sure we set the status
13548	 * properly.  The FETD is responsible for freeing the I/O and doing
13549	 * whatever it needs to do to clean up its state.
13550	 */
13551	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13552		ctl_set_task_aborted(&io->scsiio);
13553
13554	/*
13555	 * If enabled, print command error status.
13556	 * We don't print UAs unless debugging was enabled explicitly.
13557	 */
13558	do {
13559		if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)
13560			break;
13561		if (!bootverbose && (ctl_debug & CTL_DEBUG_INFO) == 0)
13562			break;
13563		if ((ctl_debug & CTL_DEBUG_INFO) == 0 &&
13564		    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR) &&
13565		     (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13566			int error_code, sense_key, asc, ascq;
13567
13568			scsi_extract_sense_len(&io->scsiio.sense_data,
13569			    io->scsiio.sense_len, &error_code, &sense_key,
13570			    &asc, &ascq, /*show_errors*/ 0);
13571			if (sense_key == SSD_KEY_UNIT_ATTENTION)
13572				break;
13573		}
13574
13575		ctl_io_error_print(io, NULL);
13576	} while (0);
13577
13578	/*
13579	 * Tell the FETD or the other shelf controller we're done with this
13580	 * command.  Note that only SCSI commands get to this point.  Task
13581	 * management commands are completed above.
13582	 *
13583	 * We only send status to the other controller if we're in XFER
13584	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13585	 * received the I/O (from CTL's perspective), and so the status is
13586	 * generated there.
13587	 *
13588	 * XXX KDM if we hold the lock here, we could cause a deadlock
13589	 * if the frontend comes back in in this context to queue
13590	 * something.
13591	 */
13592	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13593	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13594		union ctl_ha_msg msg;
13595
13596		memset(&msg, 0, sizeof(msg));
13597		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13598		msg.hdr.original_sc = io->io_hdr.original_sc;
13599		msg.hdr.nexus = io->io_hdr.nexus;
13600		msg.hdr.status = io->io_hdr.status;
13601		msg.scsi.scsi_status = io->scsiio.scsi_status;
13602		msg.scsi.tag_num = io->scsiio.tag_num;
13603		msg.scsi.tag_type = io->scsiio.tag_type;
13604		msg.scsi.sense_len = io->scsiio.sense_len;
13605		msg.scsi.sense_residual = io->scsiio.sense_residual;
13606		msg.scsi.residual = io->scsiio.residual;
13607		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13608		       sizeof(io->scsiio.sense_data));
13609		/*
13610		 * We copy this whether or not this is an I/O-related
13611		 * command.  Otherwise, we'd have to go and check to see
13612		 * whether it's a read/write command, and it really isn't
13613		 * worth it.
13614		 */
13615		memcpy(&msg.scsi.lbalen,
13616		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13617		       sizeof(msg.scsi.lbalen));
13618
13619		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13620				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13621			/* XXX do something here */
13622		}
13623
13624		ctl_free_io(io);
13625	} else
13626		fe_done(io);
13627
13628	return (CTL_RETVAL_COMPLETE);
13629}
13630
13631#ifdef CTL_WITH_CA
13632/*
13633 * Front end should call this if it doesn't do autosense.  When the request
13634 * sense comes back in from the initiator, we'll dequeue this and send it.
13635 */
13636int
13637ctl_queue_sense(union ctl_io *io)
13638{
13639	struct ctl_lun *lun;
13640	struct ctl_softc *ctl_softc;
13641	uint32_t initidx, targ_lun;
13642
13643	ctl_softc = control_softc;
13644
13645	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13646
13647	/*
13648	 * LUN lookup will likely move to the ctl_work_thread() once we
13649	 * have our new queueing infrastructure (that doesn't put things on
13650	 * a per-LUN queue initially).  That is so that we can handle
13651	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13652	 * can't deal with that right now.
13653	 */
13654	mtx_lock(&ctl_softc->ctl_lock);
13655
13656	/*
13657	 * If we don't have a LUN for this, just toss the sense
13658	 * information.
13659	 */
13660	targ_lun = io->io_hdr.nexus.targ_lun;
13661	targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13662	if ((targ_lun < CTL_MAX_LUNS)
13663	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
13664		lun = ctl_softc->ctl_luns[targ_lun];
13665	else
13666		goto bailout;
13667
13668	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13669
13670	mtx_lock(&lun->lun_lock);
13671	/*
13672	 * Already have CA set for this LUN...toss the sense information.
13673	 */
13674	if (ctl_is_set(lun->have_ca, initidx)) {
13675		mtx_unlock(&lun->lun_lock);
13676		goto bailout;
13677	}
13678
13679	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13680	       ctl_min(sizeof(lun->pending_sense[initidx]),
13681	       sizeof(io->scsiio.sense_data)));
13682	ctl_set_mask(lun->have_ca, initidx);
13683	mtx_unlock(&lun->lun_lock);
13684
13685bailout:
13686	mtx_unlock(&ctl_softc->ctl_lock);
13687
13688	ctl_free_io(io);
13689
13690	return (CTL_RETVAL_COMPLETE);
13691}
13692#endif
13693
13694/*
13695 * Primary command inlet from frontend ports.  All SCSI and task I/O
13696 * requests must go through this function.
13697 */
13698int
13699ctl_queue(union ctl_io *io)
13700{
13701	struct ctl_softc *ctl_softc;
13702
13703	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13704
13705	ctl_softc = control_softc;
13706
13707#ifdef CTL_TIME_IO
13708	io->io_hdr.start_time = time_uptime;
13709	getbintime(&io->io_hdr.start_bt);
13710#endif /* CTL_TIME_IO */
13711
13712	/* Map FE-specific LUN ID into global one. */
13713	io->io_hdr.nexus.targ_mapped_lun =
13714	    ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
13715
13716	switch (io->io_hdr.io_type) {
13717	case CTL_IO_SCSI:
13718	case CTL_IO_TASK:
13719		if (ctl_debug & CTL_DEBUG_CDB)
13720			ctl_io_print(io);
13721		ctl_enqueue_incoming(io);
13722		break;
13723	default:
13724		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13725		return (EINVAL);
13726	}
13727
13728	return (CTL_RETVAL_COMPLETE);
13729}
13730
13731#ifdef CTL_IO_DELAY
13732static void
13733ctl_done_timer_wakeup(void *arg)
13734{
13735	union ctl_io *io;
13736
13737	io = (union ctl_io *)arg;
13738	ctl_done(io);
13739}
13740#endif /* CTL_IO_DELAY */
13741
13742void
13743ctl_done(union ctl_io *io)
13744{
13745	struct ctl_softc *ctl_softc;
13746
13747	ctl_softc = control_softc;
13748
13749	/*
13750	 * Enable this to catch duplicate completion issues.
13751	 */
13752#if 0
13753	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13754		printf("%s: type %d msg %d cdb %x iptl: "
13755		       "%d:%d:%d:%d tag 0x%04x "
13756		       "flag %#x status %x\n",
13757			__func__,
13758			io->io_hdr.io_type,
13759			io->io_hdr.msg_type,
13760			io->scsiio.cdb[0],
13761			io->io_hdr.nexus.initid.id,
13762			io->io_hdr.nexus.targ_port,
13763			io->io_hdr.nexus.targ_target.id,
13764			io->io_hdr.nexus.targ_lun,
13765			(io->io_hdr.io_type ==
13766			CTL_IO_TASK) ?
13767			io->taskio.tag_num :
13768			io->scsiio.tag_num,
13769		        io->io_hdr.flags,
13770			io->io_hdr.status);
13771	} else
13772		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13773#endif
13774
13775	/*
13776	 * This is an internal copy of an I/O, and should not go through
13777	 * the normal done processing logic.
13778	 */
13779	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13780		return;
13781
13782	/*
13783	 * We need to send a msg to the serializing shelf to finish the IO
13784	 * as well.  We don't send a finish message to the other shelf if
13785	 * this is a task management command.  Task management commands
13786	 * aren't serialized in the OOA queue, but rather just executed on
13787	 * both shelf controllers for commands that originated on that
13788	 * controller.
13789	 */
13790	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
13791	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
13792		union ctl_ha_msg msg_io;
13793
13794		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
13795		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
13796		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
13797		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
13798		}
13799		/* continue on to finish IO */
13800	}
13801#ifdef CTL_IO_DELAY
13802	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13803		struct ctl_lun *lun;
13804
13805		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13806
13807		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13808	} else {
13809		struct ctl_lun *lun;
13810
13811		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13812
13813		if ((lun != NULL)
13814		 && (lun->delay_info.done_delay > 0)) {
13815			struct callout *callout;
13816
13817			callout = (struct callout *)&io->io_hdr.timer_bytes;
13818			callout_init(callout, /*mpsafe*/ 1);
13819			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13820			callout_reset(callout,
13821				      lun->delay_info.done_delay * hz,
13822				      ctl_done_timer_wakeup, io);
13823			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13824				lun->delay_info.done_delay = 0;
13825			return;
13826		}
13827	}
13828#endif /* CTL_IO_DELAY */
13829
13830	ctl_enqueue_done(io);
13831}
13832
13833int
13834ctl_isc(struct ctl_scsiio *ctsio)
13835{
13836	struct ctl_lun *lun;
13837	int retval;
13838
13839	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13840
13841	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
13842
13843	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
13844
13845	retval = lun->backend->data_submit((union ctl_io *)ctsio);
13846
13847	return (retval);
13848}
13849
13850
13851static void
13852ctl_work_thread(void *arg)
13853{
13854	struct ctl_thread *thr = (struct ctl_thread *)arg;
13855	struct ctl_softc *softc = thr->ctl_softc;
13856	union ctl_io *io;
13857	int retval;
13858
13859	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13860
13861	for (;;) {
13862		retval = 0;
13863
13864		/*
13865		 * We handle the queues in this order:
13866		 * - ISC
13867		 * - done queue (to free up resources, unblock other commands)
13868		 * - RtR queue
13869		 * - incoming queue
13870		 *
13871		 * If those queues are empty, we break out of the loop and
13872		 * go to sleep.
13873		 */
13874		mtx_lock(&thr->queue_lock);
13875		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13876		if (io != NULL) {
13877			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13878			mtx_unlock(&thr->queue_lock);
13879			ctl_handle_isc(io);
13880			continue;
13881		}
13882		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13883		if (io != NULL) {
13884			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13885			/* clear any blocked commands, call fe_done */
13886			mtx_unlock(&thr->queue_lock);
13887			retval = ctl_process_done(io);
13888			continue;
13889		}
13890		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13891		if (io != NULL) {
13892			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13893			mtx_unlock(&thr->queue_lock);
13894			if (io->io_hdr.io_type == CTL_IO_TASK)
13895				ctl_run_task(io);
13896			else
13897				ctl_scsiio_precheck(softc, &io->scsiio);
13898			continue;
13899		}
13900		if (!ctl_pause_rtr) {
13901			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13902			if (io != NULL) {
13903				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13904				mtx_unlock(&thr->queue_lock);
13905				retval = ctl_scsiio(&io->scsiio);
13906				if (retval != CTL_RETVAL_COMPLETE)
13907					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13908				continue;
13909			}
13910		}
13911
13912		/* Sleep until we have something to do. */
13913		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13914	}
13915}
13916
13917static void
13918ctl_lun_thread(void *arg)
13919{
13920	struct ctl_softc *softc = (struct ctl_softc *)arg;
13921	struct ctl_be_lun *be_lun;
13922	int retval;
13923
13924	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13925
13926	for (;;) {
13927		retval = 0;
13928		mtx_lock(&softc->ctl_lock);
13929		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13930		if (be_lun != NULL) {
13931			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13932			mtx_unlock(&softc->ctl_lock);
13933			ctl_create_lun(be_lun);
13934			continue;
13935		}
13936
13937		/* Sleep until we have something to do. */
13938		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13939		    PDROP | PRIBIO, "-", 0);
13940	}
13941}
13942
13943static void
13944ctl_thresh_thread(void *arg)
13945{
13946	struct ctl_softc *softc = (struct ctl_softc *)arg;
13947	struct ctl_lun *lun;
13948	struct ctl_be_lun *be_lun;
13949	struct scsi_da_rw_recovery_page *rwpage;
13950	struct ctl_logical_block_provisioning_page *page;
13951	const char *attr;
13952	uint64_t thres, val;
13953	int i, e;
13954
13955	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13956
13957	for (;;) {
13958		mtx_lock(&softc->ctl_lock);
13959		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13960			be_lun = lun->be_lun;
13961			if ((lun->flags & CTL_LUN_DISABLED) ||
13962			    (lun->flags & CTL_LUN_OFFLINE) ||
13963			    (be_lun->flags & CTL_LUN_FLAG_UNMAP) == 0 ||
13964			    lun->backend->lun_attr == NULL)
13965				continue;
13966			rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13967			if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13968				continue;
13969			e = 0;
13970			page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13971			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13972				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13973					continue;
13974				thres = scsi_4btoul(page->descr[i].count);
13975				thres <<= CTL_LBP_EXPONENT;
13976				switch (page->descr[i].resource) {
13977				case 0x01:
13978					attr = "blocksavail";
13979					break;
13980				case 0x02:
13981					attr = "blocksused";
13982					break;
13983				case 0xf1:
13984					attr = "poolblocksavail";
13985					break;
13986				case 0xf2:
13987					attr = "poolblocksused";
13988					break;
13989				default:
13990					continue;
13991				}
13992				mtx_unlock(&softc->ctl_lock); // XXX
13993				val = lun->backend->lun_attr(
13994				    lun->be_lun->be_lun, attr);
13995				mtx_lock(&softc->ctl_lock);
13996				if (val == UINT64_MAX)
13997					continue;
13998				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13999				    == SLBPPD_ARMING_INC)
14000					e |= (val >= thres);
14001				else
14002					e |= (val <= thres);
14003			}
14004			mtx_lock(&lun->lun_lock);
14005			if (e) {
14006				if (lun->lasttpt == 0 ||
14007				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
14008					lun->lasttpt = time_uptime;
14009					for (i = 0; i < CTL_MAX_INITIATORS; i++)
14010						lun->pending_ua[i] |=
14011						    CTL_UA_THIN_PROV_THRES;
14012				}
14013			} else {
14014				lun->lasttpt = 0;
14015				for (i = 0; i < CTL_MAX_INITIATORS; i++)
14016					lun->pending_ua[i] &= ~CTL_UA_THIN_PROV_THRES;
14017			}
14018			mtx_unlock(&lun->lun_lock);
14019		}
14020		mtx_unlock(&softc->ctl_lock);
14021		pause("-", CTL_LBP_PERIOD * hz);
14022	}
14023}
14024
14025static void
14026ctl_enqueue_incoming(union ctl_io *io)
14027{
14028	struct ctl_softc *softc = control_softc;
14029	struct ctl_thread *thr;
14030	u_int idx;
14031
14032	idx = (io->io_hdr.nexus.targ_port * 127 +
14033	       io->io_hdr.nexus.initid.id) % worker_threads;
14034	thr = &softc->threads[idx];
14035	mtx_lock(&thr->queue_lock);
14036	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14037	mtx_unlock(&thr->queue_lock);
14038	wakeup(thr);
14039}
14040
14041static void
14042ctl_enqueue_rtr(union ctl_io *io)
14043{
14044	struct ctl_softc *softc = control_softc;
14045	struct ctl_thread *thr;
14046
14047	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14048	mtx_lock(&thr->queue_lock);
14049	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14050	mtx_unlock(&thr->queue_lock);
14051	wakeup(thr);
14052}
14053
14054static void
14055ctl_enqueue_done(union ctl_io *io)
14056{
14057	struct ctl_softc *softc = control_softc;
14058	struct ctl_thread *thr;
14059
14060	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14061	mtx_lock(&thr->queue_lock);
14062	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14063	mtx_unlock(&thr->queue_lock);
14064	wakeup(thr);
14065}
14066
14067static void
14068ctl_enqueue_isc(union ctl_io *io)
14069{
14070	struct ctl_softc *softc = control_softc;
14071	struct ctl_thread *thr;
14072
14073	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14074	mtx_lock(&thr->queue_lock);
14075	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14076	mtx_unlock(&thr->queue_lock);
14077	wakeup(thr);
14078}
14079
14080/* Initialization and failover */
14081
14082void
14083ctl_init_isc_msg(void)
14084{
14085	printf("CTL: Still calling this thing\n");
14086}
14087
14088/*
14089 * Init component
14090 * 	Initializes component into configuration defined by bootMode
14091 *	(see hasc-sv.c)
14092 *  	returns hasc_Status:
14093 * 		OK
14094 *		ERROR - fatal error
14095 */
14096static ctl_ha_comp_status
14097ctl_isc_init(struct ctl_ha_component *c)
14098{
14099	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14100
14101	c->status = ret;
14102	return ret;
14103}
14104
14105/* Start component
14106 * 	Starts component in state requested. If component starts successfully,
14107 *	it must set its own state to the requestrd state
14108 *	When requested state is HASC_STATE_HA, the component may refine it
14109 * 	by adding _SLAVE or _MASTER flags.
14110 *	Currently allowed state transitions are:
14111 *	UNKNOWN->HA		- initial startup
14112 *	UNKNOWN->SINGLE - initial startup when no parter detected
14113 *	HA->SINGLE		- failover
14114 * returns ctl_ha_comp_status:
14115 * 		OK	- component successfully started in requested state
14116 *		FAILED  - could not start the requested state, failover may
14117 * 			  be possible
14118 *		ERROR	- fatal error detected, no future startup possible
14119 */
14120static ctl_ha_comp_status
14121ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14122{
14123	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14124
14125	printf("%s: go\n", __func__);
14126
14127	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14128	if (c->state == CTL_HA_STATE_UNKNOWN ) {
14129		control_softc->is_single = 0;
14130		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14131		    != CTL_HA_STATUS_SUCCESS) {
14132			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14133			ret = CTL_HA_COMP_STATUS_ERROR;
14134		}
14135	} else if (CTL_HA_STATE_IS_HA(c->state)
14136		&& CTL_HA_STATE_IS_SINGLE(state)){
14137		// HA->SINGLE transition
14138	        ctl_failover();
14139		control_softc->is_single = 1;
14140	} else {
14141		printf("ctl_isc_start:Invalid state transition %X->%X\n",
14142		       c->state, state);
14143		ret = CTL_HA_COMP_STATUS_ERROR;
14144	}
14145	if (CTL_HA_STATE_IS_SINGLE(state))
14146		control_softc->is_single = 1;
14147
14148	c->state = state;
14149	c->status = ret;
14150	return ret;
14151}
14152
14153/*
14154 * Quiesce component
14155 * The component must clear any error conditions (set status to OK) and
14156 * prepare itself to another Start call
14157 * returns ctl_ha_comp_status:
14158 * 	OK
14159 *	ERROR
14160 */
14161static ctl_ha_comp_status
14162ctl_isc_quiesce(struct ctl_ha_component *c)
14163{
14164	int ret = CTL_HA_COMP_STATUS_OK;
14165
14166	ctl_pause_rtr = 1;
14167	c->status = ret;
14168	return ret;
14169}
14170
14171struct ctl_ha_component ctl_ha_component_ctlisc =
14172{
14173	.name = "CTL ISC",
14174	.state = CTL_HA_STATE_UNKNOWN,
14175	.init = ctl_isc_init,
14176	.start = ctl_isc_start,
14177	.quiesce = ctl_isc_quiesce
14178};
14179
14180/*
14181 *  vim: ts=8
14182 */
14183