ctl.c revision 288812
1/*-
2 * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3 * Copyright (c) 2012 The FreeBSD Foundation
4 * Copyright (c) 2015 Alexander Motin <mav@FreeBSD.org>
5 * All rights reserved.
6 *
7 * Portions of this software were developed by Edward Tomasz Napierala
8 * under sponsorship from the FreeBSD Foundation.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions, and the following disclaimer,
15 *    without modification.
16 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
17 *    substantially similar to the "NO WARRANTY" disclaimer below
18 *    ("Disclaimer") and any redistribution must be conditioned upon
19 *    including a substantially similar Disclaimer requirement for further
20 *    binary redistribution.
21 *
22 * NO WARRANTY
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
26 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
31 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
32 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33 * POSSIBILITY OF SUCH DAMAGES.
34 *
35 * $Id$
36 */
37/*
38 * CAM Target Layer, a SCSI device emulation subsystem.
39 *
40 * Author: Ken Merry <ken@FreeBSD.org>
41 */
42
43#define _CTL_C
44
45#include <sys/cdefs.h>
46__FBSDID("$FreeBSD: stable/10/sys/cam/ctl/ctl.c 288812 2015-10-05 11:38:51Z mav $");
47
48#include <sys/param.h>
49#include <sys/systm.h>
50#include <sys/ctype.h>
51#include <sys/kernel.h>
52#include <sys/types.h>
53#include <sys/kthread.h>
54#include <sys/bio.h>
55#include <sys/fcntl.h>
56#include <sys/lock.h>
57#include <sys/module.h>
58#include <sys/mutex.h>
59#include <sys/condvar.h>
60#include <sys/malloc.h>
61#include <sys/conf.h>
62#include <sys/ioccom.h>
63#include <sys/queue.h>
64#include <sys/sbuf.h>
65#include <sys/smp.h>
66#include <sys/endian.h>
67#include <sys/sysctl.h>
68#include <vm/uma.h>
69
70#include <cam/cam.h>
71#include <cam/scsi/scsi_all.h>
72#include <cam/scsi/scsi_cd.h>
73#include <cam/scsi/scsi_da.h>
74#include <cam/ctl/ctl_io.h>
75#include <cam/ctl/ctl.h>
76#include <cam/ctl/ctl_frontend.h>
77#include <cam/ctl/ctl_util.h>
78#include <cam/ctl/ctl_backend.h>
79#include <cam/ctl/ctl_ioctl.h>
80#include <cam/ctl/ctl_ha.h>
81#include <cam/ctl/ctl_private.h>
82#include <cam/ctl/ctl_debug.h>
83#include <cam/ctl/ctl_scsi_all.h>
84#include <cam/ctl/ctl_error.h>
85
86struct ctl_softc *control_softc = NULL;
87
88/*
89 * Template mode pages.
90 */
91
92/*
93 * Note that these are default values only.  The actual values will be
94 * filled in when the user does a mode sense.
95 */
96const static struct copan_debugconf_subpage debugconf_page_default = {
97	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
98	DBGCNF_SUBPAGE_CODE,		/* subpage */
99	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
100	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
101	DBGCNF_VERSION,			/* page_version */
102	{CTL_TIME_IO_DEFAULT_SECS>>8,
103	 CTL_TIME_IO_DEFAULT_SECS>>0},	/* ctl_time_io_secs */
104};
105
106const static struct copan_debugconf_subpage debugconf_page_changeable = {
107	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
108	DBGCNF_SUBPAGE_CODE,		/* subpage */
109	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
110	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
111	0,				/* page_version */
112	{0xff,0xff},			/* ctl_time_io_secs */
113};
114
115const static struct scsi_da_rw_recovery_page rw_er_page_default = {
116	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
117	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
118	/*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
119	/*read_retry_count*/0,
120	/*correction_span*/0,
121	/*head_offset_count*/0,
122	/*data_strobe_offset_cnt*/0,
123	/*byte8*/SMS_RWER_LBPERE,
124	/*write_retry_count*/0,
125	/*reserved2*/0,
126	/*recovery_time_limit*/{0, 0},
127};
128
129const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
130	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
131	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
132	/*byte3*/0,
133	/*read_retry_count*/0,
134	/*correction_span*/0,
135	/*head_offset_count*/0,
136	/*data_strobe_offset_cnt*/0,
137	/*byte8*/0,
138	/*write_retry_count*/0,
139	/*reserved2*/0,
140	/*recovery_time_limit*/{0, 0},
141};
142
143const static struct scsi_format_page format_page_default = {
144	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
145	/*page_length*/sizeof(struct scsi_format_page) - 2,
146	/*tracks_per_zone*/ {0, 0},
147	/*alt_sectors_per_zone*/ {0, 0},
148	/*alt_tracks_per_zone*/ {0, 0},
149	/*alt_tracks_per_lun*/ {0, 0},
150	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
151			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
152	/*bytes_per_sector*/ {0, 0},
153	/*interleave*/ {0, 0},
154	/*track_skew*/ {0, 0},
155	/*cylinder_skew*/ {0, 0},
156	/*flags*/ SFP_HSEC,
157	/*reserved*/ {0, 0, 0}
158};
159
160const static struct scsi_format_page format_page_changeable = {
161	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
162	/*page_length*/sizeof(struct scsi_format_page) - 2,
163	/*tracks_per_zone*/ {0, 0},
164	/*alt_sectors_per_zone*/ {0, 0},
165	/*alt_tracks_per_zone*/ {0, 0},
166	/*alt_tracks_per_lun*/ {0, 0},
167	/*sectors_per_track*/ {0, 0},
168	/*bytes_per_sector*/ {0, 0},
169	/*interleave*/ {0, 0},
170	/*track_skew*/ {0, 0},
171	/*cylinder_skew*/ {0, 0},
172	/*flags*/ 0,
173	/*reserved*/ {0, 0, 0}
174};
175
176const static struct scsi_rigid_disk_page rigid_disk_page_default = {
177	/*page_code*/SMS_RIGID_DISK_PAGE,
178	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
179	/*cylinders*/ {0, 0, 0},
180	/*heads*/ CTL_DEFAULT_HEADS,
181	/*start_write_precomp*/ {0, 0, 0},
182	/*start_reduced_current*/ {0, 0, 0},
183	/*step_rate*/ {0, 0},
184	/*landing_zone_cylinder*/ {0, 0, 0},
185	/*rpl*/ SRDP_RPL_DISABLED,
186	/*rotational_offset*/ 0,
187	/*reserved1*/ 0,
188	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
189			   CTL_DEFAULT_ROTATION_RATE & 0xff},
190	/*reserved2*/ {0, 0}
191};
192
193const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
194	/*page_code*/SMS_RIGID_DISK_PAGE,
195	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
196	/*cylinders*/ {0, 0, 0},
197	/*heads*/ 0,
198	/*start_write_precomp*/ {0, 0, 0},
199	/*start_reduced_current*/ {0, 0, 0},
200	/*step_rate*/ {0, 0},
201	/*landing_zone_cylinder*/ {0, 0, 0},
202	/*rpl*/ 0,
203	/*rotational_offset*/ 0,
204	/*reserved1*/ 0,
205	/*rotation_rate*/ {0, 0},
206	/*reserved2*/ {0, 0}
207};
208
209const static struct scsi_caching_page caching_page_default = {
210	/*page_code*/SMS_CACHING_PAGE,
211	/*page_length*/sizeof(struct scsi_caching_page) - 2,
212	/*flags1*/ SCP_DISC | SCP_WCE,
213	/*ret_priority*/ 0,
214	/*disable_pf_transfer_len*/ {0xff, 0xff},
215	/*min_prefetch*/ {0, 0},
216	/*max_prefetch*/ {0xff, 0xff},
217	/*max_pf_ceiling*/ {0xff, 0xff},
218	/*flags2*/ 0,
219	/*cache_segments*/ 0,
220	/*cache_seg_size*/ {0, 0},
221	/*reserved*/ 0,
222	/*non_cache_seg_size*/ {0, 0, 0}
223};
224
225const static struct scsi_caching_page caching_page_changeable = {
226	/*page_code*/SMS_CACHING_PAGE,
227	/*page_length*/sizeof(struct scsi_caching_page) - 2,
228	/*flags1*/ SCP_WCE | SCP_RCD,
229	/*ret_priority*/ 0,
230	/*disable_pf_transfer_len*/ {0, 0},
231	/*min_prefetch*/ {0, 0},
232	/*max_prefetch*/ {0, 0},
233	/*max_pf_ceiling*/ {0, 0},
234	/*flags2*/ 0,
235	/*cache_segments*/ 0,
236	/*cache_seg_size*/ {0, 0},
237	/*reserved*/ 0,
238	/*non_cache_seg_size*/ {0, 0, 0}
239};
240
241const static struct scsi_control_page control_page_default = {
242	/*page_code*/SMS_CONTROL_MODE_PAGE,
243	/*page_length*/sizeof(struct scsi_control_page) - 2,
244	/*rlec*/0,
245	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
246	/*eca_and_aen*/0,
247	/*flags4*/SCP_TAS,
248	/*aen_holdoff_period*/{0, 0},
249	/*busy_timeout_period*/{0, 0},
250	/*extended_selftest_completion_time*/{0, 0}
251};
252
253const static struct scsi_control_page control_page_changeable = {
254	/*page_code*/SMS_CONTROL_MODE_PAGE,
255	/*page_length*/sizeof(struct scsi_control_page) - 2,
256	/*rlec*/SCP_DSENSE,
257	/*queue_flags*/SCP_QUEUE_ALG_MASK,
258	/*eca_and_aen*/SCP_SWP,
259	/*flags4*/0,
260	/*aen_holdoff_period*/{0, 0},
261	/*busy_timeout_period*/{0, 0},
262	/*extended_selftest_completion_time*/{0, 0}
263};
264
265#define CTL_CEM_LEN	(sizeof(struct scsi_control_ext_page) - 4)
266
267const static struct scsi_control_ext_page control_ext_page_default = {
268	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
269	/*subpage_code*/0x01,
270	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
271	/*flags*/0,
272	/*prio*/0,
273	/*max_sense*/0
274};
275
276const static struct scsi_control_ext_page control_ext_page_changeable = {
277	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
278	/*subpage_code*/0x01,
279	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
280	/*flags*/0,
281	/*prio*/0,
282	/*max_sense*/0
283};
284
285const static struct scsi_info_exceptions_page ie_page_default = {
286	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
287	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
288	/*info_flags*/SIEP_FLAGS_DEXCPT,
289	/*mrie*/0,
290	/*interval_timer*/{0, 0, 0, 0},
291	/*report_count*/{0, 0, 0, 0}
292};
293
294const static struct scsi_info_exceptions_page ie_page_changeable = {
295	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
296	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
297	/*info_flags*/0,
298	/*mrie*/0,
299	/*interval_timer*/{0, 0, 0, 0},
300	/*report_count*/{0, 0, 0, 0}
301};
302
303#define CTL_LBPM_LEN	(sizeof(struct ctl_logical_block_provisioning_page) - 4)
304
305const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
306	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
307	/*subpage_code*/0x02,
308	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
309	/*flags*/0,
310	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
311	/*descr*/{}},
312	{{/*flags*/0,
313	  /*resource*/0x01,
314	  /*reserved*/{0, 0},
315	  /*count*/{0, 0, 0, 0}},
316	 {/*flags*/0,
317	  /*resource*/0x02,
318	  /*reserved*/{0, 0},
319	  /*count*/{0, 0, 0, 0}},
320	 {/*flags*/0,
321	  /*resource*/0xf1,
322	  /*reserved*/{0, 0},
323	  /*count*/{0, 0, 0, 0}},
324	 {/*flags*/0,
325	  /*resource*/0xf2,
326	  /*reserved*/{0, 0},
327	  /*count*/{0, 0, 0, 0}}
328	}
329};
330
331const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
332	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
333	/*subpage_code*/0x02,
334	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
335	/*flags*/0,
336	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
337	/*descr*/{}},
338	{{/*flags*/0,
339	  /*resource*/0,
340	  /*reserved*/{0, 0},
341	  /*count*/{0, 0, 0, 0}},
342	 {/*flags*/0,
343	  /*resource*/0,
344	  /*reserved*/{0, 0},
345	  /*count*/{0, 0, 0, 0}},
346	 {/*flags*/0,
347	  /*resource*/0,
348	  /*reserved*/{0, 0},
349	  /*count*/{0, 0, 0, 0}},
350	 {/*flags*/0,
351	  /*resource*/0,
352	  /*reserved*/{0, 0},
353	  /*count*/{0, 0, 0, 0}}
354	}
355};
356
357const static struct scsi_cddvd_capabilities_page cddvd_page_default = {
358	/*page_code*/SMS_CDDVD_CAPS_PAGE,
359	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
360	/*caps1*/0x3f,
361	/*caps2*/0x00,
362	/*caps3*/0xf0,
363	/*caps4*/0x00,
364	/*caps5*/0x29,
365	/*caps6*/0x00,
366	/*obsolete*/{0, 0},
367	/*nvol_levels*/{0, 0},
368	/*buffer_size*/{8, 0},
369	/*obsolete2*/{0, 0},
370	/*reserved*/0,
371	/*digital*/0,
372	/*obsolete3*/0,
373	/*copy_management*/0,
374	/*reserved2*/0,
375	/*rotation_control*/0,
376	/*cur_write_speed*/0,
377	/*num_speed_descr*/0,
378};
379
380const static struct scsi_cddvd_capabilities_page cddvd_page_changeable = {
381	/*page_code*/SMS_CDDVD_CAPS_PAGE,
382	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
383	/*caps1*/0,
384	/*caps2*/0,
385	/*caps3*/0,
386	/*caps4*/0,
387	/*caps5*/0,
388	/*caps6*/0,
389	/*obsolete*/{0, 0},
390	/*nvol_levels*/{0, 0},
391	/*buffer_size*/{0, 0},
392	/*obsolete2*/{0, 0},
393	/*reserved*/0,
394	/*digital*/0,
395	/*obsolete3*/0,
396	/*copy_management*/0,
397	/*reserved2*/0,
398	/*rotation_control*/0,
399	/*cur_write_speed*/0,
400	/*num_speed_descr*/0,
401};
402
403SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
404static int worker_threads = -1;
405TUNABLE_INT("kern.cam.ctl.worker_threads", &worker_threads);
406SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
407    &worker_threads, 1, "Number of worker threads");
408static int ctl_debug = CTL_DEBUG_NONE;
409TUNABLE_INT("kern.cam.ctl.debug", &ctl_debug);
410SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
411    &ctl_debug, 0, "Enabled debug flags");
412
413/*
414 * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
415 * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
416 * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
417 * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
418 */
419#define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
420
421static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
422				  int param);
423static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
424static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
425static int ctl_init(void);
426void ctl_shutdown(void);
427static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
428static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
429static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
430static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
431			      struct ctl_ooa *ooa_hdr,
432			      struct ctl_ooa_entry *kern_entries);
433static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
434		     struct thread *td);
435static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
436			 struct ctl_be_lun *be_lun);
437static int ctl_free_lun(struct ctl_lun *lun);
438static void ctl_create_lun(struct ctl_be_lun *be_lun);
439static struct ctl_port * ctl_io_port(struct ctl_io_hdr *io_hdr);
440
441static int ctl_do_mode_select(union ctl_io *io);
442static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
443			   uint64_t res_key, uint64_t sa_res_key,
444			   uint8_t type, uint32_t residx,
445			   struct ctl_scsiio *ctsio,
446			   struct scsi_per_res_out *cdb,
447			   struct scsi_per_res_out_parms* param);
448static void ctl_pro_preempt_other(struct ctl_lun *lun,
449				  union ctl_ha_msg *msg);
450static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
451static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
452static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
453static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
454static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
455static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
456static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
457					 int alloc_len);
458static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
459					 int alloc_len);
460static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
461static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
462static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
463static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
464static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
465static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
466    bool seq);
467static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
468static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
469    union ctl_io *pending_io, union ctl_io *ooa_io);
470static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
471				union ctl_io *starting_io);
472static int ctl_check_blocked(struct ctl_lun *lun);
473static int ctl_scsiio_lun_check(struct ctl_lun *lun,
474				const struct ctl_cmd_entry *entry,
475				struct ctl_scsiio *ctsio);
476static void ctl_failover_lun(union ctl_io *io);
477static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
478			       struct ctl_scsiio *ctsio);
479static int ctl_scsiio(struct ctl_scsiio *ctsio);
480
481static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
482static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
483			    ctl_ua_type ua_type);
484static int ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io,
485			 ctl_ua_type ua_type);
486static int ctl_lun_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
487static int ctl_abort_task(union ctl_io *io);
488static int ctl_abort_task_set(union ctl_io *io);
489static int ctl_query_task(union ctl_io *io, int task_set);
490static int ctl_i_t_nexus_reset(union ctl_io *io);
491static int ctl_query_async_event(union ctl_io *io);
492static void ctl_run_task(union ctl_io *io);
493#ifdef CTL_IO_DELAY
494static void ctl_datamove_timer_wakeup(void *arg);
495static void ctl_done_timer_wakeup(void *arg);
496#endif /* CTL_IO_DELAY */
497
498static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
499static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
500static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
501static void ctl_datamove_remote_write(union ctl_io *io);
502static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
503static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
504static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
505static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
506				    ctl_ha_dt_cb callback);
507static void ctl_datamove_remote_read(union ctl_io *io);
508static void ctl_datamove_remote(union ctl_io *io);
509static void ctl_process_done(union ctl_io *io);
510static void ctl_lun_thread(void *arg);
511static void ctl_thresh_thread(void *arg);
512static void ctl_work_thread(void *arg);
513static void ctl_enqueue_incoming(union ctl_io *io);
514static void ctl_enqueue_rtr(union ctl_io *io);
515static void ctl_enqueue_done(union ctl_io *io);
516static void ctl_enqueue_isc(union ctl_io *io);
517static const struct ctl_cmd_entry *
518    ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
519static const struct ctl_cmd_entry *
520    ctl_validate_command(struct ctl_scsiio *ctsio);
521static int ctl_cmd_applicable(uint8_t lun_type,
522    const struct ctl_cmd_entry *entry);
523
524static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
525static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
526static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
527static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
528
529/*
530 * Load the serialization table.  This isn't very pretty, but is probably
531 * the easiest way to do it.
532 */
533#include "ctl_ser_table.c"
534
535/*
536 * We only need to define open, close and ioctl routines for this driver.
537 */
538static struct cdevsw ctl_cdevsw = {
539	.d_version =	D_VERSION,
540	.d_flags =	0,
541	.d_open =	ctl_open,
542	.d_close =	ctl_close,
543	.d_ioctl =	ctl_ioctl,
544	.d_name =	"ctl",
545};
546
547
548MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
549
550static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
551
552static moduledata_t ctl_moduledata = {
553	"ctl",
554	ctl_module_event_handler,
555	NULL
556};
557
558DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
559MODULE_VERSION(ctl, 1);
560
561static struct ctl_frontend ha_frontend =
562{
563	.name = "ha",
564};
565
566static void
567ctl_ha_datamove(union ctl_io *io)
568{
569	struct ctl_lun *lun;
570	struct ctl_sg_entry *sgl;
571	union ctl_ha_msg msg;
572	uint32_t sg_entries_sent;
573	int do_sg_copy, i, j;
574
575	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
576	memset(&msg.dt, 0, sizeof(msg.dt));
577	msg.hdr.msg_type = CTL_MSG_DATAMOVE;
578	msg.hdr.original_sc = io->io_hdr.original_sc;
579	msg.hdr.serializing_sc = io;
580	msg.hdr.nexus = io->io_hdr.nexus;
581	msg.hdr.status = io->io_hdr.status;
582	msg.dt.flags = io->io_hdr.flags;
583
584	/*
585	 * We convert everything into a S/G list here.  We can't
586	 * pass by reference, only by value between controllers.
587	 * So we can't pass a pointer to the S/G list, only as many
588	 * S/G entries as we can fit in here.  If it's possible for
589	 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
590	 * then we need to break this up into multiple transfers.
591	 */
592	if (io->scsiio.kern_sg_entries == 0) {
593		msg.dt.kern_sg_entries = 1;
594#if 0
595		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
596			msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
597		} else {
598			/* XXX KDM use busdma here! */
599			msg.dt.sg_list[0].addr =
600			    (void *)vtophys(io->scsiio.kern_data_ptr);
601		}
602#else
603		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
604		    ("HA does not support BUS_ADDR"));
605		msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
606#endif
607		msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
608		do_sg_copy = 0;
609	} else {
610		msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
611		do_sg_copy = 1;
612	}
613
614	msg.dt.kern_data_len = io->scsiio.kern_data_len;
615	msg.dt.kern_total_len = io->scsiio.kern_total_len;
616	msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
617	msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
618	msg.dt.sg_sequence = 0;
619
620	/*
621	 * Loop until we've sent all of the S/G entries.  On the
622	 * other end, we'll recompose these S/G entries into one
623	 * contiguous list before processing.
624	 */
625	for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
626	    msg.dt.sg_sequence++) {
627		msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
628		    sizeof(msg.dt.sg_list[0])),
629		    msg.dt.kern_sg_entries - sg_entries_sent);
630		if (do_sg_copy != 0) {
631			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
632			for (i = sg_entries_sent, j = 0;
633			     i < msg.dt.cur_sg_entries; i++, j++) {
634#if 0
635				if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
636					msg.dt.sg_list[j].addr = sgl[i].addr;
637				} else {
638					/* XXX KDM use busdma here! */
639					msg.dt.sg_list[j].addr =
640					    (void *)vtophys(sgl[i].addr);
641				}
642#else
643				KASSERT((io->io_hdr.flags &
644				    CTL_FLAG_BUS_ADDR) == 0,
645				    ("HA does not support BUS_ADDR"));
646				msg.dt.sg_list[j].addr = sgl[i].addr;
647#endif
648				msg.dt.sg_list[j].len = sgl[i].len;
649			}
650		}
651
652		sg_entries_sent += msg.dt.cur_sg_entries;
653		msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
654		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
655		    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
656		    sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
657		    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
658			io->io_hdr.port_status = 31341;
659			io->scsiio.be_move_done(io);
660			return;
661		}
662		msg.dt.sent_sg_entries = sg_entries_sent;
663	}
664
665	/*
666	 * Officially handover the request from us to peer.
667	 * If failover has just happened, then we must return error.
668	 * If failover happen just after, then it is not our problem.
669	 */
670	if (lun)
671		mtx_lock(&lun->lun_lock);
672	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
673		if (lun)
674			mtx_unlock(&lun->lun_lock);
675		io->io_hdr.port_status = 31342;
676		io->scsiio.be_move_done(io);
677		return;
678	}
679	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
680	io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
681	if (lun)
682		mtx_unlock(&lun->lun_lock);
683}
684
685static void
686ctl_ha_done(union ctl_io *io)
687{
688	union ctl_ha_msg msg;
689
690	if (io->io_hdr.io_type == CTL_IO_SCSI) {
691		memset(&msg, 0, sizeof(msg));
692		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
693		msg.hdr.original_sc = io->io_hdr.original_sc;
694		msg.hdr.nexus = io->io_hdr.nexus;
695		msg.hdr.status = io->io_hdr.status;
696		msg.scsi.scsi_status = io->scsiio.scsi_status;
697		msg.scsi.tag_num = io->scsiio.tag_num;
698		msg.scsi.tag_type = io->scsiio.tag_type;
699		msg.scsi.sense_len = io->scsiio.sense_len;
700		msg.scsi.sense_residual = io->scsiio.sense_residual;
701		msg.scsi.residual = io->scsiio.residual;
702		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
703		    io->scsiio.sense_len);
704		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
705		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
706		    msg.scsi.sense_len, M_WAITOK);
707	}
708	ctl_free_io(io);
709}
710
711static void
712ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
713			    union ctl_ha_msg *msg_info)
714{
715	struct ctl_scsiio *ctsio;
716
717	if (msg_info->hdr.original_sc == NULL) {
718		printf("%s: original_sc == NULL!\n", __func__);
719		/* XXX KDM now what? */
720		return;
721	}
722
723	ctsio = &msg_info->hdr.original_sc->scsiio;
724	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
725	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
726	ctsio->io_hdr.status = msg_info->hdr.status;
727	ctsio->scsi_status = msg_info->scsi.scsi_status;
728	ctsio->sense_len = msg_info->scsi.sense_len;
729	ctsio->sense_residual = msg_info->scsi.sense_residual;
730	ctsio->residual = msg_info->scsi.residual;
731	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
732	       msg_info->scsi.sense_len);
733	ctl_enqueue_isc((union ctl_io *)ctsio);
734}
735
736static void
737ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
738				union ctl_ha_msg *msg_info)
739{
740	struct ctl_scsiio *ctsio;
741
742	if (msg_info->hdr.serializing_sc == NULL) {
743		printf("%s: serializing_sc == NULL!\n", __func__);
744		/* XXX KDM now what? */
745		return;
746	}
747
748	ctsio = &msg_info->hdr.serializing_sc->scsiio;
749	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
750	ctl_enqueue_isc((union ctl_io *)ctsio);
751}
752
753void
754ctl_isc_announce_lun(struct ctl_lun *lun)
755{
756	struct ctl_softc *softc = lun->ctl_softc;
757	union ctl_ha_msg *msg;
758	struct ctl_ha_msg_lun_pr_key pr_key;
759	int i, k;
760
761	if (softc->ha_link != CTL_HA_LINK_ONLINE)
762		return;
763	mtx_lock(&lun->lun_lock);
764	i = sizeof(msg->lun);
765	if (lun->lun_devid)
766		i += lun->lun_devid->len;
767	i += sizeof(pr_key) * lun->pr_key_count;
768alloc:
769	mtx_unlock(&lun->lun_lock);
770	msg = malloc(i, M_CTL, M_WAITOK);
771	mtx_lock(&lun->lun_lock);
772	k = sizeof(msg->lun);
773	if (lun->lun_devid)
774		k += lun->lun_devid->len;
775	k += sizeof(pr_key) * lun->pr_key_count;
776	if (i < k) {
777		free(msg, M_CTL);
778		i = k;
779		goto alloc;
780	}
781	bzero(&msg->lun, sizeof(msg->lun));
782	msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
783	msg->hdr.nexus.targ_lun = lun->lun;
784	msg->hdr.nexus.targ_mapped_lun = lun->lun;
785	msg->lun.flags = lun->flags;
786	msg->lun.pr_generation = lun->PRGeneration;
787	msg->lun.pr_res_idx = lun->pr_res_idx;
788	msg->lun.pr_res_type = lun->res_type;
789	msg->lun.pr_key_count = lun->pr_key_count;
790	i = 0;
791	if (lun->lun_devid) {
792		msg->lun.lun_devid_len = lun->lun_devid->len;
793		memcpy(&msg->lun.data[i], lun->lun_devid->data,
794		    msg->lun.lun_devid_len);
795		i += msg->lun.lun_devid_len;
796	}
797	for (k = 0; k < CTL_MAX_INITIATORS; k++) {
798		if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
799			continue;
800		pr_key.pr_iid = k;
801		memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
802		i += sizeof(pr_key);
803	}
804	mtx_unlock(&lun->lun_lock);
805	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
806	    M_WAITOK);
807	free(msg, M_CTL);
808
809	if (lun->flags & CTL_LUN_PRIMARY_SC) {
810		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
811			ctl_isc_announce_mode(lun, -1,
812			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
813			    lun->mode_pages.index[i].subpage);
814		}
815	}
816}
817
818void
819ctl_isc_announce_port(struct ctl_port *port)
820{
821	struct ctl_softc *softc = port->ctl_softc;
822	union ctl_ha_msg *msg;
823	int i;
824
825	if (port->targ_port < softc->port_min ||
826	    port->targ_port >= softc->port_max ||
827	    softc->ha_link != CTL_HA_LINK_ONLINE)
828		return;
829	i = sizeof(msg->port) + strlen(port->port_name) + 1;
830	if (port->lun_map)
831		i += sizeof(uint32_t) * CTL_MAX_LUNS;
832	if (port->port_devid)
833		i += port->port_devid->len;
834	if (port->target_devid)
835		i += port->target_devid->len;
836	if (port->init_devid)
837		i += port->init_devid->len;
838	msg = malloc(i, M_CTL, M_WAITOK);
839	bzero(&msg->port, sizeof(msg->port));
840	msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
841	msg->hdr.nexus.targ_port = port->targ_port;
842	msg->port.port_type = port->port_type;
843	msg->port.physical_port = port->physical_port;
844	msg->port.virtual_port = port->virtual_port;
845	msg->port.status = port->status;
846	i = 0;
847	msg->port.name_len = sprintf(&msg->port.data[i],
848	    "%d:%s", softc->ha_id, port->port_name) + 1;
849	i += msg->port.name_len;
850	if (port->lun_map) {
851		msg->port.lun_map_len = sizeof(uint32_t) * CTL_MAX_LUNS;
852		memcpy(&msg->port.data[i], port->lun_map,
853		    msg->port.lun_map_len);
854		i += msg->port.lun_map_len;
855	}
856	if (port->port_devid) {
857		msg->port.port_devid_len = port->port_devid->len;
858		memcpy(&msg->port.data[i], port->port_devid->data,
859		    msg->port.port_devid_len);
860		i += msg->port.port_devid_len;
861	}
862	if (port->target_devid) {
863		msg->port.target_devid_len = port->target_devid->len;
864		memcpy(&msg->port.data[i], port->target_devid->data,
865		    msg->port.target_devid_len);
866		i += msg->port.target_devid_len;
867	}
868	if (port->init_devid) {
869		msg->port.init_devid_len = port->init_devid->len;
870		memcpy(&msg->port.data[i], port->init_devid->data,
871		    msg->port.init_devid_len);
872		i += msg->port.init_devid_len;
873	}
874	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
875	    M_WAITOK);
876	free(msg, M_CTL);
877}
878
879void
880ctl_isc_announce_iid(struct ctl_port *port, int iid)
881{
882	struct ctl_softc *softc = port->ctl_softc;
883	union ctl_ha_msg *msg;
884	int i, l;
885
886	if (port->targ_port < softc->port_min ||
887	    port->targ_port >= softc->port_max ||
888	    softc->ha_link != CTL_HA_LINK_ONLINE)
889		return;
890	mtx_lock(&softc->ctl_lock);
891	i = sizeof(msg->iid);
892	l = 0;
893	if (port->wwpn_iid[iid].name)
894		l = strlen(port->wwpn_iid[iid].name) + 1;
895	i += l;
896	msg = malloc(i, M_CTL, M_NOWAIT);
897	if (msg == NULL) {
898		mtx_unlock(&softc->ctl_lock);
899		return;
900	}
901	bzero(&msg->iid, sizeof(msg->iid));
902	msg->hdr.msg_type = CTL_MSG_IID_SYNC;
903	msg->hdr.nexus.targ_port = port->targ_port;
904	msg->hdr.nexus.initid = iid;
905	msg->iid.in_use = port->wwpn_iid[iid].in_use;
906	msg->iid.name_len = l;
907	msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
908	if (port->wwpn_iid[iid].name)
909		strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
910	mtx_unlock(&softc->ctl_lock);
911	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
912	free(msg, M_CTL);
913}
914
915void
916ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
917    uint8_t page, uint8_t subpage)
918{
919	struct ctl_softc *softc = lun->ctl_softc;
920	union ctl_ha_msg msg;
921	int i;
922
923	if (softc->ha_link != CTL_HA_LINK_ONLINE)
924		return;
925	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
926		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
927		    page && lun->mode_pages.index[i].subpage == subpage)
928			break;
929	}
930	if (i == CTL_NUM_MODE_PAGES)
931		return;
932	bzero(&msg.mode, sizeof(msg.mode));
933	msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
934	msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
935	msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
936	msg.hdr.nexus.targ_lun = lun->lun;
937	msg.hdr.nexus.targ_mapped_lun = lun->lun;
938	msg.mode.page_code = page;
939	msg.mode.subpage = subpage;
940	msg.mode.page_len = lun->mode_pages.index[i].page_len;
941	memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
942	    msg.mode.page_len);
943	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
944	    M_WAITOK);
945}
946
947static void
948ctl_isc_ha_link_up(struct ctl_softc *softc)
949{
950	struct ctl_port *port;
951	struct ctl_lun *lun;
952	union ctl_ha_msg msg;
953	int i;
954
955	/* Announce this node parameters to peer for validation. */
956	msg.login.msg_type = CTL_MSG_LOGIN;
957	msg.login.version = CTL_HA_VERSION;
958	msg.login.ha_mode = softc->ha_mode;
959	msg.login.ha_id = softc->ha_id;
960	msg.login.max_luns = CTL_MAX_LUNS;
961	msg.login.max_ports = CTL_MAX_PORTS;
962	msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
963	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
964	    M_WAITOK);
965
966	STAILQ_FOREACH(port, &softc->port_list, links) {
967		ctl_isc_announce_port(port);
968		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
969			if (port->wwpn_iid[i].in_use)
970				ctl_isc_announce_iid(port, i);
971		}
972	}
973	STAILQ_FOREACH(lun, &softc->lun_list, links)
974		ctl_isc_announce_lun(lun);
975}
976
977static void
978ctl_isc_ha_link_down(struct ctl_softc *softc)
979{
980	struct ctl_port *port;
981	struct ctl_lun *lun;
982	union ctl_io *io;
983	int i;
984
985	mtx_lock(&softc->ctl_lock);
986	STAILQ_FOREACH(lun, &softc->lun_list, links) {
987		mtx_lock(&lun->lun_lock);
988		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
989			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
990			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
991		}
992		mtx_unlock(&lun->lun_lock);
993
994		mtx_unlock(&softc->ctl_lock);
995		io = ctl_alloc_io(softc->othersc_pool);
996		mtx_lock(&softc->ctl_lock);
997		ctl_zero_io(io);
998		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
999		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1000		ctl_enqueue_isc(io);
1001	}
1002
1003	STAILQ_FOREACH(port, &softc->port_list, links) {
1004		if (port->targ_port >= softc->port_min &&
1005		    port->targ_port < softc->port_max)
1006			continue;
1007		port->status &= ~CTL_PORT_STATUS_ONLINE;
1008		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1009			port->wwpn_iid[i].in_use = 0;
1010			free(port->wwpn_iid[i].name, M_CTL);
1011			port->wwpn_iid[i].name = NULL;
1012		}
1013	}
1014	mtx_unlock(&softc->ctl_lock);
1015}
1016
1017static void
1018ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1019{
1020	struct ctl_lun *lun;
1021	uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1022
1023	mtx_lock(&softc->ctl_lock);
1024	if (msg->hdr.nexus.targ_lun < CTL_MAX_LUNS &&
1025	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) != NULL) {
1026		mtx_lock(&lun->lun_lock);
1027		mtx_unlock(&softc->ctl_lock);
1028		if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES &&
1029		    msg->ua.ua_set)
1030			memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1031		if (msg->ua.ua_all) {
1032			if (msg->ua.ua_set)
1033				ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1034			else
1035				ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1036		} else {
1037			if (msg->ua.ua_set)
1038				ctl_est_ua(lun, iid, msg->ua.ua_type);
1039			else
1040				ctl_clr_ua(lun, iid, msg->ua.ua_type);
1041		}
1042		mtx_unlock(&lun->lun_lock);
1043	} else
1044		mtx_unlock(&softc->ctl_lock);
1045}
1046
1047static void
1048ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1049{
1050	struct ctl_lun *lun;
1051	struct ctl_ha_msg_lun_pr_key pr_key;
1052	int i, k;
1053	ctl_lun_flags oflags;
1054	uint32_t targ_lun;
1055
1056	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1057	mtx_lock(&softc->ctl_lock);
1058	if ((targ_lun >= CTL_MAX_LUNS) ||
1059	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
1060		mtx_unlock(&softc->ctl_lock);
1061		return;
1062	}
1063	mtx_lock(&lun->lun_lock);
1064	mtx_unlock(&softc->ctl_lock);
1065	if (lun->flags & CTL_LUN_DISABLED) {
1066		mtx_unlock(&lun->lun_lock);
1067		return;
1068	}
1069	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1070	if (msg->lun.lun_devid_len != i || (i > 0 &&
1071	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1072		mtx_unlock(&lun->lun_lock);
1073		printf("%s: Received conflicting HA LUN %d\n",
1074		    __func__, msg->hdr.nexus.targ_lun);
1075		return;
1076	} else {
1077		/* Record whether peer is primary. */
1078		oflags = lun->flags;
1079		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1080		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1081			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1082		else
1083			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1084		if (oflags != lun->flags)
1085			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1086
1087		/* If peer is primary and we are not -- use data */
1088		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1089		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1090			lun->PRGeneration = msg->lun.pr_generation;
1091			lun->pr_res_idx = msg->lun.pr_res_idx;
1092			lun->res_type = msg->lun.pr_res_type;
1093			lun->pr_key_count = msg->lun.pr_key_count;
1094			for (k = 0; k < CTL_MAX_INITIATORS; k++)
1095				ctl_clr_prkey(lun, k);
1096			for (k = 0; k < msg->lun.pr_key_count; k++) {
1097				memcpy(&pr_key, &msg->lun.data[i],
1098				    sizeof(pr_key));
1099				ctl_alloc_prkey(lun, pr_key.pr_iid);
1100				ctl_set_prkey(lun, pr_key.pr_iid,
1101				    pr_key.pr_key);
1102				i += sizeof(pr_key);
1103			}
1104		}
1105
1106		mtx_unlock(&lun->lun_lock);
1107		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1108		    __func__, msg->hdr.nexus.targ_lun,
1109		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1110		    "primary" : "secondary"));
1111
1112		/* If we are primary but peer doesn't know -- notify */
1113		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1114		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1115			ctl_isc_announce_lun(lun);
1116	}
1117}
1118
1119static void
1120ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1121{
1122	struct ctl_port *port;
1123	struct ctl_lun *lun;
1124	int i, new;
1125
1126	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1127	if (port == NULL) {
1128		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1129		    msg->hdr.nexus.targ_port));
1130		new = 1;
1131		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1132		port->frontend = &ha_frontend;
1133		port->targ_port = msg->hdr.nexus.targ_port;
1134		port->fe_datamove = ctl_ha_datamove;
1135		port->fe_done = ctl_ha_done;
1136	} else if (port->frontend == &ha_frontend) {
1137		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1138		    msg->hdr.nexus.targ_port));
1139		new = 0;
1140	} else {
1141		printf("%s: Received conflicting HA port %d\n",
1142		    __func__, msg->hdr.nexus.targ_port);
1143		return;
1144	}
1145	port->port_type = msg->port.port_type;
1146	port->physical_port = msg->port.physical_port;
1147	port->virtual_port = msg->port.virtual_port;
1148	port->status = msg->port.status;
1149	i = 0;
1150	free(port->port_name, M_CTL);
1151	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1152	    M_CTL);
1153	i += msg->port.name_len;
1154	if (msg->port.lun_map_len != 0) {
1155		if (port->lun_map == NULL)
1156			port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
1157			    M_CTL, M_WAITOK);
1158		memcpy(port->lun_map, &msg->port.data[i],
1159		    sizeof(uint32_t) * CTL_MAX_LUNS);
1160		i += msg->port.lun_map_len;
1161	} else {
1162		free(port->lun_map, M_CTL);
1163		port->lun_map = NULL;
1164	}
1165	if (msg->port.port_devid_len != 0) {
1166		if (port->port_devid == NULL ||
1167		    port->port_devid->len != msg->port.port_devid_len) {
1168			free(port->port_devid, M_CTL);
1169			port->port_devid = malloc(sizeof(struct ctl_devid) +
1170			    msg->port.port_devid_len, M_CTL, M_WAITOK);
1171		}
1172		memcpy(port->port_devid->data, &msg->port.data[i],
1173		    msg->port.port_devid_len);
1174		port->port_devid->len = msg->port.port_devid_len;
1175		i += msg->port.port_devid_len;
1176	} else {
1177		free(port->port_devid, M_CTL);
1178		port->port_devid = NULL;
1179	}
1180	if (msg->port.target_devid_len != 0) {
1181		if (port->target_devid == NULL ||
1182		    port->target_devid->len != msg->port.target_devid_len) {
1183			free(port->target_devid, M_CTL);
1184			port->target_devid = malloc(sizeof(struct ctl_devid) +
1185			    msg->port.target_devid_len, M_CTL, M_WAITOK);
1186		}
1187		memcpy(port->target_devid->data, &msg->port.data[i],
1188		    msg->port.target_devid_len);
1189		port->target_devid->len = msg->port.target_devid_len;
1190		i += msg->port.target_devid_len;
1191	} else {
1192		free(port->target_devid, M_CTL);
1193		port->target_devid = NULL;
1194	}
1195	if (msg->port.init_devid_len != 0) {
1196		if (port->init_devid == NULL ||
1197		    port->init_devid->len != msg->port.init_devid_len) {
1198			free(port->init_devid, M_CTL);
1199			port->init_devid = malloc(sizeof(struct ctl_devid) +
1200			    msg->port.init_devid_len, M_CTL, M_WAITOK);
1201		}
1202		memcpy(port->init_devid->data, &msg->port.data[i],
1203		    msg->port.init_devid_len);
1204		port->init_devid->len = msg->port.init_devid_len;
1205		i += msg->port.init_devid_len;
1206	} else {
1207		free(port->init_devid, M_CTL);
1208		port->init_devid = NULL;
1209	}
1210	if (new) {
1211		if (ctl_port_register(port) != 0) {
1212			printf("%s: ctl_port_register() failed with error\n",
1213			    __func__);
1214		}
1215	}
1216	mtx_lock(&softc->ctl_lock);
1217	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1218		if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
1219			continue;
1220		mtx_lock(&lun->lun_lock);
1221		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1222		mtx_unlock(&lun->lun_lock);
1223	}
1224	mtx_unlock(&softc->ctl_lock);
1225}
1226
1227static void
1228ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1229{
1230	struct ctl_port *port;
1231	int iid;
1232
1233	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1234	if (port == NULL) {
1235		printf("%s: Received IID for unknown port %d\n",
1236		    __func__, msg->hdr.nexus.targ_port);
1237		return;
1238	}
1239	iid = msg->hdr.nexus.initid;
1240	port->wwpn_iid[iid].in_use = msg->iid.in_use;
1241	port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1242	free(port->wwpn_iid[iid].name, M_CTL);
1243	if (msg->iid.name_len) {
1244		port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1245		    msg->iid.name_len, M_CTL);
1246	} else
1247		port->wwpn_iid[iid].name = NULL;
1248}
1249
1250static void
1251ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1252{
1253
1254	if (msg->login.version != CTL_HA_VERSION) {
1255		printf("CTL HA peers have different versions %d != %d\n",
1256		    msg->login.version, CTL_HA_VERSION);
1257		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1258		return;
1259	}
1260	if (msg->login.ha_mode != softc->ha_mode) {
1261		printf("CTL HA peers have different ha_mode %d != %d\n",
1262		    msg->login.ha_mode, softc->ha_mode);
1263		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1264		return;
1265	}
1266	if (msg->login.ha_id == softc->ha_id) {
1267		printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1268		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1269		return;
1270	}
1271	if (msg->login.max_luns != CTL_MAX_LUNS ||
1272	    msg->login.max_ports != CTL_MAX_PORTS ||
1273	    msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1274		printf("CTL HA peers have different limits\n");
1275		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1276		return;
1277	}
1278}
1279
1280static void
1281ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1282{
1283	struct ctl_lun *lun;
1284	int i;
1285	uint32_t initidx, targ_lun;
1286
1287	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1288	mtx_lock(&softc->ctl_lock);
1289	if ((targ_lun >= CTL_MAX_LUNS) ||
1290	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
1291		mtx_unlock(&softc->ctl_lock);
1292		return;
1293	}
1294	mtx_lock(&lun->lun_lock);
1295	mtx_unlock(&softc->ctl_lock);
1296	if (lun->flags & CTL_LUN_DISABLED) {
1297		mtx_unlock(&lun->lun_lock);
1298		return;
1299	}
1300	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1301		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1302		    msg->mode.page_code &&
1303		    lun->mode_pages.index[i].subpage == msg->mode.subpage)
1304			break;
1305	}
1306	if (i == CTL_NUM_MODE_PAGES) {
1307		mtx_unlock(&lun->lun_lock);
1308		return;
1309	}
1310	memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1311	    lun->mode_pages.index[i].page_len);
1312	initidx = ctl_get_initindex(&msg->hdr.nexus);
1313	if (initidx != -1)
1314		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1315	mtx_unlock(&lun->lun_lock);
1316}
1317
1318/*
1319 * ISC (Inter Shelf Communication) event handler.  Events from the HA
1320 * subsystem come in here.
1321 */
1322static void
1323ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1324{
1325	struct ctl_softc *softc = control_softc;
1326	union ctl_io *io;
1327	struct ctl_prio *presio;
1328	ctl_ha_status isc_status;
1329
1330	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1331	if (event == CTL_HA_EVT_MSG_RECV) {
1332		union ctl_ha_msg *msg, msgbuf;
1333
1334		if (param > sizeof(msgbuf))
1335			msg = malloc(param, M_CTL, M_WAITOK);
1336		else
1337			msg = &msgbuf;
1338		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1339		    M_WAITOK);
1340		if (isc_status != CTL_HA_STATUS_SUCCESS) {
1341			printf("%s: Error receiving message: %d\n",
1342			    __func__, isc_status);
1343			if (msg != &msgbuf)
1344				free(msg, M_CTL);
1345			return;
1346		}
1347
1348		CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1349		switch (msg->hdr.msg_type) {
1350		case CTL_MSG_SERIALIZE:
1351			io = ctl_alloc_io(softc->othersc_pool);
1352			ctl_zero_io(io);
1353			// populate ctsio from msg
1354			io->io_hdr.io_type = CTL_IO_SCSI;
1355			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1356			io->io_hdr.original_sc = msg->hdr.original_sc;
1357			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1358					    CTL_FLAG_IO_ACTIVE;
1359			/*
1360			 * If we're in serialization-only mode, we don't
1361			 * want to go through full done processing.  Thus
1362			 * the COPY flag.
1363			 *
1364			 * XXX KDM add another flag that is more specific.
1365			 */
1366			if (softc->ha_mode != CTL_HA_MODE_XFER)
1367				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1368			io->io_hdr.nexus = msg->hdr.nexus;
1369#if 0
1370			printf("port %u, iid %u, lun %u\n",
1371			       io->io_hdr.nexus.targ_port,
1372			       io->io_hdr.nexus.initid,
1373			       io->io_hdr.nexus.targ_lun);
1374#endif
1375			io->scsiio.tag_num = msg->scsi.tag_num;
1376			io->scsiio.tag_type = msg->scsi.tag_type;
1377#ifdef CTL_TIME_IO
1378			io->io_hdr.start_time = time_uptime;
1379			getbinuptime(&io->io_hdr.start_bt);
1380#endif /* CTL_TIME_IO */
1381			io->scsiio.cdb_len = msg->scsi.cdb_len;
1382			memcpy(io->scsiio.cdb, msg->scsi.cdb,
1383			       CTL_MAX_CDBLEN);
1384			if (softc->ha_mode == CTL_HA_MODE_XFER) {
1385				const struct ctl_cmd_entry *entry;
1386
1387				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1388				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1389				io->io_hdr.flags |=
1390					entry->flags & CTL_FLAG_DATA_MASK;
1391			}
1392			ctl_enqueue_isc(io);
1393			break;
1394
1395		/* Performed on the Originating SC, XFER mode only */
1396		case CTL_MSG_DATAMOVE: {
1397			struct ctl_sg_entry *sgl;
1398			int i, j;
1399
1400			io = msg->hdr.original_sc;
1401			if (io == NULL) {
1402				printf("%s: original_sc == NULL!\n", __func__);
1403				/* XXX KDM do something here */
1404				break;
1405			}
1406			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1407			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1408			/*
1409			 * Keep track of this, we need to send it back over
1410			 * when the datamove is complete.
1411			 */
1412			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1413			if (msg->hdr.status == CTL_SUCCESS)
1414				io->io_hdr.status = msg->hdr.status;
1415
1416			if (msg->dt.sg_sequence == 0) {
1417#ifdef CTL_TIME_IO
1418				getbinuptime(&io->io_hdr.dma_start_bt);
1419#endif
1420				i = msg->dt.kern_sg_entries +
1421				    msg->dt.kern_data_len /
1422				    CTL_HA_DATAMOVE_SEGMENT + 1;
1423				sgl = malloc(sizeof(*sgl) * i, M_CTL,
1424				    M_WAITOK | M_ZERO);
1425				io->io_hdr.remote_sglist = sgl;
1426				io->io_hdr.local_sglist =
1427				    &sgl[msg->dt.kern_sg_entries];
1428
1429				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1430
1431				io->scsiio.kern_sg_entries =
1432					msg->dt.kern_sg_entries;
1433				io->scsiio.rem_sg_entries =
1434					msg->dt.kern_sg_entries;
1435				io->scsiio.kern_data_len =
1436					msg->dt.kern_data_len;
1437				io->scsiio.kern_total_len =
1438					msg->dt.kern_total_len;
1439				io->scsiio.kern_data_resid =
1440					msg->dt.kern_data_resid;
1441				io->scsiio.kern_rel_offset =
1442					msg->dt.kern_rel_offset;
1443				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1444				io->io_hdr.flags |= msg->dt.flags &
1445				    CTL_FLAG_BUS_ADDR;
1446			} else
1447				sgl = (struct ctl_sg_entry *)
1448					io->scsiio.kern_data_ptr;
1449
1450			for (i = msg->dt.sent_sg_entries, j = 0;
1451			     i < (msg->dt.sent_sg_entries +
1452			     msg->dt.cur_sg_entries); i++, j++) {
1453				sgl[i].addr = msg->dt.sg_list[j].addr;
1454				sgl[i].len = msg->dt.sg_list[j].len;
1455
1456#if 0
1457				printf("%s: DATAMOVE: %p,%lu j=%d, i=%d\n",
1458				    __func__, sgl[i].addr, sgl[i].len, j, i);
1459#endif
1460			}
1461
1462			/*
1463			 * If this is the last piece of the I/O, we've got
1464			 * the full S/G list.  Queue processing in the thread.
1465			 * Otherwise wait for the next piece.
1466			 */
1467			if (msg->dt.sg_last != 0)
1468				ctl_enqueue_isc(io);
1469			break;
1470		}
1471		/* Performed on the Serializing (primary) SC, XFER mode only */
1472		case CTL_MSG_DATAMOVE_DONE: {
1473			if (msg->hdr.serializing_sc == NULL) {
1474				printf("%s: serializing_sc == NULL!\n",
1475				       __func__);
1476				/* XXX KDM now what? */
1477				break;
1478			}
1479			/*
1480			 * We grab the sense information here in case
1481			 * there was a failure, so we can return status
1482			 * back to the initiator.
1483			 */
1484			io = msg->hdr.serializing_sc;
1485			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1486			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1487			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1488			io->io_hdr.port_status = msg->scsi.fetd_status;
1489			io->scsiio.residual = msg->scsi.residual;
1490			if (msg->hdr.status != CTL_STATUS_NONE) {
1491				io->io_hdr.status = msg->hdr.status;
1492				io->scsiio.scsi_status = msg->scsi.scsi_status;
1493				io->scsiio.sense_len = msg->scsi.sense_len;
1494				io->scsiio.sense_residual =msg->scsi.sense_residual;
1495				memcpy(&io->scsiio.sense_data,
1496				    &msg->scsi.sense_data,
1497				    msg->scsi.sense_len);
1498				if (msg->hdr.status == CTL_SUCCESS)
1499					io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1500			}
1501			ctl_enqueue_isc(io);
1502			break;
1503		}
1504
1505		/* Preformed on Originating SC, SER_ONLY mode */
1506		case CTL_MSG_R2R:
1507			io = msg->hdr.original_sc;
1508			if (io == NULL) {
1509				printf("%s: original_sc == NULL!\n",
1510				    __func__);
1511				break;
1512			}
1513			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1514			io->io_hdr.msg_type = CTL_MSG_R2R;
1515			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1516			ctl_enqueue_isc(io);
1517			break;
1518
1519		/*
1520		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1521		 * mode.
1522		 * Performed on the Originating (i.e. secondary) SC in XFER
1523		 * mode
1524		 */
1525		case CTL_MSG_FINISH_IO:
1526			if (softc->ha_mode == CTL_HA_MODE_XFER)
1527				ctl_isc_handler_finish_xfer(softc, msg);
1528			else
1529				ctl_isc_handler_finish_ser_only(softc, msg);
1530			break;
1531
1532		/* Preformed on Originating SC */
1533		case CTL_MSG_BAD_JUJU:
1534			io = msg->hdr.original_sc;
1535			if (io == NULL) {
1536				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1537				       __func__);
1538				break;
1539			}
1540			ctl_copy_sense_data(msg, io);
1541			/*
1542			 * IO should have already been cleaned up on other
1543			 * SC so clear this flag so we won't send a message
1544			 * back to finish the IO there.
1545			 */
1546			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1547			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1548
1549			/* io = msg->hdr.serializing_sc; */
1550			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1551			ctl_enqueue_isc(io);
1552			break;
1553
1554		/* Handle resets sent from the other side */
1555		case CTL_MSG_MANAGE_TASKS: {
1556			struct ctl_taskio *taskio;
1557			taskio = (struct ctl_taskio *)ctl_alloc_io(
1558			    softc->othersc_pool);
1559			ctl_zero_io((union ctl_io *)taskio);
1560			taskio->io_hdr.io_type = CTL_IO_TASK;
1561			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1562			taskio->io_hdr.nexus = msg->hdr.nexus;
1563			taskio->task_action = msg->task.task_action;
1564			taskio->tag_num = msg->task.tag_num;
1565			taskio->tag_type = msg->task.tag_type;
1566#ifdef CTL_TIME_IO
1567			taskio->io_hdr.start_time = time_uptime;
1568			getbinuptime(&taskio->io_hdr.start_bt);
1569#endif /* CTL_TIME_IO */
1570			ctl_run_task((union ctl_io *)taskio);
1571			break;
1572		}
1573		/* Persistent Reserve action which needs attention */
1574		case CTL_MSG_PERS_ACTION:
1575			presio = (struct ctl_prio *)ctl_alloc_io(
1576			    softc->othersc_pool);
1577			ctl_zero_io((union ctl_io *)presio);
1578			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1579			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1580			presio->io_hdr.nexus = msg->hdr.nexus;
1581			presio->pr_msg = msg->pr;
1582			ctl_enqueue_isc((union ctl_io *)presio);
1583			break;
1584		case CTL_MSG_UA:
1585			ctl_isc_ua(softc, msg, param);
1586			break;
1587		case CTL_MSG_PORT_SYNC:
1588			ctl_isc_port_sync(softc, msg, param);
1589			break;
1590		case CTL_MSG_LUN_SYNC:
1591			ctl_isc_lun_sync(softc, msg, param);
1592			break;
1593		case CTL_MSG_IID_SYNC:
1594			ctl_isc_iid_sync(softc, msg, param);
1595			break;
1596		case CTL_MSG_LOGIN:
1597			ctl_isc_login(softc, msg, param);
1598			break;
1599		case CTL_MSG_MODE_SYNC:
1600			ctl_isc_mode_sync(softc, msg, param);
1601			break;
1602		default:
1603			printf("Received HA message of unknown type %d\n",
1604			    msg->hdr.msg_type);
1605			ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1606			break;
1607		}
1608		if (msg != &msgbuf)
1609			free(msg, M_CTL);
1610	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1611		printf("CTL: HA link status changed from %d to %d\n",
1612		    softc->ha_link, param);
1613		if (param == softc->ha_link)
1614			return;
1615		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1616			softc->ha_link = param;
1617			ctl_isc_ha_link_down(softc);
1618		} else {
1619			softc->ha_link = param;
1620			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1621				ctl_isc_ha_link_up(softc);
1622		}
1623		return;
1624	} else {
1625		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1626		return;
1627	}
1628}
1629
1630static void
1631ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1632{
1633
1634	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1635	    src->scsi.sense_len);
1636	dest->scsiio.scsi_status = src->scsi.scsi_status;
1637	dest->scsiio.sense_len = src->scsi.sense_len;
1638	dest->io_hdr.status = src->hdr.status;
1639}
1640
1641static void
1642ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1643{
1644
1645	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1646	    src->scsiio.sense_len);
1647	dest->scsi.scsi_status = src->scsiio.scsi_status;
1648	dest->scsi.sense_len = src->scsiio.sense_len;
1649	dest->hdr.status = src->io_hdr.status;
1650}
1651
1652void
1653ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1654{
1655	struct ctl_softc *softc = lun->ctl_softc;
1656	ctl_ua_type *pu;
1657
1658	if (initidx < softc->init_min || initidx >= softc->init_max)
1659		return;
1660	mtx_assert(&lun->lun_lock, MA_OWNED);
1661	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1662	if (pu == NULL)
1663		return;
1664	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1665}
1666
1667void
1668ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1669{
1670	int i;
1671
1672	mtx_assert(&lun->lun_lock, MA_OWNED);
1673	if (lun->pending_ua[port] == NULL)
1674		return;
1675	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1676		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1677			continue;
1678		lun->pending_ua[port][i] |= ua;
1679	}
1680}
1681
1682void
1683ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1684{
1685	struct ctl_softc *softc = lun->ctl_softc;
1686	int i;
1687
1688	mtx_assert(&lun->lun_lock, MA_OWNED);
1689	for (i = softc->port_min; i < softc->port_max; i++)
1690		ctl_est_ua_port(lun, i, except, ua);
1691}
1692
1693void
1694ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1695{
1696	struct ctl_softc *softc = lun->ctl_softc;
1697	ctl_ua_type *pu;
1698
1699	if (initidx < softc->init_min || initidx >= softc->init_max)
1700		return;
1701	mtx_assert(&lun->lun_lock, MA_OWNED);
1702	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1703	if (pu == NULL)
1704		return;
1705	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1706}
1707
1708void
1709ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1710{
1711	struct ctl_softc *softc = lun->ctl_softc;
1712	int i, j;
1713
1714	mtx_assert(&lun->lun_lock, MA_OWNED);
1715	for (i = softc->port_min; i < softc->port_max; i++) {
1716		if (lun->pending_ua[i] == NULL)
1717			continue;
1718		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1719			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1720				continue;
1721			lun->pending_ua[i][j] &= ~ua;
1722		}
1723	}
1724}
1725
1726void
1727ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1728    ctl_ua_type ua_type)
1729{
1730	struct ctl_lun *lun;
1731
1732	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1733	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1734		mtx_lock(&lun->lun_lock);
1735		ctl_clr_ua(lun, initidx, ua_type);
1736		mtx_unlock(&lun->lun_lock);
1737	}
1738}
1739
1740static int
1741ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1742{
1743	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1744	struct ctl_lun *lun;
1745	struct ctl_lun_req ireq;
1746	int error, value;
1747
1748	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1749	error = sysctl_handle_int(oidp, &value, 0, req);
1750	if ((error != 0) || (req->newptr == NULL))
1751		return (error);
1752
1753	mtx_lock(&softc->ctl_lock);
1754	if (value == 0)
1755		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1756	else
1757		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1758	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1759		mtx_unlock(&softc->ctl_lock);
1760		bzero(&ireq, sizeof(ireq));
1761		ireq.reqtype = CTL_LUNREQ_MODIFY;
1762		ireq.reqdata.modify.lun_id = lun->lun;
1763		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1764		    curthread);
1765		if (ireq.status != CTL_LUN_OK) {
1766			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1767			    __func__, ireq.status, ireq.error_str);
1768		}
1769		mtx_lock(&softc->ctl_lock);
1770	}
1771	mtx_unlock(&softc->ctl_lock);
1772	return (0);
1773}
1774
1775static int
1776ctl_init(void)
1777{
1778	struct ctl_softc *softc;
1779	void *other_pool;
1780	int i, error;
1781
1782	softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1783			       M_WAITOK | M_ZERO);
1784
1785	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1786			      "cam/ctl");
1787	softc->dev->si_drv1 = softc;
1788
1789	sysctl_ctx_init(&softc->sysctl_ctx);
1790	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1791		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1792		CTLFLAG_RD, 0, "CAM Target Layer");
1793
1794	if (softc->sysctl_tree == NULL) {
1795		printf("%s: unable to allocate sysctl tree\n", __func__);
1796		destroy_dev(softc->dev);
1797		free(control_softc, M_DEVBUF);
1798		control_softc = NULL;
1799		return (ENOMEM);
1800	}
1801
1802	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1803	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1804	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1805	softc->flags = 0;
1806
1807	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1808	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1809	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1810
1811	/*
1812	 * In Copan's HA scheme, the "master" and "slave" roles are
1813	 * figured out through the slot the controller is in.  Although it
1814	 * is an active/active system, someone has to be in charge.
1815	 */
1816	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1817	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1818	    "HA head ID (0 - no HA)");
1819	if (softc->ha_id == 0 || softc->ha_id > NUM_TARGET_PORT_GROUPS) {
1820		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1821		softc->is_single = 1;
1822		softc->port_cnt = CTL_MAX_PORTS;
1823		softc->port_min = 0;
1824	} else {
1825		softc->port_cnt = CTL_MAX_PORTS / NUM_TARGET_PORT_GROUPS;
1826		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1827	}
1828	softc->port_max = softc->port_min + softc->port_cnt;
1829	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1830	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1831
1832	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1833	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1834	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
1835
1836	STAILQ_INIT(&softc->lun_list);
1837	STAILQ_INIT(&softc->pending_lun_queue);
1838	STAILQ_INIT(&softc->fe_list);
1839	STAILQ_INIT(&softc->port_list);
1840	STAILQ_INIT(&softc->be_list);
1841	ctl_tpc_init(softc);
1842
1843	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1844	                    &other_pool) != 0)
1845	{
1846		printf("ctl: can't allocate %d entry other SC pool, "
1847		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1848		return (ENOMEM);
1849	}
1850	softc->othersc_pool = other_pool;
1851
1852	if (worker_threads <= 0)
1853		worker_threads = max(1, mp_ncpus / 4);
1854	if (worker_threads > CTL_MAX_THREADS)
1855		worker_threads = CTL_MAX_THREADS;
1856
1857	for (i = 0; i < worker_threads; i++) {
1858		struct ctl_thread *thr = &softc->threads[i];
1859
1860		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1861		thr->ctl_softc = softc;
1862		STAILQ_INIT(&thr->incoming_queue);
1863		STAILQ_INIT(&thr->rtr_queue);
1864		STAILQ_INIT(&thr->done_queue);
1865		STAILQ_INIT(&thr->isc_queue);
1866
1867		error = kproc_kthread_add(ctl_work_thread, thr,
1868		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1869		if (error != 0) {
1870			printf("error creating CTL work thread!\n");
1871			ctl_pool_free(other_pool);
1872			return (error);
1873		}
1874	}
1875	error = kproc_kthread_add(ctl_lun_thread, softc,
1876	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1877	if (error != 0) {
1878		printf("error creating CTL lun thread!\n");
1879		ctl_pool_free(other_pool);
1880		return (error);
1881	}
1882	error = kproc_kthread_add(ctl_thresh_thread, softc,
1883	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1884	if (error != 0) {
1885		printf("error creating CTL threshold thread!\n");
1886		ctl_pool_free(other_pool);
1887		return (error);
1888	}
1889
1890	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1891	    OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1892	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1893
1894	if (softc->is_single == 0) {
1895		ctl_frontend_register(&ha_frontend);
1896		if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
1897			printf("ctl_init: ctl_ha_msg_init failed.\n");
1898			softc->is_single = 1;
1899		} else
1900		if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
1901		    != CTL_HA_STATUS_SUCCESS) {
1902			printf("ctl_init: ctl_ha_msg_register failed.\n");
1903			softc->is_single = 1;
1904		}
1905	}
1906	return (0);
1907}
1908
1909void
1910ctl_shutdown(void)
1911{
1912	struct ctl_softc *softc = control_softc;
1913	struct ctl_lun *lun, *next_lun;
1914
1915	if (softc->is_single == 0) {
1916		ctl_ha_msg_shutdown(softc);
1917		if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL)
1918		    != CTL_HA_STATUS_SUCCESS)
1919			printf("%s: ctl_ha_msg_deregister failed.\n", __func__);
1920		if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
1921			printf("%s: ctl_ha_msg_destroy failed.\n", __func__);
1922		ctl_frontend_deregister(&ha_frontend);
1923	}
1924
1925	mtx_lock(&softc->ctl_lock);
1926
1927	/*
1928	 * Free up each LUN.
1929	 */
1930	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1931		next_lun = STAILQ_NEXT(lun, links);
1932		ctl_free_lun(lun);
1933	}
1934
1935	mtx_unlock(&softc->ctl_lock);
1936
1937#if 0
1938	ctl_shutdown_thread(softc->work_thread);
1939	mtx_destroy(&softc->queue_lock);
1940#endif
1941
1942	ctl_tpc_shutdown(softc);
1943	uma_zdestroy(softc->io_zone);
1944	mtx_destroy(&softc->ctl_lock);
1945
1946	destroy_dev(softc->dev);
1947
1948	sysctl_ctx_free(&softc->sysctl_ctx);
1949
1950	free(control_softc, M_DEVBUF);
1951	control_softc = NULL;
1952}
1953
1954static int
1955ctl_module_event_handler(module_t mod, int what, void *arg)
1956{
1957
1958	switch (what) {
1959	case MOD_LOAD:
1960		return (ctl_init());
1961	case MOD_UNLOAD:
1962		return (EBUSY);
1963	default:
1964		return (EOPNOTSUPP);
1965	}
1966}
1967
1968/*
1969 * XXX KDM should we do some access checks here?  Bump a reference count to
1970 * prevent a CTL module from being unloaded while someone has it open?
1971 */
1972static int
1973ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1974{
1975	return (0);
1976}
1977
1978static int
1979ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1980{
1981	return (0);
1982}
1983
1984/*
1985 * Remove an initiator by port number and initiator ID.
1986 * Returns 0 for success, -1 for failure.
1987 */
1988int
1989ctl_remove_initiator(struct ctl_port *port, int iid)
1990{
1991	struct ctl_softc *softc = port->ctl_softc;
1992
1993	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1994
1995	if (iid > CTL_MAX_INIT_PER_PORT) {
1996		printf("%s: initiator ID %u > maximun %u!\n",
1997		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1998		return (-1);
1999	}
2000
2001	mtx_lock(&softc->ctl_lock);
2002	port->wwpn_iid[iid].in_use--;
2003	port->wwpn_iid[iid].last_use = time_uptime;
2004	mtx_unlock(&softc->ctl_lock);
2005	ctl_isc_announce_iid(port, iid);
2006
2007	return (0);
2008}
2009
2010/*
2011 * Add an initiator to the initiator map.
2012 * Returns iid for success, < 0 for failure.
2013 */
2014int
2015ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2016{
2017	struct ctl_softc *softc = port->ctl_softc;
2018	time_t best_time;
2019	int i, best;
2020
2021	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2022
2023	if (iid >= CTL_MAX_INIT_PER_PORT) {
2024		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2025		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2026		free(name, M_CTL);
2027		return (-1);
2028	}
2029
2030	mtx_lock(&softc->ctl_lock);
2031
2032	if (iid < 0 && (wwpn != 0 || name != NULL)) {
2033		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2034			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2035				iid = i;
2036				break;
2037			}
2038			if (name != NULL && port->wwpn_iid[i].name != NULL &&
2039			    strcmp(name, port->wwpn_iid[i].name) == 0) {
2040				iid = i;
2041				break;
2042			}
2043		}
2044	}
2045
2046	if (iid < 0) {
2047		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2048			if (port->wwpn_iid[i].in_use == 0 &&
2049			    port->wwpn_iid[i].wwpn == 0 &&
2050			    port->wwpn_iid[i].name == NULL) {
2051				iid = i;
2052				break;
2053			}
2054		}
2055	}
2056
2057	if (iid < 0) {
2058		best = -1;
2059		best_time = INT32_MAX;
2060		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2061			if (port->wwpn_iid[i].in_use == 0) {
2062				if (port->wwpn_iid[i].last_use < best_time) {
2063					best = i;
2064					best_time = port->wwpn_iid[i].last_use;
2065				}
2066			}
2067		}
2068		iid = best;
2069	}
2070
2071	if (iid < 0) {
2072		mtx_unlock(&softc->ctl_lock);
2073		free(name, M_CTL);
2074		return (-2);
2075	}
2076
2077	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2078		/*
2079		 * This is not an error yet.
2080		 */
2081		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2082#if 0
2083			printf("%s: port %d iid %u WWPN %#jx arrived"
2084			    " again\n", __func__, port->targ_port,
2085			    iid, (uintmax_t)wwpn);
2086#endif
2087			goto take;
2088		}
2089		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2090		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
2091#if 0
2092			printf("%s: port %d iid %u name '%s' arrived"
2093			    " again\n", __func__, port->targ_port,
2094			    iid, name);
2095#endif
2096			goto take;
2097		}
2098
2099		/*
2100		 * This is an error, but what do we do about it?  The
2101		 * driver is telling us we have a new WWPN for this
2102		 * initiator ID, so we pretty much need to use it.
2103		 */
2104		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2105		    " but WWPN %#jx '%s' is still at that address\n",
2106		    __func__, port->targ_port, iid, wwpn, name,
2107		    (uintmax_t)port->wwpn_iid[iid].wwpn,
2108		    port->wwpn_iid[iid].name);
2109
2110		/*
2111		 * XXX KDM clear have_ca and ua_pending on each LUN for
2112		 * this initiator.
2113		 */
2114	}
2115take:
2116	free(port->wwpn_iid[iid].name, M_CTL);
2117	port->wwpn_iid[iid].name = name;
2118	port->wwpn_iid[iid].wwpn = wwpn;
2119	port->wwpn_iid[iid].in_use++;
2120	mtx_unlock(&softc->ctl_lock);
2121	ctl_isc_announce_iid(port, iid);
2122
2123	return (iid);
2124}
2125
2126static int
2127ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2128{
2129	int len;
2130
2131	switch (port->port_type) {
2132	case CTL_PORT_FC:
2133	{
2134		struct scsi_transportid_fcp *id =
2135		    (struct scsi_transportid_fcp *)buf;
2136		if (port->wwpn_iid[iid].wwpn == 0)
2137			return (0);
2138		memset(id, 0, sizeof(*id));
2139		id->format_protocol = SCSI_PROTO_FC;
2140		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2141		return (sizeof(*id));
2142	}
2143	case CTL_PORT_ISCSI:
2144	{
2145		struct scsi_transportid_iscsi_port *id =
2146		    (struct scsi_transportid_iscsi_port *)buf;
2147		if (port->wwpn_iid[iid].name == NULL)
2148			return (0);
2149		memset(id, 0, 256);
2150		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2151		    SCSI_PROTO_ISCSI;
2152		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2153		len = roundup2(min(len, 252), 4);
2154		scsi_ulto2b(len, id->additional_length);
2155		return (sizeof(*id) + len);
2156	}
2157	case CTL_PORT_SAS:
2158	{
2159		struct scsi_transportid_sas *id =
2160		    (struct scsi_transportid_sas *)buf;
2161		if (port->wwpn_iid[iid].wwpn == 0)
2162			return (0);
2163		memset(id, 0, sizeof(*id));
2164		id->format_protocol = SCSI_PROTO_SAS;
2165		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2166		return (sizeof(*id));
2167	}
2168	default:
2169	{
2170		struct scsi_transportid_spi *id =
2171		    (struct scsi_transportid_spi *)buf;
2172		memset(id, 0, sizeof(*id));
2173		id->format_protocol = SCSI_PROTO_SPI;
2174		scsi_ulto2b(iid, id->scsi_addr);
2175		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2176		return (sizeof(*id));
2177	}
2178	}
2179}
2180
2181/*
2182 * Serialize a command that went down the "wrong" side, and so was sent to
2183 * this controller for execution.  The logic is a little different than the
2184 * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2185 * sent back to the other side, but in the success case, we execute the
2186 * command on this side (XFER mode) or tell the other side to execute it
2187 * (SER_ONLY mode).
2188 */
2189static int
2190ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2191{
2192	struct ctl_softc *softc = control_softc;
2193	union ctl_ha_msg msg_info;
2194	struct ctl_port *port;
2195	struct ctl_lun *lun;
2196	const struct ctl_cmd_entry *entry;
2197	int retval = 0;
2198	uint32_t targ_lun;
2199
2200	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2201	mtx_lock(&softc->ctl_lock);
2202
2203	/* Make sure that we know about this port. */
2204	port = ctl_io_port(&ctsio->io_hdr);
2205	if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2206		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2207					 /*retry_count*/ 1);
2208		goto badjuju;
2209	}
2210
2211	/* Make sure that we know about this LUN. */
2212	if ((targ_lun < CTL_MAX_LUNS) &&
2213	    ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
2214		mtx_lock(&lun->lun_lock);
2215		mtx_unlock(&softc->ctl_lock);
2216		/*
2217		 * If the LUN is invalid, pretend that it doesn't exist.
2218		 * It will go away as soon as all pending I/O has been
2219		 * completed.
2220		 */
2221		if (lun->flags & CTL_LUN_DISABLED) {
2222			mtx_unlock(&lun->lun_lock);
2223			lun = NULL;
2224		}
2225	} else {
2226		mtx_unlock(&softc->ctl_lock);
2227		lun = NULL;
2228	}
2229	if (lun == NULL) {
2230		/*
2231		 * The other node would not send this request to us unless
2232		 * received announce that we are primary node for this LUN.
2233		 * If this LUN does not exist now, it is probably result of
2234		 * a race, so respond to initiator in the most opaque way.
2235		 */
2236		ctl_set_busy(ctsio);
2237		goto badjuju;
2238	}
2239
2240	entry = ctl_get_cmd_entry(ctsio, NULL);
2241	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2242		mtx_unlock(&lun->lun_lock);
2243		goto badjuju;
2244	}
2245
2246	ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
2247	ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = lun->be_lun;
2248
2249	/*
2250	 * Every I/O goes into the OOA queue for a
2251	 * particular LUN, and stays there until completion.
2252	 */
2253#ifdef CTL_TIME_IO
2254	if (TAILQ_EMPTY(&lun->ooa_queue))
2255		lun->idle_time += getsbinuptime() - lun->last_busy;
2256#endif
2257	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2258
2259	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2260		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2261		 ooa_links))) {
2262	case CTL_ACTION_BLOCK:
2263		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2264		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2265				  blocked_links);
2266		mtx_unlock(&lun->lun_lock);
2267		break;
2268	case CTL_ACTION_PASS:
2269	case CTL_ACTION_SKIP:
2270		if (softc->ha_mode == CTL_HA_MODE_XFER) {
2271			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2272			ctl_enqueue_rtr((union ctl_io *)ctsio);
2273			mtx_unlock(&lun->lun_lock);
2274		} else {
2275			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2276			mtx_unlock(&lun->lun_lock);
2277
2278			/* send msg back to other side */
2279			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2280			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2281			msg_info.hdr.msg_type = CTL_MSG_R2R;
2282			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2283			    sizeof(msg_info.hdr), M_WAITOK);
2284		}
2285		break;
2286	case CTL_ACTION_OVERLAP:
2287		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2288		mtx_unlock(&lun->lun_lock);
2289		ctl_set_overlapped_cmd(ctsio);
2290		goto badjuju;
2291	case CTL_ACTION_OVERLAP_TAG:
2292		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2293		mtx_unlock(&lun->lun_lock);
2294		ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2295		goto badjuju;
2296	case CTL_ACTION_ERROR:
2297	default:
2298		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2299		mtx_unlock(&lun->lun_lock);
2300
2301		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2302					 /*retry_count*/ 0);
2303badjuju:
2304		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2305		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2306		msg_info.hdr.serializing_sc = NULL;
2307		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2308		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2309		    sizeof(msg_info.scsi), M_WAITOK);
2310		retval = 1;
2311		break;
2312	}
2313	return (retval);
2314}
2315
2316/*
2317 * Returns 0 for success, errno for failure.
2318 */
2319static void
2320ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2321		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2322{
2323	union ctl_io *io;
2324
2325	mtx_lock(&lun->lun_lock);
2326	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2327	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2328	     ooa_links)) {
2329		struct ctl_ooa_entry *entry;
2330
2331		/*
2332		 * If we've got more than we can fit, just count the
2333		 * remaining entries.
2334		 */
2335		if (*cur_fill_num >= ooa_hdr->alloc_num)
2336			continue;
2337
2338		entry = &kern_entries[*cur_fill_num];
2339
2340		entry->tag_num = io->scsiio.tag_num;
2341		entry->lun_num = lun->lun;
2342#ifdef CTL_TIME_IO
2343		entry->start_bt = io->io_hdr.start_bt;
2344#endif
2345		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2346		entry->cdb_len = io->scsiio.cdb_len;
2347		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2348			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2349
2350		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2351			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2352
2353		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2354			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2355
2356		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2357			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2358
2359		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2360			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2361	}
2362	mtx_unlock(&lun->lun_lock);
2363}
2364
2365static void *
2366ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2367		 size_t error_str_len)
2368{
2369	void *kptr;
2370
2371	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2372
2373	if (copyin(user_addr, kptr, len) != 0) {
2374		snprintf(error_str, error_str_len, "Error copying %d bytes "
2375			 "from user address %p to kernel address %p", len,
2376			 user_addr, kptr);
2377		free(kptr, M_CTL);
2378		return (NULL);
2379	}
2380
2381	return (kptr);
2382}
2383
2384static void
2385ctl_free_args(int num_args, struct ctl_be_arg *args)
2386{
2387	int i;
2388
2389	if (args == NULL)
2390		return;
2391
2392	for (i = 0; i < num_args; i++) {
2393		free(args[i].kname, M_CTL);
2394		free(args[i].kvalue, M_CTL);
2395	}
2396
2397	free(args, M_CTL);
2398}
2399
2400static struct ctl_be_arg *
2401ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2402		char *error_str, size_t error_str_len)
2403{
2404	struct ctl_be_arg *args;
2405	int i;
2406
2407	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2408				error_str, error_str_len);
2409
2410	if (args == NULL)
2411		goto bailout;
2412
2413	for (i = 0; i < num_args; i++) {
2414		args[i].kname = NULL;
2415		args[i].kvalue = NULL;
2416	}
2417
2418	for (i = 0; i < num_args; i++) {
2419		uint8_t *tmpptr;
2420
2421		args[i].kname = ctl_copyin_alloc(args[i].name,
2422			args[i].namelen, error_str, error_str_len);
2423		if (args[i].kname == NULL)
2424			goto bailout;
2425
2426		if (args[i].kname[args[i].namelen - 1] != '\0') {
2427			snprintf(error_str, error_str_len, "Argument %d "
2428				 "name is not NUL-terminated", i);
2429			goto bailout;
2430		}
2431
2432		if (args[i].flags & CTL_BEARG_RD) {
2433			tmpptr = ctl_copyin_alloc(args[i].value,
2434				args[i].vallen, error_str, error_str_len);
2435			if (tmpptr == NULL)
2436				goto bailout;
2437			if ((args[i].flags & CTL_BEARG_ASCII)
2438			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2439				snprintf(error_str, error_str_len, "Argument "
2440				    "%d value is not NUL-terminated", i);
2441				goto bailout;
2442			}
2443			args[i].kvalue = tmpptr;
2444		} else {
2445			args[i].kvalue = malloc(args[i].vallen,
2446			    M_CTL, M_WAITOK | M_ZERO);
2447		}
2448	}
2449
2450	return (args);
2451bailout:
2452
2453	ctl_free_args(num_args, args);
2454
2455	return (NULL);
2456}
2457
2458static void
2459ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2460{
2461	int i;
2462
2463	for (i = 0; i < num_args; i++) {
2464		if (args[i].flags & CTL_BEARG_WR)
2465			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2466	}
2467}
2468
2469/*
2470 * Escape characters that are illegal or not recommended in XML.
2471 */
2472int
2473ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2474{
2475	char *end = str + size;
2476	int retval;
2477
2478	retval = 0;
2479
2480	for (; *str && str < end; str++) {
2481		switch (*str) {
2482		case '&':
2483			retval = sbuf_printf(sb, "&amp;");
2484			break;
2485		case '>':
2486			retval = sbuf_printf(sb, "&gt;");
2487			break;
2488		case '<':
2489			retval = sbuf_printf(sb, "&lt;");
2490			break;
2491		default:
2492			retval = sbuf_putc(sb, *str);
2493			break;
2494		}
2495
2496		if (retval != 0)
2497			break;
2498
2499	}
2500
2501	return (retval);
2502}
2503
2504static void
2505ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2506{
2507	struct scsi_vpd_id_descriptor *desc;
2508	int i;
2509
2510	if (id == NULL || id->len < 4)
2511		return;
2512	desc = (struct scsi_vpd_id_descriptor *)id->data;
2513	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2514	case SVPD_ID_TYPE_T10:
2515		sbuf_printf(sb, "t10.");
2516		break;
2517	case SVPD_ID_TYPE_EUI64:
2518		sbuf_printf(sb, "eui.");
2519		break;
2520	case SVPD_ID_TYPE_NAA:
2521		sbuf_printf(sb, "naa.");
2522		break;
2523	case SVPD_ID_TYPE_SCSI_NAME:
2524		break;
2525	}
2526	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2527	case SVPD_ID_CODESET_BINARY:
2528		for (i = 0; i < desc->length; i++)
2529			sbuf_printf(sb, "%02x", desc->identifier[i]);
2530		break;
2531	case SVPD_ID_CODESET_ASCII:
2532		sbuf_printf(sb, "%.*s", (int)desc->length,
2533		    (char *)desc->identifier);
2534		break;
2535	case SVPD_ID_CODESET_UTF8:
2536		sbuf_printf(sb, "%s", (char *)desc->identifier);
2537		break;
2538	}
2539}
2540
2541static int
2542ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2543	  struct thread *td)
2544{
2545	struct ctl_softc *softc = dev->si_drv1;
2546	struct ctl_lun *lun;
2547	int retval;
2548
2549	retval = 0;
2550
2551	switch (cmd) {
2552	case CTL_IO:
2553		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2554		break;
2555	case CTL_ENABLE_PORT:
2556	case CTL_DISABLE_PORT:
2557	case CTL_SET_PORT_WWNS: {
2558		struct ctl_port *port;
2559		struct ctl_port_entry *entry;
2560
2561		entry = (struct ctl_port_entry *)addr;
2562
2563		mtx_lock(&softc->ctl_lock);
2564		STAILQ_FOREACH(port, &softc->port_list, links) {
2565			int action, done;
2566
2567			if (port->targ_port < softc->port_min ||
2568			    port->targ_port >= softc->port_max)
2569				continue;
2570
2571			action = 0;
2572			done = 0;
2573			if ((entry->port_type == CTL_PORT_NONE)
2574			 && (entry->targ_port == port->targ_port)) {
2575				/*
2576				 * If the user only wants to enable or
2577				 * disable or set WWNs on a specific port,
2578				 * do the operation and we're done.
2579				 */
2580				action = 1;
2581				done = 1;
2582			} else if (entry->port_type & port->port_type) {
2583				/*
2584				 * Compare the user's type mask with the
2585				 * particular frontend type to see if we
2586				 * have a match.
2587				 */
2588				action = 1;
2589				done = 0;
2590
2591				/*
2592				 * Make sure the user isn't trying to set
2593				 * WWNs on multiple ports at the same time.
2594				 */
2595				if (cmd == CTL_SET_PORT_WWNS) {
2596					printf("%s: Can't set WWNs on "
2597					       "multiple ports\n", __func__);
2598					retval = EINVAL;
2599					break;
2600				}
2601			}
2602			if (action == 0)
2603				continue;
2604
2605			/*
2606			 * XXX KDM we have to drop the lock here, because
2607			 * the online/offline operations can potentially
2608			 * block.  We need to reference count the frontends
2609			 * so they can't go away,
2610			 */
2611			if (cmd == CTL_ENABLE_PORT) {
2612				mtx_unlock(&softc->ctl_lock);
2613				ctl_port_online(port);
2614				mtx_lock(&softc->ctl_lock);
2615			} else if (cmd == CTL_DISABLE_PORT) {
2616				mtx_unlock(&softc->ctl_lock);
2617				ctl_port_offline(port);
2618				mtx_lock(&softc->ctl_lock);
2619			} else if (cmd == CTL_SET_PORT_WWNS) {
2620				ctl_port_set_wwns(port,
2621				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2622				    1 : 0, entry->wwnn,
2623				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2624				    1 : 0, entry->wwpn);
2625			}
2626			if (done != 0)
2627				break;
2628		}
2629		mtx_unlock(&softc->ctl_lock);
2630		break;
2631	}
2632	case CTL_GET_OOA: {
2633		struct ctl_ooa *ooa_hdr;
2634		struct ctl_ooa_entry *entries;
2635		uint32_t cur_fill_num;
2636
2637		ooa_hdr = (struct ctl_ooa *)addr;
2638
2639		if ((ooa_hdr->alloc_len == 0)
2640		 || (ooa_hdr->alloc_num == 0)) {
2641			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2642			       "must be non-zero\n", __func__,
2643			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2644			retval = EINVAL;
2645			break;
2646		}
2647
2648		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2649		    sizeof(struct ctl_ooa_entry))) {
2650			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2651			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2652			       __func__, ooa_hdr->alloc_len,
2653			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2654			retval = EINVAL;
2655			break;
2656		}
2657
2658		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2659		if (entries == NULL) {
2660			printf("%s: could not allocate %d bytes for OOA "
2661			       "dump\n", __func__, ooa_hdr->alloc_len);
2662			retval = ENOMEM;
2663			break;
2664		}
2665
2666		mtx_lock(&softc->ctl_lock);
2667		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2668		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2669		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2670			mtx_unlock(&softc->ctl_lock);
2671			free(entries, M_CTL);
2672			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2673			       __func__, (uintmax_t)ooa_hdr->lun_num);
2674			retval = EINVAL;
2675			break;
2676		}
2677
2678		cur_fill_num = 0;
2679
2680		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2681			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2682				ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2683				    ooa_hdr, entries);
2684			}
2685		} else {
2686			lun = softc->ctl_luns[ooa_hdr->lun_num];
2687			ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2688			    entries);
2689		}
2690		mtx_unlock(&softc->ctl_lock);
2691
2692		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2693		ooa_hdr->fill_len = ooa_hdr->fill_num *
2694			sizeof(struct ctl_ooa_entry);
2695		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2696		if (retval != 0) {
2697			printf("%s: error copying out %d bytes for OOA dump\n",
2698			       __func__, ooa_hdr->fill_len);
2699		}
2700
2701		getbinuptime(&ooa_hdr->cur_bt);
2702
2703		if (cur_fill_num > ooa_hdr->alloc_num) {
2704			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2705			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2706		} else {
2707			ooa_hdr->dropped_num = 0;
2708			ooa_hdr->status = CTL_OOA_OK;
2709		}
2710
2711		free(entries, M_CTL);
2712		break;
2713	}
2714	case CTL_DELAY_IO: {
2715		struct ctl_io_delay_info *delay_info;
2716
2717		delay_info = (struct ctl_io_delay_info *)addr;
2718
2719#ifdef CTL_IO_DELAY
2720		mtx_lock(&softc->ctl_lock);
2721
2722		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2723		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2724			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2725		} else {
2726			lun = softc->ctl_luns[delay_info->lun_id];
2727			mtx_lock(&lun->lun_lock);
2728
2729			delay_info->status = CTL_DELAY_STATUS_OK;
2730
2731			switch (delay_info->delay_type) {
2732			case CTL_DELAY_TYPE_CONT:
2733				break;
2734			case CTL_DELAY_TYPE_ONESHOT:
2735				break;
2736			default:
2737				delay_info->status =
2738					CTL_DELAY_STATUS_INVALID_TYPE;
2739				break;
2740			}
2741
2742			switch (delay_info->delay_loc) {
2743			case CTL_DELAY_LOC_DATAMOVE:
2744				lun->delay_info.datamove_type =
2745					delay_info->delay_type;
2746				lun->delay_info.datamove_delay =
2747					delay_info->delay_secs;
2748				break;
2749			case CTL_DELAY_LOC_DONE:
2750				lun->delay_info.done_type =
2751					delay_info->delay_type;
2752				lun->delay_info.done_delay =
2753					delay_info->delay_secs;
2754				break;
2755			default:
2756				delay_info->status =
2757					CTL_DELAY_STATUS_INVALID_LOC;
2758				break;
2759			}
2760			mtx_unlock(&lun->lun_lock);
2761		}
2762
2763		mtx_unlock(&softc->ctl_lock);
2764#else
2765		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2766#endif /* CTL_IO_DELAY */
2767		break;
2768	}
2769	case CTL_GETSTATS: {
2770		struct ctl_stats *stats;
2771		int i;
2772
2773		stats = (struct ctl_stats *)addr;
2774
2775		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2776		     stats->alloc_len) {
2777			stats->status = CTL_SS_NEED_MORE_SPACE;
2778			stats->num_luns = softc->num_luns;
2779			break;
2780		}
2781		/*
2782		 * XXX KDM no locking here.  If the LUN list changes,
2783		 * things can blow up.
2784		 */
2785		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2786		     i++, lun = STAILQ_NEXT(lun, links)) {
2787			retval = copyout(&lun->stats, &stats->lun_stats[i],
2788					 sizeof(lun->stats));
2789			if (retval != 0)
2790				break;
2791		}
2792		stats->num_luns = softc->num_luns;
2793		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2794				 softc->num_luns;
2795		stats->status = CTL_SS_OK;
2796#ifdef CTL_TIME_IO
2797		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2798#else
2799		stats->flags = CTL_STATS_FLAG_NONE;
2800#endif
2801		getnanouptime(&stats->timestamp);
2802		break;
2803	}
2804	case CTL_ERROR_INJECT: {
2805		struct ctl_error_desc *err_desc, *new_err_desc;
2806
2807		err_desc = (struct ctl_error_desc *)addr;
2808
2809		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2810				      M_WAITOK | M_ZERO);
2811		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2812
2813		mtx_lock(&softc->ctl_lock);
2814		lun = softc->ctl_luns[err_desc->lun_id];
2815		if (lun == NULL) {
2816			mtx_unlock(&softc->ctl_lock);
2817			free(new_err_desc, M_CTL);
2818			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2819			       __func__, (uintmax_t)err_desc->lun_id);
2820			retval = EINVAL;
2821			break;
2822		}
2823		mtx_lock(&lun->lun_lock);
2824		mtx_unlock(&softc->ctl_lock);
2825
2826		/*
2827		 * We could do some checking here to verify the validity
2828		 * of the request, but given the complexity of error
2829		 * injection requests, the checking logic would be fairly
2830		 * complex.
2831		 *
2832		 * For now, if the request is invalid, it just won't get
2833		 * executed and might get deleted.
2834		 */
2835		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2836
2837		/*
2838		 * XXX KDM check to make sure the serial number is unique,
2839		 * in case we somehow manage to wrap.  That shouldn't
2840		 * happen for a very long time, but it's the right thing to
2841		 * do.
2842		 */
2843		new_err_desc->serial = lun->error_serial;
2844		err_desc->serial = lun->error_serial;
2845		lun->error_serial++;
2846
2847		mtx_unlock(&lun->lun_lock);
2848		break;
2849	}
2850	case CTL_ERROR_INJECT_DELETE: {
2851		struct ctl_error_desc *delete_desc, *desc, *desc2;
2852		int delete_done;
2853
2854		delete_desc = (struct ctl_error_desc *)addr;
2855		delete_done = 0;
2856
2857		mtx_lock(&softc->ctl_lock);
2858		lun = softc->ctl_luns[delete_desc->lun_id];
2859		if (lun == NULL) {
2860			mtx_unlock(&softc->ctl_lock);
2861			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2862			       __func__, (uintmax_t)delete_desc->lun_id);
2863			retval = EINVAL;
2864			break;
2865		}
2866		mtx_lock(&lun->lun_lock);
2867		mtx_unlock(&softc->ctl_lock);
2868		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2869			if (desc->serial != delete_desc->serial)
2870				continue;
2871
2872			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2873				      links);
2874			free(desc, M_CTL);
2875			delete_done = 1;
2876		}
2877		mtx_unlock(&lun->lun_lock);
2878		if (delete_done == 0) {
2879			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2880			       "error serial %ju on LUN %u\n", __func__,
2881			       delete_desc->serial, delete_desc->lun_id);
2882			retval = EINVAL;
2883			break;
2884		}
2885		break;
2886	}
2887	case CTL_DUMP_STRUCTS: {
2888		int i, j, k;
2889		struct ctl_port *port;
2890		struct ctl_frontend *fe;
2891
2892		mtx_lock(&softc->ctl_lock);
2893		printf("CTL Persistent Reservation information start:\n");
2894		for (i = 0; i < CTL_MAX_LUNS; i++) {
2895			lun = softc->ctl_luns[i];
2896
2897			if ((lun == NULL)
2898			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
2899				continue;
2900
2901			for (j = 0; j < CTL_MAX_PORTS; j++) {
2902				if (lun->pr_keys[j] == NULL)
2903					continue;
2904				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2905					if (lun->pr_keys[j][k] == 0)
2906						continue;
2907					printf("  LUN %d port %d iid %d key "
2908					       "%#jx\n", i, j, k,
2909					       (uintmax_t)lun->pr_keys[j][k]);
2910				}
2911			}
2912		}
2913		printf("CTL Persistent Reservation information end\n");
2914		printf("CTL Ports:\n");
2915		STAILQ_FOREACH(port, &softc->port_list, links) {
2916			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2917			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2918			       port->frontend->name, port->port_type,
2919			       port->physical_port, port->virtual_port,
2920			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2921			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2922				if (port->wwpn_iid[j].in_use == 0 &&
2923				    port->wwpn_iid[j].wwpn == 0 &&
2924				    port->wwpn_iid[j].name == NULL)
2925					continue;
2926
2927				printf("    iid %u use %d WWPN %#jx '%s'\n",
2928				    j, port->wwpn_iid[j].in_use,
2929				    (uintmax_t)port->wwpn_iid[j].wwpn,
2930				    port->wwpn_iid[j].name);
2931			}
2932		}
2933		printf("CTL Port information end\n");
2934		mtx_unlock(&softc->ctl_lock);
2935		/*
2936		 * XXX KDM calling this without a lock.  We'd likely want
2937		 * to drop the lock before calling the frontend's dump
2938		 * routine anyway.
2939		 */
2940		printf("CTL Frontends:\n");
2941		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2942			printf("  Frontend '%s'\n", fe->name);
2943			if (fe->fe_dump != NULL)
2944				fe->fe_dump();
2945		}
2946		printf("CTL Frontend information end\n");
2947		break;
2948	}
2949	case CTL_LUN_REQ: {
2950		struct ctl_lun_req *lun_req;
2951		struct ctl_backend_driver *backend;
2952
2953		lun_req = (struct ctl_lun_req *)addr;
2954
2955		backend = ctl_backend_find(lun_req->backend);
2956		if (backend == NULL) {
2957			lun_req->status = CTL_LUN_ERROR;
2958			snprintf(lun_req->error_str,
2959				 sizeof(lun_req->error_str),
2960				 "Backend \"%s\" not found.",
2961				 lun_req->backend);
2962			break;
2963		}
2964		if (lun_req->num_be_args > 0) {
2965			lun_req->kern_be_args = ctl_copyin_args(
2966				lun_req->num_be_args,
2967				lun_req->be_args,
2968				lun_req->error_str,
2969				sizeof(lun_req->error_str));
2970			if (lun_req->kern_be_args == NULL) {
2971				lun_req->status = CTL_LUN_ERROR;
2972				break;
2973			}
2974		}
2975
2976		retval = backend->ioctl(dev, cmd, addr, flag, td);
2977
2978		if (lun_req->num_be_args > 0) {
2979			ctl_copyout_args(lun_req->num_be_args,
2980				      lun_req->kern_be_args);
2981			ctl_free_args(lun_req->num_be_args,
2982				      lun_req->kern_be_args);
2983		}
2984		break;
2985	}
2986	case CTL_LUN_LIST: {
2987		struct sbuf *sb;
2988		struct ctl_lun_list *list;
2989		struct ctl_option *opt;
2990
2991		list = (struct ctl_lun_list *)addr;
2992
2993		/*
2994		 * Allocate a fixed length sbuf here, based on the length
2995		 * of the user's buffer.  We could allocate an auto-extending
2996		 * buffer, and then tell the user how much larger our
2997		 * amount of data is than his buffer, but that presents
2998		 * some problems:
2999		 *
3000		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3001		 *     we can't hold a lock while calling them with an
3002		 *     auto-extending buffer.
3003 		 *
3004		 * 2.  There is not currently a LUN reference counting
3005		 *     mechanism, outside of outstanding transactions on
3006		 *     the LUN's OOA queue.  So a LUN could go away on us
3007		 *     while we're getting the LUN number, backend-specific
3008		 *     information, etc.  Thus, given the way things
3009		 *     currently work, we need to hold the CTL lock while
3010		 *     grabbing LUN information.
3011		 *
3012		 * So, from the user's standpoint, the best thing to do is
3013		 * allocate what he thinks is a reasonable buffer length,
3014		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3015		 * double the buffer length and try again.  (And repeat
3016		 * that until he succeeds.)
3017		 */
3018		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3019		if (sb == NULL) {
3020			list->status = CTL_LUN_LIST_ERROR;
3021			snprintf(list->error_str, sizeof(list->error_str),
3022				 "Unable to allocate %d bytes for LUN list",
3023				 list->alloc_len);
3024			break;
3025		}
3026
3027		sbuf_printf(sb, "<ctllunlist>\n");
3028
3029		mtx_lock(&softc->ctl_lock);
3030		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3031			mtx_lock(&lun->lun_lock);
3032			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3033					     (uintmax_t)lun->lun);
3034
3035			/*
3036			 * Bail out as soon as we see that we've overfilled
3037			 * the buffer.
3038			 */
3039			if (retval != 0)
3040				break;
3041
3042			retval = sbuf_printf(sb, "\t<backend_type>%s"
3043					     "</backend_type>\n",
3044					     (lun->backend == NULL) ?  "none" :
3045					     lun->backend->name);
3046
3047			if (retval != 0)
3048				break;
3049
3050			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3051					     lun->be_lun->lun_type);
3052
3053			if (retval != 0)
3054				break;
3055
3056			if (lun->backend == NULL) {
3057				retval = sbuf_printf(sb, "</lun>\n");
3058				if (retval != 0)
3059					break;
3060				continue;
3061			}
3062
3063			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3064					     (lun->be_lun->maxlba > 0) ?
3065					     lun->be_lun->maxlba + 1 : 0);
3066
3067			if (retval != 0)
3068				break;
3069
3070			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3071					     lun->be_lun->blocksize);
3072
3073			if (retval != 0)
3074				break;
3075
3076			retval = sbuf_printf(sb, "\t<serial_number>");
3077
3078			if (retval != 0)
3079				break;
3080
3081			retval = ctl_sbuf_printf_esc(sb,
3082			    lun->be_lun->serial_num,
3083			    sizeof(lun->be_lun->serial_num));
3084
3085			if (retval != 0)
3086				break;
3087
3088			retval = sbuf_printf(sb, "</serial_number>\n");
3089
3090			if (retval != 0)
3091				break;
3092
3093			retval = sbuf_printf(sb, "\t<device_id>");
3094
3095			if (retval != 0)
3096				break;
3097
3098			retval = ctl_sbuf_printf_esc(sb,
3099			    lun->be_lun->device_id,
3100			    sizeof(lun->be_lun->device_id));
3101
3102			if (retval != 0)
3103				break;
3104
3105			retval = sbuf_printf(sb, "</device_id>\n");
3106
3107			if (retval != 0)
3108				break;
3109
3110			if (lun->backend->lun_info != NULL) {
3111				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3112				if (retval != 0)
3113					break;
3114			}
3115			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3116				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3117				    opt->name, opt->value, opt->name);
3118				if (retval != 0)
3119					break;
3120			}
3121
3122			retval = sbuf_printf(sb, "</lun>\n");
3123
3124			if (retval != 0)
3125				break;
3126			mtx_unlock(&lun->lun_lock);
3127		}
3128		if (lun != NULL)
3129			mtx_unlock(&lun->lun_lock);
3130		mtx_unlock(&softc->ctl_lock);
3131
3132		if ((retval != 0)
3133		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3134			retval = 0;
3135			sbuf_delete(sb);
3136			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3137			snprintf(list->error_str, sizeof(list->error_str),
3138				 "Out of space, %d bytes is too small",
3139				 list->alloc_len);
3140			break;
3141		}
3142
3143		sbuf_finish(sb);
3144
3145		retval = copyout(sbuf_data(sb), list->lun_xml,
3146				 sbuf_len(sb) + 1);
3147
3148		list->fill_len = sbuf_len(sb) + 1;
3149		list->status = CTL_LUN_LIST_OK;
3150		sbuf_delete(sb);
3151		break;
3152	}
3153	case CTL_ISCSI: {
3154		struct ctl_iscsi *ci;
3155		struct ctl_frontend *fe;
3156
3157		ci = (struct ctl_iscsi *)addr;
3158
3159		fe = ctl_frontend_find("iscsi");
3160		if (fe == NULL) {
3161			ci->status = CTL_ISCSI_ERROR;
3162			snprintf(ci->error_str, sizeof(ci->error_str),
3163			    "Frontend \"iscsi\" not found.");
3164			break;
3165		}
3166
3167		retval = fe->ioctl(dev, cmd, addr, flag, td);
3168		break;
3169	}
3170	case CTL_PORT_REQ: {
3171		struct ctl_req *req;
3172		struct ctl_frontend *fe;
3173
3174		req = (struct ctl_req *)addr;
3175
3176		fe = ctl_frontend_find(req->driver);
3177		if (fe == NULL) {
3178			req->status = CTL_LUN_ERROR;
3179			snprintf(req->error_str, sizeof(req->error_str),
3180			    "Frontend \"%s\" not found.", req->driver);
3181			break;
3182		}
3183		if (req->num_args > 0) {
3184			req->kern_args = ctl_copyin_args(req->num_args,
3185			    req->args, req->error_str, sizeof(req->error_str));
3186			if (req->kern_args == NULL) {
3187				req->status = CTL_LUN_ERROR;
3188				break;
3189			}
3190		}
3191
3192		if (fe->ioctl)
3193			retval = fe->ioctl(dev, cmd, addr, flag, td);
3194		else
3195			retval = ENODEV;
3196
3197		if (req->num_args > 0) {
3198			ctl_copyout_args(req->num_args, req->kern_args);
3199			ctl_free_args(req->num_args, req->kern_args);
3200		}
3201		break;
3202	}
3203	case CTL_PORT_LIST: {
3204		struct sbuf *sb;
3205		struct ctl_port *port;
3206		struct ctl_lun_list *list;
3207		struct ctl_option *opt;
3208		int j;
3209		uint32_t plun;
3210
3211		list = (struct ctl_lun_list *)addr;
3212
3213		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3214		if (sb == NULL) {
3215			list->status = CTL_LUN_LIST_ERROR;
3216			snprintf(list->error_str, sizeof(list->error_str),
3217				 "Unable to allocate %d bytes for LUN list",
3218				 list->alloc_len);
3219			break;
3220		}
3221
3222		sbuf_printf(sb, "<ctlportlist>\n");
3223
3224		mtx_lock(&softc->ctl_lock);
3225		STAILQ_FOREACH(port, &softc->port_list, links) {
3226			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3227					     (uintmax_t)port->targ_port);
3228
3229			/*
3230			 * Bail out as soon as we see that we've overfilled
3231			 * the buffer.
3232			 */
3233			if (retval != 0)
3234				break;
3235
3236			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3237			    "</frontend_type>\n", port->frontend->name);
3238			if (retval != 0)
3239				break;
3240
3241			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3242					     port->port_type);
3243			if (retval != 0)
3244				break;
3245
3246			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3247			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3248			if (retval != 0)
3249				break;
3250
3251			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3252			    port->port_name);
3253			if (retval != 0)
3254				break;
3255
3256			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3257			    port->physical_port);
3258			if (retval != 0)
3259				break;
3260
3261			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3262			    port->virtual_port);
3263			if (retval != 0)
3264				break;
3265
3266			if (port->target_devid != NULL) {
3267				sbuf_printf(sb, "\t<target>");
3268				ctl_id_sbuf(port->target_devid, sb);
3269				sbuf_printf(sb, "</target>\n");
3270			}
3271
3272			if (port->port_devid != NULL) {
3273				sbuf_printf(sb, "\t<port>");
3274				ctl_id_sbuf(port->port_devid, sb);
3275				sbuf_printf(sb, "</port>\n");
3276			}
3277
3278			if (port->port_info != NULL) {
3279				retval = port->port_info(port->onoff_arg, sb);
3280				if (retval != 0)
3281					break;
3282			}
3283			STAILQ_FOREACH(opt, &port->options, links) {
3284				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3285				    opt->name, opt->value, opt->name);
3286				if (retval != 0)
3287					break;
3288			}
3289
3290			if (port->lun_map != NULL) {
3291				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3292				for (j = 0; j < CTL_MAX_LUNS; j++) {
3293					plun = ctl_lun_map_from_port(port, j);
3294					if (plun >= CTL_MAX_LUNS)
3295						continue;
3296					sbuf_printf(sb,
3297					    "\t<lun id=\"%u\">%u</lun>\n",
3298					    j, plun);
3299				}
3300			}
3301
3302			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3303				if (port->wwpn_iid[j].in_use == 0 ||
3304				    (port->wwpn_iid[j].wwpn == 0 &&
3305				     port->wwpn_iid[j].name == NULL))
3306					continue;
3307
3308				if (port->wwpn_iid[j].name != NULL)
3309					retval = sbuf_printf(sb,
3310					    "\t<initiator id=\"%u\">%s</initiator>\n",
3311					    j, port->wwpn_iid[j].name);
3312				else
3313					retval = sbuf_printf(sb,
3314					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3315					    j, port->wwpn_iid[j].wwpn);
3316				if (retval != 0)
3317					break;
3318			}
3319			if (retval != 0)
3320				break;
3321
3322			retval = sbuf_printf(sb, "</targ_port>\n");
3323			if (retval != 0)
3324				break;
3325		}
3326		mtx_unlock(&softc->ctl_lock);
3327
3328		if ((retval != 0)
3329		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3330			retval = 0;
3331			sbuf_delete(sb);
3332			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3333			snprintf(list->error_str, sizeof(list->error_str),
3334				 "Out of space, %d bytes is too small",
3335				 list->alloc_len);
3336			break;
3337		}
3338
3339		sbuf_finish(sb);
3340
3341		retval = copyout(sbuf_data(sb), list->lun_xml,
3342				 sbuf_len(sb) + 1);
3343
3344		list->fill_len = sbuf_len(sb) + 1;
3345		list->status = CTL_LUN_LIST_OK;
3346		sbuf_delete(sb);
3347		break;
3348	}
3349	case CTL_LUN_MAP: {
3350		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3351		struct ctl_port *port;
3352
3353		mtx_lock(&softc->ctl_lock);
3354		if (lm->port < softc->port_min ||
3355		    lm->port >= softc->port_max ||
3356		    (port = softc->ctl_ports[lm->port]) == NULL) {
3357			mtx_unlock(&softc->ctl_lock);
3358			return (ENXIO);
3359		}
3360		if (port->status & CTL_PORT_STATUS_ONLINE) {
3361			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3362				if (ctl_lun_map_to_port(port, lun->lun) >=
3363				    CTL_MAX_LUNS)
3364					continue;
3365				mtx_lock(&lun->lun_lock);
3366				ctl_est_ua_port(lun, lm->port, -1,
3367				    CTL_UA_LUN_CHANGE);
3368				mtx_unlock(&lun->lun_lock);
3369			}
3370		}
3371		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3372		if (lm->plun < CTL_MAX_LUNS) {
3373			if (lm->lun == UINT32_MAX)
3374				retval = ctl_lun_map_unset(port, lm->plun);
3375			else if (lm->lun < CTL_MAX_LUNS &&
3376			    softc->ctl_luns[lm->lun] != NULL)
3377				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3378			else
3379				return (ENXIO);
3380		} else if (lm->plun == UINT32_MAX) {
3381			if (lm->lun == UINT32_MAX)
3382				retval = ctl_lun_map_deinit(port);
3383			else
3384				retval = ctl_lun_map_init(port);
3385		} else
3386			return (ENXIO);
3387		if (port->status & CTL_PORT_STATUS_ONLINE)
3388			ctl_isc_announce_port(port);
3389		break;
3390	}
3391	default: {
3392		/* XXX KDM should we fix this? */
3393#if 0
3394		struct ctl_backend_driver *backend;
3395		unsigned int type;
3396		int found;
3397
3398		found = 0;
3399
3400		/*
3401		 * We encode the backend type as the ioctl type for backend
3402		 * ioctls.  So parse it out here, and then search for a
3403		 * backend of this type.
3404		 */
3405		type = _IOC_TYPE(cmd);
3406
3407		STAILQ_FOREACH(backend, &softc->be_list, links) {
3408			if (backend->type == type) {
3409				found = 1;
3410				break;
3411			}
3412		}
3413		if (found == 0) {
3414			printf("ctl: unknown ioctl command %#lx or backend "
3415			       "%d\n", cmd, type);
3416			retval = EINVAL;
3417			break;
3418		}
3419		retval = backend->ioctl(dev, cmd, addr, flag, td);
3420#endif
3421		retval = ENOTTY;
3422		break;
3423	}
3424	}
3425	return (retval);
3426}
3427
3428uint32_t
3429ctl_get_initindex(struct ctl_nexus *nexus)
3430{
3431	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3432}
3433
3434int
3435ctl_lun_map_init(struct ctl_port *port)
3436{
3437	struct ctl_softc *softc = port->ctl_softc;
3438	struct ctl_lun *lun;
3439	uint32_t i;
3440
3441	if (port->lun_map == NULL)
3442		port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3443		    M_CTL, M_NOWAIT);
3444	if (port->lun_map == NULL)
3445		return (ENOMEM);
3446	for (i = 0; i < CTL_MAX_LUNS; i++)
3447		port->lun_map[i] = UINT32_MAX;
3448	if (port->status & CTL_PORT_STATUS_ONLINE) {
3449		if (port->lun_disable != NULL) {
3450			STAILQ_FOREACH(lun, &softc->lun_list, links)
3451				port->lun_disable(port->targ_lun_arg, lun->lun);
3452		}
3453		ctl_isc_announce_port(port);
3454	}
3455	return (0);
3456}
3457
3458int
3459ctl_lun_map_deinit(struct ctl_port *port)
3460{
3461	struct ctl_softc *softc = port->ctl_softc;
3462	struct ctl_lun *lun;
3463
3464	if (port->lun_map == NULL)
3465		return (0);
3466	free(port->lun_map, M_CTL);
3467	port->lun_map = NULL;
3468	if (port->status & CTL_PORT_STATUS_ONLINE) {
3469		if (port->lun_enable != NULL) {
3470			STAILQ_FOREACH(lun, &softc->lun_list, links)
3471				port->lun_enable(port->targ_lun_arg, lun->lun);
3472		}
3473		ctl_isc_announce_port(port);
3474	}
3475	return (0);
3476}
3477
3478int
3479ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3480{
3481	int status;
3482	uint32_t old;
3483
3484	if (port->lun_map == NULL) {
3485		status = ctl_lun_map_init(port);
3486		if (status != 0)
3487			return (status);
3488	}
3489	old = port->lun_map[plun];
3490	port->lun_map[plun] = glun;
3491	if ((port->status & CTL_PORT_STATUS_ONLINE) && old >= CTL_MAX_LUNS) {
3492		if (port->lun_enable != NULL)
3493			port->lun_enable(port->targ_lun_arg, plun);
3494		ctl_isc_announce_port(port);
3495	}
3496	return (0);
3497}
3498
3499int
3500ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3501{
3502	uint32_t old;
3503
3504	if (port->lun_map == NULL)
3505		return (0);
3506	old = port->lun_map[plun];
3507	port->lun_map[plun] = UINT32_MAX;
3508	if ((port->status & CTL_PORT_STATUS_ONLINE) && old < CTL_MAX_LUNS) {
3509		if (port->lun_disable != NULL)
3510			port->lun_disable(port->targ_lun_arg, plun);
3511		ctl_isc_announce_port(port);
3512	}
3513	return (0);
3514}
3515
3516uint32_t
3517ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3518{
3519
3520	if (port == NULL)
3521		return (UINT32_MAX);
3522	if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3523		return (lun_id);
3524	return (port->lun_map[lun_id]);
3525}
3526
3527uint32_t
3528ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3529{
3530	uint32_t i;
3531
3532	if (port == NULL)
3533		return (UINT32_MAX);
3534	if (port->lun_map == NULL)
3535		return (lun_id);
3536	for (i = 0; i < CTL_MAX_LUNS; i++) {
3537		if (port->lun_map[i] == lun_id)
3538			return (i);
3539	}
3540	return (UINT32_MAX);
3541}
3542
3543static struct ctl_port *
3544ctl_io_port(struct ctl_io_hdr *io_hdr)
3545{
3546
3547	return (control_softc->ctl_ports[io_hdr->nexus.targ_port]);
3548}
3549
3550int
3551ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3552{
3553	int i;
3554
3555	for (i = first; i < last; i++) {
3556		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3557			return (i);
3558	}
3559	return (-1);
3560}
3561
3562int
3563ctl_set_mask(uint32_t *mask, uint32_t bit)
3564{
3565	uint32_t chunk, piece;
3566
3567	chunk = bit >> 5;
3568	piece = bit % (sizeof(uint32_t) * 8);
3569
3570	if ((mask[chunk] & (1 << piece)) != 0)
3571		return (-1);
3572	else
3573		mask[chunk] |= (1 << piece);
3574
3575	return (0);
3576}
3577
3578int
3579ctl_clear_mask(uint32_t *mask, uint32_t bit)
3580{
3581	uint32_t chunk, piece;
3582
3583	chunk = bit >> 5;
3584	piece = bit % (sizeof(uint32_t) * 8);
3585
3586	if ((mask[chunk] & (1 << piece)) == 0)
3587		return (-1);
3588	else
3589		mask[chunk] &= ~(1 << piece);
3590
3591	return (0);
3592}
3593
3594int
3595ctl_is_set(uint32_t *mask, uint32_t bit)
3596{
3597	uint32_t chunk, piece;
3598
3599	chunk = bit >> 5;
3600	piece = bit % (sizeof(uint32_t) * 8);
3601
3602	if ((mask[chunk] & (1 << piece)) == 0)
3603		return (0);
3604	else
3605		return (1);
3606}
3607
3608static uint64_t
3609ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3610{
3611	uint64_t *t;
3612
3613	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3614	if (t == NULL)
3615		return (0);
3616	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3617}
3618
3619static void
3620ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3621{
3622	uint64_t *t;
3623
3624	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3625	if (t == NULL)
3626		return;
3627	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3628}
3629
3630static void
3631ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3632{
3633	uint64_t *p;
3634	u_int i;
3635
3636	i = residx/CTL_MAX_INIT_PER_PORT;
3637	if (lun->pr_keys[i] != NULL)
3638		return;
3639	mtx_unlock(&lun->lun_lock);
3640	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3641	    M_WAITOK | M_ZERO);
3642	mtx_lock(&lun->lun_lock);
3643	if (lun->pr_keys[i] == NULL)
3644		lun->pr_keys[i] = p;
3645	else
3646		free(p, M_CTL);
3647}
3648
3649static void
3650ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3651{
3652	uint64_t *t;
3653
3654	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3655	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3656	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3657}
3658
3659/*
3660 * ctl_softc, pool_name, total_ctl_io are passed in.
3661 * npool is passed out.
3662 */
3663int
3664ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3665		uint32_t total_ctl_io, void **npool)
3666{
3667#ifdef IO_POOLS
3668	struct ctl_io_pool *pool;
3669
3670	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3671					    M_NOWAIT | M_ZERO);
3672	if (pool == NULL)
3673		return (ENOMEM);
3674
3675	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3676	pool->ctl_softc = ctl_softc;
3677	pool->zone = uma_zsecond_create(pool->name, NULL,
3678	    NULL, NULL, NULL, ctl_softc->io_zone);
3679	/* uma_prealloc(pool->zone, total_ctl_io); */
3680
3681	*npool = pool;
3682#else
3683	*npool = ctl_softc->io_zone;
3684#endif
3685	return (0);
3686}
3687
3688void
3689ctl_pool_free(struct ctl_io_pool *pool)
3690{
3691
3692	if (pool == NULL)
3693		return;
3694
3695#ifdef IO_POOLS
3696	uma_zdestroy(pool->zone);
3697	free(pool, M_CTL);
3698#endif
3699}
3700
3701union ctl_io *
3702ctl_alloc_io(void *pool_ref)
3703{
3704	union ctl_io *io;
3705#ifdef IO_POOLS
3706	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3707
3708	io = uma_zalloc(pool->zone, M_WAITOK);
3709#else
3710	io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3711#endif
3712	if (io != NULL)
3713		io->io_hdr.pool = pool_ref;
3714	return (io);
3715}
3716
3717union ctl_io *
3718ctl_alloc_io_nowait(void *pool_ref)
3719{
3720	union ctl_io *io;
3721#ifdef IO_POOLS
3722	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3723
3724	io = uma_zalloc(pool->zone, M_NOWAIT);
3725#else
3726	io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3727#endif
3728	if (io != NULL)
3729		io->io_hdr.pool = pool_ref;
3730	return (io);
3731}
3732
3733void
3734ctl_free_io(union ctl_io *io)
3735{
3736#ifdef IO_POOLS
3737	struct ctl_io_pool *pool;
3738#endif
3739
3740	if (io == NULL)
3741		return;
3742
3743#ifdef IO_POOLS
3744	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3745	uma_zfree(pool->zone, io);
3746#else
3747	uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3748#endif
3749}
3750
3751void
3752ctl_zero_io(union ctl_io *io)
3753{
3754	void *pool_ref;
3755
3756	if (io == NULL)
3757		return;
3758
3759	/*
3760	 * May need to preserve linked list pointers at some point too.
3761	 */
3762	pool_ref = io->io_hdr.pool;
3763	memset(io, 0, sizeof(*io));
3764	io->io_hdr.pool = pool_ref;
3765}
3766
3767int
3768ctl_expand_number(const char *buf, uint64_t *num)
3769{
3770	char *endptr;
3771	uint64_t number;
3772	unsigned shift;
3773
3774	number = strtoq(buf, &endptr, 0);
3775
3776	switch (tolower((unsigned char)*endptr)) {
3777	case 'e':
3778		shift = 60;
3779		break;
3780	case 'p':
3781		shift = 50;
3782		break;
3783	case 't':
3784		shift = 40;
3785		break;
3786	case 'g':
3787		shift = 30;
3788		break;
3789	case 'm':
3790		shift = 20;
3791		break;
3792	case 'k':
3793		shift = 10;
3794		break;
3795	case 'b':
3796	case '\0': /* No unit. */
3797		*num = number;
3798		return (0);
3799	default:
3800		/* Unrecognized unit. */
3801		return (-1);
3802	}
3803
3804	if ((number << shift) >> shift != number) {
3805		/* Overflow */
3806		return (-1);
3807	}
3808	*num = number << shift;
3809	return (0);
3810}
3811
3812
3813/*
3814 * This routine could be used in the future to load default and/or saved
3815 * mode page parameters for a particuar lun.
3816 */
3817static int
3818ctl_init_page_index(struct ctl_lun *lun)
3819{
3820	int i;
3821	struct ctl_page_index *page_index;
3822	const char *value;
3823	uint64_t ival;
3824
3825	memcpy(&lun->mode_pages.index, page_index_template,
3826	       sizeof(page_index_template));
3827
3828	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3829
3830		page_index = &lun->mode_pages.index[i];
3831		if (lun->be_lun->lun_type == T_DIRECT &&
3832		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
3833			continue;
3834		if (lun->be_lun->lun_type == T_PROCESSOR &&
3835		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
3836			continue;
3837		if (lun->be_lun->lun_type == T_CDROM &&
3838		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
3839			continue;
3840
3841		switch (page_index->page_code & SMPH_PC_MASK) {
3842		case SMS_RW_ERROR_RECOVERY_PAGE: {
3843			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3844				panic("subpage is incorrect!");
3845			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3846			       &rw_er_page_default,
3847			       sizeof(rw_er_page_default));
3848			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3849			       &rw_er_page_changeable,
3850			       sizeof(rw_er_page_changeable));
3851			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3852			       &rw_er_page_default,
3853			       sizeof(rw_er_page_default));
3854			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3855			       &rw_er_page_default,
3856			       sizeof(rw_er_page_default));
3857			page_index->page_data =
3858				(uint8_t *)lun->mode_pages.rw_er_page;
3859			break;
3860		}
3861		case SMS_FORMAT_DEVICE_PAGE: {
3862			struct scsi_format_page *format_page;
3863
3864			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3865				panic("subpage is incorrect!");
3866
3867			/*
3868			 * Sectors per track are set above.  Bytes per
3869			 * sector need to be set here on a per-LUN basis.
3870			 */
3871			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3872			       &format_page_default,
3873			       sizeof(format_page_default));
3874			memcpy(&lun->mode_pages.format_page[
3875			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
3876			       sizeof(format_page_changeable));
3877			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3878			       &format_page_default,
3879			       sizeof(format_page_default));
3880			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3881			       &format_page_default,
3882			       sizeof(format_page_default));
3883
3884			format_page = &lun->mode_pages.format_page[
3885				CTL_PAGE_CURRENT];
3886			scsi_ulto2b(lun->be_lun->blocksize,
3887				    format_page->bytes_per_sector);
3888
3889			format_page = &lun->mode_pages.format_page[
3890				CTL_PAGE_DEFAULT];
3891			scsi_ulto2b(lun->be_lun->blocksize,
3892				    format_page->bytes_per_sector);
3893
3894			format_page = &lun->mode_pages.format_page[
3895				CTL_PAGE_SAVED];
3896			scsi_ulto2b(lun->be_lun->blocksize,
3897				    format_page->bytes_per_sector);
3898
3899			page_index->page_data =
3900				(uint8_t *)lun->mode_pages.format_page;
3901			break;
3902		}
3903		case SMS_RIGID_DISK_PAGE: {
3904			struct scsi_rigid_disk_page *rigid_disk_page;
3905			uint32_t sectors_per_cylinder;
3906			uint64_t cylinders;
3907#ifndef	__XSCALE__
3908			int shift;
3909#endif /* !__XSCALE__ */
3910
3911			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3912				panic("invalid subpage value %d",
3913				      page_index->subpage);
3914
3915			/*
3916			 * Rotation rate and sectors per track are set
3917			 * above.  We calculate the cylinders here based on
3918			 * capacity.  Due to the number of heads and
3919			 * sectors per track we're using, smaller arrays
3920			 * may turn out to have 0 cylinders.  Linux and
3921			 * FreeBSD don't pay attention to these mode pages
3922			 * to figure out capacity, but Solaris does.  It
3923			 * seems to deal with 0 cylinders just fine, and
3924			 * works out a fake geometry based on the capacity.
3925			 */
3926			memcpy(&lun->mode_pages.rigid_disk_page[
3927			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
3928			       sizeof(rigid_disk_page_default));
3929			memcpy(&lun->mode_pages.rigid_disk_page[
3930			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
3931			       sizeof(rigid_disk_page_changeable));
3932
3933			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
3934				CTL_DEFAULT_HEADS;
3935
3936			/*
3937			 * The divide method here will be more accurate,
3938			 * probably, but results in floating point being
3939			 * used in the kernel on i386 (__udivdi3()).  On the
3940			 * XScale, though, __udivdi3() is implemented in
3941			 * software.
3942			 *
3943			 * The shift method for cylinder calculation is
3944			 * accurate if sectors_per_cylinder is a power of
3945			 * 2.  Otherwise it might be slightly off -- you
3946			 * might have a bit of a truncation problem.
3947			 */
3948#ifdef	__XSCALE__
3949			cylinders = (lun->be_lun->maxlba + 1) /
3950				sectors_per_cylinder;
3951#else
3952			for (shift = 31; shift > 0; shift--) {
3953				if (sectors_per_cylinder & (1 << shift))
3954					break;
3955			}
3956			cylinders = (lun->be_lun->maxlba + 1) >> shift;
3957#endif
3958
3959			/*
3960			 * We've basically got 3 bytes, or 24 bits for the
3961			 * cylinder size in the mode page.  If we're over,
3962			 * just round down to 2^24.
3963			 */
3964			if (cylinders > 0xffffff)
3965				cylinders = 0xffffff;
3966
3967			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
3968				CTL_PAGE_DEFAULT];
3969			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
3970
3971			if ((value = ctl_get_opt(&lun->be_lun->options,
3972			    "rpm")) != NULL) {
3973				scsi_ulto2b(strtol(value, NULL, 0),
3974				     rigid_disk_page->rotation_rate);
3975			}
3976
3977			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
3978			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
3979			       sizeof(rigid_disk_page_default));
3980			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
3981			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
3982			       sizeof(rigid_disk_page_default));
3983
3984			page_index->page_data =
3985				(uint8_t *)lun->mode_pages.rigid_disk_page;
3986			break;
3987		}
3988		case SMS_CACHING_PAGE: {
3989			struct scsi_caching_page *caching_page;
3990
3991			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
3992				panic("invalid subpage value %d",
3993				      page_index->subpage);
3994			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
3995			       &caching_page_default,
3996			       sizeof(caching_page_default));
3997			memcpy(&lun->mode_pages.caching_page[
3998			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
3999			       sizeof(caching_page_changeable));
4000			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4001			       &caching_page_default,
4002			       sizeof(caching_page_default));
4003			caching_page = &lun->mode_pages.caching_page[
4004			    CTL_PAGE_SAVED];
4005			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4006			if (value != NULL && strcmp(value, "off") == 0)
4007				caching_page->flags1 &= ~SCP_WCE;
4008			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4009			if (value != NULL && strcmp(value, "off") == 0)
4010				caching_page->flags1 |= SCP_RCD;
4011			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4012			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4013			       sizeof(caching_page_default));
4014			page_index->page_data =
4015				(uint8_t *)lun->mode_pages.caching_page;
4016			break;
4017		}
4018		case SMS_CONTROL_MODE_PAGE: {
4019			switch (page_index->subpage) {
4020			case SMS_SUBPAGE_PAGE_0: {
4021				struct scsi_control_page *control_page;
4022
4023				memcpy(&lun->mode_pages.control_page[
4024				    CTL_PAGE_DEFAULT],
4025				       &control_page_default,
4026				       sizeof(control_page_default));
4027				memcpy(&lun->mode_pages.control_page[
4028				    CTL_PAGE_CHANGEABLE],
4029				       &control_page_changeable,
4030				       sizeof(control_page_changeable));
4031				memcpy(&lun->mode_pages.control_page[
4032				    CTL_PAGE_SAVED],
4033				       &control_page_default,
4034				       sizeof(control_page_default));
4035				control_page = &lun->mode_pages.control_page[
4036				    CTL_PAGE_SAVED];
4037				value = ctl_get_opt(&lun->be_lun->options,
4038				    "reordering");
4039				if (value != NULL &&
4040				    strcmp(value, "unrestricted") == 0) {
4041					control_page->queue_flags &=
4042					    ~SCP_QUEUE_ALG_MASK;
4043					control_page->queue_flags |=
4044					    SCP_QUEUE_ALG_UNRESTRICTED;
4045				}
4046				memcpy(&lun->mode_pages.control_page[
4047				    CTL_PAGE_CURRENT],
4048				       &lun->mode_pages.control_page[
4049				    CTL_PAGE_SAVED],
4050				       sizeof(control_page_default));
4051				page_index->page_data =
4052				    (uint8_t *)lun->mode_pages.control_page;
4053				break;
4054			}
4055			case 0x01:
4056				memcpy(&lun->mode_pages.control_ext_page[
4057				    CTL_PAGE_DEFAULT],
4058				       &control_ext_page_default,
4059				       sizeof(control_ext_page_default));
4060				memcpy(&lun->mode_pages.control_ext_page[
4061				    CTL_PAGE_CHANGEABLE],
4062				       &control_ext_page_changeable,
4063				       sizeof(control_ext_page_changeable));
4064				memcpy(&lun->mode_pages.control_ext_page[
4065				    CTL_PAGE_SAVED],
4066				       &control_ext_page_default,
4067				       sizeof(control_ext_page_default));
4068				memcpy(&lun->mode_pages.control_ext_page[
4069				    CTL_PAGE_CURRENT],
4070				       &lun->mode_pages.control_ext_page[
4071				    CTL_PAGE_SAVED],
4072				       sizeof(control_ext_page_default));
4073				page_index->page_data =
4074				    (uint8_t *)lun->mode_pages.control_ext_page;
4075				break;
4076			}
4077			break;
4078		}
4079		case SMS_INFO_EXCEPTIONS_PAGE: {
4080			switch (page_index->subpage) {
4081			case SMS_SUBPAGE_PAGE_0:
4082				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4083				       &ie_page_default,
4084				       sizeof(ie_page_default));
4085				memcpy(&lun->mode_pages.ie_page[
4086				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4087				       sizeof(ie_page_changeable));
4088				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4089				       &ie_page_default,
4090				       sizeof(ie_page_default));
4091				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4092				       &ie_page_default,
4093				       sizeof(ie_page_default));
4094				page_index->page_data =
4095					(uint8_t *)lun->mode_pages.ie_page;
4096				break;
4097			case 0x02: {
4098				struct ctl_logical_block_provisioning_page *page;
4099
4100				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4101				       &lbp_page_default,
4102				       sizeof(lbp_page_default));
4103				memcpy(&lun->mode_pages.lbp_page[
4104				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4105				       sizeof(lbp_page_changeable));
4106				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4107				       &lbp_page_default,
4108				       sizeof(lbp_page_default));
4109				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4110				value = ctl_get_opt(&lun->be_lun->options,
4111				    "avail-threshold");
4112				if (value != NULL &&
4113				    ctl_expand_number(value, &ival) == 0) {
4114					page->descr[0].flags |= SLBPPD_ENABLED |
4115					    SLBPPD_ARMING_DEC;
4116					if (lun->be_lun->blocksize)
4117						ival /= lun->be_lun->blocksize;
4118					else
4119						ival /= 512;
4120					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4121					    page->descr[0].count);
4122				}
4123				value = ctl_get_opt(&lun->be_lun->options,
4124				    "used-threshold");
4125				if (value != NULL &&
4126				    ctl_expand_number(value, &ival) == 0) {
4127					page->descr[1].flags |= SLBPPD_ENABLED |
4128					    SLBPPD_ARMING_INC;
4129					if (lun->be_lun->blocksize)
4130						ival /= lun->be_lun->blocksize;
4131					else
4132						ival /= 512;
4133					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4134					    page->descr[1].count);
4135				}
4136				value = ctl_get_opt(&lun->be_lun->options,
4137				    "pool-avail-threshold");
4138				if (value != NULL &&
4139				    ctl_expand_number(value, &ival) == 0) {
4140					page->descr[2].flags |= SLBPPD_ENABLED |
4141					    SLBPPD_ARMING_DEC;
4142					if (lun->be_lun->blocksize)
4143						ival /= lun->be_lun->blocksize;
4144					else
4145						ival /= 512;
4146					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4147					    page->descr[2].count);
4148				}
4149				value = ctl_get_opt(&lun->be_lun->options,
4150				    "pool-used-threshold");
4151				if (value != NULL &&
4152				    ctl_expand_number(value, &ival) == 0) {
4153					page->descr[3].flags |= SLBPPD_ENABLED |
4154					    SLBPPD_ARMING_INC;
4155					if (lun->be_lun->blocksize)
4156						ival /= lun->be_lun->blocksize;
4157					else
4158						ival /= 512;
4159					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4160					    page->descr[3].count);
4161				}
4162				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4163				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4164				       sizeof(lbp_page_default));
4165				page_index->page_data =
4166					(uint8_t *)lun->mode_pages.lbp_page;
4167			}}
4168			break;
4169		}
4170		case SMS_CDDVD_CAPS_PAGE:{
4171			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4172			       &cddvd_page_default,
4173			       sizeof(cddvd_page_default));
4174			memcpy(&lun->mode_pages.cddvd_page[
4175			       CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4176			       sizeof(cddvd_page_changeable));
4177			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4178			       &cddvd_page_default,
4179			       sizeof(cddvd_page_default));
4180			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4181			       &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4182			       sizeof(cddvd_page_default));
4183			page_index->page_data =
4184				(uint8_t *)lun->mode_pages.cddvd_page;
4185			break;
4186		}
4187		case SMS_VENDOR_SPECIFIC_PAGE:{
4188			switch (page_index->subpage) {
4189			case DBGCNF_SUBPAGE_CODE: {
4190				memcpy(&lun->mode_pages.debugconf_subpage[
4191				       CTL_PAGE_CURRENT],
4192				       &debugconf_page_default,
4193				       sizeof(debugconf_page_default));
4194				memcpy(&lun->mode_pages.debugconf_subpage[
4195				       CTL_PAGE_CHANGEABLE],
4196				       &debugconf_page_changeable,
4197				       sizeof(debugconf_page_changeable));
4198				memcpy(&lun->mode_pages.debugconf_subpage[
4199				       CTL_PAGE_DEFAULT],
4200				       &debugconf_page_default,
4201				       sizeof(debugconf_page_default));
4202				memcpy(&lun->mode_pages.debugconf_subpage[
4203				       CTL_PAGE_SAVED],
4204				       &debugconf_page_default,
4205				       sizeof(debugconf_page_default));
4206				page_index->page_data =
4207				    (uint8_t *)lun->mode_pages.debugconf_subpage;
4208				break;
4209			}
4210			default:
4211				panic("invalid subpage value %d",
4212				      page_index->subpage);
4213				break;
4214			}
4215   			break;
4216		}
4217		default:
4218			panic("invalid page value %d",
4219			      page_index->page_code & SMPH_PC_MASK);
4220			break;
4221    	}
4222	}
4223
4224	return (CTL_RETVAL_COMPLETE);
4225}
4226
4227static int
4228ctl_init_log_page_index(struct ctl_lun *lun)
4229{
4230	struct ctl_page_index *page_index;
4231	int i, j, k, prev;
4232
4233	memcpy(&lun->log_pages.index, log_page_index_template,
4234	       sizeof(log_page_index_template));
4235
4236	prev = -1;
4237	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4238
4239		page_index = &lun->log_pages.index[i];
4240		if (lun->be_lun->lun_type == T_DIRECT &&
4241		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4242			continue;
4243		if (lun->be_lun->lun_type == T_PROCESSOR &&
4244		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4245			continue;
4246		if (lun->be_lun->lun_type == T_CDROM &&
4247		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4248			continue;
4249
4250		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4251		    lun->backend->lun_attr == NULL)
4252			continue;
4253
4254		if (page_index->page_code != prev) {
4255			lun->log_pages.pages_page[j] = page_index->page_code;
4256			prev = page_index->page_code;
4257			j++;
4258		}
4259		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4260		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4261		k++;
4262	}
4263	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4264	lun->log_pages.index[0].page_len = j;
4265	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4266	lun->log_pages.index[1].page_len = k * 2;
4267	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4268	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4269	lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4270	lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4271
4272	return (CTL_RETVAL_COMPLETE);
4273}
4274
4275static int
4276hex2bin(const char *str, uint8_t *buf, int buf_size)
4277{
4278	int i;
4279	u_char c;
4280
4281	memset(buf, 0, buf_size);
4282	while (isspace(str[0]))
4283		str++;
4284	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4285		str += 2;
4286	buf_size *= 2;
4287	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4288		c = str[i];
4289		if (isdigit(c))
4290			c -= '0';
4291		else if (isalpha(c))
4292			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4293		else
4294			break;
4295		if (c >= 16)
4296			break;
4297		if ((i & 1) == 0)
4298			buf[i / 2] |= (c << 4);
4299		else
4300			buf[i / 2] |= c;
4301	}
4302	return ((i + 1) / 2);
4303}
4304
4305/*
4306 * LUN allocation.
4307 *
4308 * Requirements:
4309 * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4310 *   wants us to allocate the LUN and he can block.
4311 * - ctl_softc is always set
4312 * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4313 *
4314 * Returns 0 for success, non-zero (errno) for failure.
4315 */
4316static int
4317ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4318	      struct ctl_be_lun *const be_lun)
4319{
4320	struct ctl_lun *nlun, *lun;
4321	struct scsi_vpd_id_descriptor *desc;
4322	struct scsi_vpd_id_t10 *t10id;
4323	const char *eui, *naa, *scsiname, *vendor, *value;
4324	int lun_number, i, lun_malloced;
4325	int devidlen, idlen1, idlen2 = 0, len;
4326
4327	if (be_lun == NULL)
4328		return (EINVAL);
4329
4330	/*
4331	 * We currently only support Direct Access or Processor LUN types.
4332	 */
4333	switch (be_lun->lun_type) {
4334	case T_DIRECT:
4335	case T_PROCESSOR:
4336	case T_CDROM:
4337		break;
4338	case T_SEQUENTIAL:
4339	case T_CHANGER:
4340	default:
4341		be_lun->lun_config_status(be_lun->be_lun,
4342					  CTL_LUN_CONFIG_FAILURE);
4343		break;
4344	}
4345	if (ctl_lun == NULL) {
4346		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4347		lun_malloced = 1;
4348	} else {
4349		lun_malloced = 0;
4350		lun = ctl_lun;
4351	}
4352
4353	memset(lun, 0, sizeof(*lun));
4354	if (lun_malloced)
4355		lun->flags = CTL_LUN_MALLOCED;
4356
4357	/* Generate LUN ID. */
4358	devidlen = max(CTL_DEVID_MIN_LEN,
4359	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4360	idlen1 = sizeof(*t10id) + devidlen;
4361	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4362	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4363	if (scsiname != NULL) {
4364		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4365		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4366	}
4367	eui = ctl_get_opt(&be_lun->options, "eui");
4368	if (eui != NULL) {
4369		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4370	}
4371	naa = ctl_get_opt(&be_lun->options, "naa");
4372	if (naa != NULL) {
4373		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4374	}
4375	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4376	    M_CTL, M_WAITOK | M_ZERO);
4377	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4378	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4379	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4380	desc->length = idlen1;
4381	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4382	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4383	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4384		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4385	} else {
4386		strncpy(t10id->vendor, vendor,
4387		    min(sizeof(t10id->vendor), strlen(vendor)));
4388	}
4389	strncpy((char *)t10id->vendor_spec_id,
4390	    (char *)be_lun->device_id, devidlen);
4391	if (scsiname != NULL) {
4392		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4393		    desc->length);
4394		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4395		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4396		    SVPD_ID_TYPE_SCSI_NAME;
4397		desc->length = idlen2;
4398		strlcpy(desc->identifier, scsiname, idlen2);
4399	}
4400	if (eui != NULL) {
4401		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4402		    desc->length);
4403		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4404		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4405		    SVPD_ID_TYPE_EUI64;
4406		desc->length = hex2bin(eui, desc->identifier, 16);
4407		desc->length = desc->length > 12 ? 16 :
4408		    (desc->length > 8 ? 12 : 8);
4409		len -= 16 - desc->length;
4410	}
4411	if (naa != NULL) {
4412		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4413		    desc->length);
4414		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4415		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4416		    SVPD_ID_TYPE_NAA;
4417		desc->length = hex2bin(naa, desc->identifier, 16);
4418		desc->length = desc->length > 8 ? 16 : 8;
4419		len -= 16 - desc->length;
4420	}
4421	lun->lun_devid->len = len;
4422
4423	mtx_lock(&ctl_softc->ctl_lock);
4424	/*
4425	 * See if the caller requested a particular LUN number.  If so, see
4426	 * if it is available.  Otherwise, allocate the first available LUN.
4427	 */
4428	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4429		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4430		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4431			mtx_unlock(&ctl_softc->ctl_lock);
4432			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4433				printf("ctl: requested LUN ID %d is higher "
4434				       "than CTL_MAX_LUNS - 1 (%d)\n",
4435				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4436			} else {
4437				/*
4438				 * XXX KDM return an error, or just assign
4439				 * another LUN ID in this case??
4440				 */
4441				printf("ctl: requested LUN ID %d is already "
4442				       "in use\n", be_lun->req_lun_id);
4443			}
4444			if (lun->flags & CTL_LUN_MALLOCED)
4445				free(lun, M_CTL);
4446			be_lun->lun_config_status(be_lun->be_lun,
4447						  CTL_LUN_CONFIG_FAILURE);
4448			return (ENOSPC);
4449		}
4450		lun_number = be_lun->req_lun_id;
4451	} else {
4452		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4453		if (lun_number == -1) {
4454			mtx_unlock(&ctl_softc->ctl_lock);
4455			printf("ctl: can't allocate LUN, out of LUNs\n");
4456			if (lun->flags & CTL_LUN_MALLOCED)
4457				free(lun, M_CTL);
4458			be_lun->lun_config_status(be_lun->be_lun,
4459						  CTL_LUN_CONFIG_FAILURE);
4460			return (ENOSPC);
4461		}
4462	}
4463	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4464
4465	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4466	lun->lun = lun_number;
4467	lun->be_lun = be_lun;
4468	/*
4469	 * The processor LUN is always enabled.  Disk LUNs come on line
4470	 * disabled, and must be enabled by the backend.
4471	 */
4472	lun->flags |= CTL_LUN_DISABLED;
4473	lun->backend = be_lun->be;
4474	be_lun->ctl_lun = lun;
4475	be_lun->lun_id = lun_number;
4476	atomic_add_int(&be_lun->be->num_luns, 1);
4477	if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4478		lun->flags |= CTL_LUN_EJECTED;
4479	if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4480		lun->flags |= CTL_LUN_NO_MEDIA;
4481	if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4482		lun->flags |= CTL_LUN_STOPPED;
4483
4484	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4485		lun->flags |= CTL_LUN_PRIMARY_SC;
4486
4487	value = ctl_get_opt(&be_lun->options, "removable");
4488	if (value != NULL) {
4489		if (strcmp(value, "on") == 0)
4490			lun->flags |= CTL_LUN_REMOVABLE;
4491	} else if (be_lun->lun_type == T_CDROM)
4492		lun->flags |= CTL_LUN_REMOVABLE;
4493
4494	lun->ctl_softc = ctl_softc;
4495#ifdef CTL_TIME_IO
4496	lun->last_busy = getsbinuptime();
4497#endif
4498	TAILQ_INIT(&lun->ooa_queue);
4499	TAILQ_INIT(&lun->blocked_queue);
4500	STAILQ_INIT(&lun->error_list);
4501	ctl_tpc_lun_init(lun);
4502
4503	/*
4504	 * Initialize the mode and log page index.
4505	 */
4506	ctl_init_page_index(lun);
4507	ctl_init_log_page_index(lun);
4508
4509	/*
4510	 * Now, before we insert this lun on the lun list, set the lun
4511	 * inventory changed UA for all other luns.
4512	 */
4513	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4514		mtx_lock(&nlun->lun_lock);
4515		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4516		mtx_unlock(&nlun->lun_lock);
4517	}
4518
4519	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4520
4521	ctl_softc->ctl_luns[lun_number] = lun;
4522
4523	ctl_softc->num_luns++;
4524
4525	/* Setup statistics gathering */
4526	lun->stats.device_type = be_lun->lun_type;
4527	lun->stats.lun_number = lun_number;
4528	lun->stats.blocksize = be_lun->blocksize;
4529	if (be_lun->blocksize == 0)
4530		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4531	for (i = 0;i < CTL_MAX_PORTS;i++)
4532		lun->stats.ports[i].targ_port = i;
4533
4534	mtx_unlock(&ctl_softc->ctl_lock);
4535
4536	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4537	return (0);
4538}
4539
4540/*
4541 * Delete a LUN.
4542 * Assumptions:
4543 * - LUN has already been marked invalid and any pending I/O has been taken
4544 *   care of.
4545 */
4546static int
4547ctl_free_lun(struct ctl_lun *lun)
4548{
4549	struct ctl_softc *softc;
4550	struct ctl_lun *nlun;
4551	int i;
4552
4553	softc = lun->ctl_softc;
4554
4555	mtx_assert(&softc->ctl_lock, MA_OWNED);
4556
4557	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4558
4559	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4560
4561	softc->ctl_luns[lun->lun] = NULL;
4562
4563	if (!TAILQ_EMPTY(&lun->ooa_queue))
4564		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4565
4566	softc->num_luns--;
4567
4568	/*
4569	 * Tell the backend to free resources, if this LUN has a backend.
4570	 */
4571	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4572	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4573
4574	ctl_tpc_lun_shutdown(lun);
4575	mtx_destroy(&lun->lun_lock);
4576	free(lun->lun_devid, M_CTL);
4577	for (i = 0; i < CTL_MAX_PORTS; i++)
4578		free(lun->pending_ua[i], M_CTL);
4579	for (i = 0; i < CTL_MAX_PORTS; i++)
4580		free(lun->pr_keys[i], M_CTL);
4581	free(lun->write_buffer, M_CTL);
4582	if (lun->flags & CTL_LUN_MALLOCED)
4583		free(lun, M_CTL);
4584
4585	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4586		mtx_lock(&nlun->lun_lock);
4587		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4588		mtx_unlock(&nlun->lun_lock);
4589	}
4590
4591	return (0);
4592}
4593
4594static void
4595ctl_create_lun(struct ctl_be_lun *be_lun)
4596{
4597
4598	/*
4599	 * ctl_alloc_lun() should handle all potential failure cases.
4600	 */
4601	ctl_alloc_lun(control_softc, NULL, be_lun);
4602}
4603
4604int
4605ctl_add_lun(struct ctl_be_lun *be_lun)
4606{
4607	struct ctl_softc *softc = control_softc;
4608
4609	mtx_lock(&softc->ctl_lock);
4610	STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4611	mtx_unlock(&softc->ctl_lock);
4612	wakeup(&softc->pending_lun_queue);
4613
4614	return (0);
4615}
4616
4617int
4618ctl_enable_lun(struct ctl_be_lun *be_lun)
4619{
4620	struct ctl_softc *softc;
4621	struct ctl_port *port, *nport;
4622	struct ctl_lun *lun;
4623	int retval;
4624
4625	lun = (struct ctl_lun *)be_lun->ctl_lun;
4626	softc = lun->ctl_softc;
4627
4628	mtx_lock(&softc->ctl_lock);
4629	mtx_lock(&lun->lun_lock);
4630	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4631		/*
4632		 * eh?  Why did we get called if the LUN is already
4633		 * enabled?
4634		 */
4635		mtx_unlock(&lun->lun_lock);
4636		mtx_unlock(&softc->ctl_lock);
4637		return (0);
4638	}
4639	lun->flags &= ~CTL_LUN_DISABLED;
4640	mtx_unlock(&lun->lun_lock);
4641
4642	for (port = STAILQ_FIRST(&softc->port_list); port != NULL; port = nport) {
4643		nport = STAILQ_NEXT(port, links);
4644		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4645		    port->lun_map != NULL || port->lun_enable == NULL)
4646			continue;
4647
4648		/*
4649		 * Drop the lock while we call the FETD's enable routine.
4650		 * This can lead to a callback into CTL (at least in the
4651		 * case of the internal initiator frontend.
4652		 */
4653		mtx_unlock(&softc->ctl_lock);
4654		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4655		mtx_lock(&softc->ctl_lock);
4656		if (retval != 0) {
4657			printf("%s: FETD %s port %d returned error "
4658			       "%d for lun_enable on lun %jd\n",
4659			       __func__, port->port_name, port->targ_port,
4660			       retval, (intmax_t)lun->lun);
4661		}
4662	}
4663
4664	mtx_unlock(&softc->ctl_lock);
4665	ctl_isc_announce_lun(lun);
4666
4667	return (0);
4668}
4669
4670int
4671ctl_disable_lun(struct ctl_be_lun *be_lun)
4672{
4673	struct ctl_softc *softc;
4674	struct ctl_port *port;
4675	struct ctl_lun *lun;
4676	int retval;
4677
4678	lun = (struct ctl_lun *)be_lun->ctl_lun;
4679	softc = lun->ctl_softc;
4680
4681	mtx_lock(&softc->ctl_lock);
4682	mtx_lock(&lun->lun_lock);
4683	if (lun->flags & CTL_LUN_DISABLED) {
4684		mtx_unlock(&lun->lun_lock);
4685		mtx_unlock(&softc->ctl_lock);
4686		return (0);
4687	}
4688	lun->flags |= CTL_LUN_DISABLED;
4689	mtx_unlock(&lun->lun_lock);
4690
4691	STAILQ_FOREACH(port, &softc->port_list, links) {
4692		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4693		    port->lun_map != NULL || port->lun_disable == NULL)
4694			continue;
4695
4696		/*
4697		 * Drop the lock before we call the frontend's disable
4698		 * routine, to avoid lock order reversals.
4699		 *
4700		 * XXX KDM what happens if the frontend list changes while
4701		 * we're traversing it?  It's unlikely, but should be handled.
4702		 */
4703		mtx_unlock(&softc->ctl_lock);
4704		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4705		mtx_lock(&softc->ctl_lock);
4706		if (retval != 0) {
4707			printf("%s: FETD %s port %d returned error "
4708			       "%d for lun_disable on lun %jd\n",
4709			       __func__, port->port_name, port->targ_port,
4710			       retval, (intmax_t)lun->lun);
4711		}
4712	}
4713
4714	mtx_unlock(&softc->ctl_lock);
4715	ctl_isc_announce_lun(lun);
4716
4717	return (0);
4718}
4719
4720int
4721ctl_start_lun(struct ctl_be_lun *be_lun)
4722{
4723	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4724
4725	mtx_lock(&lun->lun_lock);
4726	lun->flags &= ~CTL_LUN_STOPPED;
4727	mtx_unlock(&lun->lun_lock);
4728	return (0);
4729}
4730
4731int
4732ctl_stop_lun(struct ctl_be_lun *be_lun)
4733{
4734	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4735
4736	mtx_lock(&lun->lun_lock);
4737	lun->flags |= CTL_LUN_STOPPED;
4738	mtx_unlock(&lun->lun_lock);
4739	return (0);
4740}
4741
4742int
4743ctl_lun_no_media(struct ctl_be_lun *be_lun)
4744{
4745	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4746
4747	mtx_lock(&lun->lun_lock);
4748	lun->flags |= CTL_LUN_NO_MEDIA;
4749	mtx_unlock(&lun->lun_lock);
4750	return (0);
4751}
4752
4753int
4754ctl_lun_has_media(struct ctl_be_lun *be_lun)
4755{
4756	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4757	union ctl_ha_msg msg;
4758
4759	mtx_lock(&lun->lun_lock);
4760	lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4761	if (lun->flags & CTL_LUN_REMOVABLE)
4762		ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4763	mtx_unlock(&lun->lun_lock);
4764	if ((lun->flags & CTL_LUN_REMOVABLE) &&
4765	    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4766		bzero(&msg.ua, sizeof(msg.ua));
4767		msg.hdr.msg_type = CTL_MSG_UA;
4768		msg.hdr.nexus.initid = -1;
4769		msg.hdr.nexus.targ_port = -1;
4770		msg.hdr.nexus.targ_lun = lun->lun;
4771		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4772		msg.ua.ua_all = 1;
4773		msg.ua.ua_set = 1;
4774		msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4775		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4776		    M_WAITOK);
4777	}
4778	return (0);
4779}
4780
4781int
4782ctl_lun_ejected(struct ctl_be_lun *be_lun)
4783{
4784	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4785
4786	mtx_lock(&lun->lun_lock);
4787	lun->flags |= CTL_LUN_EJECTED;
4788	mtx_unlock(&lun->lun_lock);
4789	return (0);
4790}
4791
4792int
4793ctl_lun_primary(struct ctl_be_lun *be_lun)
4794{
4795	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4796
4797	mtx_lock(&lun->lun_lock);
4798	lun->flags |= CTL_LUN_PRIMARY_SC;
4799	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4800	mtx_unlock(&lun->lun_lock);
4801	ctl_isc_announce_lun(lun);
4802	return (0);
4803}
4804
4805int
4806ctl_lun_secondary(struct ctl_be_lun *be_lun)
4807{
4808	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4809
4810	mtx_lock(&lun->lun_lock);
4811	lun->flags &= ~CTL_LUN_PRIMARY_SC;
4812	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4813	mtx_unlock(&lun->lun_lock);
4814	ctl_isc_announce_lun(lun);
4815	return (0);
4816}
4817
4818int
4819ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4820{
4821	struct ctl_softc *softc;
4822	struct ctl_lun *lun;
4823
4824	lun = (struct ctl_lun *)be_lun->ctl_lun;
4825	softc = lun->ctl_softc;
4826
4827	mtx_lock(&lun->lun_lock);
4828
4829	/*
4830	 * The LUN needs to be disabled before it can be marked invalid.
4831	 */
4832	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4833		mtx_unlock(&lun->lun_lock);
4834		return (-1);
4835	}
4836	/*
4837	 * Mark the LUN invalid.
4838	 */
4839	lun->flags |= CTL_LUN_INVALID;
4840
4841	/*
4842	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4843	 * If we have something in the OOA queue, we'll free it when the
4844	 * last I/O completes.
4845	 */
4846	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4847		mtx_unlock(&lun->lun_lock);
4848		mtx_lock(&softc->ctl_lock);
4849		ctl_free_lun(lun);
4850		mtx_unlock(&softc->ctl_lock);
4851	} else
4852		mtx_unlock(&lun->lun_lock);
4853
4854	return (0);
4855}
4856
4857void
4858ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4859{
4860	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4861	union ctl_ha_msg msg;
4862
4863	mtx_lock(&lun->lun_lock);
4864	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
4865	mtx_unlock(&lun->lun_lock);
4866	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4867		/* Send msg to other side. */
4868		bzero(&msg.ua, sizeof(msg.ua));
4869		msg.hdr.msg_type = CTL_MSG_UA;
4870		msg.hdr.nexus.initid = -1;
4871		msg.hdr.nexus.targ_port = -1;
4872		msg.hdr.nexus.targ_lun = lun->lun;
4873		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4874		msg.ua.ua_all = 1;
4875		msg.ua.ua_set = 1;
4876		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
4877		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4878		    M_WAITOK);
4879	}
4880}
4881
4882/*
4883 * Backend "memory move is complete" callback for requests that never
4884 * make it down to say RAIDCore's configuration code.
4885 */
4886int
4887ctl_config_move_done(union ctl_io *io)
4888{
4889	int retval;
4890
4891	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4892	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4893	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
4894
4895	if ((io->io_hdr.port_status != 0) &&
4896	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4897	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4898		/*
4899		 * For hardware error sense keys, the sense key
4900		 * specific value is defined to be a retry count,
4901		 * but we use it to pass back an internal FETD
4902		 * error code.  XXX KDM  Hopefully the FETD is only
4903		 * using 16 bits for an error code, since that's
4904		 * all the space we have in the sks field.
4905		 */
4906		ctl_set_internal_failure(&io->scsiio,
4907					 /*sks_valid*/ 1,
4908					 /*retry_count*/
4909					 io->io_hdr.port_status);
4910	}
4911
4912	if (ctl_debug & CTL_DEBUG_CDB_DATA)
4913		ctl_data_print(io);
4914	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
4915	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4916	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
4917	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
4918		/*
4919		 * XXX KDM just assuming a single pointer here, and not a
4920		 * S/G list.  If we start using S/G lists for config data,
4921		 * we'll need to know how to clean them up here as well.
4922		 */
4923		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4924			free(io->scsiio.kern_data_ptr, M_CTL);
4925		ctl_done(io);
4926		retval = CTL_RETVAL_COMPLETE;
4927	} else {
4928		/*
4929		 * XXX KDM now we need to continue data movement.  Some
4930		 * options:
4931		 * - call ctl_scsiio() again?  We don't do this for data
4932		 *   writes, because for those at least we know ahead of
4933		 *   time where the write will go and how long it is.  For
4934		 *   config writes, though, that information is largely
4935		 *   contained within the write itself, thus we need to
4936		 *   parse out the data again.
4937		 *
4938		 * - Call some other function once the data is in?
4939		 */
4940
4941		/*
4942		 * XXX KDM call ctl_scsiio() again for now, and check flag
4943		 * bits to see whether we're allocated or not.
4944		 */
4945		retval = ctl_scsiio(&io->scsiio);
4946	}
4947	return (retval);
4948}
4949
4950/*
4951 * This gets called by a backend driver when it is done with a
4952 * data_submit method.
4953 */
4954void
4955ctl_data_submit_done(union ctl_io *io)
4956{
4957	/*
4958	 * If the IO_CONT flag is set, we need to call the supplied
4959	 * function to continue processing the I/O, instead of completing
4960	 * the I/O just yet.
4961	 *
4962	 * If there is an error, though, we don't want to keep processing.
4963	 * Instead, just send status back to the initiator.
4964	 */
4965	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
4966	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
4967	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4968	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4969		io->scsiio.io_cont(io);
4970		return;
4971	}
4972	ctl_done(io);
4973}
4974
4975/*
4976 * This gets called by a backend driver when it is done with a
4977 * configuration write.
4978 */
4979void
4980ctl_config_write_done(union ctl_io *io)
4981{
4982	uint8_t *buf;
4983
4984	/*
4985	 * If the IO_CONT flag is set, we need to call the supplied
4986	 * function to continue processing the I/O, instead of completing
4987	 * the I/O just yet.
4988	 *
4989	 * If there is an error, though, we don't want to keep processing.
4990	 * Instead, just send status back to the initiator.
4991	 */
4992	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
4993	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
4994	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4995	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4996		io->scsiio.io_cont(io);
4997		return;
4998	}
4999	/*
5000	 * Since a configuration write can be done for commands that actually
5001	 * have data allocated, like write buffer, and commands that have
5002	 * no data, like start/stop unit, we need to check here.
5003	 */
5004	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5005		buf = io->scsiio.kern_data_ptr;
5006	else
5007		buf = NULL;
5008	ctl_done(io);
5009	if (buf)
5010		free(buf, M_CTL);
5011}
5012
5013void
5014ctl_config_read_done(union ctl_io *io)
5015{
5016	uint8_t *buf;
5017
5018	/*
5019	 * If there is some error -- we are done, skip data transfer.
5020	 */
5021	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5022	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5023	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5024		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5025			buf = io->scsiio.kern_data_ptr;
5026		else
5027			buf = NULL;
5028		ctl_done(io);
5029		if (buf)
5030			free(buf, M_CTL);
5031		return;
5032	}
5033
5034	/*
5035	 * If the IO_CONT flag is set, we need to call the supplied
5036	 * function to continue processing the I/O, instead of completing
5037	 * the I/O just yet.
5038	 */
5039	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5040		io->scsiio.io_cont(io);
5041		return;
5042	}
5043
5044	ctl_datamove(io);
5045}
5046
5047/*
5048 * SCSI release command.
5049 */
5050int
5051ctl_scsi_release(struct ctl_scsiio *ctsio)
5052{
5053	struct ctl_lun *lun;
5054	uint32_t residx;
5055
5056	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5057
5058	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5059	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5060
5061	/*
5062	 * XXX KDM right now, we only support LUN reservation.  We don't
5063	 * support 3rd party reservations, or extent reservations, which
5064	 * might actually need the parameter list.  If we've gotten this
5065	 * far, we've got a LUN reservation.  Anything else got kicked out
5066	 * above.  So, according to SPC, ignore the length.
5067	 */
5068
5069	mtx_lock(&lun->lun_lock);
5070
5071	/*
5072	 * According to SPC, it is not an error for an intiator to attempt
5073	 * to release a reservation on a LUN that isn't reserved, or that
5074	 * is reserved by another initiator.  The reservation can only be
5075	 * released, though, by the initiator who made it or by one of
5076	 * several reset type events.
5077	 */
5078	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5079			lun->flags &= ~CTL_LUN_RESERVED;
5080
5081	mtx_unlock(&lun->lun_lock);
5082
5083	ctl_set_success(ctsio);
5084	ctl_done((union ctl_io *)ctsio);
5085	return (CTL_RETVAL_COMPLETE);
5086}
5087
5088int
5089ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5090{
5091	struct ctl_lun *lun;
5092	uint32_t residx;
5093
5094	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5095
5096	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5097	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5098
5099	/*
5100	 * XXX KDM right now, we only support LUN reservation.  We don't
5101	 * support 3rd party reservations, or extent reservations, which
5102	 * might actually need the parameter list.  If we've gotten this
5103	 * far, we've got a LUN reservation.  Anything else got kicked out
5104	 * above.  So, according to SPC, ignore the length.
5105	 */
5106
5107	mtx_lock(&lun->lun_lock);
5108	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5109		ctl_set_reservation_conflict(ctsio);
5110		goto bailout;
5111	}
5112	lun->flags |= CTL_LUN_RESERVED;
5113	lun->res_idx = residx;
5114	ctl_set_success(ctsio);
5115
5116bailout:
5117	mtx_unlock(&lun->lun_lock);
5118	ctl_done((union ctl_io *)ctsio);
5119	return (CTL_RETVAL_COMPLETE);
5120}
5121
5122int
5123ctl_start_stop(struct ctl_scsiio *ctsio)
5124{
5125	struct scsi_start_stop_unit *cdb;
5126	struct ctl_lun *lun;
5127	int retval;
5128
5129	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5130
5131	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5132	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5133
5134	if ((lun->flags & CTL_LUN_PR_RESERVED)
5135	 && ((cdb->how & SSS_START)==0)) {
5136		uint32_t residx;
5137
5138		residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5139		if (ctl_get_prkey(lun, residx) == 0
5140		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5141
5142			ctl_set_reservation_conflict(ctsio);
5143			ctl_done((union ctl_io *)ctsio);
5144			return (CTL_RETVAL_COMPLETE);
5145		}
5146	}
5147
5148	if ((cdb->how & SSS_LOEJ) &&
5149	    (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5150		ctl_set_invalid_field(ctsio,
5151				      /*sks_valid*/ 1,
5152				      /*command*/ 1,
5153				      /*field*/ 4,
5154				      /*bit_valid*/ 1,
5155				      /*bit*/ 1);
5156		ctl_done((union ctl_io *)ctsio);
5157		return (CTL_RETVAL_COMPLETE);
5158	}
5159
5160	retval = lun->backend->config_write((union ctl_io *)ctsio);
5161	return (retval);
5162}
5163
5164int
5165ctl_prevent_allow(struct ctl_scsiio *ctsio)
5166{
5167	struct ctl_lun *lun;
5168	int retval;
5169
5170	CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5171
5172	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5173
5174	if ((lun->flags & CTL_LUN_REMOVABLE) == 0) {
5175		ctl_set_invalid_opcode(ctsio);
5176		ctl_done((union ctl_io *)ctsio);
5177		return (CTL_RETVAL_COMPLETE);
5178	}
5179
5180	retval = lun->backend->config_write((union ctl_io *)ctsio);
5181	return (retval);
5182}
5183
5184/*
5185 * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5186 * we don't really do anything with the LBA and length fields if the user
5187 * passes them in.  Instead we'll just flush out the cache for the entire
5188 * LUN.
5189 */
5190int
5191ctl_sync_cache(struct ctl_scsiio *ctsio)
5192{
5193	struct ctl_lun *lun;
5194	struct ctl_softc *softc;
5195	struct ctl_lba_len_flags *lbalen;
5196	uint64_t starting_lba;
5197	uint32_t block_count;
5198	int retval;
5199	uint8_t byte2;
5200
5201	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5202
5203	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5204	softc = lun->ctl_softc;
5205	retval = 0;
5206
5207	switch (ctsio->cdb[0]) {
5208	case SYNCHRONIZE_CACHE: {
5209		struct scsi_sync_cache *cdb;
5210		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5211
5212		starting_lba = scsi_4btoul(cdb->begin_lba);
5213		block_count = scsi_2btoul(cdb->lb_count);
5214		byte2 = cdb->byte2;
5215		break;
5216	}
5217	case SYNCHRONIZE_CACHE_16: {
5218		struct scsi_sync_cache_16 *cdb;
5219		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5220
5221		starting_lba = scsi_8btou64(cdb->begin_lba);
5222		block_count = scsi_4btoul(cdb->lb_count);
5223		byte2 = cdb->byte2;
5224		break;
5225	}
5226	default:
5227		ctl_set_invalid_opcode(ctsio);
5228		ctl_done((union ctl_io *)ctsio);
5229		goto bailout;
5230		break; /* NOTREACHED */
5231	}
5232
5233	/*
5234	 * We check the LBA and length, but don't do anything with them.
5235	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5236	 * get flushed.  This check will just help satisfy anyone who wants
5237	 * to see an error for an out of range LBA.
5238	 */
5239	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5240		ctl_set_lba_out_of_range(ctsio);
5241		ctl_done((union ctl_io *)ctsio);
5242		goto bailout;
5243	}
5244
5245	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5246	lbalen->lba = starting_lba;
5247	lbalen->len = block_count;
5248	lbalen->flags = byte2;
5249	retval = lun->backend->config_write((union ctl_io *)ctsio);
5250
5251bailout:
5252	return (retval);
5253}
5254
5255int
5256ctl_format(struct ctl_scsiio *ctsio)
5257{
5258	struct scsi_format *cdb;
5259	struct ctl_lun *lun;
5260	int length, defect_list_len;
5261
5262	CTL_DEBUG_PRINT(("ctl_format\n"));
5263
5264	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5265
5266	cdb = (struct scsi_format *)ctsio->cdb;
5267
5268	length = 0;
5269	if (cdb->byte2 & SF_FMTDATA) {
5270		if (cdb->byte2 & SF_LONGLIST)
5271			length = sizeof(struct scsi_format_header_long);
5272		else
5273			length = sizeof(struct scsi_format_header_short);
5274	}
5275
5276	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5277	 && (length > 0)) {
5278		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5279		ctsio->kern_data_len = length;
5280		ctsio->kern_total_len = length;
5281		ctsio->kern_data_resid = 0;
5282		ctsio->kern_rel_offset = 0;
5283		ctsio->kern_sg_entries = 0;
5284		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5285		ctsio->be_move_done = ctl_config_move_done;
5286		ctl_datamove((union ctl_io *)ctsio);
5287
5288		return (CTL_RETVAL_COMPLETE);
5289	}
5290
5291	defect_list_len = 0;
5292
5293	if (cdb->byte2 & SF_FMTDATA) {
5294		if (cdb->byte2 & SF_LONGLIST) {
5295			struct scsi_format_header_long *header;
5296
5297			header = (struct scsi_format_header_long *)
5298				ctsio->kern_data_ptr;
5299
5300			defect_list_len = scsi_4btoul(header->defect_list_len);
5301			if (defect_list_len != 0) {
5302				ctl_set_invalid_field(ctsio,
5303						      /*sks_valid*/ 1,
5304						      /*command*/ 0,
5305						      /*field*/ 2,
5306						      /*bit_valid*/ 0,
5307						      /*bit*/ 0);
5308				goto bailout;
5309			}
5310		} else {
5311			struct scsi_format_header_short *header;
5312
5313			header = (struct scsi_format_header_short *)
5314				ctsio->kern_data_ptr;
5315
5316			defect_list_len = scsi_2btoul(header->defect_list_len);
5317			if (defect_list_len != 0) {
5318				ctl_set_invalid_field(ctsio,
5319						      /*sks_valid*/ 1,
5320						      /*command*/ 0,
5321						      /*field*/ 2,
5322						      /*bit_valid*/ 0,
5323						      /*bit*/ 0);
5324				goto bailout;
5325			}
5326		}
5327	}
5328
5329	ctl_set_success(ctsio);
5330bailout:
5331
5332	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5333		free(ctsio->kern_data_ptr, M_CTL);
5334		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5335	}
5336
5337	ctl_done((union ctl_io *)ctsio);
5338	return (CTL_RETVAL_COMPLETE);
5339}
5340
5341int
5342ctl_read_buffer(struct ctl_scsiio *ctsio)
5343{
5344	struct ctl_lun *lun;
5345	uint64_t buffer_offset;
5346	uint32_t len;
5347	uint8_t byte2;
5348	static uint8_t descr[4];
5349	static uint8_t echo_descr[4] = { 0 };
5350
5351	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5352	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5353	switch (ctsio->cdb[0]) {
5354	case READ_BUFFER: {
5355		struct scsi_read_buffer *cdb;
5356
5357		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5358		buffer_offset = scsi_3btoul(cdb->offset);
5359		len = scsi_3btoul(cdb->length);
5360		byte2 = cdb->byte2;
5361		break;
5362	}
5363	case READ_BUFFER_16: {
5364		struct scsi_read_buffer_16 *cdb;
5365
5366		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5367		buffer_offset = scsi_8btou64(cdb->offset);
5368		len = scsi_4btoul(cdb->length);
5369		byte2 = cdb->byte2;
5370		break;
5371	}
5372	default: /* This shouldn't happen. */
5373		ctl_set_invalid_opcode(ctsio);
5374		ctl_done((union ctl_io *)ctsio);
5375		return (CTL_RETVAL_COMPLETE);
5376	}
5377
5378	if ((byte2 & RWB_MODE) != RWB_MODE_DATA &&
5379	    (byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5380	    (byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5381		ctl_set_invalid_field(ctsio,
5382				      /*sks_valid*/ 1,
5383				      /*command*/ 1,
5384				      /*field*/ 1,
5385				      /*bit_valid*/ 1,
5386				      /*bit*/ 4);
5387		ctl_done((union ctl_io *)ctsio);
5388		return (CTL_RETVAL_COMPLETE);
5389	}
5390
5391	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5392	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5393		ctl_set_invalid_field(ctsio,
5394				      /*sks_valid*/ 1,
5395				      /*command*/ 1,
5396				      /*field*/ 6,
5397				      /*bit_valid*/ 0,
5398				      /*bit*/ 0);
5399		ctl_done((union ctl_io *)ctsio);
5400		return (CTL_RETVAL_COMPLETE);
5401	}
5402
5403	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5404		descr[0] = 0;
5405		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5406		ctsio->kern_data_ptr = descr;
5407		len = min(len, sizeof(descr));
5408	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5409		ctsio->kern_data_ptr = echo_descr;
5410		len = min(len, sizeof(echo_descr));
5411	} else {
5412		if (lun->write_buffer == NULL) {
5413			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5414			    M_CTL, M_WAITOK);
5415		}
5416		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5417	}
5418	ctsio->kern_data_len = len;
5419	ctsio->kern_total_len = len;
5420	ctsio->kern_data_resid = 0;
5421	ctsio->kern_rel_offset = 0;
5422	ctsio->kern_sg_entries = 0;
5423	ctl_set_success(ctsio);
5424	ctsio->be_move_done = ctl_config_move_done;
5425	ctl_datamove((union ctl_io *)ctsio);
5426	return (CTL_RETVAL_COMPLETE);
5427}
5428
5429int
5430ctl_write_buffer(struct ctl_scsiio *ctsio)
5431{
5432	struct scsi_write_buffer *cdb;
5433	struct ctl_lun *lun;
5434	int buffer_offset, len;
5435
5436	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5437
5438	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5439	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5440
5441	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5442		ctl_set_invalid_field(ctsio,
5443				      /*sks_valid*/ 1,
5444				      /*command*/ 1,
5445				      /*field*/ 1,
5446				      /*bit_valid*/ 1,
5447				      /*bit*/ 4);
5448		ctl_done((union ctl_io *)ctsio);
5449		return (CTL_RETVAL_COMPLETE);
5450	}
5451
5452	len = scsi_3btoul(cdb->length);
5453	buffer_offset = scsi_3btoul(cdb->offset);
5454
5455	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5456		ctl_set_invalid_field(ctsio,
5457				      /*sks_valid*/ 1,
5458				      /*command*/ 1,
5459				      /*field*/ 6,
5460				      /*bit_valid*/ 0,
5461				      /*bit*/ 0);
5462		ctl_done((union ctl_io *)ctsio);
5463		return (CTL_RETVAL_COMPLETE);
5464	}
5465
5466	/*
5467	 * If we've got a kernel request that hasn't been malloced yet,
5468	 * malloc it and tell the caller the data buffer is here.
5469	 */
5470	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5471		if (lun->write_buffer == NULL) {
5472			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5473			    M_CTL, M_WAITOK);
5474		}
5475		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5476		ctsio->kern_data_len = len;
5477		ctsio->kern_total_len = len;
5478		ctsio->kern_data_resid = 0;
5479		ctsio->kern_rel_offset = 0;
5480		ctsio->kern_sg_entries = 0;
5481		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5482		ctsio->be_move_done = ctl_config_move_done;
5483		ctl_datamove((union ctl_io *)ctsio);
5484
5485		return (CTL_RETVAL_COMPLETE);
5486	}
5487
5488	ctl_set_success(ctsio);
5489	ctl_done((union ctl_io *)ctsio);
5490	return (CTL_RETVAL_COMPLETE);
5491}
5492
5493int
5494ctl_write_same(struct ctl_scsiio *ctsio)
5495{
5496	struct ctl_lun *lun;
5497	struct ctl_lba_len_flags *lbalen;
5498	uint64_t lba;
5499	uint32_t num_blocks;
5500	int len, retval;
5501	uint8_t byte2;
5502
5503	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5504
5505	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5506
5507	switch (ctsio->cdb[0]) {
5508	case WRITE_SAME_10: {
5509		struct scsi_write_same_10 *cdb;
5510
5511		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5512
5513		lba = scsi_4btoul(cdb->addr);
5514		num_blocks = scsi_2btoul(cdb->length);
5515		byte2 = cdb->byte2;
5516		break;
5517	}
5518	case WRITE_SAME_16: {
5519		struct scsi_write_same_16 *cdb;
5520
5521		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5522
5523		lba = scsi_8btou64(cdb->addr);
5524		num_blocks = scsi_4btoul(cdb->length);
5525		byte2 = cdb->byte2;
5526		break;
5527	}
5528	default:
5529		/*
5530		 * We got a command we don't support.  This shouldn't
5531		 * happen, commands should be filtered out above us.
5532		 */
5533		ctl_set_invalid_opcode(ctsio);
5534		ctl_done((union ctl_io *)ctsio);
5535
5536		return (CTL_RETVAL_COMPLETE);
5537		break; /* NOTREACHED */
5538	}
5539
5540	/* ANCHOR flag can be used only together with UNMAP */
5541	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5542		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5543		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5544		ctl_done((union ctl_io *)ctsio);
5545		return (CTL_RETVAL_COMPLETE);
5546	}
5547
5548	/*
5549	 * The first check is to make sure we're in bounds, the second
5550	 * check is to catch wrap-around problems.  If the lba + num blocks
5551	 * is less than the lba, then we've wrapped around and the block
5552	 * range is invalid anyway.
5553	 */
5554	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5555	 || ((lba + num_blocks) < lba)) {
5556		ctl_set_lba_out_of_range(ctsio);
5557		ctl_done((union ctl_io *)ctsio);
5558		return (CTL_RETVAL_COMPLETE);
5559	}
5560
5561	/* Zero number of blocks means "to the last logical block" */
5562	if (num_blocks == 0) {
5563		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5564			ctl_set_invalid_field(ctsio,
5565					      /*sks_valid*/ 0,
5566					      /*command*/ 1,
5567					      /*field*/ 0,
5568					      /*bit_valid*/ 0,
5569					      /*bit*/ 0);
5570			ctl_done((union ctl_io *)ctsio);
5571			return (CTL_RETVAL_COMPLETE);
5572		}
5573		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5574	}
5575
5576	len = lun->be_lun->blocksize;
5577
5578	/*
5579	 * If we've got a kernel request that hasn't been malloced yet,
5580	 * malloc it and tell the caller the data buffer is here.
5581	 */
5582	if ((byte2 & SWS_NDOB) == 0 &&
5583	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5584		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5585		ctsio->kern_data_len = len;
5586		ctsio->kern_total_len = len;
5587		ctsio->kern_data_resid = 0;
5588		ctsio->kern_rel_offset = 0;
5589		ctsio->kern_sg_entries = 0;
5590		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5591		ctsio->be_move_done = ctl_config_move_done;
5592		ctl_datamove((union ctl_io *)ctsio);
5593
5594		return (CTL_RETVAL_COMPLETE);
5595	}
5596
5597	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5598	lbalen->lba = lba;
5599	lbalen->len = num_blocks;
5600	lbalen->flags = byte2;
5601	retval = lun->backend->config_write((union ctl_io *)ctsio);
5602
5603	return (retval);
5604}
5605
5606int
5607ctl_unmap(struct ctl_scsiio *ctsio)
5608{
5609	struct ctl_lun *lun;
5610	struct scsi_unmap *cdb;
5611	struct ctl_ptr_len_flags *ptrlen;
5612	struct scsi_unmap_header *hdr;
5613	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5614	uint64_t lba;
5615	uint32_t num_blocks;
5616	int len, retval;
5617	uint8_t byte2;
5618
5619	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5620
5621	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5622	cdb = (struct scsi_unmap *)ctsio->cdb;
5623
5624	len = scsi_2btoul(cdb->length);
5625	byte2 = cdb->byte2;
5626
5627	/*
5628	 * If we've got a kernel request that hasn't been malloced yet,
5629	 * malloc it and tell the caller the data buffer is here.
5630	 */
5631	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5632		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5633		ctsio->kern_data_len = len;
5634		ctsio->kern_total_len = len;
5635		ctsio->kern_data_resid = 0;
5636		ctsio->kern_rel_offset = 0;
5637		ctsio->kern_sg_entries = 0;
5638		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5639		ctsio->be_move_done = ctl_config_move_done;
5640		ctl_datamove((union ctl_io *)ctsio);
5641
5642		return (CTL_RETVAL_COMPLETE);
5643	}
5644
5645	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5646	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5647	if (len < sizeof (*hdr) ||
5648	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5649	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5650	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5651		ctl_set_invalid_field(ctsio,
5652				      /*sks_valid*/ 0,
5653				      /*command*/ 0,
5654				      /*field*/ 0,
5655				      /*bit_valid*/ 0,
5656				      /*bit*/ 0);
5657		goto done;
5658	}
5659	len = scsi_2btoul(hdr->desc_length);
5660	buf = (struct scsi_unmap_desc *)(hdr + 1);
5661	end = buf + len / sizeof(*buf);
5662
5663	endnz = buf;
5664	for (range = buf; range < end; range++) {
5665		lba = scsi_8btou64(range->lba);
5666		num_blocks = scsi_4btoul(range->length);
5667		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5668		 || ((lba + num_blocks) < lba)) {
5669			ctl_set_lba_out_of_range(ctsio);
5670			ctl_done((union ctl_io *)ctsio);
5671			return (CTL_RETVAL_COMPLETE);
5672		}
5673		if (num_blocks != 0)
5674			endnz = range + 1;
5675	}
5676
5677	/*
5678	 * Block backend can not handle zero last range.
5679	 * Filter it out and return if there is nothing left.
5680	 */
5681	len = (uint8_t *)endnz - (uint8_t *)buf;
5682	if (len == 0) {
5683		ctl_set_success(ctsio);
5684		goto done;
5685	}
5686
5687	mtx_lock(&lun->lun_lock);
5688	ptrlen = (struct ctl_ptr_len_flags *)
5689	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5690	ptrlen->ptr = (void *)buf;
5691	ptrlen->len = len;
5692	ptrlen->flags = byte2;
5693	ctl_check_blocked(lun);
5694	mtx_unlock(&lun->lun_lock);
5695
5696	retval = lun->backend->config_write((union ctl_io *)ctsio);
5697	return (retval);
5698
5699done:
5700	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5701		free(ctsio->kern_data_ptr, M_CTL);
5702		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5703	}
5704	ctl_done((union ctl_io *)ctsio);
5705	return (CTL_RETVAL_COMPLETE);
5706}
5707
5708/*
5709 * Note that this function currently doesn't actually do anything inside
5710 * CTL to enforce things if the DQue bit is turned on.
5711 *
5712 * Also note that this function can't be used in the default case, because
5713 * the DQue bit isn't set in the changeable mask for the control mode page
5714 * anyway.  This is just here as an example for how to implement a page
5715 * handler, and a placeholder in case we want to allow the user to turn
5716 * tagged queueing on and off.
5717 *
5718 * The D_SENSE bit handling is functional, however, and will turn
5719 * descriptor sense on and off for a given LUN.
5720 */
5721int
5722ctl_control_page_handler(struct ctl_scsiio *ctsio,
5723			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5724{
5725	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5726	struct ctl_lun *lun;
5727	int set_ua;
5728	uint32_t initidx;
5729
5730	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5731	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5732	set_ua = 0;
5733
5734	user_cp = (struct scsi_control_page *)page_ptr;
5735	current_cp = (struct scsi_control_page *)
5736		(page_index->page_data + (page_index->page_len *
5737		CTL_PAGE_CURRENT));
5738	saved_cp = (struct scsi_control_page *)
5739		(page_index->page_data + (page_index->page_len *
5740		CTL_PAGE_SAVED));
5741
5742	mtx_lock(&lun->lun_lock);
5743	if (((current_cp->rlec & SCP_DSENSE) == 0)
5744	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
5745		/*
5746		 * Descriptor sense is currently turned off and the user
5747		 * wants to turn it on.
5748		 */
5749		current_cp->rlec |= SCP_DSENSE;
5750		saved_cp->rlec |= SCP_DSENSE;
5751		lun->flags |= CTL_LUN_SENSE_DESC;
5752		set_ua = 1;
5753	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
5754		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
5755		/*
5756		 * Descriptor sense is currently turned on, and the user
5757		 * wants to turn it off.
5758		 */
5759		current_cp->rlec &= ~SCP_DSENSE;
5760		saved_cp->rlec &= ~SCP_DSENSE;
5761		lun->flags &= ~CTL_LUN_SENSE_DESC;
5762		set_ua = 1;
5763	}
5764	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
5765	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
5766		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5767		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5768		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5769		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5770		set_ua = 1;
5771	}
5772	if ((current_cp->eca_and_aen & SCP_SWP) !=
5773	    (user_cp->eca_and_aen & SCP_SWP)) {
5774		current_cp->eca_and_aen &= ~SCP_SWP;
5775		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5776		saved_cp->eca_and_aen &= ~SCP_SWP;
5777		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5778		set_ua = 1;
5779	}
5780	if (set_ua != 0)
5781		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5782	mtx_unlock(&lun->lun_lock);
5783	if (set_ua) {
5784		ctl_isc_announce_mode(lun,
5785		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5786		    page_index->page_code, page_index->subpage);
5787	}
5788	return (0);
5789}
5790
5791int
5792ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
5793		     struct ctl_page_index *page_index, uint8_t *page_ptr)
5794{
5795	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
5796	struct ctl_lun *lun;
5797	int set_ua;
5798	uint32_t initidx;
5799
5800	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5801	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5802	set_ua = 0;
5803
5804	user_cp = (struct scsi_caching_page *)page_ptr;
5805	current_cp = (struct scsi_caching_page *)
5806		(page_index->page_data + (page_index->page_len *
5807		CTL_PAGE_CURRENT));
5808	saved_cp = (struct scsi_caching_page *)
5809		(page_index->page_data + (page_index->page_len *
5810		CTL_PAGE_SAVED));
5811
5812	mtx_lock(&lun->lun_lock);
5813	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
5814	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
5815		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5816		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5817		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5818		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5819		set_ua = 1;
5820	}
5821	if (set_ua != 0)
5822		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5823	mtx_unlock(&lun->lun_lock);
5824	if (set_ua) {
5825		ctl_isc_announce_mode(lun,
5826		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5827		    page_index->page_code, page_index->subpage);
5828	}
5829	return (0);
5830}
5831
5832int
5833ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
5834				struct ctl_page_index *page_index,
5835				uint8_t *page_ptr)
5836{
5837	uint8_t *c;
5838	int i;
5839
5840	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
5841	ctl_time_io_secs =
5842		(c[0] << 8) |
5843		(c[1] << 0) |
5844		0;
5845	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
5846	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
5847	printf("page data:");
5848	for (i=0; i<8; i++)
5849		printf(" %.2x",page_ptr[i]);
5850	printf("\n");
5851	return (0);
5852}
5853
5854int
5855ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
5856			       struct ctl_page_index *page_index,
5857			       int pc)
5858{
5859	struct copan_debugconf_subpage *page;
5860
5861	page = (struct copan_debugconf_subpage *)page_index->page_data +
5862		(page_index->page_len * pc);
5863
5864	switch (pc) {
5865	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
5866	case SMS_PAGE_CTRL_DEFAULT >> 6:
5867	case SMS_PAGE_CTRL_SAVED >> 6:
5868		/*
5869		 * We don't update the changable or default bits for this page.
5870		 */
5871		break;
5872	case SMS_PAGE_CTRL_CURRENT >> 6:
5873		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
5874		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
5875		break;
5876	default:
5877		break;
5878	}
5879	return (0);
5880}
5881
5882
5883static int
5884ctl_do_mode_select(union ctl_io *io)
5885{
5886	struct scsi_mode_page_header *page_header;
5887	struct ctl_page_index *page_index;
5888	struct ctl_scsiio *ctsio;
5889	int page_len, page_len_offset, page_len_size;
5890	union ctl_modepage_info *modepage_info;
5891	struct ctl_lun *lun;
5892	int *len_left, *len_used;
5893	int retval, i;
5894
5895	ctsio = &io->scsiio;
5896	page_index = NULL;
5897	page_len = 0;
5898	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5899
5900	modepage_info = (union ctl_modepage_info *)
5901		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5902	len_left = &modepage_info->header.len_left;
5903	len_used = &modepage_info->header.len_used;
5904
5905do_next_page:
5906
5907	page_header = (struct scsi_mode_page_header *)
5908		(ctsio->kern_data_ptr + *len_used);
5909
5910	if (*len_left == 0) {
5911		free(ctsio->kern_data_ptr, M_CTL);
5912		ctl_set_success(ctsio);
5913		ctl_done((union ctl_io *)ctsio);
5914		return (CTL_RETVAL_COMPLETE);
5915	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
5916
5917		free(ctsio->kern_data_ptr, M_CTL);
5918		ctl_set_param_len_error(ctsio);
5919		ctl_done((union ctl_io *)ctsio);
5920		return (CTL_RETVAL_COMPLETE);
5921
5922	} else if ((page_header->page_code & SMPH_SPF)
5923		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
5924
5925		free(ctsio->kern_data_ptr, M_CTL);
5926		ctl_set_param_len_error(ctsio);
5927		ctl_done((union ctl_io *)ctsio);
5928		return (CTL_RETVAL_COMPLETE);
5929	}
5930
5931
5932	/*
5933	 * XXX KDM should we do something with the block descriptor?
5934	 */
5935	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5936		page_index = &lun->mode_pages.index[i];
5937		if (lun->be_lun->lun_type == T_DIRECT &&
5938		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
5939			continue;
5940		if (lun->be_lun->lun_type == T_PROCESSOR &&
5941		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
5942			continue;
5943		if (lun->be_lun->lun_type == T_CDROM &&
5944		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
5945			continue;
5946
5947		if ((page_index->page_code & SMPH_PC_MASK) !=
5948		    (page_header->page_code & SMPH_PC_MASK))
5949			continue;
5950
5951		/*
5952		 * If neither page has a subpage code, then we've got a
5953		 * match.
5954		 */
5955		if (((page_index->page_code & SMPH_SPF) == 0)
5956		 && ((page_header->page_code & SMPH_SPF) == 0)) {
5957			page_len = page_header->page_length;
5958			break;
5959		}
5960
5961		/*
5962		 * If both pages have subpages, then the subpage numbers
5963		 * have to match.
5964		 */
5965		if ((page_index->page_code & SMPH_SPF)
5966		  && (page_header->page_code & SMPH_SPF)) {
5967			struct scsi_mode_page_header_sp *sph;
5968
5969			sph = (struct scsi_mode_page_header_sp *)page_header;
5970			if (page_index->subpage == sph->subpage) {
5971				page_len = scsi_2btoul(sph->page_length);
5972				break;
5973			}
5974		}
5975	}
5976
5977	/*
5978	 * If we couldn't find the page, or if we don't have a mode select
5979	 * handler for it, send back an error to the user.
5980	 */
5981	if ((i >= CTL_NUM_MODE_PAGES)
5982	 || (page_index->select_handler == NULL)) {
5983		ctl_set_invalid_field(ctsio,
5984				      /*sks_valid*/ 1,
5985				      /*command*/ 0,
5986				      /*field*/ *len_used,
5987				      /*bit_valid*/ 0,
5988				      /*bit*/ 0);
5989		free(ctsio->kern_data_ptr, M_CTL);
5990		ctl_done((union ctl_io *)ctsio);
5991		return (CTL_RETVAL_COMPLETE);
5992	}
5993
5994	if (page_index->page_code & SMPH_SPF) {
5995		page_len_offset = 2;
5996		page_len_size = 2;
5997	} else {
5998		page_len_size = 1;
5999		page_len_offset = 1;
6000	}
6001
6002	/*
6003	 * If the length the initiator gives us isn't the one we specify in
6004	 * the mode page header, or if they didn't specify enough data in
6005	 * the CDB to avoid truncating this page, kick out the request.
6006	 */
6007	if ((page_len != (page_index->page_len - page_len_offset -
6008			  page_len_size))
6009	 || (*len_left < page_index->page_len)) {
6010
6011
6012		ctl_set_invalid_field(ctsio,
6013				      /*sks_valid*/ 1,
6014				      /*command*/ 0,
6015				      /*field*/ *len_used + page_len_offset,
6016				      /*bit_valid*/ 0,
6017				      /*bit*/ 0);
6018		free(ctsio->kern_data_ptr, M_CTL);
6019		ctl_done((union ctl_io *)ctsio);
6020		return (CTL_RETVAL_COMPLETE);
6021	}
6022
6023	/*
6024	 * Run through the mode page, checking to make sure that the bits
6025	 * the user changed are actually legal for him to change.
6026	 */
6027	for (i = 0; i < page_index->page_len; i++) {
6028		uint8_t *user_byte, *change_mask, *current_byte;
6029		int bad_bit;
6030		int j;
6031
6032		user_byte = (uint8_t *)page_header + i;
6033		change_mask = page_index->page_data +
6034			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6035		current_byte = page_index->page_data +
6036			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6037
6038		/*
6039		 * Check to see whether the user set any bits in this byte
6040		 * that he is not allowed to set.
6041		 */
6042		if ((*user_byte & ~(*change_mask)) ==
6043		    (*current_byte & ~(*change_mask)))
6044			continue;
6045
6046		/*
6047		 * Go through bit by bit to determine which one is illegal.
6048		 */
6049		bad_bit = 0;
6050		for (j = 7; j >= 0; j--) {
6051			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6052			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6053				bad_bit = i;
6054				break;
6055			}
6056		}
6057		ctl_set_invalid_field(ctsio,
6058				      /*sks_valid*/ 1,
6059				      /*command*/ 0,
6060				      /*field*/ *len_used + i,
6061				      /*bit_valid*/ 1,
6062				      /*bit*/ bad_bit);
6063		free(ctsio->kern_data_ptr, M_CTL);
6064		ctl_done((union ctl_io *)ctsio);
6065		return (CTL_RETVAL_COMPLETE);
6066	}
6067
6068	/*
6069	 * Decrement these before we call the page handler, since we may
6070	 * end up getting called back one way or another before the handler
6071	 * returns to this context.
6072	 */
6073	*len_left -= page_index->page_len;
6074	*len_used += page_index->page_len;
6075
6076	retval = page_index->select_handler(ctsio, page_index,
6077					    (uint8_t *)page_header);
6078
6079	/*
6080	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6081	 * wait until this queued command completes to finish processing
6082	 * the mode page.  If it returns anything other than
6083	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6084	 * already set the sense information, freed the data pointer, and
6085	 * completed the io for us.
6086	 */
6087	if (retval != CTL_RETVAL_COMPLETE)
6088		goto bailout_no_done;
6089
6090	/*
6091	 * If the initiator sent us more than one page, parse the next one.
6092	 */
6093	if (*len_left > 0)
6094		goto do_next_page;
6095
6096	ctl_set_success(ctsio);
6097	free(ctsio->kern_data_ptr, M_CTL);
6098	ctl_done((union ctl_io *)ctsio);
6099
6100bailout_no_done:
6101
6102	return (CTL_RETVAL_COMPLETE);
6103
6104}
6105
6106int
6107ctl_mode_select(struct ctl_scsiio *ctsio)
6108{
6109	int param_len, pf, sp;
6110	int header_size, bd_len;
6111	union ctl_modepage_info *modepage_info;
6112
6113	switch (ctsio->cdb[0]) {
6114	case MODE_SELECT_6: {
6115		struct scsi_mode_select_6 *cdb;
6116
6117		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6118
6119		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6120		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6121		param_len = cdb->length;
6122		header_size = sizeof(struct scsi_mode_header_6);
6123		break;
6124	}
6125	case MODE_SELECT_10: {
6126		struct scsi_mode_select_10 *cdb;
6127
6128		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6129
6130		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6131		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6132		param_len = scsi_2btoul(cdb->length);
6133		header_size = sizeof(struct scsi_mode_header_10);
6134		break;
6135	}
6136	default:
6137		ctl_set_invalid_opcode(ctsio);
6138		ctl_done((union ctl_io *)ctsio);
6139		return (CTL_RETVAL_COMPLETE);
6140	}
6141
6142	/*
6143	 * From SPC-3:
6144	 * "A parameter list length of zero indicates that the Data-Out Buffer
6145	 * shall be empty. This condition shall not be considered as an error."
6146	 */
6147	if (param_len == 0) {
6148		ctl_set_success(ctsio);
6149		ctl_done((union ctl_io *)ctsio);
6150		return (CTL_RETVAL_COMPLETE);
6151	}
6152
6153	/*
6154	 * Since we'll hit this the first time through, prior to
6155	 * allocation, we don't need to free a data buffer here.
6156	 */
6157	if (param_len < header_size) {
6158		ctl_set_param_len_error(ctsio);
6159		ctl_done((union ctl_io *)ctsio);
6160		return (CTL_RETVAL_COMPLETE);
6161	}
6162
6163	/*
6164	 * Allocate the data buffer and grab the user's data.  In theory,
6165	 * we shouldn't have to sanity check the parameter list length here
6166	 * because the maximum size is 64K.  We should be able to malloc
6167	 * that much without too many problems.
6168	 */
6169	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6170		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6171		ctsio->kern_data_len = param_len;
6172		ctsio->kern_total_len = param_len;
6173		ctsio->kern_data_resid = 0;
6174		ctsio->kern_rel_offset = 0;
6175		ctsio->kern_sg_entries = 0;
6176		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6177		ctsio->be_move_done = ctl_config_move_done;
6178		ctl_datamove((union ctl_io *)ctsio);
6179
6180		return (CTL_RETVAL_COMPLETE);
6181	}
6182
6183	switch (ctsio->cdb[0]) {
6184	case MODE_SELECT_6: {
6185		struct scsi_mode_header_6 *mh6;
6186
6187		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6188		bd_len = mh6->blk_desc_len;
6189		break;
6190	}
6191	case MODE_SELECT_10: {
6192		struct scsi_mode_header_10 *mh10;
6193
6194		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6195		bd_len = scsi_2btoul(mh10->blk_desc_len);
6196		break;
6197	}
6198	default:
6199		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6200		break;
6201	}
6202
6203	if (param_len < (header_size + bd_len)) {
6204		free(ctsio->kern_data_ptr, M_CTL);
6205		ctl_set_param_len_error(ctsio);
6206		ctl_done((union ctl_io *)ctsio);
6207		return (CTL_RETVAL_COMPLETE);
6208	}
6209
6210	/*
6211	 * Set the IO_CONT flag, so that if this I/O gets passed to
6212	 * ctl_config_write_done(), it'll get passed back to
6213	 * ctl_do_mode_select() for further processing, or completion if
6214	 * we're all done.
6215	 */
6216	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6217	ctsio->io_cont = ctl_do_mode_select;
6218
6219	modepage_info = (union ctl_modepage_info *)
6220		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6221	memset(modepage_info, 0, sizeof(*modepage_info));
6222	modepage_info->header.len_left = param_len - header_size - bd_len;
6223	modepage_info->header.len_used = header_size + bd_len;
6224
6225	return (ctl_do_mode_select((union ctl_io *)ctsio));
6226}
6227
6228int
6229ctl_mode_sense(struct ctl_scsiio *ctsio)
6230{
6231	struct ctl_lun *lun;
6232	int pc, page_code, dbd, llba, subpage;
6233	int alloc_len, page_len, header_len, total_len;
6234	struct scsi_mode_block_descr *block_desc;
6235	struct ctl_page_index *page_index;
6236
6237	dbd = 0;
6238	llba = 0;
6239	block_desc = NULL;
6240
6241	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6242
6243	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6244	switch (ctsio->cdb[0]) {
6245	case MODE_SENSE_6: {
6246		struct scsi_mode_sense_6 *cdb;
6247
6248		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6249
6250		header_len = sizeof(struct scsi_mode_hdr_6);
6251		if (cdb->byte2 & SMS_DBD)
6252			dbd = 1;
6253		else
6254			header_len += sizeof(struct scsi_mode_block_descr);
6255
6256		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6257		page_code = cdb->page & SMS_PAGE_CODE;
6258		subpage = cdb->subpage;
6259		alloc_len = cdb->length;
6260		break;
6261	}
6262	case MODE_SENSE_10: {
6263		struct scsi_mode_sense_10 *cdb;
6264
6265		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6266
6267		header_len = sizeof(struct scsi_mode_hdr_10);
6268
6269		if (cdb->byte2 & SMS_DBD)
6270			dbd = 1;
6271		else
6272			header_len += sizeof(struct scsi_mode_block_descr);
6273		if (cdb->byte2 & SMS10_LLBAA)
6274			llba = 1;
6275		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6276		page_code = cdb->page & SMS_PAGE_CODE;
6277		subpage = cdb->subpage;
6278		alloc_len = scsi_2btoul(cdb->length);
6279		break;
6280	}
6281	default:
6282		ctl_set_invalid_opcode(ctsio);
6283		ctl_done((union ctl_io *)ctsio);
6284		return (CTL_RETVAL_COMPLETE);
6285		break; /* NOTREACHED */
6286	}
6287
6288	/*
6289	 * We have to make a first pass through to calculate the size of
6290	 * the pages that match the user's query.  Then we allocate enough
6291	 * memory to hold it, and actually copy the data into the buffer.
6292	 */
6293	switch (page_code) {
6294	case SMS_ALL_PAGES_PAGE: {
6295		int i;
6296
6297		page_len = 0;
6298
6299		/*
6300		 * At the moment, values other than 0 and 0xff here are
6301		 * reserved according to SPC-3.
6302		 */
6303		if ((subpage != SMS_SUBPAGE_PAGE_0)
6304		 && (subpage != SMS_SUBPAGE_ALL)) {
6305			ctl_set_invalid_field(ctsio,
6306					      /*sks_valid*/ 1,
6307					      /*command*/ 1,
6308					      /*field*/ 3,
6309					      /*bit_valid*/ 0,
6310					      /*bit*/ 0);
6311			ctl_done((union ctl_io *)ctsio);
6312			return (CTL_RETVAL_COMPLETE);
6313		}
6314
6315		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6316			page_index = &lun->mode_pages.index[i];
6317
6318			/* Make sure the page is supported for this dev type */
6319			if (lun->be_lun->lun_type == T_DIRECT &&
6320			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6321				continue;
6322			if (lun->be_lun->lun_type == T_PROCESSOR &&
6323			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6324				continue;
6325			if (lun->be_lun->lun_type == T_CDROM &&
6326			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6327				continue;
6328
6329			/*
6330			 * We don't use this subpage if the user didn't
6331			 * request all subpages.
6332			 */
6333			if ((page_index->subpage != 0)
6334			 && (subpage == SMS_SUBPAGE_PAGE_0))
6335				continue;
6336
6337#if 0
6338			printf("found page %#x len %d\n",
6339			       page_index->page_code & SMPH_PC_MASK,
6340			       page_index->page_len);
6341#endif
6342			page_len += page_index->page_len;
6343		}
6344		break;
6345	}
6346	default: {
6347		int i;
6348
6349		page_len = 0;
6350
6351		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6352			page_index = &lun->mode_pages.index[i];
6353
6354			/* Make sure the page is supported for this dev type */
6355			if (lun->be_lun->lun_type == T_DIRECT &&
6356			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6357				continue;
6358			if (lun->be_lun->lun_type == T_PROCESSOR &&
6359			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6360				continue;
6361			if (lun->be_lun->lun_type == T_CDROM &&
6362			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6363				continue;
6364
6365			/* Look for the right page code */
6366			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6367				continue;
6368
6369			/* Look for the right subpage or the subpage wildcard*/
6370			if ((page_index->subpage != subpage)
6371			 && (subpage != SMS_SUBPAGE_ALL))
6372				continue;
6373
6374#if 0
6375			printf("found page %#x len %d\n",
6376			       page_index->page_code & SMPH_PC_MASK,
6377			       page_index->page_len);
6378#endif
6379
6380			page_len += page_index->page_len;
6381		}
6382
6383		if (page_len == 0) {
6384			ctl_set_invalid_field(ctsio,
6385					      /*sks_valid*/ 1,
6386					      /*command*/ 1,
6387					      /*field*/ 2,
6388					      /*bit_valid*/ 1,
6389					      /*bit*/ 5);
6390			ctl_done((union ctl_io *)ctsio);
6391			return (CTL_RETVAL_COMPLETE);
6392		}
6393		break;
6394	}
6395	}
6396
6397	total_len = header_len + page_len;
6398#if 0
6399	printf("header_len = %d, page_len = %d, total_len = %d\n",
6400	       header_len, page_len, total_len);
6401#endif
6402
6403	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6404	ctsio->kern_sg_entries = 0;
6405	ctsio->kern_data_resid = 0;
6406	ctsio->kern_rel_offset = 0;
6407	if (total_len < alloc_len) {
6408		ctsio->residual = alloc_len - total_len;
6409		ctsio->kern_data_len = total_len;
6410		ctsio->kern_total_len = total_len;
6411	} else {
6412		ctsio->residual = 0;
6413		ctsio->kern_data_len = alloc_len;
6414		ctsio->kern_total_len = alloc_len;
6415	}
6416
6417	switch (ctsio->cdb[0]) {
6418	case MODE_SENSE_6: {
6419		struct scsi_mode_hdr_6 *header;
6420
6421		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6422
6423		header->datalen = MIN(total_len - 1, 254);
6424		if (lun->be_lun->lun_type == T_DIRECT) {
6425			header->dev_specific = 0x10; /* DPOFUA */
6426			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6427			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6428			    .eca_and_aen & SCP_SWP) != 0)
6429				    header->dev_specific |= 0x80; /* WP */
6430		}
6431		if (dbd)
6432			header->block_descr_len = 0;
6433		else
6434			header->block_descr_len =
6435				sizeof(struct scsi_mode_block_descr);
6436		block_desc = (struct scsi_mode_block_descr *)&header[1];
6437		break;
6438	}
6439	case MODE_SENSE_10: {
6440		struct scsi_mode_hdr_10 *header;
6441		int datalen;
6442
6443		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6444
6445		datalen = MIN(total_len - 2, 65533);
6446		scsi_ulto2b(datalen, header->datalen);
6447		if (lun->be_lun->lun_type == T_DIRECT) {
6448			header->dev_specific = 0x10; /* DPOFUA */
6449			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6450			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6451			    .eca_and_aen & SCP_SWP) != 0)
6452				    header->dev_specific |= 0x80; /* WP */
6453		}
6454		if (dbd)
6455			scsi_ulto2b(0, header->block_descr_len);
6456		else
6457			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6458				    header->block_descr_len);
6459		block_desc = (struct scsi_mode_block_descr *)&header[1];
6460		break;
6461	}
6462	default:
6463		panic("invalid CDB type %#x", ctsio->cdb[0]);
6464		break; /* NOTREACHED */
6465	}
6466
6467	/*
6468	 * If we've got a disk, use its blocksize in the block
6469	 * descriptor.  Otherwise, just set it to 0.
6470	 */
6471	if (dbd == 0) {
6472		if (lun->be_lun->lun_type == T_DIRECT)
6473			scsi_ulto3b(lun->be_lun->blocksize,
6474				    block_desc->block_len);
6475		else
6476			scsi_ulto3b(0, block_desc->block_len);
6477	}
6478
6479	switch (page_code) {
6480	case SMS_ALL_PAGES_PAGE: {
6481		int i, data_used;
6482
6483		data_used = header_len;
6484		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6485			struct ctl_page_index *page_index;
6486
6487			page_index = &lun->mode_pages.index[i];
6488			if (lun->be_lun->lun_type == T_DIRECT &&
6489			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6490				continue;
6491			if (lun->be_lun->lun_type == T_PROCESSOR &&
6492			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6493				continue;
6494			if (lun->be_lun->lun_type == T_CDROM &&
6495			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6496				continue;
6497
6498			/*
6499			 * We don't use this subpage if the user didn't
6500			 * request all subpages.  We already checked (above)
6501			 * to make sure the user only specified a subpage
6502			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6503			 */
6504			if ((page_index->subpage != 0)
6505			 && (subpage == SMS_SUBPAGE_PAGE_0))
6506				continue;
6507
6508			/*
6509			 * Call the handler, if it exists, to update the
6510			 * page to the latest values.
6511			 */
6512			if (page_index->sense_handler != NULL)
6513				page_index->sense_handler(ctsio, page_index,pc);
6514
6515			memcpy(ctsio->kern_data_ptr + data_used,
6516			       page_index->page_data +
6517			       (page_index->page_len * pc),
6518			       page_index->page_len);
6519			data_used += page_index->page_len;
6520		}
6521		break;
6522	}
6523	default: {
6524		int i, data_used;
6525
6526		data_used = header_len;
6527
6528		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6529			struct ctl_page_index *page_index;
6530
6531			page_index = &lun->mode_pages.index[i];
6532
6533			/* Look for the right page code */
6534			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6535				continue;
6536
6537			/* Look for the right subpage or the subpage wildcard*/
6538			if ((page_index->subpage != subpage)
6539			 && (subpage != SMS_SUBPAGE_ALL))
6540				continue;
6541
6542			/* Make sure the page is supported for this dev type */
6543			if (lun->be_lun->lun_type == T_DIRECT &&
6544			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6545				continue;
6546			if (lun->be_lun->lun_type == T_PROCESSOR &&
6547			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6548				continue;
6549			if (lun->be_lun->lun_type == T_CDROM &&
6550			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6551				continue;
6552
6553			/*
6554			 * Call the handler, if it exists, to update the
6555			 * page to the latest values.
6556			 */
6557			if (page_index->sense_handler != NULL)
6558				page_index->sense_handler(ctsio, page_index,pc);
6559
6560			memcpy(ctsio->kern_data_ptr + data_used,
6561			       page_index->page_data +
6562			       (page_index->page_len * pc),
6563			       page_index->page_len);
6564			data_used += page_index->page_len;
6565		}
6566		break;
6567	}
6568	}
6569
6570	ctl_set_success(ctsio);
6571	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6572	ctsio->be_move_done = ctl_config_move_done;
6573	ctl_datamove((union ctl_io *)ctsio);
6574	return (CTL_RETVAL_COMPLETE);
6575}
6576
6577int
6578ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6579			       struct ctl_page_index *page_index,
6580			       int pc)
6581{
6582	struct ctl_lun *lun;
6583	struct scsi_log_param_header *phdr;
6584	uint8_t *data;
6585	uint64_t val;
6586
6587	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6588	data = page_index->page_data;
6589
6590	if (lun->backend->lun_attr != NULL &&
6591	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6592	     != UINT64_MAX) {
6593		phdr = (struct scsi_log_param_header *)data;
6594		scsi_ulto2b(0x0001, phdr->param_code);
6595		phdr->param_control = SLP_LBIN | SLP_LP;
6596		phdr->param_len = 8;
6597		data = (uint8_t *)(phdr + 1);
6598		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6599		data[4] = 0x02; /* per-pool */
6600		data += phdr->param_len;
6601	}
6602
6603	if (lun->backend->lun_attr != NULL &&
6604	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6605	     != UINT64_MAX) {
6606		phdr = (struct scsi_log_param_header *)data;
6607		scsi_ulto2b(0x0002, phdr->param_code);
6608		phdr->param_control = SLP_LBIN | SLP_LP;
6609		phdr->param_len = 8;
6610		data = (uint8_t *)(phdr + 1);
6611		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6612		data[4] = 0x01; /* per-LUN */
6613		data += phdr->param_len;
6614	}
6615
6616	if (lun->backend->lun_attr != NULL &&
6617	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6618	     != UINT64_MAX) {
6619		phdr = (struct scsi_log_param_header *)data;
6620		scsi_ulto2b(0x00f1, phdr->param_code);
6621		phdr->param_control = SLP_LBIN | SLP_LP;
6622		phdr->param_len = 8;
6623		data = (uint8_t *)(phdr + 1);
6624		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6625		data[4] = 0x02; /* per-pool */
6626		data += phdr->param_len;
6627	}
6628
6629	if (lun->backend->lun_attr != NULL &&
6630	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6631	     != UINT64_MAX) {
6632		phdr = (struct scsi_log_param_header *)data;
6633		scsi_ulto2b(0x00f2, phdr->param_code);
6634		phdr->param_control = SLP_LBIN | SLP_LP;
6635		phdr->param_len = 8;
6636		data = (uint8_t *)(phdr + 1);
6637		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6638		data[4] = 0x02; /* per-pool */
6639		data += phdr->param_len;
6640	}
6641
6642	page_index->page_len = data - page_index->page_data;
6643	return (0);
6644}
6645
6646int
6647ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6648			       struct ctl_page_index *page_index,
6649			       int pc)
6650{
6651	struct ctl_lun *lun;
6652	struct stat_page *data;
6653	uint64_t rn, wn, rb, wb;
6654	struct bintime rt, wt;
6655	int i;
6656
6657	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6658	data = (struct stat_page *)page_index->page_data;
6659
6660	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6661	data->sap.hdr.param_control = SLP_LBIN;
6662	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6663	    sizeof(struct scsi_log_param_header);
6664	rn = wn = rb = wb = 0;
6665	bintime_clear(&rt);
6666	bintime_clear(&wt);
6667	for (i = 0; i < CTL_MAX_PORTS; i++) {
6668		rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6669		wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6670		rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6671		wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6672		bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6673		bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6674	}
6675	scsi_u64to8b(rn, data->sap.read_num);
6676	scsi_u64to8b(wn, data->sap.write_num);
6677	if (lun->stats.blocksize > 0) {
6678		scsi_u64to8b(wb / lun->stats.blocksize,
6679		    data->sap.recvieved_lba);
6680		scsi_u64to8b(rb / lun->stats.blocksize,
6681		    data->sap.transmitted_lba);
6682	}
6683	scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6684	    data->sap.read_int);
6685	scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6686	    data->sap.write_int);
6687	scsi_u64to8b(0, data->sap.weighted_num);
6688	scsi_u64to8b(0, data->sap.weighted_int);
6689	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6690	data->it.hdr.param_control = SLP_LBIN;
6691	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6692	    sizeof(struct scsi_log_param_header);
6693#ifdef CTL_TIME_IO
6694	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6695#endif
6696	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6697	data->it.hdr.param_control = SLP_LBIN;
6698	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6699	    sizeof(struct scsi_log_param_header);
6700	scsi_ulto4b(3, data->ti.exponent);
6701	scsi_ulto4b(1, data->ti.integer);
6702
6703	page_index->page_len = sizeof(*data);
6704	return (0);
6705}
6706
6707int
6708ctl_log_sense(struct ctl_scsiio *ctsio)
6709{
6710	struct ctl_lun *lun;
6711	int i, pc, page_code, subpage;
6712	int alloc_len, total_len;
6713	struct ctl_page_index *page_index;
6714	struct scsi_log_sense *cdb;
6715	struct scsi_log_header *header;
6716
6717	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6718
6719	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6720	cdb = (struct scsi_log_sense *)ctsio->cdb;
6721	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6722	page_code = cdb->page & SLS_PAGE_CODE;
6723	subpage = cdb->subpage;
6724	alloc_len = scsi_2btoul(cdb->length);
6725
6726	page_index = NULL;
6727	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6728		page_index = &lun->log_pages.index[i];
6729
6730		/* Look for the right page code */
6731		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6732			continue;
6733
6734		/* Look for the right subpage or the subpage wildcard*/
6735		if (page_index->subpage != subpage)
6736			continue;
6737
6738		break;
6739	}
6740	if (i >= CTL_NUM_LOG_PAGES) {
6741		ctl_set_invalid_field(ctsio,
6742				      /*sks_valid*/ 1,
6743				      /*command*/ 1,
6744				      /*field*/ 2,
6745				      /*bit_valid*/ 0,
6746				      /*bit*/ 0);
6747		ctl_done((union ctl_io *)ctsio);
6748		return (CTL_RETVAL_COMPLETE);
6749	}
6750
6751	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6752
6753	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6754	ctsio->kern_sg_entries = 0;
6755	ctsio->kern_data_resid = 0;
6756	ctsio->kern_rel_offset = 0;
6757	if (total_len < alloc_len) {
6758		ctsio->residual = alloc_len - total_len;
6759		ctsio->kern_data_len = total_len;
6760		ctsio->kern_total_len = total_len;
6761	} else {
6762		ctsio->residual = 0;
6763		ctsio->kern_data_len = alloc_len;
6764		ctsio->kern_total_len = alloc_len;
6765	}
6766
6767	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6768	header->page = page_index->page_code;
6769	if (page_index->subpage) {
6770		header->page |= SL_SPF;
6771		header->subpage = page_index->subpage;
6772	}
6773	scsi_ulto2b(page_index->page_len, header->datalen);
6774
6775	/*
6776	 * Call the handler, if it exists, to update the
6777	 * page to the latest values.
6778	 */
6779	if (page_index->sense_handler != NULL)
6780		page_index->sense_handler(ctsio, page_index, pc);
6781
6782	memcpy(header + 1, page_index->page_data, page_index->page_len);
6783
6784	ctl_set_success(ctsio);
6785	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6786	ctsio->be_move_done = ctl_config_move_done;
6787	ctl_datamove((union ctl_io *)ctsio);
6788	return (CTL_RETVAL_COMPLETE);
6789}
6790
6791int
6792ctl_read_capacity(struct ctl_scsiio *ctsio)
6793{
6794	struct scsi_read_capacity *cdb;
6795	struct scsi_read_capacity_data *data;
6796	struct ctl_lun *lun;
6797	uint32_t lba;
6798
6799	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6800
6801	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6802
6803	lba = scsi_4btoul(cdb->addr);
6804	if (((cdb->pmi & SRC_PMI) == 0)
6805	 && (lba != 0)) {
6806		ctl_set_invalid_field(/*ctsio*/ ctsio,
6807				      /*sks_valid*/ 1,
6808				      /*command*/ 1,
6809				      /*field*/ 2,
6810				      /*bit_valid*/ 0,
6811				      /*bit*/ 0);
6812		ctl_done((union ctl_io *)ctsio);
6813		return (CTL_RETVAL_COMPLETE);
6814	}
6815
6816	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6817
6818	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6819	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6820	ctsio->residual = 0;
6821	ctsio->kern_data_len = sizeof(*data);
6822	ctsio->kern_total_len = sizeof(*data);
6823	ctsio->kern_data_resid = 0;
6824	ctsio->kern_rel_offset = 0;
6825	ctsio->kern_sg_entries = 0;
6826
6827	/*
6828	 * If the maximum LBA is greater than 0xfffffffe, the user must
6829	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6830	 * serivce action set.
6831	 */
6832	if (lun->be_lun->maxlba > 0xfffffffe)
6833		scsi_ulto4b(0xffffffff, data->addr);
6834	else
6835		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6836
6837	/*
6838	 * XXX KDM this may not be 512 bytes...
6839	 */
6840	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6841
6842	ctl_set_success(ctsio);
6843	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6844	ctsio->be_move_done = ctl_config_move_done;
6845	ctl_datamove((union ctl_io *)ctsio);
6846	return (CTL_RETVAL_COMPLETE);
6847}
6848
6849int
6850ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6851{
6852	struct scsi_read_capacity_16 *cdb;
6853	struct scsi_read_capacity_data_long *data;
6854	struct ctl_lun *lun;
6855	uint64_t lba;
6856	uint32_t alloc_len;
6857
6858	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6859
6860	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6861
6862	alloc_len = scsi_4btoul(cdb->alloc_len);
6863	lba = scsi_8btou64(cdb->addr);
6864
6865	if ((cdb->reladr & SRC16_PMI)
6866	 && (lba != 0)) {
6867		ctl_set_invalid_field(/*ctsio*/ ctsio,
6868				      /*sks_valid*/ 1,
6869				      /*command*/ 1,
6870				      /*field*/ 2,
6871				      /*bit_valid*/ 0,
6872				      /*bit*/ 0);
6873		ctl_done((union ctl_io *)ctsio);
6874		return (CTL_RETVAL_COMPLETE);
6875	}
6876
6877	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6878
6879	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6880	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6881
6882	if (sizeof(*data) < alloc_len) {
6883		ctsio->residual = alloc_len - sizeof(*data);
6884		ctsio->kern_data_len = sizeof(*data);
6885		ctsio->kern_total_len = sizeof(*data);
6886	} else {
6887		ctsio->residual = 0;
6888		ctsio->kern_data_len = alloc_len;
6889		ctsio->kern_total_len = alloc_len;
6890	}
6891	ctsio->kern_data_resid = 0;
6892	ctsio->kern_rel_offset = 0;
6893	ctsio->kern_sg_entries = 0;
6894
6895	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6896	/* XXX KDM this may not be 512 bytes... */
6897	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6898	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6899	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
6900	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
6901		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
6902
6903	ctl_set_success(ctsio);
6904	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6905	ctsio->be_move_done = ctl_config_move_done;
6906	ctl_datamove((union ctl_io *)ctsio);
6907	return (CTL_RETVAL_COMPLETE);
6908}
6909
6910int
6911ctl_get_lba_status(struct ctl_scsiio *ctsio)
6912{
6913	struct scsi_get_lba_status *cdb;
6914	struct scsi_get_lba_status_data *data;
6915	struct ctl_lun *lun;
6916	struct ctl_lba_len_flags *lbalen;
6917	uint64_t lba;
6918	uint32_t alloc_len, total_len;
6919	int retval;
6920
6921	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
6922
6923	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6924	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
6925	lba = scsi_8btou64(cdb->addr);
6926	alloc_len = scsi_4btoul(cdb->alloc_len);
6927
6928	if (lba > lun->be_lun->maxlba) {
6929		ctl_set_lba_out_of_range(ctsio);
6930		ctl_done((union ctl_io *)ctsio);
6931		return (CTL_RETVAL_COMPLETE);
6932	}
6933
6934	total_len = sizeof(*data) + sizeof(data->descr[0]);
6935	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6936	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
6937
6938	if (total_len < alloc_len) {
6939		ctsio->residual = alloc_len - total_len;
6940		ctsio->kern_data_len = total_len;
6941		ctsio->kern_total_len = total_len;
6942	} else {
6943		ctsio->residual = 0;
6944		ctsio->kern_data_len = alloc_len;
6945		ctsio->kern_total_len = alloc_len;
6946	}
6947	ctsio->kern_data_resid = 0;
6948	ctsio->kern_rel_offset = 0;
6949	ctsio->kern_sg_entries = 0;
6950
6951	/* Fill dummy data in case backend can't tell anything. */
6952	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
6953	scsi_u64to8b(lba, data->descr[0].addr);
6954	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
6955	    data->descr[0].length);
6956	data->descr[0].status = 0; /* Mapped or unknown. */
6957
6958	ctl_set_success(ctsio);
6959	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6960	ctsio->be_move_done = ctl_config_move_done;
6961
6962	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6963	lbalen->lba = lba;
6964	lbalen->len = total_len;
6965	lbalen->flags = 0;
6966	retval = lun->backend->config_read((union ctl_io *)ctsio);
6967	return (CTL_RETVAL_COMPLETE);
6968}
6969
6970int
6971ctl_read_defect(struct ctl_scsiio *ctsio)
6972{
6973	struct scsi_read_defect_data_10 *ccb10;
6974	struct scsi_read_defect_data_12 *ccb12;
6975	struct scsi_read_defect_data_hdr_10 *data10;
6976	struct scsi_read_defect_data_hdr_12 *data12;
6977	uint32_t alloc_len, data_len;
6978	uint8_t format;
6979
6980	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
6981
6982	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
6983		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
6984		format = ccb10->format;
6985		alloc_len = scsi_2btoul(ccb10->alloc_length);
6986		data_len = sizeof(*data10);
6987	} else {
6988		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
6989		format = ccb12->format;
6990		alloc_len = scsi_4btoul(ccb12->alloc_length);
6991		data_len = sizeof(*data12);
6992	}
6993	if (alloc_len == 0) {
6994		ctl_set_success(ctsio);
6995		ctl_done((union ctl_io *)ctsio);
6996		return (CTL_RETVAL_COMPLETE);
6997	}
6998
6999	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7000	if (data_len < alloc_len) {
7001		ctsio->residual = alloc_len - data_len;
7002		ctsio->kern_data_len = data_len;
7003		ctsio->kern_total_len = data_len;
7004	} else {
7005		ctsio->residual = 0;
7006		ctsio->kern_data_len = alloc_len;
7007		ctsio->kern_total_len = alloc_len;
7008	}
7009	ctsio->kern_data_resid = 0;
7010	ctsio->kern_rel_offset = 0;
7011	ctsio->kern_sg_entries = 0;
7012
7013	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7014		data10 = (struct scsi_read_defect_data_hdr_10 *)
7015		    ctsio->kern_data_ptr;
7016		data10->format = format;
7017		scsi_ulto2b(0, data10->length);
7018	} else {
7019		data12 = (struct scsi_read_defect_data_hdr_12 *)
7020		    ctsio->kern_data_ptr;
7021		data12->format = format;
7022		scsi_ulto2b(0, data12->generation);
7023		scsi_ulto4b(0, data12->length);
7024	}
7025
7026	ctl_set_success(ctsio);
7027	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7028	ctsio->be_move_done = ctl_config_move_done;
7029	ctl_datamove((union ctl_io *)ctsio);
7030	return (CTL_RETVAL_COMPLETE);
7031}
7032
7033int
7034ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7035{
7036	struct scsi_maintenance_in *cdb;
7037	int retval;
7038	int alloc_len, ext, total_len = 0, g, pc, pg, gs, os;
7039	int num_target_port_groups, num_target_ports;
7040	struct ctl_lun *lun;
7041	struct ctl_softc *softc;
7042	struct ctl_port *port;
7043	struct scsi_target_group_data *rtg_ptr;
7044	struct scsi_target_group_data_extended *rtg_ext_ptr;
7045	struct scsi_target_port_group_descriptor *tpg_desc;
7046
7047	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7048
7049	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7050	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7051	softc = lun->ctl_softc;
7052
7053	retval = CTL_RETVAL_COMPLETE;
7054
7055	switch (cdb->byte2 & STG_PDF_MASK) {
7056	case STG_PDF_LENGTH:
7057		ext = 0;
7058		break;
7059	case STG_PDF_EXTENDED:
7060		ext = 1;
7061		break;
7062	default:
7063		ctl_set_invalid_field(/*ctsio*/ ctsio,
7064				      /*sks_valid*/ 1,
7065				      /*command*/ 1,
7066				      /*field*/ 2,
7067				      /*bit_valid*/ 1,
7068				      /*bit*/ 5);
7069		ctl_done((union ctl_io *)ctsio);
7070		return(retval);
7071	}
7072
7073	if (softc->is_single)
7074		num_target_port_groups = 1;
7075	else
7076		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7077	num_target_ports = 0;
7078	mtx_lock(&softc->ctl_lock);
7079	STAILQ_FOREACH(port, &softc->port_list, links) {
7080		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7081			continue;
7082		if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7083			continue;
7084		num_target_ports++;
7085	}
7086	mtx_unlock(&softc->ctl_lock);
7087
7088	if (ext)
7089		total_len = sizeof(struct scsi_target_group_data_extended);
7090	else
7091		total_len = sizeof(struct scsi_target_group_data);
7092	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7093		num_target_port_groups +
7094	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7095
7096	alloc_len = scsi_4btoul(cdb->length);
7097
7098	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7099
7100	ctsio->kern_sg_entries = 0;
7101
7102	if (total_len < alloc_len) {
7103		ctsio->residual = alloc_len - total_len;
7104		ctsio->kern_data_len = total_len;
7105		ctsio->kern_total_len = total_len;
7106	} else {
7107		ctsio->residual = 0;
7108		ctsio->kern_data_len = alloc_len;
7109		ctsio->kern_total_len = alloc_len;
7110	}
7111	ctsio->kern_data_resid = 0;
7112	ctsio->kern_rel_offset = 0;
7113
7114	if (ext) {
7115		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7116		    ctsio->kern_data_ptr;
7117		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7118		rtg_ext_ptr->format_type = 0x10;
7119		rtg_ext_ptr->implicit_transition_time = 0;
7120		tpg_desc = &rtg_ext_ptr->groups[0];
7121	} else {
7122		rtg_ptr = (struct scsi_target_group_data *)
7123		    ctsio->kern_data_ptr;
7124		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7125		tpg_desc = &rtg_ptr->groups[0];
7126	}
7127
7128	mtx_lock(&softc->ctl_lock);
7129	pg = softc->port_min / softc->port_cnt;
7130	if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7131		gs = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7132	else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7133		gs = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7134	else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7135		gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7136	else
7137		gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7138	if (lun->flags & CTL_LUN_PRIMARY_SC) {
7139		os = gs;
7140		gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7141	} else
7142		os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7143	for (g = 0; g < num_target_port_groups; g++) {
7144		tpg_desc->pref_state = (g == pg) ? gs : os;
7145		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7146		    TPG_U_SUP | TPG_T_SUP;
7147		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7148		tpg_desc->status = TPG_IMPLICIT;
7149		pc = 0;
7150		STAILQ_FOREACH(port, &softc->port_list, links) {
7151			if (port->targ_port < g * softc->port_cnt ||
7152			    port->targ_port >= (g + 1) * softc->port_cnt)
7153				continue;
7154			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7155				continue;
7156			if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7157				continue;
7158			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7159			    relative_target_port_identifier);
7160			pc++;
7161		}
7162		tpg_desc->target_port_count = pc;
7163		tpg_desc = (struct scsi_target_port_group_descriptor *)
7164		    &tpg_desc->descriptors[pc];
7165	}
7166	mtx_unlock(&softc->ctl_lock);
7167
7168	ctl_set_success(ctsio);
7169	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7170	ctsio->be_move_done = ctl_config_move_done;
7171	ctl_datamove((union ctl_io *)ctsio);
7172	return(retval);
7173}
7174
7175int
7176ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7177{
7178	struct ctl_lun *lun;
7179	struct scsi_report_supported_opcodes *cdb;
7180	const struct ctl_cmd_entry *entry, *sentry;
7181	struct scsi_report_supported_opcodes_all *all;
7182	struct scsi_report_supported_opcodes_descr *descr;
7183	struct scsi_report_supported_opcodes_one *one;
7184	int retval;
7185	int alloc_len, total_len;
7186	int opcode, service_action, i, j, num;
7187
7188	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7189
7190	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7191	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7192
7193	retval = CTL_RETVAL_COMPLETE;
7194
7195	opcode = cdb->requested_opcode;
7196	service_action = scsi_2btoul(cdb->requested_service_action);
7197	switch (cdb->options & RSO_OPTIONS_MASK) {
7198	case RSO_OPTIONS_ALL:
7199		num = 0;
7200		for (i = 0; i < 256; i++) {
7201			entry = &ctl_cmd_table[i];
7202			if (entry->flags & CTL_CMD_FLAG_SA5) {
7203				for (j = 0; j < 32; j++) {
7204					sentry = &((const struct ctl_cmd_entry *)
7205					    entry->execute)[j];
7206					if (ctl_cmd_applicable(
7207					    lun->be_lun->lun_type, sentry))
7208						num++;
7209				}
7210			} else {
7211				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7212				    entry))
7213					num++;
7214			}
7215		}
7216		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7217		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7218		break;
7219	case RSO_OPTIONS_OC:
7220		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7221			ctl_set_invalid_field(/*ctsio*/ ctsio,
7222					      /*sks_valid*/ 1,
7223					      /*command*/ 1,
7224					      /*field*/ 2,
7225					      /*bit_valid*/ 1,
7226					      /*bit*/ 2);
7227			ctl_done((union ctl_io *)ctsio);
7228			return (CTL_RETVAL_COMPLETE);
7229		}
7230		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7231		break;
7232	case RSO_OPTIONS_OC_SA:
7233		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7234		    service_action >= 32) {
7235			ctl_set_invalid_field(/*ctsio*/ ctsio,
7236					      /*sks_valid*/ 1,
7237					      /*command*/ 1,
7238					      /*field*/ 2,
7239					      /*bit_valid*/ 1,
7240					      /*bit*/ 2);
7241			ctl_done((union ctl_io *)ctsio);
7242			return (CTL_RETVAL_COMPLETE);
7243		}
7244		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7245		break;
7246	default:
7247		ctl_set_invalid_field(/*ctsio*/ ctsio,
7248				      /*sks_valid*/ 1,
7249				      /*command*/ 1,
7250				      /*field*/ 2,
7251				      /*bit_valid*/ 1,
7252				      /*bit*/ 2);
7253		ctl_done((union ctl_io *)ctsio);
7254		return (CTL_RETVAL_COMPLETE);
7255	}
7256
7257	alloc_len = scsi_4btoul(cdb->length);
7258
7259	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7260
7261	ctsio->kern_sg_entries = 0;
7262
7263	if (total_len < alloc_len) {
7264		ctsio->residual = alloc_len - total_len;
7265		ctsio->kern_data_len = total_len;
7266		ctsio->kern_total_len = total_len;
7267	} else {
7268		ctsio->residual = 0;
7269		ctsio->kern_data_len = alloc_len;
7270		ctsio->kern_total_len = alloc_len;
7271	}
7272	ctsio->kern_data_resid = 0;
7273	ctsio->kern_rel_offset = 0;
7274
7275	switch (cdb->options & RSO_OPTIONS_MASK) {
7276	case RSO_OPTIONS_ALL:
7277		all = (struct scsi_report_supported_opcodes_all *)
7278		    ctsio->kern_data_ptr;
7279		num = 0;
7280		for (i = 0; i < 256; i++) {
7281			entry = &ctl_cmd_table[i];
7282			if (entry->flags & CTL_CMD_FLAG_SA5) {
7283				for (j = 0; j < 32; j++) {
7284					sentry = &((const struct ctl_cmd_entry *)
7285					    entry->execute)[j];
7286					if (!ctl_cmd_applicable(
7287					    lun->be_lun->lun_type, sentry))
7288						continue;
7289					descr = &all->descr[num++];
7290					descr->opcode = i;
7291					scsi_ulto2b(j, descr->service_action);
7292					descr->flags = RSO_SERVACTV;
7293					scsi_ulto2b(sentry->length,
7294					    descr->cdb_length);
7295				}
7296			} else {
7297				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7298				    entry))
7299					continue;
7300				descr = &all->descr[num++];
7301				descr->opcode = i;
7302				scsi_ulto2b(0, descr->service_action);
7303				descr->flags = 0;
7304				scsi_ulto2b(entry->length, descr->cdb_length);
7305			}
7306		}
7307		scsi_ulto4b(
7308		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7309		    all->length);
7310		break;
7311	case RSO_OPTIONS_OC:
7312		one = (struct scsi_report_supported_opcodes_one *)
7313		    ctsio->kern_data_ptr;
7314		entry = &ctl_cmd_table[opcode];
7315		goto fill_one;
7316	case RSO_OPTIONS_OC_SA:
7317		one = (struct scsi_report_supported_opcodes_one *)
7318		    ctsio->kern_data_ptr;
7319		entry = &ctl_cmd_table[opcode];
7320		entry = &((const struct ctl_cmd_entry *)
7321		    entry->execute)[service_action];
7322fill_one:
7323		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7324			one->support = 3;
7325			scsi_ulto2b(entry->length, one->cdb_length);
7326			one->cdb_usage[0] = opcode;
7327			memcpy(&one->cdb_usage[1], entry->usage,
7328			    entry->length - 1);
7329		} else
7330			one->support = 1;
7331		break;
7332	}
7333
7334	ctl_set_success(ctsio);
7335	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7336	ctsio->be_move_done = ctl_config_move_done;
7337	ctl_datamove((union ctl_io *)ctsio);
7338	return(retval);
7339}
7340
7341int
7342ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7343{
7344	struct scsi_report_supported_tmf *cdb;
7345	struct scsi_report_supported_tmf_data *data;
7346	int retval;
7347	int alloc_len, total_len;
7348
7349	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7350
7351	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7352
7353	retval = CTL_RETVAL_COMPLETE;
7354
7355	total_len = sizeof(struct scsi_report_supported_tmf_data);
7356	alloc_len = scsi_4btoul(cdb->length);
7357
7358	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7359
7360	ctsio->kern_sg_entries = 0;
7361
7362	if (total_len < alloc_len) {
7363		ctsio->residual = alloc_len - total_len;
7364		ctsio->kern_data_len = total_len;
7365		ctsio->kern_total_len = total_len;
7366	} else {
7367		ctsio->residual = 0;
7368		ctsio->kern_data_len = alloc_len;
7369		ctsio->kern_total_len = alloc_len;
7370	}
7371	ctsio->kern_data_resid = 0;
7372	ctsio->kern_rel_offset = 0;
7373
7374	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7375	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7376	    RST_TRS;
7377	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7378
7379	ctl_set_success(ctsio);
7380	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7381	ctsio->be_move_done = ctl_config_move_done;
7382	ctl_datamove((union ctl_io *)ctsio);
7383	return (retval);
7384}
7385
7386int
7387ctl_report_timestamp(struct ctl_scsiio *ctsio)
7388{
7389	struct scsi_report_timestamp *cdb;
7390	struct scsi_report_timestamp_data *data;
7391	struct timeval tv;
7392	int64_t timestamp;
7393	int retval;
7394	int alloc_len, total_len;
7395
7396	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7397
7398	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7399
7400	retval = CTL_RETVAL_COMPLETE;
7401
7402	total_len = sizeof(struct scsi_report_timestamp_data);
7403	alloc_len = scsi_4btoul(cdb->length);
7404
7405	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7406
7407	ctsio->kern_sg_entries = 0;
7408
7409	if (total_len < alloc_len) {
7410		ctsio->residual = alloc_len - total_len;
7411		ctsio->kern_data_len = total_len;
7412		ctsio->kern_total_len = total_len;
7413	} else {
7414		ctsio->residual = 0;
7415		ctsio->kern_data_len = alloc_len;
7416		ctsio->kern_total_len = alloc_len;
7417	}
7418	ctsio->kern_data_resid = 0;
7419	ctsio->kern_rel_offset = 0;
7420
7421	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7422	scsi_ulto2b(sizeof(*data) - 2, data->length);
7423	data->origin = RTS_ORIG_OUTSIDE;
7424	getmicrotime(&tv);
7425	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7426	scsi_ulto4b(timestamp >> 16, data->timestamp);
7427	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7428
7429	ctl_set_success(ctsio);
7430	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7431	ctsio->be_move_done = ctl_config_move_done;
7432	ctl_datamove((union ctl_io *)ctsio);
7433	return (retval);
7434}
7435
7436int
7437ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7438{
7439	struct scsi_per_res_in *cdb;
7440	int alloc_len, total_len = 0;
7441	/* struct scsi_per_res_in_rsrv in_data; */
7442	struct ctl_lun *lun;
7443	struct ctl_softc *softc;
7444	uint64_t key;
7445
7446	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7447
7448	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7449
7450	alloc_len = scsi_2btoul(cdb->length);
7451
7452	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7453	softc = lun->ctl_softc;
7454
7455retry:
7456	mtx_lock(&lun->lun_lock);
7457	switch (cdb->action) {
7458	case SPRI_RK: /* read keys */
7459		total_len = sizeof(struct scsi_per_res_in_keys) +
7460			lun->pr_key_count *
7461			sizeof(struct scsi_per_res_key);
7462		break;
7463	case SPRI_RR: /* read reservation */
7464		if (lun->flags & CTL_LUN_PR_RESERVED)
7465			total_len = sizeof(struct scsi_per_res_in_rsrv);
7466		else
7467			total_len = sizeof(struct scsi_per_res_in_header);
7468		break;
7469	case SPRI_RC: /* report capabilities */
7470		total_len = sizeof(struct scsi_per_res_cap);
7471		break;
7472	case SPRI_RS: /* read full status */
7473		total_len = sizeof(struct scsi_per_res_in_header) +
7474		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7475		    lun->pr_key_count;
7476		break;
7477	default:
7478		panic("Invalid PR type %x", cdb->action);
7479	}
7480	mtx_unlock(&lun->lun_lock);
7481
7482	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7483
7484	if (total_len < alloc_len) {
7485		ctsio->residual = alloc_len - total_len;
7486		ctsio->kern_data_len = total_len;
7487		ctsio->kern_total_len = total_len;
7488	} else {
7489		ctsio->residual = 0;
7490		ctsio->kern_data_len = alloc_len;
7491		ctsio->kern_total_len = alloc_len;
7492	}
7493
7494	ctsio->kern_data_resid = 0;
7495	ctsio->kern_rel_offset = 0;
7496	ctsio->kern_sg_entries = 0;
7497
7498	mtx_lock(&lun->lun_lock);
7499	switch (cdb->action) {
7500	case SPRI_RK: { // read keys
7501        struct scsi_per_res_in_keys *res_keys;
7502		int i, key_count;
7503
7504		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7505
7506		/*
7507		 * We had to drop the lock to allocate our buffer, which
7508		 * leaves time for someone to come in with another
7509		 * persistent reservation.  (That is unlikely, though,
7510		 * since this should be the only persistent reservation
7511		 * command active right now.)
7512		 */
7513		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7514		    (lun->pr_key_count *
7515		     sizeof(struct scsi_per_res_key)))){
7516			mtx_unlock(&lun->lun_lock);
7517			free(ctsio->kern_data_ptr, M_CTL);
7518			printf("%s: reservation length changed, retrying\n",
7519			       __func__);
7520			goto retry;
7521		}
7522
7523		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7524
7525		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7526			     lun->pr_key_count, res_keys->header.length);
7527
7528		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7529			if ((key = ctl_get_prkey(lun, i)) == 0)
7530				continue;
7531
7532			/*
7533			 * We used lun->pr_key_count to calculate the
7534			 * size to allocate.  If it turns out the number of
7535			 * initiators with the registered flag set is
7536			 * larger than that (i.e. they haven't been kept in
7537			 * sync), we've got a problem.
7538			 */
7539			if (key_count >= lun->pr_key_count) {
7540				key_count++;
7541				continue;
7542			}
7543			scsi_u64to8b(key, res_keys->keys[key_count].key);
7544			key_count++;
7545		}
7546		break;
7547	}
7548	case SPRI_RR: { // read reservation
7549		struct scsi_per_res_in_rsrv *res;
7550		int tmp_len, header_only;
7551
7552		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7553
7554		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7555
7556		if (lun->flags & CTL_LUN_PR_RESERVED)
7557		{
7558			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7559			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7560				    res->header.length);
7561			header_only = 0;
7562		} else {
7563			tmp_len = sizeof(struct scsi_per_res_in_header);
7564			scsi_ulto4b(0, res->header.length);
7565			header_only = 1;
7566		}
7567
7568		/*
7569		 * We had to drop the lock to allocate our buffer, which
7570		 * leaves time for someone to come in with another
7571		 * persistent reservation.  (That is unlikely, though,
7572		 * since this should be the only persistent reservation
7573		 * command active right now.)
7574		 */
7575		if (tmp_len != total_len) {
7576			mtx_unlock(&lun->lun_lock);
7577			free(ctsio->kern_data_ptr, M_CTL);
7578			printf("%s: reservation status changed, retrying\n",
7579			       __func__);
7580			goto retry;
7581		}
7582
7583		/*
7584		 * No reservation held, so we're done.
7585		 */
7586		if (header_only != 0)
7587			break;
7588
7589		/*
7590		 * If the registration is an All Registrants type, the key
7591		 * is 0, since it doesn't really matter.
7592		 */
7593		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7594			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7595			    res->data.reservation);
7596		}
7597		res->data.scopetype = lun->res_type;
7598		break;
7599	}
7600	case SPRI_RC:     //report capabilities
7601	{
7602		struct scsi_per_res_cap *res_cap;
7603		uint16_t type_mask;
7604
7605		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7606		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7607		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7608		type_mask = SPRI_TM_WR_EX_AR |
7609			    SPRI_TM_EX_AC_RO |
7610			    SPRI_TM_WR_EX_RO |
7611			    SPRI_TM_EX_AC |
7612			    SPRI_TM_WR_EX |
7613			    SPRI_TM_EX_AC_AR;
7614		scsi_ulto2b(type_mask, res_cap->type_mask);
7615		break;
7616	}
7617	case SPRI_RS: { // read full status
7618		struct scsi_per_res_in_full *res_status;
7619		struct scsi_per_res_in_full_desc *res_desc;
7620		struct ctl_port *port;
7621		int i, len;
7622
7623		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7624
7625		/*
7626		 * We had to drop the lock to allocate our buffer, which
7627		 * leaves time for someone to come in with another
7628		 * persistent reservation.  (That is unlikely, though,
7629		 * since this should be the only persistent reservation
7630		 * command active right now.)
7631		 */
7632		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7633		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7634		     lun->pr_key_count)){
7635			mtx_unlock(&lun->lun_lock);
7636			free(ctsio->kern_data_ptr, M_CTL);
7637			printf("%s: reservation length changed, retrying\n",
7638			       __func__);
7639			goto retry;
7640		}
7641
7642		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7643
7644		res_desc = &res_status->desc[0];
7645		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7646			if ((key = ctl_get_prkey(lun, i)) == 0)
7647				continue;
7648
7649			scsi_u64to8b(key, res_desc->res_key.key);
7650			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7651			    (lun->pr_res_idx == i ||
7652			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7653				res_desc->flags = SPRI_FULL_R_HOLDER;
7654				res_desc->scopetype = lun->res_type;
7655			}
7656			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7657			    res_desc->rel_trgt_port_id);
7658			len = 0;
7659			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7660			if (port != NULL)
7661				len = ctl_create_iid(port,
7662				    i % CTL_MAX_INIT_PER_PORT,
7663				    res_desc->transport_id);
7664			scsi_ulto4b(len, res_desc->additional_length);
7665			res_desc = (struct scsi_per_res_in_full_desc *)
7666			    &res_desc->transport_id[len];
7667		}
7668		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7669		    res_status->header.length);
7670		break;
7671	}
7672	default:
7673		/*
7674		 * This is a bug, because we just checked for this above,
7675		 * and should have returned an error.
7676		 */
7677		panic("Invalid PR type %x", cdb->action);
7678		break; /* NOTREACHED */
7679	}
7680	mtx_unlock(&lun->lun_lock);
7681
7682	ctl_set_success(ctsio);
7683	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7684	ctsio->be_move_done = ctl_config_move_done;
7685	ctl_datamove((union ctl_io *)ctsio);
7686	return (CTL_RETVAL_COMPLETE);
7687}
7688
7689/*
7690 * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7691 * it should return.
7692 */
7693static int
7694ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7695		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7696		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7697		struct scsi_per_res_out_parms* param)
7698{
7699	union ctl_ha_msg persis_io;
7700	int i;
7701
7702	mtx_lock(&lun->lun_lock);
7703	if (sa_res_key == 0) {
7704		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7705			/* validate scope and type */
7706			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7707			     SPR_LU_SCOPE) {
7708				mtx_unlock(&lun->lun_lock);
7709				ctl_set_invalid_field(/*ctsio*/ ctsio,
7710						      /*sks_valid*/ 1,
7711						      /*command*/ 1,
7712						      /*field*/ 2,
7713						      /*bit_valid*/ 1,
7714						      /*bit*/ 4);
7715				ctl_done((union ctl_io *)ctsio);
7716				return (1);
7717			}
7718
7719		        if (type>8 || type==2 || type==4 || type==0) {
7720				mtx_unlock(&lun->lun_lock);
7721				ctl_set_invalid_field(/*ctsio*/ ctsio,
7722       	           				      /*sks_valid*/ 1,
7723						      /*command*/ 1,
7724						      /*field*/ 2,
7725						      /*bit_valid*/ 1,
7726						      /*bit*/ 0);
7727				ctl_done((union ctl_io *)ctsio);
7728				return (1);
7729		        }
7730
7731			/*
7732			 * Unregister everybody else and build UA for
7733			 * them
7734			 */
7735			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7736				if (i == residx || ctl_get_prkey(lun, i) == 0)
7737					continue;
7738
7739				ctl_clr_prkey(lun, i);
7740				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7741			}
7742			lun->pr_key_count = 1;
7743			lun->res_type = type;
7744			if (lun->res_type != SPR_TYPE_WR_EX_AR
7745			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7746				lun->pr_res_idx = residx;
7747			lun->PRGeneration++;
7748			mtx_unlock(&lun->lun_lock);
7749
7750			/* send msg to other side */
7751			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7752			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7753			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7754			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7755			persis_io.pr.pr_info.res_type = type;
7756			memcpy(persis_io.pr.pr_info.sa_res_key,
7757			       param->serv_act_res_key,
7758			       sizeof(param->serv_act_res_key));
7759			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7760			    sizeof(persis_io.pr), M_WAITOK);
7761		} else {
7762			/* not all registrants */
7763			mtx_unlock(&lun->lun_lock);
7764			free(ctsio->kern_data_ptr, M_CTL);
7765			ctl_set_invalid_field(ctsio,
7766					      /*sks_valid*/ 1,
7767					      /*command*/ 0,
7768					      /*field*/ 8,
7769					      /*bit_valid*/ 0,
7770					      /*bit*/ 0);
7771			ctl_done((union ctl_io *)ctsio);
7772			return (1);
7773		}
7774	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7775		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7776		int found = 0;
7777
7778		if (res_key == sa_res_key) {
7779			/* special case */
7780			/*
7781			 * The spec implies this is not good but doesn't
7782			 * say what to do. There are two choices either
7783			 * generate a res conflict or check condition
7784			 * with illegal field in parameter data. Since
7785			 * that is what is done when the sa_res_key is
7786			 * zero I'll take that approach since this has
7787			 * to do with the sa_res_key.
7788			 */
7789			mtx_unlock(&lun->lun_lock);
7790			free(ctsio->kern_data_ptr, M_CTL);
7791			ctl_set_invalid_field(ctsio,
7792					      /*sks_valid*/ 1,
7793					      /*command*/ 0,
7794					      /*field*/ 8,
7795					      /*bit_valid*/ 0,
7796					      /*bit*/ 0);
7797			ctl_done((union ctl_io *)ctsio);
7798			return (1);
7799		}
7800
7801		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7802			if (ctl_get_prkey(lun, i) != sa_res_key)
7803				continue;
7804
7805			found = 1;
7806			ctl_clr_prkey(lun, i);
7807			lun->pr_key_count--;
7808			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7809		}
7810		if (!found) {
7811			mtx_unlock(&lun->lun_lock);
7812			free(ctsio->kern_data_ptr, M_CTL);
7813			ctl_set_reservation_conflict(ctsio);
7814			ctl_done((union ctl_io *)ctsio);
7815			return (CTL_RETVAL_COMPLETE);
7816		}
7817		lun->PRGeneration++;
7818		mtx_unlock(&lun->lun_lock);
7819
7820		/* send msg to other side */
7821		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7822		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7823		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7824		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7825		persis_io.pr.pr_info.res_type = type;
7826		memcpy(persis_io.pr.pr_info.sa_res_key,
7827		       param->serv_act_res_key,
7828		       sizeof(param->serv_act_res_key));
7829		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7830		    sizeof(persis_io.pr), M_WAITOK);
7831	} else {
7832		/* Reserved but not all registrants */
7833		/* sa_res_key is res holder */
7834		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7835			/* validate scope and type */
7836			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7837			     SPR_LU_SCOPE) {
7838				mtx_unlock(&lun->lun_lock);
7839				ctl_set_invalid_field(/*ctsio*/ ctsio,
7840						      /*sks_valid*/ 1,
7841						      /*command*/ 1,
7842						      /*field*/ 2,
7843						      /*bit_valid*/ 1,
7844						      /*bit*/ 4);
7845				ctl_done((union ctl_io *)ctsio);
7846				return (1);
7847			}
7848
7849			if (type>8 || type==2 || type==4 || type==0) {
7850				mtx_unlock(&lun->lun_lock);
7851				ctl_set_invalid_field(/*ctsio*/ ctsio,
7852						      /*sks_valid*/ 1,
7853						      /*command*/ 1,
7854						      /*field*/ 2,
7855						      /*bit_valid*/ 1,
7856						      /*bit*/ 0);
7857				ctl_done((union ctl_io *)ctsio);
7858				return (1);
7859			}
7860
7861			/*
7862			 * Do the following:
7863			 * if sa_res_key != res_key remove all
7864			 * registrants w/sa_res_key and generate UA
7865			 * for these registrants(Registrations
7866			 * Preempted) if it wasn't an exclusive
7867			 * reservation generate UA(Reservations
7868			 * Preempted) for all other registered nexuses
7869			 * if the type has changed. Establish the new
7870			 * reservation and holder. If res_key and
7871			 * sa_res_key are the same do the above
7872			 * except don't unregister the res holder.
7873			 */
7874
7875			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7876				if (i == residx || ctl_get_prkey(lun, i) == 0)
7877					continue;
7878
7879				if (sa_res_key == ctl_get_prkey(lun, i)) {
7880					ctl_clr_prkey(lun, i);
7881					lun->pr_key_count--;
7882					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7883				} else if (type != lun->res_type
7884					&& (lun->res_type == SPR_TYPE_WR_EX_RO
7885					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
7886					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
7887				}
7888			}
7889			lun->res_type = type;
7890			if (lun->res_type != SPR_TYPE_WR_EX_AR
7891			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7892				lun->pr_res_idx = residx;
7893			else
7894				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7895			lun->PRGeneration++;
7896			mtx_unlock(&lun->lun_lock);
7897
7898			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7899			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7900			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7901			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7902			persis_io.pr.pr_info.res_type = type;
7903			memcpy(persis_io.pr.pr_info.sa_res_key,
7904			       param->serv_act_res_key,
7905			       sizeof(param->serv_act_res_key));
7906			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7907			    sizeof(persis_io.pr), M_WAITOK);
7908		} else {
7909			/*
7910			 * sa_res_key is not the res holder just
7911			 * remove registrants
7912			 */
7913			int found=0;
7914
7915			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7916				if (sa_res_key != ctl_get_prkey(lun, i))
7917					continue;
7918
7919				found = 1;
7920				ctl_clr_prkey(lun, i);
7921				lun->pr_key_count--;
7922				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7923			}
7924
7925			if (!found) {
7926				mtx_unlock(&lun->lun_lock);
7927				free(ctsio->kern_data_ptr, M_CTL);
7928				ctl_set_reservation_conflict(ctsio);
7929				ctl_done((union ctl_io *)ctsio);
7930		        	return (1);
7931			}
7932			lun->PRGeneration++;
7933			mtx_unlock(&lun->lun_lock);
7934
7935			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7936			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7937			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7938			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7939			persis_io.pr.pr_info.res_type = type;
7940			memcpy(persis_io.pr.pr_info.sa_res_key,
7941			       param->serv_act_res_key,
7942			       sizeof(param->serv_act_res_key));
7943			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7944			    sizeof(persis_io.pr), M_WAITOK);
7945		}
7946	}
7947	return (0);
7948}
7949
7950static void
7951ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
7952{
7953	uint64_t sa_res_key;
7954	int i;
7955
7956	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
7957
7958	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7959	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
7960	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
7961		if (sa_res_key == 0) {
7962			/*
7963			 * Unregister everybody else and build UA for
7964			 * them
7965			 */
7966			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7967				if (i == msg->pr.pr_info.residx ||
7968				    ctl_get_prkey(lun, i) == 0)
7969					continue;
7970
7971				ctl_clr_prkey(lun, i);
7972				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7973			}
7974
7975			lun->pr_key_count = 1;
7976			lun->res_type = msg->pr.pr_info.res_type;
7977			if (lun->res_type != SPR_TYPE_WR_EX_AR
7978			 && lun->res_type != SPR_TYPE_EX_AC_AR)
7979				lun->pr_res_idx = msg->pr.pr_info.residx;
7980		} else {
7981		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7982				if (sa_res_key == ctl_get_prkey(lun, i))
7983					continue;
7984
7985				ctl_clr_prkey(lun, i);
7986				lun->pr_key_count--;
7987				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7988			}
7989		}
7990	} else {
7991		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7992			if (i == msg->pr.pr_info.residx ||
7993			    ctl_get_prkey(lun, i) == 0)
7994				continue;
7995
7996			if (sa_res_key == ctl_get_prkey(lun, i)) {
7997				ctl_clr_prkey(lun, i);
7998				lun->pr_key_count--;
7999				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8000			} else if (msg->pr.pr_info.res_type != lun->res_type
8001				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8002				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8003				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8004			}
8005		}
8006		lun->res_type = msg->pr.pr_info.res_type;
8007		if (lun->res_type != SPR_TYPE_WR_EX_AR
8008		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8009			lun->pr_res_idx = msg->pr.pr_info.residx;
8010		else
8011			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8012	}
8013	lun->PRGeneration++;
8014
8015}
8016
8017
8018int
8019ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8020{
8021	int retval;
8022	u_int32_t param_len;
8023	struct scsi_per_res_out *cdb;
8024	struct ctl_lun *lun;
8025	struct scsi_per_res_out_parms* param;
8026	struct ctl_softc *softc;
8027	uint32_t residx;
8028	uint64_t res_key, sa_res_key, key;
8029	uint8_t type;
8030	union ctl_ha_msg persis_io;
8031	int    i;
8032
8033	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8034
8035	retval = CTL_RETVAL_COMPLETE;
8036
8037	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8038	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8039	softc = lun->ctl_softc;
8040
8041	/*
8042	 * We only support whole-LUN scope.  The scope & type are ignored for
8043	 * register, register and ignore existing key and clear.
8044	 * We sometimes ignore scope and type on preempts too!!
8045	 * Verify reservation type here as well.
8046	 */
8047	type = cdb->scope_type & SPR_TYPE_MASK;
8048	if ((cdb->action == SPRO_RESERVE)
8049	 || (cdb->action == SPRO_RELEASE)) {
8050		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8051			ctl_set_invalid_field(/*ctsio*/ ctsio,
8052					      /*sks_valid*/ 1,
8053					      /*command*/ 1,
8054					      /*field*/ 2,
8055					      /*bit_valid*/ 1,
8056					      /*bit*/ 4);
8057			ctl_done((union ctl_io *)ctsio);
8058			return (CTL_RETVAL_COMPLETE);
8059		}
8060
8061		if (type>8 || type==2 || type==4 || type==0) {
8062			ctl_set_invalid_field(/*ctsio*/ ctsio,
8063					      /*sks_valid*/ 1,
8064					      /*command*/ 1,
8065					      /*field*/ 2,
8066					      /*bit_valid*/ 1,
8067					      /*bit*/ 0);
8068			ctl_done((union ctl_io *)ctsio);
8069			return (CTL_RETVAL_COMPLETE);
8070		}
8071	}
8072
8073	param_len = scsi_4btoul(cdb->length);
8074
8075	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8076		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8077		ctsio->kern_data_len = param_len;
8078		ctsio->kern_total_len = param_len;
8079		ctsio->kern_data_resid = 0;
8080		ctsio->kern_rel_offset = 0;
8081		ctsio->kern_sg_entries = 0;
8082		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8083		ctsio->be_move_done = ctl_config_move_done;
8084		ctl_datamove((union ctl_io *)ctsio);
8085
8086		return (CTL_RETVAL_COMPLETE);
8087	}
8088
8089	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8090
8091	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8092	res_key = scsi_8btou64(param->res_key.key);
8093	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8094
8095	/*
8096	 * Validate the reservation key here except for SPRO_REG_IGNO
8097	 * This must be done for all other service actions
8098	 */
8099	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8100		mtx_lock(&lun->lun_lock);
8101		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8102			if (res_key != key) {
8103				/*
8104				 * The current key passed in doesn't match
8105				 * the one the initiator previously
8106				 * registered.
8107				 */
8108				mtx_unlock(&lun->lun_lock);
8109				free(ctsio->kern_data_ptr, M_CTL);
8110				ctl_set_reservation_conflict(ctsio);
8111				ctl_done((union ctl_io *)ctsio);
8112				return (CTL_RETVAL_COMPLETE);
8113			}
8114		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8115			/*
8116			 * We are not registered
8117			 */
8118			mtx_unlock(&lun->lun_lock);
8119			free(ctsio->kern_data_ptr, M_CTL);
8120			ctl_set_reservation_conflict(ctsio);
8121			ctl_done((union ctl_io *)ctsio);
8122			return (CTL_RETVAL_COMPLETE);
8123		} else if (res_key != 0) {
8124			/*
8125			 * We are not registered and trying to register but
8126			 * the register key isn't zero.
8127			 */
8128			mtx_unlock(&lun->lun_lock);
8129			free(ctsio->kern_data_ptr, M_CTL);
8130			ctl_set_reservation_conflict(ctsio);
8131			ctl_done((union ctl_io *)ctsio);
8132			return (CTL_RETVAL_COMPLETE);
8133		}
8134		mtx_unlock(&lun->lun_lock);
8135	}
8136
8137	switch (cdb->action & SPRO_ACTION_MASK) {
8138	case SPRO_REGISTER:
8139	case SPRO_REG_IGNO: {
8140
8141#if 0
8142		printf("Registration received\n");
8143#endif
8144
8145		/*
8146		 * We don't support any of these options, as we report in
8147		 * the read capabilities request (see
8148		 * ctl_persistent_reserve_in(), above).
8149		 */
8150		if ((param->flags & SPR_SPEC_I_PT)
8151		 || (param->flags & SPR_ALL_TG_PT)
8152		 || (param->flags & SPR_APTPL)) {
8153			int bit_ptr;
8154
8155			if (param->flags & SPR_APTPL)
8156				bit_ptr = 0;
8157			else if (param->flags & SPR_ALL_TG_PT)
8158				bit_ptr = 2;
8159			else /* SPR_SPEC_I_PT */
8160				bit_ptr = 3;
8161
8162			free(ctsio->kern_data_ptr, M_CTL);
8163			ctl_set_invalid_field(ctsio,
8164					      /*sks_valid*/ 1,
8165					      /*command*/ 0,
8166					      /*field*/ 20,
8167					      /*bit_valid*/ 1,
8168					      /*bit*/ bit_ptr);
8169			ctl_done((union ctl_io *)ctsio);
8170			return (CTL_RETVAL_COMPLETE);
8171		}
8172
8173		mtx_lock(&lun->lun_lock);
8174
8175		/*
8176		 * The initiator wants to clear the
8177		 * key/unregister.
8178		 */
8179		if (sa_res_key == 0) {
8180			if ((res_key == 0
8181			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8182			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8183			  && ctl_get_prkey(lun, residx) == 0)) {
8184				mtx_unlock(&lun->lun_lock);
8185				goto done;
8186			}
8187
8188			ctl_clr_prkey(lun, residx);
8189			lun->pr_key_count--;
8190
8191			if (residx == lun->pr_res_idx) {
8192				lun->flags &= ~CTL_LUN_PR_RESERVED;
8193				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8194
8195				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8196				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8197				 && lun->pr_key_count) {
8198					/*
8199					 * If the reservation is a registrants
8200					 * only type we need to generate a UA
8201					 * for other registered inits.  The
8202					 * sense code should be RESERVATIONS
8203					 * RELEASED
8204					 */
8205
8206					for (i = softc->init_min; i < softc->init_max; i++){
8207						if (ctl_get_prkey(lun, i) == 0)
8208							continue;
8209						ctl_est_ua(lun, i,
8210						    CTL_UA_RES_RELEASE);
8211					}
8212				}
8213				lun->res_type = 0;
8214			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8215				if (lun->pr_key_count==0) {
8216					lun->flags &= ~CTL_LUN_PR_RESERVED;
8217					lun->res_type = 0;
8218					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8219				}
8220			}
8221			lun->PRGeneration++;
8222			mtx_unlock(&lun->lun_lock);
8223
8224			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8225			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8226			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8227			persis_io.pr.pr_info.residx = residx;
8228			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8229			    sizeof(persis_io.pr), M_WAITOK);
8230		} else /* sa_res_key != 0 */ {
8231
8232			/*
8233			 * If we aren't registered currently then increment
8234			 * the key count and set the registered flag.
8235			 */
8236			ctl_alloc_prkey(lun, residx);
8237			if (ctl_get_prkey(lun, residx) == 0)
8238				lun->pr_key_count++;
8239			ctl_set_prkey(lun, residx, sa_res_key);
8240			lun->PRGeneration++;
8241			mtx_unlock(&lun->lun_lock);
8242
8243			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8244			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8245			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8246			persis_io.pr.pr_info.residx = residx;
8247			memcpy(persis_io.pr.pr_info.sa_res_key,
8248			       param->serv_act_res_key,
8249			       sizeof(param->serv_act_res_key));
8250			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8251			    sizeof(persis_io.pr), M_WAITOK);
8252		}
8253
8254		break;
8255	}
8256	case SPRO_RESERVE:
8257#if 0
8258                printf("Reserve executed type %d\n", type);
8259#endif
8260		mtx_lock(&lun->lun_lock);
8261		if (lun->flags & CTL_LUN_PR_RESERVED) {
8262			/*
8263			 * if this isn't the reservation holder and it's
8264			 * not a "all registrants" type or if the type is
8265			 * different then we have a conflict
8266			 */
8267			if ((lun->pr_res_idx != residx
8268			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8269			 || lun->res_type != type) {
8270				mtx_unlock(&lun->lun_lock);
8271				free(ctsio->kern_data_ptr, M_CTL);
8272				ctl_set_reservation_conflict(ctsio);
8273				ctl_done((union ctl_io *)ctsio);
8274				return (CTL_RETVAL_COMPLETE);
8275			}
8276			mtx_unlock(&lun->lun_lock);
8277		} else /* create a reservation */ {
8278			/*
8279			 * If it's not an "all registrants" type record
8280			 * reservation holder
8281			 */
8282			if (type != SPR_TYPE_WR_EX_AR
8283			 && type != SPR_TYPE_EX_AC_AR)
8284				lun->pr_res_idx = residx; /* Res holder */
8285			else
8286				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8287
8288			lun->flags |= CTL_LUN_PR_RESERVED;
8289			lun->res_type = type;
8290
8291			mtx_unlock(&lun->lun_lock);
8292
8293			/* send msg to other side */
8294			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8295			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8296			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8297			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8298			persis_io.pr.pr_info.res_type = type;
8299			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8300			    sizeof(persis_io.pr), M_WAITOK);
8301		}
8302		break;
8303
8304	case SPRO_RELEASE:
8305		mtx_lock(&lun->lun_lock);
8306		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8307			/* No reservation exists return good status */
8308			mtx_unlock(&lun->lun_lock);
8309			goto done;
8310		}
8311		/*
8312		 * Is this nexus a reservation holder?
8313		 */
8314		if (lun->pr_res_idx != residx
8315		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8316			/*
8317			 * not a res holder return good status but
8318			 * do nothing
8319			 */
8320			mtx_unlock(&lun->lun_lock);
8321			goto done;
8322		}
8323
8324		if (lun->res_type != type) {
8325			mtx_unlock(&lun->lun_lock);
8326			free(ctsio->kern_data_ptr, M_CTL);
8327			ctl_set_illegal_pr_release(ctsio);
8328			ctl_done((union ctl_io *)ctsio);
8329			return (CTL_RETVAL_COMPLETE);
8330		}
8331
8332		/* okay to release */
8333		lun->flags &= ~CTL_LUN_PR_RESERVED;
8334		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8335		lun->res_type = 0;
8336
8337		/*
8338		 * if this isn't an exclusive access
8339		 * res generate UA for all other
8340		 * registrants.
8341		 */
8342		if (type != SPR_TYPE_EX_AC
8343		 && type != SPR_TYPE_WR_EX) {
8344			for (i = softc->init_min; i < softc->init_max; i++) {
8345				if (i == residx || ctl_get_prkey(lun, i) == 0)
8346					continue;
8347				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8348			}
8349		}
8350		mtx_unlock(&lun->lun_lock);
8351
8352		/* Send msg to other side */
8353		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8354		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8355		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8356		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8357		     sizeof(persis_io.pr), M_WAITOK);
8358		break;
8359
8360	case SPRO_CLEAR:
8361		/* send msg to other side */
8362
8363		mtx_lock(&lun->lun_lock);
8364		lun->flags &= ~CTL_LUN_PR_RESERVED;
8365		lun->res_type = 0;
8366		lun->pr_key_count = 0;
8367		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8368
8369		ctl_clr_prkey(lun, residx);
8370		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8371			if (ctl_get_prkey(lun, i) != 0) {
8372				ctl_clr_prkey(lun, i);
8373				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8374			}
8375		lun->PRGeneration++;
8376		mtx_unlock(&lun->lun_lock);
8377
8378		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8379		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8380		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8381		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8382		     sizeof(persis_io.pr), M_WAITOK);
8383		break;
8384
8385	case SPRO_PREEMPT:
8386	case SPRO_PRE_ABO: {
8387		int nretval;
8388
8389		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8390					  residx, ctsio, cdb, param);
8391		if (nretval != 0)
8392			return (CTL_RETVAL_COMPLETE);
8393		break;
8394	}
8395	default:
8396		panic("Invalid PR type %x", cdb->action);
8397	}
8398
8399done:
8400	free(ctsio->kern_data_ptr, M_CTL);
8401	ctl_set_success(ctsio);
8402	ctl_done((union ctl_io *)ctsio);
8403
8404	return (retval);
8405}
8406
8407/*
8408 * This routine is for handling a message from the other SC pertaining to
8409 * persistent reserve out. All the error checking will have been done
8410 * so only perorming the action need be done here to keep the two
8411 * in sync.
8412 */
8413static void
8414ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8415{
8416	struct ctl_softc *softc = control_softc;
8417	struct ctl_lun *lun;
8418	int i;
8419	uint32_t residx, targ_lun;
8420
8421	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8422	mtx_lock(&softc->ctl_lock);
8423	if ((targ_lun >= CTL_MAX_LUNS) ||
8424	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
8425		mtx_unlock(&softc->ctl_lock);
8426		return;
8427	}
8428	mtx_lock(&lun->lun_lock);
8429	mtx_unlock(&softc->ctl_lock);
8430	if (lun->flags & CTL_LUN_DISABLED) {
8431		mtx_unlock(&lun->lun_lock);
8432		return;
8433	}
8434	residx = ctl_get_initindex(&msg->hdr.nexus);
8435	switch(msg->pr.pr_info.action) {
8436	case CTL_PR_REG_KEY:
8437		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8438		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8439			lun->pr_key_count++;
8440		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8441		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8442		lun->PRGeneration++;
8443		break;
8444
8445	case CTL_PR_UNREG_KEY:
8446		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8447		lun->pr_key_count--;
8448
8449		/* XXX Need to see if the reservation has been released */
8450		/* if so do we need to generate UA? */
8451		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8452			lun->flags &= ~CTL_LUN_PR_RESERVED;
8453			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8454
8455			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8456			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8457			 && lun->pr_key_count) {
8458				/*
8459				 * If the reservation is a registrants
8460				 * only type we need to generate a UA
8461				 * for other registered inits.  The
8462				 * sense code should be RESERVATIONS
8463				 * RELEASED
8464				 */
8465
8466				for (i = softc->init_min; i < softc->init_max; i++) {
8467					if (ctl_get_prkey(lun, i) == 0)
8468						continue;
8469
8470					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8471				}
8472			}
8473			lun->res_type = 0;
8474		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8475			if (lun->pr_key_count==0) {
8476				lun->flags &= ~CTL_LUN_PR_RESERVED;
8477				lun->res_type = 0;
8478				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8479			}
8480		}
8481		lun->PRGeneration++;
8482		break;
8483
8484	case CTL_PR_RESERVE:
8485		lun->flags |= CTL_LUN_PR_RESERVED;
8486		lun->res_type = msg->pr.pr_info.res_type;
8487		lun->pr_res_idx = msg->pr.pr_info.residx;
8488
8489		break;
8490
8491	case CTL_PR_RELEASE:
8492		/*
8493		 * if this isn't an exclusive access res generate UA for all
8494		 * other registrants.
8495		 */
8496		if (lun->res_type != SPR_TYPE_EX_AC
8497		 && lun->res_type != SPR_TYPE_WR_EX) {
8498			for (i = softc->init_min; i < softc->init_max; i++)
8499				if (i == residx || ctl_get_prkey(lun, i) == 0)
8500					continue;
8501				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8502		}
8503
8504		lun->flags &= ~CTL_LUN_PR_RESERVED;
8505		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8506		lun->res_type = 0;
8507		break;
8508
8509	case CTL_PR_PREEMPT:
8510		ctl_pro_preempt_other(lun, msg);
8511		break;
8512	case CTL_PR_CLEAR:
8513		lun->flags &= ~CTL_LUN_PR_RESERVED;
8514		lun->res_type = 0;
8515		lun->pr_key_count = 0;
8516		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8517
8518		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8519			if (ctl_get_prkey(lun, i) == 0)
8520				continue;
8521			ctl_clr_prkey(lun, i);
8522			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8523		}
8524		lun->PRGeneration++;
8525		break;
8526	}
8527
8528	mtx_unlock(&lun->lun_lock);
8529}
8530
8531int
8532ctl_read_write(struct ctl_scsiio *ctsio)
8533{
8534	struct ctl_lun *lun;
8535	struct ctl_lba_len_flags *lbalen;
8536	uint64_t lba;
8537	uint32_t num_blocks;
8538	int flags, retval;
8539	int isread;
8540
8541	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8542
8543	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8544
8545	flags = 0;
8546	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8547	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8548	switch (ctsio->cdb[0]) {
8549	case READ_6:
8550	case WRITE_6: {
8551		struct scsi_rw_6 *cdb;
8552
8553		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8554
8555		lba = scsi_3btoul(cdb->addr);
8556		/* only 5 bits are valid in the most significant address byte */
8557		lba &= 0x1fffff;
8558		num_blocks = cdb->length;
8559		/*
8560		 * This is correct according to SBC-2.
8561		 */
8562		if (num_blocks == 0)
8563			num_blocks = 256;
8564		break;
8565	}
8566	case READ_10:
8567	case WRITE_10: {
8568		struct scsi_rw_10 *cdb;
8569
8570		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8571		if (cdb->byte2 & SRW10_FUA)
8572			flags |= CTL_LLF_FUA;
8573		if (cdb->byte2 & SRW10_DPO)
8574			flags |= CTL_LLF_DPO;
8575		lba = scsi_4btoul(cdb->addr);
8576		num_blocks = scsi_2btoul(cdb->length);
8577		break;
8578	}
8579	case WRITE_VERIFY_10: {
8580		struct scsi_write_verify_10 *cdb;
8581
8582		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8583		flags |= CTL_LLF_FUA;
8584		if (cdb->byte2 & SWV_DPO)
8585			flags |= CTL_LLF_DPO;
8586		lba = scsi_4btoul(cdb->addr);
8587		num_blocks = scsi_2btoul(cdb->length);
8588		break;
8589	}
8590	case READ_12:
8591	case WRITE_12: {
8592		struct scsi_rw_12 *cdb;
8593
8594		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8595		if (cdb->byte2 & SRW12_FUA)
8596			flags |= CTL_LLF_FUA;
8597		if (cdb->byte2 & SRW12_DPO)
8598			flags |= CTL_LLF_DPO;
8599		lba = scsi_4btoul(cdb->addr);
8600		num_blocks = scsi_4btoul(cdb->length);
8601		break;
8602	}
8603	case WRITE_VERIFY_12: {
8604		struct scsi_write_verify_12 *cdb;
8605
8606		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8607		flags |= CTL_LLF_FUA;
8608		if (cdb->byte2 & SWV_DPO)
8609			flags |= CTL_LLF_DPO;
8610		lba = scsi_4btoul(cdb->addr);
8611		num_blocks = scsi_4btoul(cdb->length);
8612		break;
8613	}
8614	case READ_16:
8615	case WRITE_16: {
8616		struct scsi_rw_16 *cdb;
8617
8618		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8619		if (cdb->byte2 & SRW12_FUA)
8620			flags |= CTL_LLF_FUA;
8621		if (cdb->byte2 & SRW12_DPO)
8622			flags |= CTL_LLF_DPO;
8623		lba = scsi_8btou64(cdb->addr);
8624		num_blocks = scsi_4btoul(cdb->length);
8625		break;
8626	}
8627	case WRITE_ATOMIC_16: {
8628		struct scsi_write_atomic_16 *cdb;
8629
8630		if (lun->be_lun->atomicblock == 0) {
8631			ctl_set_invalid_opcode(ctsio);
8632			ctl_done((union ctl_io *)ctsio);
8633			return (CTL_RETVAL_COMPLETE);
8634		}
8635
8636		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8637		if (cdb->byte2 & SRW12_FUA)
8638			flags |= CTL_LLF_FUA;
8639		if (cdb->byte2 & SRW12_DPO)
8640			flags |= CTL_LLF_DPO;
8641		lba = scsi_8btou64(cdb->addr);
8642		num_blocks = scsi_2btoul(cdb->length);
8643		if (num_blocks > lun->be_lun->atomicblock) {
8644			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8645			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8646			    /*bit*/ 0);
8647			ctl_done((union ctl_io *)ctsio);
8648			return (CTL_RETVAL_COMPLETE);
8649		}
8650		break;
8651	}
8652	case WRITE_VERIFY_16: {
8653		struct scsi_write_verify_16 *cdb;
8654
8655		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8656		flags |= CTL_LLF_FUA;
8657		if (cdb->byte2 & SWV_DPO)
8658			flags |= CTL_LLF_DPO;
8659		lba = scsi_8btou64(cdb->addr);
8660		num_blocks = scsi_4btoul(cdb->length);
8661		break;
8662	}
8663	default:
8664		/*
8665		 * We got a command we don't support.  This shouldn't
8666		 * happen, commands should be filtered out above us.
8667		 */
8668		ctl_set_invalid_opcode(ctsio);
8669		ctl_done((union ctl_io *)ctsio);
8670
8671		return (CTL_RETVAL_COMPLETE);
8672		break; /* NOTREACHED */
8673	}
8674
8675	/*
8676	 * The first check is to make sure we're in bounds, the second
8677	 * check is to catch wrap-around problems.  If the lba + num blocks
8678	 * is less than the lba, then we've wrapped around and the block
8679	 * range is invalid anyway.
8680	 */
8681	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8682	 || ((lba + num_blocks) < lba)) {
8683		ctl_set_lba_out_of_range(ctsio);
8684		ctl_done((union ctl_io *)ctsio);
8685		return (CTL_RETVAL_COMPLETE);
8686	}
8687
8688	/*
8689	 * According to SBC-3, a transfer length of 0 is not an error.
8690	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8691	 * translates to 256 blocks for those commands.
8692	 */
8693	if (num_blocks == 0) {
8694		ctl_set_success(ctsio);
8695		ctl_done((union ctl_io *)ctsio);
8696		return (CTL_RETVAL_COMPLETE);
8697	}
8698
8699	/* Set FUA and/or DPO if caches are disabled. */
8700	if (isread) {
8701		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8702		    SCP_RCD) != 0)
8703			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8704	} else {
8705		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8706		    SCP_WCE) == 0)
8707			flags |= CTL_LLF_FUA;
8708	}
8709
8710	lbalen = (struct ctl_lba_len_flags *)
8711	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8712	lbalen->lba = lba;
8713	lbalen->len = num_blocks;
8714	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8715
8716	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8717	ctsio->kern_rel_offset = 0;
8718
8719	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8720
8721	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8722	return (retval);
8723}
8724
8725static int
8726ctl_cnw_cont(union ctl_io *io)
8727{
8728	struct ctl_scsiio *ctsio;
8729	struct ctl_lun *lun;
8730	struct ctl_lba_len_flags *lbalen;
8731	int retval;
8732
8733	ctsio = &io->scsiio;
8734	ctsio->io_hdr.status = CTL_STATUS_NONE;
8735	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8736	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8737	lbalen = (struct ctl_lba_len_flags *)
8738	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8739	lbalen->flags &= ~CTL_LLF_COMPARE;
8740	lbalen->flags |= CTL_LLF_WRITE;
8741
8742	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8743	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8744	return (retval);
8745}
8746
8747int
8748ctl_cnw(struct ctl_scsiio *ctsio)
8749{
8750	struct ctl_lun *lun;
8751	struct ctl_lba_len_flags *lbalen;
8752	uint64_t lba;
8753	uint32_t num_blocks;
8754	int flags, retval;
8755
8756	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8757
8758	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8759
8760	flags = 0;
8761	switch (ctsio->cdb[0]) {
8762	case COMPARE_AND_WRITE: {
8763		struct scsi_compare_and_write *cdb;
8764
8765		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8766		if (cdb->byte2 & SRW10_FUA)
8767			flags |= CTL_LLF_FUA;
8768		if (cdb->byte2 & SRW10_DPO)
8769			flags |= CTL_LLF_DPO;
8770		lba = scsi_8btou64(cdb->addr);
8771		num_blocks = cdb->length;
8772		break;
8773	}
8774	default:
8775		/*
8776		 * We got a command we don't support.  This shouldn't
8777		 * happen, commands should be filtered out above us.
8778		 */
8779		ctl_set_invalid_opcode(ctsio);
8780		ctl_done((union ctl_io *)ctsio);
8781
8782		return (CTL_RETVAL_COMPLETE);
8783		break; /* NOTREACHED */
8784	}
8785
8786	/*
8787	 * The first check is to make sure we're in bounds, the second
8788	 * check is to catch wrap-around problems.  If the lba + num blocks
8789	 * is less than the lba, then we've wrapped around and the block
8790	 * range is invalid anyway.
8791	 */
8792	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8793	 || ((lba + num_blocks) < lba)) {
8794		ctl_set_lba_out_of_range(ctsio);
8795		ctl_done((union ctl_io *)ctsio);
8796		return (CTL_RETVAL_COMPLETE);
8797	}
8798
8799	/*
8800	 * According to SBC-3, a transfer length of 0 is not an error.
8801	 */
8802	if (num_blocks == 0) {
8803		ctl_set_success(ctsio);
8804		ctl_done((union ctl_io *)ctsio);
8805		return (CTL_RETVAL_COMPLETE);
8806	}
8807
8808	/* Set FUA if write cache is disabled. */
8809	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8810	    SCP_WCE) == 0)
8811		flags |= CTL_LLF_FUA;
8812
8813	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8814	ctsio->kern_rel_offset = 0;
8815
8816	/*
8817	 * Set the IO_CONT flag, so that if this I/O gets passed to
8818	 * ctl_data_submit_done(), it'll get passed back to
8819	 * ctl_ctl_cnw_cont() for further processing.
8820	 */
8821	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8822	ctsio->io_cont = ctl_cnw_cont;
8823
8824	lbalen = (struct ctl_lba_len_flags *)
8825	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8826	lbalen->lba = lba;
8827	lbalen->len = num_blocks;
8828	lbalen->flags = CTL_LLF_COMPARE | flags;
8829
8830	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8831	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8832	return (retval);
8833}
8834
8835int
8836ctl_verify(struct ctl_scsiio *ctsio)
8837{
8838	struct ctl_lun *lun;
8839	struct ctl_lba_len_flags *lbalen;
8840	uint64_t lba;
8841	uint32_t num_blocks;
8842	int bytchk, flags;
8843	int retval;
8844
8845	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8846
8847	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8848
8849	bytchk = 0;
8850	flags = CTL_LLF_FUA;
8851	switch (ctsio->cdb[0]) {
8852	case VERIFY_10: {
8853		struct scsi_verify_10 *cdb;
8854
8855		cdb = (struct scsi_verify_10 *)ctsio->cdb;
8856		if (cdb->byte2 & SVFY_BYTCHK)
8857			bytchk = 1;
8858		if (cdb->byte2 & SVFY_DPO)
8859			flags |= CTL_LLF_DPO;
8860		lba = scsi_4btoul(cdb->addr);
8861		num_blocks = scsi_2btoul(cdb->length);
8862		break;
8863	}
8864	case VERIFY_12: {
8865		struct scsi_verify_12 *cdb;
8866
8867		cdb = (struct scsi_verify_12 *)ctsio->cdb;
8868		if (cdb->byte2 & SVFY_BYTCHK)
8869			bytchk = 1;
8870		if (cdb->byte2 & SVFY_DPO)
8871			flags |= CTL_LLF_DPO;
8872		lba = scsi_4btoul(cdb->addr);
8873		num_blocks = scsi_4btoul(cdb->length);
8874		break;
8875	}
8876	case VERIFY_16: {
8877		struct scsi_rw_16 *cdb;
8878
8879		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8880		if (cdb->byte2 & SVFY_BYTCHK)
8881			bytchk = 1;
8882		if (cdb->byte2 & SVFY_DPO)
8883			flags |= CTL_LLF_DPO;
8884		lba = scsi_8btou64(cdb->addr);
8885		num_blocks = scsi_4btoul(cdb->length);
8886		break;
8887	}
8888	default:
8889		/*
8890		 * We got a command we don't support.  This shouldn't
8891		 * happen, commands should be filtered out above us.
8892		 */
8893		ctl_set_invalid_opcode(ctsio);
8894		ctl_done((union ctl_io *)ctsio);
8895		return (CTL_RETVAL_COMPLETE);
8896	}
8897
8898	/*
8899	 * The first check is to make sure we're in bounds, the second
8900	 * check is to catch wrap-around problems.  If the lba + num blocks
8901	 * is less than the lba, then we've wrapped around and the block
8902	 * range is invalid anyway.
8903	 */
8904	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8905	 || ((lba + num_blocks) < lba)) {
8906		ctl_set_lba_out_of_range(ctsio);
8907		ctl_done((union ctl_io *)ctsio);
8908		return (CTL_RETVAL_COMPLETE);
8909	}
8910
8911	/*
8912	 * According to SBC-3, a transfer length of 0 is not an error.
8913	 */
8914	if (num_blocks == 0) {
8915		ctl_set_success(ctsio);
8916		ctl_done((union ctl_io *)ctsio);
8917		return (CTL_RETVAL_COMPLETE);
8918	}
8919
8920	lbalen = (struct ctl_lba_len_flags *)
8921	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8922	lbalen->lba = lba;
8923	lbalen->len = num_blocks;
8924	if (bytchk) {
8925		lbalen->flags = CTL_LLF_COMPARE | flags;
8926		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8927	} else {
8928		lbalen->flags = CTL_LLF_VERIFY | flags;
8929		ctsio->kern_total_len = 0;
8930	}
8931	ctsio->kern_rel_offset = 0;
8932
8933	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
8934	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8935	return (retval);
8936}
8937
8938int
8939ctl_report_luns(struct ctl_scsiio *ctsio)
8940{
8941	struct ctl_softc *softc;
8942	struct scsi_report_luns *cdb;
8943	struct scsi_report_luns_data *lun_data;
8944	struct ctl_lun *lun, *request_lun;
8945	struct ctl_port *port;
8946	int num_luns, retval;
8947	uint32_t alloc_len, lun_datalen;
8948	int num_filled;
8949	uint32_t initidx, targ_lun_id, lun_id;
8950
8951	retval = CTL_RETVAL_COMPLETE;
8952	cdb = (struct scsi_report_luns *)ctsio->cdb;
8953	port = ctl_io_port(&ctsio->io_hdr);
8954	softc = port->ctl_softc;
8955
8956	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
8957
8958	mtx_lock(&softc->ctl_lock);
8959	num_luns = 0;
8960	for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
8961		if (ctl_lun_map_from_port(port, targ_lun_id) < CTL_MAX_LUNS)
8962			num_luns++;
8963	}
8964	mtx_unlock(&softc->ctl_lock);
8965
8966	switch (cdb->select_report) {
8967	case RPL_REPORT_DEFAULT:
8968	case RPL_REPORT_ALL:
8969	case RPL_REPORT_NONSUBSID:
8970		break;
8971	case RPL_REPORT_WELLKNOWN:
8972	case RPL_REPORT_ADMIN:
8973	case RPL_REPORT_CONGLOM:
8974		num_luns = 0;
8975		break;
8976	default:
8977		ctl_set_invalid_field(ctsio,
8978				      /*sks_valid*/ 1,
8979				      /*command*/ 1,
8980				      /*field*/ 2,
8981				      /*bit_valid*/ 0,
8982				      /*bit*/ 0);
8983		ctl_done((union ctl_io *)ctsio);
8984		return (retval);
8985		break; /* NOTREACHED */
8986	}
8987
8988	alloc_len = scsi_4btoul(cdb->length);
8989	/*
8990	 * The initiator has to allocate at least 16 bytes for this request,
8991	 * so he can at least get the header and the first LUN.  Otherwise
8992	 * we reject the request (per SPC-3 rev 14, section 6.21).
8993	 */
8994	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
8995	    sizeof(struct scsi_report_luns_lundata))) {
8996		ctl_set_invalid_field(ctsio,
8997				      /*sks_valid*/ 1,
8998				      /*command*/ 1,
8999				      /*field*/ 6,
9000				      /*bit_valid*/ 0,
9001				      /*bit*/ 0);
9002		ctl_done((union ctl_io *)ctsio);
9003		return (retval);
9004	}
9005
9006	request_lun = (struct ctl_lun *)
9007		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9008
9009	lun_datalen = sizeof(*lun_data) +
9010		(num_luns * sizeof(struct scsi_report_luns_lundata));
9011
9012	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9013	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9014	ctsio->kern_sg_entries = 0;
9015
9016	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9017
9018	mtx_lock(&softc->ctl_lock);
9019	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9020		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9021		if (lun_id >= CTL_MAX_LUNS)
9022			continue;
9023		lun = softc->ctl_luns[lun_id];
9024		if (lun == NULL)
9025			continue;
9026
9027		if (targ_lun_id <= 0xff) {
9028			/*
9029			 * Peripheral addressing method, bus number 0.
9030			 */
9031			lun_data->luns[num_filled].lundata[0] =
9032				RPL_LUNDATA_ATYP_PERIPH;
9033			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9034			num_filled++;
9035		} else if (targ_lun_id <= 0x3fff) {
9036			/*
9037			 * Flat addressing method.
9038			 */
9039			lun_data->luns[num_filled].lundata[0] =
9040				RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9041			lun_data->luns[num_filled].lundata[1] =
9042				(targ_lun_id & 0xff);
9043			num_filled++;
9044		} else if (targ_lun_id <= 0xffffff) {
9045			/*
9046			 * Extended flat addressing method.
9047			 */
9048			lun_data->luns[num_filled].lundata[0] =
9049			    RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9050			scsi_ulto3b(targ_lun_id,
9051			    &lun_data->luns[num_filled].lundata[1]);
9052			num_filled++;
9053		} else {
9054			printf("ctl_report_luns: bogus LUN number %jd, "
9055			       "skipping\n", (intmax_t)targ_lun_id);
9056		}
9057		/*
9058		 * According to SPC-3, rev 14 section 6.21:
9059		 *
9060		 * "The execution of a REPORT LUNS command to any valid and
9061		 * installed logical unit shall clear the REPORTED LUNS DATA
9062		 * HAS CHANGED unit attention condition for all logical
9063		 * units of that target with respect to the requesting
9064		 * initiator. A valid and installed logical unit is one
9065		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9066		 * INQUIRY data (see 6.4.2)."
9067		 *
9068		 * If request_lun is NULL, the LUN this report luns command
9069		 * was issued to is either disabled or doesn't exist. In that
9070		 * case, we shouldn't clear any pending lun change unit
9071		 * attention.
9072		 */
9073		if (request_lun != NULL) {
9074			mtx_lock(&lun->lun_lock);
9075			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9076			mtx_unlock(&lun->lun_lock);
9077		}
9078	}
9079	mtx_unlock(&softc->ctl_lock);
9080
9081	/*
9082	 * It's quite possible that we've returned fewer LUNs than we allocated
9083	 * space for.  Trim it.
9084	 */
9085	lun_datalen = sizeof(*lun_data) +
9086		(num_filled * sizeof(struct scsi_report_luns_lundata));
9087
9088	if (lun_datalen < alloc_len) {
9089		ctsio->residual = alloc_len - lun_datalen;
9090		ctsio->kern_data_len = lun_datalen;
9091		ctsio->kern_total_len = lun_datalen;
9092	} else {
9093		ctsio->residual = 0;
9094		ctsio->kern_data_len = alloc_len;
9095		ctsio->kern_total_len = alloc_len;
9096	}
9097	ctsio->kern_data_resid = 0;
9098	ctsio->kern_rel_offset = 0;
9099	ctsio->kern_sg_entries = 0;
9100
9101	/*
9102	 * We set this to the actual data length, regardless of how much
9103	 * space we actually have to return results.  If the user looks at
9104	 * this value, he'll know whether or not he allocated enough space
9105	 * and reissue the command if necessary.  We don't support well
9106	 * known logical units, so if the user asks for that, return none.
9107	 */
9108	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9109
9110	/*
9111	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9112	 * this request.
9113	 */
9114	ctl_set_success(ctsio);
9115	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9116	ctsio->be_move_done = ctl_config_move_done;
9117	ctl_datamove((union ctl_io *)ctsio);
9118	return (retval);
9119}
9120
9121int
9122ctl_request_sense(struct ctl_scsiio *ctsio)
9123{
9124	struct scsi_request_sense *cdb;
9125	struct scsi_sense_data *sense_ptr;
9126	struct ctl_softc *ctl_softc;
9127	struct ctl_lun *lun;
9128	uint32_t initidx;
9129	int have_error;
9130	scsi_sense_data_type sense_format;
9131	ctl_ua_type ua_type;
9132
9133	cdb = (struct scsi_request_sense *)ctsio->cdb;
9134
9135	ctl_softc = control_softc;
9136	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9137
9138	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9139
9140	/*
9141	 * Determine which sense format the user wants.
9142	 */
9143	if (cdb->byte2 & SRS_DESC)
9144		sense_format = SSD_TYPE_DESC;
9145	else
9146		sense_format = SSD_TYPE_FIXED;
9147
9148	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9149	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9150	ctsio->kern_sg_entries = 0;
9151
9152	/*
9153	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9154	 * larger than the largest allowed value for the length field in the
9155	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9156	 */
9157	ctsio->residual = 0;
9158	ctsio->kern_data_len = cdb->length;
9159	ctsio->kern_total_len = cdb->length;
9160
9161	ctsio->kern_data_resid = 0;
9162	ctsio->kern_rel_offset = 0;
9163	ctsio->kern_sg_entries = 0;
9164
9165	/*
9166	 * If we don't have a LUN, we don't have any pending sense.
9167	 */
9168	if (lun == NULL)
9169		goto no_sense;
9170
9171	have_error = 0;
9172	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9173	/*
9174	 * Check for pending sense, and then for pending unit attentions.
9175	 * Pending sense gets returned first, then pending unit attentions.
9176	 */
9177	mtx_lock(&lun->lun_lock);
9178#ifdef CTL_WITH_CA
9179	if (ctl_is_set(lun->have_ca, initidx)) {
9180		scsi_sense_data_type stored_format;
9181
9182		/*
9183		 * Check to see which sense format was used for the stored
9184		 * sense data.
9185		 */
9186		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9187
9188		/*
9189		 * If the user requested a different sense format than the
9190		 * one we stored, then we need to convert it to the other
9191		 * format.  If we're going from descriptor to fixed format
9192		 * sense data, we may lose things in translation, depending
9193		 * on what options were used.
9194		 *
9195		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9196		 * for some reason we'll just copy it out as-is.
9197		 */
9198		if ((stored_format == SSD_TYPE_FIXED)
9199		 && (sense_format == SSD_TYPE_DESC))
9200			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9201			    &lun->pending_sense[initidx],
9202			    (struct scsi_sense_data_desc *)sense_ptr);
9203		else if ((stored_format == SSD_TYPE_DESC)
9204		      && (sense_format == SSD_TYPE_FIXED))
9205			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9206			    &lun->pending_sense[initidx],
9207			    (struct scsi_sense_data_fixed *)sense_ptr);
9208		else
9209			memcpy(sense_ptr, &lun->pending_sense[initidx],
9210			       MIN(sizeof(*sense_ptr),
9211			       sizeof(lun->pending_sense[initidx])));
9212
9213		ctl_clear_mask(lun->have_ca, initidx);
9214		have_error = 1;
9215	} else
9216#endif
9217	{
9218		ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9219		if (ua_type != CTL_UA_NONE)
9220			have_error = 1;
9221		if (ua_type == CTL_UA_LUN_CHANGE) {
9222			mtx_unlock(&lun->lun_lock);
9223			mtx_lock(&ctl_softc->ctl_lock);
9224			ctl_clr_ua_allluns(ctl_softc, initidx, ua_type);
9225			mtx_unlock(&ctl_softc->ctl_lock);
9226			mtx_lock(&lun->lun_lock);
9227		}
9228
9229	}
9230	mtx_unlock(&lun->lun_lock);
9231
9232	/*
9233	 * We already have a pending error, return it.
9234	 */
9235	if (have_error != 0) {
9236		/*
9237		 * We report the SCSI status as OK, since the status of the
9238		 * request sense command itself is OK.
9239		 * We report 0 for the sense length, because we aren't doing
9240		 * autosense in this case.  We're reporting sense as
9241		 * parameter data.
9242		 */
9243		ctl_set_success(ctsio);
9244		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9245		ctsio->be_move_done = ctl_config_move_done;
9246		ctl_datamove((union ctl_io *)ctsio);
9247		return (CTL_RETVAL_COMPLETE);
9248	}
9249
9250no_sense:
9251
9252	/*
9253	 * No sense information to report, so we report that everything is
9254	 * okay.
9255	 */
9256	ctl_set_sense_data(sense_ptr,
9257			   lun,
9258			   sense_format,
9259			   /*current_error*/ 1,
9260			   /*sense_key*/ SSD_KEY_NO_SENSE,
9261			   /*asc*/ 0x00,
9262			   /*ascq*/ 0x00,
9263			   SSD_ELEM_NONE);
9264
9265	/*
9266	 * We report 0 for the sense length, because we aren't doing
9267	 * autosense in this case.  We're reporting sense as parameter data.
9268	 */
9269	ctl_set_success(ctsio);
9270	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9271	ctsio->be_move_done = ctl_config_move_done;
9272	ctl_datamove((union ctl_io *)ctsio);
9273	return (CTL_RETVAL_COMPLETE);
9274}
9275
9276int
9277ctl_tur(struct ctl_scsiio *ctsio)
9278{
9279
9280	CTL_DEBUG_PRINT(("ctl_tur\n"));
9281
9282	ctl_set_success(ctsio);
9283	ctl_done((union ctl_io *)ctsio);
9284
9285	return (CTL_RETVAL_COMPLETE);
9286}
9287
9288/*
9289 * SCSI VPD page 0x00, the Supported VPD Pages page.
9290 */
9291static int
9292ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9293{
9294	struct scsi_vpd_supported_pages *pages;
9295	int sup_page_size;
9296	struct ctl_lun *lun;
9297	int p;
9298
9299	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9300
9301	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9302	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9303	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9304	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9305	ctsio->kern_sg_entries = 0;
9306
9307	if (sup_page_size < alloc_len) {
9308		ctsio->residual = alloc_len - sup_page_size;
9309		ctsio->kern_data_len = sup_page_size;
9310		ctsio->kern_total_len = sup_page_size;
9311	} else {
9312		ctsio->residual = 0;
9313		ctsio->kern_data_len = alloc_len;
9314		ctsio->kern_total_len = alloc_len;
9315	}
9316	ctsio->kern_data_resid = 0;
9317	ctsio->kern_rel_offset = 0;
9318	ctsio->kern_sg_entries = 0;
9319
9320	/*
9321	 * The control device is always connected.  The disk device, on the
9322	 * other hand, may not be online all the time.  Need to change this
9323	 * to figure out whether the disk device is actually online or not.
9324	 */
9325	if (lun != NULL)
9326		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9327				lun->be_lun->lun_type;
9328	else
9329		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9330
9331	p = 0;
9332	/* Supported VPD pages */
9333	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9334	/* Serial Number */
9335	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9336	/* Device Identification */
9337	pages->page_list[p++] = SVPD_DEVICE_ID;
9338	/* Extended INQUIRY Data */
9339	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9340	/* Mode Page Policy */
9341	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9342	/* SCSI Ports */
9343	pages->page_list[p++] = SVPD_SCSI_PORTS;
9344	/* Third-party Copy */
9345	pages->page_list[p++] = SVPD_SCSI_TPC;
9346	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9347		/* Block limits */
9348		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9349		/* Block Device Characteristics */
9350		pages->page_list[p++] = SVPD_BDC;
9351		/* Logical Block Provisioning */
9352		pages->page_list[p++] = SVPD_LBP;
9353	}
9354	pages->length = p;
9355
9356	ctl_set_success(ctsio);
9357	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9358	ctsio->be_move_done = ctl_config_move_done;
9359	ctl_datamove((union ctl_io *)ctsio);
9360	return (CTL_RETVAL_COMPLETE);
9361}
9362
9363/*
9364 * SCSI VPD page 0x80, the Unit Serial Number page.
9365 */
9366static int
9367ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9368{
9369	struct scsi_vpd_unit_serial_number *sn_ptr;
9370	struct ctl_lun *lun;
9371	int data_len;
9372
9373	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9374
9375	data_len = 4 + CTL_SN_LEN;
9376	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9377	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9378	if (data_len < alloc_len) {
9379		ctsio->residual = alloc_len - data_len;
9380		ctsio->kern_data_len = data_len;
9381		ctsio->kern_total_len = data_len;
9382	} else {
9383		ctsio->residual = 0;
9384		ctsio->kern_data_len = alloc_len;
9385		ctsio->kern_total_len = alloc_len;
9386	}
9387	ctsio->kern_data_resid = 0;
9388	ctsio->kern_rel_offset = 0;
9389	ctsio->kern_sg_entries = 0;
9390
9391	/*
9392	 * The control device is always connected.  The disk device, on the
9393	 * other hand, may not be online all the time.  Need to change this
9394	 * to figure out whether the disk device is actually online or not.
9395	 */
9396	if (lun != NULL)
9397		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9398				  lun->be_lun->lun_type;
9399	else
9400		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9401
9402	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9403	sn_ptr->length = CTL_SN_LEN;
9404	/*
9405	 * If we don't have a LUN, we just leave the serial number as
9406	 * all spaces.
9407	 */
9408	if (lun != NULL) {
9409		strncpy((char *)sn_ptr->serial_num,
9410			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9411	} else
9412		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9413
9414	ctl_set_success(ctsio);
9415	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9416	ctsio->be_move_done = ctl_config_move_done;
9417	ctl_datamove((union ctl_io *)ctsio);
9418	return (CTL_RETVAL_COMPLETE);
9419}
9420
9421
9422/*
9423 * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9424 */
9425static int
9426ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9427{
9428	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9429	struct ctl_lun *lun;
9430	int data_len;
9431
9432	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9433
9434	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9435	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9436	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9437	ctsio->kern_sg_entries = 0;
9438
9439	if (data_len < alloc_len) {
9440		ctsio->residual = alloc_len - data_len;
9441		ctsio->kern_data_len = data_len;
9442		ctsio->kern_total_len = data_len;
9443	} else {
9444		ctsio->residual = 0;
9445		ctsio->kern_data_len = alloc_len;
9446		ctsio->kern_total_len = alloc_len;
9447	}
9448	ctsio->kern_data_resid = 0;
9449	ctsio->kern_rel_offset = 0;
9450	ctsio->kern_sg_entries = 0;
9451
9452	/*
9453	 * The control device is always connected.  The disk device, on the
9454	 * other hand, may not be online all the time.
9455	 */
9456	if (lun != NULL)
9457		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9458				     lun->be_lun->lun_type;
9459	else
9460		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9461	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9462	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9463	/*
9464	 * We support head of queue, ordered and simple tags.
9465	 */
9466	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9467	/*
9468	 * Volatile cache supported.
9469	 */
9470	eid_ptr->flags3 = SVPD_EID_V_SUP;
9471
9472	/*
9473	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9474	 * attention for a particular IT nexus on all LUNs once we report
9475	 * it to that nexus once.  This bit is required as of SPC-4.
9476	 */
9477	eid_ptr->flags4 = SVPD_EID_LUICLT;
9478
9479	/*
9480	 * XXX KDM in order to correctly answer this, we would need
9481	 * information from the SIM to determine how much sense data it
9482	 * can send.  So this would really be a path inquiry field, most
9483	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9484	 * but the hardware may or may not be able to support that much.
9485	 * 0 just means that the maximum sense data length is not reported.
9486	 */
9487	eid_ptr->max_sense_length = 0;
9488
9489	ctl_set_success(ctsio);
9490	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9491	ctsio->be_move_done = ctl_config_move_done;
9492	ctl_datamove((union ctl_io *)ctsio);
9493	return (CTL_RETVAL_COMPLETE);
9494}
9495
9496static int
9497ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9498{
9499	struct scsi_vpd_mode_page_policy *mpp_ptr;
9500	struct ctl_lun *lun;
9501	int data_len;
9502
9503	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9504
9505	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9506	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9507
9508	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9509	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9510	ctsio->kern_sg_entries = 0;
9511
9512	if (data_len < alloc_len) {
9513		ctsio->residual = alloc_len - data_len;
9514		ctsio->kern_data_len = data_len;
9515		ctsio->kern_total_len = data_len;
9516	} else {
9517		ctsio->residual = 0;
9518		ctsio->kern_data_len = alloc_len;
9519		ctsio->kern_total_len = alloc_len;
9520	}
9521	ctsio->kern_data_resid = 0;
9522	ctsio->kern_rel_offset = 0;
9523	ctsio->kern_sg_entries = 0;
9524
9525	/*
9526	 * The control device is always connected.  The disk device, on the
9527	 * other hand, may not be online all the time.
9528	 */
9529	if (lun != NULL)
9530		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9531				     lun->be_lun->lun_type;
9532	else
9533		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9534	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9535	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9536	mpp_ptr->descr[0].page_code = 0x3f;
9537	mpp_ptr->descr[0].subpage_code = 0xff;
9538	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9539
9540	ctl_set_success(ctsio);
9541	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9542	ctsio->be_move_done = ctl_config_move_done;
9543	ctl_datamove((union ctl_io *)ctsio);
9544	return (CTL_RETVAL_COMPLETE);
9545}
9546
9547/*
9548 * SCSI VPD page 0x83, the Device Identification page.
9549 */
9550static int
9551ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9552{
9553	struct scsi_vpd_device_id *devid_ptr;
9554	struct scsi_vpd_id_descriptor *desc;
9555	struct ctl_softc *softc;
9556	struct ctl_lun *lun;
9557	struct ctl_port *port;
9558	int data_len;
9559	uint8_t proto;
9560
9561	softc = control_softc;
9562
9563	port = ctl_io_port(&ctsio->io_hdr);
9564	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9565
9566	data_len = sizeof(struct scsi_vpd_device_id) +
9567	    sizeof(struct scsi_vpd_id_descriptor) +
9568		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9569	    sizeof(struct scsi_vpd_id_descriptor) +
9570		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9571	if (lun && lun->lun_devid)
9572		data_len += lun->lun_devid->len;
9573	if (port && port->port_devid)
9574		data_len += port->port_devid->len;
9575	if (port && port->target_devid)
9576		data_len += port->target_devid->len;
9577
9578	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9579	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9580	ctsio->kern_sg_entries = 0;
9581
9582	if (data_len < alloc_len) {
9583		ctsio->residual = alloc_len - data_len;
9584		ctsio->kern_data_len = data_len;
9585		ctsio->kern_total_len = data_len;
9586	} else {
9587		ctsio->residual = 0;
9588		ctsio->kern_data_len = alloc_len;
9589		ctsio->kern_total_len = alloc_len;
9590	}
9591	ctsio->kern_data_resid = 0;
9592	ctsio->kern_rel_offset = 0;
9593	ctsio->kern_sg_entries = 0;
9594
9595	/*
9596	 * The control device is always connected.  The disk device, on the
9597	 * other hand, may not be online all the time.
9598	 */
9599	if (lun != NULL)
9600		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9601				     lun->be_lun->lun_type;
9602	else
9603		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9604	devid_ptr->page_code = SVPD_DEVICE_ID;
9605	scsi_ulto2b(data_len - 4, devid_ptr->length);
9606
9607	if (port && port->port_type == CTL_PORT_FC)
9608		proto = SCSI_PROTO_FC << 4;
9609	else if (port && port->port_type == CTL_PORT_ISCSI)
9610		proto = SCSI_PROTO_ISCSI << 4;
9611	else
9612		proto = SCSI_PROTO_SPI << 4;
9613	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9614
9615	/*
9616	 * We're using a LUN association here.  i.e., this device ID is a
9617	 * per-LUN identifier.
9618	 */
9619	if (lun && lun->lun_devid) {
9620		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9621		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9622		    lun->lun_devid->len);
9623	}
9624
9625	/*
9626	 * This is for the WWPN which is a port association.
9627	 */
9628	if (port && port->port_devid) {
9629		memcpy(desc, port->port_devid->data, port->port_devid->len);
9630		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9631		    port->port_devid->len);
9632	}
9633
9634	/*
9635	 * This is for the Relative Target Port(type 4h) identifier
9636	 */
9637	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9638	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9639	    SVPD_ID_TYPE_RELTARG;
9640	desc->length = 4;
9641	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9642	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9643	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9644
9645	/*
9646	 * This is for the Target Port Group(type 5h) identifier
9647	 */
9648	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9649	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9650	    SVPD_ID_TYPE_TPORTGRP;
9651	desc->length = 4;
9652	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / softc->port_cnt + 1,
9653	    &desc->identifier[2]);
9654	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9655	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9656
9657	/*
9658	 * This is for the Target identifier
9659	 */
9660	if (port && port->target_devid) {
9661		memcpy(desc, port->target_devid->data, port->target_devid->len);
9662	}
9663
9664	ctl_set_success(ctsio);
9665	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9666	ctsio->be_move_done = ctl_config_move_done;
9667	ctl_datamove((union ctl_io *)ctsio);
9668	return (CTL_RETVAL_COMPLETE);
9669}
9670
9671static int
9672ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9673{
9674	struct ctl_softc *softc = control_softc;
9675	struct scsi_vpd_scsi_ports *sp;
9676	struct scsi_vpd_port_designation *pd;
9677	struct scsi_vpd_port_designation_cont *pdc;
9678	struct ctl_lun *lun;
9679	struct ctl_port *port;
9680	int data_len, num_target_ports, iid_len, id_len;
9681
9682	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9683
9684	num_target_ports = 0;
9685	iid_len = 0;
9686	id_len = 0;
9687	mtx_lock(&softc->ctl_lock);
9688	STAILQ_FOREACH(port, &softc->port_list, links) {
9689		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9690			continue;
9691		if (lun != NULL &&
9692		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9693			continue;
9694		num_target_ports++;
9695		if (port->init_devid)
9696			iid_len += port->init_devid->len;
9697		if (port->port_devid)
9698			id_len += port->port_devid->len;
9699	}
9700	mtx_unlock(&softc->ctl_lock);
9701
9702	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9703	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9704	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9705	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9706	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9707	ctsio->kern_sg_entries = 0;
9708
9709	if (data_len < alloc_len) {
9710		ctsio->residual = alloc_len - data_len;
9711		ctsio->kern_data_len = data_len;
9712		ctsio->kern_total_len = data_len;
9713	} else {
9714		ctsio->residual = 0;
9715		ctsio->kern_data_len = alloc_len;
9716		ctsio->kern_total_len = alloc_len;
9717	}
9718	ctsio->kern_data_resid = 0;
9719	ctsio->kern_rel_offset = 0;
9720	ctsio->kern_sg_entries = 0;
9721
9722	/*
9723	 * The control device is always connected.  The disk device, on the
9724	 * other hand, may not be online all the time.  Need to change this
9725	 * to figure out whether the disk device is actually online or not.
9726	 */
9727	if (lun != NULL)
9728		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9729				  lun->be_lun->lun_type;
9730	else
9731		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9732
9733	sp->page_code = SVPD_SCSI_PORTS;
9734	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9735	    sp->page_length);
9736	pd = &sp->design[0];
9737
9738	mtx_lock(&softc->ctl_lock);
9739	STAILQ_FOREACH(port, &softc->port_list, links) {
9740		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9741			continue;
9742		if (lun != NULL &&
9743		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9744			continue;
9745		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9746		if (port->init_devid) {
9747			iid_len = port->init_devid->len;
9748			memcpy(pd->initiator_transportid,
9749			    port->init_devid->data, port->init_devid->len);
9750		} else
9751			iid_len = 0;
9752		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9753		pdc = (struct scsi_vpd_port_designation_cont *)
9754		    (&pd->initiator_transportid[iid_len]);
9755		if (port->port_devid) {
9756			id_len = port->port_devid->len;
9757			memcpy(pdc->target_port_descriptors,
9758			    port->port_devid->data, port->port_devid->len);
9759		} else
9760			id_len = 0;
9761		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9762		pd = (struct scsi_vpd_port_designation *)
9763		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9764	}
9765	mtx_unlock(&softc->ctl_lock);
9766
9767	ctl_set_success(ctsio);
9768	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9769	ctsio->be_move_done = ctl_config_move_done;
9770	ctl_datamove((union ctl_io *)ctsio);
9771	return (CTL_RETVAL_COMPLETE);
9772}
9773
9774static int
9775ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9776{
9777	struct scsi_vpd_block_limits *bl_ptr;
9778	struct ctl_lun *lun;
9779
9780	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9781
9782	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9783	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9784	ctsio->kern_sg_entries = 0;
9785
9786	if (sizeof(*bl_ptr) < alloc_len) {
9787		ctsio->residual = alloc_len - sizeof(*bl_ptr);
9788		ctsio->kern_data_len = sizeof(*bl_ptr);
9789		ctsio->kern_total_len = sizeof(*bl_ptr);
9790	} else {
9791		ctsio->residual = 0;
9792		ctsio->kern_data_len = alloc_len;
9793		ctsio->kern_total_len = alloc_len;
9794	}
9795	ctsio->kern_data_resid = 0;
9796	ctsio->kern_rel_offset = 0;
9797	ctsio->kern_sg_entries = 0;
9798
9799	/*
9800	 * The control device is always connected.  The disk device, on the
9801	 * other hand, may not be online all the time.  Need to change this
9802	 * to figure out whether the disk device is actually online or not.
9803	 */
9804	if (lun != NULL)
9805		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9806				  lun->be_lun->lun_type;
9807	else
9808		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9809
9810	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9811	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9812	bl_ptr->max_cmp_write_len = 0xff;
9813	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9814	if (lun != NULL) {
9815		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9816		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9817			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
9818			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
9819			if (lun->be_lun->ublockexp != 0) {
9820				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9821				    bl_ptr->opt_unmap_grain);
9822				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9823				    bl_ptr->unmap_grain_align);
9824			}
9825		}
9826		scsi_ulto4b(lun->be_lun->atomicblock,
9827		    bl_ptr->max_atomic_transfer_length);
9828		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9829		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9830		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9831		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9832	}
9833	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
9834
9835	ctl_set_success(ctsio);
9836	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9837	ctsio->be_move_done = ctl_config_move_done;
9838	ctl_datamove((union ctl_io *)ctsio);
9839	return (CTL_RETVAL_COMPLETE);
9840}
9841
9842static int
9843ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9844{
9845	struct scsi_vpd_block_device_characteristics *bdc_ptr;
9846	struct ctl_lun *lun;
9847	const char *value;
9848	u_int i;
9849
9850	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9851
9852	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9853	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9854	ctsio->kern_sg_entries = 0;
9855
9856	if (sizeof(*bdc_ptr) < alloc_len) {
9857		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
9858		ctsio->kern_data_len = sizeof(*bdc_ptr);
9859		ctsio->kern_total_len = sizeof(*bdc_ptr);
9860	} else {
9861		ctsio->residual = 0;
9862		ctsio->kern_data_len = alloc_len;
9863		ctsio->kern_total_len = alloc_len;
9864	}
9865	ctsio->kern_data_resid = 0;
9866	ctsio->kern_rel_offset = 0;
9867	ctsio->kern_sg_entries = 0;
9868
9869	/*
9870	 * The control device is always connected.  The disk device, on the
9871	 * other hand, may not be online all the time.  Need to change this
9872	 * to figure out whether the disk device is actually online or not.
9873	 */
9874	if (lun != NULL)
9875		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9876				  lun->be_lun->lun_type;
9877	else
9878		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9879	bdc_ptr->page_code = SVPD_BDC;
9880	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9881	if (lun != NULL &&
9882	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
9883		i = strtol(value, NULL, 0);
9884	else
9885		i = CTL_DEFAULT_ROTATION_RATE;
9886	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9887	if (lun != NULL &&
9888	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
9889		i = strtol(value, NULL, 0);
9890	else
9891		i = 0;
9892	bdc_ptr->wab_wac_ff = (i & 0x0f);
9893	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9894
9895	ctl_set_success(ctsio);
9896	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9897	ctsio->be_move_done = ctl_config_move_done;
9898	ctl_datamove((union ctl_io *)ctsio);
9899	return (CTL_RETVAL_COMPLETE);
9900}
9901
9902static int
9903ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9904{
9905	struct scsi_vpd_logical_block_prov *lbp_ptr;
9906	struct ctl_lun *lun;
9907
9908	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9909
9910	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9911	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9912	ctsio->kern_sg_entries = 0;
9913
9914	if (sizeof(*lbp_ptr) < alloc_len) {
9915		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
9916		ctsio->kern_data_len = sizeof(*lbp_ptr);
9917		ctsio->kern_total_len = sizeof(*lbp_ptr);
9918	} else {
9919		ctsio->residual = 0;
9920		ctsio->kern_data_len = alloc_len;
9921		ctsio->kern_total_len = alloc_len;
9922	}
9923	ctsio->kern_data_resid = 0;
9924	ctsio->kern_rel_offset = 0;
9925	ctsio->kern_sg_entries = 0;
9926
9927	/*
9928	 * The control device is always connected.  The disk device, on the
9929	 * other hand, may not be online all the time.  Need to change this
9930	 * to figure out whether the disk device is actually online or not.
9931	 */
9932	if (lun != NULL)
9933		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9934				  lun->be_lun->lun_type;
9935	else
9936		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9937
9938	lbp_ptr->page_code = SVPD_LBP;
9939	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
9940	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
9941	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9942		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
9943		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
9944		lbp_ptr->prov_type = SVPD_LBP_THIN;
9945	}
9946
9947	ctl_set_success(ctsio);
9948	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9949	ctsio->be_move_done = ctl_config_move_done;
9950	ctl_datamove((union ctl_io *)ctsio);
9951	return (CTL_RETVAL_COMPLETE);
9952}
9953
9954/*
9955 * INQUIRY with the EVPD bit set.
9956 */
9957static int
9958ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
9959{
9960	struct ctl_lun *lun;
9961	struct scsi_inquiry *cdb;
9962	int alloc_len, retval;
9963
9964	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9965	cdb = (struct scsi_inquiry *)ctsio->cdb;
9966	alloc_len = scsi_2btoul(cdb->length);
9967
9968	switch (cdb->page_code) {
9969	case SVPD_SUPPORTED_PAGES:
9970		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
9971		break;
9972	case SVPD_UNIT_SERIAL_NUMBER:
9973		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
9974		break;
9975	case SVPD_DEVICE_ID:
9976		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
9977		break;
9978	case SVPD_EXTENDED_INQUIRY_DATA:
9979		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
9980		break;
9981	case SVPD_MODE_PAGE_POLICY:
9982		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
9983		break;
9984	case SVPD_SCSI_PORTS:
9985		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
9986		break;
9987	case SVPD_SCSI_TPC:
9988		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
9989		break;
9990	case SVPD_BLOCK_LIMITS:
9991		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9992			goto err;
9993		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
9994		break;
9995	case SVPD_BDC:
9996		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9997			goto err;
9998		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
9999		break;
10000	case SVPD_LBP:
10001		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10002			goto err;
10003		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10004		break;
10005	default:
10006err:
10007		ctl_set_invalid_field(ctsio,
10008				      /*sks_valid*/ 1,
10009				      /*command*/ 1,
10010				      /*field*/ 2,
10011				      /*bit_valid*/ 0,
10012				      /*bit*/ 0);
10013		ctl_done((union ctl_io *)ctsio);
10014		retval = CTL_RETVAL_COMPLETE;
10015		break;
10016	}
10017
10018	return (retval);
10019}
10020
10021/*
10022 * Standard INQUIRY data.
10023 */
10024static int
10025ctl_inquiry_std(struct ctl_scsiio *ctsio)
10026{
10027	struct scsi_inquiry_data *inq_ptr;
10028	struct scsi_inquiry *cdb;
10029	struct ctl_softc *softc = control_softc;
10030	struct ctl_port *port;
10031	struct ctl_lun *lun;
10032	char *val;
10033	uint32_t alloc_len, data_len;
10034	ctl_port_type port_type;
10035
10036	port = ctl_io_port(&ctsio->io_hdr);
10037	port_type = port->port_type;
10038	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10039		port_type = CTL_PORT_SCSI;
10040
10041	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10042	cdb = (struct scsi_inquiry *)ctsio->cdb;
10043	alloc_len = scsi_2btoul(cdb->length);
10044
10045	/*
10046	 * We malloc the full inquiry data size here and fill it
10047	 * in.  If the user only asks for less, we'll give him
10048	 * that much.
10049	 */
10050	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10051	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10052	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10053	ctsio->kern_sg_entries = 0;
10054	ctsio->kern_data_resid = 0;
10055	ctsio->kern_rel_offset = 0;
10056
10057	if (data_len < alloc_len) {
10058		ctsio->residual = alloc_len - data_len;
10059		ctsio->kern_data_len = data_len;
10060		ctsio->kern_total_len = data_len;
10061	} else {
10062		ctsio->residual = 0;
10063		ctsio->kern_data_len = alloc_len;
10064		ctsio->kern_total_len = alloc_len;
10065	}
10066
10067	if (lun != NULL) {
10068		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10069		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10070			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10071			    lun->be_lun->lun_type;
10072		} else {
10073			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10074			    lun->be_lun->lun_type;
10075		}
10076		if (lun->flags & CTL_LUN_REMOVABLE)
10077			inq_ptr->dev_qual2 |= SID_RMB;
10078	} else
10079		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10080
10081	/* RMB in byte 2 is 0 */
10082	inq_ptr->version = SCSI_REV_SPC4;
10083
10084	/*
10085	 * According to SAM-3, even if a device only supports a single
10086	 * level of LUN addressing, it should still set the HISUP bit:
10087	 *
10088	 * 4.9.1 Logical unit numbers overview
10089	 *
10090	 * All logical unit number formats described in this standard are
10091	 * hierarchical in structure even when only a single level in that
10092	 * hierarchy is used. The HISUP bit shall be set to one in the
10093	 * standard INQUIRY data (see SPC-2) when any logical unit number
10094	 * format described in this standard is used.  Non-hierarchical
10095	 * formats are outside the scope of this standard.
10096	 *
10097	 * Therefore we set the HiSup bit here.
10098	 *
10099	 * The reponse format is 2, per SPC-3.
10100	 */
10101	inq_ptr->response_format = SID_HiSup | 2;
10102
10103	inq_ptr->additional_length = data_len -
10104	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10105	CTL_DEBUG_PRINT(("additional_length = %d\n",
10106			 inq_ptr->additional_length));
10107
10108	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10109	if (port_type == CTL_PORT_SCSI)
10110		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10111	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10112	inq_ptr->flags = SID_CmdQue;
10113	if (port_type == CTL_PORT_SCSI)
10114		inq_ptr->flags |= SID_WBus16 | SID_Sync;
10115
10116	/*
10117	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10118	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10119	 * name and 4 bytes for the revision.
10120	 */
10121	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10122	    "vendor")) == NULL) {
10123		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10124	} else {
10125		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10126		strncpy(inq_ptr->vendor, val,
10127		    min(sizeof(inq_ptr->vendor), strlen(val)));
10128	}
10129	if (lun == NULL) {
10130		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10131		    sizeof(inq_ptr->product));
10132	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10133		switch (lun->be_lun->lun_type) {
10134		case T_DIRECT:
10135			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10136			    sizeof(inq_ptr->product));
10137			break;
10138		case T_PROCESSOR:
10139			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10140			    sizeof(inq_ptr->product));
10141			break;
10142		case T_CDROM:
10143			strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10144			    sizeof(inq_ptr->product));
10145			break;
10146		default:
10147			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10148			    sizeof(inq_ptr->product));
10149			break;
10150		}
10151	} else {
10152		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10153		strncpy(inq_ptr->product, val,
10154		    min(sizeof(inq_ptr->product), strlen(val)));
10155	}
10156
10157	/*
10158	 * XXX make this a macro somewhere so it automatically gets
10159	 * incremented when we make changes.
10160	 */
10161	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10162	    "revision")) == NULL) {
10163		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10164	} else {
10165		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10166		strncpy(inq_ptr->revision, val,
10167		    min(sizeof(inq_ptr->revision), strlen(val)));
10168	}
10169
10170	/*
10171	 * For parallel SCSI, we support double transition and single
10172	 * transition clocking.  We also support QAS (Quick Arbitration
10173	 * and Selection) and Information Unit transfers on both the
10174	 * control and array devices.
10175	 */
10176	if (port_type == CTL_PORT_SCSI)
10177		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10178				    SID_SPI_IUS;
10179
10180	/* SAM-5 (no version claimed) */
10181	scsi_ulto2b(0x00A0, inq_ptr->version1);
10182	/* SPC-4 (no version claimed) */
10183	scsi_ulto2b(0x0460, inq_ptr->version2);
10184	if (port_type == CTL_PORT_FC) {
10185		/* FCP-2 ANSI INCITS.350:2003 */
10186		scsi_ulto2b(0x0917, inq_ptr->version3);
10187	} else if (port_type == CTL_PORT_SCSI) {
10188		/* SPI-4 ANSI INCITS.362:200x */
10189		scsi_ulto2b(0x0B56, inq_ptr->version3);
10190	} else if (port_type == CTL_PORT_ISCSI) {
10191		/* iSCSI (no version claimed) */
10192		scsi_ulto2b(0x0960, inq_ptr->version3);
10193	} else if (port_type == CTL_PORT_SAS) {
10194		/* SAS (no version claimed) */
10195		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10196	}
10197
10198	if (lun == NULL) {
10199		/* SBC-4 (no version claimed) */
10200		scsi_ulto2b(0x0600, inq_ptr->version4);
10201	} else {
10202		switch (lun->be_lun->lun_type) {
10203		case T_DIRECT:
10204			/* SBC-4 (no version claimed) */
10205			scsi_ulto2b(0x0600, inq_ptr->version4);
10206			break;
10207		case T_PROCESSOR:
10208			break;
10209		case T_CDROM:
10210			/* MMC-6 (no version claimed) */
10211			scsi_ulto2b(0x04E0, inq_ptr->version4);
10212			break;
10213		default:
10214			break;
10215		}
10216	}
10217
10218	ctl_set_success(ctsio);
10219	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10220	ctsio->be_move_done = ctl_config_move_done;
10221	ctl_datamove((union ctl_io *)ctsio);
10222	return (CTL_RETVAL_COMPLETE);
10223}
10224
10225int
10226ctl_inquiry(struct ctl_scsiio *ctsio)
10227{
10228	struct scsi_inquiry *cdb;
10229	int retval;
10230
10231	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10232
10233	cdb = (struct scsi_inquiry *)ctsio->cdb;
10234	if (cdb->byte2 & SI_EVPD)
10235		retval = ctl_inquiry_evpd(ctsio);
10236	else if (cdb->page_code == 0)
10237		retval = ctl_inquiry_std(ctsio);
10238	else {
10239		ctl_set_invalid_field(ctsio,
10240				      /*sks_valid*/ 1,
10241				      /*command*/ 1,
10242				      /*field*/ 2,
10243				      /*bit_valid*/ 0,
10244				      /*bit*/ 0);
10245		ctl_done((union ctl_io *)ctsio);
10246		return (CTL_RETVAL_COMPLETE);
10247	}
10248
10249	return (retval);
10250}
10251
10252int
10253ctl_get_config(struct ctl_scsiio *ctsio)
10254{
10255	struct scsi_get_config_header *hdr;
10256	struct scsi_get_config_feature *feature;
10257	struct scsi_get_config *cdb;
10258	struct ctl_lun *lun;
10259	uint32_t alloc_len, data_len;
10260	int rt, starting;
10261
10262	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10263	cdb = (struct scsi_get_config *)ctsio->cdb;
10264	rt = (cdb->rt & SGC_RT_MASK);
10265	starting = scsi_2btoul(cdb->starting_feature);
10266	alloc_len = scsi_2btoul(cdb->length);
10267
10268	data_len = sizeof(struct scsi_get_config_header) +
10269	    sizeof(struct scsi_get_config_feature) + 8 +
10270	    sizeof(struct scsi_get_config_feature) + 8 +
10271	    sizeof(struct scsi_get_config_feature) + 4 +
10272	    sizeof(struct scsi_get_config_feature) + 4 +
10273	    sizeof(struct scsi_get_config_feature) + 8 +
10274	    sizeof(struct scsi_get_config_feature) +
10275	    sizeof(struct scsi_get_config_feature) + 4 +
10276	    sizeof(struct scsi_get_config_feature) + 4;
10277	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10278	ctsio->kern_sg_entries = 0;
10279	ctsio->kern_data_resid = 0;
10280	ctsio->kern_rel_offset = 0;
10281
10282	hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10283	if (lun->flags & CTL_LUN_NO_MEDIA)
10284		scsi_ulto2b(0x0000, hdr->current_profile);
10285	else
10286		scsi_ulto2b(0x0010, hdr->current_profile);
10287	feature = (struct scsi_get_config_feature *)(hdr + 1);
10288
10289	if (starting > 0x001f)
10290		goto done;
10291	if (starting > 0x001e)
10292		goto f1f;
10293	if (starting > 0x001d)
10294		goto f1e;
10295	if (starting > 0x0010)
10296		goto f1d;
10297	if (starting > 0x0003)
10298		goto f10;
10299	if (starting > 0x0002)
10300		goto f3;
10301	if (starting > 0x0001)
10302		goto f2;
10303	if (starting > 0x0000)
10304		goto f1;
10305
10306	/* Profile List */
10307	scsi_ulto2b(0x0000, feature->feature_code);
10308	feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10309	feature->add_length = 8;
10310	scsi_ulto2b(0x0008, &feature->feature_data[0]);	/* CD-ROM */
10311	feature->feature_data[2] = 0x00;
10312	scsi_ulto2b(0x0010, &feature->feature_data[4]);	/* DVD-ROM */
10313	feature->feature_data[6] = 0x01;
10314	feature = (struct scsi_get_config_feature *)
10315	    &feature->feature_data[feature->add_length];
10316
10317f1:	/* Core */
10318	scsi_ulto2b(0x0001, feature->feature_code);
10319	feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10320	feature->add_length = 8;
10321	scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10322	feature->feature_data[4] = 0x03;
10323	feature = (struct scsi_get_config_feature *)
10324	    &feature->feature_data[feature->add_length];
10325
10326f2:	/* Morphing */
10327	scsi_ulto2b(0x0002, feature->feature_code);
10328	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10329	feature->add_length = 4;
10330	feature->feature_data[0] = 0x02;
10331	feature = (struct scsi_get_config_feature *)
10332	    &feature->feature_data[feature->add_length];
10333
10334f3:	/* Removable Medium */
10335	scsi_ulto2b(0x0003, feature->feature_code);
10336	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10337	feature->add_length = 4;
10338	feature->feature_data[0] = 0x39;
10339	feature = (struct scsi_get_config_feature *)
10340	    &feature->feature_data[feature->add_length];
10341
10342	if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10343		goto done;
10344
10345f10:	/* Random Read */
10346	scsi_ulto2b(0x0010, feature->feature_code);
10347	feature->flags = 0x00;
10348	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10349		feature->flags |= SGC_F_CURRENT;
10350	feature->add_length = 8;
10351	scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10352	scsi_ulto2b(1, &feature->feature_data[4]);
10353	feature->feature_data[6] = 0x00;
10354	feature = (struct scsi_get_config_feature *)
10355	    &feature->feature_data[feature->add_length];
10356
10357f1d:	/* Multi-Read */
10358	scsi_ulto2b(0x001D, feature->feature_code);
10359	feature->flags = 0x00;
10360	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10361		feature->flags |= SGC_F_CURRENT;
10362	feature->add_length = 0;
10363	feature = (struct scsi_get_config_feature *)
10364	    &feature->feature_data[feature->add_length];
10365
10366f1e:	/* CD Read */
10367	scsi_ulto2b(0x001E, feature->feature_code);
10368	feature->flags = 0x00;
10369	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10370		feature->flags |= SGC_F_CURRENT;
10371	feature->add_length = 4;
10372	feature->feature_data[0] = 0x00;
10373	feature = (struct scsi_get_config_feature *)
10374	    &feature->feature_data[feature->add_length];
10375
10376f1f:	/* DVD Read */
10377	scsi_ulto2b(0x001F, feature->feature_code);
10378	feature->flags = 0x08;
10379	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10380		feature->flags |= SGC_F_CURRENT;
10381	feature->add_length = 4;
10382	feature->feature_data[0] = 0x01;
10383	feature->feature_data[2] = 0x03;
10384	feature = (struct scsi_get_config_feature *)
10385	    &feature->feature_data[feature->add_length];
10386
10387done:
10388	data_len = (uint8_t *)feature - (uint8_t *)hdr;
10389	if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10390		feature = (struct scsi_get_config_feature *)(hdr + 1);
10391		if (scsi_2btoul(feature->feature_code) == starting)
10392			feature = (struct scsi_get_config_feature *)
10393			    &feature->feature_data[feature->add_length];
10394		data_len = (uint8_t *)feature - (uint8_t *)hdr;
10395	}
10396	scsi_ulto4b(data_len - 4, hdr->data_length);
10397	if (data_len < alloc_len) {
10398		ctsio->residual = alloc_len - data_len;
10399		ctsio->kern_data_len = data_len;
10400		ctsio->kern_total_len = data_len;
10401	} else {
10402		ctsio->residual = 0;
10403		ctsio->kern_data_len = alloc_len;
10404		ctsio->kern_total_len = alloc_len;
10405	}
10406
10407	ctl_set_success(ctsio);
10408	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10409	ctsio->be_move_done = ctl_config_move_done;
10410	ctl_datamove((union ctl_io *)ctsio);
10411	return (CTL_RETVAL_COMPLETE);
10412}
10413
10414int
10415ctl_get_event_status(struct ctl_scsiio *ctsio)
10416{
10417	struct scsi_get_event_status_header *hdr;
10418	struct scsi_get_event_status *cdb;
10419	struct ctl_lun *lun;
10420	uint32_t alloc_len, data_len;
10421	int notif_class;
10422
10423	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10424	cdb = (struct scsi_get_event_status *)ctsio->cdb;
10425	if ((cdb->byte2 & SGESN_POLLED) == 0) {
10426		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10427		    /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10428		ctl_done((union ctl_io *)ctsio);
10429		return (CTL_RETVAL_COMPLETE);
10430	}
10431	notif_class = cdb->notif_class;
10432	alloc_len = scsi_2btoul(cdb->length);
10433
10434	data_len = sizeof(struct scsi_get_event_status_header);
10435	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10436	ctsio->kern_sg_entries = 0;
10437	ctsio->kern_data_resid = 0;
10438	ctsio->kern_rel_offset = 0;
10439
10440	if (data_len < alloc_len) {
10441		ctsio->residual = alloc_len - data_len;
10442		ctsio->kern_data_len = data_len;
10443		ctsio->kern_total_len = data_len;
10444	} else {
10445		ctsio->residual = 0;
10446		ctsio->kern_data_len = alloc_len;
10447		ctsio->kern_total_len = alloc_len;
10448	}
10449
10450	hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10451	scsi_ulto2b(0, hdr->descr_length);
10452	hdr->nea_class = SGESN_NEA;
10453	hdr->supported_class = 0;
10454
10455	ctl_set_success(ctsio);
10456	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10457	ctsio->be_move_done = ctl_config_move_done;
10458	ctl_datamove((union ctl_io *)ctsio);
10459	return (CTL_RETVAL_COMPLETE);
10460}
10461
10462int
10463ctl_mechanism_status(struct ctl_scsiio *ctsio)
10464{
10465	struct scsi_mechanism_status_header *hdr;
10466	struct scsi_mechanism_status *cdb;
10467	struct ctl_lun *lun;
10468	uint32_t alloc_len, data_len;
10469
10470	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10471	cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10472	alloc_len = scsi_2btoul(cdb->length);
10473
10474	data_len = sizeof(struct scsi_mechanism_status_header);
10475	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10476	ctsio->kern_sg_entries = 0;
10477	ctsio->kern_data_resid = 0;
10478	ctsio->kern_rel_offset = 0;
10479
10480	if (data_len < alloc_len) {
10481		ctsio->residual = alloc_len - data_len;
10482		ctsio->kern_data_len = data_len;
10483		ctsio->kern_total_len = data_len;
10484	} else {
10485		ctsio->residual = 0;
10486		ctsio->kern_data_len = alloc_len;
10487		ctsio->kern_total_len = alloc_len;
10488	}
10489
10490	hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10491	hdr->state1 = 0x00;
10492	hdr->state2 = 0xe0;
10493	scsi_ulto3b(0, hdr->lba);
10494	hdr->slots_num = 0;
10495	scsi_ulto2b(0, hdr->slots_length);
10496
10497	ctl_set_success(ctsio);
10498	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10499	ctsio->be_move_done = ctl_config_move_done;
10500	ctl_datamove((union ctl_io *)ctsio);
10501	return (CTL_RETVAL_COMPLETE);
10502}
10503
10504static void
10505ctl_ultomsf(uint32_t lba, uint8_t *buf)
10506{
10507
10508	lba += 150;
10509	buf[0] = 0;
10510	buf[1] = bin2bcd((lba / 75) / 60);
10511	buf[2] = bin2bcd((lba / 75) % 60);
10512	buf[3] = bin2bcd(lba % 75);
10513}
10514
10515int
10516ctl_read_toc(struct ctl_scsiio *ctsio)
10517{
10518	struct scsi_read_toc_hdr *hdr;
10519	struct scsi_read_toc_type01_descr *descr;
10520	struct scsi_read_toc *cdb;
10521	struct ctl_lun *lun;
10522	uint32_t alloc_len, data_len;
10523	int format, msf;
10524
10525	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10526	cdb = (struct scsi_read_toc *)ctsio->cdb;
10527	msf = (cdb->byte2 & CD_MSF) != 0;
10528	format = cdb->format;
10529	alloc_len = scsi_2btoul(cdb->data_len);
10530
10531	data_len = sizeof(struct scsi_read_toc_hdr);
10532	if (format == 0)
10533		data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10534	else
10535		data_len += sizeof(struct scsi_read_toc_type01_descr);
10536	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10537	ctsio->kern_sg_entries = 0;
10538	ctsio->kern_data_resid = 0;
10539	ctsio->kern_rel_offset = 0;
10540
10541	if (data_len < alloc_len) {
10542		ctsio->residual = alloc_len - data_len;
10543		ctsio->kern_data_len = data_len;
10544		ctsio->kern_total_len = data_len;
10545	} else {
10546		ctsio->residual = 0;
10547		ctsio->kern_data_len = alloc_len;
10548		ctsio->kern_total_len = alloc_len;
10549	}
10550
10551	hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10552	if (format == 0) {
10553		scsi_ulto2b(0x12, hdr->data_length);
10554		hdr->first = 1;
10555		hdr->last = 1;
10556		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10557		descr->addr_ctl = 0x14;
10558		descr->track_number = 1;
10559		if (msf)
10560			ctl_ultomsf(0, descr->track_start);
10561		else
10562			scsi_ulto4b(0, descr->track_start);
10563		descr++;
10564		descr->addr_ctl = 0x14;
10565		descr->track_number = 0xaa;
10566		if (msf)
10567			ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10568		else
10569			scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10570	} else {
10571		scsi_ulto2b(0x0a, hdr->data_length);
10572		hdr->first = 1;
10573		hdr->last = 1;
10574		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10575		descr->addr_ctl = 0x14;
10576		descr->track_number = 1;
10577		if (msf)
10578			ctl_ultomsf(0, descr->track_start);
10579		else
10580			scsi_ulto4b(0, descr->track_start);
10581	}
10582
10583	ctl_set_success(ctsio);
10584	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10585	ctsio->be_move_done = ctl_config_move_done;
10586	ctl_datamove((union ctl_io *)ctsio);
10587	return (CTL_RETVAL_COMPLETE);
10588}
10589
10590/*
10591 * For known CDB types, parse the LBA and length.
10592 */
10593static int
10594ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10595{
10596	if (io->io_hdr.io_type != CTL_IO_SCSI)
10597		return (1);
10598
10599	switch (io->scsiio.cdb[0]) {
10600	case COMPARE_AND_WRITE: {
10601		struct scsi_compare_and_write *cdb;
10602
10603		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10604
10605		*lba = scsi_8btou64(cdb->addr);
10606		*len = cdb->length;
10607		break;
10608	}
10609	case READ_6:
10610	case WRITE_6: {
10611		struct scsi_rw_6 *cdb;
10612
10613		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10614
10615		*lba = scsi_3btoul(cdb->addr);
10616		/* only 5 bits are valid in the most significant address byte */
10617		*lba &= 0x1fffff;
10618		*len = cdb->length;
10619		break;
10620	}
10621	case READ_10:
10622	case WRITE_10: {
10623		struct scsi_rw_10 *cdb;
10624
10625		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10626
10627		*lba = scsi_4btoul(cdb->addr);
10628		*len = scsi_2btoul(cdb->length);
10629		break;
10630	}
10631	case WRITE_VERIFY_10: {
10632		struct scsi_write_verify_10 *cdb;
10633
10634		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10635
10636		*lba = scsi_4btoul(cdb->addr);
10637		*len = scsi_2btoul(cdb->length);
10638		break;
10639	}
10640	case READ_12:
10641	case WRITE_12: {
10642		struct scsi_rw_12 *cdb;
10643
10644		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10645
10646		*lba = scsi_4btoul(cdb->addr);
10647		*len = scsi_4btoul(cdb->length);
10648		break;
10649	}
10650	case WRITE_VERIFY_12: {
10651		struct scsi_write_verify_12 *cdb;
10652
10653		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10654
10655		*lba = scsi_4btoul(cdb->addr);
10656		*len = scsi_4btoul(cdb->length);
10657		break;
10658	}
10659	case READ_16:
10660	case WRITE_16: {
10661		struct scsi_rw_16 *cdb;
10662
10663		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10664
10665		*lba = scsi_8btou64(cdb->addr);
10666		*len = scsi_4btoul(cdb->length);
10667		break;
10668	}
10669	case WRITE_ATOMIC_16: {
10670		struct scsi_write_atomic_16 *cdb;
10671
10672		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10673
10674		*lba = scsi_8btou64(cdb->addr);
10675		*len = scsi_2btoul(cdb->length);
10676		break;
10677	}
10678	case WRITE_VERIFY_16: {
10679		struct scsi_write_verify_16 *cdb;
10680
10681		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10682
10683		*lba = scsi_8btou64(cdb->addr);
10684		*len = scsi_4btoul(cdb->length);
10685		break;
10686	}
10687	case WRITE_SAME_10: {
10688		struct scsi_write_same_10 *cdb;
10689
10690		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10691
10692		*lba = scsi_4btoul(cdb->addr);
10693		*len = scsi_2btoul(cdb->length);
10694		break;
10695	}
10696	case WRITE_SAME_16: {
10697		struct scsi_write_same_16 *cdb;
10698
10699		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10700
10701		*lba = scsi_8btou64(cdb->addr);
10702		*len = scsi_4btoul(cdb->length);
10703		break;
10704	}
10705	case VERIFY_10: {
10706		struct scsi_verify_10 *cdb;
10707
10708		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10709
10710		*lba = scsi_4btoul(cdb->addr);
10711		*len = scsi_2btoul(cdb->length);
10712		break;
10713	}
10714	case VERIFY_12: {
10715		struct scsi_verify_12 *cdb;
10716
10717		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10718
10719		*lba = scsi_4btoul(cdb->addr);
10720		*len = scsi_4btoul(cdb->length);
10721		break;
10722	}
10723	case VERIFY_16: {
10724		struct scsi_verify_16 *cdb;
10725
10726		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10727
10728		*lba = scsi_8btou64(cdb->addr);
10729		*len = scsi_4btoul(cdb->length);
10730		break;
10731	}
10732	case UNMAP: {
10733		*lba = 0;
10734		*len = UINT64_MAX;
10735		break;
10736	}
10737	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10738		struct scsi_get_lba_status *cdb;
10739
10740		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10741		*lba = scsi_8btou64(cdb->addr);
10742		*len = UINT32_MAX;
10743		break;
10744	}
10745	default:
10746		return (1);
10747		break; /* NOTREACHED */
10748	}
10749
10750	return (0);
10751}
10752
10753static ctl_action
10754ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10755    bool seq)
10756{
10757	uint64_t endlba1, endlba2;
10758
10759	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10760	endlba2 = lba2 + len2 - 1;
10761
10762	if ((endlba1 < lba2) || (endlba2 < lba1))
10763		return (CTL_ACTION_PASS);
10764	else
10765		return (CTL_ACTION_BLOCK);
10766}
10767
10768static int
10769ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10770{
10771	struct ctl_ptr_len_flags *ptrlen;
10772	struct scsi_unmap_desc *buf, *end, *range;
10773	uint64_t lba;
10774	uint32_t len;
10775
10776	/* If not UNMAP -- go other way. */
10777	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10778	    io->scsiio.cdb[0] != UNMAP)
10779		return (CTL_ACTION_ERROR);
10780
10781	/* If UNMAP without data -- block and wait for data. */
10782	ptrlen = (struct ctl_ptr_len_flags *)
10783	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10784	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10785	    ptrlen->ptr == NULL)
10786		return (CTL_ACTION_BLOCK);
10787
10788	/* UNMAP with data -- check for collision. */
10789	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10790	end = buf + ptrlen->len / sizeof(*buf);
10791	for (range = buf; range < end; range++) {
10792		lba = scsi_8btou64(range->lba);
10793		len = scsi_4btoul(range->length);
10794		if ((lba < lba2 + len2) && (lba + len > lba2))
10795			return (CTL_ACTION_BLOCK);
10796	}
10797	return (CTL_ACTION_PASS);
10798}
10799
10800static ctl_action
10801ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10802{
10803	uint64_t lba1, lba2;
10804	uint64_t len1, len2;
10805	int retval;
10806
10807	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10808		return (CTL_ACTION_ERROR);
10809
10810	retval = ctl_extent_check_unmap(io1, lba2, len2);
10811	if (retval != CTL_ACTION_ERROR)
10812		return (retval);
10813
10814	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10815		return (CTL_ACTION_ERROR);
10816
10817	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10818		seq = FALSE;
10819	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10820}
10821
10822static ctl_action
10823ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10824{
10825	uint64_t lba1, lba2;
10826	uint64_t len1, len2;
10827
10828	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10829		return (CTL_ACTION_PASS);
10830	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10831		return (CTL_ACTION_ERROR);
10832	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10833		return (CTL_ACTION_ERROR);
10834
10835	if (lba1 + len1 == lba2)
10836		return (CTL_ACTION_BLOCK);
10837	return (CTL_ACTION_PASS);
10838}
10839
10840static ctl_action
10841ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10842    union ctl_io *ooa_io)
10843{
10844	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10845	const ctl_serialize_action *serialize_row;
10846
10847	/*
10848	 * The initiator attempted multiple untagged commands at the same
10849	 * time.  Can't do that.
10850	 */
10851	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10852	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10853	 && ((pending_io->io_hdr.nexus.targ_port ==
10854	      ooa_io->io_hdr.nexus.targ_port)
10855	  && (pending_io->io_hdr.nexus.initid ==
10856	      ooa_io->io_hdr.nexus.initid))
10857	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10858	      CTL_FLAG_STATUS_SENT)) == 0))
10859		return (CTL_ACTION_OVERLAP);
10860
10861	/*
10862	 * The initiator attempted to send multiple tagged commands with
10863	 * the same ID.  (It's fine if different initiators have the same
10864	 * tag ID.)
10865	 *
10866	 * Even if all of those conditions are true, we don't kill the I/O
10867	 * if the command ahead of us has been aborted.  We won't end up
10868	 * sending it to the FETD, and it's perfectly legal to resend a
10869	 * command with the same tag number as long as the previous
10870	 * instance of this tag number has been aborted somehow.
10871	 */
10872	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10873	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10874	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10875	 && ((pending_io->io_hdr.nexus.targ_port ==
10876	      ooa_io->io_hdr.nexus.targ_port)
10877	  && (pending_io->io_hdr.nexus.initid ==
10878	      ooa_io->io_hdr.nexus.initid))
10879	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10880	      CTL_FLAG_STATUS_SENT)) == 0))
10881		return (CTL_ACTION_OVERLAP_TAG);
10882
10883	/*
10884	 * If we get a head of queue tag, SAM-3 says that we should
10885	 * immediately execute it.
10886	 *
10887	 * What happens if this command would normally block for some other
10888	 * reason?  e.g. a request sense with a head of queue tag
10889	 * immediately after a write.  Normally that would block, but this
10890	 * will result in its getting executed immediately...
10891	 *
10892	 * We currently return "pass" instead of "skip", so we'll end up
10893	 * going through the rest of the queue to check for overlapped tags.
10894	 *
10895	 * XXX KDM check for other types of blockage first??
10896	 */
10897	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10898		return (CTL_ACTION_PASS);
10899
10900	/*
10901	 * Ordered tags have to block until all items ahead of them
10902	 * have completed.  If we get called with an ordered tag, we always
10903	 * block, if something else is ahead of us in the queue.
10904	 */
10905	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10906		return (CTL_ACTION_BLOCK);
10907
10908	/*
10909	 * Simple tags get blocked until all head of queue and ordered tags
10910	 * ahead of them have completed.  I'm lumping untagged commands in
10911	 * with simple tags here.  XXX KDM is that the right thing to do?
10912	 */
10913	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10914	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10915	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10916	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10917		return (CTL_ACTION_BLOCK);
10918
10919	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10920	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10921
10922	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10923
10924	switch (serialize_row[pending_entry->seridx]) {
10925	case CTL_SER_BLOCK:
10926		return (CTL_ACTION_BLOCK);
10927	case CTL_SER_EXTENT:
10928		return (ctl_extent_check(ooa_io, pending_io,
10929		    (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10930	case CTL_SER_EXTENTOPT:
10931		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10932		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10933			return (ctl_extent_check(ooa_io, pending_io,
10934			    (lun->be_lun &&
10935			     lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10936		return (CTL_ACTION_PASS);
10937	case CTL_SER_EXTENTSEQ:
10938		if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
10939			return (ctl_extent_check_seq(ooa_io, pending_io));
10940		return (CTL_ACTION_PASS);
10941	case CTL_SER_PASS:
10942		return (CTL_ACTION_PASS);
10943	case CTL_SER_BLOCKOPT:
10944		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
10945		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
10946			return (CTL_ACTION_BLOCK);
10947		return (CTL_ACTION_PASS);
10948	case CTL_SER_SKIP:
10949		return (CTL_ACTION_SKIP);
10950	default:
10951		panic("invalid serialization value %d",
10952		      serialize_row[pending_entry->seridx]);
10953	}
10954
10955	return (CTL_ACTION_ERROR);
10956}
10957
10958/*
10959 * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10960 * Assumptions:
10961 * - pending_io is generally either incoming, or on the blocked queue
10962 * - starting I/O is the I/O we want to start the check with.
10963 */
10964static ctl_action
10965ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10966	      union ctl_io *starting_io)
10967{
10968	union ctl_io *ooa_io;
10969	ctl_action action;
10970
10971	mtx_assert(&lun->lun_lock, MA_OWNED);
10972
10973	/*
10974	 * Run back along the OOA queue, starting with the current
10975	 * blocked I/O and going through every I/O before it on the
10976	 * queue.  If starting_io is NULL, we'll just end up returning
10977	 * CTL_ACTION_PASS.
10978	 */
10979	for (ooa_io = starting_io; ooa_io != NULL;
10980	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10981	     ooa_links)){
10982
10983		/*
10984		 * This routine just checks to see whether
10985		 * cur_blocked is blocked by ooa_io, which is ahead
10986		 * of it in the queue.  It doesn't queue/dequeue
10987		 * cur_blocked.
10988		 */
10989		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10990		switch (action) {
10991		case CTL_ACTION_BLOCK:
10992		case CTL_ACTION_OVERLAP:
10993		case CTL_ACTION_OVERLAP_TAG:
10994		case CTL_ACTION_SKIP:
10995		case CTL_ACTION_ERROR:
10996			return (action);
10997			break; /* NOTREACHED */
10998		case CTL_ACTION_PASS:
10999			break;
11000		default:
11001			panic("invalid action %d", action);
11002			break;  /* NOTREACHED */
11003		}
11004	}
11005
11006	return (CTL_ACTION_PASS);
11007}
11008
11009/*
11010 * Assumptions:
11011 * - An I/O has just completed, and has been removed from the per-LUN OOA
11012 *   queue, so some items on the blocked queue may now be unblocked.
11013 */
11014static int
11015ctl_check_blocked(struct ctl_lun *lun)
11016{
11017	struct ctl_softc *softc = lun->ctl_softc;
11018	union ctl_io *cur_blocked, *next_blocked;
11019
11020	mtx_assert(&lun->lun_lock, MA_OWNED);
11021
11022	/*
11023	 * Run forward from the head of the blocked queue, checking each
11024	 * entry against the I/Os prior to it on the OOA queue to see if
11025	 * there is still any blockage.
11026	 *
11027	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11028	 * with our removing a variable on it while it is traversing the
11029	 * list.
11030	 */
11031	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11032	     cur_blocked != NULL; cur_blocked = next_blocked) {
11033		union ctl_io *prev_ooa;
11034		ctl_action action;
11035
11036		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11037							  blocked_links);
11038
11039		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11040						      ctl_ooaq, ooa_links);
11041
11042		/*
11043		 * If cur_blocked happens to be the first item in the OOA
11044		 * queue now, prev_ooa will be NULL, and the action
11045		 * returned will just be CTL_ACTION_PASS.
11046		 */
11047		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11048
11049		switch (action) {
11050		case CTL_ACTION_BLOCK:
11051			/* Nothing to do here, still blocked */
11052			break;
11053		case CTL_ACTION_OVERLAP:
11054		case CTL_ACTION_OVERLAP_TAG:
11055			/*
11056			 * This shouldn't happen!  In theory we've already
11057			 * checked this command for overlap...
11058			 */
11059			break;
11060		case CTL_ACTION_PASS:
11061		case CTL_ACTION_SKIP: {
11062			const struct ctl_cmd_entry *entry;
11063
11064			/*
11065			 * The skip case shouldn't happen, this transaction
11066			 * should have never made it onto the blocked queue.
11067			 */
11068			/*
11069			 * This I/O is no longer blocked, we can remove it
11070			 * from the blocked queue.  Since this is a TAILQ
11071			 * (doubly linked list), we can do O(1) removals
11072			 * from any place on the list.
11073			 */
11074			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11075				     blocked_links);
11076			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11077
11078			if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11079			    (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11080				/*
11081				 * Need to send IO back to original side to
11082				 * run
11083				 */
11084				union ctl_ha_msg msg_info;
11085
11086				cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11087				msg_info.hdr.original_sc =
11088					cur_blocked->io_hdr.original_sc;
11089				msg_info.hdr.serializing_sc = cur_blocked;
11090				msg_info.hdr.msg_type = CTL_MSG_R2R;
11091				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11092				    sizeof(msg_info.hdr), M_NOWAIT);
11093				break;
11094			}
11095			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11096
11097			/*
11098			 * Check this I/O for LUN state changes that may
11099			 * have happened while this command was blocked.
11100			 * The LUN state may have been changed by a command
11101			 * ahead of us in the queue, so we need to re-check
11102			 * for any states that can be caused by SCSI
11103			 * commands.
11104			 */
11105			if (ctl_scsiio_lun_check(lun, entry,
11106						 &cur_blocked->scsiio) == 0) {
11107				cur_blocked->io_hdr.flags |=
11108				                      CTL_FLAG_IS_WAS_ON_RTR;
11109				ctl_enqueue_rtr(cur_blocked);
11110			} else
11111				ctl_done(cur_blocked);
11112			break;
11113		}
11114		default:
11115			/*
11116			 * This probably shouldn't happen -- we shouldn't
11117			 * get CTL_ACTION_ERROR, or anything else.
11118			 */
11119			break;
11120		}
11121	}
11122
11123	return (CTL_RETVAL_COMPLETE);
11124}
11125
11126/*
11127 * This routine (with one exception) checks LUN flags that can be set by
11128 * commands ahead of us in the OOA queue.  These flags have to be checked
11129 * when a command initially comes in, and when we pull a command off the
11130 * blocked queue and are preparing to execute it.  The reason we have to
11131 * check these flags for commands on the blocked queue is that the LUN
11132 * state may have been changed by a command ahead of us while we're on the
11133 * blocked queue.
11134 *
11135 * Ordering is somewhat important with these checks, so please pay
11136 * careful attention to the placement of any new checks.
11137 */
11138static int
11139ctl_scsiio_lun_check(struct ctl_lun *lun,
11140    const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11141{
11142	struct ctl_softc *softc = lun->ctl_softc;
11143	int retval;
11144	uint32_t residx;
11145
11146	retval = 0;
11147
11148	mtx_assert(&lun->lun_lock, MA_OWNED);
11149
11150	/*
11151	 * If this shelf is a secondary shelf controller, we may have to
11152	 * reject some commands disallowed by HA mode and link state.
11153	 */
11154	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11155		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11156		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11157			ctl_set_lun_unavail(ctsio);
11158			retval = 1;
11159			goto bailout;
11160		}
11161		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11162		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11163			ctl_set_lun_transit(ctsio);
11164			retval = 1;
11165			goto bailout;
11166		}
11167		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11168		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11169			ctl_set_lun_standby(ctsio);
11170			retval = 1;
11171			goto bailout;
11172		}
11173
11174		/* The rest of checks are only done on executing side */
11175		if (softc->ha_mode == CTL_HA_MODE_XFER)
11176			goto bailout;
11177	}
11178
11179	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11180		if (lun->be_lun &&
11181		    lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11182			ctl_set_hw_write_protected(ctsio);
11183			retval = 1;
11184			goto bailout;
11185		}
11186		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11187		    .eca_and_aen & SCP_SWP) != 0) {
11188			ctl_set_sense(ctsio, /*current_error*/ 1,
11189			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11190			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11191			retval = 1;
11192			goto bailout;
11193		}
11194	}
11195
11196	/*
11197	 * Check for a reservation conflict.  If this command isn't allowed
11198	 * even on reserved LUNs, and if this initiator isn't the one who
11199	 * reserved us, reject the command with a reservation conflict.
11200	 */
11201	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11202	if ((lun->flags & CTL_LUN_RESERVED)
11203	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11204		if (lun->res_idx != residx) {
11205			ctl_set_reservation_conflict(ctsio);
11206			retval = 1;
11207			goto bailout;
11208		}
11209	}
11210
11211	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11212	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11213		/* No reservation or command is allowed. */;
11214	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11215	    (lun->res_type == SPR_TYPE_WR_EX ||
11216	     lun->res_type == SPR_TYPE_WR_EX_RO ||
11217	     lun->res_type == SPR_TYPE_WR_EX_AR)) {
11218		/* The command is allowed for Write Exclusive resv. */;
11219	} else {
11220		/*
11221		 * if we aren't registered or it's a res holder type
11222		 * reservation and this isn't the res holder then set a
11223		 * conflict.
11224		 */
11225		if (ctl_get_prkey(lun, residx) == 0
11226		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11227			ctl_set_reservation_conflict(ctsio);
11228			retval = 1;
11229			goto bailout;
11230		}
11231	}
11232
11233	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11234		if (lun->flags & CTL_LUN_EJECTED)
11235			ctl_set_lun_ejected(ctsio);
11236		else if (lun->flags & CTL_LUN_NO_MEDIA) {
11237			if (lun->flags & CTL_LUN_REMOVABLE)
11238				ctl_set_lun_no_media(ctsio);
11239			else
11240				ctl_set_lun_int_reqd(ctsio);
11241		} else if (lun->flags & CTL_LUN_STOPPED)
11242			ctl_set_lun_stopped(ctsio);
11243		else
11244			goto bailout;
11245		retval = 1;
11246		goto bailout;
11247	}
11248
11249bailout:
11250	return (retval);
11251}
11252
11253static void
11254ctl_failover_io(union ctl_io *io, int have_lock)
11255{
11256	ctl_set_busy(&io->scsiio);
11257	ctl_done(io);
11258}
11259
11260static void
11261ctl_failover_lun(union ctl_io *rio)
11262{
11263	struct ctl_softc *softc = control_softc;
11264	struct ctl_lun *lun;
11265	struct ctl_io_hdr *io, *next_io;
11266	uint32_t targ_lun;
11267
11268	targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11269	CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", targ_lun));
11270
11271	/* Find and lock the LUN. */
11272	mtx_lock(&softc->ctl_lock);
11273	if ((targ_lun < CTL_MAX_LUNS) &&
11274	    ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11275		mtx_lock(&lun->lun_lock);
11276		mtx_unlock(&softc->ctl_lock);
11277		if (lun->flags & CTL_LUN_DISABLED) {
11278			mtx_unlock(&lun->lun_lock);
11279			return;
11280		}
11281	} else {
11282		mtx_unlock(&softc->ctl_lock);
11283		return;
11284	}
11285
11286	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11287		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11288			/* We are master */
11289			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11290				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11291					io->flags |= CTL_FLAG_ABORT;
11292					io->flags |= CTL_FLAG_FAILOVER;
11293				} else { /* This can be only due to DATAMOVE */
11294					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11295					io->flags &= ~CTL_FLAG_DMA_INPROG;
11296					io->flags |= CTL_FLAG_IO_ACTIVE;
11297					io->port_status = 31340;
11298					ctl_enqueue_isc((union ctl_io *)io);
11299				}
11300			}
11301			/* We are slave */
11302			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11303				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11304				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11305					io->flags |= CTL_FLAG_FAILOVER;
11306				} else {
11307					ctl_set_busy(&((union ctl_io *)io)->
11308					    scsiio);
11309					ctl_done((union ctl_io *)io);
11310				}
11311			}
11312		}
11313	} else { /* SERIALIZE modes */
11314		TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11315		    next_io) {
11316			/* We are master */
11317			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11318				TAILQ_REMOVE(&lun->blocked_queue, io,
11319				    blocked_links);
11320				io->flags &= ~CTL_FLAG_BLOCKED;
11321				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11322				ctl_free_io((union ctl_io *)io);
11323			}
11324		}
11325		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11326			/* We are master */
11327			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11328				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11329				ctl_free_io((union ctl_io *)io);
11330			}
11331			/* We are slave */
11332			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11333				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11334				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11335					ctl_set_busy(&((union ctl_io *)io)->
11336					    scsiio);
11337					ctl_done((union ctl_io *)io);
11338				}
11339			}
11340		}
11341		ctl_check_blocked(lun);
11342	}
11343	mtx_unlock(&lun->lun_lock);
11344}
11345
11346static int
11347ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11348{
11349	struct ctl_lun *lun;
11350	const struct ctl_cmd_entry *entry;
11351	uint32_t initidx, targ_lun;
11352	int retval;
11353
11354	retval = 0;
11355
11356	lun = NULL;
11357
11358	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11359	if ((targ_lun < CTL_MAX_LUNS)
11360	 && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11361		/*
11362		 * If the LUN is invalid, pretend that it doesn't exist.
11363		 * It will go away as soon as all pending I/O has been
11364		 * completed.
11365		 */
11366		mtx_lock(&lun->lun_lock);
11367		if (lun->flags & CTL_LUN_DISABLED) {
11368			mtx_unlock(&lun->lun_lock);
11369			lun = NULL;
11370			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11371			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11372		} else {
11373			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11374			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11375				lun->be_lun;
11376
11377			/*
11378			 * Every I/O goes into the OOA queue for a
11379			 * particular LUN, and stays there until completion.
11380			 */
11381#ifdef CTL_TIME_IO
11382			if (TAILQ_EMPTY(&lun->ooa_queue)) {
11383				lun->idle_time += getsbinuptime() -
11384				    lun->last_busy;
11385			}
11386#endif
11387			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11388			    ooa_links);
11389		}
11390	} else {
11391		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11392		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11393	}
11394
11395	/* Get command entry and return error if it is unsuppotyed. */
11396	entry = ctl_validate_command(ctsio);
11397	if (entry == NULL) {
11398		if (lun)
11399			mtx_unlock(&lun->lun_lock);
11400		return (retval);
11401	}
11402
11403	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11404	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11405
11406	/*
11407	 * Check to see whether we can send this command to LUNs that don't
11408	 * exist.  This should pretty much only be the case for inquiry
11409	 * and request sense.  Further checks, below, really require having
11410	 * a LUN, so we can't really check the command anymore.  Just put
11411	 * it on the rtr queue.
11412	 */
11413	if (lun == NULL) {
11414		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11415			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11416			ctl_enqueue_rtr((union ctl_io *)ctsio);
11417			return (retval);
11418		}
11419
11420		ctl_set_unsupported_lun(ctsio);
11421		ctl_done((union ctl_io *)ctsio);
11422		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11423		return (retval);
11424	} else {
11425		/*
11426		 * Make sure we support this particular command on this LUN.
11427		 * e.g., we don't support writes to the control LUN.
11428		 */
11429		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11430			mtx_unlock(&lun->lun_lock);
11431			ctl_set_invalid_opcode(ctsio);
11432			ctl_done((union ctl_io *)ctsio);
11433			return (retval);
11434		}
11435	}
11436
11437	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11438
11439#ifdef CTL_WITH_CA
11440	/*
11441	 * If we've got a request sense, it'll clear the contingent
11442	 * allegiance condition.  Otherwise, if we have a CA condition for
11443	 * this initiator, clear it, because it sent down a command other
11444	 * than request sense.
11445	 */
11446	if ((ctsio->cdb[0] != REQUEST_SENSE)
11447	 && (ctl_is_set(lun->have_ca, initidx)))
11448		ctl_clear_mask(lun->have_ca, initidx);
11449#endif
11450
11451	/*
11452	 * If the command has this flag set, it handles its own unit
11453	 * attention reporting, we shouldn't do anything.  Otherwise we
11454	 * check for any pending unit attentions, and send them back to the
11455	 * initiator.  We only do this when a command initially comes in,
11456	 * not when we pull it off the blocked queue.
11457	 *
11458	 * According to SAM-3, section 5.3.2, the order that things get
11459	 * presented back to the host is basically unit attentions caused
11460	 * by some sort of reset event, busy status, reservation conflicts
11461	 * or task set full, and finally any other status.
11462	 *
11463	 * One issue here is that some of the unit attentions we report
11464	 * don't fall into the "reset" category (e.g. "reported luns data
11465	 * has changed").  So reporting it here, before the reservation
11466	 * check, may be technically wrong.  I guess the only thing to do
11467	 * would be to check for and report the reset events here, and then
11468	 * check for the other unit attention types after we check for a
11469	 * reservation conflict.
11470	 *
11471	 * XXX KDM need to fix this
11472	 */
11473	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11474		ctl_ua_type ua_type;
11475
11476		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11477		    SSD_TYPE_NONE);
11478		if (ua_type != CTL_UA_NONE) {
11479			mtx_unlock(&lun->lun_lock);
11480			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11481			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11482			ctsio->sense_len = SSD_FULL_SIZE;
11483			ctl_done((union ctl_io *)ctsio);
11484			return (retval);
11485		}
11486	}
11487
11488
11489	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11490		mtx_unlock(&lun->lun_lock);
11491		ctl_done((union ctl_io *)ctsio);
11492		return (retval);
11493	}
11494
11495	/*
11496	 * XXX CHD this is where we want to send IO to other side if
11497	 * this LUN is secondary on this SC. We will need to make a copy
11498	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11499	 * the copy we send as FROM_OTHER.
11500	 * We also need to stuff the address of the original IO so we can
11501	 * find it easily. Something similar will need be done on the other
11502	 * side so when we are done we can find the copy.
11503	 */
11504	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11505	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11506	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11507		union ctl_ha_msg msg_info;
11508		int isc_retval;
11509
11510		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11511		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11512		mtx_unlock(&lun->lun_lock);
11513
11514		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11515		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11516		msg_info.hdr.serializing_sc = NULL;
11517		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11518		msg_info.scsi.tag_num = ctsio->tag_num;
11519		msg_info.scsi.tag_type = ctsio->tag_type;
11520		msg_info.scsi.cdb_len = ctsio->cdb_len;
11521		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11522
11523		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11524		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11525		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11526			ctl_set_busy(ctsio);
11527			ctl_done((union ctl_io *)ctsio);
11528			return (retval);
11529		}
11530		return (retval);
11531	}
11532
11533	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11534			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11535			      ctl_ooaq, ooa_links))) {
11536	case CTL_ACTION_BLOCK:
11537		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11538		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11539				  blocked_links);
11540		mtx_unlock(&lun->lun_lock);
11541		return (retval);
11542	case CTL_ACTION_PASS:
11543	case CTL_ACTION_SKIP:
11544		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11545		mtx_unlock(&lun->lun_lock);
11546		ctl_enqueue_rtr((union ctl_io *)ctsio);
11547		break;
11548	case CTL_ACTION_OVERLAP:
11549		mtx_unlock(&lun->lun_lock);
11550		ctl_set_overlapped_cmd(ctsio);
11551		ctl_done((union ctl_io *)ctsio);
11552		break;
11553	case CTL_ACTION_OVERLAP_TAG:
11554		mtx_unlock(&lun->lun_lock);
11555		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11556		ctl_done((union ctl_io *)ctsio);
11557		break;
11558	case CTL_ACTION_ERROR:
11559	default:
11560		mtx_unlock(&lun->lun_lock);
11561		ctl_set_internal_failure(ctsio,
11562					 /*sks_valid*/ 0,
11563					 /*retry_count*/ 0);
11564		ctl_done((union ctl_io *)ctsio);
11565		break;
11566	}
11567	return (retval);
11568}
11569
11570const struct ctl_cmd_entry *
11571ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11572{
11573	const struct ctl_cmd_entry *entry;
11574	int service_action;
11575
11576	entry = &ctl_cmd_table[ctsio->cdb[0]];
11577	if (sa)
11578		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11579	if (entry->flags & CTL_CMD_FLAG_SA5) {
11580		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11581		entry = &((const struct ctl_cmd_entry *)
11582		    entry->execute)[service_action];
11583	}
11584	return (entry);
11585}
11586
11587const struct ctl_cmd_entry *
11588ctl_validate_command(struct ctl_scsiio *ctsio)
11589{
11590	const struct ctl_cmd_entry *entry;
11591	int i, sa;
11592	uint8_t diff;
11593
11594	entry = ctl_get_cmd_entry(ctsio, &sa);
11595	if (entry->execute == NULL) {
11596		if (sa)
11597			ctl_set_invalid_field(ctsio,
11598					      /*sks_valid*/ 1,
11599					      /*command*/ 1,
11600					      /*field*/ 1,
11601					      /*bit_valid*/ 1,
11602					      /*bit*/ 4);
11603		else
11604			ctl_set_invalid_opcode(ctsio);
11605		ctl_done((union ctl_io *)ctsio);
11606		return (NULL);
11607	}
11608	KASSERT(entry->length > 0,
11609	    ("Not defined length for command 0x%02x/0x%02x",
11610	     ctsio->cdb[0], ctsio->cdb[1]));
11611	for (i = 1; i < entry->length; i++) {
11612		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11613		if (diff == 0)
11614			continue;
11615		ctl_set_invalid_field(ctsio,
11616				      /*sks_valid*/ 1,
11617				      /*command*/ 1,
11618				      /*field*/ i,
11619				      /*bit_valid*/ 1,
11620				      /*bit*/ fls(diff) - 1);
11621		ctl_done((union ctl_io *)ctsio);
11622		return (NULL);
11623	}
11624	return (entry);
11625}
11626
11627static int
11628ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11629{
11630
11631	switch (lun_type) {
11632	case T_DIRECT:
11633		if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11634			return (0);
11635		break;
11636	case T_PROCESSOR:
11637		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11638			return (0);
11639		break;
11640	case T_CDROM:
11641		if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11642			return (0);
11643		break;
11644	default:
11645		return (0);
11646	}
11647	return (1);
11648}
11649
11650static int
11651ctl_scsiio(struct ctl_scsiio *ctsio)
11652{
11653	int retval;
11654	const struct ctl_cmd_entry *entry;
11655
11656	retval = CTL_RETVAL_COMPLETE;
11657
11658	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11659
11660	entry = ctl_get_cmd_entry(ctsio, NULL);
11661
11662	/*
11663	 * If this I/O has been aborted, just send it straight to
11664	 * ctl_done() without executing it.
11665	 */
11666	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11667		ctl_done((union ctl_io *)ctsio);
11668		goto bailout;
11669	}
11670
11671	/*
11672	 * All the checks should have been handled by ctl_scsiio_precheck().
11673	 * We should be clear now to just execute the I/O.
11674	 */
11675	retval = entry->execute(ctsio);
11676
11677bailout:
11678	return (retval);
11679}
11680
11681/*
11682 * Since we only implement one target right now, a bus reset simply resets
11683 * our single target.
11684 */
11685static int
11686ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11687{
11688	return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11689}
11690
11691static int
11692ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11693		 ctl_ua_type ua_type)
11694{
11695	struct ctl_port *port;
11696	struct ctl_lun *lun;
11697	int retval;
11698
11699	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11700		union ctl_ha_msg msg_info;
11701
11702		msg_info.hdr.nexus = io->io_hdr.nexus;
11703		if (ua_type==CTL_UA_TARG_RESET)
11704			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11705		else
11706			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11707		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11708		msg_info.hdr.original_sc = NULL;
11709		msg_info.hdr.serializing_sc = NULL;
11710		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11711		    sizeof(msg_info.task), M_WAITOK);
11712	}
11713	retval = 0;
11714
11715	mtx_lock(&softc->ctl_lock);
11716	port = ctl_io_port(&io->io_hdr);
11717	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11718		if (port != NULL &&
11719		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
11720			continue;
11721		retval += ctl_do_lun_reset(lun, io, ua_type);
11722	}
11723	mtx_unlock(&softc->ctl_lock);
11724	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11725	return (retval);
11726}
11727
11728/*
11729 * The LUN should always be set.  The I/O is optional, and is used to
11730 * distinguish between I/Os sent by this initiator, and by other
11731 * initiators.  We set unit attention for initiators other than this one.
11732 * SAM-3 is vague on this point.  It does say that a unit attention should
11733 * be established for other initiators when a LUN is reset (see section
11734 * 5.7.3), but it doesn't specifically say that the unit attention should
11735 * be established for this particular initiator when a LUN is reset.  Here
11736 * is the relevant text, from SAM-3 rev 8:
11737 *
11738 * 5.7.2 When a SCSI initiator port aborts its own tasks
11739 *
11740 * When a SCSI initiator port causes its own task(s) to be aborted, no
11741 * notification that the task(s) have been aborted shall be returned to
11742 * the SCSI initiator port other than the completion response for the
11743 * command or task management function action that caused the task(s) to
11744 * be aborted and notification(s) associated with related effects of the
11745 * action (e.g., a reset unit attention condition).
11746 *
11747 * XXX KDM for now, we're setting unit attention for all initiators.
11748 */
11749static int
11750ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11751{
11752	union ctl_io *xio;
11753#if 0
11754	uint32_t initidx;
11755#endif
11756#ifdef CTL_WITH_CA
11757	int i;
11758#endif
11759
11760	mtx_lock(&lun->lun_lock);
11761	/*
11762	 * Run through the OOA queue and abort each I/O.
11763	 */
11764	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11765	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11766		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11767	}
11768
11769	/*
11770	 * This version sets unit attention for every
11771	 */
11772#if 0
11773	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11774	ctl_est_ua_all(lun, initidx, ua_type);
11775#else
11776	ctl_est_ua_all(lun, -1, ua_type);
11777#endif
11778
11779	/*
11780	 * A reset (any kind, really) clears reservations established with
11781	 * RESERVE/RELEASE.  It does not clear reservations established
11782	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11783	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11784	 * reservations made with the RESERVE/RELEASE commands, because
11785	 * those commands are obsolete in SPC-3.
11786	 */
11787	lun->flags &= ~CTL_LUN_RESERVED;
11788
11789#ifdef CTL_WITH_CA
11790	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11791		ctl_clear_mask(lun->have_ca, i);
11792#endif
11793	mtx_unlock(&lun->lun_lock);
11794
11795	return (0);
11796}
11797
11798static int
11799ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
11800{
11801	struct ctl_lun *lun;
11802	uint32_t targ_lun;
11803	int retval;
11804
11805	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11806	mtx_lock(&softc->ctl_lock);
11807	if ((targ_lun >= CTL_MAX_LUNS) ||
11808	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11809		mtx_unlock(&softc->ctl_lock);
11810		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11811		return (1);
11812	}
11813	retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
11814	mtx_unlock(&softc->ctl_lock);
11815	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11816
11817	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11818		union ctl_ha_msg msg_info;
11819
11820		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11821		msg_info.hdr.nexus = io->io_hdr.nexus;
11822		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11823		msg_info.hdr.original_sc = NULL;
11824		msg_info.hdr.serializing_sc = NULL;
11825		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11826		    sizeof(msg_info.task), M_WAITOK);
11827	}
11828	return (retval);
11829}
11830
11831static void
11832ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11833    int other_sc)
11834{
11835	union ctl_io *xio;
11836
11837	mtx_assert(&lun->lun_lock, MA_OWNED);
11838
11839	/*
11840	 * Run through the OOA queue and attempt to find the given I/O.
11841	 * The target port, initiator ID, tag type and tag number have to
11842	 * match the values that we got from the initiator.  If we have an
11843	 * untagged command to abort, simply abort the first untagged command
11844	 * we come to.  We only allow one untagged command at a time of course.
11845	 */
11846	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11847	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11848
11849		if ((targ_port == UINT32_MAX ||
11850		     targ_port == xio->io_hdr.nexus.targ_port) &&
11851		    (init_id == UINT32_MAX ||
11852		     init_id == xio->io_hdr.nexus.initid)) {
11853			if (targ_port != xio->io_hdr.nexus.targ_port ||
11854			    init_id != xio->io_hdr.nexus.initid)
11855				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11856			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11857			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11858				union ctl_ha_msg msg_info;
11859
11860				msg_info.hdr.nexus = xio->io_hdr.nexus;
11861				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11862				msg_info.task.tag_num = xio->scsiio.tag_num;
11863				msg_info.task.tag_type = xio->scsiio.tag_type;
11864				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11865				msg_info.hdr.original_sc = NULL;
11866				msg_info.hdr.serializing_sc = NULL;
11867				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11868				    sizeof(msg_info.task), M_NOWAIT);
11869			}
11870		}
11871	}
11872}
11873
11874static int
11875ctl_abort_task_set(union ctl_io *io)
11876{
11877	struct ctl_softc *softc = control_softc;
11878	struct ctl_lun *lun;
11879	uint32_t targ_lun;
11880
11881	/*
11882	 * Look up the LUN.
11883	 */
11884	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11885	mtx_lock(&softc->ctl_lock);
11886	if ((targ_lun >= CTL_MAX_LUNS) ||
11887	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11888		mtx_unlock(&softc->ctl_lock);
11889		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11890		return (1);
11891	}
11892
11893	mtx_lock(&lun->lun_lock);
11894	mtx_unlock(&softc->ctl_lock);
11895	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11896		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11897		    io->io_hdr.nexus.initid,
11898		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11899	} else { /* CTL_TASK_CLEAR_TASK_SET */
11900		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11901		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11902	}
11903	mtx_unlock(&lun->lun_lock);
11904	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11905	return (0);
11906}
11907
11908static int
11909ctl_i_t_nexus_reset(union ctl_io *io)
11910{
11911	struct ctl_softc *softc = control_softc;
11912	struct ctl_lun *lun;
11913	uint32_t initidx;
11914
11915	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11916		union ctl_ha_msg msg_info;
11917
11918		msg_info.hdr.nexus = io->io_hdr.nexus;
11919		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
11920		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11921		msg_info.hdr.original_sc = NULL;
11922		msg_info.hdr.serializing_sc = NULL;
11923		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11924		    sizeof(msg_info.task), M_WAITOK);
11925	}
11926
11927	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11928	mtx_lock(&softc->ctl_lock);
11929	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11930		mtx_lock(&lun->lun_lock);
11931		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11932		    io->io_hdr.nexus.initid, 1);
11933#ifdef CTL_WITH_CA
11934		ctl_clear_mask(lun->have_ca, initidx);
11935#endif
11936		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
11937			lun->flags &= ~CTL_LUN_RESERVED;
11938		ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
11939		mtx_unlock(&lun->lun_lock);
11940	}
11941	mtx_unlock(&softc->ctl_lock);
11942	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11943	return (0);
11944}
11945
11946static int
11947ctl_abort_task(union ctl_io *io)
11948{
11949	union ctl_io *xio;
11950	struct ctl_lun *lun;
11951	struct ctl_softc *softc;
11952#if 0
11953	struct sbuf sb;
11954	char printbuf[128];
11955#endif
11956	int found;
11957	uint32_t targ_lun;
11958
11959	softc = control_softc;
11960	found = 0;
11961
11962	/*
11963	 * Look up the LUN.
11964	 */
11965	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11966	mtx_lock(&softc->ctl_lock);
11967	if ((targ_lun >= CTL_MAX_LUNS) ||
11968	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11969		mtx_unlock(&softc->ctl_lock);
11970		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11971		return (1);
11972	}
11973
11974#if 0
11975	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11976	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11977#endif
11978
11979	mtx_lock(&lun->lun_lock);
11980	mtx_unlock(&softc->ctl_lock);
11981	/*
11982	 * Run through the OOA queue and attempt to find the given I/O.
11983	 * The target port, initiator ID, tag type and tag number have to
11984	 * match the values that we got from the initiator.  If we have an
11985	 * untagged command to abort, simply abort the first untagged command
11986	 * we come to.  We only allow one untagged command at a time of course.
11987	 */
11988	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11989	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11990#if 0
11991		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
11992
11993		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
11994			    lun->lun, xio->scsiio.tag_num,
11995			    xio->scsiio.tag_type,
11996			    (xio->io_hdr.blocked_links.tqe_prev
11997			    == NULL) ? "" : " BLOCKED",
11998			    (xio->io_hdr.flags &
11999			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12000			    (xio->io_hdr.flags &
12001			    CTL_FLAG_ABORT) ? " ABORT" : "",
12002			    (xio->io_hdr.flags &
12003			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12004		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12005		sbuf_finish(&sb);
12006		printf("%s\n", sbuf_data(&sb));
12007#endif
12008
12009		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12010		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12011		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12012			continue;
12013
12014		/*
12015		 * If the abort says that the task is untagged, the
12016		 * task in the queue must be untagged.  Otherwise,
12017		 * we just check to see whether the tag numbers
12018		 * match.  This is because the QLogic firmware
12019		 * doesn't pass back the tag type in an abort
12020		 * request.
12021		 */
12022#if 0
12023		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12024		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12025		 || (xio->scsiio.tag_num == io->taskio.tag_num))
12026#endif
12027		/*
12028		 * XXX KDM we've got problems with FC, because it
12029		 * doesn't send down a tag type with aborts.  So we
12030		 * can only really go by the tag number...
12031		 * This may cause problems with parallel SCSI.
12032		 * Need to figure that out!!
12033		 */
12034		if (xio->scsiio.tag_num == io->taskio.tag_num) {
12035			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12036			found = 1;
12037			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12038			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12039				union ctl_ha_msg msg_info;
12040
12041				msg_info.hdr.nexus = io->io_hdr.nexus;
12042				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12043				msg_info.task.tag_num = io->taskio.tag_num;
12044				msg_info.task.tag_type = io->taskio.tag_type;
12045				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12046				msg_info.hdr.original_sc = NULL;
12047				msg_info.hdr.serializing_sc = NULL;
12048#if 0
12049				printf("Sent Abort to other side\n");
12050#endif
12051				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12052				    sizeof(msg_info.task), M_NOWAIT);
12053			}
12054#if 0
12055			printf("ctl_abort_task: found I/O to abort\n");
12056#endif
12057		}
12058	}
12059	mtx_unlock(&lun->lun_lock);
12060
12061	if (found == 0) {
12062		/*
12063		 * This isn't really an error.  It's entirely possible for
12064		 * the abort and command completion to cross on the wire.
12065		 * This is more of an informative/diagnostic error.
12066		 */
12067#if 0
12068		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12069		       "%u:%u:%u tag %d type %d\n",
12070		       io->io_hdr.nexus.initid,
12071		       io->io_hdr.nexus.targ_port,
12072		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12073		       io->taskio.tag_type);
12074#endif
12075	}
12076	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12077	return (0);
12078}
12079
12080static int
12081ctl_query_task(union ctl_io *io, int task_set)
12082{
12083	union ctl_io *xio;
12084	struct ctl_lun *lun;
12085	struct ctl_softc *softc;
12086	int found = 0;
12087	uint32_t targ_lun;
12088
12089	softc = control_softc;
12090	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12091	mtx_lock(&softc->ctl_lock);
12092	if ((targ_lun >= CTL_MAX_LUNS) ||
12093	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12094		mtx_unlock(&softc->ctl_lock);
12095		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12096		return (1);
12097	}
12098	mtx_lock(&lun->lun_lock);
12099	mtx_unlock(&softc->ctl_lock);
12100	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12101	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12102
12103		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12104		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12105		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12106			continue;
12107
12108		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12109			found = 1;
12110			break;
12111		}
12112	}
12113	mtx_unlock(&lun->lun_lock);
12114	if (found)
12115		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12116	else
12117		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12118	return (0);
12119}
12120
12121static int
12122ctl_query_async_event(union ctl_io *io)
12123{
12124	struct ctl_lun *lun;
12125	struct ctl_softc *softc;
12126	ctl_ua_type ua;
12127	uint32_t targ_lun, initidx;
12128
12129	softc = control_softc;
12130	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12131	mtx_lock(&softc->ctl_lock);
12132	if ((targ_lun >= CTL_MAX_LUNS) ||
12133	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12134		mtx_unlock(&softc->ctl_lock);
12135		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12136		return (1);
12137	}
12138	mtx_lock(&lun->lun_lock);
12139	mtx_unlock(&softc->ctl_lock);
12140	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12141	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12142	mtx_unlock(&lun->lun_lock);
12143	if (ua != CTL_UA_NONE)
12144		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12145	else
12146		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12147	return (0);
12148}
12149
12150static void
12151ctl_run_task(union ctl_io *io)
12152{
12153	struct ctl_softc *softc = control_softc;
12154	int retval = 1;
12155
12156	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12157	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12158	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12159	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12160	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12161	switch (io->taskio.task_action) {
12162	case CTL_TASK_ABORT_TASK:
12163		retval = ctl_abort_task(io);
12164		break;
12165	case CTL_TASK_ABORT_TASK_SET:
12166	case CTL_TASK_CLEAR_TASK_SET:
12167		retval = ctl_abort_task_set(io);
12168		break;
12169	case CTL_TASK_CLEAR_ACA:
12170		break;
12171	case CTL_TASK_I_T_NEXUS_RESET:
12172		retval = ctl_i_t_nexus_reset(io);
12173		break;
12174	case CTL_TASK_LUN_RESET:
12175		retval = ctl_lun_reset(softc, io);
12176		break;
12177	case CTL_TASK_TARGET_RESET:
12178		retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12179		break;
12180	case CTL_TASK_BUS_RESET:
12181		retval = ctl_bus_reset(softc, io);
12182		break;
12183	case CTL_TASK_PORT_LOGIN:
12184		break;
12185	case CTL_TASK_PORT_LOGOUT:
12186		break;
12187	case CTL_TASK_QUERY_TASK:
12188		retval = ctl_query_task(io, 0);
12189		break;
12190	case CTL_TASK_QUERY_TASK_SET:
12191		retval = ctl_query_task(io, 1);
12192		break;
12193	case CTL_TASK_QUERY_ASYNC_EVENT:
12194		retval = ctl_query_async_event(io);
12195		break;
12196	default:
12197		printf("%s: got unknown task management event %d\n",
12198		       __func__, io->taskio.task_action);
12199		break;
12200	}
12201	if (retval == 0)
12202		io->io_hdr.status = CTL_SUCCESS;
12203	else
12204		io->io_hdr.status = CTL_ERROR;
12205	ctl_done(io);
12206}
12207
12208/*
12209 * For HA operation.  Handle commands that come in from the other
12210 * controller.
12211 */
12212static void
12213ctl_handle_isc(union ctl_io *io)
12214{
12215	int free_io;
12216	struct ctl_lun *lun;
12217	struct ctl_softc *softc = control_softc;
12218	uint32_t targ_lun;
12219
12220	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12221	lun = softc->ctl_luns[targ_lun];
12222
12223	switch (io->io_hdr.msg_type) {
12224	case CTL_MSG_SERIALIZE:
12225		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12226		break;
12227	case CTL_MSG_R2R: {
12228		const struct ctl_cmd_entry *entry;
12229
12230		/*
12231		 * This is only used in SER_ONLY mode.
12232		 */
12233		free_io = 0;
12234		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12235		mtx_lock(&lun->lun_lock);
12236		if (ctl_scsiio_lun_check(lun,
12237		    entry, (struct ctl_scsiio *)io) != 0) {
12238			mtx_unlock(&lun->lun_lock);
12239			ctl_done(io);
12240			break;
12241		}
12242		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12243		mtx_unlock(&lun->lun_lock);
12244		ctl_enqueue_rtr(io);
12245		break;
12246	}
12247	case CTL_MSG_FINISH_IO:
12248		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12249			free_io = 0;
12250			ctl_done(io);
12251		} else {
12252			free_io = 1;
12253			mtx_lock(&lun->lun_lock);
12254			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12255				     ooa_links);
12256			ctl_check_blocked(lun);
12257			mtx_unlock(&lun->lun_lock);
12258		}
12259		break;
12260	case CTL_MSG_PERS_ACTION:
12261		ctl_hndl_per_res_out_on_other_sc(
12262			(union ctl_ha_msg *)&io->presio.pr_msg);
12263		free_io = 1;
12264		break;
12265	case CTL_MSG_BAD_JUJU:
12266		free_io = 0;
12267		ctl_done(io);
12268		break;
12269	case CTL_MSG_DATAMOVE:
12270		/* Only used in XFER mode */
12271		free_io = 0;
12272		ctl_datamove_remote(io);
12273		break;
12274	case CTL_MSG_DATAMOVE_DONE:
12275		/* Only used in XFER mode */
12276		free_io = 0;
12277		io->scsiio.be_move_done(io);
12278		break;
12279	case CTL_MSG_FAILOVER:
12280		ctl_failover_lun(io);
12281		free_io = 1;
12282		break;
12283	default:
12284		free_io = 1;
12285		printf("%s: Invalid message type %d\n",
12286		       __func__, io->io_hdr.msg_type);
12287		break;
12288	}
12289	if (free_io)
12290		ctl_free_io(io);
12291
12292}
12293
12294
12295/*
12296 * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12297 * there is no match.
12298 */
12299static ctl_lun_error_pattern
12300ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12301{
12302	const struct ctl_cmd_entry *entry;
12303	ctl_lun_error_pattern filtered_pattern, pattern;
12304
12305	pattern = desc->error_pattern;
12306
12307	/*
12308	 * XXX KDM we need more data passed into this function to match a
12309	 * custom pattern, and we actually need to implement custom pattern
12310	 * matching.
12311	 */
12312	if (pattern & CTL_LUN_PAT_CMD)
12313		return (CTL_LUN_PAT_CMD);
12314
12315	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12316		return (CTL_LUN_PAT_ANY);
12317
12318	entry = ctl_get_cmd_entry(ctsio, NULL);
12319
12320	filtered_pattern = entry->pattern & pattern;
12321
12322	/*
12323	 * If the user requested specific flags in the pattern (e.g.
12324	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12325	 * flags.
12326	 *
12327	 * If the user did not specify any flags, it doesn't matter whether
12328	 * or not the command supports the flags.
12329	 */
12330	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12331	     (pattern & ~CTL_LUN_PAT_MASK))
12332		return (CTL_LUN_PAT_NONE);
12333
12334	/*
12335	 * If the user asked for a range check, see if the requested LBA
12336	 * range overlaps with this command's LBA range.
12337	 */
12338	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12339		uint64_t lba1;
12340		uint64_t len1;
12341		ctl_action action;
12342		int retval;
12343
12344		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12345		if (retval != 0)
12346			return (CTL_LUN_PAT_NONE);
12347
12348		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12349					      desc->lba_range.len, FALSE);
12350		/*
12351		 * A "pass" means that the LBA ranges don't overlap, so
12352		 * this doesn't match the user's range criteria.
12353		 */
12354		if (action == CTL_ACTION_PASS)
12355			return (CTL_LUN_PAT_NONE);
12356	}
12357
12358	return (filtered_pattern);
12359}
12360
12361static void
12362ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12363{
12364	struct ctl_error_desc *desc, *desc2;
12365
12366	mtx_assert(&lun->lun_lock, MA_OWNED);
12367
12368	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12369		ctl_lun_error_pattern pattern;
12370		/*
12371		 * Check to see whether this particular command matches
12372		 * the pattern in the descriptor.
12373		 */
12374		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12375		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12376			continue;
12377
12378		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12379		case CTL_LUN_INJ_ABORTED:
12380			ctl_set_aborted(&io->scsiio);
12381			break;
12382		case CTL_LUN_INJ_MEDIUM_ERR:
12383			ctl_set_medium_error(&io->scsiio,
12384			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12385			     CTL_FLAG_DATA_OUT);
12386			break;
12387		case CTL_LUN_INJ_UA:
12388			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12389			 * OCCURRED */
12390			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12391			break;
12392		case CTL_LUN_INJ_CUSTOM:
12393			/*
12394			 * We're assuming the user knows what he is doing.
12395			 * Just copy the sense information without doing
12396			 * checks.
12397			 */
12398			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12399			      MIN(sizeof(desc->custom_sense),
12400				  sizeof(io->scsiio.sense_data)));
12401			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12402			io->scsiio.sense_len = SSD_FULL_SIZE;
12403			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12404			break;
12405		case CTL_LUN_INJ_NONE:
12406		default:
12407			/*
12408			 * If this is an error injection type we don't know
12409			 * about, clear the continuous flag (if it is set)
12410			 * so it will get deleted below.
12411			 */
12412			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12413			break;
12414		}
12415		/*
12416		 * By default, each error injection action is a one-shot
12417		 */
12418		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12419			continue;
12420
12421		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12422
12423		free(desc, M_CTL);
12424	}
12425}
12426
12427#ifdef CTL_IO_DELAY
12428static void
12429ctl_datamove_timer_wakeup(void *arg)
12430{
12431	union ctl_io *io;
12432
12433	io = (union ctl_io *)arg;
12434
12435	ctl_datamove(io);
12436}
12437#endif /* CTL_IO_DELAY */
12438
12439void
12440ctl_datamove(union ctl_io *io)
12441{
12442	struct ctl_lun *lun;
12443	void (*fe_datamove)(union ctl_io *io);
12444
12445	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12446
12447	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12448
12449	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12450#ifdef CTL_TIME_IO
12451	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12452		char str[256];
12453		char path_str[64];
12454		struct sbuf sb;
12455
12456		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12457		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12458
12459		sbuf_cat(&sb, path_str);
12460		switch (io->io_hdr.io_type) {
12461		case CTL_IO_SCSI:
12462			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12463			sbuf_printf(&sb, "\n");
12464			sbuf_cat(&sb, path_str);
12465			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12466				    io->scsiio.tag_num, io->scsiio.tag_type);
12467			break;
12468		case CTL_IO_TASK:
12469			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12470				    "Tag Type: %d\n", io->taskio.task_action,
12471				    io->taskio.tag_num, io->taskio.tag_type);
12472			break;
12473		default:
12474			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12475			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12476			break;
12477		}
12478		sbuf_cat(&sb, path_str);
12479		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12480			    (intmax_t)time_uptime - io->io_hdr.start_time);
12481		sbuf_finish(&sb);
12482		printf("%s", sbuf_data(&sb));
12483	}
12484#endif /* CTL_TIME_IO */
12485
12486#ifdef CTL_IO_DELAY
12487	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12488		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12489	} else {
12490		if ((lun != NULL)
12491		 && (lun->delay_info.datamove_delay > 0)) {
12492
12493			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12494			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12495			callout_reset(&io->io_hdr.delay_callout,
12496				      lun->delay_info.datamove_delay * hz,
12497				      ctl_datamove_timer_wakeup, io);
12498			if (lun->delay_info.datamove_type ==
12499			    CTL_DELAY_TYPE_ONESHOT)
12500				lun->delay_info.datamove_delay = 0;
12501			return;
12502		}
12503	}
12504#endif
12505
12506	/*
12507	 * This command has been aborted.  Set the port status, so we fail
12508	 * the data move.
12509	 */
12510	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12511		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12512		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12513		       io->io_hdr.nexus.targ_port,
12514		       io->io_hdr.nexus.targ_lun);
12515		io->io_hdr.port_status = 31337;
12516		/*
12517		 * Note that the backend, in this case, will get the
12518		 * callback in its context.  In other cases it may get
12519		 * called in the frontend's interrupt thread context.
12520		 */
12521		io->scsiio.be_move_done(io);
12522		return;
12523	}
12524
12525	/* Don't confuse frontend with zero length data move. */
12526	if (io->scsiio.kern_data_len == 0) {
12527		io->scsiio.be_move_done(io);
12528		return;
12529	}
12530
12531	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12532	fe_datamove(io);
12533}
12534
12535static void
12536ctl_send_datamove_done(union ctl_io *io, int have_lock)
12537{
12538	union ctl_ha_msg msg;
12539#ifdef CTL_TIME_IO
12540	struct bintime cur_bt;
12541#endif
12542
12543	memset(&msg, 0, sizeof(msg));
12544	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12545	msg.hdr.original_sc = io;
12546	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12547	msg.hdr.nexus = io->io_hdr.nexus;
12548	msg.hdr.status = io->io_hdr.status;
12549	msg.scsi.tag_num = io->scsiio.tag_num;
12550	msg.scsi.tag_type = io->scsiio.tag_type;
12551	msg.scsi.scsi_status = io->scsiio.scsi_status;
12552	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12553	       io->scsiio.sense_len);
12554	msg.scsi.sense_len = io->scsiio.sense_len;
12555	msg.scsi.sense_residual = io->scsiio.sense_residual;
12556	msg.scsi.fetd_status = io->io_hdr.port_status;
12557	msg.scsi.residual = io->scsiio.residual;
12558	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12559	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12560		ctl_failover_io(io, /*have_lock*/ have_lock);
12561		return;
12562	}
12563	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12564	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12565	    msg.scsi.sense_len, M_WAITOK);
12566
12567#ifdef CTL_TIME_IO
12568	getbinuptime(&cur_bt);
12569	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12570	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12571#endif
12572	io->io_hdr.num_dmas++;
12573}
12574
12575/*
12576 * The DMA to the remote side is done, now we need to tell the other side
12577 * we're done so it can continue with its data movement.
12578 */
12579static void
12580ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12581{
12582	union ctl_io *io;
12583	int i;
12584
12585	io = rq->context;
12586
12587	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12588		printf("%s: ISC DMA write failed with error %d", __func__,
12589		       rq->ret);
12590		ctl_set_internal_failure(&io->scsiio,
12591					 /*sks_valid*/ 1,
12592					 /*retry_count*/ rq->ret);
12593	}
12594
12595	ctl_dt_req_free(rq);
12596
12597	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12598		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12599	free(io->io_hdr.remote_sglist, M_CTL);
12600	io->io_hdr.remote_sglist = NULL;
12601	io->io_hdr.local_sglist = NULL;
12602
12603	/*
12604	 * The data is in local and remote memory, so now we need to send
12605	 * status (good or back) back to the other side.
12606	 */
12607	ctl_send_datamove_done(io, /*have_lock*/ 0);
12608}
12609
12610/*
12611 * We've moved the data from the host/controller into local memory.  Now we
12612 * need to push it over to the remote controller's memory.
12613 */
12614static int
12615ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12616{
12617	int retval;
12618
12619	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12620					  ctl_datamove_remote_write_cb);
12621	return (retval);
12622}
12623
12624static void
12625ctl_datamove_remote_write(union ctl_io *io)
12626{
12627	int retval;
12628	void (*fe_datamove)(union ctl_io *io);
12629
12630	/*
12631	 * - Get the data from the host/HBA into local memory.
12632	 * - DMA memory from the local controller to the remote controller.
12633	 * - Send status back to the remote controller.
12634	 */
12635
12636	retval = ctl_datamove_remote_sgl_setup(io);
12637	if (retval != 0)
12638		return;
12639
12640	/* Switch the pointer over so the FETD knows what to do */
12641	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12642
12643	/*
12644	 * Use a custom move done callback, since we need to send completion
12645	 * back to the other controller, not to the backend on this side.
12646	 */
12647	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12648
12649	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12650	fe_datamove(io);
12651}
12652
12653static int
12654ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12655{
12656#if 0
12657	char str[256];
12658	char path_str[64];
12659	struct sbuf sb;
12660#endif
12661	int i;
12662
12663	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12664		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12665	free(io->io_hdr.remote_sglist, M_CTL);
12666	io->io_hdr.remote_sglist = NULL;
12667	io->io_hdr.local_sglist = NULL;
12668
12669#if 0
12670	scsi_path_string(io, path_str, sizeof(path_str));
12671	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12672	sbuf_cat(&sb, path_str);
12673	scsi_command_string(&io->scsiio, NULL, &sb);
12674	sbuf_printf(&sb, "\n");
12675	sbuf_cat(&sb, path_str);
12676	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12677		    io->scsiio.tag_num, io->scsiio.tag_type);
12678	sbuf_cat(&sb, path_str);
12679	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12680		    io->io_hdr.flags, io->io_hdr.status);
12681	sbuf_finish(&sb);
12682	printk("%s", sbuf_data(&sb));
12683#endif
12684
12685
12686	/*
12687	 * The read is done, now we need to send status (good or bad) back
12688	 * to the other side.
12689	 */
12690	ctl_send_datamove_done(io, /*have_lock*/ 0);
12691
12692	return (0);
12693}
12694
12695static void
12696ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12697{
12698	union ctl_io *io;
12699	void (*fe_datamove)(union ctl_io *io);
12700
12701	io = rq->context;
12702
12703	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12704		printf("%s: ISC DMA read failed with error %d\n", __func__,
12705		       rq->ret);
12706		ctl_set_internal_failure(&io->scsiio,
12707					 /*sks_valid*/ 1,
12708					 /*retry_count*/ rq->ret);
12709	}
12710
12711	ctl_dt_req_free(rq);
12712
12713	/* Switch the pointer over so the FETD knows what to do */
12714	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12715
12716	/*
12717	 * Use a custom move done callback, since we need to send completion
12718	 * back to the other controller, not to the backend on this side.
12719	 */
12720	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12721
12722	/* XXX KDM add checks like the ones in ctl_datamove? */
12723
12724	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12725	fe_datamove(io);
12726}
12727
12728static int
12729ctl_datamove_remote_sgl_setup(union ctl_io *io)
12730{
12731	struct ctl_sg_entry *local_sglist;
12732	uint32_t len_to_go;
12733	int retval;
12734	int i;
12735
12736	retval = 0;
12737	local_sglist = io->io_hdr.local_sglist;
12738	len_to_go = io->scsiio.kern_data_len;
12739
12740	/*
12741	 * The difficult thing here is that the size of the various
12742	 * S/G segments may be different than the size from the
12743	 * remote controller.  That'll make it harder when DMAing
12744	 * the data back to the other side.
12745	 */
12746	for (i = 0; len_to_go > 0; i++) {
12747		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12748		local_sglist[i].addr =
12749		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12750
12751		len_to_go -= local_sglist[i].len;
12752	}
12753	/*
12754	 * Reset the number of S/G entries accordingly.  The original
12755	 * number of S/G entries is available in rem_sg_entries.
12756	 */
12757	io->scsiio.kern_sg_entries = i;
12758
12759#if 0
12760	printf("%s: kern_sg_entries = %d\n", __func__,
12761	       io->scsiio.kern_sg_entries);
12762	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12763		printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12764		       local_sglist[i].addr, local_sglist[i].len);
12765#endif
12766
12767	return (retval);
12768}
12769
12770static int
12771ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12772			 ctl_ha_dt_cb callback)
12773{
12774	struct ctl_ha_dt_req *rq;
12775	struct ctl_sg_entry *remote_sglist, *local_sglist;
12776	uint32_t local_used, remote_used, total_used;
12777	int i, j, isc_ret;
12778
12779	rq = ctl_dt_req_alloc();
12780
12781	/*
12782	 * If we failed to allocate the request, and if the DMA didn't fail
12783	 * anyway, set busy status.  This is just a resource allocation
12784	 * failure.
12785	 */
12786	if ((rq == NULL)
12787	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12788	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12789		ctl_set_busy(&io->scsiio);
12790
12791	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12792	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12793
12794		if (rq != NULL)
12795			ctl_dt_req_free(rq);
12796
12797		/*
12798		 * The data move failed.  We need to return status back
12799		 * to the other controller.  No point in trying to DMA
12800		 * data to the remote controller.
12801		 */
12802
12803		ctl_send_datamove_done(io, /*have_lock*/ 0);
12804
12805		return (1);
12806	}
12807
12808	local_sglist = io->io_hdr.local_sglist;
12809	remote_sglist = io->io_hdr.remote_sglist;
12810	local_used = 0;
12811	remote_used = 0;
12812	total_used = 0;
12813
12814	/*
12815	 * Pull/push the data over the wire from/to the other controller.
12816	 * This takes into account the possibility that the local and
12817	 * remote sglists may not be identical in terms of the size of
12818	 * the elements and the number of elements.
12819	 *
12820	 * One fundamental assumption here is that the length allocated for
12821	 * both the local and remote sglists is identical.  Otherwise, we've
12822	 * essentially got a coding error of some sort.
12823	 */
12824	isc_ret = CTL_HA_STATUS_SUCCESS;
12825	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12826		uint32_t cur_len;
12827		uint8_t *tmp_ptr;
12828
12829		rq->command = command;
12830		rq->context = io;
12831
12832		/*
12833		 * Both pointers should be aligned.  But it is possible
12834		 * that the allocation length is not.  They should both
12835		 * also have enough slack left over at the end, though,
12836		 * to round up to the next 8 byte boundary.
12837		 */
12838		cur_len = MIN(local_sglist[i].len - local_used,
12839			      remote_sglist[j].len - remote_used);
12840		rq->size = cur_len;
12841
12842		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12843		tmp_ptr += local_used;
12844
12845#if 0
12846		/* Use physical addresses when talking to ISC hardware */
12847		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12848			/* XXX KDM use busdma */
12849			rq->local = vtophys(tmp_ptr);
12850		} else
12851			rq->local = tmp_ptr;
12852#else
12853		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12854		    ("HA does not support BUS_ADDR"));
12855		rq->local = tmp_ptr;
12856#endif
12857
12858		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12859		tmp_ptr += remote_used;
12860		rq->remote = tmp_ptr;
12861
12862		rq->callback = NULL;
12863
12864		local_used += cur_len;
12865		if (local_used >= local_sglist[i].len) {
12866			i++;
12867			local_used = 0;
12868		}
12869
12870		remote_used += cur_len;
12871		if (remote_used >= remote_sglist[j].len) {
12872			j++;
12873			remote_used = 0;
12874		}
12875		total_used += cur_len;
12876
12877		if (total_used >= io->scsiio.kern_data_len)
12878			rq->callback = callback;
12879
12880#if 0
12881		printf("%s: %s: local %p remote %p size %d\n", __func__,
12882		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
12883		       rq->local, rq->remote, rq->size);
12884#endif
12885
12886		isc_ret = ctl_dt_single(rq);
12887		if (isc_ret > CTL_HA_STATUS_SUCCESS)
12888			break;
12889	}
12890	if (isc_ret != CTL_HA_STATUS_WAIT) {
12891		rq->ret = isc_ret;
12892		callback(rq);
12893	}
12894
12895	return (0);
12896}
12897
12898static void
12899ctl_datamove_remote_read(union ctl_io *io)
12900{
12901	int retval;
12902	int i;
12903
12904	/*
12905	 * This will send an error to the other controller in the case of a
12906	 * failure.
12907	 */
12908	retval = ctl_datamove_remote_sgl_setup(io);
12909	if (retval != 0)
12910		return;
12911
12912	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12913					  ctl_datamove_remote_read_cb);
12914	if (retval != 0) {
12915		/*
12916		 * Make sure we free memory if there was an error..  The
12917		 * ctl_datamove_remote_xfer() function will send the
12918		 * datamove done message, or call the callback with an
12919		 * error if there is a problem.
12920		 */
12921		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12922			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12923		free(io->io_hdr.remote_sglist, M_CTL);
12924		io->io_hdr.remote_sglist = NULL;
12925		io->io_hdr.local_sglist = NULL;
12926	}
12927}
12928
12929/*
12930 * Process a datamove request from the other controller.  This is used for
12931 * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12932 * first.  Once that is complete, the data gets DMAed into the remote
12933 * controller's memory.  For reads, we DMA from the remote controller's
12934 * memory into our memory first, and then move it out to the FETD.
12935 */
12936static void
12937ctl_datamove_remote(union ctl_io *io)
12938{
12939
12940	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12941
12942	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12943		ctl_failover_io(io, /*have_lock*/ 0);
12944		return;
12945	}
12946
12947	/*
12948	 * Note that we look for an aborted I/O here, but don't do some of
12949	 * the other checks that ctl_datamove() normally does.
12950	 * We don't need to run the datamove delay code, since that should
12951	 * have been done if need be on the other controller.
12952	 */
12953	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12954		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
12955		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12956		       io->io_hdr.nexus.targ_port,
12957		       io->io_hdr.nexus.targ_lun);
12958		io->io_hdr.port_status = 31338;
12959		ctl_send_datamove_done(io, /*have_lock*/ 0);
12960		return;
12961	}
12962
12963	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
12964		ctl_datamove_remote_write(io);
12965	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
12966		ctl_datamove_remote_read(io);
12967	else {
12968		io->io_hdr.port_status = 31339;
12969		ctl_send_datamove_done(io, /*have_lock*/ 0);
12970	}
12971}
12972
12973static void
12974ctl_process_done(union ctl_io *io)
12975{
12976	struct ctl_lun *lun;
12977	struct ctl_softc *softc = control_softc;
12978	void (*fe_done)(union ctl_io *io);
12979	union ctl_ha_msg msg;
12980	uint32_t targ_port = io->io_hdr.nexus.targ_port;
12981
12982	CTL_DEBUG_PRINT(("ctl_process_done\n"));
12983	fe_done = softc->ctl_ports[targ_port]->fe_done;
12984
12985#ifdef CTL_TIME_IO
12986	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12987		char str[256];
12988		char path_str[64];
12989		struct sbuf sb;
12990
12991		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12992		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12993
12994		sbuf_cat(&sb, path_str);
12995		switch (io->io_hdr.io_type) {
12996		case CTL_IO_SCSI:
12997			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12998			sbuf_printf(&sb, "\n");
12999			sbuf_cat(&sb, path_str);
13000			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13001				    io->scsiio.tag_num, io->scsiio.tag_type);
13002			break;
13003		case CTL_IO_TASK:
13004			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13005				    "Tag Type: %d\n", io->taskio.task_action,
13006				    io->taskio.tag_num, io->taskio.tag_type);
13007			break;
13008		default:
13009			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13010			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13011			break;
13012		}
13013		sbuf_cat(&sb, path_str);
13014		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13015			    (intmax_t)time_uptime - io->io_hdr.start_time);
13016		sbuf_finish(&sb);
13017		printf("%s", sbuf_data(&sb));
13018	}
13019#endif /* CTL_TIME_IO */
13020
13021	switch (io->io_hdr.io_type) {
13022	case CTL_IO_SCSI:
13023		break;
13024	case CTL_IO_TASK:
13025		if (ctl_debug & CTL_DEBUG_INFO)
13026			ctl_io_error_print(io, NULL);
13027		fe_done(io);
13028		return;
13029	default:
13030		panic("ctl_process_done: invalid io type %d\n",
13031		      io->io_hdr.io_type);
13032		break; /* NOTREACHED */
13033	}
13034
13035	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13036	if (lun == NULL) {
13037		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13038				 io->io_hdr.nexus.targ_mapped_lun));
13039		goto bailout;
13040	}
13041
13042	mtx_lock(&lun->lun_lock);
13043
13044	/*
13045	 * Check to see if we have any errors to inject here.  We only
13046	 * inject errors for commands that don't already have errors set.
13047	 */
13048	if ((STAILQ_FIRST(&lun->error_list) != NULL) &&
13049	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13050	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13051		ctl_inject_error(lun, io);
13052
13053	/*
13054	 * XXX KDM how do we treat commands that aren't completed
13055	 * successfully?
13056	 *
13057	 * XXX KDM should we also track I/O latency?
13058	 */
13059	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13060	    io->io_hdr.io_type == CTL_IO_SCSI) {
13061#ifdef CTL_TIME_IO
13062		struct bintime cur_bt;
13063#endif
13064		int type;
13065
13066		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13067		    CTL_FLAG_DATA_IN)
13068			type = CTL_STATS_READ;
13069		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13070		    CTL_FLAG_DATA_OUT)
13071			type = CTL_STATS_WRITE;
13072		else
13073			type = CTL_STATS_NO_IO;
13074
13075		lun->stats.ports[targ_port].bytes[type] +=
13076		    io->scsiio.kern_total_len;
13077		lun->stats.ports[targ_port].operations[type]++;
13078#ifdef CTL_TIME_IO
13079		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13080		   &io->io_hdr.dma_bt);
13081		getbinuptime(&cur_bt);
13082		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13083		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13084#endif
13085		lun->stats.ports[targ_port].num_dmas[type] +=
13086		    io->io_hdr.num_dmas;
13087	}
13088
13089	/*
13090	 * Remove this from the OOA queue.
13091	 */
13092	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13093#ifdef CTL_TIME_IO
13094	if (TAILQ_EMPTY(&lun->ooa_queue))
13095		lun->last_busy = getsbinuptime();
13096#endif
13097
13098	/*
13099	 * Run through the blocked queue on this LUN and see if anything
13100	 * has become unblocked, now that this transaction is done.
13101	 */
13102	ctl_check_blocked(lun);
13103
13104	/*
13105	 * If the LUN has been invalidated, free it if there is nothing
13106	 * left on its OOA queue.
13107	 */
13108	if ((lun->flags & CTL_LUN_INVALID)
13109	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13110		mtx_unlock(&lun->lun_lock);
13111		mtx_lock(&softc->ctl_lock);
13112		ctl_free_lun(lun);
13113		mtx_unlock(&softc->ctl_lock);
13114	} else
13115		mtx_unlock(&lun->lun_lock);
13116
13117bailout:
13118
13119	/*
13120	 * If this command has been aborted, make sure we set the status
13121	 * properly.  The FETD is responsible for freeing the I/O and doing
13122	 * whatever it needs to do to clean up its state.
13123	 */
13124	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13125		ctl_set_task_aborted(&io->scsiio);
13126
13127	/*
13128	 * If enabled, print command error status.
13129	 */
13130	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13131	    (ctl_debug & CTL_DEBUG_INFO) != 0)
13132		ctl_io_error_print(io, NULL);
13133
13134	/*
13135	 * Tell the FETD or the other shelf controller we're done with this
13136	 * command.  Note that only SCSI commands get to this point.  Task
13137	 * management commands are completed above.
13138	 */
13139	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13140	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13141		memset(&msg, 0, sizeof(msg));
13142		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13143		msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13144		msg.hdr.nexus = io->io_hdr.nexus;
13145		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13146		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13147		    M_WAITOK);
13148	}
13149
13150	fe_done(io);
13151}
13152
13153#ifdef CTL_WITH_CA
13154/*
13155 * Front end should call this if it doesn't do autosense.  When the request
13156 * sense comes back in from the initiator, we'll dequeue this and send it.
13157 */
13158int
13159ctl_queue_sense(union ctl_io *io)
13160{
13161	struct ctl_lun *lun;
13162	struct ctl_port *port;
13163	struct ctl_softc *softc;
13164	uint32_t initidx, targ_lun;
13165
13166	softc = control_softc;
13167
13168	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13169
13170	/*
13171	 * LUN lookup will likely move to the ctl_work_thread() once we
13172	 * have our new queueing infrastructure (that doesn't put things on
13173	 * a per-LUN queue initially).  That is so that we can handle
13174	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13175	 * can't deal with that right now.
13176	 */
13177	mtx_lock(&softc->ctl_lock);
13178
13179	/*
13180	 * If we don't have a LUN for this, just toss the sense
13181	 * information.
13182	 */
13183	port = ctl_io_port(&ctsio->io_hdr);
13184	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13185	if ((targ_lun < CTL_MAX_LUNS)
13186	 && (softc->ctl_luns[targ_lun] != NULL))
13187		lun = softc->ctl_luns[targ_lun];
13188	else
13189		goto bailout;
13190
13191	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13192
13193	mtx_lock(&lun->lun_lock);
13194	/*
13195	 * Already have CA set for this LUN...toss the sense information.
13196	 */
13197	if (ctl_is_set(lun->have_ca, initidx)) {
13198		mtx_unlock(&lun->lun_lock);
13199		goto bailout;
13200	}
13201
13202	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13203	       MIN(sizeof(lun->pending_sense[initidx]),
13204	       sizeof(io->scsiio.sense_data)));
13205	ctl_set_mask(lun->have_ca, initidx);
13206	mtx_unlock(&lun->lun_lock);
13207
13208bailout:
13209	mtx_unlock(&softc->ctl_lock);
13210
13211	ctl_free_io(io);
13212
13213	return (CTL_RETVAL_COMPLETE);
13214}
13215#endif
13216
13217/*
13218 * Primary command inlet from frontend ports.  All SCSI and task I/O
13219 * requests must go through this function.
13220 */
13221int
13222ctl_queue(union ctl_io *io)
13223{
13224	struct ctl_port *port;
13225
13226	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13227
13228#ifdef CTL_TIME_IO
13229	io->io_hdr.start_time = time_uptime;
13230	getbinuptime(&io->io_hdr.start_bt);
13231#endif /* CTL_TIME_IO */
13232
13233	/* Map FE-specific LUN ID into global one. */
13234	port = ctl_io_port(&io->io_hdr);
13235	io->io_hdr.nexus.targ_mapped_lun =
13236	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13237
13238	switch (io->io_hdr.io_type) {
13239	case CTL_IO_SCSI:
13240	case CTL_IO_TASK:
13241		if (ctl_debug & CTL_DEBUG_CDB)
13242			ctl_io_print(io);
13243		ctl_enqueue_incoming(io);
13244		break;
13245	default:
13246		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13247		return (EINVAL);
13248	}
13249
13250	return (CTL_RETVAL_COMPLETE);
13251}
13252
13253#ifdef CTL_IO_DELAY
13254static void
13255ctl_done_timer_wakeup(void *arg)
13256{
13257	union ctl_io *io;
13258
13259	io = (union ctl_io *)arg;
13260	ctl_done(io);
13261}
13262#endif /* CTL_IO_DELAY */
13263
13264void
13265ctl_serseq_done(union ctl_io *io)
13266{
13267	struct ctl_lun *lun;
13268
13269	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13270	if (lun->be_lun == NULL ||
13271	    lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13272		return;
13273	mtx_lock(&lun->lun_lock);
13274	io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13275	ctl_check_blocked(lun);
13276	mtx_unlock(&lun->lun_lock);
13277}
13278
13279void
13280ctl_done(union ctl_io *io)
13281{
13282
13283	/*
13284	 * Enable this to catch duplicate completion issues.
13285	 */
13286#if 0
13287	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13288		printf("%s: type %d msg %d cdb %x iptl: "
13289		       "%u:%u:%u tag 0x%04x "
13290		       "flag %#x status %x\n",
13291			__func__,
13292			io->io_hdr.io_type,
13293			io->io_hdr.msg_type,
13294			io->scsiio.cdb[0],
13295			io->io_hdr.nexus.initid,
13296			io->io_hdr.nexus.targ_port,
13297			io->io_hdr.nexus.targ_lun,
13298			(io->io_hdr.io_type ==
13299			CTL_IO_TASK) ?
13300			io->taskio.tag_num :
13301			io->scsiio.tag_num,
13302		        io->io_hdr.flags,
13303			io->io_hdr.status);
13304	} else
13305		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13306#endif
13307
13308	/*
13309	 * This is an internal copy of an I/O, and should not go through
13310	 * the normal done processing logic.
13311	 */
13312	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13313		return;
13314
13315#ifdef CTL_IO_DELAY
13316	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13317		struct ctl_lun *lun;
13318
13319		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13320
13321		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13322	} else {
13323		struct ctl_lun *lun;
13324
13325		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13326
13327		if ((lun != NULL)
13328		 && (lun->delay_info.done_delay > 0)) {
13329
13330			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13331			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13332			callout_reset(&io->io_hdr.delay_callout,
13333				      lun->delay_info.done_delay * hz,
13334				      ctl_done_timer_wakeup, io);
13335			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13336				lun->delay_info.done_delay = 0;
13337			return;
13338		}
13339	}
13340#endif /* CTL_IO_DELAY */
13341
13342	ctl_enqueue_done(io);
13343}
13344
13345static void
13346ctl_work_thread(void *arg)
13347{
13348	struct ctl_thread *thr = (struct ctl_thread *)arg;
13349	struct ctl_softc *softc = thr->ctl_softc;
13350	union ctl_io *io;
13351	int retval;
13352
13353	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13354
13355	for (;;) {
13356		/*
13357		 * We handle the queues in this order:
13358		 * - ISC
13359		 * - done queue (to free up resources, unblock other commands)
13360		 * - RtR queue
13361		 * - incoming queue
13362		 *
13363		 * If those queues are empty, we break out of the loop and
13364		 * go to sleep.
13365		 */
13366		mtx_lock(&thr->queue_lock);
13367		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13368		if (io != NULL) {
13369			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13370			mtx_unlock(&thr->queue_lock);
13371			ctl_handle_isc(io);
13372			continue;
13373		}
13374		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13375		if (io != NULL) {
13376			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13377			/* clear any blocked commands, call fe_done */
13378			mtx_unlock(&thr->queue_lock);
13379			ctl_process_done(io);
13380			continue;
13381		}
13382		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13383		if (io != NULL) {
13384			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13385			mtx_unlock(&thr->queue_lock);
13386			if (io->io_hdr.io_type == CTL_IO_TASK)
13387				ctl_run_task(io);
13388			else
13389				ctl_scsiio_precheck(softc, &io->scsiio);
13390			continue;
13391		}
13392		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13393		if (io != NULL) {
13394			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13395			mtx_unlock(&thr->queue_lock);
13396			retval = ctl_scsiio(&io->scsiio);
13397			if (retval != CTL_RETVAL_COMPLETE)
13398				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13399			continue;
13400		}
13401
13402		/* Sleep until we have something to do. */
13403		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13404	}
13405}
13406
13407static void
13408ctl_lun_thread(void *arg)
13409{
13410	struct ctl_softc *softc = (struct ctl_softc *)arg;
13411	struct ctl_be_lun *be_lun;
13412
13413	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13414
13415	for (;;) {
13416		mtx_lock(&softc->ctl_lock);
13417		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13418		if (be_lun != NULL) {
13419			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13420			mtx_unlock(&softc->ctl_lock);
13421			ctl_create_lun(be_lun);
13422			continue;
13423		}
13424
13425		/* Sleep until we have something to do. */
13426		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13427		    PDROP | PRIBIO, "-", 0);
13428	}
13429}
13430
13431static void
13432ctl_thresh_thread(void *arg)
13433{
13434	struct ctl_softc *softc = (struct ctl_softc *)arg;
13435	struct ctl_lun *lun;
13436	struct scsi_da_rw_recovery_page *rwpage;
13437	struct ctl_logical_block_provisioning_page *page;
13438	const char *attr;
13439	union ctl_ha_msg msg;
13440	uint64_t thres, val;
13441	int i, e, set;
13442
13443	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13444
13445	for (;;) {
13446		mtx_lock(&softc->ctl_lock);
13447		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13448			if ((lun->flags & CTL_LUN_DISABLED) ||
13449			    (lun->flags & CTL_LUN_NO_MEDIA) ||
13450			    lun->backend->lun_attr == NULL)
13451				continue;
13452			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13453			    softc->ha_mode == CTL_HA_MODE_XFER)
13454				continue;
13455			rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13456			if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13457				continue;
13458			e = 0;
13459			page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13460			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13461				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13462					continue;
13463				thres = scsi_4btoul(page->descr[i].count);
13464				thres <<= CTL_LBP_EXPONENT;
13465				switch (page->descr[i].resource) {
13466				case 0x01:
13467					attr = "blocksavail";
13468					break;
13469				case 0x02:
13470					attr = "blocksused";
13471					break;
13472				case 0xf1:
13473					attr = "poolblocksavail";
13474					break;
13475				case 0xf2:
13476					attr = "poolblocksused";
13477					break;
13478				default:
13479					continue;
13480				}
13481				mtx_unlock(&softc->ctl_lock); // XXX
13482				val = lun->backend->lun_attr(
13483				    lun->be_lun->be_lun, attr);
13484				mtx_lock(&softc->ctl_lock);
13485				if (val == UINT64_MAX)
13486					continue;
13487				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13488				    == SLBPPD_ARMING_INC)
13489					e = (val >= thres);
13490				else
13491					e = (val <= thres);
13492				if (e)
13493					break;
13494			}
13495			mtx_lock(&lun->lun_lock);
13496			if (e) {
13497				scsi_u64to8b((uint8_t *)&page->descr[i] -
13498				    (uint8_t *)page, lun->ua_tpt_info);
13499				if (lun->lasttpt == 0 ||
13500				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13501					lun->lasttpt = time_uptime;
13502					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13503					set = 1;
13504				} else
13505					set = 0;
13506			} else {
13507				lun->lasttpt = 0;
13508				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13509				set = -1;
13510			}
13511			mtx_unlock(&lun->lun_lock);
13512			if (set != 0 &&
13513			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13514				/* Send msg to other side. */
13515				bzero(&msg.ua, sizeof(msg.ua));
13516				msg.hdr.msg_type = CTL_MSG_UA;
13517				msg.hdr.nexus.initid = -1;
13518				msg.hdr.nexus.targ_port = -1;
13519				msg.hdr.nexus.targ_lun = lun->lun;
13520				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13521				msg.ua.ua_all = 1;
13522				msg.ua.ua_set = (set > 0);
13523				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13524				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13525				mtx_unlock(&softc->ctl_lock); // XXX
13526				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13527				    sizeof(msg.ua), M_WAITOK);
13528				mtx_lock(&softc->ctl_lock);
13529			}
13530		}
13531		mtx_unlock(&softc->ctl_lock);
13532		pause("-", CTL_LBP_PERIOD * hz);
13533	}
13534}
13535
13536static void
13537ctl_enqueue_incoming(union ctl_io *io)
13538{
13539	struct ctl_softc *softc = control_softc;
13540	struct ctl_thread *thr;
13541	u_int idx;
13542
13543	idx = (io->io_hdr.nexus.targ_port * 127 +
13544	       io->io_hdr.nexus.initid) % worker_threads;
13545	thr = &softc->threads[idx];
13546	mtx_lock(&thr->queue_lock);
13547	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13548	mtx_unlock(&thr->queue_lock);
13549	wakeup(thr);
13550}
13551
13552static void
13553ctl_enqueue_rtr(union ctl_io *io)
13554{
13555	struct ctl_softc *softc = control_softc;
13556	struct ctl_thread *thr;
13557
13558	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13559	mtx_lock(&thr->queue_lock);
13560	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13561	mtx_unlock(&thr->queue_lock);
13562	wakeup(thr);
13563}
13564
13565static void
13566ctl_enqueue_done(union ctl_io *io)
13567{
13568	struct ctl_softc *softc = control_softc;
13569	struct ctl_thread *thr;
13570
13571	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13572	mtx_lock(&thr->queue_lock);
13573	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13574	mtx_unlock(&thr->queue_lock);
13575	wakeup(thr);
13576}
13577
13578static void
13579ctl_enqueue_isc(union ctl_io *io)
13580{
13581	struct ctl_softc *softc = control_softc;
13582	struct ctl_thread *thr;
13583
13584	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13585	mtx_lock(&thr->queue_lock);
13586	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13587	mtx_unlock(&thr->queue_lock);
13588	wakeup(thr);
13589}
13590
13591/*
13592 *  vim: ts=8
13593 */
13594